-
Notifications
You must be signed in to change notification settings - Fork 0
/
a3.java
executable file
·1701 lines (1493 loc) · 59.7 KB
/
a3.java
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
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.FlavorEvent;
import java.awt.datatransfer.FlavorListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;
import javax.swing.text.JTextComponent;
import javax.swing.text.LayeredHighlighter;
import javax.swing.text.Position;
import javax.swing.text.View;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.undo.UndoManager;
class TextEditorFrame extends JFrame implements ActionListener, ChangeListener, DocumentListener, CaretListener, FlavorListener, UndoableEditListener
{
final private String applicationTitle = "Simple Text Editor";
private JTextPane textPane; // Main editable text area
private JScrollPane textPaneScrollPane; // A scoll pane container
private JMenuBar menuBar;
private JMenu fileMenu;
private JMenuItem newMenuItem;
private JMenuItem openMenuItem;
private JMenuItem saveMenuItem;
private JMenuItem saveAsMenuItem;
private JMenuItem exitMenuItem;
private JMenu editMenu;
private JMenuItem undoMenuItem;
private JMenuItem redoMenuItem;
private JMenuItem cutMenuItem;
private JMenuItem copyMenuItem;
private JMenuItem pasteMenuItem;
private JMenuItem deleteMenuItem;
private JMenuItem selectAllMenuItem;
private JMenu searchMenu;
private JMenuItem quickFindMenuItem;
/*private JMenu viewMenu;
private JMenuItem wordWrapMenuItem;*/
private JMenu highlightingMenu;
private JMenuItem noneMenuItem;
private JMenuItem englishSpellcheckingMenuItem;
private JMenuItem javaSourceCodeMenuItem;
private ButtonGroup highlightingButtonGroup = new ButtonGroup();
private ButtonModel lastHighlightingOption = null;
private MyPopupMenu popupMenu;
private QuickFindPanel quickFindPanel;
private Properties properties = new Properties();
private int frameMaximized = 0;
private int frameLocationX = Integer.MIN_VALUE, frameLocationY = Integer.MIN_VALUE;
private int frameSizeX = -1, frameSizeY = -1;
private HashSet<String> dictionary = new HashSet<String>();
private Vector<String> addedToDictionary = new Vector<String>();
private String textPaneContent = "";
private Tuple<Integer> shouldBeHighlighted = null;
private HashSet<String> javaKeywords = new HashSet<String>(Arrays.asList( "abstract", "assert", "boolean", "break", "byte", "case", "catch", "catch", "char",
"class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "final", "finally", "float", "for", "goto", "if", "implements", "import",
"instanceof", "int", "interface", "long", "native", "new", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super",
"switch", "synchronized", "this", "throw", "throws", "transient", "try", "void", "volatile", "while", "true", "false", "null"));
private UndoManager undoManager = new UndoManager();
private File documentFile = null; // The currently opened file
private boolean documentHasUnsavedChanges;
private File lastDirectory = null; // Keeps track of the last current directory
final private int defaultTabSize = 4; // Legacy: It was used in assignment 2
private class MyPopupMenu extends JPopupMenu implements ActionListener
{
private JMenuItem ignoreAllMenuItem;
private JMenuItem addToDictionaryMenuItem;
private JMenuItem cutPopupMenuItem;
private JMenuItem copyPopupMenuItem;
private JMenuItem pastePopupMenuItem;
private JMenuItem deletePopupMenuItem;
private JMenuItem selectAllPopupMenuItem;
MyPopupMenu(ActionListener listener)
{
super();
ignoreAllMenuItem = new JMenuItem("Ignore All");
ignoreAllMenuItem.setMnemonic('I');
ignoreAllMenuItem.addActionListener(this);
addToDictionaryMenuItem = new JMenuItem("Add to Dictionary");
addToDictionaryMenuItem.setMnemonic('D');
addToDictionaryMenuItem.addActionListener(this);
cutPopupMenuItem = new JMenuItem("Cut");
cutPopupMenuItem.setMnemonic('T');
cutPopupMenuItem.addActionListener(listener);
copyPopupMenuItem = new JMenuItem("Copy");
copyPopupMenuItem.setMnemonic('C');
copyPopupMenuItem.addActionListener(listener);
pastePopupMenuItem = new JMenuItem("Paste");
pastePopupMenuItem.setMnemonic('P');
pastePopupMenuItem.addActionListener(listener);
pastePopupMenuItem.setEnabled(Toolkit.getDefaultToolkit().getSystemClipboard().isDataFlavorAvailable(DataFlavor.plainTextFlavor));
deletePopupMenuItem = new JMenuItem("Delete");
deletePopupMenuItem.setMnemonic('D');
deletePopupMenuItem.addActionListener(listener);
selectAllPopupMenuItem = new JMenuItem("Select All");
selectAllPopupMenuItem.setMnemonic('A');
selectAllPopupMenuItem.addActionListener(listener);
}
public JMenuItem getPastePopupMenuItem() { return pastePopupMenuItem; }
@Override
public void show(Component invoker, int x, int y) {
JPopupMenu popupMenu = new JPopupMenu();
JTextPane textPane = (JTextPane)invoker;
int caretPosition = textPane.viewToModel(new Point(x, y));
if (caretPosition != textPane.getText().length()) {
Tuple<Integer> loc = findIncorrectWord(textPane, caretPosition);
if (loc != null) try
{
String incorrectWord = textPane.getText(loc.getFirst(), loc.getSecond() - loc.getFirst());
incorrectWord = incorrectWord.trim();
Vector<String> suggestions = findCorrections(incorrectWord.toLowerCase());
for (Iterator<String> it = suggestions.iterator(); it.hasNext(); )
{
JMenuItem suggestionMenuItem = new JMenuItem(transferWordCase(incorrectWord, it.next()));
suggestionMenuItem.addActionListener(this);
suggestionMenuItem.setActionCommand(loc.toString());
popupMenu.add(suggestionMenuItem);
}
ignoreAllMenuItem.setActionCommand(incorrectWord.toLowerCase() + " " + loc.toString());
addToDictionaryMenuItem.setActionCommand(incorrectWord.toLowerCase() + " " + loc.toString());
popupMenu.addSeparator();
popupMenu.add(ignoreAllMenuItem);
popupMenu.add(addToDictionaryMenuItem);
popupMenu.addSeparator();
} catch (BadLocationException ble) {}
}
if (textPane.getSelectionStart() != textPane.getSelectionEnd() && caretPosition >= textPane.getSelectionStart() && caretPosition <= textPane.getSelectionEnd())
{
cutPopupMenuItem.setEnabled(true);
copyPopupMenuItem.setEnabled(true);
deletePopupMenuItem.setEnabled(true);
} else {
cutPopupMenuItem.setEnabled(false);
copyPopupMenuItem.setEnabled(false);
deletePopupMenuItem.setEnabled(false);
textPane.setCaretPosition(caretPosition);
}
popupMenu.add(cutPopupMenuItem);
popupMenu.add(copyPopupMenuItem);
popupMenu.add(pastePopupMenuItem);
popupMenu.add(deletePopupMenuItem);
popupMenu.addSeparator();
popupMenu.add(selectAllPopupMenuItem);
popupMenu.show(invoker, x, y);
}
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == ignoreAllMenuItem)
{
String word = ae.getActionCommand().split(" ")[0];
//Tuple<Integer> loc = Tuple.valueOfInteger(ae.getActionCommand().substring(word.length() + 1));
dictionary.add(word);
//removeHighlightAt(loc);
fullCheckSpelling();
}
else if (ae.getSource() == addToDictionaryMenuItem)
{
String word = ae.getActionCommand().split(" ")[0];
//Tuple<Integer> loc = Tuple.valueOfInteger(ae.getActionCommand().substring(word.length() + 1));
dictionary.add(word);
addedToDictionary.add(word);
//removeHighlightAt(loc);
fullCheckSpelling();
}
else
{
String suggestion = ((JMenuItem)ae.getSource()).getText();
Tuple<Integer> loc = Tuple.valueOfInteger(ae.getActionCommand());
try {
textPane.getDocument().remove(loc.getFirst(), loc.getSecond() - loc.getFirst());
textPane.getDocument().insertString(loc.getFirst(), suggestion, null);
} catch (BadLocationException ble) {}
}
}
private Tuple<Integer> findIncorrectWord(JTextPane textPane, int caretPosition)
{
Highlighter.Highlight[] highlights = textPane.getHighlighter().getHighlights();
for (int i = 0; i < highlights.length; i++)
{
Highlighter.Highlight h = highlights[i];
if (h.getPainter() instanceof UnderlineHighlightPainter) {
if (caretPosition >= h.getStartOffset() && caretPosition <= h.getEndOffset()) {
return new Tuple<Integer>(h.getStartOffset(), h.getEndOffset());
}
}
}
return null;
}
private void removeHighlightAt(Tuple<Integer> loc)
{
Highlighter.Highlight[] highlights = textPane.getHighlighter().getHighlights();
for (int i = 0; i < highlights.length; ++i)
{
Highlighter.Highlight h = highlights[i];
if (h.getPainter() instanceof UnderlineHighlightPainter) {
if (loc.getFirst() == h.getStartOffset() && loc.getSecond() == h.getEndOffset()) {
textPane.getHighlighter().removeHighlight(h);
}
}
}
}
}
// This function takes a String representing a misspelled word (i.e. word not in the dictionary)
// and tries to look for similar words in the dictionary as suggestions
// It returns all found suggestions (no more than 5) in a Vector of Strings.
// Pre-condition: misspelledWord is a string not in dictionary
// Post-condition: returns a vector of suggestions, i.e. similar words that are in dictionary
private Vector<String> findCorrections(String misspelledWord)
{
final int maxSuggestions = 5;
Vector<String> suggestions = new Vector<String>();
if (dictionary.contains(misspelledWord))
{
suggestions.add(misspelledWord);
}
else
{
for (int i = 1; i <= Math.abs(misspelledWord.hashCode() % 3) + 1; ++i) {
//suggestions.add(misspelledWord + "_suggestion" + i);
// Pick random words from the dictionary as 'suggestions'... not very clever
Random r = new Random(misspelledWord.hashCode() + i);
suggestions.add((String)dictionary.toArray()[r.nextInt(dictionary.size())]);
}
}
if (suggestions.size() > maxSuggestions) suggestions.setSize(maxSuggestions);
return suggestions;
}
// This function transfers the case from one word to another
private String transferWordCase(String originalWord, String newWord)
{
if (originalWord.substring(0, 1).equals(originalWord.substring(0, 1).toLowerCase()))
return newWord.toLowerCase();
else if (originalWord.equals(originalWord.toUpperCase()))
return newWord.toUpperCase();
else
return newWord.substring(0, 1).toUpperCase() + newWord.substring(1).toLowerCase();
}
private void loadDictionary()
{
try {
Scanner s = new Scanner(new BufferedReader(new FileReader("dictionary.txt")));
while (s.hasNext()) {
dictionary.add(s.next().trim().toLowerCase());
}
s.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
private void saveDictionary()
{
if (addedToDictionary.size() == 0)
return;
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("dictionary.txt", true)));
for (Iterator<String> it = addedToDictionary.iterator(); it.hasNext(); )
out.print("\r\n" + it.next()); // Windows newline on purpose, so that the dictionary format stays consistent across platforms
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
private void performFileOpen() {
JFileChooser chooser = createChooser(JFileChooser.OPEN_DIALOG);
int response = chooser.showDialog(this, null);
if (response == JFileChooser.APPROVE_OPTION) {
File file = null;
try {
file = chooser.getSelectedFile();
BufferedReader br = new BufferedReader(new FileReader(file));
textPane.read(br, null);
br.close();
lastFileFilter = chooser.getFileFilter();
if (file.getName().toLowerCase().endsWith(".java")) {
highlightingButtonGroup.setSelected(noneMenuItem.getModel(), true); // Force fullCheckSpelling() to get executed
highlightingButtonGroup.setSelected(javaSourceCodeMenuItem.getModel(), true);
} else {
highlightingButtonGroup.setSelected(noneMenuItem.getModel(), true); // Force fullCheckSpelling() to get executed
highlightingButtonGroup.setSelected(englishSpellcheckingMenuItem.getModel(), true);
}
textPaneWasReset();
documentFile = file;
setDocumentHasUnsavedChanges(false);
lastDirectory = file.getParentFile();
} catch (java.io.FileNotFoundException fnfe) {
System.err.println("Warning: File '" + file + "' not found.");
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
private boolean performFileSave() {
if (documentFile != null) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(documentFile));
textPane.write(bw);
bw.close();
setDocumentHasUnsavedChanges(false);
} catch (IOException e) {
System.err.println("Warning: Failed to save file '" + documentFile + "'.");
e.printStackTrace();
}
return true;
} else {
return performFileSaveAs();
}
}
private boolean performFileSaveAs()
{
JFileChooser chooser = createChooser(JFileChooser.SAVE_DIALOG);
while (true) {
int response = chooser.showDialog(this, null);
if (response == JFileChooser.APPROVE_OPTION) {
File file = null;
try {
file = chooser.getSelectedFile();
if (file.exists()) {
// Ask the user if he wants to replace the existing file
int replaceResponse = JOptionPane.showConfirmDialog(this, "The file '" + file.getName() +
"' already exists.\nDo you want to replace it?", "Save As", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (replaceResponse == JOptionPane.NO_OPTION)
continue; // Bring up the file chooser again and let the user select another file or cancel
}
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
textPane.write(bw);
bw.close();
lastFileFilter = chooser.getFileFilter();
if (file.getName().toLowerCase().endsWith(".java")) {
highlightingButtonGroup.setSelected(javaSourceCodeMenuItem.getModel(), true);
} else {
highlightingButtonGroup.setSelected(englishSpellcheckingMenuItem.getModel(), true);
}
documentFile = file;
setDocumentHasUnsavedChanges(false);
lastDirectory = file.getParentFile();
} catch (IOException e) {
System.err.println("Warning: Failed to 'save as' file '" + file + "'.");
e.printStackTrace();
}
return true;
}
else
return false;
}
}
private void textPaneWasReset()
{
textPane.getDocument().addDocumentListener(this);
textPane.getDocument().addUndoableEditListener(this);
undoManager.discardAllEdits();
updateUnredoMenuItems();
quickFindPanel.hidePanel(false);
}
private boolean wordAcceptedByDictionary(String word)
{
boolean isWordInDictionary = dictionary.contains(word) || dictionary.contains(word.substring(0, 1).toLowerCase() + word.substring(1));
boolean isNumber = word.matches("\\d+");
boolean isAcronym = word.matches("[A-Z]+");
return isWordInDictionary || isNumber || isAcronym;
}
private boolean isJavaKeyword(String text) {
return javaKeywords.contains(text);
}
private Highlighter.HighlightPainter painter = new UnderlineHighlightPainter(Color.red);
private void checkSpelling(DocumentEvent evt)
{
System.out.println("=====Searching..===============================");
final Highlighter highlighter = textPane.getHighlighter();
String textPaneCaseContent = ""; // Text pane content with character case preserved (not all lower-case)
try {
Document d = textPane.getDocument();
textPaneCaseContent = d.getText(0, d.getLength());
textPaneContent = textPaneCaseContent.toLowerCase();
} catch (BadLocationException e) {
// Shouldn't happen
return;
}
boolean currentWordWasHighlighted = false;
int caretPosition = -1;
//if (evt.getType() == DocumentEvent.EventType.INSERT && evt.getLength() == 1) caretPosition = evt.getOffset() + evt.getLength();
if (evt.getType() == DocumentEvent.EventType.INSERT) caretPosition = evt.getOffset() + evt.getLength();
else if (evt.getType() == DocumentEvent.EventType.REMOVE) caretPosition = evt.getOffset();
Tuple<Integer> b4exp = new Tuple<Integer>(0, 0);
Tuple<Integer> range = null;
if (evt.getType() == DocumentEvent.EventType.INSERT) { range = expandRange(textPaneContent, evt.getOffset(), evt.getOffset() + evt.getLength()); b4exp.setFirst(evt.getOffset()); b4exp.setSecond(evt.getOffset() + evt.getLength()); }
else if (evt.getType() == DocumentEvent.EventType.REMOVE) { range = expandRange(textPaneContent, evt.getOffset(), evt.getOffset()); b4exp.setFirst(evt.getOffset()); b4exp.setSecond(evt.getOffset()); }
System.out.println(new Tuple<Integer>(b4exp.getFirst(), b4exp.getSecond()) + " expanded to " + range);
System.out.println("'" + textPaneContent.substring(b4exp.getFirst(), b4exp.getSecond()) + "' expanded to '" + textPaneContent.substring(range.getFirst(), range.getSecond()) + "'");
// Clear the in-range previous English Dictionary Spellchecking
if (highlightingButtonGroup.getSelection() == englishSpellcheckingMenuItem.getModel())
{
// Remove any existing highlights for last word
Highlighter.Highlight[] highlights = highlighter.getHighlights();
for (int i = 0; i < highlights.length; ++i) {
Highlighter.Highlight h = highlights[i];
if (h.getPainter() instanceof UnderlineHighlightPainter) {
if (h.getStartOffset() >= range.getFirst() && h.getEndOffset() <= range.getSecond()) {
highlighter.removeHighlight(h);
if (evt.getLength() == 1 && inRange(caretPosition, new Tuple<Integer>(h.getStartOffset(), h.getEndOffset()))) {
currentWordWasHighlighted = true;
}
//System.out.println("removed highlight " + h.getStartOffset() + ", " + h.getEndOffset());
}
}
}
}
// Clear the in-range previous Java Source Code Syntax Highlighting
else if (highlightingButtonGroup.getSelection() == javaSourceCodeMenuItem.getModel())
{
// Remove Java keyword highlighting
//textPane.getStyledDocument().setCharacterAttributes(range.getFirst(), range.getSecond() - range.getFirst(), textPane.getStyledDocument().getDefaultRootElement().getAttributes(), true);
final int start = range.getFirst();
final int length = range.getSecond() - range.getFirst();
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
textPane.getStyledDocument().setCharacterAttributes(start, length, textPane.getStyledDocument().getDefaultRootElement().getAttributes(), true);
}
});
}
Pattern p = Pattern.compile("[\\w'-]+");
Matcher m = p.matcher(textPaneContent);
m.region(range.getFirst(), range.getSecond());
// English Dictionary Spellchecking
if (highlightingButtonGroup.getSelection() == englishSpellcheckingMenuItem.getModel())
{
System.out.println("Event type = " + evt.getType());
System.out.println("offset = " + evt.getOffset() + ", length = " + evt.getLength());
while (m.find())
{
System.out.println("looping " + m.start() + " to " + m.end() + "; caret at " + caretPosition);
try {
if (!wordAcceptedByDictionary(textPaneCaseContent.substring(m.start(), m.end()))) {
//if (currentWordWasHighlighted || (evt.getLength() == 1 && !inRange(caretPosition, new Tuple<Integer>(m.start(), m.end()))))
if (evt.getLength() == 1 && inRange(caretPosition, new Tuple<Integer>(m.start(), m.end()))) {
if (currentWordWasHighlighted) {
highlighter.addHighlight(m.start(), m.end(), painter);
System.out.println("highlighting " + m.start() + " to " + m.end());
} else {
shouldBeHighlighted = new Tuple<Integer>(m.start(), m.end());
System.out.println("shouldBeHighlighted = " + shouldBeHighlighted);
}
} else {
highlighter.addHighlight(m.start(), m.end(), painter);
System.out.println("highlighting " + m.start() + " to " + m.end());
}
} else {
//if (shouldBeHighlighted != null && shouldBeHighlighted.getFirst() >= m.start() && shouldBeHighlighted.getSecond() <= m.end())
Tuple<Integer> shouldNotBeHighlighted = new Tuple<Integer>(m.start(), m.end());
if (shouldBeHighlighted != null && shouldBeHighlighted.doesOverlap(shouldNotBeHighlighted))
shouldBeHighlighted = null;
}
} catch (BadLocationException e) {
// Nothing to do
}
}
}
// Java Source Code Syntax Highlighting
else if (highlightingButtonGroup.getSelection() == javaSourceCodeMenuItem.getModel())
{
final SimpleAttributeSet keywordText = new SimpleAttributeSet();
StyleConstants.setForeground(keywordText, Color.blue);
//StyleConstants.setBold(keywordText, true);
while (m.find())
{
//System.out.println("looping " + m.start() + " to " + m.end());
if (isJavaKeyword(textPaneCaseContent.substring(m.start(), m.end()))) {
//textPane.getStyledDocument().setCharacterAttributes(m.start(), m.end() - m.start(), keywordText, true);
final int start = m.start();
final int length = m.end() - m.start();
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
textPane.getStyledDocument().setCharacterAttributes(start, length, keywordText, true);
}
});
}
}
}
}
private boolean isWordChar(char ch)
{
if ((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '\'' || ch == '-' || ch == '_')
return true;
else
return false;
}
private Tuple<Integer> expandRange(String content, int start, int end)
{
while (start > 0 && isWordChar(content.charAt(start - 1))) {
--start;
}
while (end < content.length() && isWordChar(content.charAt(end))) {
++end;
}
return new Tuple<Integer>(start, end);
}
private boolean inRange(int position, Tuple<Integer> range)
{
return (position >= range.getFirst() && position <= range.getSecond());
}
private void fullCheckSpelling()
{
//System.out.println("full spell Searching..");
final Highlighter highlighter = textPane.getHighlighter();
String textPaneCaseContent = ""; // Text pane content with character case preserved (not all lower-case)
// Clear all of the previous English Dictionary Spellchecking
if (lastHighlightingOption == englishSpellcheckingMenuItem.getModel())
{
// Remove any existing highlights
Highlighter.Highlight[] highlights = highlighter.getHighlights();
for (int i = 0; i < highlights.length; ++i) {
Highlighter.Highlight h = highlights[i];
if (h.getPainter() instanceof UnderlineHighlightPainter) {
highlighter.removeHighlight(h);
}
}
}
// Clear all of the previous Java Source Code Syntax Highlighting
else if (lastHighlightingOption == javaSourceCodeMenuItem.getModel())
{
// Remove Java keyword highlighting
textPane.getStyledDocument().setCharacterAttributes(0, textPane.getStyledDocument().getLength(), textPane.getStyledDocument().getDefaultRootElement().getAttributes(), true);
// Remove bracket highlighting
Highlighter.Highlight[] highlights = highlighter.getHighlights();
for (int i = 0; i < highlights.length; ++i) {
Highlighter.Highlight h = highlights[i];
if (h.getPainter() == painterBracketMatched || h.getPainter() == painterBracketUnmatched) {
highlighter.removeHighlight(h);
}
}
}
try {
Document d = textPane.getDocument();
textPaneCaseContent = d.getText(0, d.getLength());
textPaneContent = textPaneCaseContent.toLowerCase();
} catch (BadLocationException e) {
// Shouldn't happen
return;
}
Pattern p = Pattern.compile("[\\w'-]+");
Matcher m = p.matcher(textPaneContent);
// English Dictionary Spellchecking
if (highlightingButtonGroup.getSelection() == englishSpellcheckingMenuItem.getModel())
{
while (m.find())
{
//System.out.println("looping " + m.start() + " to " + m.end());
try {
if (!wordAcceptedByDictionary(textPaneCaseContent.substring(m.start(), m.end()))) {
highlighter.addHighlight(m.start(), m.end(), painter);
//System.out.println("highlighting " + m.start() + " to " + m.end());
}
} catch (BadLocationException e) {
// Nothing to do
}
}
}
// Java Source Code Syntax Highlighting
else if (highlightingButtonGroup.getSelection() == javaSourceCodeMenuItem.getModel())
{
SimpleAttributeSet keywordText = new SimpleAttributeSet();
StyleConstants.setForeground(keywordText, Color.blue);
//StyleConstants.setBold(keywordText, true);
while (m.find())
{
//System.out.println("looping " + m.start() + " to " + m.end());
if (isJavaKeyword(textPaneCaseContent.substring(m.start(), m.end()))) {
textPane.getStyledDocument().setCharacterAttributes(m.start(), m.end() - m.start(), keywordText, true);
}
}
// Highlight a bracket pair if caret is over a bracket
highlightBracketPair(textPane.getCaretPosition());
}
}
public void insertUpdate(DocumentEvent e) { quickFindPanel.hidePanel(false); checkSpelling(e); setDocumentHasUnsavedChanges(true); }
public void removeUpdate(DocumentEvent e) { quickFindPanel.hidePanel(false); checkSpelling(e); setDocumentHasUnsavedChanges(documentFile != null || textPane.getText().length() != 0); }
public void changedUpdate(DocumentEvent e) {}
private void updateUnredoMenuItems()
{
if (undoMenuItem != null) undoMenuItem.setEnabled(undoManager.canUndo());
if (redoMenuItem != null) redoMenuItem.setEnabled(undoManager.canRedo());
}
public void undoableEditHappened(UndoableEditEvent e) { undoManager.undoableEditHappened(e); updateUnredoMenuItems(); }
private Highlighter.HighlightPainter painterBracketMatched = new DefaultHighlighter.DefaultHighlightPainter(Color.green);
private Highlighter.HighlightPainter painterBracketUnmatched = new DefaultHighlighter.DefaultHighlightPainter(Color.red);
public void caretUpdate(CaretEvent e)
{
int caretPosition = e.getDot();
boolean selectionExists = e.getDot() != e.getMark();
cutMenuItem.setEnabled(selectionExists);
copyMenuItem.setEnabled(selectionExists);
deleteMenuItem.setEnabled(selectionExists);
// If there is a selection
if (selectionExists)
{
// Leave focus of current word
if (shouldBeHighlighted != null) {
try {
textPane.getHighlighter().addHighlight(shouldBeHighlighted.getFirst(), shouldBeHighlighted.getSecond(), painter);
System.out.println("highlighting shouldBeHighlighted " + shouldBeHighlighted.getFirst() + " to " + shouldBeHighlighted.getSecond());
} catch (BadLocationException ble) {}
shouldBeHighlighted = null;
}
} else {
if (shouldBeHighlighted != null && !inRange(caretPosition, shouldBeHighlighted)) {
try {
textPane.getHighlighter().addHighlight(shouldBeHighlighted.getFirst(), shouldBeHighlighted.getSecond(), painter);
System.out.println("highlighting shouldBeHighlighted " + shouldBeHighlighted.getFirst() + " to " + shouldBeHighlighted.getSecond());
} catch (BadLocationException ble) {}
shouldBeHighlighted = null;
}
}
// Bracket highlighter/matcher
if (highlightingButtonGroup.getSelection() == javaSourceCodeMenuItem.getModel()) // Java Source Code Syntax Highlighting
{
// Clear old brackets
Highlighter highlighter = textPane.getHighlighter();
Highlighter.Highlight[] highlights = highlighter.getHighlights();
for (int i = 0; i < highlights.length; ++i)
{
Highlighter.Highlight h = highlights[i];
if (h.getPainter() == painterBracketMatched || h.getPainter() == painterBracketUnmatched) {
highlighter.removeHighlight(h);
}
}
// Highlight new pair
highlightBracketPair(caretPosition);
}
}
private int isBracket(char ch)
{
final String openBracket = "{([<";
final String closeBracket = "})]>";
int bracket;
if ((bracket = openBracket.indexOf(ch) + 1) != 0)
return +bracket;
else if ((bracket = closeBracket.indexOf(ch) + 1) != 0)
return -bracket;
else return 0;
}
private void highlightBracketPair(int caretPosition)
{
if (quickFindPanel.isVisible())
return;
Highlighter highlighter = textPane.getHighlighter();
int bracket, bracketDirection, startPos, endPos;
Stack<Integer> brackets = new Stack<Integer>();
if ((caretPosition >= 1 && (bracket = isBracket(textPaneContent.charAt(startPos = caretPosition - 1))) != 0) ||
(caretPosition < textPaneContent.length() && (bracket = isBracket(textPaneContent.charAt(startPos = caretPosition))) != 0))
{
endPos = startPos; // Assume the other bracket will not be found first, then search for it
bracketDirection = bracket > 0 ? +1 : -1; // Figure out the direction of the scan
brackets.push(bracket);
for (int pos = startPos + bracketDirection; pos >= 0 && pos < textPaneContent.length(); pos += bracketDirection)
{
bracket = isBracket(textPaneContent.charAt(pos));
if (bracket != 0) {
if (bracket * brackets.peek() > 0) {
// Same direction bracket, push on stack
brackets.push(bracket);
} else {
// Opposite direction bracket, make sure it matches the previous one
if (bracket + brackets.peek() == 0) {
// Match successful, so pop the bracket from stack
brackets.pop();
if (brackets.empty()) {
// Found the endBracket
endPos = pos;
break;
}
} else {
// Match unsuccessful, therefore the starting braket was broken
break;
}
}
}
}
// Paint the found brackets
try {
if (startPos != endPos) {
highlighter.addHighlight(startPos, startPos + 1, painterBracketMatched);
highlighter.addHighlight(endPos, endPos + 1, painterBracketMatched);
} else
highlighter.addHighlight(startPos, startPos + 1, painterBracketUnmatched);
} catch (BadLocationException ble) { ble.printStackTrace(); }
}
}
// Creates a fresh new JFileChooser
// This is needed to reset it if the user presses cancel, which doesn't happen in Java if you
// reuse the same instance
// But that's how all other Windows applications behave, so I wanted it to be consistent
private FileNameExtensionFilter txtFilter = new FileNameExtensionFilter("Text Files (*.txt)", "txt");
private FileNameExtensionFilter javaFilter = new FileNameExtensionFilter("Java Source Files (*.java)", "java");
private FileFilter lastFileFilter = null;
private JFileChooser createChooser(int chooserType)
{
JFileChooser chooser = new JFileChooser();
if (lastDirectory != null)
chooser.setCurrentDirectory(lastDirectory);
// This is needed to get the file filters in correct order and the text filter active by default
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileFilter(txtFilter);
chooser.addChoosableFileFilter(javaFilter);
chooser.setAcceptAllFileFilterUsed(true);
if (lastFileFilter == null)
chooser.setFileFilter(txtFilter); // Set Text Files filter selected by default
else
chooser.setFileFilter(lastFileFilter);
if (chooserType == JFileChooser.OPEN_DIALOG) {
// Nothing to do
} else if (chooserType == JFileChooser.SAVE_DIALOG) {
// Change the text from 'Save' to 'Save As'
chooser.setDialogTitle("Save As");
chooser.setApproveButtonText("Save As");
}
return chooser;
}
// Returns true if this stage passes, and it should move on to the next step
// i.e. it only returns false if the user presses Cancel button
private boolean dealWithUnsavedChanges()
{
if (getDocumentHasUnsavedChanges())
{
String fileName = "Untitled";
try {
if (documentFile != null)
fileName = documentFile.getCanonicalPath();
} catch (Exception e) {}
int response = JOptionPane.showConfirmDialog(this, "There are unsaved changes in the '"
+ fileName + "' file.\n\nDo you want to save the changes?",
applicationTitle, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
if (response == JOptionPane.YES_OPTION)
{
return performFileSave();
}
else if (response == JOptionPane.NO_OPTION)
return true;
else if (response == JOptionPane.CANCEL_OPTION)
return false;
else
return false;
} else
return true;
}
private class QuickFindPanel extends JPanel implements ActionListener, KeyListener, DocumentListener
{
private int panelHeight;
private JTextField findTextField;
private JLabel resultsCountLabel;
private JButton previousResultButton;
private JButton nextResultButton;
private JButton closeButton;
private Tuple<Integer> searchResults = new Tuple<Integer>(0, 0);
private boolean performedSearch = false;
private int originalViewport;
QuickFindPanel()
{
super();
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(Box.createHorizontalStrut(3));
findTextField = new JTextField();
findTextField.setBorder(null);
findTextField.addActionListener(this);
findTextField.addKeyListener(this);
findTextField.getDocument().addDocumentListener(this);
add(findTextField);
add(Box.createHorizontalStrut(3));
resultsCountLabel = new JLabel();
resultsCountLabel.setOpaque(true);
add(resultsCountLabel);
add(Box.createHorizontalStrut(3));
previousResultButton = new JButton(new ImageIcon("Previous.gif"));
previousResultButton.setPreferredSize(new Dimension(24, 22));
previousResultButton.setBorder(null);
previousResultButton.addActionListener(this);
add(previousResultButton);
nextResultButton = new JButton(new ImageIcon("Next.gif"));
nextResultButton.setPreferredSize(new Dimension(24, 22));
nextResultButton.setBorder(null);
nextResultButton.addActionListener(this);
add(nextResultButton);
add(Box.createHorizontalGlue());
closeButton = new JButton(new ImageIcon("Close.gif"));
closeButton.setPreferredSize(new Dimension(24, 22));
closeButton.setBorder(null);
closeButton.addActionListener(this);
add(closeButton);
setBorder(new LineBorder(Color.gray));
setBackground(findTextField.getBackground());
//width = findTextField.getX() * 3 + findTextField.getWidth() + closeButton.getWidth();
//height = findTextField.getY() * 2 + Math.max(findTextField.getHeight(), closeButton.getHeight());
panelHeight = Math.max(findTextField.getPreferredSize().height, closeButton.getPreferredSize().height);
setVisible(false);
}
public void updateSize()
{
//int width = 200;//findTextField.getX() * 3 + findTextField.getWidth() + closeButton.getWidth();
//int height = 50;//findTextField.getY() * 2 + Math.max(findTextField.getHeight(), closeButton.getHeight());
int width = 250;
Rectangle containerBounds = textPaneScrollPane.getParent().getBounds();
setBounds(Math.max(containerBounds.width - 325, 0), containerBounds.y, Math.min(275, containerBounds.width), panelHeight);
}
public void insertUpdate(DocumentEvent e) { searchResults = highlightString(findTextField.getText()); performedSearch = true; updateResultsCount(0); }