-
Notifications
You must be signed in to change notification settings - Fork 2
/
EditorFrame.java
2605 lines (2405 loc) · 105 KB
/
EditorFrame.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
package editor.gui.editor;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Set;
import java.util.Stack;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DropMode;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.WindowConstants;
import javax.swing.border.EtchedBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.table.AbstractTableModel;
import editor.collection.CardList;
import editor.collection.deck.CategorySpec;
import editor.collection.deck.Deck;
import editor.collection.deck.Hand;
import editor.collection.export.CardListFormat;
import editor.database.card.Card;
import editor.gui.CardTagPanel;
import editor.gui.MainFrame;
import editor.gui.TableSelectionListener;
import editor.gui.ccp.CCPItems;
import editor.gui.ccp.data.CategoryTransferData;
import editor.gui.ccp.data.DataFlavors;
import editor.gui.ccp.handler.CategoryTransferHandler;
import editor.gui.ccp.handler.EditorFrameTransferHandler;
import editor.gui.ccp.handler.EditorTableTransferHandler;
import editor.gui.display.CardImagePanel;
import editor.gui.display.CardTable;
import editor.gui.display.CardTableModel;
import editor.gui.generic.CardMenuItems;
import editor.gui.generic.ChangeTitleListener;
import editor.gui.generic.ComponentUtils;
import editor.gui.generic.EditablePanel;
import editor.gui.generic.ScrollablePanel;
import editor.gui.generic.TableMouseAdapter;
import editor.gui.generic.VerticalButtonList;
import editor.gui.settings.SettingsDialog;
import editor.util.MouseListenerFactory;
import editor.util.PopupMenuListenerFactory;
import editor.util.UndoableAction;
import editor.util.UnicodeSymbols;
/**
* This class represents an internal frame for editing a deck. It contains a table that shows all cards
* and their counts in the deck as well as zero or more tables for categories within it. It can add cards
* to a deck and add, edit, and delete categories. It is contained within the main frame, which has the
* inventory from which cards can be added.
*
* @author Alec Roelke
*/
@SuppressWarnings("serial")
public class EditorFrame extends JInternalFrame
{
/**
* This enum represents an order that category panels can be sorted in.
*
* @author Alec Roelke
*/
private enum CategoryOrder
{
/**
* Sort categories in ascending alphabetical order.
*/
A_Z("A-Z", (d) -> (a, b) -> a.getName().compareToIgnoreCase(b.getName())),
/**
* Sort categories in descending alphabetical order.
*/
Z_A("Z-A", (d) -> (a, b) -> -a.getName().compareToIgnoreCase(b.getName())),
/**
* Sort categories in order of increasing card count.
*/
ASCENDING("Ascending Size", (d) -> Comparator.comparingInt((a) -> d.getCategoryList(a.getName()).total())),
/**
* Sort categories in order of decreasing card count.
*/
DESCENDING("Descending Size", (d) -> (a, b) -> d.getCategoryList(b.getName()).total() - d.getCategoryList(a.getName()).total()),
/**
* Sort categories in order of increasing rank.
*/
PRIORITY("Increasing Rank", (d) -> Comparator.comparingInt((a) -> d.getCategoryRank(a.getName()))),
/**
* Sort categories in order of decreasing rank.
*/
REVERSE("Decreasing Rank", (d) -> (a, b) -> d.getCategoryRank(b.getName()) - d.getCategoryRank(a.getName()));
/**
* String to display when a String representation of this
* CategoryOrder is called for.
*/
private final String name;
/**
* Function comparing two {@link CategorySpec}s from a deck
*/
private final Function<Deck, Comparator<CategorySpec>> order;
/**
* Create a new CategoryOrder.
*
* @param n Name of the new CategoryOrder
* @param o Function comparing two CategorySpecs from a Deck
*/
CategoryOrder(String n, Function<Deck, Comparator<CategorySpec>> o)
{
name = n;
order = o;
}
/**
* Compare the two given {@link CategorySpec}s from the given Deck.
*
* @param d deck containing the categories
* @param a first category
* @param b second category
* @return a negative number if the first category comes before the second in the given deck,
* a positive number if it comes after, and 0 if there is no relative order.
*/
public int compare(Deck d, CategorySpec a, CategorySpec b)
{
return order.apply(d).compare(a, b);
}
@Override
public String toString()
{
return name;
}
}
/**
* Struct containing the current state of a deck, the original state of it as it was
* loaded, and the table model and table for displaying the deck.
*
* @author Alec Roelke
*/
private static final class DeckData
{
/**
* Name of the deck, if it isn't the main deck.
*/
public Optional<String> name;
/**
* Current state of the deck.
*/
public final Deck current;
/**
* Original state of the deck just after loading it.
*/
public Deck original;
/**
* Model backing the table.
*/
public CardTableModel model;
/**
* Table displaying the deck.
*/
public CardTable table;
/**
* Create a copy of a DeckData.
*
* @param d DeckData to copy
*/
public DeckData(DeckData d)
{
current = new Deck();
current.addAll(d.current);
original = new Deck();
original.addAll(d.original);
name = d.name;
}
/**
* Create a new DeckData with the given optional name. Don't use this
* constructor.
*
* @param deck deck to use as backing data
* @param n name of the deck if it isn't the main deck
*/
private DeckData(Deck deck, Optional<String> n)
{
current = deck;
original = new Deck();
original.addAll(deck);
name = n;
}
/**
* Create a new DeckData to represent the main deck. Do not use this constructor
* to create an extra list.
*
* @param deck list of cards to put in the deck
*/
public DeckData(Deck deck)
{
this(deck, Optional.empty());
}
/**
* Create a new DeckData using the given Deck. The original deck
* will be a copy of it. Do not use this constructor for the main deck.
*
* @param deck Deck to use as backing data
* @param n name of the deck
*/
public DeckData(Deck deck, String n)
{
this(deck, Optional.of(n));
}
/**
* Create a new DeckData for a list with the given name. Do not use this
* constructor for the main deck.
*
* @param n name of the new list
*/
public DeckData(String n)
{
this(new Deck(), n);
}
/**
* @return A String containing the cards that are different between the current deck
* and the original one from the last save, preceded by "-Nx" or "+Nx" to indicate
* count changes, where N is the number of copies added or removed.
*/
public String getChanges()
{
StringBuilder changes = new StringBuilder();
for (Card c : original)
{
int had = original.contains(c) ? original.getEntry(c).count() : 0;
int has = current.contains(c) ? current.getEntry(c).count() : 0;
if (has < had)
changes.append("-").append(had - has).append("x ").append(c.unifiedName()).append(" (").append(c.expansion().name).append(")\n");
}
for (Card c : current)
{
int had = original.contains(c) ? original.getEntry(c).count() : 0;
int has = current.contains(c) ? current.getEntry(c).count() : 0;
if (had < has)
changes.append("+").append(has - had).append("x ").append(c.unifiedName()).append(" (").append(c.expansion().name).append(")\n");
}
return changes.toString();
}
}
/**
* Popup menu listener for a CardTable of this EditorFrame. It controls the visibility
* and contents of the include and exclude options.
*
* @author Alec Roelke
*/
private class TableCategoriesPopupListener implements PopupMenuListener
{
/**
* Submenu for quickly adding cards to categories.
*/
private JMenu addToCategoryMenu;
/**
* Item for editing the categories of cards.
*/
private JMenuItem editCategoriesItem;
/**
* Separator between category edit and card edit sections of the table
* popup menu.
*/
private JSeparator menuSeparator;
/**
* Submenu for quickly removing cards from categories.
*/
private JMenu removeFromCategoryMenu;
/**
* Table in which the menu appears.
*/
private CardTable table;
/**
* Create a new TablePopupListener.
*
* @param add submenu for adding cards
* @param remove submenu for removing cards
* @param edit item for editing card categories
* @param sep separator between menu items
* @param t table which will contain the popup
*/
public TableCategoriesPopupListener(JMenu add, JMenu remove, JMenuItem edit, JSeparator sep, CardTable t)
{
addToCategoryMenu = add;
removeFromCategoryMenu = remove;
editCategoriesItem = edit;
menuSeparator = sep;
table = t;
}
@Override
public void popupMenuCanceled(PopupMenuEvent e)
{}
/**
* {@inheritDoc}
* When the popup menu becomes invisible (something is selected or it
* is canceled), the submenus should be cleared so they don't get
* duplicate items.
*/
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e)
{
addToCategoryMenu.removeAll();
removeFromCategoryMenu.removeAll();
}
/**
* {@inheritDoc}
* Just before the popup menu becomes visible, its submenus for adding
* the selected cards to categories and removing them from categories
* should be populated. If any of them are empty, they become invisible.
* If there are no selected cards or there are no categories, the edit
* categories item also becomes invisible.
*/
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e)
{
if (parent.getSelectedTable().filter((f) -> f == table).isPresent())
{
if (parent.getSelectedCards().size() == 1)
{
Card card = parent.getSelectedCards().get(0);
for (CategorySpec category : deck().current.categories())
{
if (!category.includes(card))
{
JMenuItem categoryItem = new JMenuItem(category.getName());
categoryItem.addActionListener((e2) -> includeIn(card, category));
addToCategoryMenu.add(categoryItem);
}
}
addToCategoryMenu.setVisible(addToCategoryMenu.getItemCount() > 0);
for (CategorySpec category : deck().current.categories())
{
if (category.includes(card))
{
JMenuItem categoryItem = new JMenuItem(category.getName());
categoryItem.addActionListener((e2) -> excludeFrom(card, category));
removeFromCategoryMenu.add(categoryItem);
}
}
removeFromCategoryMenu.setVisible(removeFromCategoryMenu.getItemCount() > 0);
}
else
{
addToCategoryMenu.setVisible(false);
removeFromCategoryMenu.setVisible(false);
}
editCategoriesItem.setVisible(!parent.getSelectedCards().isEmpty() && !deck().current.categories().isEmpty());
menuSeparator.setVisible(addToCategoryMenu.isVisible() || removeFromCategoryMenu.isVisible() || editCategoriesItem.isVisible());
}
}
}
/** Tab number containing the main list of cards. */
public static final int MAIN_TABLE = 0;
/** Tab number containing categories. */
public static final int CATEGORIES = 1;
/** Tab number containing sample hands. */
public static final int SAMPLE_HANDS = 2;
/** Tab number containing user-defined notes. */
public static final int NOTES = 3;
/** Tab number containing the changelog. */
public static final int CHANGELOG = 4;
/**
* Name denoting the main deck for making modifications.
*/
public static final int MAIN_DECK = 0;
/**
* Label showing the average mana value of nonland cards in the deck.
*/
private JLabel avgManaValueLabel;
/**
* Panel containing categories.
*/
private Box categoriesContainer;
/**
* Panels showing categories in this deck (individual panels should not be operated
* on except for GUI-related functions).
*/
private Collection<CategoryPanel> categoryPanels;
/**
* Text area to show the changelog.
*/
private JTextArea changelogArea;
/**
* Label showing the total number of cards in the deck.
*/
private JLabel countLabel;
/**
* Tabs showing extra lists.
*/
private JTabbedPane extrasPane;
/**
* File where the deck was last saved.
*/
private File file;
/**
* Hand containing cards to show in the sample hand tab.
*/
private Hand hand;
/**
* Panel showing a sample hand and a table showing probabilities of category requirements.
*/
private CalculateHandPanel handCalculations;
/**
* Scroll pane containing the sample hand image panel.
*/
private JScrollPane imagePane;
/**
* Panel containing images for the sample hand.
*/
private ScrollablePanel imagePanel;
/**
* Label showing the total number of land cards in the deck.
*/
private JLabel landLabel;
/**
* All lists in the editor. The index into this list of a card list is that card
* list's ID. The main deck always has ID 0, and will never be null. Other lists
* will have IDs starting from 1, and any empty spots will be indicated with a null
* value here.
*/
private List<DeckData> lists;
/**
* Tabbed pane for choosing whether to display the entire deck or the categories.
*/
private JTabbedPane listTabs;
/**
* Label showing the median mana value of nonland cards in the deck.
*/
private JLabel medManaValueLabel;
/**
* Menu containing sideboards to move cards from the main deck to one at a time.
*/
private JMenu moveToMenu;
/**
* Menu containing sideboards to move cards from the main deck to all at once.
*/
private JMenu moveAllToMenu;
/**
* Label showing the total number of nonland cards in the deck.
*/
private JLabel nonlandLabel;
/**
* Text area containing deck notes.
*/
private JTextArea notesArea;
/**
* Parent {@link MainFrame}.
*/
private MainFrame parent;
/**
* Buffer containing actions to redo. Clears whenever an action is performed
* (but not when it is redone).
*/
private Stack<UndoableAction<Boolean, Boolean>> redoBuffer;
/**
* Combo box allowing changes to be made in the order that categories are display in.
*/
private JComboBox<CategoryOrder> sortCategoriesBox;
/**
* Size of starting hands.
*/
private int startingHandSize;
/**
* Panel containing extra lists.
*/
private JPanel southPanel;
/**
* Layout of the panel containing extra lists, allow it to switch between a set of tabs
* containing tables and a blank panel with instructions for adding the first extra list.
*/
private CardLayout southLayout;
/**
* Combo box showing categories to jump between them.
*/
private JComboBox<String> switchCategoryBox;
/**
* Model for the combo box to display items.
*/
private DefaultComboBoxModel<String> switchCategoryModel;
/**
* Stack containing actions to undo.
*/
private Stack<UndoableAction<Boolean, Boolean>> undoBuffer;
/**
* Whether or not the deck has been saved since it has last been changed.
*/
private boolean unsaved;
/**
* Create a new EditorFrame to edit a deck.
*
* @param p MainFrame parent of the new EditorFrame
* @param u index of the new frame, used for initial bounds and title if it's a new deck
* @param manager #DeckSerializer to read the loaded deck from
*/
public EditorFrame(MainFrame p, int u, DeckSerializer manager)
{
super(!manager.canSaveFile() ? "Untitled " + u : manager.file().getName(), true, true, true, true);
setBounds(((u - 1)%5)*30, ((u - 1)%5)*30, 600, 600);
setLayout(new BorderLayout(0, 0));
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
lists = new ArrayList<>(2);
lists.add(new DeckData(manager.deck()));
parent = p;
unsaved = false;
undoBuffer = new Stack<>();
redoBuffer = new Stack<>();
startingHandSize = SettingsDialog.settings().editor.hand.size();
if (manager.canSaveFile())
setFile(manager.file());
else
setUnsaved();
listTabs = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.SCROLL_TAB_LAYOUT);
add(listTabs, BorderLayout.CENTER);
JPanel mainPanel = new JPanel(new BorderLayout());
deck().model = new CardTableModel(this, deck().current, SettingsDialog.settings().editor.columns);
deck().table = new CardTable(deck().model);
deck().table.setStripeColor(SettingsDialog.settings().editor.stripe);
TableSelectionListener listener = new TableSelectionListener(parent, deck().table, deck().current);
deck().table.addMouseListener(listener);
deck().table.getSelectionModel().addListSelectionListener(listener);
for (int i = 0; i < deck().table.getColumnCount(); i++)
if (deck().model.isCellEditable(0, i))
deck().table.getColumn(deck().model.getColumnName(i)).setCellEditor(CardTable.createCellEditor(this, deck().model.getColumnData(i)));
deck().table.setTransferHandler(new EditorTableTransferHandler(this, MAIN_DECK));
deck().table.setDragEnabled(true);
deck().table.setDropMode(DropMode.ON);
JScrollPane mainDeckPane = new JScrollPane(deck().table);
mainDeckPane.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
mainPanel.add(mainDeckPane, BorderLayout.CENTER);
VerticalButtonList deckButtons = new VerticalButtonList("+", String.valueOf(UnicodeSymbols.MINUS), "X");
deckButtons.get("+").addActionListener((e) -> {
addCards(MAIN_DECK, parent.getSelectedCards(), 1);
});
deckButtons.get(String.valueOf(UnicodeSymbols.MINUS)).addActionListener((e) -> removeCards(MAIN_DECK, parent.getSelectedCards(), 1));
deckButtons.get("X").addActionListener((e) -> removeCards(MAIN_DECK, parent.getSelectedCards(), parent.getSelectedCards().stream().mapToInt((c) -> deck().current.getEntry(c).count()).reduce(0, Math::max)));
mainPanel.add(deckButtons, BorderLayout.WEST);
southPanel = new JPanel(southLayout = new CardLayout());
mainPanel.add(southPanel, BorderLayout.SOUTH);
JPanel extrasPanel = new JPanel();
extrasPanel.setLayout(new BorderLayout());
southPanel.add(extrasPanel, "extras");
VerticalButtonList extrasButtons = new VerticalButtonList("+", String.valueOf(UnicodeSymbols.MINUS), "X");
extrasButtons.get("+").addActionListener((e) -> getSelectedExtraID().ifPresent((id) -> addCards(id, parent.getSelectedCards(), 1)));
extrasButtons.get(String.valueOf(UnicodeSymbols.MINUS)).addActionListener((e) -> {
getSelectedExtraID().ifPresent((id) -> removeCards(id, parent.getSelectedCards(), 1));
});
extrasButtons.get("X").addActionListener((e) -> getSelectedExtraID().ifPresent((id) -> {
removeCards(id, parent.getSelectedCards(), parent.getSelectedCards().stream().mapToInt((c) -> sideboard().getEntry(c).count()).reduce(0, Math::max));
}));
extrasPanel.add(extrasButtons, BorderLayout.WEST);
extrasPane = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.SCROLL_TAB_LAYOUT);
extrasPanel.add(extrasPane, BorderLayout.CENTER);
JPanel emptyPanel = new JPanel(new BorderLayout());
emptyPanel.setBorder(BorderFactory.createEtchedBorder());
JLabel emptyLabel = new JLabel("Click to add a sideboard.");
emptyLabel.setHorizontalAlignment(JLabel.CENTER);
emptyPanel.add(emptyLabel, BorderLayout.CENTER);
southPanel.add(emptyPanel, "empty");
southLayout.show(southPanel, "empty");
listTabs.addTab("Cards", mainPanel);
// Main table popup menu
JPopupMenu tableMenu = new JPopupMenu();
deck().table.addMouseListener(new TableMouseAdapter(deck().table, tableMenu));
// Cut, copy, paste
CCPItems ccp = new CCPItems(deck().table, true);
tableMenu.add(ccp.cut);
tableMenu.add(ccp.copy);
tableMenu.add(ccp.paste);
tableMenu.add(new JSeparator());
// Add/remove cards
CardMenuItems tableMenuCardItems = new CardMenuItems(() -> Optional.of(this), parent::getSelectedCards, true);
tableMenuCardItems.addAddItems(tableMenu);
tableMenu.add(new JSeparator());
tableMenuCardItems.addRemoveItems(tableMenu);
tableMenu.add(new JSeparator());
// Move cards to sideboard
tableMenu.add(moveToMenu = new JMenu("Move to"));
tableMenu.add(moveAllToMenu = new JMenu("Move all to"));
JSeparator moveSeparator = new JSeparator();
tableMenu.add(moveSeparator);
// Quick edit categories
JMenu addToCategoryMenu = new JMenu("Include in");
tableMenu.add(addToCategoryMenu);
JMenu removeFromCategoryMenu = new JMenu("Exclude from");
tableMenu.add(removeFromCategoryMenu);
// Edit categories item
JMenuItem editCategoriesItem = new JMenuItem("Edit Categories...");
editCategoriesItem.addActionListener((e) -> {
IncludeExcludePanel iePanel = new IncludeExcludePanel(deck().current.categories().stream().sorted((a, b) -> a.getName().compareToIgnoreCase(b.getName())).collect(Collectors.toList()), parent.getSelectedCards());
if (JOptionPane.showConfirmDialog(this, new JScrollPane(iePanel), "Set Categories", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) == JOptionPane.OK_OPTION)
editInclusion(iePanel.getIncluded(), iePanel.getExcluded());
});
tableMenu.add(editCategoriesItem);
JSeparator categoriesSeparator = new JSeparator();
tableMenu.add(categoriesSeparator);
// Edit card tags item
JMenuItem editTagsItem = new JMenuItem("Edit Tags...");
editTagsItem.addActionListener((e) -> CardTagPanel.editTags(parent.getSelectedCards(), parent));
tableMenu.add(editTagsItem);
// Table memu popup listeners
tableMenu.addPopupMenuListener(new TableCategoriesPopupListener(addToCategoryMenu, removeFromCategoryMenu,
editCategoriesItem, categoriesSeparator, deck().table));
tableMenu.addPopupMenuListener(PopupMenuListenerFactory.createVisibleListener((e) -> {
ccp.cut.setEnabled(!parent.getSelectedCards().isEmpty());
ccp.copy.setEnabled(!parent.getSelectedCards().isEmpty());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
ccp.paste.setEnabled(clipboard.isDataFlavorAvailable(DataFlavors.entryFlavor) || clipboard.isDataFlavorAvailable(DataFlavors.cardFlavor));
tableMenuCardItems.setEnabled(!parent.getSelectedCards().isEmpty());
moveToMenu.setVisible(!extras().isEmpty());
moveAllToMenu.setVisible(!extras().isEmpty());
moveSeparator.setVisible(!extras().isEmpty());
addToCategoryMenu.setEnabled(!categoryPanels.isEmpty());
removeFromCategoryMenu.setEnabled(!categoryPanels.isEmpty());
editCategoriesItem.setEnabled(!categoryPanels.isEmpty());
editTagsItem.setEnabled(!parent.getSelectedCards().isEmpty());
moveToMenu.removeAll();
moveAllToMenu.removeAll();
for (int i = 1; i < lists.size(); i++)
{
if (lists.get(i) != null)
{
final int id = i;
JMenuItem moveToItem = new JMenuItem(lists.get(i).name.get());
moveToItem.addActionListener((e2) -> moveCards(MAIN_DECK, id, parent.getSelectedCards().stream().collect(Collectors.toMap(Function.identity(), (c) -> 1))));
moveToMenu.add(moveToItem);
JMenuItem moveAllToItem = new JMenuItem(lists.get(i).name.get());
moveAllToItem.addActionListener((e2) -> moveCards(MAIN_DECK, id, parent.getSelectedCards().stream().collect(Collectors.toMap(Function.identity(), (c) -> deck().current.getEntry(c).count()))));
moveAllToMenu.add(moveAllToItem);
}
}
}));
// Panel containing categories
JPanel categoriesPanel = new JPanel(new BorderLayout());
JPanel categoriesMainPanel = new JPanel(new BorderLayout());
categoriesPanel.add(categoriesMainPanel, BorderLayout.CENTER);
listTabs.addTab("Categories", categoriesPanel);
// Panel containing components above the category panel
Box categoryHeaderPanel = new Box(BoxLayout.X_AXIS);
categoriesMainPanel.add(categoryHeaderPanel, BorderLayout.NORTH);
// Button to add a new category
JPanel addCategoryPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
JButton addCategoryButton = new JButton("Add");
addCategoryButton.addActionListener((e) -> createCategory().ifPresent(this::addCategory));
addCategoryPanel.add(addCategoryButton);
categoryHeaderPanel.add(addCategoryPanel);
// Combo box to change category sort order
JPanel sortCategoriesPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
sortCategoriesPanel.add(new JLabel("Display order:"));
sortCategoriesBox = new JComboBox<>(CategoryOrder.values());
sortCategoriesBox.addActionListener((e) -> {
if (sortCategoriesBox.isPopupVisible())
{
updateCategoryPanel();
update();
}
});
sortCategoriesPanel.add(sortCategoriesBox);
categoryHeaderPanel.add(sortCategoriesPanel);
// Combo box to switch to a different category
JPanel switchCategoryPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
switchCategoryBox = new JComboBox<>(switchCategoryModel = new DefaultComboBoxModel<>());
switchCategoryBox.setEnabled(false);
switchCategoryBox.addActionListener((e) -> {
if (switchCategoryBox.isPopupVisible())
{
getCategoryPanel(switchCategoryBox.getItemAt(switchCategoryBox.getSelectedIndex())).ifPresent((c) -> {
c.scrollRectToVisible(new Rectangle(c.getSize()));
c.flash();
});
}
});
switchCategoryPanel.add(new JLabel("Go to category:"));
switchCategoryPanel.add(switchCategoryBox);
categoryHeaderPanel.add(switchCategoryPanel);
// Make sure all parts of the category panel fit inside the window (this is necessary because
// JScrollPanes do weird things with non-scroll-savvy components)
JPanel categoriesSuperContainer = new ScrollablePanel(new BorderLayout(), ScrollablePanel.TRACK_WIDTH);
categoriesContainer = new Box(BoxLayout.Y_AXIS);
categoryPanels = new ArrayList<>();
// The category panel is a vertically-scrollable panel that contains all categories stacked vertically
// The categories should have a constant height, but fit the container horizontally
categoriesSuperContainer.add(categoriesContainer, BorderLayout.NORTH);
JScrollPane categoriesPane = new JScrollPane(categoriesSuperContainer, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
categoriesMainPanel.add(categoriesPane, BorderLayout.CENTER);
// Transfer handler for the category box
// We explicitly use null here to cause exceptions if cutting or copying, as that should never happen
categoriesPane.setTransferHandler(new CategoryTransferHandler(null, (c) -> containsCategory(c.getName()), this::addCategory, null));
// Popup menu for category container
JPopupMenu categoriesMenu = new JPopupMenu();
CCPItems categoriesCCP = new CCPItems(categoriesPane, false);
categoriesCCP.paste.setText("Paste Category");
categoriesMenu.add(categoriesCCP.paste);
categoriesMenu.add(new JSeparator());
JMenuItem categoriesCreateItem = new JMenuItem("Add Category...");
categoriesCreateItem.addActionListener((e) -> createCategory().ifPresent(this::addCategory));
categoriesMenu.add(categoriesCreateItem);
categoriesMenu.addPopupMenuListener(PopupMenuListenerFactory.createVisibleListener((e) -> {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
try
{
categoriesCCP.paste.setEnabled(!containsCategory(((CategoryTransferData)clipboard.getData(DataFlavors.categoryFlavor)).spec.getName()));
}
catch (UnsupportedFlavorException | IOException x)
{
categoriesCCP.paste.setEnabled(false);
}
}));
categoriesPane.setComponentPopupMenu(categoriesMenu);
VerticalButtonList categoryButtons = new VerticalButtonList("+", String.valueOf(UnicodeSymbols.MINUS), "X");
categoryButtons.get("+").addActionListener((e) -> addCards(MAIN_DECK, parent.getSelectedCards(), 1));
categoryButtons.get(String.valueOf(UnicodeSymbols.MINUS)).addActionListener((e) -> removeCards(MAIN_DECK, parent.getSelectedCards(), 1));
categoryButtons.get("X").addActionListener((e) -> removeCards(MAIN_DECK, parent.getSelectedCards(), parent.getSelectedCards().stream().mapToInt((c) -> deck().current.getEntry(c).count()).reduce(0, Math::max)));
categoriesPanel.add(categoryButtons, BorderLayout.WEST);
// Sample hands
JPanel handPanel = new JPanel(new BorderLayout());
// Table showing the cards in hand
hand = new Hand(deck().current);
imagePanel = new ScrollablePanel(ScrollablePanel.TRACK_HEIGHT);
imagePanel.setLayout(new BoxLayout(imagePanel, BoxLayout.X_AXIS));
imagePane = new JScrollPane(imagePanel);
imagePane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
setHandBackground(SettingsDialog.settings().editor.hand.background());
// Control panel for manipulating the sample hand
JPanel handModPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
JButton newHandButton = new JButton("New Hand");
newHandButton.addActionListener((e) -> {
hand.newHand(startingHandSize);
imagePanel.removeAll();
for (Card c : hand)
{
CardImagePanel panel = new CardImagePanel();
panel.setCard(c);
panel.setBackground(SettingsDialog.settings().editor.hand.background());
imagePanel.add(panel);
imagePanel.add(Box.createHorizontalStrut(10));
}
imagePanel.validate();
update();
});
handModPanel.add(newHandButton);
JButton mulliganButton = new JButton("Mulligan");
mulliganButton.addActionListener((e) -> {
hand.mulligan();
imagePanel.removeAll();
for (Card c : hand)
{
CardImagePanel panel = new CardImagePanel();
imagePanel.add(panel);
panel.setCard(c);
panel.setBackground(SettingsDialog.settings().editor.hand.background());
imagePanel.add(Box.createHorizontalStrut(10));
}
imagePanel.validate();
update();
});
handModPanel.add(mulliganButton);
JButton drawCardButton = new JButton("Draw a Card");
drawCardButton.addActionListener((e) -> {
if (hand.size() < deck().current.total())
{
hand.draw();
CardImagePanel panel = new CardImagePanel();
panel.setBackground(SettingsDialog.settings().editor.hand.background());
imagePanel.add(panel);
panel.setCard(hand.get(hand.size() - 1));
imagePanel.add(Box.createHorizontalStrut(10));
imagePanel.validate();
update();
}
});
handModPanel.add(drawCardButton);
List.of(
newHandButton.getPreferredSize(),
mulliganButton.getPreferredSize(),
drawCardButton.getPreferredSize()
).stream().mapToInt((d) -> d.width).max().ifPresent(w -> {
newHandButton.setPreferredSize(new Dimension(w, newHandButton.getPreferredSize().height));
mulliganButton.setPreferredSize(new Dimension(w, mulliganButton.getPreferredSize().height));
drawCardButton.setPreferredSize(new Dimension(w, drawCardButton.getPreferredSize().height));
});
handCalculations = new CalculateHandPanel(deck().current);
JSplitPane handSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, imagePane, handCalculations);
handSplit.setOneTouchExpandable(true);
handSplit.setContinuousLayout(true);
SwingUtilities.invokeLater(() -> handSplit.setDividerLocation(0.5));
handSplit.setResizeWeight(0.5);
handPanel.add(handModPanel, BorderLayout.NORTH);
handPanel.add(handSplit, BorderLayout.CENTER);
listTabs.addTab("Sample Hand", handPanel);
hand.refresh();
// Notes
notesArea = new JTextArea(manager.notes());
var notes = new Stack<String>();
notes.push(notesArea.getText());
notesArea.getDocument().addDocumentListener(new DocumentListener() {
boolean undoing;
Timer timer;
{
undoing = false;
timer = new Timer(500, (e) -> {
final String text = notesArea.getText();
if (!undoing && !text.equals(notes.peek()))
{
performAction(() -> {
notes.push(text);
if (!notesArea.getText().equals(notes.peek()))
{
undoing = true;
notesArea.setText(text);
listTabs.setSelectedIndex(NOTES);
undoing = false;
}
return true;
}, () -> {
notes.pop();
undoing = true;
notesArea.setText(notes.peek());
listTabs.setSelectedIndex(NOTES);
undoing = false;
return true;
});
}
});
timer.setRepeats(false);
}
public void performNotesAction(final String text)
{
if (timer.isRunning())
timer.restart();
else
timer.start();
}
@Override
public void insertUpdate(DocumentEvent e)
{
performNotesAction(notesArea.getText());
}
@Override
public void removeUpdate(DocumentEvent e)
{
performNotesAction(notesArea.getText());
}
@Override
public void changedUpdate(DocumentEvent e)
{
performNotesAction(notesArea.getText());
}
});
CCPItems notesCCP = new CCPItems(() -> notesArea, true);
JPopupMenu notesMenu = new JPopupMenu();
notesMenu.add(notesCCP.cut);
notesMenu.add(notesCCP.copy);
notesMenu.add(notesCCP.paste);
notesMenu.addPopupMenuListener(PopupMenuListenerFactory.createVisibleListener((e) -> {
String text = notesArea.getSelectedText();
notesCCP.cut.setEnabled(text != null && !text.isEmpty());
notesCCP.copy.setEnabled(text != null && !text.isEmpty());
notesCCP.paste.setEnabled(Toolkit.getDefaultToolkit().getSystemClipboard().isDataFlavorAvailable(DataFlavor.stringFlavor));
}));
notesArea.setComponentPopupMenu(notesMenu);
listTabs.addTab("Notes", new JScrollPane(notesArea));
// Panel to show the stats of the deck
JPanel bottomPanel = new JPanel(new BorderLayout());
getContentPane().add(bottomPanel, BorderLayout.SOUTH);
// Labels to counts for total cards, lands, and nonlands
Box statsPanel = new Box(BoxLayout.X_AXIS);
statsPanel.add(Box.createHorizontalStrut(10));
countLabel = new JLabel();
statsPanel.add(countLabel);
statsPanel.add(ComponentUtils.createHorizontalSeparator(10, ComponentUtils.TEXT_SIZE));
landLabel = new JLabel();
statsPanel.add(landLabel);