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