-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathProofEditorPanel.java
More file actions
1131 lines (1000 loc) · 44.6 KB
/
ProofEditorPanel.java
File metadata and controls
1131 lines (1000 loc) · 44.6 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 edu.rpi.legup.ui;
import edu.rpi.legup.app.GameBoardFacade;
import edu.rpi.legup.app.LegupPreferences;
import edu.rpi.legup.controller.BoardController;
import edu.rpi.legup.controller.RuleController;
import edu.rpi.legup.history.ICommand;
import edu.rpi.legup.history.IHistoryListener;
import edu.rpi.legup.model.Puzzle;
import edu.rpi.legup.model.PuzzleExporter;
import edu.rpi.legup.model.gameboard.Board;
import edu.rpi.legup.model.tree.Tree;
import edu.rpi.legup.model.tree.TreeNode;
import edu.rpi.legup.model.tree.TreeTransition;
import edu.rpi.legup.save.ExportFileException;
import edu.rpi.legup.save.InvalidFileFormatException;
import edu.rpi.legup.ui.boardview.BoardView;
import edu.rpi.legup.ui.proofeditorui.rulesview.RuleFrame;
import edu.rpi.legup.ui.proofeditorui.treeview.TreePanel;
import edu.rpi.legup.ui.proofeditorui.treeview.TreeViewSelection;
import edu.rpi.legup.user.Submission;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ProofEditorPanel extends LegupPanel implements IHistoryListener {
private static final Logger LOGGER = LogManager.getLogger(ProofEditorPanel.class.getName());
private JMenuBar mBar;
private TreePanel treePanel;
private JFileChooser fileChooser;
private JFrame frame;
private RuleFrame ruleFrame;
private DynamicView dynamicBoardView;
private JSplitPane topHalfPanel, mainPanel;
private TitledBorder boardBorder;
private JButton[] toolBarButtons;
private JMenu file;
private JMenuItem newPuzzle,
resetPuzzle,
saveProofAs,
saveProofChange,
helpTutorial,
preferences,
exit;
private JMenu edit;
private JMenuItem undo, redo, fitBoardToScreen, fitTreeToScreen;
private JMenu view;
private JMenu proof;
private JMenuItem add, delete, merge, collapse;
private JCheckBoxMenuItem allowDefault, caseRuleGen, imdFeedback;
private JMenu about, help;
private JMenuItem helpLegup, aboutLegup;
private JToolBar toolBar;
private BoardView boardView;
private JFileChooser folderBrowser;
private LegupUI legupUI;
public static final int ALLOW_HINTS = 1;
public static final int ALLOW_DEFAPP = 2;
public static final int ALLOW_FULLAI = 4;
public static final int ALLOW_JUST = 8;
public static final int REQ_STEP_JUST = 16;
public static final int IMD_FEEDBACK = 32;
public static final int INTERN_RO = 64;
public static final int AUTO_JUST = 128;
static final int[] TOOLBAR_SEPARATOR_BEFORE = {2, 4, 8};
private static final String[] PROFILES = {
"No Assistance",
"Rigorous Proof",
"Casual Proof",
"Assisted Proof",
"Guided Proof",
"Training-Wheels Proof",
"No Restrictions"
};
private static final int[] PROF_FLAGS = {
0,
ALLOW_JUST | REQ_STEP_JUST,
ALLOW_JUST,
ALLOW_HINTS | ALLOW_JUST | AUTO_JUST,
ALLOW_HINTS | ALLOW_JUST | REQ_STEP_JUST,
ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_JUST | IMD_FEEDBACK | INTERN_RO,
ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_FULLAI | ALLOW_JUST
};
private JMenu proofMode = new JMenu("Proof Mode");
private JCheckBoxMenuItem[] proofModeItems = new JCheckBoxMenuItem[PROF_FLAGS.length];
private static int CONFIG_INDEX = 0;
protected JMenu ai = new JMenu("AI");
protected JMenuItem runAI = new JMenuItem("Run AI to completion");
protected JMenuItem setpAI = new JMenuItem("Run AI one Step");
protected JMenuItem testAI = new JMenuItem("Test AI!");
protected JMenuItem hintAI = new JMenuItem("Hint");
public ProofEditorPanel(JFileChooser fileChooser, JFrame frame, LegupUI legupUI) {
this.fileChooser = fileChooser;
this.frame = frame;
this.legupUI = legupUI;
setLayout(new BorderLayout());
setPreferredSize(new Dimension(800, 700));
}
@Override
public void makeVisible() {
this.removeAll();
setupToolBar();
setupContent();
frame.setJMenuBar(getMenuBar());
}
public JMenuBar getMenuBar() {
if (mBar != null) return mBar;
mBar = new JMenuBar();
file = new JMenu("File");
newPuzzle = new JMenuItem("Open");
resetPuzzle = new JMenuItem("Reset Puzzle");
// genPuzzle = new JMenuItem("Puzzle Generators"); // TODO: implement puzzle
// generator
saveProofAs = new JMenuItem("Save As"); // create a new file to save
saveProofChange = new JMenuItem("Save"); // save to the current file
preferences = new JMenuItem("Preferences");
helpTutorial = new JMenuItem("Help"); // jump to web page
exit = new JMenuItem("Exit");
edit = new JMenu("Edit");
undo = new JMenuItem("Undo");
redo = new JMenuItem("Redo");
fitBoardToScreen = new JMenuItem("Fit Board to Screen");
fitTreeToScreen = new JMenuItem("Fit Tree to Screen");
view = new JMenu("View");
proof = new JMenu("Proof");
String os = LegupUI.getOS();
add = new JMenuItem("Add");
add.addActionListener(a -> treePanel.add());
if (os.equals("mac")) {
add.setAccelerator(
KeyStroke.getKeyStroke(
'A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
} else {
add.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_DOWN_MASK));
}
proof.add(add);
delete = new JMenuItem("Delete");
delete.addActionListener(a -> treePanel.delete());
if (os.equals("mac")) {
delete.setAccelerator(
KeyStroke.getKeyStroke(
'D', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
} else {
delete.setAccelerator(KeyStroke.getKeyStroke('D', InputEvent.CTRL_DOWN_MASK));
}
proof.add(delete);
merge = new JMenuItem("Merge");
merge.addActionListener(a -> treePanel.merge());
if (os.equals("mac")) {
merge.setAccelerator(
KeyStroke.getKeyStroke(
'M', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
} else {
merge.setAccelerator(KeyStroke.getKeyStroke('M', InputEvent.CTRL_DOWN_MASK));
}
proof.add(merge);
collapse = new JMenuItem("Collapse");
collapse.addActionListener(a -> treePanel.collapse());
if (os.equals("mac")) {
collapse.setAccelerator(
KeyStroke.getKeyStroke(
'C', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
} else {
collapse.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_DOWN_MASK));
}
collapse.setEnabled(false);
proof.add(collapse);
allowDefault =
new JCheckBoxMenuItem(
"Allow Default Rule Applications",
LegupPreferences.getInstance()
.getUserPref(LegupPreferences.ALLOW_DEFAULT_RULES)
.equalsIgnoreCase(Boolean.toString(true)));
allowDefault.addChangeListener(
e -> {
LegupPreferences.getInstance()
.setUserPref(
LegupPreferences.ALLOW_DEFAULT_RULES,
Boolean.toString(allowDefault.isSelected()));
});
proof.add(allowDefault);
caseRuleGen =
new JCheckBoxMenuItem(
"Automatically generate cases for CaseRule",
LegupPreferences.getInstance()
.getUserPref(LegupPreferences.AUTO_GENERATE_CASES)
.equalsIgnoreCase(Boolean.toString(true)));
caseRuleGen.addChangeListener(
e -> {
LegupPreferences.getInstance()
.setUserPref(
LegupPreferences.AUTO_GENERATE_CASES,
Boolean.toString(caseRuleGen.isSelected()));
});
proof.add(caseRuleGen);
imdFeedback =
new JCheckBoxMenuItem(
"Provide immediate feedback",
LegupPreferences.getInstance()
.getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK)
.equalsIgnoreCase(Boolean.toString(true)));
imdFeedback.addChangeListener(
e -> {
LegupPreferences.getInstance()
.setUserPref(
LegupPreferences.IMMEDIATE_FEEDBACK,
Boolean.toString(imdFeedback.isSelected()));
});
proof.add(imdFeedback);
about = new JMenu("About");
helpLegup = new JMenuItem("Help Legup");
aboutLegup = new JMenuItem("About Legup");
mBar.add(file);
file.add(newPuzzle);
newPuzzle.addActionListener((ActionEvent) -> loadPuzzle());
if (os.equals("mac")) {
newPuzzle.setAccelerator(
KeyStroke.getKeyStroke(
'N', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
} else {
newPuzzle.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.CTRL_DOWN_MASK));
}
file.add(resetPuzzle);
resetPuzzle.addActionListener(
a -> {
Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule();
if (puzzle != null) {
Tree tree = GameBoardFacade.getInstance().getTree();
TreeNode rootNode = tree.getRootNode();
if (rootNode != null) {
int confirmReset =
JOptionPane.showConfirmDialog(
this,
"Reset Puzzle to Root Node?",
"Confirm Reset",
JOptionPane.YES_NO_OPTION);
if (confirmReset == JOptionPane.YES_OPTION) {
List<TreeTransition> children = rootNode.getChildren();
children.forEach(
t ->
puzzle.notifyTreeListeners(
l -> l.onTreeElementRemoved(t)));
children.forEach(
t ->
puzzle.notifyBoardListeners(
l -> l.onTreeElementChanged(t)));
rootNode.clearChildren();
final TreeViewSelection selection =
new TreeViewSelection(
treePanel.getTreeView().getElementView(rootNode));
puzzle.notifyTreeListeners(
l -> l.onTreeSelectionChanged(selection));
puzzle.notifyBoardListeners(
listener ->
listener.onTreeElementChanged(
selection
.getFirstSelection()
.getTreeElement()));
GameBoardFacade.getInstance().getHistory().clear();
}
}
}
});
if (os.equals("mac")) {
resetPuzzle.setAccelerator(
KeyStroke.getKeyStroke(
'R', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
} else {
resetPuzzle.setAccelerator(KeyStroke.getKeyStroke('R', InputEvent.CTRL_DOWN_MASK));
}
file.addSeparator();
file.add(saveProofAs);
saveProofAs.addActionListener((ActionEvent) -> saveProofAs());
// save proof as...
if (os.equals("mac")) {
saveProofAs.setAccelerator(
KeyStroke.getKeyStroke(
'S', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
} else {
saveProofAs.setAccelerator(KeyStroke.getKeyStroke('S', InputEvent.CTRL_DOWN_MASK));
}
// save proof change
if (os.equals("mac")) {
saveProofChange.setAccelerator(
KeyStroke.getKeyStroke(
'A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
} else {
saveProofChange.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_DOWN_MASK));
}
file.add(saveProofChange);
saveProofChange.addActionListener((ActionEvent) -> saveProofChange());
file.addSeparator();
// preference
file.add(preferences);
preferences.addActionListener(
a -> {
PreferencesDialog preferencesDialog =
PreferencesDialog.CreateDialogForProofEditor(
this.frame, this.ruleFrame);
});
file.addSeparator();
// help function
if (os.equals("mac")) {
helpTutorial.setAccelerator(
KeyStroke.getKeyStroke(
'H', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
} else {
helpTutorial.setAccelerator(KeyStroke.getKeyStroke('H', InputEvent.CTRL_DOWN_MASK));
}
file.add(helpTutorial);
helpTutorial.addActionListener((ActionEvent) -> helpTutorial());
file.addSeparator();
// exit
file.add(exit);
exit.addActionListener((ActionEvent) -> exitEditor());
if (os.equals("mac")) {
exit.setAccelerator(
KeyStroke.getKeyStroke(
'Q', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
} else {
exit.setAccelerator(KeyStroke.getKeyStroke('Q', InputEvent.CTRL_DOWN_MASK));
}
mBar.add(edit);
edit.add(undo);
undo.addActionListener((ActionEvent) -> GameBoardFacade.getInstance().getHistory().undo());
if (os.equals("mac")) {
undo.setAccelerator(
KeyStroke.getKeyStroke(
'Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
} else {
undo.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_DOWN_MASK));
}
edit.add(redo);
// Created action to support two keybinds (CTRL-SHIFT-Z, CTRL-Y)
Action redoAction =
new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
GameBoardFacade.getInstance().getHistory().redo();
}
};
if (os.equals("mac")) {
redo.getInputMap(WHEN_IN_FOCUSED_WINDOW)
.put(
KeyStroke.getKeyStroke(
'Z',
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()
+ InputEvent.SHIFT_DOWN_MASK),
"redoAction");
redo.getInputMap(WHEN_IN_FOCUSED_WINDOW)
.put(
KeyStroke.getKeyStroke(
'Y', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
"redoAction");
redo.setAccelerator(
KeyStroke.getKeyStroke(
'Z',
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()
+ InputEvent.SHIFT_DOWN_MASK));
} else {
redo.getInputMap(WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke('Y', InputEvent.CTRL_DOWN_MASK), "redoAction");
redo.getInputMap(WHEN_IN_FOCUSED_WINDOW)
.put(
KeyStroke.getKeyStroke(
'Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK),
"redoAction");
redo.getActionMap().put("redoAction", redoAction);
// Button in menu will show CTRL-SHIFT-Z as primary keybind
redo.setAccelerator(
KeyStroke.getKeyStroke(
'Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK));
}
edit.add(fitBoardToScreen);
fitBoardToScreen.addActionListener(
(ActionEvent) -> dynamicBoardView.fitBoardViewToScreen());
edit.add(fitTreeToScreen);
fitTreeToScreen.addActionListener((ActionEvent) -> this.fitTreeViewToScreen());
mBar.add(proof);
about.add(aboutLegup);
aboutLegup.addActionListener(
l -> {
JOptionPane.showMessageDialog(null, "Version: 5.1.0");
});
about.add(helpLegup);
helpLegup.addActionListener(
l -> {
try {
java.awt.Desktop.getDesktop()
.browse(URI.create("https://github.com/Bram-Hub/LEGUP/wiki"));
} catch (IOException e) {
LOGGER.error("Can't open web page");
}
});
mBar.add(about);
return mBar;
}
public void exitEditor() {
// Wipes the puzzle entirely as if LEGUP just started
GameBoardFacade.getInstance().clearPuzzle();
this.legupUI.displayPanel(0);
treePanel = null;
boardView = null;
}
// File opener
public Object[] promptPuzzle() {
GameBoardFacade facade = GameBoardFacade.getInstance();
if (facade.getBoard() != null) {
if (noquit("Opening a new puzzle?")) {
return new Object[0];
}
}
LegupPreferences preferences = LegupPreferences.getInstance();
String preferredDirectory = preferences.getUserPref(LegupPreferences.WORK_DIRECTORY);
if (preferences.getSavedPath() != "") {
preferredDirectory = preferences.getSavedPath();
}
File preferredDirectoryFile = new File(preferredDirectory);
JFileChooser fileBrowser = new JFileChooser(preferredDirectoryFile);
String fileName = null;
File puzzleFile = null;
fileBrowser.showOpenDialog(this);
fileBrowser.setVisible(true);
fileBrowser.setCurrentDirectory(new File(preferredDirectory));
fileBrowser.setDialogTitle("Select Proof File");
fileBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileBrowser.setAcceptAllFileFilterUsed(false);
File puzzlePath = fileBrowser.getSelectedFile();
System.out.println(puzzlePath.getAbsolutePath());
if (puzzlePath != null) {
fileName = puzzlePath.getAbsolutePath();
String lastDirectoryPath = fileName.substring(0, fileName.lastIndexOf(File.separator));
preferences.setSavedPath(lastDirectoryPath);
puzzleFile = puzzlePath;
} else {
// The attempt to prompt a puzzle ended gracefully (cancel)
return null;
}
return new Object[] {fileName, puzzleFile};
}
public void loadPuzzle() {
Object[] items = promptPuzzle();
// Return if items == null (cancel)
if (items == null) {
return;
}
String fileName = (String) items[0];
File puzzleFile = (File) items[1];
loadPuzzle(fileName, puzzleFile);
}
public void loadPuzzle(String fileName, File puzzleFile) {
if (puzzleFile != null && puzzleFile.exists()) {
try {
legupUI.displayPanel(1);
GameBoardFacade.getInstance().loadPuzzle(fileName);
String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName();
frame.setTitle(puzzleName + " - " + puzzleFile.getName());
} catch (InvalidFileFormatException e) {
legupUI.displayPanel(0);
LOGGER.error(e.getMessage());
if (e.getMessage()
.contains(
"Proof Tree construction error: could not find rule by ID")) { // TO
// DO: make error
// message not
// hardcoded
JOptionPane.showMessageDialog(
null,
"This file runs on an outdated version of Legup\n"
+ "and is not compatible with the current version.",
"Error",
JOptionPane.ERROR_MESSAGE);
loadPuzzle();
} else {
JOptionPane.showMessageDialog(
null,
"File does not exist or it cannot be read",
"Error",
JOptionPane.ERROR_MESSAGE);
loadPuzzle();
}
}
}
}
/** save the proof in the current file */
private void direct_save() {
Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule();
if (puzzle == null) {
return;
}
String fileName = GameBoardFacade.getInstance().getCurFileName();
if (fileName != null) {
try {
PuzzleExporter exporter = puzzle.getExporter();
if (exporter == null) {
throw new ExportFileException("Puzzle exporter null");
}
exporter.exportPuzzle(fileName);
} catch (ExportFileException e) {
e.printStackTrace();
}
}
}
/** Create a new file and save proof to it */
private void saveProofAs() {
Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule();
if (puzzle == null) {
return;
}
fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
// fileChooser.setMode(JFileChooser.SAVE);
// fileChooser.setTitle("Save As");
fileChooser.setDialogTitle("Save as");
String curFileName = GameBoardFacade.getInstance().getCurFileName();
if (curFileName == null) {
fileChooser.setCurrentDirectory(
// fileChooser.setDirectory(
Path.of(LegupPreferences.getInstance().getUserPref(LegupPreferences.WORK_DIRECTORY)).toFile());
} else {
File curFile = new File(curFileName);
// fileChooser.setDirectory(curFile.getParent());
fileChooser.setCurrentDirectory(curFile.getParentFile());
}
fileChooser.setVisible(true);
String fileName = null;
if (fileChooser.getCurrentDirectory() != null && fileChooser.getSelectedFile() != null) {
fileName = fileChooser.getCurrentDirectory() + File.separator + fileChooser.getSelectedFile();
}
if (fileName != null) {
try {
PuzzleExporter exporter = puzzle.getExporter();
if (exporter == null) {
throw new ExportFileException("Puzzle exporter null");
}
exporter.exportPuzzle(fileName);
} catch (ExportFileException e) {
e.printStackTrace();
}
}
}
// Hyperlink for help button; links to wiki page for tutorials
private void helpTutorial() {
// redirecting to certain help link in wiki
Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule();
if (puzzle == null) {
return;
}
String puz = puzzle.getName();
String url;
switch (puz) {
case "LightUp":
url = "https://github.com/Bram-Hub/Legup/wiki/Light%20up-Rules";
break;
case "Nurikabe":
url = "https://github.com/Bram-Hub/Legup/wiki/Nurikabe-Rules";
break;
case "TreeTent":
url = "https://github.com/Bram-Hub/Legup/wiki/Tree-Tent-Rules";
break;
case "Skyscrapers":
url = "https://github.com/Bram-Hub/Legup/wiki/Skyscrapers-Rules";
break;
case "ShortTruthTable":
url = "https://github.com/Bram-Hub/Legup/wiki/Short-Truth-Table-Rules";
break;
default:
url = "https://github.com/Bram-Hub/Legup/wiki/LEGUP-Tutorial";
}
Runtime rt = Runtime.getRuntime();
try {
// rt.exec("rundll32 url.dll,FileProtocolHandler "+url);
java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
} catch (IOException e) {
e.printStackTrace();
}
}
// add the new function need to implement
public void add_drop() {
// add the mouse event then we can use the new listener to implement and
// we should create a need jbuttom for it to ship the rule we select.
JPanel panel = new JPanel();
JButton moveing_buttom = new JButton();
moveing_buttom.setFocusPainted(false);
moveing_buttom.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// get the selected rule
}
});
panel.add(moveing_buttom);
}
// Quick save proof to the current file with a pop window to show "successfully saved"
private void saveProofChange() {
Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule();
if (puzzle == null) {
return;
}
String fileName = GameBoardFacade.getInstance().getCurFileName();
if (fileName != null) {
try {
PuzzleExporter exporter = puzzle.getExporter();
if (exporter == null) {
throw new ExportFileException("Puzzle exporter null");
}
exporter.exportPuzzle(fileName);
// Save confirmation
JOptionPane.showMessageDialog(
null, "Successfully Saved", "Confirm", JOptionPane.INFORMATION_MESSAGE);
} catch (ExportFileException e) {
e.printStackTrace();
}
}
}
// ask to edu.rpi.legup.save current proof
public boolean noquit(String instr) {
int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION);
return n != JOptionPane.YES_OPTION;
}
/** Sets the main content for the edu.rpi.legup.user interface */
protected void setupContent() {
// JPanel consoleBox = new JPanel(new BorderLayout());
JPanel treeBox = new JPanel(new BorderLayout());
JPanel ruleBox = new JPanel(new BorderLayout());
RuleController ruleController = new RuleController();
ruleFrame = new RuleFrame(ruleController);
ruleBox.add(ruleFrame, BorderLayout.WEST);
treePanel = new TreePanel();
dynamicBoardView =
new DynamicView(new ScrollView(new BoardController()), DynamicViewType.BOARD);
TitledBorder titleBoard = BorderFactory.createTitledBorder("Board");
titleBoard.setTitleJustification(TitledBorder.CENTER);
dynamicBoardView.setBorder(titleBoard);
JPanel boardPanel = new JPanel(new BorderLayout());
topHalfPanel =
new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, ruleFrame, dynamicBoardView);
mainPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, topHalfPanel, treePanel);
topHalfPanel.setPreferredSize(new Dimension(600, 400));
mainPanel.setPreferredSize(new Dimension(600, 600));
boardPanel.add(mainPanel);
boardPanel.setVisible(true);
boardBorder = BorderFactory.createTitledBorder("Board");
boardBorder.setTitleJustification(TitledBorder.CENTER);
ruleBox.add(boardPanel);
treeBox.add(ruleBox);
this.add(treeBox);
// consoleBox.add(treeBox);
//
// getContentPane().add(consoleBox);
// JPopupPanel popupPanel = new JPopupPanel();
// setGlassPane(popupPanel);
// popupPanel.setVisible(true);
mainPanel.setDividerLocation(mainPanel.getMaximumDividerLocation() + 100);
// frame.pack();
revalidate();
}
private void setupToolBar() {
setToolBarButtons(new JButton[ToolbarName.values().length]);
for (int i = 0; i < ToolbarName.values().length; i++) {
String toolBarName = ToolbarName.values()[i].toString();
URL resourceLocation =
ClassLoader.getSystemClassLoader()
.getResource("edu/rpi/legup/images/Legup/" + toolBarName + ".png");
// Scale the image icons down to make the buttons smaller
ImageIcon imageIcon = new ImageIcon(resourceLocation);
Image image = imageIcon.getImage();
imageIcon =
new ImageIcon(
image.getScaledInstance(
this.TOOLBAR_ICON_SCALE,
this.TOOLBAR_ICON_SCALE,
Image.SCALE_SMOOTH));
JButton button = new JButton(toolBarName, imageIcon);
button.setFocusPainted(false);
getToolBarButtons()[i] = button;
}
toolBar = new JToolBar();
toolBar.setFloatable(false);
toolBar.setRollover(true);
for (int i = 0; i < getToolBarButtons().length; i++) {
for (int s = 0; s < TOOLBAR_SEPARATOR_BEFORE.length; s++) {
if (i == TOOLBAR_SEPARATOR_BEFORE[s]) {
toolBar.addSeparator();
}
}
String toolBarName = ToolbarName.values()[i].toString();
toolBar.add(getToolBarButtons()[i]);
getToolBarButtons()[i].setToolTipText(toolBarName);
getToolBarButtons()[i].setVerticalTextPosition(SwingConstants.BOTTOM);
getToolBarButtons()[i].setHorizontalTextPosition(SwingConstants.CENTER);
}
// toolBarButtons[ToolbarName.OPEN_PUZZLE.ordinal()].addActionListener((ActionEvent
// e) ->
// promptPuzzle());
// toolBarButtons[ToolbarName.SAVE.ordinal()].addActionListener((ActionEvent e) ->
// saveProof());
// toolBarButtons[ToolbarName.UNDO.ordinal()].addActionListener((ActionEvent e) ->
// GameBoardFacade.getInstance().getHistory().undo());
// toolBarButtons[ToolbarName.REDO.ordinal()].addActionListener((ActionEvent e) ->
// GameBoardFacade.getInstance().getHistory().redo());
toolBarButtons[ToolbarName.HINT.ordinal()].addActionListener((ActionEvent e) -> {});
toolBarButtons[ToolbarName.CHECK.ordinal()].addActionListener(
(ActionEvent e) -> checkProof());
toolBarButtons[ToolbarName.SUBMIT.ordinal()].addActionListener((ActionEvent e) -> {});
toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].addActionListener((ActionEvent e) -> {});
toolBarButtons[ToolbarName.CHECK_ALL.ordinal()].addActionListener(
(ActionEvent e) -> checkProofAll());
// toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(false);
// toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false);
// toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false);
toolBarButtons[ToolbarName.HINT.ordinal()].setEnabled(false);
toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(false);
toolBarButtons[ToolbarName.SUBMIT.ordinal()].setEnabled(false);
toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].setEnabled(false);
toolBarButtons[ToolbarName.CHECK_ALL.ordinal()].setEnabled(true);
this.add(toolBar, BorderLayout.NORTH);
}
/**
* Sets the toolbar buttons
*
* @param toolBarButtons toolbar buttons
*/
public void setToolBarButtons(JButton[] toolBarButtons) {
this.toolBarButtons = toolBarButtons;
}
/**
* Gets the toolbar buttons
*
* @return toolbar buttons
*/
public JButton[] getToolBarButtons() {
return toolBarButtons;
}
/** Checks the proof for correctness */
private void checkProof() {
GameBoardFacade facade = GameBoardFacade.getInstance();
Tree tree = GameBoardFacade.getInstance().getTree();
Board board = facade.getBoard();
Board finalBoard = null;
boolean delayStatus = true; // board.evalDelayStatus();
repaintAll();
Puzzle puzzle = facade.getPuzzleModule();
if (puzzle.isPuzzleComplete()) {
// This is for submission which is not integrated yet
/*int confirm = JOptionPane.showConfirmDialog(null, "Congratulations! Your proof is correct. Would you like to submit?", "Proof Submission", JOptionPane.YES_NO_OPTION);
if (confirm == JOptionPane.YES_OPTION) {
Submission submission = new Submission(board);
submission.submit();
}*/
JOptionPane.showMessageDialog(null, "Congratulations! Your proof is correct.");
} else {
String message = "\nThe game board is not solved.";
JOptionPane.showMessageDialog(
null, message, "Invalid proof.", JOptionPane.ERROR_MESSAGE);
}
}
private void repaintAll() {
boardView.repaint();
treePanel.repaint();
}
public void setPuzzleView(Puzzle puzzle) {
this.boardView = puzzle.getBoardView();
dynamicBoardView = new DynamicView(boardView, DynamicViewType.BOARD);
this.topHalfPanel.setRightComponent(dynamicBoardView);
this.topHalfPanel.setVisible(true);
String boardType = boardView.getBoard().getClass().getSimpleName();
boardType = boardType.substring(0, boardType.indexOf("Board"));
TitledBorder titleBoard = BorderFactory.createTitledBorder(boardType + " Board");
titleBoard.setTitleJustification(TitledBorder.CENTER);
dynamicBoardView.setBorder(titleBoard);
this.treePanel.getTreeView().resetView();
this.treePanel.getTreeView().setTree(puzzle.getTree());
puzzle.addTreeListener(treePanel.getTreeView());
puzzle.addBoardListener(puzzle.getBoardView());
ruleFrame.getDirectRulePanel().setRules(puzzle.getDirectRules());
ruleFrame.getCasePanel().setRules(puzzle.getCaseRules());
ruleFrame.getContradictionPanel().setRules(puzzle.getContradictionRules());
ruleFrame.getSearchPanel().setSearchBar(puzzle);
toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(true);
// toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(true);
reloadGui();
}
public void reloadGui() {
repaintTree();
}
public void repaintTree() {
treePanel.repaintTreeView(GameBoardFacade.getInstance().getTree());
}
/** Checks the proof for all files */
private void checkProofAll() {
GameBoardFacade facade = GameBoardFacade.getInstance();
/*
* Select dir to grade; recursively grade sub-dirs using traverseDir()
* Selected dir must have sub-dirs for each student:
* GradeThis
* |
* | -> Student 1
* | |
* | | -> Proofs
*/
LegupPreferences preferences = LegupPreferences.getInstance();
File preferredDirectory =
new File(preferences.getUserPref(LegupPreferences.WORK_DIRECTORY));
folderBrowser = new JFileChooser(preferredDirectory);
folderBrowser.showOpenDialog(this);
folderBrowser.setVisible(true);
folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY));
folderBrowser.setDialogTitle("Select Directory");
folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
folderBrowser.setAcceptAllFileFilterUsed(false);
File folder = folderBrowser.getSelectedFile();
// Write csv file (Path,File-Name,Puzzle-Type,Score,Solved?)
File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv");
try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) {
writer.append("Name,File Name,Puzzle Type,Score,Solved?\n");
// Go through student folders
for (final File folderEntry :
Objects.requireNonNull(folder.listFiles(File::isDirectory))) {
// Write path
String path = folderEntry.getName();
traverseDir(folderEntry, writer, path);
}
} catch (IOException ex) {
LOGGER.error(ex.getMessage());
}
JOptionPane.showMessageDialog(null, "Batch grading complete.");
}
private boolean basicCheckProof(int[][] origCells) {
return false;
}
private void traverseDir(File folder, BufferedWriter writer, String path) throws IOException {
// Recursively traverse directory
GameBoardFacade facade = GameBoardFacade.getInstance();
// Folder is empty
if (Objects.requireNonNull(folder.listFiles()).length == 0) {
writer.append(path).append(",Empty folder,,Ungradeable\n");
return;
}
// Travese directory, recurse if sub-directory found
// If ungradeable, do not leave a score (0, 1)
for (final File f : Objects.requireNonNull(folder.listFiles())) {
// Recurse
if (f.isDirectory()) {
traverseDir(f, writer, path + "/" + f.getName());
continue;
}
// Set path name
writer.append(path).append(",");
// Load puzzle, run checker
// If wrong file type, ungradeable
String fName = f.getName();
String fPath = f.getAbsolutePath();
File puzzleFile = new File(fPath);
if (puzzleFile.exists()) {
// Try to load file. If invalid, note in csv
try {
// Load puzzle, run checker
GameBoardFacade.getInstance().loadPuzzle(fPath);
String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName();
frame.setTitle(puzzleName + " - " + puzzleFile.getName());
facade = GameBoardFacade.getInstance();
Puzzle puzzle = facade.getPuzzleModule();
// Write data
writer.append(fName).append(",");
writer.append(puzzle.getName()).append(",");
if (puzzle.isPuzzleComplete()) {
writer.append("1,Solved\n");
} else {
writer.append("0,Unsolved\n");