]> Dogcows Code - chaz/vimcoder/blob - src/com/dogcows/Editor.java
ff38a0ff4df175efde211fe7dd050fa3be86cd91
[chaz/vimcoder] / src / com / dogcows / Editor.java
1
2 package com.dogcows;
3
4 import java.io.File;
5 import java.io.FileWriter;
6 import java.io.IOException;
7 import java.util.*;
8
9 import com.topcoder.client.contestant.ProblemComponentModel;
10 import com.topcoder.shared.language.Language;
11 import com.topcoder.shared.problem.DataType;
12 import com.topcoder.shared.problem.Renderer;
13 import com.topcoder.shared.problem.TestCase;
14
15 /**
16 * @author Charles McGarvey
17 * The TopCoder Arena editor plug-in providing support for Vim.
18 *
19 * Distributable under the terms and conditions of the 2-clause BSD license;
20 * see the file COPYING for a complete text of the license.
21 */
22 public class Editor
23 {
24 /**
25 * The problem ID number.
26 */
27 private String id;
28
29 /**
30 * The name of the class.
31 */
32 private String name;
33
34 /**
35 * The path of the current source file.
36 */
37 private File sourceFile;
38
39 /**
40 * The path of the problem directory.
41 */
42 private File directory;
43
44
45 /**
46 * Map languages names to file extensions.
47 */
48 private static final Map<String,String> languageExtension = new HashMap<String,String>();
49 static
50 {
51 languageExtension.put("Java", "java");
52 languageExtension.put("C++", "cc");
53 languageExtension.put("C#", "cs");
54 languageExtension.put("VB", "vb");
55 languageExtension.put("Python", "py");
56 }
57
58
59 /**
60 * Construct an editor with the problem objects given us by the Arena.
61 * @param component A container for the particulars of the problem.
62 * @param language The currently selected language.
63 * @param renderer A helper object to help format the problem statement.
64 * @throws Exception If the editor could not set itself up.
65 */
66 public Editor(ProblemComponentModel component,
67 Language language,
68 Renderer renderer) throws Exception
69 {
70 this.id = String.valueOf(component.getProblem().getProblemID());
71 this.name = component.getClassName();
72
73 // Make sure the top-level vimcoder directory exists.
74 File topDir = VimCoder.getStorageDirectory();
75 if (!topDir.isDirectory())
76 {
77 if (!topDir.mkdirs()) throw new IOException(topDir.getPath());
78 }
79
80 // Make sure the problem directory exists.
81 this.directory = new File(topDir, id);
82 if (!directory.isDirectory())
83 {
84 if (!directory.mkdirs()) throw new IOException(directory.getPath());
85 }
86
87 String lang = language.getName();
88 String ext = languageExtension.get(lang);
89
90 // Set up the terms used for the template expansion.
91 HashMap<String,String> terms = new HashMap<String,String>();
92 terms.put("RETURNTYPE", component.getReturnType().getDescriptor(language));
93 terms.put("CLASSNAME", name);
94 terms.put("METHODNAME", component.getMethodName());
95 terms.put("METHODPARAMS", getMethodParams(component.getParamTypes(),
96 component.getParamNames(),
97 language));
98 terms.put("METHODPARAMNAMES", Util.join(component.getParamNames(), ", "));
99 terms.put("METHODPARAMSTREAMIN", Util.join(component.getParamNames(), " >> "));
100 terms.put("METHODPARAMSTREAMOUT", Util.join(component.getParamNames(), " << \", \" << "));
101 terms.put("METHODPARAMDECLARES", getMethodParamDeclarations(component.getParamTypes(),
102 component.getParamNames(),
103 language));
104
105 // Write the problem statement as an HTML file in the problem directory.
106 File problemFile = new File(directory, "Problem.html");
107 if (!problemFile.canRead())
108 {
109 FileWriter writer = new FileWriter(problemFile);
110 try
111 {
112 writer.write(renderer.toHTML(language));
113 }
114 finally
115 {
116 writer.close();
117 }
118 }
119
120 // Expand the template for the main class and write it to the current
121 // source file.
122 sourceFile = new File(directory, name + "." + ext);
123 if (!sourceFile.canRead())
124 {
125 String text = Util.expandTemplate(readTemplate(lang + "Template"),
126 terms);
127 FileWriter writer = new FileWriter(sourceFile);
128 writer.write(text);
129 writer.close();
130 }
131
132 // Expand the driver template and write it to a source file.
133 File driverFile = new File(directory, "driver." + ext);
134 if (!driverFile.canRead())
135 {
136 String text = Util.expandTemplate(readTemplate(lang + "Driver"),
137 terms);
138 FileWriter writer = new FileWriter(driverFile);
139 writer.write(text);
140 writer.close();
141 }
142
143 // Write the test cases to a text file. The driver code can read this
144 // file and perform the tests based on what it reads.
145 File testcaseFile = new File(directory, "testcases.txt");
146 if (!testcaseFile.canRead())
147 {
148 StringBuilder text = new StringBuilder();
149 if (component.hasTestCases())
150 {
151 for (TestCase testCase : component.getTestCases())
152 {
153 text.append(testCase.getOutput() + System.getProperty("line.separator"));
154 for (String input : testCase.getInput())
155 {
156 text.append(input + System.getProperty("line.separator"));
157 }
158 }
159 }
160 FileWriter writer = new FileWriter(testcaseFile);
161 writer.write(text.toString());
162 writer.close();
163 }
164
165 // Finally, expand the Makefile template and write it.
166 File makeFile = new File(directory, "Makefile");
167 {
168 String text = Util.expandTemplate(readTemplate(lang + "Makefile"),
169 terms);
170 FileWriter writer = new FileWriter(makeFile);
171 writer.write(text);
172 writer.close();
173 }
174 }
175
176 /**
177 * Save the source code provided by the server, and tell the Vim server to
178 * edit the current source file.
179 * @param source The source code.
180 * @throws Exception If the source couldn't be written or the Vim server
181 * had a problem.
182 */
183 public void setSource(String source) throws Exception
184 {
185 FileWriter writer = new FileWriter(new File(directory, name));
186 writer.write(source);
187 writer.close();
188 sendVimCommand("--remote-tab-silent", sourceFile.getPath());
189 }
190
191 /**
192 * Read the source code from the current source file.
193 * @return The source code.
194 * @throws IOException If the source file could not be read.
195 */
196 public String getSource() throws IOException
197 {
198 return Util.readFile(sourceFile) + "\n// Edited by " +
199 VimCoder.version + "\n// " + VimCoder.website + "\n\n";
200 }
201
202
203 /**
204 * Send a command to the Vim server.
205 * If the server isn't running, it will be started with the name
206 * VIMCODER#### where #### is the problem ID.
207 * @param command The command to send to the server.
208 * @param argument A single argument for the remote command.
209 * @throws Exception If the command could not be sent.
210 */
211 private void sendVimCommand(String command,
212 String argument) throws Exception
213 {
214 String[] arguments = {argument};
215 sendVimCommand(command, arguments);
216 }
217
218 /**
219 * Send a command to the Vim server.
220 * If the server isn't running, it will be started with the name
221 * VIMCODER#### where #### is the problem ID.
222 * @param command The command to send to the server.
223 * @param argument Arguments for the remote command.
224 * @throws Exception If the command could not be sent.
225 */
226 private void sendVimCommand(String command,
227 String[] arguments) throws Exception
228 {
229 String[] vimCommand = VimCoder.getVimCommand().split("\\s");
230 String[] flags = {"--servername", "VimCoder" + id, command};
231 vimCommand = Util.concat(vimCommand, flags);
232 vimCommand = Util.concat(vimCommand, arguments);
233 Process child = Runtime.getRuntime().exec(vimCommand, null, directory);
234
235 /* FIXME: This is a pretty bad hack. The problem is that the Vim
236 * process doesn't fork to the background on some systems, so we
237 * can't wait on the child. At the same time, calling this method
238 * before the previous child could finish initializing the server
239 * may result in multiple editor windows popping up. We'd also
240 * like to be able to get the return code from the child if we can.
241 * The workaround here is to stall the thread for a little while or
242 * until we see that the child exits. If the child never exits
243 * before the timeout, we will assume it is not backgrounding and
244 * that everything worked. This works as long as the Vim server is
245 * able to start within the stall period. */
246 long expire = System.currentTimeMillis() + 1000;
247 while (System.currentTimeMillis() < expire)
248 {
249 Thread.yield();
250 try
251 {
252 int exitCode = child.exitValue();
253 if (exitCode != 0) throw new Exception("Vim process returned exit code " + exitCode + ".");
254 break;
255 }
256 catch (IllegalThreadStateException exception)
257 {
258 // The child has not exited; intentionally ignoring exception.
259 }
260 }
261 }
262
263
264 /**
265 * Read a template.
266 * We first look in the storage directory. If we can't find one, we
267 * look among the resources.
268 * @param tName The name of the template.
269 * @return The contents of the template file, or an empty string.
270 */
271 private String readTemplate(String tName)
272 {
273 File templateFile = new File(VimCoder.getStorageDirectory(), tName);
274 try
275 {
276 if (templateFile.canRead()) return Util.readFile(templateFile);
277 return Util.readResource(tName);
278 }
279 catch (IOException exception)
280 {
281 return "";
282 }
283 }
284
285
286 /**
287 * Convert an array of data types to an array of strings according to a
288 * given language.
289 * @param types The data types.
290 * @param language The language to use in the conversion.
291 * @return The array of string representations of the data types.
292 */
293 private String[] getStringTypes(DataType[] types, Language language)
294 {
295 String[] strings = new String[types.length];
296 for (int i = 0; i < types.length; ++i)
297 {
298 strings[i] = types[i].getDescriptor(language);
299 }
300 return strings;
301 }
302
303 /**
304 * Combine the data types and parameter names into a comma-separated list of
305 * the method parameters.
306 * The result could be used inside the parentheses of a method
307 * declaration.
308 * @param types The data types of the parameters.
309 * @param names The names of the parameters.
310 * @param language The language used for representing the data types.
311 * @return The list of parameters.
312 */
313 private String getMethodParams(DataType[] types,
314 String[] names,
315 Language language)
316 {
317 String[] typeStrings = getStringTypes(types, language);
318 return Util.join(Util.combine(typeStrings, names, " "), ", ");
319 }
320
321 /**
322 * Combine the data types and parameter names into a group of variable
323 * declarations.
324 * Each declaration is separated by a new line and terminated with a
325 * semicolon.
326 * @param types The data types of the parameters.
327 * @param names The names of the parameters.
328 * @param language The language used for representing the data types.
329 * @return The parameters as a block of declarations.
330 */
331 private String getMethodParamDeclarations(DataType[] types,
332 String[] names,
333 Language language)
334 {
335 final String end = ";" + System.getProperty("line.separator");
336 String[] typeStrings = getStringTypes(types, language);
337 return Util.join(Util.combine(typeStrings, names, "\t"), end) + end;
338 }
339 }
340
This page took 0.041982 seconds and 3 git commands to generate.