Debian Codegraph @

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

raw symbols SCIP
1 package processing.app;
2
3 import cc.arduino.Constants;
4 import cc.arduino.contributions.GPGDetachedSignatureVerifier;
5 import cc.arduino.contributions.VersionComparator;
6 import cc.arduino.contributions.libraries.LibrariesIndexer;
7 import cc.arduino.contributions.packages.ContributedPlatform;
8 import cc.arduino.contributions.packages.ContributedTool;
9 import cc.arduino.contributions.packages.ContributionsIndexer;
10 import cc.arduino.packages.DiscoveryManager;
11 import com.fasterxml.jackson.core.JsonProcessingException;
12 import org.apache.commons.compress.utils.IOUtils;
13 import org.apache.commons.logging.impl.LogFactoryImpl;
14 import org.apache.commons.logging.impl.NoOpLog;
15 import processing.app.debug.*;
16 import processing.app.helpers.*;
17 import processing.app.helpers.filefilters.OnlyDirs;
18 import processing.app.helpers.filefilters.OnlyFilesWithExtension;
19 import processing.app.legacy.PApplet;
20 import processing.app.packages.LibraryList;
21 import processing.app.packages.UserLibrary;
22 import processing.app.packages.UserLibraryFolder;
23 import processing.app.packages.UserLibraryFolder.Location;
24 import cc.arduino.files.DeleteFilesOnShutdown;
25 import processing.app.helpers.FileUtils;
26
27 import java.beans.PropertyChangeListener;
28 import java.beans.PropertyChangeSupport;
29 import java.io.File;
30 import java.io.FileWriter;
31 import java.io.IOException;
32 import java.util.*;
33 import java.util.logging.Level;
34 import java.util.logging.Logger;
35
36 import cc.arduino.packages.BoardPort;
37
38 import static processing.app.I18n.tr;
39 import static processing.app.helpers.filefilters.OnlyDirs.ONLY_DIRS;
40
41 public class BaseNoGui {
42
43 /** Version string to be used for build */
44 public static final int REVISION = 10819;
45 /** Extended version string displayed on GUI */
46 public static final String VERSION_NAME = "1.8.19";
47 public static final String VERSION_NAME_LONG;
48
49 // Current directory to use for relative paths specified on the
50 // commandline
51 static String currentDirectory = System.getProperty("user.dir");
52
53 static {
54 String versionNameLong = VERSION_NAME;
55 File hourlyBuildTxt = new File(getContentFile("lib"), "hourlyBuild.txt");
56 if (hourlyBuildTxt.exists() && hourlyBuildTxt.canRead()) {
57 versionNameLong += " Hourly Build";
58 try {
59 versionNameLong += " " + FileUtils.readFileToString(hourlyBuildTxt).trim();
60 } catch (IOException e) {
61 //noop
62 }
63 }
64
65 File windowsStoreConfig = new File(getContentFile("lib"), "windowsStore.txt");
66 if (windowsStoreConfig.exists()) {
67 try {
68 PreferencesMap conf = new PreferencesMap(windowsStoreConfig);
69 PreferencesData.setBoolean("runtime.is-windows-store-app", true);
70 PreferencesData.set("runtime.windows-store-app.id", conf.get("appid"));
71 versionNameLong += " (Windows Store " + conf.get("version") + ")";
72 } catch (IOException e1) {
73 e1.printStackTrace();
74 }
75 }
76
77 VERSION_NAME_LONG = versionNameLong;
78 }
79
80 private static DiscoveryManager discoveryManager;
81
82 // these are static because they're used by Sketch
83 static private File examplesFolder;
84 static private File toolsFolder;
85
86 // maps #included files to their library folder
87 public static Map<String, LibraryList> importToLibraryTable;
88
89 // XXX: Remove this field
90 static private List<UserLibraryFolder> librariesFolders;
91
92 static UserNotifier notifier = new BasicUserNotifier();
93
94 static public Map<String, TargetPackage> packages;
95
96 static Platform platform;
97
98 static File portableFolder = null;
99 static final String portableSketchbookFolder = "sketchbook";
100
101 public static ContributionsIndexer indexer;
102 public static LibrariesIndexer librariesIndexer;
103
104 private static String boardManagerLink = "";
105
106 private static File buildCache;
107
108 // Returns a File object for the given pathname. If the pathname
109 // is not absolute, it is interpreted relative to the current
110 // directory when starting the IDE (which is not the same as the
111 // current working directory!).
112 static public File absoluteFile(String path) {
113 if (path == null) return null;
114
115 File file = new File(path);
116 if (!file.isAbsolute()) {
117 file = new File(currentDirectory, path);
118 }
119 return file;
120 }
121
122 /**
123 * Get the number of lines in a file by counting the number of newline
124 * characters inside a String (and adding 1).
125 */
126 static public int countLines(String what) {
127 int count = 1;
128 for (char c : what.toCharArray()) {
129 if (c == '\n') count++;
130 }
131 return count;
132 }
133
134 static public PreferencesMap getBoardPreferences() {
135 TargetBoard board = getTargetBoard();
136 if (board == null)
137 return null;
138 String boardId = board.getId();
139
140 PreferencesMap prefs = new PreferencesMap(board.getPreferences());
141
142 String extendedName = prefs.get("name");
143 for (String menuId : board.getMenuIds()) {
144 if (!board.hasMenu(menuId))
145 continue;
146
147 // Get "custom_[MENU_ID]" preference (for example "custom_cpu")
148 String entry = PreferencesData.get("custom_" + menuId);
149 if (entry != null && entry.startsWith(boardId)) {
150
151 String selectionId = entry.substring(boardId.length() + 1);
152 prefs.putAll(board.getMenuPreferences(menuId, selectionId));
153
154 // Update the name with the extended configuration
155 extendedName += ", " + board.getMenuLabel(menuId, selectionId);
156 }
157 }
158 prefs.put("name", extendedName);
159
160 // Resolve tools needed for this board
161 List<ContributedTool> requiredTools = new ArrayList<>();
162
163 // Add all tools dependencies specified in package index
164 ContributedPlatform p = indexer.getContributedPlaform(getTargetPlatform());
165 if (p != null)
166 requiredTools.addAll(p.getResolvedTools());
167
168 // Add all tools dependencies from the (possibily) referenced core
169 String core = prefs.get("build.core");
170 if (core != null && core.contains(":")) {
171 String split[] = core.split(":");
172 TargetPlatform referenced = BaseNoGui.getCurrentTargetPlatformFromPackage(split[0]);
173 if (referenced != null) {
174 ContributedPlatform referencedPlatform = indexer.getContributedPlaform(referenced);
175 if (referencedPlatform != null)
176 requiredTools.addAll(referencedPlatform.getResolvedTools());
177 } else {
178 String msg = tr("The current selected board needs the core '{0}' that is not installed.");
179 System.out.println(I18n.format(msg, core));
180 }
181 }
182
183 String prefix = "runtime.tools.";
184 for (ContributedTool tool : requiredTools) {
185 File folder = tool.getInstalledFolder();
186 if (folder == null) {
187 continue;
188 }
189 String toolPath = folder.getAbsolutePath();
190 prefs.put(prefix + tool.getName() + ".path", toolPath);
191 prefs.put(prefix + tool.getName() + "-" + tool.getVersion() + ".path", toolPath);
192 PreferencesData.set(prefix + tool.getName() + ".path", toolPath);
193 PreferencesData.set(prefix + tool.getName() + "-" + tool.getVersion() + ".path", toolPath);
194 }
195 return prefs;
196 }
197
198 static public File getContentFile(String name) {
199 String appDir = System.getProperty("APP_DIR");
200 if (appDir == null || appDir.length() == 0) {
201 appDir = currentDirectory;
202 }
203 File installationFolder = new File(appDir);
204 return new File(installationFolder, name);
205 }
206
207 static public TargetPlatform getCurrentTargetPlatformFromPackage(String pack) {
208 return getTargetPlatform(pack, PreferencesData.get("target_platform"));
209 }
210
211 static public File getDefaultSketchbookFolder() {
212 if (getPortableFolder() != null)
213 return new File(getPortableFolder(), getPortableSketchbookFolder());
214
215 File sketchbookFolder = null;
216 try {
217 sketchbookFolder = getPlatform().getDefaultSketchbookFolder();
218 } catch (Exception e) { }
219
220 return sketchbookFolder;
221 }
222
223 public static DiscoveryManager getDiscoveryManager() {
224 if (discoveryManager == null) {
225 discoveryManager = new DiscoveryManager(packages);
226 }
227 return discoveryManager;
228 }
229
230 static public File getExamplesFolder() {
231 return examplesFolder;
232 }
233
234 static public String getExamplesPath() {
235 return examplesFolder.getAbsolutePath();
236 }
237
238 static public File getHardwareFolder() {
239 // calculate on the fly because it's needed by Preferences.init() to find
240 // the boards.txt and programmers.txt preferences files (which happens
241 // before the other folders / paths get cached).
242 return getContentFile("hardware");
243 }
244
245 static public String getHardwarePath() {
246 return getHardwareFolder().getAbsolutePath();
247 }
248
249 static public List<UserLibraryFolder> getLibrariesFolders() {
250 return librariesFolders;
251 }
252
253 static public Platform getPlatform() {
254 return platform;
255 }
256
257 static public File getPortableFolder() {
258 return portableFolder;
259 }
260
261 static public String getPortableSketchbookFolder() {
262 return portableSketchbookFolder;
263 }
264
265 static public File getCachePath() {
266 if (buildCache == null) {
267 try {
268 buildCache = FileUtils.createTempFolder("arduino_cache_");
269 DeleteFilesOnShutdown.add(buildCache);
270 } catch (IOException e) {
271 return null;
272 }
273 }
274 return buildCache;
275 }
276
277 /**
278 * Convenience method to get a File object for the specified filename inside
279 * the settings folder.
280 * For now, only used by Preferences to get the preferences.txt file.
281 * @param filename A file inside the settings folder.
282 * @return filename wrapped as a File object inside the settings folder
283 */
284 static public File getSettingsFile(String filename) {
285 return new File(getSettingsFolder(), filename);
286 }
287
288 static public File getSettingsFolder() {
289 if (getPortableFolder() != null)
290 return getPortableFolder();
291
292 File settingsFolder = null;
293
294 String preferencesPath = PreferencesData.get("settings.path");
295 if (preferencesPath != null) {
296 settingsFolder = absoluteFile(preferencesPath);
297
298 } else {
299 try {
300 settingsFolder = getPlatform().getSettingsFolder();
301 } catch (Exception e) {
302 showError(tr("Problem getting data folder"),
303 tr("Error getting the Arduino data folder."), e);
304 }
305 }
306
307 // create the folder if it doesn't exist already
308 if (!settingsFolder.exists()) {
309 if (!settingsFolder.mkdirs()) {
310 showError(tr("Settings issues"),
311 tr("Arduino cannot run because it could not\n" +
312 "create a folder to store your settings."), null);
313 }
314 }
315 return settingsFolder;
316 }
317
318 static public File getSketchbookFolder() {
319 String sketchBookPath = PreferencesData.get("sketchbook.path");
320 if (getPortableFolder() != null && !new File(sketchBookPath).isAbsolute()) {
321 return new File(getPortableFolder(), sketchBookPath);
322 }
323 return absoluteFile(sketchBookPath);
324 }
325
326 static public File getSketchbookHardwareFolder() {
327 return new File(getSketchbookFolder(), "hardware");
328 }
329
330 static public UserLibraryFolder getSketchbookLibrariesFolder() {
331 File libdir = new File(getSketchbookFolder(), "libraries");
332 if (!libdir.exists()) {
333 FileWriter freadme = null;
334 try {
335 libdir.mkdirs();
336 freadme = new FileWriter(new File(libdir, "readme.txt"));
337 freadme.write(tr("For information on installing libraries, see: " +
338 "http://www.arduino.cc/en/Guide/Libraries\n"));
339 } catch (Exception e) {
340 } finally {
341 IOUtils.closeQuietly(freadme);
342 }
343 }
344 return new UserLibraryFolder(libdir, Location.SKETCHBOOK);
345 }
346
347 static public String getSketchbookPath() {
348 // Get the sketchbook path, and make sure it's set properly
349 String sketchbookPath = PreferencesData.get("sketchbook.path");
350
351 // If a value is at least set, first check to see if the folder exists.
352 // If it doesn't, warn the user that the sketchbook folder is being reset.
353 if (sketchbookPath != null) {
354 File sketchbookFolder;
355 if (getPortableFolder() != null && !new File(sketchbookPath).isAbsolute()) {
356 sketchbookFolder = new File(getPortableFolder(), sketchbookPath);
357 } else {
358 sketchbookFolder = absoluteFile(sketchbookPath);
359 }
360 if (!sketchbookFolder.exists()) {
361 showWarning(tr("Sketchbook folder disappeared"),
362 tr("The sketchbook folder no longer exists.\n" +
363 "Arduino will switch to the default sketchbook\n" +
364 "location, and create a new sketchbook folder if\n" +
365 "necessary. Arduino will then stop talking about\n" +
366 "himself in the third person."), null);
367 sketchbookPath = null;
368 }
369 }
370
371 return sketchbookPath;
372 }
373
374 public static TargetBoard getTargetBoard() {
375 TargetPlatform targetPlatform = getTargetPlatform();
376 if (targetPlatform == null)
377 return null;
378 String boardId = PreferencesData.get("board");
379 return targetPlatform.getBoard(boardId);
380 }
381
382 /**
383 * Returns a specific TargetPackage
384 *
385 * @param packageName
386 * @return
387 */
388 static public TargetPackage getTargetPackage(String packageName) {
389 return packages.get(packageName);
390 }
391
392 /**
393 * Returns the currently selected TargetPlatform.
394 *
395 * @return
396 */
397 static public TargetPlatform getTargetPlatform() {
398 String packageName = PreferencesData.get("target_package");
399 String platformName = PreferencesData.get("target_platform");
400 return getTargetPlatform(packageName, platformName);
401 }
402
403 /**
404 * Returns a specific TargetPlatform searching Package/Platform
405 *
406 * @param packageName
407 * @param platformName
408 * @return
409 */
410 static public TargetPlatform getTargetPlatform(String packageName,
411 String platformName) {
412 TargetPackage p = packages.get(packageName);
413 if (p == null)
414 return null;
415 return p.get(platformName);
416 }
417
418 static public File getToolsFolder() {
419 return toolsFolder;
420 }
421
422 static public String getToolsPath() {
423 return toolsFolder.getAbsolutePath();
424 }
425
426 static public String getBoardManagerLink() {
427 return boardManagerLink;
428 }
429
430 protected static PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(BaseNoGui.class);
431
432 public static void setBoardManagerLink(String temp) {
433 boardManagerLink = temp;
434 propertyChangeSupport.firePropertyChange("boardManagerLink", "", boardManagerLink);
435 }
436
437 public static void addPropertyChangeListener(PropertyChangeListener listener) {
438 propertyChangeSupport.addPropertyChangeListener(listener);
439 }
440
441 /**
442 * Given a folder, return a list of the header files in that folder (but not
443 * the header files in its sub-folders, as those should be included from
444 * within the header files at the top-level).
445 */
446 static public String[] headerListFromIncludePath(File path) throws IOException {
447 String[] list = path.list(new OnlyFilesWithExtension(".h", ".hh", ".hpp"));
448 if (list == null) {
449 throw new IOException();
450 }
451 return list;
452 }
453
454 protected static void dumpPrefs(CommandlineParser parser) {
455 if (parser.getGetPref() != null) {
456 String value = PreferencesData.get(parser.getGetPref(), null);
457 if (value != null) {
458 System.out.println(value);
459 System.exit(0);
460 } else {
461 System.exit(4);
462 }
463 } else {
464 System.out.println("#PREFDUMP#");
465 PreferencesMap prefs = PreferencesData.getMap();
466 for (Map.Entry<String, String> entry : prefs.entrySet()) {
467 System.out.println(entry.getKey() + "=" + entry.getValue());
468 }
469 System.exit(0);
470 }
471 }
472
473 static public void initLogger() {
474 System.setProperty(LogFactoryImpl.LOG_PROPERTY, NoOpLog.class.getCanonicalName());
475 Logger.getLogger("javax.jmdns").setLevel(Level.OFF);
476 }
477
478 static public void initPackages() throws Exception {
479 indexer = new ContributionsIndexer(getSettingsFolder(), getHardwareFolder(), getPlatform(),
480 new GPGDetachedSignatureVerifier());
481
482 try {
483 indexer.parseIndex();
484 } catch (JsonProcessingException e) {
485 File indexFile = indexer.getIndexFile(Constants.DEFAULT_INDEX_FILE_NAME);
486 File indexSignatureFile = indexer.getIndexFile(Constants.DEFAULT_INDEX_FILE_NAME + ".sig");
487 indexFile.delete();
488 indexSignatureFile.delete();
489 throw e;
490 }
491 indexer.syncWithFilesystem();
492
493 packages = new LinkedHashMap<>();
494 loadHardware(getHardwareFolder());
495 loadContributedHardware(indexer);
496 loadHardware(getSketchbookHardwareFolder());
497 createToolPreferences(indexer.getInstalledTools(), true);
498
499 librariesIndexer = new LibrariesIndexer(getSettingsFolder());
500 try {
501 librariesIndexer.parseIndex();
502 } catch (JsonProcessingException e) {
503 File librariesIndexFile = librariesIndexer.getIndexFile();
504 librariesIndexFile.delete();
505 }
506
507 if (discoveryManager == null) {
508 discoveryManager = new DiscoveryManager(packages);
509 }
510 }
511
512 static public void initPlatform() {
513 try {
514 Class<?> platformClass = Class.forName("processing.app.Platform");
515 if (OSUtils.isMacOS()) {
516 platformClass = Class.forName("processing.app.macosx.Platform");
517 } else if (OSUtils.isWindows()) {
518 platformClass = Class.forName("processing.app.windows.Platform");
519 } else if (OSUtils.isLinux()) {
520 platformClass = Class.forName("processing.app.linux.Platform");
521 }
522 platform = (Platform) platformClass.newInstance();
523 } catch (Exception e) {
524 showError(tr("Problem Setting the Platform"),
525 tr("An unknown error occurred while trying to load\n" +
526 "platform-specific code for your machine."), e);
527 }
528 }
529
530 static public void initPortableFolder() {
531 // Portable folder
532 portableFolder = getContentFile("portable");
533 if (!portableFolder.exists()) {
534 portableFolder = null;
535 }
536 }
537
538 static public void initVersion() {
539 // help 3rd party installers find the correct hardware path
540 PreferencesData.set("last.ide." + VERSION_NAME + ".hardwarepath", getHardwarePath());
541 PreferencesData.set("last.ide." + VERSION_NAME + ".daterun", "" + (new Date()).getTime() / 1000);
542 }
543
544 /**
545 * Return true if the name is valid for a Processing sketch.
546 */
547 static public boolean isSanitaryName(String name) {
548 return sanitizeName(name).equals(name);
549 }
550
551 static protected void loadHardware(File folder) {
552 if (!folder.isDirectory()) {
553 return;
554 }
555
556 String list[] = folder.list(new OnlyDirs());
557
558 // if a bad folder or something like that, this might come back null
559 if (list == null) {
560 return;
561 }
562
563 // alphabetize list, since it's not always alpha order
564 // replaced hella slow bubble sort with this feller for 0093
565 Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
566
567 for (String target : list) {
568 // Skip reserved 'tools' folder.
569 if (target.equals("tools")) {
570 continue;
571 }
572 File subfolder = new File(folder, target);
573
574 TargetPackage targetPackage;
575 if (packages.containsKey(target)) {
576 targetPackage = packages.get(target);
577 } else {
578 targetPackage = new LegacyTargetPackage(target);
579 packages.put(target, targetPackage);
580 }
581 try {
582 loadTargetPackage(targetPackage, subfolder);
583 } catch (TargetPlatformException e) {
584 System.out.println("WARNING: Error loading hardware folder " + new File(folder, target));
585 System.out.println(" " + e.getMessage());
586 }
587 }
588 }
589
590 private static void loadTargetPackage(TargetPackage targetPackage, File _folder) throws TargetPlatformException {
591 File[] folders = _folder.listFiles(ONLY_DIRS);
592 if (folders == null) {
593 return;
594 }
595
596 for (File subFolder : folders) {
597 if (!subFolder.exists() || !subFolder.canRead()) {
598 continue;
599 }
600 String arch = subFolder.getName();
601 try {
602 TargetPlatform p = new LegacyTargetPlatform(arch, subFolder, targetPackage);
603 targetPackage.getPlatforms().put(arch, p);
604 } catch (TargetPlatformException e) {
605 System.err.println(e.getMessage());
606 }
607 }
608
609 if (targetPackage.getPlatforms().size() == 0) {
610 throw new TargetPlatformException(I18n.format(tr("No valid hardware definitions found in folder {0}."), _folder.getName()));
611 }
612 }
613
614 /**
615 * Grab the contents of a file as a string.
616 */
617 static public String loadFile(File file) throws IOException {
618 String[] contents = PApplet.loadStrings(file);
619 if (contents == null) return null;
620 return PApplet.join(contents, "\n");
621 }
622
623 public static void checkInstallationFolder() {
624 if (isIDEInstalledIntoSettingsFolder()) {
625 showError(tr("Incorrect IDE installation folder"), tr("Your copy of the IDE is installed in a subfolder of your settings folder.\nPlease move the IDE to another folder."), 10);
626 }
627 if (isIDEInstalledIntoSketchbookFolder()) {
628 showError(tr("Incorrect IDE installation folder"), tr("Your copy of the IDE is installed in a subfolder of your sketchbook.\nPlease move the IDE to another folder."), 10);
629 }
630 }
631
632 public static boolean isIDEInstalledIntoSketchbookFolder() {
633 return PreferencesData.has("sketchbook.path") && FileUtils.isSubDirectory(new File(PreferencesData.get("sketchbook.path")), new File(PreferencesData.get("runtime.ide.path")));
634 }
635
636 public static boolean isIDEInstalledIntoSettingsFolder() {
637 try {
638 return FileUtils.isSubDirectory(BaseNoGui.getPlatform().getSettingsFolder(), new File(PreferencesData.get("runtime.ide.path")));
639 } catch (Exception e) {
640 return false;
641 }
642 }
643
644 static public void onBoardOrPortChange() {
645 examplesFolder = getContentFile("examples");
646 toolsFolder = getContentFile("tools");
647 librariesFolders = new ArrayList<>();
648
649 // Add IDE libraries folder
650 librariesFolders.add(new UserLibraryFolder(getContentFile("libraries"), Location.IDE_BUILTIN));
651
652 TargetPlatform targetPlatform = getTargetPlatform();
653 if (targetPlatform != null) {
654 String core = getBoardPreferences().get("build.core", "arduino");
655 if (core.contains(":")) {
656 String referencedCore = core.split(":")[0];
657 TargetPlatform referencedPlatform = getTargetPlatform(referencedCore, targetPlatform.getId());
658 if (referencedPlatform != null) {
659 File referencedPlatformFolder = referencedPlatform.getFolder();
660 // Add libraries folder for the referenced platform
661 File folder = new File(referencedPlatformFolder, "libraries");
662 librariesFolders.add(new UserLibraryFolder(folder, Location.REFERENCED_CORE));
663 }
664 }
665 File platformFolder = targetPlatform.getFolder();
666 // Add libraries folder for the selected platform
667 File folder = new File(platformFolder, "libraries");
668 librariesFolders.add(new UserLibraryFolder(folder, Location.CORE));
669 }
670
671 // Add libraries folder for the sketchbook
672 librariesFolders.add(getSketchbookLibrariesFolder());
673
674 // Scan for libraries in each library folder.
675 // Libraries located in the latest folders on the list can override
676 // other libraries with the same name.
677 librariesIndexer.setLibrariesFolders(librariesFolders);
678 if (getTargetPlatform() != null) {
679 librariesIndexer.setArchitecturePriority(getTargetPlatform().getId());
680 }
681 librariesIndexer.rescanLibraries();
682
683 populateImportToLibraryTable();
684 }
685
686 static protected void loadContributedHardware(ContributionsIndexer idx) {
687 for (TargetPackage pack : idx.createTargetPackages()) {
688 packages.put(pack.getId(), pack);
689 }
690 }
691
692 public static void createToolPreferences(Collection<ContributedTool> installedTools, boolean removeOldKeys) {
693 String prefix = "runtime.tools.";
694 if (removeOldKeys) {
695 PreferencesData.removeAllKeysWithPrefix(prefix);
696 }
697
698 Map<String, String> latestVersions = new HashMap<>();
699 for (ContributedTool tool : installedTools) {
700 File installedFolder = tool.getInstalledFolder();
701 String toolPath;
702 if (installedFolder != null) {
703 toolPath = installedFolder.getAbsolutePath();
704 } else {
705 toolPath = Constants.PREF_REMOVE_PLACEHOLDER;
706 }
707 String toolName = tool.getName();
708 String toolVersion = tool.getVersion();
709 PreferencesData.set(prefix + toolName + "-" + toolVersion + ".path", toolPath);
710 PreferencesData.set(prefix + tool.getPackager() + "-" + toolName + "-" + toolVersion + ".path", toolPath);
711 // In the generic tool property put the path of the latest version if more are available
712 try {
713 if (!latestVersions.containsKey(toolName) || VersionComparator.greaterThan(toolVersion, latestVersions.get(toolName))) {
714 latestVersions.put(toolName, toolVersion);
715 PreferencesData.set(prefix + toolName + ".path", toolPath);
716 }
717 } catch (Exception e) {
718 // Ignore invalid versions
719 }
720 }
721 }
722
723 static public void populateImportToLibraryTable() {
724 // Populate importToLibraryTable. Each header filename maps to
725 // a list of libraries. Compiler.java will use only the first
726 // library on each list. The others are used only to advise
727 // user of ambiguously matched and duplicate libraries.
728 importToLibraryTable = new HashMap<>();
729 for (UserLibrary lib : librariesIndexer.getInstalledLibraries()) {
730 try {
731 String headers[] = headerListFromIncludePath(lib.getSrcFolder());
732 for (String header : headers) {
733 LibraryList list = importToLibraryTable.get(header);
734 if (list == null) {
735 // This is the first library found with this header
736 list = new LibraryList();
737 list.addFirst(lib);
738 importToLibraryTable.put(header, list);
739 } else {
740 UserLibrary old = list.peekFirst();
741 boolean useThisLib = true;
742 // This is the case where 2 libraries have a .h header
743 // with the same name. We must decide which library to
744 // use when a sketch has #include "name.h"
745 //
746 // When all other factors are equal, "libName" is
747 // used in preference to "oldName", because getLibraries()
748 // gives the library list in order from less specific to
749 // more specific locations.
750 //
751 // But often one library is more clearly the user's
752 // intention to use. Many cases are tested, always first
753 // for "libName", then for "oldName".
754 //
755 String name = header.substring(0, header.length() - 2); // name without ".h"
756 String oldName = old.getInstalledFolder().getName(); // just the library folder name
757 String libName = lib.getInstalledFolder().getName(); // just the library folder name
758 //System.out.println("name conflict: " + name);
759 //System.out.println(" old = " + oldName + " -> " + old.getInstalledFolder().getPath());
760 //System.out.println(" new = " + libName + " -> " + lib.getInstalledFolder().getPath());
761 String name_lc = name.toLowerCase();
762 String oldName_lc = oldName.toLowerCase();
763 String libName_lc = libName.toLowerCase();
764 // always favor a perfect name match
765 if (libName.equals(name)) {
766 } else if (oldName.equals(name)) {
767 useThisLib = false;
768 // check for "-master" appended (zip file from github)
769 } else if (libName.equals(name+"-master")) {
770 } else if (oldName.equals(name+"-master")) {
771 useThisLib = false;
772 // next, favor a match with other stuff appended
773 } else if (libName.startsWith(name)) {
774 } else if (oldName.startsWith(name)) {
775 useThisLib = false;
776 // otherwise, favor a match with stuff prepended
777 } else if (libName.endsWith(name)) {
778 } else if (oldName.endsWith(name)) {
779 useThisLib = false;
780 // as a last resort, match if stuff prepended and appended
781 } else if (libName.contains(name)) {
782 } else if (oldName.contains(name)) {
783 useThisLib = false;
784 // repeat all the above tests, with case insensitive matching
785 } else if (libName_lc.equals(name_lc)) {
786 } else if (oldName_lc.equals(name_lc)) {
787 useThisLib = false;
788 } else if (libName_lc.equals(name_lc+"-master")) {
789 } else if (oldName_lc.equals(name_lc+"-master")) {
790 useThisLib = false;
791 } else if (libName_lc.startsWith(name_lc)) {
792 } else if (oldName_lc.startsWith(name_lc)) {
793 useThisLib = false;
794 } else if (libName_lc.endsWith(name_lc)) {
795 } else if (oldName_lc.endsWith(name_lc)) {
796 useThisLib = false;
797 } else if (libName_lc.contains(name_lc)) {
798 } else if (oldName_lc.contains(name_lc)) {
799 useThisLib = false;
800 } else {
801 // none of these tests matched, so just default to "libName".
802 }
803 if (useThisLib) {
804 list.addFirst(lib);
805 } else {
806 list.addLast(lib);
807 }
808 }
809 }
810 } catch (IOException e) {
811 showWarning(tr("Error"), I18n
812 .format("Unable to list header files in {0}", lib.getSrcFolder()), e);
813 }
814 }
815 }
816
817 static public void initParameters(String args[]) throws Exception {
818 String preferencesFile = null;
819
820 // Do a first pass over the commandline arguments, the rest of them
821 // will be processed by the Base constructor. Note that this loop
822 // does not look at the last element of args, to prevent crashing
823 // when no parameter was specified to an option. Later, Base() will
824 // then show an error for these.
825 for (int i = 0; i < args.length - 1; i++) {
826 if (args[i].equals("--preferences-file")) {
827 ++i;
828 preferencesFile = args[i];
829 continue;
830 }
831 }
832
833 // run static initialization that grabs all the prefs
834 PreferencesData.init(absoluteFile(preferencesFile));
835 }
836
837 /**
838 * Produce a sanitized name that fits our standards for likely to work.
839 * <p/>
840 * Java classes have a wider range of names that are technically allowed
841 * (supposedly any Unicode name) than what we support. The reason for
842 * going more narrow is to avoid situations with text encodings and
843 * converting during the process of moving files between operating
844 * systems, i.e. uploading from a Windows machine to a Linux server,
845 * or reading a FAT32 partition in OS X and using a thumb drive.
846 * <p/>
847 * This helper function replaces everything but A-Z, a-z, and 0-9 with
848 * underscores. Also disallows starting the sketch name with a digit.
849 */
850 static public String sanitizeName(String origName) {
851 char c[] = origName.toCharArray();
852 StringBuffer buffer = new StringBuffer();
853
854 for (int i = 0; i < c.length; i++) {
855 if (((c[i] >= '0') && (c[i] <= '9')) ||
856 ((c[i] >= 'a') && (c[i] <= 'z')) ||
857 ((c[i] >= 'A') && (c[i] <= 'Z')) ||
858 ((i > 0) && (c[i] == '-')) ||
859 ((i > 0) && (c[i] == '.'))) {
860 buffer.append(c[i]);
861 } else {
862 buffer.append('_');
863 }
864 }
865 // let's not be ridiculous about the length of filenames.
866 // in fact, Mac OS 9 can handle 255 chars, though it can't really
867 // deal with filenames longer than 31 chars in the Finder.
868 // but limiting to that for sketches would mean setting the
869 // upper-bound on the character limit here to 25 characters
870 // (to handle the base name + ".class")
871 if (buffer.length() > 63) {
872 buffer.setLength(63);
873 }
874 return buffer.toString();
875 }
876
877 /**
878 * Save the content of a String into a file
879 * - Save the content into a temp file
880 * - Find the canonical path of the file (if it's a symlink, follow it)
881 * - Remove the original file
882 * - Move temp file to original path
883 * This ensures that the file is not getting truncated if the disk is full
884 */
885 static public void saveFile(String str, File file) throws IOException {
886 File temp = File.createTempFile(file.getName(), null, file.getParentFile());
887 // Split the file content using minimum common separator \n
888 // then trim any other character (\r) so saveStrings can print it in the correct
889 // format for every OS
890 String strArray[] = str.split("\n");
891 for (String item : strArray) {
892 item.trim();
893 }
894 PApplet.saveStrings(temp, strArray);
895
896 try {
897 file = file.toPath().toRealPath().toFile().getCanonicalFile();
898 } catch (IOException e) {
899 }
900
901 if (file.exists()) {
902 boolean result = file.delete();
903 if (!result) {
904 throw new IOException(
905 I18n.format(
906 tr("Could not remove old version of {0}"),
907 file.getAbsolutePath()));
908 }
909 }
910 boolean result = temp.renameTo(file);
911 if (!result) {
912 throw new IOException(
913 I18n.format(
914 tr("Could not replace {0}"),
915 file.getAbsolutePath()));
916 }
917 }
918
919 static public void selectBoard(TargetBoard targetBoard) {
920 TargetPlatform targetPlatform = targetBoard.getContainerPlatform();
921 TargetPackage targetPackage = targetPlatform.getContainerPackage();
922
923 PreferencesData.set("target_package", targetPackage.getId());
924 PreferencesData.set("target_platform", targetPlatform.getId());
925 PreferencesData.set("board", targetBoard.getId());
926
927 File platformFolder = targetPlatform.getFolder();
928 PreferencesData.set("runtime.platform.path", platformFolder.getAbsolutePath());
929 PreferencesData.set("runtime.hardware.path", platformFolder.getParentFile().getAbsolutePath());
930 }
931
932 public static void selectSerialPort(String port) {
933 PreferencesData.set("serial.port", port);
934 BoardPort boardPort = getDiscoveryManager().find(port, true);
935 if (boardPort != null) {
936 PreferencesData.set("serial.port.iserial", boardPort.getPrefs().get("iserial"));
937 }
938 String portFile = port;
939 if (port.startsWith("/dev/")) {
940 portFile = portFile.substring(5);
941 }
942 PreferencesData.set("serial.port.file", portFile);
943 }
944
945 static public void showError(String title, String message, int exit_code) {
946 showError(title, message, null, exit_code);
947 }
948
949 static public void showError(String title, String message, Throwable e) {
950 notifier.showError(title, message, e, 1);
951 }
952
953 /**
954 * Show an error message that's actually fatal to the program.
955 * This is an error that can't be recovered. Use showWarning()
956 * for errors that allow P5 to continue running.
957 */
958 static public void showError(String title, String message, Throwable e, int exit_code) {
959 notifier.showError(title, message, e, exit_code);
960 }
961
962 /**
963 * "No cookie for you" type messages. Nothing fatal or all that
964 * much of a bummer, but something to notify the user about.
965 */
966 static public void showMessage(String title, String message) {
967 notifier.showMessage(title, message);
968 }
969
970 /**
971 * Non-fatal error message with optional stack trace side dish.
972 */
973 static public void showWarning(String title, String message, Exception e) {
974 notifier.showWarning(title, message, e);
975 }
976
977 }