Repository navigation
Expand file tree
/
Copy pathNotepad.java
More file actions
3883 lines (3342 loc) · 154 KB
/
Copy pathNotepad.java
File metadata and controls
3883 lines (3342 loc) · 154 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 nn;
import javax.swing.tree.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.event.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.List;
import java.util.function.Consumer;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.stream.Stream;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
import javax.swing.undo.UndoableEdit;
public class Notepad {
public enum Theme {
DRACULA, ONE_DARK, NORD, LIGHT, HIGH_CONTRAST
}
private JFrame frame;
private JTabbedPane tabbedPane;
private JTextArea outputArea;
private JTextArea inputArea;
private JPanel consolePanel;
private JSplitPane mainSplitPane;
private JSplitPane workspaceSplitPane;
private boolean projectExplorerVisible = true;
private int projectExplorerWidth = 240;
private JPanel projectExplorerPanel;
private JPanel projectExplorerHeader;
private JTree projectTree;
private DefaultTreeModel projectTreeModel;
private JLabel projectTitleLabel;
private File projectRoot;
private JSplitPane consoleSplitPane;
private JToolBar toolBar;
private StatusBar statusBar;
// ——— Explorer enhancements ———
private JTextField explorerFilterField;
private DefaultMutableTreeNode unfilteredRoot;
private javax.swing.Timer explorerFilterTimer;
private JMenuBar menuBar;
private JMenu fileMenu, editMenu, formatMenu, languageMenu, themeMenu, viewMenu, runMenu;
private JCheckBoxMenuItem wordWrapItem;
private JMenu fontMenu, fontSizeMenu;
private JMenu recentFilesMenu;
private Theme currentTheme = Theme.DRACULA;
private int defaultFontSize = 16;
private String currentFontFamily = "JetBrains Mono";
private List<String> recentFiles = new ArrayList<>();
private static final int MAX_RECENT_FILES = 10;
private static final String TEMPLATE_PATH = "./res/";
private static final String RECENT_FILE = "./recent_files.dat";
private Process currentProcess;
private PrintWriter processInputWriter;
private javax.swing.Timer autoSaveTimer;
// Reused fonts to avoid repeated identical Font allocation across components.
private static final Font UI_FONT = new Font("Segoe UI", Font.PLAIN, 13);
private static final Font UI_FONT_BOLD = new Font("Segoe UI", Font.BOLD, 14);
private static final Font SYMBOL_FONT = new Font("Segoe UI Symbol", Font.PLAIN, 16);
private static final Font CONSOLE_FONT = new Font("JetBrains Mono", Font.PLAIN, 13);
private static final Font STATUS_FONT = new Font("Segoe UI", Font.PLAIN, 12);
private static final Font STATUS_FONT_ITALIC = new Font("Segoe UI", Font.ITALIC, 11);
// ——— Color palettes ———
private static final Color[] DRACULA = {
new Color(40, 42, 54), new Color(68, 71, 90), new Color(98, 114, 164),
new Color(248, 248, 242), new Color(80, 250, 123), new Color(255, 85, 85),
new Color(255, 184, 108), new Color(189, 147, 249), new Color(139, 233, 253),
new Color(255, 121, 198), new Color(241, 250, 140), new Color(69, 71, 90),
};
private static final Color[] ONE_DARK = {
new Color(40, 44, 52), new Color(50, 55, 65), new Color(92, 99, 112),
new Color(171, 178, 191), new Color(152, 195, 121), new Color(224, 108, 117),
new Color(209, 154, 102), new Color(198, 120, 221), new Color(86, 182, 194),
new Color(229, 192, 123), new Color(97, 175, 239), new Color(44, 48, 56),
};
private static final Color[] NORD = {
new Color(46, 52, 64), new Color(59, 66, 82), new Color(76, 86, 106),
new Color(216, 222, 233), new Color(163, 190, 140), new Color(191, 97, 106),
new Color(208, 135, 112), new Color(180, 142, 173), new Color(136, 192, 208),
new Color(235, 203, 139), new Color(129, 161, 193), new Color(48, 54, 66),
};
private static final Color[] LIGHT = {
new Color(250, 250, 250), new Color(240, 240, 240), new Color(200, 200, 200),
new Color(30, 30, 30), new Color(0, 150, 80), new Color(220, 50, 50),
new Color(220, 120, 0), new Color(150, 50, 200), new Color(0, 150, 200),
new Color(200, 50, 150), new Color(180, 160, 0), new Color(235, 235, 235),
};
private static final Color[] HIGH_CONTRAST = {
Color.BLACK, new Color(20, 20, 20), Color.DARK_GRAY, Color.WHITE,
Color.GREEN, Color.RED, Color.ORANGE, Color.MAGENTA, Color.CYAN,
Color.PINK, Color.YELLOW, Color.BLACK,
};
private static class Palette {
Color bg, bgLighter, comment, fg, green, red, orange, purple, cyan, pink, yellow, lineHL;
Palette(Color[] c) {
bg = c[0];
bgLighter = c[1];
comment = c[2];
fg = c[3];
green = c[4];
red = c[5];
orange = c[6];
purple = c[7];
cyan = c[8];
pink = c[9];
yellow = c[10];
lineHL = c[11];
}
}
private Palette pal;
// ———————————————————————————————— CONSTRUCTOR ————————————————————————————————
public Notepad() {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception ignored) {
}
loadRecentFiles();
pal = palette(currentTheme);
createFrame();
createToolBar();
createTabbedEditor();
createConsolePanel();
createProjectExplorer();
createMainSplitPane();
createStatusBar();
createMenuBar();
applyTheme(currentTheme);
loadProjectFolder(new File(System.getProperty("user.dir")));
addNewTab();
startAutoSave();
frame.setVisible(true);
}
private Palette palette(Theme t) {
switch (t) {
case DRACULA:
return new Palette(DRACULA);
case ONE_DARK:
return new Palette(ONE_DARK);
case NORD:
return new Palette(NORD);
case LIGHT:
return new Palette(LIGHT);
case HIGH_CONTRAST:
return new Palette(HIGH_CONTRAST);
default:
return new Palette(DRACULA);
}
}
// ———————————————————————————————— FRAME ————————————————————————————————
private void createFrame() {
frame = new JFrame("pavans-Notepadplusplus");
frame.setSize(1200, 800);
frame.setMinimumSize(new Dimension(800, 500));
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationRelativeTo(null);
try {
Image logo = Toolkit.getDefaultToolkit().getImage("./icons/pavans-notepadplus.ico");
if (logo != null)
frame.setIconImage(logo);
} catch (Exception ignored) {
}
new DropTarget(frame, new DropTargetAdapter() {
public void drop(DropTargetDropEvent e) {
try {
e.acceptDrop(DnDConstants.ACTION_COPY);
@SuppressWarnings("unchecked")
List<File> files = (List<File>) e.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
for (File f : files)
openFileInTab(f.getAbsolutePath());
} catch (Exception ignored) {
}
}
});
// Stop the autosave timer and any running child process cleanly on close
// instead of leaking a live Timer/threads after disposal.
frame.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
if (autoSaveTimer != null)
autoSaveTimer.stop();
stopRunningProcess();
}
});
}
// ———————————————————————————————— TOOLBAR ————————————————————————————————
private void createToolBar() {
toolBar = new JToolBar();
toolBar.setFloatable(false);
toolBar.setBorderPainted(false);
toolBar.setMargin(new Insets(4, 8, 4, 8));
toolBar.setPreferredSize(new Dimension(0, 46));
toolBar.add(toolBtn("☰", "Show/Hide Project Explorer", e -> toggleProjectExplorer()));
toolBar.add(toolBtn("📄", "New (Ctrl+N)", e -> addNewTab()));
toolBar.add(toolBtn("📂", "Open (Ctrl+O)", e -> openFile()));
toolBar.add(toolBtn("💾", "Save (Ctrl+S)", e -> saveCurrentTab(false)));
toolBar.add(toolBtn("💿", "Save As (Ctrl+Shift+S)", e -> saveCurrentTab(true)));
toolBar.add(sep(10));
toolBar.add(toolBtn("⚙", "Compile (Ctrl+Shift+B)", e -> compileJavaCode()));
toolBar.add(toolBtn("▶", "Run (F5)", e -> runCurrentFile()));
toolBar.add(toolBtn("⏹", "Stop (Shift+F5)", e -> stopRunningProcess()));
toolBar.add(sep(10));
toolBar.add(toolBtn("🔍", "Find / Replace (Ctrl+F)", e -> showFindReplace()));
toolBar.add(toolBtn("➕", "Zoom In (Ctrl++)", e -> zoomIn()));
toolBar.add(toolBtn("➖", "Zoom Out (Ctrl+-)", e -> zoomOut()));
frame.add(toolBar, BorderLayout.NORTH);
}
private JButton toolBtn(String text, String tip, ActionListener a) {
JButton b = new JButton(text);
b.setToolTipText(tip);
b.setFont(SYMBOL_FONT);
b.setFocusPainted(false);
b.setBorderPainted(false);
b.setContentAreaFilled(false);
b.setForeground(pal.fg);
b.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
b.setPreferredSize(new Dimension(36, 32));
b.setMargin(new Insets(1, 3, 1, 3));
b.addActionListener(a);
b.putClientProperty("nn.hoverable", true);
b.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
b.setContentAreaFilled(true);
b.setBackground(pal.bgLighter);
}
public void mouseExited(MouseEvent e) {
b.setContentAreaFilled(false);
}
});
return b;
}
private Component sep(int w) {
JLabel l = new JLabel();
l.setPreferredSize(new Dimension(w, 0));
return l;
}
// ———————————————————————————————— TABBED EDITOR
// ————————————————————————————————
private void createTabbedEditor() {
tabbedPane = new JTabbedPane();
tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
tabbedPane.setFont(UI_FONT);
tabbedPane.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isMiddleMouseButton(e)) {
int i = tabbedPane.indexAtLocation(e.getX(), e.getY());
if (i >= 0)
closeTab(i);
}
}
});
tabbedPane.addChangeListener(e -> {
updateFrameTitle();
statusBar.refresh();
revealCurrentFileInExplorer();
});
}
private void addNewTab() {
DocumentTab tab = new DocumentTab();
int i = tabbedPane.getTabCount();
tabbedPane.addTab("Untitled", tab.scrollPane);
tabbedPane.setTabComponentAt(i, tabHeader("Untitled"));
tabbedPane.setSelectedIndex(i);
storeTabRef(i, tab);
tab.textArea.requestFocusInWindow();
tab.applyEditorColors(pal);
updateFrameTitle();
}
private JPanel tabHeader(String title) {
JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT, 4, 0));
p.setOpaque(true);
p.setBackground(pal.bg);
JLabel l = new JLabel(title);
l.setFont(UI_FONT);
l.setForeground(pal.fg);
JLabel x = new JLabel("\u00D7");
x.setFont(UI_FONT);
x.setPreferredSize(new Dimension(20, 20));
x.setHorizontalAlignment(SwingConstants.CENTER);
x.setForeground(pal.fg);
x.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
x.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
x.setOpaque(true);
x.setBackground(pal.bgLighter);
}
public void mouseExited(MouseEvent e) {
x.setOpaque(false);
}
public void mouseClicked(MouseEvent e) {
int idx = tabbedPane.indexOfTabComponent(p);
if (idx >= 0)
closeTab(idx);
}
});
p.add(l);
p.add(x);
return p;
}
private void closeTab(int idx) {
DocumentTab tab = tabAt(idx);
if (tab.dirty) {
int r = JOptionPane.showConfirmDialog(frame,
"Save changes to " + tab.fileName + "?", "Unsaved Changes",
JOptionPane.YES_NO_CANCEL_OPTION);
if (r == JOptionPane.CANCEL_OPTION)
return;
if (r == JOptionPane.YES_OPTION)
saveCurrentTab(false);
}
// Release timers/listeners before dropping the reference so a pending
// highlight Timer doesn't keep firing against a detached component.
tab.dispose();
tabbedPane.remove(idx);
if (tabbedPane.getTabCount() == 0)
addNewTab();
updateFrameTitle();
}
// ———————————————————————————————— DocumentTab ————————————————————————————————
class DocumentTab {
JTextPane textArea;
LineNumberComponent lineNumbers;
JScrollPane scrollPane;
String filePath;
String fileName = "Untitled";
String defaultExtension = "";
boolean dirty;
UndoManager undoManager;
private DocumentListener syntaxHighlightListener;
private javax.swing.Timer highlightTimer;
private int lastCaretLine = -1;
private DefaultHighlighter.DefaultHighlightPainter lineHighlightPainter;
private static final int HIGHLIGHT_SIZE_LIMIT = 60_000;
DocumentTab() {
undoManager = new UndoManager();
undoManager.setLimit(200);
textArea = new JTextPane();
textArea.setFont(new Font(currentFontFamily, Font.PLAIN, defaultFontSize));
textArea.setMargin(new Insets(12, 12, 12, 12));
TabSet tabs = new TabSet(new TabStop[] { new TabStop(32, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE) });
StyledDocument doc = textArea.getStyledDocument();
SimpleAttributeSet attrs = new SimpleAttributeSet();
StyleConstants.setTabSet(attrs, tabs);
doc.setParagraphAttributes(0, doc.getLength(), attrs, false);
/*
* Store only real text changes.
*
* Syntax highlighting uses setCharacterAttributes(), which generates
* DocumentEvent.EventType.CHANGE edits. Those style changes must not
* consume the user's 100 undo entries.
*/
doc.addUndoableEditListener(event -> {
UndoableEdit edit = event.getEdit();
if (edit instanceof AbstractDocument.DefaultDocumentEvent) {
AbstractDocument.DefaultDocumentEvent documentEvent = (AbstractDocument.DefaultDocumentEvent) edit;
if (documentEvent.getType() == DocumentEvent.EventType.CHANGE) {
return;
}
}
undoManager.addEdit(edit);
});
installUndoRedoKeyBindings();
lineNumbers = new LineNumberComponent(textArea);
JPanel editorPanel = new JPanel(new BorderLayout());
editorPanel.add(lineNumbers, BorderLayout.WEST);
editorPanel.add(textArea, BorderLayout.CENTER);
editorPanel.setBackground(pal.bg);
scrollPane = new JScrollPane(editorPanel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.getViewport().setBackground(pal.bg);
scrollPane.setBorder(null);
scrollPane.getVerticalScrollBar().setUnitIncrement(16);
// Debounced, size-capped syntax highlighting: one restyle pass per
// pause in typing instead of restarting a timer on every keystroke
// without a real bound on cost.
syntaxHighlightListener = new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
markDirty();
scheduleHighlight();
}
public void removeUpdate(DocumentEvent e) {
markDirty();
scheduleHighlight();
}
public void changedUpdate(DocumentEvent e) {
/* style-only change */ }
};
doc.addDocumentListener(syntaxHighlightListener);
textArea.addCaretListener(e -> {
statusBar.refresh();
highlightCurrentLine();
// Only repaint the gutter when the caret actually changed line.
try {
int line = getLineOfOffset(textArea, textArea.getCaretPosition());
if (line != lastCaretLine) {
lastCaretLine = line;
lineNumbers.repaint();
}
} catch (BadLocationException ignored) {
}
});
textArea.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "auto-indent");
textArea.getActionMap().put("auto-indent", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
doAutoIndent();
}
});
textArea.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
maybePopup(e);
}
public void mouseReleased(MouseEvent e) {
maybePopup(e);
}
void maybePopup(MouseEvent e) {
if (e.isPopupTrigger())
showPopup(e);
}
});
}
private void installUndoRedoKeyBindings() {
int shortcutMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx();
InputMap inputMap = textArea.getInputMap(JComponent.WHEN_FOCUSED);
ActionMap actionMap = textArea.getActionMap();
inputMap.put(
KeyStroke.getKeyStroke(
KeyEvent.VK_Z,
shortcutMask),
"notepad-undo");
inputMap.put(
KeyStroke.getKeyStroke(
KeyEvent.VK_Y,
shortcutMask),
"notepad-redo");
// Also support Ctrl+Shift+Z as an alternative redo shortcut.
inputMap.put(
KeyStroke.getKeyStroke(
KeyEvent.VK_Z,
shortcutMask | InputEvent.SHIFT_DOWN_MASK),
"notepad-redo");
actionMap.put("notepad-undo", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent event) {
performUndo();
}
});
actionMap.put("notepad-redo", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent event) {
performRedo();
}
});
}
void performUndo() {
try {
if (undoManager.canUndo()) {
undoManager.undo();
}
} catch (CannotUndoException ignored) {
}
textArea.requestFocusInWindow();
}
void performRedo() {
try {
if (undoManager.canRedo()) {
undoManager.redo();
}
} catch (CannotRedoException ignored) {
}
textArea.requestFocusInWindow();
}
private void scheduleHighlight() {
if (highlightTimer != null) {
highlightTimer.stop();
}
highlightTimer = new javax.swing.Timer(400, e -> {
int len = textArea.getDocument().getLength();
if (len > HIGHLIGHT_SIZE_LIMIT) {
return;
}
try {
StyledDocument doc = textArea.getStyledDocument();
doc.removeDocumentListener(syntaxHighlightListener);
try {
JavaSyntaxHighlighter.highlightSyntax(textArea, textArea.getText());
} finally {
doc.addDocumentListener(syntaxHighlightListener);
}
} catch (Exception ex) {
ex.printStackTrace();
}
});
highlightTimer.setRepeats(false);
highlightTimer.start();
}
void showPopup(MouseEvent e) {
JPopupMenu pop = new JPopupMenu();
pop.setBackground(pal.bgLighter);
pop.setForeground(pal.fg);
addItem(pop, "Undo", ev -> performUndo());
addItem(pop, "Redo", ev -> performRedo());
pop.addSeparator();
addItem(pop, "Cut", ev -> textArea.cut());
addItem(pop, "Copy", ev -> textArea.copy());
addItem(pop, "Paste", ev -> textArea.paste());
pop.addSeparator();
addItem(pop, "Select All", ev -> textArea.selectAll());
pop.addSeparator();
addItem(pop, "📂 Reveal in Explorer", ev -> revealCurrentFileInExplorer());
pop.show(textArea, e.getX(), e.getY());
}
void addItem(JPopupMenu m, String n, Consumer<ActionEvent> a) {
JMenuItem i = new JMenuItem(n);
i.setFont(SYMBOL_FONT);
i.setBackground(pal.bgLighter);
i.setForeground(pal.fg);
i.addActionListener(ev -> a.accept(ev));
m.add(i);
}
void doAutoIndent() {
try {
int pos = textArea.getCaretPosition();
int line = getLineOfOffset(textArea, pos);
int start = getLineStartOffset(textArea, line);
String prev = textArea.getText(start, pos - start);
StringBuilder ind = new StringBuilder();
for (int i = 0; i < prev.length(); i++) {
char c = prev.charAt(i);
if (c == ' ' || c == '\t')
ind.append(c);
else
break;
}
String t = prev.trim();
if (t.endsWith("{") || t.endsWith("(") || t.endsWith(":"))
ind.append(" ");
textArea.getDocument().insertString(pos, "\n" + ind.toString(), null);
} catch (BadLocationException ignored) {
}
}
// O(1) dirty tracking instead of hashing the whole document text on
// every keystroke (the previous version called getText().hashCode()
// on the full buffer on every insert/remove — the single biggest
// source of typing lag on non-trivial files).
void markDirty() {
if (!dirty) {
dirty = true;
updateTabTitle();
updateFrameTitle();
}
}
void markClean() {
dirty = false;
updateTabTitle();
updateFrameTitle();
}
void updateTabTitle() {
int idx = tabbedPane.indexOfComponent(scrollPane);
if (idx < 0)
return;
JPanel h = (JPanel) tabbedPane.getTabComponentAt(idx);
if (h != null)
((JLabel) h.getComponent(0)).setText((dirty ? "* " : "") + fileName);
}
void applyEditorColors(Palette p) {
textArea.setBackground(p.bg);
textArea.setForeground(p.fg);
textArea.setCaretColor(p.fg);
textArea.setSelectedTextColor(p.fg);
StyledDocument doc = textArea.getStyledDocument();
Style defaultStyle = doc.getStyle(StyleContext.DEFAULT_STYLE);
StyleConstants.setForeground(defaultStyle, p.fg);
StyleConstants.setBackground(defaultStyle, p.bg);
lineNumbers.bgColor = p.bg;
lineNumbers.fgColor = p.comment;
scrollPane.getViewport().setBackground(p.bg);
if (textArea.getParent() != null)
textArea.getParent().setBackground(p.bg);
// Cache the highlight painter once per theme change instead of
// allocating a new Color/painter on every caret move.
lineHighlightPainter = new DefaultHighlighter.DefaultHighlightPainter(
new Color(p.lineHL.getRed(), p.lineHL.getGreen(), p.lineHL.getBlue(), 80));
highlightCurrentLine();
}
void highlightCurrentLine() {
textArea.getHighlighter().removeAllHighlights();
if (lineHighlightPainter == null)
return;
try {
int pos = textArea.getCaretPosition();
int line = getLineOfOffset(textArea, pos);
int s = getLineStartOffset(textArea, line);
int e = getLineEndOffset(textArea, line);
textArea.getHighlighter().addHighlight(s, e, lineHighlightPainter);
} catch (BadLocationException ignored) {
}
}
void applyFont() {
textArea.setFont(new Font(currentFontFamily, Font.PLAIN, defaultFontSize));
lineNumbers.updateFont();
highlightCurrentLine();
}
void setFilePath(String path) {
this.filePath = path;
this.fileName = new File(path).getName();
updateTabTitle();
updateFrameTitle();
}
// Stop pending timers and detach listeners so a closed tab can be
// garbage collected and doesn't keep doing background work.
void dispose() {
if (highlightTimer != null) {
highlightTimer.stop();
highlightTimer = null;
}
try {
textArea.getStyledDocument().removeDocumentListener(syntaxHighlightListener);
} catch (Exception ignored) {
}
}
}
// ———————————————————————————————— HELPERS ————————————————————————————————
private DocumentTab currentTab() {
int i = tabbedPane.getSelectedIndex();
return i < 0 ? null : tabAt(i);
}
private DocumentTab tabAt(int i) {
return (DocumentTab) ((JScrollPane) tabbedPane.getComponentAt(i)).getClientProperty("tab");
}
private void storeTabRef(int i, DocumentTab t) {
((JScrollPane) tabbedPane.getComponentAt(i)).putClientProperty("tab", t);
}
// ———————————————————————————————— CONSOLE ————————————————————————————————
// ———————————————————————————————— PROJECT EXPLORER
// ————————————————————————————————
private static class FileTreeNode extends DefaultMutableTreeNode {
private final File file;
FileTreeNode(File file) {
super(file);
this.file = file;
}
File getFile() {
return file;
}
@Override
public String toString() {
String name = file.getName();
return name.isEmpty() ? file.getAbsolutePath() : name;
}
}
private void createProjectExplorer() {
// ── Header ──
projectTitleLabel = new JLabel("EXPLORER");
projectTitleLabel.setFont(UI_FONT_BOLD);
JButton openFolderButton = iconBtn("📂", "Open Folder", e -> chooseProjectFolder());
JButton refreshButton = iconBtn("↻", "Refresh", e -> refreshProjectExplorer());
JButton collapseAllButton = iconBtn("▲", "Collapse All", e -> {
for (int r = projectTree.getRowCount() - 1; r > 0; r--)
projectTree.collapseRow(r);
});
JButton expandAllButton = iconBtn("▼", "Expand All", e -> {
for (int r = 0; r < projectTree.getRowCount(); r++)
projectTree.expandRow(r);
});
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 1, 0));
buttonPanel.setOpaque(false);
buttonPanel.add(collapseAllButton);
buttonPanel.add(expandAllButton);
buttonPanel.add(openFolderButton);
buttonPanel.add(refreshButton);
projectExplorerHeader = new JPanel(new BorderLayout());
projectExplorerHeader.setBorder(new EmptyBorder(6, 8, 4, 4));
projectExplorerHeader.add(projectTitleLabel, BorderLayout.CENTER);
projectExplorerHeader.add(buttonPanel, BorderLayout.EAST);
// ── Filter bar ──
explorerFilterField = new JTextField();
explorerFilterField.putClientProperty("nn.filterField", true);
explorerFilterField.setFont(SYMBOL_FONT);
explorerFilterField.setForeground(pal.comment);
explorerFilterField.setBackground(pal.bg);
explorerFilterField.setBorder(new CompoundBorder(
new MatteBorder(0, 0, 1, 0, pal.comment),
new EmptyBorder(4, 8, 4, 8)));
explorerFilterField.setText("🔍 Search files...");
Runnable applyFilter = () -> filterExplorerTree(explorerFilterField.getText());
explorerFilterField.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
if ("Search files...".equals(explorerFilterField.getText())) {
explorerFilterField.setText("");
explorerFilterField.setForeground(pal.fg);
}
}
@Override
public void focusLost(FocusEvent e) {
if (explorerFilterField.getText().isEmpty()) {
explorerFilterField.setForeground(pal.comment);
explorerFilterField.setText("Search files...");
filterExplorerTree("");
}
}
});
explorerFilterField.getDocument().addDocumentListener(new DocumentListener() {
void schedule() {
if (explorerFilterTimer != null)
explorerFilterTimer.stop();
explorerFilterTimer = new javax.swing.Timer(200, ev -> applyFilter.run());
explorerFilterTimer.setRepeats(false);
explorerFilterTimer.start();
}
@Override
public void insertUpdate(DocumentEvent e) { schedule(); }
@Override
public void removeUpdate(DocumentEvent e) { schedule(); }
@Override
public void changedUpdate(DocumentEvent e) { schedule(); }
});
// ── Tree ──
DefaultMutableTreeNode emptyRoot = new DefaultMutableTreeNode("No folder opened");
projectTreeModel = new DefaultTreeModel(emptyRoot);
projectTree = new JTree(projectTreeModel);
projectTree.setRootVisible(true);
projectTree.setShowsRootHandles(true);
projectTree.setRowHeight(24);
projectTree.setFont(UI_FONT);
projectTree.setCellRenderer(new ProjectTreeRenderer());
projectTree.setToggleClickCount(2);
projectTree.getSelectionModel().setSelectionMode(
TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
// Tooltips
projectTree.setToolTipText("");
ToolTipManager.sharedInstance().registerComponent(projectTree);
// Click behavior: single-click toggles directories, double-click opens files, right-click context menu
projectTree.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
TreePath treePath = projectTree.getPathForLocation(e.getX(), e.getY());
if (treePath == null) return;
Object value = treePath.getLastPathComponent();
if (!(value instanceof FileTreeNode)) return;
File file = ((FileTreeNode) value).getFile();
if (SwingUtilities.isRightMouseButton(e)) {
projectTree.setSelectionPath(treePath);
showExplorerContextMenu(e);
} else if (SwingUtilities.isLeftMouseButton(e)) {
if (e.getClickCount() == 1 && file.isDirectory()) {
if (projectTree.isExpanded(treePath)) {
projectTree.collapsePath(treePath);
} else {
projectTree.expandPath(treePath);
}
} else if (e.getClickCount() == 2 && !file.isDirectory()) {
openFileFromExplorer(file);
}
}
}
@Override
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger())
showExplorerContextMenu(e);
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger())
showExplorerContextMenu(e);
}
});
// Keyboard support: F2 rename, Delete delete
projectTree.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), "rename");
projectTree.getActionMap().put("rename", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
TreePath sel = projectTree.getSelectionPath();
if (sel != null && sel.getLastPathComponent() instanceof FileTreeNode ftn)
renameExplorerNode(ftn);
}
});
projectTree.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "delete");
projectTree.getActionMap().put("delete", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
TreePath sel = projectTree.getSelectionPath();
if (sel != null && sel.getLastPathComponent() instanceof FileTreeNode ftn)
deleteExplorerNode(ftn);
}
});
JScrollPane treeScrollPane = new JScrollPane(projectTree);
treeScrollPane.setBorder(null);
treeScrollPane.getVerticalScrollBar().setUnitIncrement(16);
// ── Assemble panel ──
JPanel explorerCenter = new JPanel(new BorderLayout());
explorerCenter.add(explorerFilterField, BorderLayout.NORTH);
explorerCenter.add(treeScrollPane, BorderLayout.CENTER);
projectExplorerPanel = new JPanel(new BorderLayout());
projectExplorerPanel.setMinimumSize(new Dimension(150, 0));
projectExplorerPanel.setPreferredSize(new Dimension(260, 0));
projectExplorerPanel.add(projectExplorerHeader, BorderLayout.NORTH);
projectExplorerPanel.add(explorerCenter, BorderLayout.CENTER);
}
private JButton iconBtn(String text, String tip, ActionListener a) {
JButton b = new JButton(text);
b.setToolTipText(tip);
b.setFont(SYMBOL_FONT);
b.setFocusPainted(false);
b.setBorderPainted(false);
b.setContentAreaFilled(false);
b.setForeground(pal.fg);
b.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
b.setPreferredSize(new Dimension(28, 24));
b.setMargin(new Insets(0, 2, 0, 2));
b.addActionListener(a);
b.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
b.setContentAreaFilled(true);
b.setBackground(pal.bgLighter);
}
public void mouseExited(MouseEvent e) {
b.setContentAreaFilled(false);
}
});
return b;
}
private void chooseProjectFolder() {
JFileChooser fileChooser = new JFileChooser(
projectRoot != null
? projectRoot
: new File(System.getProperty("user.dir")));
fileChooser.setDialogTitle("Open Project Folder");
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setAcceptAllFileFilterUsed(false);
if (fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
loadProjectFolder(fileChooser.getSelectedFile());
}
}
private void loadProjectFolder(File folder) {
if (folder == null || !folder.isDirectory()) {
return;
}
projectRoot = folder;
projectTitleLabel.setText(folder.getName().toUpperCase(Locale.ROOT));
projectTreeModel.setRoot(
new DefaultMutableTreeNode("Loading..."));
new SwingWorker<DefaultMutableTreeNode, Void>() {
@Override
protected DefaultMutableTreeNode doInBackground() {
return buildProjectTree(folder);
}
@Override
protected void done() {
try {
DefaultMutableTreeNode rootNode = get();
unfilteredRoot = rootNode;
projectTreeModel.setRoot(cloneNode(rootNode));
projectTreeModel.reload();
projectTree.expandRow(0);
} catch (Exception e) {
projectTreeModel.setRoot(