Debian Codegraph @

arduino-core/src/processing/app/Sketch.java

raw symbols SCIP
1 package processing.app;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.nio.file.Files;
6 import java.util.*;
7 import java.util.stream.Collectors;
8 import java.util.stream.Stream;
9
10 import cc.arduino.files.DeleteFilesOnShutdown;
11 import processing.app.helpers.FileUtils;
12
13 import static processing.app.I18n.tr;
14
15 /**
16 * This represents a single sketch, consisting of one or more files.
17 */
18 public class Sketch {
19 public static final String DEFAULT_SKETCH_EXTENSION = "ino";
20 public static final List<String> OLD_SKETCH_EXTENSIONS = Arrays.asList("pde");
21 public static final List<String> SKETCH_EXTENSIONS = Stream.concat(Stream.of(DEFAULT_SKETCH_EXTENSION), OLD_SKETCH_EXTENSIONS.stream()).collect(Collectors.toList());
22 public static final List<String> OTHER_ALLOWED_EXTENSIONS = Arrays.asList("c", "cpp", "h", "hh", "hpp", "s");
23 public static final List<String> EXTENSIONS = Stream.concat(SKETCH_EXTENSIONS.stream(), OTHER_ALLOWED_EXTENSIONS.stream()).collect(Collectors.toList());
24
25 /**
26 * folder that contains this sketch
27 */
28 private File folder;
29
30 private List<SketchFile> files = new ArrayList<>();
31
32 private File buildPath;
33
34 public static final Comparator<SketchFile> CODE_DOCS_COMPARATOR = new Comparator<SketchFile>() {
35 @Override
36 public int compare(SketchFile x, SketchFile y) {
37 if (x.isPrimary() && !y.isPrimary())
38 return -1;
39 if (y.isPrimary() && !x.isPrimary())
40 return 1;
41 return x.getFileName().compareTo(y.getFileName());
42 }
43 };
44
45 /**
46 * Create a new SketchData object, and looks at the sketch directory
47 * on disk to get populate the list of files in this sketch.
48 *
49 * @param file
50 * Any file inside the sketch directory.
51 */
52 Sketch(File file) throws IOException {
53 folder = file.getParentFile();
54 files = listSketchFiles(true);
55 }
56
57 static public File checkSketchFile(File file) {
58 // check to make sure that this .pde file is
59 // in a folder of the same name
60 String fileName = file.getName();
61 File parent = file.getParentFile();
62 String parentName = parent.getName();
63 String pdeName = parentName + ".pde";
64 File altPdeFile = new File(parent, pdeName);
65 String inoName = parentName + ".ino";
66 File altInoFile = new File(parent, inoName);
67
68 if (pdeName.equals(fileName) || inoName.equals(fileName))
69 return file;
70
71 if (altPdeFile.exists())
72 return altPdeFile;
73
74 if (altInoFile.exists())
75 return altInoFile;
76
77 return null;
78 }
79
80 /**
81 * Reload the list of files. This checks the sketch directory on disk,
82 * to see if any files were added or removed. This does *not* check
83 * the contents of the files, just their presence.
84 *
85 * @return true when the list of files was changed, false when it was
86 * not.
87 */
88 public boolean reload() throws IOException {
89 List<SketchFile> reloaded = listSketchFiles(false);
90 if (!reloaded.equals(files)) {
91 files = reloaded;
92 return true;
93 }
94 return false;
95 }
96
97 /**
98 * Scan this sketch's directory for files that should be loaded as
99 * part of this sketch. Doesn't modify this SketchData instance, just
100 * returns a filtered and sorted list of File objects ready to be
101 * passed to the SketchFile constructor.
102 *
103 * @param showWarnings
104 * When true, any invalid filenames will show a warning.
105 */
106 private List<SketchFile> listSketchFiles(boolean showWarnings) throws IOException {
107 Set<SketchFile> result = new TreeSet<>(CODE_DOCS_COMPARATOR);
108 for (File file : FileUtils.listFiles(folder, false, EXTENSIONS)) {
109 if (BaseNoGui.isSanitaryName(FileUtils.splitFilename(file).basename)) {
110 result.add(new SketchFile(this, file));
111 } else if (showWarnings) {
112 System.err.println(I18n.format(tr("File name {0} is invalid: ignored"), file.getName()));
113 }
114 }
115
116 if (result.size() == 0)
117 throw new IOException(tr("No valid code files found"));
118
119 return new ArrayList<>(result);
120 }
121
122 /**
123 * Create the data folder if it does not exist already. As a
124 * convenience, it also returns the data folder, since it's likely
125 * about to be used.
126 */
127 public File prepareDataFolder() {
128 File dataFolder = getDataFolder();
129 if (!dataFolder.exists()) {
130 dataFolder.mkdirs();
131 }
132 return dataFolder;
133 }
134
135 public void save() throws IOException {
136 for (SketchFile file : getFiles()) {
137 if (file.isModified())
138 file.save();
139 }
140 }
141
142 public int getCodeCount() {
143 return files.size();
144 }
145
146 public SketchFile[] getFiles() {
147 return files.toArray(new SketchFile[0]);
148 }
149
150 /**
151 * Returns a file object for the primary .pde of this sketch.
152 */
153 public SketchFile getPrimaryFile() {
154 return files.get(0);
155 }
156
157 /**
158 * Returns path to the main .pde file for this sketch.
159 */
160 public String getMainFilePath() {
161 return getPrimaryFile().getFile().getAbsolutePath();
162 }
163
164 public SketchFile getFile(int i) {
165 return files.get(i);
166 }
167
168 /**
169 * Gets the build path for this sketch. The first time this is called,
170 * a build path is generated and created and the same path is returned
171 * on all subsequent calls.
172 *
173 * This takes into account the build.path preference. If it is set,
174 * that path is always returned, and the directory is *not* deleted on
175 * shutdown. If the preference is not set, a random pathname in a
176 * temporary directory is generated, which is automatically deleted on
177 * shutdown.
178 */
179 public File getBuildPath() throws IOException {
180 if (buildPath == null) {
181 if (PreferencesData.get("build.path") != null) {
182 buildPath = BaseNoGui.absoluteFile(PreferencesData.get("build.path"));
183 Files.createDirectories(buildPath.toPath());
184 } else {
185 buildPath = FileUtils.createTempFolder("arduino_build_");
186 DeleteFilesOnShutdown.add(buildPath);
187 }
188 }
189
190 return buildPath;
191 }
192
193 protected void removeFile(SketchFile which) {
194 if (!files.remove(which))
195 System.err.println("removeCode: internal error.. could not find code");
196 }
197
198 public String getName() {
199 return folder.getName();
200 }
201
202 public File getFolder() {
203 return folder;
204 }
205
206 public File getDataFolder() {
207 return new File(folder, "data");
208 }
209
210 /**
211 * Is any of the files in this sketch modified?
212 */
213 public boolean isModified() {
214 for (SketchFile file : files) {
215 if (file.isModified())
216 return true;
217 }
218 return false;
219 }
220
221 /**
222 * Finds the file with the given filename and returns its index.
223 * Returns -1 when the file was not found.
224 */
225 public int findFileIndex(File filename) {
226 int i = 0;
227 for (SketchFile file : files) {
228 if (file.getFile().equals(filename))
229 return i;
230 i++;
231 }
232 return -1;
233 }
234
235 /**
236 * Check if renaming/saving this sketch to the given folder would
237 * cause a problem because: 1. The new folder already exists 2.
238 * Renaming the primary file would cause a conflict with an existing
239 * file. If so, an IOEXception is thrown. If not, the name of the new
240 * primary file is returned.
241 */
242 protected File checkNewFoldername(File newFolder) throws IOException {
243 String newPrimary = FileUtils.addExtension(newFolder.getName(), DEFAULT_SKETCH_EXTENSION);
244 // Verify the new folder does not exist yet
245 if (newFolder.exists()) {
246 String msg = I18n.format(tr("Sorry, the folder \"{0}\" already exists."), newFolder.getAbsoluteFile());
247 throw new IOException(msg);
248 }
249
250 // If the folder is actually renamed (as opposed to moved somewhere
251 // else), check for conflicts using the new filename, but the
252 // existing folder name.
253 if (!newFolder.getName().equals(folder.getName()))
254 checkNewFilename(new File(folder, newPrimary));
255
256 return new File(newFolder, newPrimary);
257 }
258
259 /**
260 * Check if renaming or adding a file would cause a problem because
261 * the file already exists in this sketch. If so, an IOEXception is
262 * thrown.
263 *
264 * @param newFile
265 * The filename of the new file, or the new name for an
266 * existing file.
267 */
268 protected void checkNewFilename(File newFile) throws IOException {
269 // Verify that the sketch doesn't have a filem with the new name
270 // already, other than the current primary (index 0)
271 if (findFileIndex(newFile) >= 0) {
272 String msg = I18n.format(tr("The sketch already contains a file named \"{0}\""), newFile.getName());
273 throw new IOException(msg);
274 }
275
276 }
277
278 /**
279 * Rename this sketch' folder to the given name. Unlike saveAs(), this
280 * moves the sketch directory, not leaving anything in the old place.
281 * This operation does not *save* the sketch, so the files on disk are
282 * moved, but not modified.
283 *
284 * @param newFolder
285 * The new folder name for this sketch. The new primary
286 * file's name will be derived from this.
287 *
288 * @throws IOException
289 * When a problem occurs. The error message should be
290 * already translated.
291 */
292 public void renameTo(File newFolder) throws IOException {
293 // Check intended rename (throws if there is a problem)
294 File newPrimary = checkNewFoldername(newFolder);
295
296 // Rename the sketch folder
297 if (!getFolder().renameTo(newFolder))
298 throw new IOException(tr("Failed to rename sketch folder"));
299
300 folder = newFolder;
301
302 // Tell each file about its new name
303 for (SketchFile file : files)
304 file.renamedTo(new File(newFolder, file.getFileName()));
305
306 // And finally, rename the primary file
307 getPrimaryFile().renameTo(newPrimary.getName());
308 }
309
310
311 public SketchFile addFile(String newName) throws IOException {
312 // Check the name will not cause any conflicts
313 File newFile = new File(folder, newName);
314 checkNewFilename(newFile);
315
316 // Add a new sketchFile
317 SketchFile sketchFile = new SketchFile(this, newFile);
318 files.add(sketchFile);
319 Collections.sort(files, CODE_DOCS_COMPARATOR);
320
321 return sketchFile;
322 }
323
324 /**
325 * Save this sketch under the new name given. Unlike renameTo(), this
326 * leaves the existing sketch in place.
327 *
328 * @param newFolder
329 * The new folder name for this sketch. The new primary
330 * file's name will be derived from this.
331 *
332 * @throws IOException
333 * When a problem occurs. The error message should be
334 * already translated.
335 */
336 public void saveAs(File newFolder) throws IOException {
337 // Check intented rename (throws if there is a problem)
338 File newPrimary = checkNewFoldername(newFolder);
339
340 // Create the folder
341 if (!newFolder.mkdirs()) {
342 String msg = I18n.format(tr("Could not create directory \"{0}\""), newFolder.getAbsolutePath());
343 throw new IOException(msg);
344 }
345
346 // Save the files to their new location
347 for (SketchFile file : files) {
348 if (file.isPrimary())
349 file.saveAs(newPrimary);
350 else
351 file.saveAs(new File(newFolder, file.getFileName()));
352 }
353
354
355 // Copy the data folder (this may take a while.. add progress bar?)
356 if (getDataFolder().exists()) {
357 File newDataFolder = new File(newFolder, "data");
358 // Check if data folder exits, if not try to create the data folder
359 if (!newDataFolder.exists() && !newDataFolder.mkdirs()) {
360 String msg = I18n.format(tr("Could not create directory \"{0}\""), newFolder.getAbsolutePath());
361 throw new IOException(msg);
362 }
363 // Copy the data files into the new folder
364 FileUtils.copy(getDataFolder(), newDataFolder);
365 }
366
367 // Change folder to the new folder
368 folder = newFolder;
369
370 }
371
372 /**
373 * Deletes this entire sketch from disk.
374 */
375 void delete() {
376 FileUtils.recursiveDelete(folder);
377 }
378 }