-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCppBuild.java
More file actions
4658 lines (4363 loc) · 224 KB
/
Copy pathCppBuild.java
File metadata and controls
4658 lines (4363 loc) · 224 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.
// Processing API names that are dangerous as user variable names (Problem 5.2/6.1)
// Processing API names confirmed to cause crashes/errors when used as variable names
// Kept minimal to avoid false positives -- only add names with confirmed crash reports
private static final java.util.Set<String> PROCESSING_API_NAMES = java.util.Set.of(
"color" // confirmed: Processing::color typedef causes operator++ crash
);
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"
);
/** No-arg constructor for allocate()-based CLI usage -- fields set via reflection. */
@SuppressWarnings("unused")
private CppBuild() {
this.sketch = null;
this.mode = null;
this.buildDir = null;
this.runtimeDir = null;
}
/**
* Result of the pre-AST string-transform pipeline.
* code: transformed sketch text with __has_include blocks removed.
* hasIncludeBlocks: extracted blocks to emit at file scope, keyed by original line index.
*/
public static final class PreparedCode {
public final String code;
public final java.util.Map<Integer, String> hasIncludeBlocks;
public PreparedCode(String code, java.util.Map<Integer, String> hasIncludeBlocks) {
this.code = code;
this.hasIncludeBlocks = hasIncludeBlocks;
}
}
/**
* Single source of truth for the pre-AST string-transform pipeline.
* Used by both writeSketchImpl() and CppCLI.
*/
public static PreparedCode prepareCode(String rawCode) throws Exception {
CppBuild b = new CppBuild();
String code = b.sanitize(rawCode);
code = b.removeUserIncludes(code);
code = code.replaceAll("(\\bfinal_suspend\\s*\\([^)]*\\))(\\s*\\{)", "$1 noexcept$2");
code = code.replaceAll("(\\binitial_suspend\\s*\\([^)]*\\))(\\s*\\{)", "$1 noexcept$2");
code = code.replaceAll("\\btranslate\\s*\\(\\s*0+\\.?0*f?\\s*,\\s*0+\\.?0*f?\\s*\\)\\s*;", "");
code = code.replaceAll("\\btranslate\\s*\\(\\s*0+\\.?0*f?\\s*,\\s*0+\\.?0*f?\\s*,\\s*0+\\.?0*f?\\s*\\)\\s*;", "");
code = b.stripRawStringLiterals(code);
code = code.replaceAll("(?<=[0-9a-fA-FxXbB])'(?=[0-9a-fA-F])", "");
code = b.javaToC(code);
code = b.stripNamespaceProcessing(code);
// Extract #if __has_include blocks before g++ -E so they survive intact.
String[] rawLines = code.split("\n", -1);
java.util.Map<Integer, String> hasIncludeBlocks = new java.util.LinkedHashMap<>();
{
StringBuilder stripped = new StringBuilder();
int depth = 0; int blockStart = -1; StringBuilder block = new StringBuilder();
for (int li = 0; li < rawLines.length; li++) {
String t = rawLines[li].strip();
boolean isHI = t.startsWith("#if __has_include") || t.startsWith("#elif __has_include");
boolean isIf = !isHI && (t.startsWith("#if ") || t.startsWith("#ifdef ") || t.startsWith("#ifndef "));
boolean isEndif = t.equals("#endif");
if (isHI && depth == 0) {
blockStart = li; block = new StringBuilder();
block.append(rawLines[li]).append("\n"); depth = 1; stripped.append("\n");
} else if (depth > 0) {
if (isHI || isIf) depth++;
block.append(rawLines[li]).append("\n");
if (isEndif) { depth--; if (depth == 0) { hasIncludeBlocks.put(blockStart, block.toString()); blockStart = -1; } }
stripped.append("\n");
} else { stripped.append(rawLines[li]).append("\n"); }
}
code = stripped.toString();
}
code = b.preprocessMacros(code);
return new PreparedCode(code, hasIncludeBlocks);
}
/** Backwards-compatible wrapper. */
public static String translateCode(String code) throws Exception {
return prepareCode(code).code;
}
/**
* Decides where a PreprocessorLine node should be emitted:
* true → file scope (preNs, before namespace Processing)
* false → namespace body (out, inside namespace Processing)
*
* Used by both writeSketchImpl() and CppCLI.runPipeline() to keep
* routing behaviour identical without duplicating the if/else chain.
*/
public static boolean isFileScopePreprocessorLine(PreprocessorLine pl) {
String rt = pl.rawText().trim();
return rt.startsWith("#include")
|| rt.startsWith("#if") || rt.startsWith("#else")
|| rt.startsWith("#elif") || rt.startsWith("#endif")
|| rt.startsWith("#define") || rt.startsWith("#undef")
|| rt.startsWith("#pragma")
|| (rt.startsWith("using ") && !rt.contains("=") && !rt.contains("namespace"));
}
/**
* Result of the shared AST pipeline (steps 1-7 + auto-hoisting).
* Both writeSketchImpl() and CppCLI.runPipeline() run these same steps;
* they differ only in how they assemble the final output from the results.
*/
public static final class AstPipelineResult {
public final EnumScopeExtractor.Result enumResult;
public final ClassHoister.Result classResult;
public final List<TypeDef> finalClasses;
public final ArrayHoister.Result arrayResult;
public final DependencyHoister.Result depResult;
public final List<FunctionDecl> forwardDecls;
public final List<TopLevelItem> autoHoisted;
public final List<TopLevelItem> filteredRest;
public AstPipelineResult(
EnumScopeExtractor.Result enumResult,
ClassHoister.Result classResult,
List<TypeDef> finalClasses,
ArrayHoister.Result arrayResult,
DependencyHoister.Result depResult,
List<FunctionDecl> forwardDecls,
List<TopLevelItem> autoHoisted,
List<TopLevelItem> filteredRest) {
this.enumResult = enumResult;
this.classResult = classResult;
this.finalClasses = finalClasses;
this.arrayResult = arrayResult;
this.depResult = depResult;
this.forwardDecls = forwardDecls;
this.autoHoisted = autoHoisted;
this.filteredRest = filteredRest;
}
}
/**
* Shared AST pipeline: parse → enum extraction → lifecycle rewrite →
* class hoisting → PSketch injection → array hoisting → dependency
* hoisting → forward decls → auto-hoisting.
*
* Both writeSketchImpl() and CppCLI.runPipeline() call this and then
* assemble their own output format from the result.
*/
public static AstPipelineResult runAstPipeline(CompilationUnit cu) {
EnumScopeExtractor.Result enumResult = EnumScopeExtractor.extract(cu.items());
List<TopLevelItem> afterLifecycle = LifecycleRewriter.rewrite(enumResult.rest, LIFECYCLE_METHOD_NAMES);
ClassHoister.Result classResult = ClassHoister.hoist(afterLifecycle);
List<PSketchInjector.Result> injectedClasses = PSketchInjector.injectAll(classResult.hoistedClasses);
List<TypeDef> finalClasses = injectedClasses.stream().map(PSketchInjector.Result::typeDef).toList();
ArrayHoister.Result arrayResult = ArrayHoister.hoist(classResult.rest);
DependencyHoister.Result depResult = DependencyHoister.hoist(arrayResult.rest, finalClasses, LIFECYCLE_METHOD_NAMES);
List<FunctionDecl> forwardDecls = ForwardDeclGenerator.generate(depResult.hoistedFunctions);
// Auto-hoist items that cannot legally be struct members.
List<TopLevelItem> autoHoisted = new ArrayList<>();
List<TopLevelItem> filteredRest = new ArrayList<>();
for (TopLevelItem item : depResult.rest) {
if (item instanceof VariableDecl vd
&& vd.type() instanceof NamedType nt
&& (nt.baseName().equals("auto") || nt.baseName().startsWith("std::function"))) {
autoHoisted.add(item);
} else if (item instanceof FunctionDecl fd
&& fd.name().startsWith("operator")
&& fd.params().size() >= 2) {
autoHoisted.add(item);
} else if (item instanceof FunctionDecl fdce && fdce.isConstexpr()) {
autoHoisted.add(item);
} else if (item instanceof VariableDecl vdq && vdq.name().contains("::")) {
autoHoisted.add(item);
} else if (item instanceof FunctionDecl fdoc && fdoc.name().contains("::")) {
autoHoisted.add(item);
} else {
filteredRest.add(item);
}
}
return new AstPipelineResult(enumResult, classResult, finalClasses,
arrayResult, depResult, forwardDecls, autoHoisted, filteredRest);
}
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) {
// Delegate to InstallWizard which handles portable gcc download in-app.
// GLFW and GLEW are bundled in libs/windows-x64/ -- no MSYS2 needed.
try {
InstallWizard.run(listener);
} catch (InstallWizard.CancelledByUser ignored) {
} catch (Exception e) {
listener.statusError("Auto-install failed: " + 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[]{
// Portable gcc (downloaded by InstallWizard, no MSYS2 needed)
System.getenv("APPDATA") + "\\CppMode\\gcc\\mingw64\\bin\\g++.exe",
"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) {}
// No g++ found anywhere -- run the install wizard.
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 needs g++ to compile sketches.<br>"
+ "<b>Auto-Install (recommended):</b><br>"
+ " Click <b>Auto-Install</b> to download g++ automatically.<br><br>"
+ "<b>Manual:</b><br>"
+ " Install MSYS2 from https://www.msys2.org and run:<br>"
+ " <code>pacman -S mingw-w64-x86_64-gcc</code><br>"
+ " Then 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 {
if (isMac) {
// On macOS, check both compiler AND libraries before deciding to skip
// the wizard. g++ may be present but GLFW/GLEW headers missing.
boolean macGpp = false;
try { macGpp = Runtime.getRuntime().exec(new String[]{"g++","--version"}).waitFor()==0; }
catch (Exception ignored) {}
String macArch = System.getProperty("os.arch","").contains("aarch64") ? "arm64" : "x64";
File macLibsDir = (runtimeDir != null)
? new File(runtimeDir.getParentFile(), "libs/macos")
: new File(System.getProperty("user.home") +
"/Library/Application Support/Processing/modes/CppMode/libs/macos");
boolean hasBundledGlfw = new File(macLibsDir, "libglfw.3.dylib").exists();
boolean hasBundledGlew = new File(macLibsDir, "libGLEW.dylib").exists();
boolean macGlfw = hasBundledGlfw
|| new File("/opt/homebrew/include/GLFW/glfw3.h").exists()
|| new File("/usr/local/include/GLFW/glfw3.h").exists();
boolean macGlew = hasBundledGlew
|| new File("/opt/homebrew/include/GL/glew.h").exists()
|| new File("/usr/local/include/GL/glew.h").exists();
if (macGpp && macGlfw && macGlew) return; // everything present, skip wizard
// 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);
int gppVer = gppMajorVersion(gpp);
if (gppVer > 0 && gppVer < 7) {
listener.statusError("g++ " + gppVer + " is too old — need GCC 7+ for C++17.");
boolean isWin2 = isWindows;
final int[] choice = {-1};
try {
javax.swing.SwingUtilities.invokeAndWait(() -> {
Object[] opts = {"Update g++", "Cancel"};
choice[0] = javax.swing.JOptionPane.showOptionDialog(null,
"<html><b>g++ " + gppVer + " is too old.</b><br><br>"
+ "CppMode requires GCC 7 or newer for C++17 support.<br>"
+ "Your version: <b>GCC " + gppVer + "</b><br><br>"
+ (isWin2 ? "Click <b>Update g++</b> to download the latest portable GCC."
: "Please update g++ using your system package manager.") + "</html>",
"g++ Too Old",
javax.swing.JOptionPane.DEFAULT_OPTION,
javax.swing.JOptionPane.ERROR_MESSAGE,
null, opts, opts[0]);
});
} catch (Exception ignored2) {}
if (choice[0] == 0) {
if (isWin2) {
try { InstallWizard.run(listener); } catch (Exception ignored3) {}
} else {
// Linux/macOS: open the install wizard which handles package managers
try { InstallWizard.run(listener); } catch (Exception ignored3) {}
}
}
throw new Exception("g++ too old: " + gppVer);
}
String stdOverride = (listener instanceof CppEditor ce) ? ce.getSelectedCppStd() : null;
List<String> cmd = buildCommand(gpp, sketchSrc, binary, isWindows, isMac, stdOverride);
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:") || line.contains("note:") || line.contains("Processing::")) {
for (String w : wordWrap(rewriteGccError(line), 120)) System.err.println(w);
} else if (!line.isBlank()) {
for (String w : wordWrap(rewriteGccError(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());
}
// Copy bundled macOS dylibs to sketch folder so the binary finds them at runtime.
if (isMac) {
String macArch2 = System.getProperty("os.arch","").contains("aarch64") ? "arm64" : "x64";
File macLibsDir2 = new File(runtimeDir.getParentFile(), "libs/macos");
if (macLibsDir2.exists()) {
for (File dylib : macLibsDir2.listFiles((d,n) -> n.endsWith(".dylib"))) {
File destDylib = new File(sketch.getFolder(), dylib.getName());
try { java.nio.file.Files.copy(dylib.toPath(), destDylib.toPath(),
java.nio.file.StandardCopyOption.REPLACE_EXISTING); }
catch (Exception ignored) {}
}
}
}
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[] allDlls = { "glfw3.dll", "glew32.dll", "libgcc_s_seh-1.dll", "libssp-0.dll", "libwinpthread-1.dll" };
String[] required = { "glfw3.dll", "glew32.dll" };
// Bundled DLLs are in libs/windows-x64 -- copy them next to the binary
File bundledDir = new File(runtimeDir.getParentFile(), "libs/windows-x64");
File binaryDir = new File(binary.getParent());
binaryDir.mkdirs();
// DLL search dirs: WinLibs portable gcc first (exact match for compiler used),
// then bundled, then MSYS2
java.util.List<File> dllSources = new java.util.ArrayList<>();
File portableGccBin = InstallWizard.getPortableGccDir();
if (portableGccBin.exists()) dllSources.add(portableGccBin);
dllSources.add(bundledDir);
for (String msysDir : new String[]{"C:\\msys64\\mingw64\\bin","C:\\msys2\\mingw64\\bin"})
dllSources.add(new File(msysDir));
for (String dll : allDlls) {
for (File sourceDir : dllSources) {
File src2 = new File(sourceDir, dll);
if (!src2.exists()) continue;
// Copy next to binary
try { java.nio.file.Files.copy(src2.toPath(), new File(binaryDir, dll).toPath(),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
} catch (Exception ignored) {}
try { java.nio.file.Files.copy(src2.toPath(), new File(sketch.getFolder(), dll).toPath(),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
} catch (Exception ignored) {}
break;
}
}
// If all required DLLs exist in bundledDir, we're good -- they were
// either copied successfully or will be found via the bundled path.
boolean allBundled = true;
for (String dll : required)
if (!new File(bundledDir, dll).exists()) { allBundled = false; break; }
if (allBundled) return;
// Bundled dir missing some DLLs -- report error
java.util.List<String> missing = new java.util.ArrayList<>();
for (String dll : required)
if (!new File(bundledDir, dll).exists()) missing.add(dll);
if (missing.isEmpty()) return;
// DLLs missing from bundle -- this should not happen in a correct install
listener.statusError("Missing DLLs: " + String.join(", ", missing) +
" -- try reinstalling CppMode from https://github.com/processing-cpp/processing.cpp");
throw new Exception("Missing DLLs: " + missing);
}
private void checkMacLibs(RunnerListener listener) throws Exception {
// Check bundled dylibs first -- if present, no Homebrew needed
String macArch = System.getProperty("os.arch","").contains("aarch64") ? "arm64" : "x64";
File macLibsDir = new File(runtimeDir.getParentFile(), "libs/macos");
boolean hasBundled = new File(macLibsDir, "libglfw.3.dylib").exists()
&& new File(macLibsDir, "libGLEW.dylib").exists();
if (hasBundled) return;
// Fall back to Homebrew check
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.
public 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