-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCppBuild.java
More file actions
4161 lines (3877 loc) · 199 KB
/
Copy pathCppBuild.java
File metadata and controls
4161 lines (3877 loc) · 199 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package processing.mode.cpp;
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.regex.*;
import processing.app.RunnerListener;
import processing.app.Sketch;
public class CppBuild {
private final Sketch sketch;
private final CppMode mode;
final File buildDir;
private final File runtimeDir;
public int headerLineCount = 0;
private static final Pattern ERR_LINE = Pattern.compile(
"(?:Sketch_run\\.cpp|sketch\\.pde):(\\d+):\\d+:\\s+error:");
private static final Pattern FUNC_DEF = Pattern.compile(
"^[ \\t]*(void|float|int|double|bool|char|long|color|auto|PVector|PImage\\s*\\*?|std::string)" +
"\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\(([^)]*)\\)\\s*\\{",
Pattern.MULTILINE);
private static final Set<String> LIFECYCLE = new HashSet<>(Arrays.asList(
"setup", "draw", "settings",
"mousePressed", "mouseReleased", "mouseClicked",
"mouseMoved", "mouseDragged", "mouseWheel",
"keyPressed", "keyReleased", "keyTyped",
"windowMoved", "windowResized"));
private static final String[] RESERVED = {
"rand", "time", "exit", "abs", "min", "max", "log", "exp", "pow"
};
// Processing.h defines these class/struct names in namespace Processing.
// If the user also defines them, we skip the user's version to avoid
// "redefinition" errors -- the engine's definition takes precedence.
private static final java.util.Set<String> RESERVED_TYPES = java.util.Set.of(
"Array", "ArrayList", "IntList", "FloatList", "StringList",
"PVector", "PImage", "PGraphics", "PShape", "PFont", "PShader",
"Table", "TableRow", "XML", "JSONValue", "color",
"IntDict", "FloatDict", "StringDict",
"BufferedReader", "PrintWriter"
);
public CppBuild(Sketch sketch, CppMode mode) {
this.sketch = sketch;
this.mode = mode;
this.buildDir = sketch.makeTempFolder();
this.runtimeDir = mode != null ? mode.getRuntimeDir() : null;
}
private void showGppDialog(String html, String btn, String url,
RunnerListener listener) throws Exception {
Object[] opts = { btn, "Cancel" };
int ch = javax.swing.JOptionPane.showOptionDialog(null,
new javax.swing.JLabel(html), "C++ Compiler Not Found",
javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.ERROR_MESSAGE, null, opts, opts[0]);
if (ch == 0) {
try { java.awt.Desktop.getDesktop().browse(new java.net.URI(url)); }
catch (Exception ignored) {}
}
listener.statusError("g++ not found â see dialog for install instructions");
throw new Exception("g++ not found");
}
private void autoInstallWindows(RunnerListener listener) {
String script =
"$ErrorActionPreference = 'Stop'\n"
+ "Write-Host '=== C++ Mode Auto-Installer ==='\n"
+ "Write-Host ''\n"
+ "$msys2Dirs = @('C:\\msys64','C:\\msys2','C:\\tools\\msys64',"
+ "\"$env:USERPROFILE\\msys64\",\"$env:LOCALAPPDATA\\msys64\")\n"
+ "$pacman = $null\n"
+ "foreach ($dir in $msys2Dirs) {\n"
+ " $p = \"$dir\\usr\\bin\\pacman.exe\"\n"
+ " if (Test-Path $p) { $pacman = $p; Write-Host \"Found MSYS2 at $dir\"; break }\n"
+ "}\n"
+ "if (-not $pacman) {\n"
+ " $inPath = Get-Command pacman -ErrorAction SilentlyContinue\n"
+ " if ($inPath) { $pacman = $inPath.Source; Write-Host \"Found pacman on PATH\" }\n"
+ "}\n"
+ "if (-not $pacman) {\n"
+ " Write-Host 'Downloading MSYS2 installer (this may take a minute)...'\n"
+ " $url = 'https://github.com/msys2/msys2-installer/releases/download/nightly-x86_64/msys2-x86_64-latest.exe'\n"
+ " $dest = \"$env:TEMP\\msys2-installer.exe\"\n"
+ " $wc = New-Object System.Net.WebClient\n"
+ " $wc.add_DownloadProgressChanged({\n"
+ " param($s,$e)\n"
+ " $pct = $e.ProgressPercentage\n"
+ " $bar = '#' * [int]($pct/2)\n"
+ " $empty = '-' * (50 - [int]($pct/2))\n"
+ " Write-Host -NoNewline \"\r [$bar$empty] $pct% \"\n"
+ " })\n"
+ " $done = $false\n"
+ " $wc.add_DownloadFileCompleted({ $done = $true })\n"
+ " $wc.DownloadFileAsync([uri]$url, $dest)\n"
+ " while (-not $done) { Start-Sleep -Milliseconds 100 }\n"
+ " Write-Host ''\n"
+ " Write-Host 'Running MSYS2 installer...'\n"
+ " Start-Process -Wait $dest -ArgumentList 'install','--confirm-command','--accept-messages','--root','C:/msys64'\n"
+ " $pacman = 'C:\\msys64\\usr\\bin\\pacman.exe'\n"
+ " Write-Host 'MSYS2 installed.'\n"
+ "}\n"
+ "Write-Host ''\n"
+ "Write-Host 'Installing g++, GLFW, GLEW...'\n"
+ "& $pacman -S --noconfirm --needed '--overwrite=*' mingw-w64-x86_64-gcc mingw-w64-x86_64-glfw mingw-w64-x86_64-glew\n"
+ "Write-Host 'Adding MSYS2 to system PATH...'\n"
+ "$mingwBin = 'C:\\msys64\\mingw64\\bin'\n"
+ "$currentPath = [Environment]::GetEnvironmentVariable('PATH','Machine')\n"
+ "if ($currentPath -notlike \"*$mingwBin*\") {\n"
+ " [Environment]::SetEnvironmentVariable('PATH', \"$mingwBin;$currentPath\", 'Machine')\n"
+ " Write-Host 'Added to system PATH.'\n"
+ "} else { Write-Host 'Already in PATH.' }\n"
+ "Write-Host ''\n"
+ "Write-Host '============================================'\n"
+ "Write-Host 'Installation complete!'\n"
+ "Write-Host 'Please restart Processing4 to use C++ Mode.'\n"
+ "Write-Host '============================================'\n"
+ "Read-Host 'Press Enter to close'\n";
try {
java.io.File tmp = java.io.File.createTempFile("cpp_install_", ".ps1");
tmp.deleteOnExit();
try (java.io.PrintWriter pw = new java.io.PrintWriter(tmp)) { pw.print(script); }
listener.statusNotice("Launching installer...");
new Thread(() -> {
try {
// Run as admin so PATH can be updated system-wide
ProcessBuilder pb2 = new ProcessBuilder(
"powershell.exe", "-ExecutionPolicy", "Bypass",
"-Command",
"Start-Process powershell -Verb RunAs -ArgumentList "
+ "'-ExecutionPolicy Bypass -NoExit -File \"" + tmp.getAbsolutePath().replace("\\", "\\\\") + "\"'");
pb2.start();
javax.swing.JOptionPane.showMessageDialog(null,
new javax.swing.JLabel(
"<html><b>Installer launched!</b><br><br>"
+ "A PowerShell window is installing g++, GLFW, and GLEW.<br><br>"
+ "When it says <b>Installation complete!</b>:<br>"
+ " 1. Close the installer window<br>"
+ " 2. <b>Restart Processing4</b></html>"),
"Installing...", javax.swing.JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e2) { listener.statusError("Error: "+e2.getMessage()); }
}).start();
} catch (Exception e) { listener.statusError("Error: "+e.getMessage()); }
}
private void autoInstallLinux(String[] pmCmd, RunnerListener listener) {
// Build a shell script that runs the package manager with sudo
// and opens in a visible terminal so the user can enter their password
String cmdStr = "sudo " + String.join(" ", pmCmd);
// Try common terminal emulators
String[] terminals = {
"x-terminal-emulator", "gnome-terminal", "konsole",
"xfce4-terminal", "mate-terminal", "xterm", "alacritty",
"kitty", "tilix", "terminator"
};
new Thread(() -> {
try {
// Write a small shell script
java.io.File tmp = java.io.File.createTempFile("cpp_install_", ".sh");
tmp.deleteOnExit();
tmp.setExecutable(true);
try (java.io.PrintWriter pw = new java.io.PrintWriter(tmp)) {
pw.println("#!/bin/bash");
pw.println("echo '=== C++ Mode Auto-Installer ==='");
pw.println("echo ''");
pw.println("echo 'Installing g++, GLFW, GLEW...'");
pw.println(cmdStr);
pw.println("echo ''");
pw.println("echo '============================================'");
pw.println("echo 'Done! Please restart Processing4.'");
pw.println("echo '============================================'");
pw.println("read -p 'Press Enter to close...'");
}
boolean launched = false;
for (String term : terminals) {
try {
Process which = Runtime.getRuntime().exec(new String[]{"which", term});
if (which.waitFor() != 0) continue;
ProcessBuilder pb2;
if (term.equals("gnome-terminal")) {
pb2 = new ProcessBuilder(term, "--", "bash", tmp.getAbsolutePath());
} else if (term.equals("konsole")) {
pb2 = new ProcessBuilder(term, "-e", "bash", tmp.getAbsolutePath());
} else if (term.equals("kitty") || term.equals("alacritty")) {
pb2 = new ProcessBuilder(term, "-e", "bash", tmp.getAbsolutePath());
} else {
pb2 = new ProcessBuilder(term, "-e", "bash " + tmp.getAbsolutePath());
}
pb2.start();
launched = true;
break;
} catch (Exception ignored) {}
}
if (!launched) {
// Fallback: try pkexec (graphical sudo) without terminal
try {
new ProcessBuilder("pkexec", "bash", tmp.getAbsolutePath()).start();
launched = true;
} catch (Exception ignored) {}
}
if (launched) {
javax.swing.JOptionPane.showMessageDialog(null,
new javax.swing.JLabel(
"<html><b>Installer launched!</b><br><br>"
+ "A terminal window is installing g++, GLFW, and GLEW.<br>"
+ "You may need to enter your password.<br><br>"
+ "When it says <b>Done!</b>:<br>"
+ " 1. Close the terminal<br>"
+ " 2. <b>Restart Processing4</b></html>"),
"Installing...", javax.swing.JOptionPane.INFORMATION_MESSAGE);
} else {
javax.swing.JOptionPane.showMessageDialog(null,
new javax.swing.JLabel(
"<html><b>Could not launch terminal.</b><br><br>"
+ "Please run manually:<br>"
+ " <code>" + cmdStr + "</code><br><br>"
+ "Then restart Processing4.</html>"),
"Manual Install Required", javax.swing.JOptionPane.WARNING_MESSAGE);
}
} catch (Exception e) { listener.statusError("Error: " + e.getMessage()); }
}).start();
}
private void checkGppAvailable(RunnerListener listener) throws Exception {
String os = System.getProperty("os.name").toLowerCase();
boolean isWin = os.contains("win");
boolean isMac = os.contains("mac");
if (isWin) {
for (String p : new String[]{
"C:\\msys64\\mingw64\\bin\\g++.exe",
"C:\\msys2\\mingw64\\bin\\g++.exe",
System.getProperty("user.home") + "\\msys64\\mingw64\\bin\\g++.exe",
"C:\\msys64\\ucrt64\\bin\\g++.exe"})
if (new File(p).exists()) return;
try { if (Runtime.getRuntime().exec(new String[]{"g++","--version"}).waitFor()==0) return; }
catch (Exception ignored) {}
// Try the guided installer first. If it succeeds, we're done. If the
// user cancels, InstallWizard throws CancelledByUser, which stops
// the build entirely instead of falling through. Only a genuine
// wizard failure (not a cancel) falls through to the dialog below.
if (InstallWizard.run(listener)) return;
Object[] opts = { "Install Automatically", "Download MSYS2", "Cancel" };
int ch = javax.swing.JOptionPane.showOptionDialog(null,
new javax.swing.JLabel(
"<html><b>g++ (C++ compiler) not found.</b><br><br>"
+ "C++ Mode requires MSYS2 with g++, GLFW, and GLEW.<br><br>"
+ "<b>Auto-Install (recommended):</b><br>"
+ " Click <b>Auto-Install</b> to install everything automatically.<br><br>"
+ "<b>Manual:</b><br>"
+ " 1. Install MSYS2 from https://www.msys2.org<br>"
+ " 2. Open <b>MSYS2 MinGW 64-bit</b> terminal<br>"
+ " 3. Run:<br>"
+ " <code>pacman -S mingw-w64-x86_64-gcc"
+ " mingw-w64-x86_64-glfw mingw-w64-x86_64-glew</code><br>"
+ " 4. Restart Processing</html>"),
"C++ Compiler Not Found",
javax.swing.JOptionPane.YES_NO_CANCEL_OPTION,
javax.swing.JOptionPane.ERROR_MESSAGE,
null, opts, opts[0]);
if (ch == 0) { autoInstallWindows(listener); return; }
else if (ch == 1) {
try { java.awt.Desktop.getDesktop().browse(new java.net.URI("https://www.msys2.org")); }
catch (Exception ignored) {}
}
listener.statusError("g++ not found â install MSYS2 to use C++ Mode");
throw new Exception("g++ not found");
} else {
try { if (Runtime.getRuntime().exec(new String[]{"g++","--version"}).waitFor()==0) return; }
catch (Exception ignored) {}
if (isMac) {
// Try the guided installer first (Xcode Command Line Tools, then
// GLFW/GLEW via Homebrew if present). A cancel throws and stops
// the build; only a genuine failure falls through to the dialog.
if (InstallWizard.run(listener)) return;
showGppDialog(
"<html><b>g++ not found.</b><br><br>"
+ "Install via Homebrew:<br>"
+ " <code>brew install gcc glfw glew</code><br><br>"
+ "Click Download Homebrew if not installed.</html>",
"Download Homebrew", "https://brew.sh", listener);
} else {
// Try the guided installer first. A cancel throws and stops the
// build; only a genuine failure falls through to the dialog below.
if (InstallWizard.run(listener)) return;
// Detect package manager and offer auto-install
String[] aptPkgs = {"g++", "libglfw3-dev", "libglew-dev"};
String[] pacmanPkgs = {"gcc", "glfw-x11", "glew"};
String[] dnfPkgs = {"gcc-c++", "glfw-devel", "glew-devel"};
String[] zypperPkgs = {"gcc-c++", "glfw-devel", "glew-devel"};
String[] emergePkgs = {"media-libs/glfw", "media-libs/glew"};
String[] nixPkgs = {"gcc", "glfw", "glew"};
String pm = null;
String[] pmCmd = null;
String pmName = null;
// Detect package manager
java.util.LinkedHashMap<String,String[]> managers = new java.util.LinkedHashMap<>();
managers.put("apt-get", new String[]{"apt-get","install","-y","g++","libglfw3-dev","libglew-dev"});
managers.put("apt", new String[]{"apt","install","-y","g++","libglfw3-dev","libglew-dev"});
managers.put("pacman", new String[]{"pacman","-S","--noconfirm","gcc","glfw-x11","glew"});
managers.put("dnf", new String[]{"dnf","install","-y","gcc-c++","glfw-devel","glew-devel"});
managers.put("yum", new String[]{"yum","install","-y","gcc-c++","glfw-devel","glew-devel"});
managers.put("zypper", new String[]{"zypper","install","-y","gcc-c++","glfw-devel","glew-devel"});
managers.put("emerge", new String[]{"emerge","media-libs/glfw","media-libs/glew","sys-devel/gcc"});
managers.put("nix-env", new String[]{"nix-env","-iA","nixpkgs.gcc","nixpkgs.glfw","nixpkgs.glew"});
managers.put("brew", new String[]{"brew","install","gcc","glfw","glew"});
for (java.util.Map.Entry<String,String[]> e : managers.entrySet()) {
try {
Process p2 = Runtime.getRuntime().exec(new String[]{"which", e.getKey()});
if (p2.waitFor() == 0) { pm = e.getKey(); pmCmd = e.getValue(); pmName = e.getKey(); break; }
} catch (Exception ignored) {}
}
String installLine = pm != null
? "Detected: <b>" + pm + "</b><br><br>"
+ "Will run:<br> <code>sudo " + String.join(" ", pmCmd) + "</code>"
: "Could not detect package manager.<br>Install manually and restart Processing.";
Object[] opts = pm != null
? new Object[]{"Install Automatically", "More Info", "Cancel"}
: new Object[]{"More Info", "Cancel"};
int ch = javax.swing.JOptionPane.showOptionDialog(null,
new javax.swing.JLabel(
"<html><b>g++ (C++ compiler) not found.</b><br><br>"
+ installLine + "<br><br>"
+ "<b>Manual install:</b><br>"
+ " <b>apt/apt-get</b> (Ubuntu, Debian, Pop!_OS, Mint):<br>"
+ " <code>sudo apt install g++ libglfw3-dev libglew-dev</code><br>"
+ " <b>pacman</b> (Arch, Manjaro, EndeavourOS):<br>"
+ " <code>sudo pacman -S gcc glfw-x11 glew</code><br>"
+ " <b>dnf/yum</b> (Fedora, RHEL, CentOS):<br>"
+ " <code>sudo dnf install gcc-c++ glfw-devel glew-devel</code><br>"
+ " <b>zypper</b> (openSUSE):<br>"
+ " <code>sudo zypper install gcc-c++ glfw-devel glew-devel</code><br>"
+ " <b>emerge</b> (Gentoo):<br>"
+ " <code>sudo emerge media-libs/glfw media-libs/glew</code><br>"
+ " <b>brew</b> (macOS/Linuxbrew):<br>"
+ " <code>brew install gcc glfw glew</code></html>"),
"C++ Compiler Not Found",
javax.swing.JOptionPane.YES_NO_CANCEL_OPTION,
javax.swing.JOptionPane.ERROR_MESSAGE,
null, opts, opts[0]);
if (pm != null && ch == 0) {
autoInstallLinux(pmCmd, listener);
return;
} else if ((pm != null && ch == 1) || (pm == null && ch == 0)) {
try { java.awt.Desktop.getDesktop().browse(new java.net.URI("https://gcc.gnu.org/install/")); }
catch (Exception ignored) {}
}
listener.statusError("g++ not found â install with your package manager");
throw new Exception("g++ not found");
}
}
}
public File compile(RunnerListener listener) throws Exception {
// Check g++ is available before doing anything else
checkGppAvailable(listener);
File sketchSrc = writeSketch(listener);
boolean isWindows = System.getProperty("os.name").toLowerCase().contains("win");
boolean isMac = System.getProperty("os.name").toLowerCase().contains("mac");
String ext = isWindows ? ".exe" : "";
File binary = new File(buildDir, sketch.getName() + ext);
String gpp = findGpp(isWindows);
List<String> cmd = buildCommand(gpp, sketchSrc, binary, isWindows, isMac);
listener.statusNotice("$ " + String.join(" ", cmd));
// Only print the full compile command when debug mode is actually on
// (i.e. the DEBUG file already caused buildCommand() to add
// -DPROCESSING_DEBUG above) -- this is itself a debugging aid, so it
// follows the same toggle as everything else PDEBUG-related, instead
// of always printing regardless of the DEBUG file's contents.
if (cmd.contains("-DPROCESSING_DEBUG")) {
System.err.println("=== FULL COMPILE COMMAND ===");
System.err.println(String.join(" ", cmd));
}
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true);
pb.directory(buildDir);
// Pass sketch folder so Processing.cpp can find data/ assets
pb.environment().put("PROCESSING_SKETCH_PATH", sketch.getFolder().getAbsolutePath());
Process proc = pb.start();
StringBuilder fullOutput = new StringBuilder();
int firstErrLine = -1;
try (BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getInputStream()))) {
String line;
while ((line = br.readLine()) != null) {
fullOutput.append(line).append("\n");
if (firstErrLine < 0) {
Matcher m = ERR_LINE.matcher(line);
if (m.find()) {
try { firstErrLine = Integer.parseInt(m.group(1)); }
catch (NumberFormatException ignored) {}
}
}
if (line.contains("error:") || line.contains("warning:")) {
for (String w : wordWrap(line, 120)) System.err.println(w);
} else if (!line.isBlank()) {
for (String w : wordWrap(line, 120)) System.out.println(w);
}
}
}
int exitCode = proc.waitFor();
if (exitCode != 0) {
if (firstErrLine > 0 && listener instanceof CppEditor) {
final int el = Math.max(1, firstErrLine - headerLineCount);
javax.swing.SwingUtilities.invokeLater(() ->
((CppEditor) listener).highlightErrorLine(el));
}
listener.statusError("Build failed â see console for errors.");
throw new Exception(fullOutput.toString());
}
// Copy default.ttf to sketch folder so the binary finds it at runtime
File font = new File(runtimeDir, "default.ttf");
if (font.exists()) {
File dest = new File(sketch.getFolder(), "default.ttf");
if (!dest.exists())
java.nio.file.Files.copy(font.toPath(), dest.toPath());
}
listener.statusNotice("Built: " + binary.getName());
// Check for required native libraries on all platforms
checkNativeLibs(listener, binary);
return binary;
}
private boolean commandExists(String cmd) {
try {
Process p = Runtime.getRuntime().exec(new String[]{ cmd, "--version" });
return p.waitFor() == 0;
} catch (Exception e) { return false; }
}
private void checkNativeLibs(RunnerListener listener, File binary) throws Exception {
String os = System.getProperty("os.name").toLowerCase();
boolean win = os.contains("win");
boolean mac = os.contains("mac");
if (win) {
checkWindowsDLLs(listener, binary);
} else if (mac) {
checkMacLibs(listener);
} else {
checkLinuxLibs(listener);
}
}
// ââ Windows ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
private boolean windowsLibsNowPresent(java.util.List<String> searchDirs, String[] required) {
outer:
for (String dll : required) {
for (String dir : searchDirs)
if (new File(dir, dll).exists()) continue outer;
return false;
}
return true;
}
private void checkWindowsDLLs(RunnerListener listener, File binary) throws Exception {
String[] required = { "glfw3.dll", "glew32.dll" };
java.util.List<String> searchDirs = new java.util.ArrayList<>();
searchDirs.add(binary.getParent());
searchDirs.add("C:\\msys64\\mingw64\\bin");
searchDirs.add("C:\\msys2\\mingw64\\bin");
String path = System.getenv("PATH");
if (path != null) for (String p : path.split(";")) searchDirs.add(p);
java.util.List<String> missing = new java.util.ArrayList<>();
outer:
for (String dll : required) {
for (String dir : searchDirs)
if (new File(dir, dll).exists()) continue outer;
missing.add(dll);
}
if (missing.isEmpty()) return;
// Try the guided installer first.
if (InstallWizard.run(listener)) {
if (windowsLibsNowPresent(searchDirs, required)) return;
}
int choice = javax.swing.JOptionPane.showConfirmDialog(null,
"Missing libraries: " + String.join(", ", missing) + "\n\n" +
"C++ Mode requires GLFW and GLEW to run sketches.\n" +
"Click OK to install them automatically via MSYS2.",
"Missing Libraries", javax.swing.JOptionPane.OK_CANCEL_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE);
if (choice != javax.swing.JOptionPane.OK_OPTION) return;
// Find MSYS2 pacman
String pacman = null;
for (String p : new String[]{
"C:\\msys64\\usr\\bin\\pacman.exe",
"C:\\msys2\\usr\\bin\\pacman.exe"})
if (new File(p).exists()) { pacman = p; break; }
if (pacman == null) {
try { java.awt.Desktop.getDesktop().browse(new java.net.URI("https://www.msys2.org")); }
catch (Exception ignored) {}
javax.swing.JOptionPane.showMessageDialog(null,
"MSYS2 not found. Please install it from https://www.msys2.org\n\n" +
"Then open MSYS2 MinGW 64-bit and run:\n" +
" pacman -S mingw-w64-x86_64-glfw mingw-w64-x86_64-glew\n\n" +
"Then restart Processing.",
"Install MSYS2", javax.swing.JOptionPane.INFORMATION_MESSAGE);
return;
}
final String finalPacman = pacman;
new Thread(() -> {
try {
listener.statusNotice("Installing GLFW and GLEW via MSYS2...");
ProcessBuilder pb = new ProcessBuilder(finalPacman, "-S", "--noconfirm",
"mingw-w64-x86_64-glfw", "mingw-w64-x86_64-glew");
pb.redirectErrorStream(true);
Process p = pb.start();
try (java.io.BufferedReader br = new java.io.BufferedReader(
new java.io.InputStreamReader(p.getInputStream()))) {
String line; while ((line = br.readLine()) != null) System.out.println(line);
}
if (p.waitFor() == 0) {
// Copy DLLs next to binary
for (String dll : new String[]{ "glfw3.dll","glew32.dll",
"libgcc_s_seh-1.dll","libstdc++-6.dll","libwinpthread-1.dll" }) {
for (String dir : new String[]{
"C:\\msys64\\mingw64\\bin","C:\\msys2\\mingw64\\bin"}) {
File src = new File(dir, dll);
if (src.exists()) {
try { java.nio.file.Files.copy(src.toPath(),
new File(binary.getParent(), dll).toPath(),
java.nio.file.StandardCopyOption.REPLACE_EXISTING); }
catch (Exception ignored) {}
break;
}
}
}
listener.statusNotice("Libraries installed â you can now run your sketch.");
javax.swing.JOptionPane.showMessageDialog(null,
"GLFW and GLEW installed successfully!\nYou can now run your sketch.",
"Done", javax.swing.JOptionPane.INFORMATION_MESSAGE);
} else {
listener.statusError("Installation failed â try manually in MSYS2 MinGW 64-bit terminal.");
}
} catch (Exception e) { listener.statusError("Install error: " + e.getMessage()); }
}).start();
}
// ââ macOS ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
private void checkMacLibs(RunnerListener listener) throws Exception {
// Check for glfw and glew via pkg-config or known Homebrew paths
boolean glfwOk = new File("/opt/homebrew/lib/libglfw.dylib").exists()
|| new File("/usr/local/lib/libglfw.dylib").exists()
|| commandExists("pkg-config glfw3");
boolean glewOk = new File("/opt/homebrew/lib/libGLEW.dylib").exists()
|| new File("/usr/local/lib/libGLEW.dylib").exists()
|| commandExists("pkg-config glew");
if (glfwOk && glewOk) return;
java.util.List<String> missing = new java.util.ArrayList<>();
if (!glfwOk) missing.add("glfw");
if (!glewOk) missing.add("glew");
// Try the guided installer first.
if (InstallWizard.run(listener)) {
boolean glfwNow = new File("/opt/homebrew/lib/libglfw.dylib").exists()
|| new File("/usr/local/lib/libglfw.dylib").exists()
|| commandExists("pkg-config glfw3");
boolean glewNow = new File("/opt/homebrew/lib/libGLEW.dylib").exists()
|| new File("/usr/local/lib/libGLEW.dylib").exists()
|| commandExists("pkg-config glew");
if (glfwNow && glewNow) return;
}
int choice = javax.swing.JOptionPane.showConfirmDialog(null,
"Missing libraries: " + String.join(", ", missing) + "\n\n" +
"C++ Mode requires GLFW and GLEW to run sketches.\n" +
"Click OK to install them via Homebrew.",
"Missing Libraries", javax.swing.JOptionPane.OK_CANCEL_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE);
if (choice != javax.swing.JOptionPane.OK_OPTION) return;
// Check if brew is available
if (!commandExists("brew")) {
try { java.awt.Desktop.getDesktop().browse(new java.net.URI("https://brew.sh")); }
catch (Exception ignored) {}
javax.swing.JOptionPane.showMessageDialog(null,
"Homebrew not found. Please install it from https://brew.sh\n\n" +
"Then run:\n brew install glfw glew\n\nThen restart Processing.",
"Install Homebrew", javax.swing.JOptionPane.INFORMATION_MESSAGE);
return;
}
new Thread(() -> {
try {
listener.statusNotice("Installing GLFW and GLEW via Homebrew...");
ProcessBuilder pb = new ProcessBuilder("brew", "install", "glfw", "glew");
pb.redirectErrorStream(true);
Process p = pb.start();
try (java.io.BufferedReader br = new java.io.BufferedReader(
new java.io.InputStreamReader(p.getInputStream()))) {
String line; while ((line = br.readLine()) != null) System.out.println(line);
}
if (p.waitFor() == 0) {
listener.statusNotice("Libraries installed â you can now run your sketch.");
javax.swing.JOptionPane.showMessageDialog(null,
"GLFW and GLEW installed successfully!\nYou can now run your sketch.",
"Done", javax.swing.JOptionPane.INFORMATION_MESSAGE);
} else {
listener.statusError("Installation failed â try: brew install glfw glew");
}
} catch (Exception e) { listener.statusError("Install error: " + e.getMessage()); }
}).start();
}
// ââ Linux ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
private void checkLinuxLibs(RunnerListener listener) throws Exception {
boolean glfwOk = new File("/usr/lib/libglfw.so").exists()
|| new File("/usr/lib/x86_64-linux-gnu/libglfw.so").exists()
|| new File("/usr/lib/x86_64-linux-gnu/libglfw.so.3").exists()
|| commandExists("pkg-config glfw3");
boolean glewOk = new File("/usr/lib/libGLEW.so").exists()
|| new File("/usr/lib/x86_64-linux-gnu/libGLEW.so").exists()
|| commandExists("pkg-config glew");
if (glfwOk && glewOk) return;
// Try the guided installer first.
if (InstallWizard.run(listener)) {
boolean glfwNow = new File("/usr/lib/libglfw.so").exists()
|| new File("/usr/lib/x86_64-linux-gnu/libglfw.so").exists()
|| new File("/usr/lib/x86_64-linux-gnu/libglfw.so.3").exists()
|| commandExists("pkg-config glfw3");
boolean glewNow = new File("/usr/lib/libGLEW.so").exists()
|| new File("/usr/lib/x86_64-linux-gnu/libGLEW.so").exists()
|| commandExists("pkg-config glew");
if (glfwNow && glewNow) return;
}
java.util.List<String> missing = new java.util.ArrayList<>();
if (!glfwOk) missing.add("libglfw3-dev");
if (!glewOk) missing.add("libglew-dev");
// Detect package manager
String installCmd = detectLinuxInstallCmd(missing);
int choice = javax.swing.JOptionPane.showConfirmDialog(null,
"Missing libraries: " + String.join(", ", missing) + "\n\n" +
"C++ Mode requires GLFW and GLEW to run sketches.\n" +
"Click OK to install them automatically.",
"Missing Libraries", javax.swing.JOptionPane.OK_CANCEL_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE);
if (choice != javax.swing.JOptionPane.OK_OPTION) return;
if (installCmd == null) {
javax.swing.JOptionPane.showMessageDialog(null,
"<html><b>Unknown Linux distribution.</b><br><br>"
+ "Please install g++, GLFW, and GLEW manually<br>"
+ "using your distro's package manager,<br>"
+ "then restart Processing.</html>",
"Missing Libraries", javax.swing.JOptionPane.WARNING_MESSAGE);
return;
}
final String cmd = installCmd;
new Thread(() -> {
try {
listener.statusNotice("Installing libraries...");
// Write install script to temp file and run it in a terminal
java.io.File tmp = java.io.File.createTempFile("cpp_install_", ".sh");
tmp.deleteOnExit();
try (java.io.PrintWriter pw = new java.io.PrintWriter(tmp)) {
pw.println("#!/bin/bash");
pw.println("echo '==============================='");
pw.println("echo ' C++ Mode Library Installer '");
pw.println("echo '==============================='");
pw.println("echo ''");
pw.println("show_progress() {");
pw.println(" local pid=$1 msg=$2 i=0");
pw.println(" local spin='|/-\\\\'");
pw.println(" while kill -0 $pid 2>/dev/null; do");
pw.println(" i=$(( (i+1) % 4 ))");
pw.println(" printf '\\r [%s] %s' \"${spin:$i:1}\" \"$msg\"");
pw.println(" sleep 0.15");
pw.println(" done");
pw.println(" printf '\\r [OK] %s\\n' \"$msg\"");
pw.println("}");
pw.println("echo 'Installing g++, GLFW, GLEW...'"); pw.println("echo 'Installing g++, GLFW, GLEW...'");
pw.println("echo ''");
pw.println(cmd + " &");
pw.println("PKG_PID=$!");
pw.println("spinner $PKG_PID 'Installing packages...'");
pw.println("wait $PKG_PID");
pw.println("EXIT=$?");
pw.println("echo ''");
pw.println("if [ $EXIT -eq 0 ]; then");
pw.println(" echo '==============================='");
pw.println(" echo ' Installation complete!'");
pw.println(" echo ' Please restart Processing.'");
pw.println(" echo '==============================='");
pw.println("else");
pw.println(" echo 'Installation failed. Try running manually:'");
pw.println(" echo '" + cmd + "'");
pw.println("fi");
pw.println("read -p 'Press Enter to close...'");
}
tmp.setExecutable(true);
// Try to open in a terminal emulator
String[] terminals = {
"x-terminal-emulator", "gnome-terminal", "konsole",
"xfce4-terminal", "xterm", "alacritty", "kitty"
};
boolean launched = false;
for (String term : terminals) {
if (!cmdExists(term)) continue;
String[] termCmd;
if (term.equals("gnome-terminal"))
termCmd = new String[]{ term, "--", "bash", tmp.getAbsolutePath() };
else if (term.equals("alacritty") || term.equals("kitty"))
termCmd = new String[]{ term, "-e", "bash", tmp.getAbsolutePath() };
else
termCmd = new String[]{ term, "-e", "bash " + tmp.getAbsolutePath() };
try {
new ProcessBuilder(termCmd).start();
launched = true;
break;
} catch (Exception ignored) {}
}
if (!launched) {
// Fallback: run directly
ProcessBuilder pb = new ProcessBuilder("bash", tmp.getAbsolutePath());
pb.redirectErrorStream(true);
Process p = pb.start();
try (java.io.BufferedReader br = new java.io.BufferedReader(
new java.io.InputStreamReader(p.getInputStream()))) {
String line; while ((line = br.readLine()) != null) System.out.println(line);
}
p.waitFor();
}
listener.statusNotice("Installer launched â restart Processing when done.");
javax.swing.JOptionPane.showMessageDialog(null,
"<html><b>Installer launched!</b><br><br>"
+ "When it says <b>Installation complete!</b>:<br>"
+ " 1. Close the terminal<br>"
+ " 2. <b>Restart Processing</b></html>",
"Installing...", javax.swing.JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) { listener.statusError("Install error: " + e.getMessage()); }
}).start();
}
private boolean cmdExists(String cmd) {
try {
String os = System.getProperty("os.name","").toLowerCase();
ProcessBuilder pb;
if (os.contains("win")) {
// On Windows use 'where' instead of 'which'
pb = new ProcessBuilder("where", cmd);
} else {
pb = new ProcessBuilder("which", cmd);
}
pb.redirectErrorStream(true);
return pb.start().waitFor() == 0;
} catch (Exception e) { return false; }
}
private boolean compilerExists(ExportTarget t) {
String os = System.getProperty("os.name","").toLowerCase();
boolean isWin = os.contains("win");
// macOS cross-compile needs osxcross - not bundled
if (t == ExportTarget.MACOS_X64 || t == ExportTarget.MACOS_ARM64)
return cmdExists(t.compiler);
// Linux targets: need Linux/Mac to cross-compile
if (!t.isWindows) {
if (t == ExportTarget.MACOS_X64 || t == ExportTarget.MACOS_ARM64)
return cmdExists(t.compiler);
if (isWin) return false; // not available on Windows - need Linux machine
if (muslToolchainInstalled(t)) return true;
return cmdExists(t.compiler);
}
// Windows target
if (isWin) {
String[] msysPaths = {
"C:\\msys64\\mingw64\\bin\\g++.exe",
"C:\\msys2\\mingw64\\bin\\g++.exe",
System.getProperty("user.home") + "\\msys64\\mingw64\\bin\\g++.exe"
};
for (String p : msysPaths)
if (new java.io.File(p).exists()) return true;
return cmdExists("g++");
}
return cmdExists(t.compiler);
}
private String detectLinuxInstallCmd(java.util.List<String> aptPkgs) {
if (cmdExists("apt-get"))
return "pkexec apt-get install -y libglfw3-dev libglew-dev g++";
if (cmdExists("pacman"))
return "pkexec bash -c 'pacman -S --noconfirm --overwrite=* gcc glfw-x11 glew"
+ " || pacman -S --noconfirm --overwrite=* gcc glfw glew'";
if (cmdExists("dnf"))
return "pkexec dnf install -y gcc-c++ glfw-devel glew-devel";
if (cmdExists("zypper"))
return "pkexec zypper install -y gcc-c++ libglfw3 libglfw-devel glew-devel";
if (cmdExists("emerge"))
return "pkexec emerge --ask=n media-libs/glfw media-libs/glew sys-devel/gcc";
if (cmdExists("xbps-install"))
return "pkexec xbps-install -y gcc glfw-devel glew";
if (cmdExists("apk"))
return "pkexec apk add --no-cache gcc g++ glfw-dev glew-dev";
return null;
}
// Lifecycle/event method names, shared between the AST pipeline's
// override-marking and dependency-exclusion rules. Same list as the
// original's local "lifecycleMethods" array, just hoisted to a
// constant since both LifecycleRewriter and DependencyHoister need it.
private static final java.util.Set<String> LIFECYCLE_METHOD_NAMES = java.util.Set.of(
"setup", "draw", "settings",
"mousePressed", "mouseReleased", "mouseClicked",
"mouseMoved", "mouseDragged", "mouseWheel",
"keyPressed", "keyReleased", "keyTyped",
"windowMoved", "windowResized"
);
/**
* Replaces the original writeSketch()'s regex/character-walking
* hoisting and rewriting passes (hoistClassesOnly, removeHoistedClasses,
* classifyTopLevelDecls-based array/variable/function hoisting,
* rewriteAsSketchMethods, the inline enumScope/constexprScope
* extraction, and the inline _PSketch-injection regex chain) with the
* real AST pipeline built and tested in tools/cpp-parser/ (see
* DECISION_two_parser_implementations.md for the full history,
* including two real bugs found and fixed via PipelineCompositionTest
* before this was wired in here).
*
* Every literal scaffolding string this method emits (the #include
* lines, the using-declarations, the _PSketch struct body, the
* free-function forwarding, and main()) is UNCHANGED from the
* original -- none of that depends on parsing user code at all, so
* none of it needed to change. Only the user-code transformation
* steps (hoisting, lifecycle override-marking, pointer-defaulting)
* were replaced.
*
* NOT YET PORTED to this pipeline, carried over as known gaps from
* DECISION_two_parser_implementations.md: constexpr/static_assert/
* type-alias "using" extraction (zero corpus evidence for any of
* these -- see EnumScopeExtractor's javadoc), and the most-vexing-
* parse direct-init rewrite for any case OTHER than the one this
* pipeline's CodeGen already emits as brace-init unconditionally
* (CodeGen renders ALL direct-init as braces now, which is a
* strictly safer superset of the original's behavior, not a gap).
*/
/**
* Wraps Parser.parse(code) with the same error-reporting convention
* already used by checkForUnsupportedJavaArraySyntax (detailed message
* to System.err, short message to listener.statusError(), then a
* RuntimeException) instead of letting a ParseException propagate as
* a raw, unhandled exception all the way up through writeSketch() ->
* compile() -> CppMode.handleLaunch() -> whatever the outer Processing
* IDE framework happens to do with an arbitrary uncaught exception
* from a Mode plugin.
*
* Found this gap while investigating a deliberately-left-unfixed
* parser limitation (non-type template arguments, e.g.
* "std::array<int, 5>") and confirming it fails GRACEFULLY (a clean
* ParseException with an accurate line/column, not a crash or a
* silent misparse) rather than just assuming so -- tracing where that
* exception actually goes surfaced that NOTHING in this Mode's own
* code catches it at all, at any layer, before this fix. Whether
* processing4's own core Editor/Sketch-running machinery already
* catches an arbitrary uncaught exception from a Mode's
* handleLaunch() with a reasonable user-facing error isn't something
* this project's available source could confirm either way -- this
* fix makes the Mode's OWN behavior strictly better regardless of
* what that outer layer does, by ensuring the sketch author sees a
* clean, accurate "your code has a syntax error at line N, column M"
* message via the IDE's own status bar specifically, the same way
* they already do for E0004 (Java array syntax) and would for any
* other Mode-level validation error.
*
* Throws AlreadyReportedException (not a plain RuntimeException) so
* the writeSketch() safety-net wrapper added alongside this (see its
* own javadoc) can tell "this was already cleanly reported to the
* user via listener.statusError()" apart from "this is a genuinely
* unexpected crash the user hasn't seen a message for yet" -- without
* relying on fragile message-string matching to make that distinction.
*/
private static final class AlreadyReportedException extends RuntimeException {
AlreadyReportedException(String message) { super(message); }
}
private static String stripRawStringLiterals(String code) {
StringBuilder out = new StringBuilder();
int i = 0;
while (i < code.length()) {
if (i + 1 < code.length() && code.charAt(i) == 'R' && code.charAt(i+1) == '"') {
int j = i + 2;
StringBuilder delim = new StringBuilder();
while (j < code.length() && code.charAt(j) != '(' && code.charAt(j) != '"') {
delim.append(code.charAt(j++));
}
if (j < code.length() && code.charAt(j) == '(') {
String closer = ")" + delim.toString() + "\"";
int end = code.indexOf(closer, j + 1);
if (end >= 0) {
out.append("\"<raw>\"");
i = end + closer.length();
continue;
}
}
}
out.append(code.charAt(i++));
}
return out.toString();
}
private CompilationUnit parseOrReportError(String code, RunnerListener listener) {
try {
return Parser.parse(code);
} catch (ParseException e) {
System.err.println(e.getMessage());
listener.statusError("Syntax error: " + e.getMessage());
throw new AlreadyReportedException("Syntax error: " + e.getMessage());
}
}
/**
* Safety-net wrapper around writeSketchImpl(). The parse step itself
* is already guarded (see parseOrReportError() and
* checkForUnsupportedJavaArraySyntax(), both throwing
* AlreadyReportedException after cleanly reporting via
* listener.statusError()) -- but writeSketchImpl() also makes roughly
* twenty further calls into the AST pipeline (ClassHoister,
* PSketchInjector, ArrayHoister, DependencyHoister, ForwardDeclGenerator,
* LifecycleRewriter, EnumScopeExtractor, CodeGen), none of which were
* individually guarded. RealHeaderStressTest/RealCorpusStressTest
* confirmed zero crashes across the full 131-file real example
* corpus, both against a hand-built stub and the real engine headers
* -- but "zero crashes on every sketch tested so far" isn't the same
* guarantee as "zero crashes on any sketch anyone ever writes," and an
* unexpected exception from deep in the pipeline (a NullPointerException,
* ClassCastException, or anything else not yet seen) would otherwise
* propagate exactly as raw and unhandled as the ParseException gap
* this same investigation found and fixed.
*
* Catches any RuntimeException that ISN'T already an
* AlreadyReportedException (avoiding a double report for an error the
* person has already seen via statusError()) and reports it the same
* way, with a generic but still useful message plus the real
* exception detail in the console -- strictly better than an
* unhandled crash, even though "an internal error occurred" is
* necessarily less specific than a real syntax-error message can be.
*/
private File writeSketch(RunnerListener listener) throws IOException {
try {
return writeSketchImpl(listener);
} catch (AlreadyReportedException e) {
throw e; // already reported via listener.statusError() at the point it was thrown -- just propagate
} catch (RuntimeException e) {
System.err.println("Internal CppMode error while preparing the sketch for compilation:");
e.printStackTrace();