Debian Codegraph @

arduino-core/src/processing/app/legacy/PApplet.java

raw symbols SCIP
1 package processing.app.legacy;
2
3 import org.apache.commons.compress.utils.IOUtils;
4
5 import java.io.*;
6 import java.text.NumberFormat;
7 import java.util.ArrayList;
8 import java.util.StringTokenizer;
9 import java.util.regex.Matcher;
10 import java.util.regex.Pattern;
11 import java.util.zip.GZIPInputStream;
12 import java.util.zip.GZIPOutputStream;
13
14 public class PApplet {
15
16 /** Path to sketch folder */
17 public String sketchPath; //folder;
18
19 /**
20 * Current platform in use, one of the
21 * PConstants WINDOWS, MACOSX, MACOS9, LINUX or OTHER.
22 */
23 static public int platform;
24
25 /**
26 * Name associated with the current 'platform' (see PConstants.platformNames)
27 */
28 //static public String platformName;
29
30 static {
31 String osname = System.getProperty("os.name");
32
33 if (osname.indexOf("Mac") != -1) {
34 platform = PConstants.MACOSX;
35
36 } else if (osname.indexOf("Windows") != -1) {
37 platform = PConstants.WINDOWS;
38
39 } else if (osname.equals("Linux")) { // true for the ibm vm
40 platform = PConstants.LINUX;
41
42 } else {
43 platform = PConstants.OTHER;
44 }
45 }
46
47 /**
48 * Split the provided String at wherever whitespace occurs. Multiple
49 * whitespace (extra spaces or tabs or whatever) between items will count as a
50 * single break.
51 * <P>
52 * The whitespace characters are "\t\n\r\f", which are the defaults for
53 * java.util.StringTokenizer, plus the unicode non-breaking space character,
54 * which is found commonly on files created by or used in conjunction with Mac
55 * OS X (character 160, or 0x00A0 in hex).
56 *
57 * <PRE>
58 * i.e. splitTokens("a b") -> { "a", "b" }
59 * splitTokens("a b") -> { "a", "b" }
60 * splitTokens("a\tb") -> { "a", "b" }
61 * splitTokens("a \t b ") -> { "a", "b" }
62 * </PRE>
63 */
64 static public String[] splitTokens(String what) {
65 return splitTokens(what, PConstants.WHITESPACE);
66 }
67
68 /**
69 * Splits a string into pieces, using any of the chars in the String 'delim'
70 * as separator characters. For instance, in addition to white space, you
71 * might want to treat commas as a separator. The delimeter characters won't
72 * appear in the returned String array.
73 *
74 * <PRE>
75 * i.e. splitTokens("a, b", " ,") -> { "a", "b" }
76 * </PRE>
77 *
78 * To include all the whitespace possibilities, use the variable WHITESPACE,
79 * found in PConstants:
80 *
81 * <PRE>
82 * i.e. splitTokens("a | b", WHITESPACE + "|"); -> { "a", "b" }
83 * </PRE>
84 */
85 static public String[] splitTokens(String what, String delim) {
86 StringTokenizer toker = new StringTokenizer(what, delim);
87 String pieces[] = new String[toker.countTokens()];
88
89 int index = 0;
90 while (toker.hasMoreTokens()) {
91 pieces[index++] = toker.nextToken();
92 }
93 return pieces;
94 }
95
96 /**
97 * Split a string into pieces along a specific character. Most commonly used
98 * to break up a String along a space or a tab character.
99 * <P>
100 * This operates differently than the others, where the single delimeter is
101 * the only breaking point, and consecutive delimeters will produce an empty
102 * string (""). This way, one can split on tab characters, but maintain the
103 * column alignments (of say an excel file) where there are empty columns.
104 */
105 static public String[] split(String what, char delim) {
106 // do this so that the exception occurs inside the user's
107 // program, rather than appearing to be a bug inside split()
108 if (what == null)
109 return null;
110
111 char chars[] = what.toCharArray();
112 int splitCount = 0; // 1;
113 for (int i = 0; i < chars.length; i++) {
114 if (chars[i] == delim)
115 splitCount++;
116 }
117 if (splitCount == 0) {
118 String splits[] = new String[1];
119 splits[0] = new String(what);
120 return splits;
121 }
122 String splits[] = new String[splitCount + 1];
123 int splitIndex = 0;
124 int startIndex = 0;
125 for (int i = 0; i < chars.length; i++) {
126 if (chars[i] == delim) {
127 splits[splitIndex++] = new String(chars, startIndex, i - startIndex);
128 startIndex = i + 1;
129 }
130 }
131 splits[splitIndex] = new String(chars, startIndex, chars.length
132 - startIndex);
133 return splits;
134 }
135
136 static public String[] subset(String list[], int start, int count) {
137 String output[] = new String[count];
138 System.arraycopy(list, start, output, 0, count);
139 return output;
140 }
141
142
143 /**
144 * Join an array of Strings together as a single String,
145 * separated by the whatever's passed in for the separator.
146 */
147 static public String join(String str[], char separator) {
148 return join(str, String.valueOf(separator));
149 }
150
151
152 /**
153 * Join an array of Strings together as a single String,
154 * separated by the whatever's passed in for the separator.
155 * <P>
156 * To use this on numbers, first pass the array to nf() or nfs()
157 * to get a list of String objects, then use join on that.
158 * <PRE>
159 * e.g. String stuff[] = { "apple", "bear", "cat" };
160 * String list = join(stuff, ", ");
161 * // list is now "apple, bear, cat"</PRE>
162 */
163 static public String join(String str[], String separator) {
164 StringBuffer buffer = new StringBuffer();
165 for (int i = 0; i < str.length; i++) {
166 if (i != 0) buffer.append(separator);
167 buffer.append(str[i]);
168 }
169 return buffer.toString();
170 }
171
172 /**
173 * Parse a String into an int value. Returns 0 if the value is bad.
174 */
175 static final public int parseInt(String what) {
176 return parseInt(what, 0);
177 }
178
179 /**
180 * Parse a String to an int, and provide an alternate value that
181 * should be used when the number is invalid.
182 */
183 static final public int parseInt(String what, int otherwise) {
184 try {
185 int offset = what.indexOf('.');
186 if (offset == -1) {
187 return Integer.parseInt(what);
188 } else {
189 return Integer.parseInt(what.substring(0, offset));
190 }
191 } catch (NumberFormatException e) { }
192 return otherwise;
193 }
194
195 /**
196 * Make an array of int elements from an array of String objects.
197 * If the String can't be parsed as a number, it will be set to zero.
198 *
199 * String s[] = { "1", "300", "44" };
200 * int numbers[] = parseInt(s);
201 *
202 * numbers will contain { 1, 300, 44 }
203 */
204 static public int[] parseInt(String what[]) {
205 return parseInt(what, 0);
206 }
207
208 /**
209 * Make an array of int elements from an array of String objects.
210 * If the String can't be parsed as a number, its entry in the
211 * array will be set to the value of the "missing" parameter.
212 *
213 * String s[] = { "1", "300", "apple", "44" };
214 * int numbers[] = parseInt(s, 9999);
215 *
216 * numbers will contain { 1, 300, 9999, 44 }
217 */
218 static public int[] parseInt(String what[], int missing) {
219 int output[] = new int[what.length];
220 for (int i = 0; i < what.length; i++) {
221 try {
222 output[i] = Integer.parseInt(what[i]);
223 } catch (NumberFormatException e) {
224 output[i] = missing;
225 }
226 }
227 return output;
228 }
229
230 static public String[] loadStrings(File file) {
231 InputStream is = null;
232 try {
233 is = createInput(file);
234 if (is != null) return loadStrings(is);
235 return null;
236 } finally {
237 IOUtils.closeQuietly(is);
238 }
239 }
240
241 static public String[] loadStrings(InputStream input) {
242 BufferedReader reader = null;
243 try {
244 reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
245
246 String lines[] = new String[100];
247 int lineCount = 0;
248 String line = null;
249 while ((line = reader.readLine()) != null) {
250 if (lineCount == lines.length) {
251 String temp[] = new String[lineCount << 1];
252 System.arraycopy(lines, 0, temp, 0, lineCount);
253 lines = temp;
254 }
255 lines[lineCount++] = line;
256 }
257
258 if (lineCount == lines.length) {
259 return lines;
260 }
261
262 // resize array to appropriate amount for these lines
263 String output[] = new String[lineCount];
264 System.arraycopy(lines, 0, output, 0, lineCount);
265 return output;
266
267 } catch (IOException e) {
268 e.printStackTrace();
269 //throw new RuntimeException("Error inside loadStrings()");
270 } finally {
271 IOUtils.closeQuietly(reader);
272 }
273 return null;
274 }
275
276 public void saveStrings(String filename, String strings[]) {
277 saveStrings(saveFile(filename), strings);
278 }
279
280
281 static public void saveStrings(File file, String strings[]) {
282 OutputStream outputStream = null;
283 try {
284 outputStream = createOutput(file);
285 saveStrings(outputStream, strings);
286 } finally {
287 IOUtils.closeQuietly(outputStream);
288 }
289 }
290
291
292 static public void saveStrings(OutputStream output, String strings[]) {
293 PrintWriter writer = null;
294 try {
295 writer = createWriter(output);
296 if (writer == null) {
297 return;
298 }
299 for (String string : strings) {
300 writer.println(string);
301 }
302 writer.flush();
303 } finally {
304 IOUtils.closeQuietly(writer);
305 }
306 }
307
308
309 static public int[] expand(int list[]) {
310 return expand(list, list.length << 1);
311 }
312
313 static public int[] expand(int list[], int newSize) {
314 int temp[] = new int[newSize];
315 System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
316 return temp;
317 }
318
319 static final public String hex(int what, int digits) {
320 String stuff = Integer.toHexString(what).toUpperCase();
321
322 int length = stuff.length();
323 if (length > digits) {
324 return stuff.substring(length - digits);
325
326 } else if (length < digits) {
327 return "00000000".substring(8 - (digits-length)) + stuff;
328 }
329 return stuff;
330 }
331
332 static public final int constrain(int amt, int low, int high) {
333 return (amt < low) ? low : ((amt > high) ? high : amt);
334 }
335
336 static public final float constrain(float amt, float low, float high) {
337 return (amt < low) ? low : ((amt > high) ? high : amt);
338 }
339
340 /**
341 * Attempts to open an application or file using your platform's launcher. The <b>file</b> parameter is a String specifying the file name and location. The location parameter must be a full path name, or the name of an executable in the system's PATH. In most cases, using a full path is the best option, rather than relying on the system PATH. Be sure to make the file executable before attempting to open it (chmod +x).
342 * <br><br>
343 * The <b>args</b> parameter is a String or String array which is passed to the command line. If you have multiple parameters, e.g. an application and a document, or a command with multiple switches, use the version that takes a String array, and place each individual item in a separate element.
344 * <br><br>
345 * If args is a String (not an array), then it can only be a single file or application with no parameters. It's not the same as executing that String using a shell. For instance, open("jikes -help") will not work properly.
346 * <br><br>
347 * This function behaves differently on each platform. On Windows, the parameters are sent to the Windows shell via "cmd /c". On Mac OS X, the "open" command is used (type "man open" in Terminal.app for documentation). On Linux, it first tries gnome-open, then kde-open, but if neither are available, it sends the command to the shell without any alterations.
348 * <br><br>
349 * For users familiar with Java, this is not quite the same as Runtime.exec(), because the launcher command is prepended. Instead, the <b>exec(String[])</b> function is a shortcut for Runtime.getRuntime.exec(String[]).
350 *
351 * @webref input:files
352 * @param filename name of the file
353 * @usage Application
354 */
355 static public void open(String filename) {
356 open(new String[] { filename });
357 }
358
359 static String openLauncher;
360
361 /**
362 * Launch a process using a platforms shell. This version uses an array
363 * to make it easier to deal with spaces in the individual elements.
364 * (This avoids the situation of trying to put single or double quotes
365 * around different bits).
366 *
367 * @param list of commands passed to the command line
368 */
369 static public Process open(String argv[]) {
370 String[] params = null;
371
372 if (platform == PConstants.WINDOWS) {
373 // just launching the .html file via the shell works
374 // but make sure to chmod +x the .html files first
375 // also place quotes around it in case there's a space
376 // in the user.dir part of the url
377 params = new String[] { "cmd", "/c" };
378
379 } else if (platform == PConstants.MACOSX) {
380 params = new String[] { "open" };
381
382 } else if (platform == PConstants.LINUX) {
383 if (openLauncher == null) {
384 // Attempt to use gnome-open
385 try {
386 Process p = Runtime.getRuntime().exec(new String[] { "gnome-open" });
387 /*int result =*/ p.waitFor();
388 // Not installed will throw an IOException (JDK 1.4.2, Ubuntu 7.04)
389 openLauncher = "gnome-open";
390 } catch (Exception e) { }
391 }
392 if (openLauncher == null) {
393 // Attempt with kde-open
394 try {
395 Process p = Runtime.getRuntime().exec(new String[] { "kde-open" });
396 /*int result =*/ p.waitFor();
397 openLauncher = "kde-open";
398 } catch (Exception e) { }
399 }
400 if (openLauncher == null) {
401 System.err.println("Could not find gnome-open or kde-open, " +
402 "the open() command may not work.");
403 }
404 if (openLauncher != null) {
405 params = new String[] { openLauncher };
406 }
407 //} else { // give up and just pass it to Runtime.exec()
408 //open(new String[] { filename });
409 //params = new String[] { filename };
410 }
411 if (params != null) {
412 // If the 'open', 'gnome-open' or 'cmd' are already included
413 if (params[0].equals(argv[0])) {
414 // then don't prepend those params again
415 return exec(argv);
416 } else {
417 params = concat(params, argv);
418 return exec(params);
419 }
420 } else {
421 return exec(argv);
422 }
423 }
424
425 static public Process exec(String[] argv) {
426 try {
427 return Runtime.getRuntime().exec(argv);
428 } catch (Exception e) {
429 e.printStackTrace();
430 throw new RuntimeException("Could not open " + join(argv, ' '));
431 }
432 }
433
434 static public String[] concat(String a[], String b[]) {
435 String c[] = new String[a.length + b.length];
436 System.arraycopy(a, 0, c, 0, a.length);
437 System.arraycopy(b, 0, c, a.length, b.length);
438 return c;
439 }
440
441 /**
442 * Identical to match(), except that it returns an array of all matches in
443 * the specified String, rather than just the first.
444 */
445 static public String[][] matchAll(String what, String regexp) {
446 Pattern p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL);
447 Matcher m = p.matcher(what);
448 ArrayList<String[]> results = new ArrayList<>();
449 int count = m.groupCount() + 1;
450 while (m.find()) {
451 String[] groups = new String[count];
452 for (int i = 0; i < count; i++) {
453 groups[i] = m.group(i);
454 }
455 results.add(groups);
456 }
457 if (results.isEmpty()) {
458 return null;
459 }
460 String[][] matches = new String[results.size()][count];
461 for (int i = 0; i < matches.length; i++) {
462 matches[i] = results.get(i);
463 }
464 return matches;
465 }
466
467 /**
468 * Match a string with a regular expression, and returns the match as an
469 * array. The first index is the matching expression, and array elements
470 * [1] and higher represent each of the groups (sequences found in parens).
471 *
472 * This uses multiline matching (Pattern.MULTILINE) and dotall mode
473 * (Pattern.DOTALL) by default, so that ^ and $ match the beginning and
474 * end of any lines found in the source, and the . operator will also
475 * pick up newline characters.
476 */
477 static public String[] match(String what, String regexp) {
478 Pattern p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL);
479 return match(what, p);
480 }
481
482 static public String[] match(String what, Pattern pattern) {
483 Matcher m = pattern.matcher(what);
484 if (m.find()) {
485 int count = m.groupCount() + 1;
486 String[] groups = new String[count];
487 for (int i = 0; i < count; i++) {
488 groups[i] = m.group(i);
489 }
490 return groups;
491 }
492 return null;
493 }
494
495 /**
496 * Integer number formatter.
497 */
498 static private NumberFormat int_nf;
499 static private int int_nf_digits;
500 static private boolean int_nf_commas;
501
502 static public String[] nf(int num[], int digits) {
503 String formatted[] = new String[num.length];
504 for (int i = 0; i < formatted.length; i++) {
505 formatted[i] = nf(num[i], digits);
506 }
507 return formatted;
508 }
509
510 static public String nf(int num, int digits) {
511 if ((int_nf != null) &&
512 (int_nf_digits == digits) &&
513 !int_nf_commas) {
514 return int_nf.format(num);
515 }
516
517 int_nf = NumberFormat.getInstance();
518 int_nf.setGroupingUsed(false); // no commas
519 int_nf_commas = false;
520 int_nf.setMinimumIntegerDigits(digits);
521 int_nf_digits = digits;
522 return int_nf.format(num);
523 }
524
525 static final public String[] str(int x[]) {
526 String s[] = new String[x.length];
527 for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
528 return s;
529 }
530
531 /**
532 * I want to print lines to a file. I have RSI from typing these
533 * eight lines of code so many times.
534 * @throws IOException
535 */
536 static public PrintWriter createWriter(File file) throws IOException {
537 createPath(file); // make sure in-between folders exist
538 OutputStream output = new FileOutputStream(file);
539 try {
540 if (file.getName().toLowerCase().endsWith(".gz")) {
541 output = new GZIPOutputStream(output);
542 }
543 } catch (IOException e) {
544 output.close();
545 throw e;
546 }
547 return createWriter(output);
548 }
549
550
551 /**
552 * I want to print lines to a file. Why am I always explaining myself?
553 * It's the JavaSoft API engineers who need to explain themselves.
554 */
555 static public PrintWriter createWriter(OutputStream output) {
556 try {
557 OutputStreamWriter osw = new OutputStreamWriter(output, "UTF-8");
558 return new PrintWriter(osw);
559 } catch (UnsupportedEncodingException e) { } // not gonna happen
560 return null;
561 }
562
563 static public InputStream createInput(File file) {
564 if (file == null) {
565 throw new IllegalArgumentException("File passed to createInput() was null");
566 }
567 try {
568 InputStream input = new FileInputStream(file);
569 if (file.getName().toLowerCase().endsWith(".gz")) {
570 return new GZIPInputStream(input);
571 }
572 return input;
573
574 } catch (IOException e) {
575 System.err.println("Could not createInput() for " + file);
576 e.printStackTrace();
577 return null;
578 }
579 }
580
581 /**
582 * Returns a path inside the applet folder to save to. Like sketchPath(),
583 * but creates any in-between folders so that things save properly.
584 * <p/>
585 * All saveXxxx() functions use the path to the sketch folder, rather than
586 * its data folder. Once exported, the data folder will be found inside the
587 * jar file of the exported application or applet. In this case, it's not
588 * possible to save data into the jar file, because it will often be running
589 * from a server, or marked in-use if running from a local file system.
590 * With this in mind, saving to the data path doesn't make sense anyway.
591 * If you know you're running locally, and want to save to the data folder,
592 * use <TT>saveXxxx("data/blah.dat")</TT>.
593 */
594 public String savePath(String where) {
595 if (where == null) return null;
596 String filename = sketchPath(where);
597 createPath(filename);
598 return filename;
599 }
600
601
602 /**
603 * Identical to savePath(), but returns a File object.
604 */
605 public File saveFile(String where) {
606 return new File(savePath(where));
607 }
608
609 /**
610 * Similar to createInput() (formerly openStream), this creates a Java
611 * OutputStream for a given filename or path. The file will be created in
612 * the sketch folder, or in the same folder as an exported application.
613 * <p/>
614 * If the path does not exist, intermediate folders will be created. If an
615 * exception occurs, it will be printed to the console, and null will be
616 * returned.
617 * <p/>
618 * Future releases may also add support for handling HTTP POST via this
619 * method (for better symmetry with createInput), however that's maybe a
620 * little too clever (and then we'd have to add the same features to the
621 * other file functions like createWriter). Who you callin' bloated?
622 */
623 public OutputStream createOutput(String filename) {
624 return createOutput(saveFile(filename));
625 }
626
627
628 static public OutputStream createOutput(File file) {
629 try {
630 createPath(file); // make sure the path exists
631 FileOutputStream fos = new FileOutputStream(file);
632 if (file.getName().toLowerCase().endsWith(".gz")) {
633 return new GZIPOutputStream(fos);
634 }
635 return fos;
636
637 } catch (IOException e) {
638 e.printStackTrace();
639 }
640 return null;
641 }
642
643 /**
644 * Prepend the sketch folder path to the filename (or path) that is
645 * passed in. External libraries should use this function to save to
646 * the sketch folder.
647 * <p/>
648 * Note that when running as an applet inside a web browser,
649 * the sketchPath will be set to null, because security restrictions
650 * prevent applets from accessing that information.
651 * <p/>
652 * This will also cause an error if the sketch is not inited properly,
653 * meaning that init() was never called on the PApplet when hosted
654 * my some other main() or by other code. For proper use of init(),
655 * see the examples in the main description text for PApplet.
656 */
657 public String sketchPath(String where) {
658 if (sketchPath == null) {
659 return where;
660 // throw new RuntimeException("The applet was not inited properly, " +
661 // "or security restrictions prevented " +
662 // "it from determining its path.");
663 }
664 // isAbsolute() could throw an access exception, but so will writing
665 // to the local disk using the sketch path, so this is safe here.
666 // for 0120, added a try/catch anyways.
667 try {
668 if (new File(where).isAbsolute()) return where;
669 } catch (Exception e) { }
670
671 return sketchPath + File.separator + where;
672 }
673
674 /**
675 * Takes a path and creates any in-between folders if they don't
676 * already exist. Useful when trying to save to a subfolder that
677 * may not actually exist.
678 */
679 static public void createPath(String path) {
680 createPath(new File(path));
681 }
682
683
684 static public void createPath(File file) {
685 try {
686 String parent = file.getParent();
687 if (parent != null) {
688 File unit = new File(parent);
689 if (!unit.exists()) unit.mkdirs();
690 }
691 } catch (SecurityException se) {
692 System.err.println("You don't have permissions to create " +
693 file.getAbsolutePath());
694 }
695 }
696
697
698 }