-
Notifications
You must be signed in to change notification settings - Fork 745
/
MageFrame.java
1853 lines (1617 loc) · 74.5 KB
/
MageFrame.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 mage.client;
import mage.MageException;
import mage.cards.action.ActionCallback;
import mage.cards.decks.Deck;
import mage.cards.repository.CardRepository;
import mage.cards.repository.CardScanner;
import mage.cards.repository.RepositoryUtil;
import mage.client.cards.BigCard;
import mage.client.chat.ChatPanelBasic;
import mage.client.components.*;
import mage.client.components.ext.dlg.DialogManager;
import mage.client.components.tray.MageTray;
import mage.client.constants.Constants;
import mage.client.constants.Constants.DeckEditorMode;
import mage.client.deckeditor.DeckEditorPane;
import mage.client.deckeditor.collection.viewer.CollectionViewerPane;
import mage.client.dialog.*;
import mage.client.draft.DraftPane;
import mage.client.draft.DraftPanel;
import mage.client.game.GamePane;
import mage.client.game.GamePanel;
import mage.client.game.PlayAreaPanel;
import mage.client.plugins.adapters.MageActionCallback;
import mage.client.plugins.impl.Plugins;
import mage.client.preference.MagePreferences;
import mage.client.remote.CallbackClientImpl;
import mage.client.table.TablesPane;
import mage.client.table.TablesPanel;
import mage.client.tournament.TournamentPane;
import mage.client.util.*;
import mage.client.util.audio.MusicPlayer;
import mage.client.util.gui.ArrowBuilder;
import mage.client.util.gui.countryBox.CountryUtil;
import mage.client.util.sets.ConstructedFormats;
import mage.client.util.stats.UpdateMemUsageTask;
import mage.components.ImagePanel;
import mage.components.ImagePanelStyle;
import mage.constants.PlayerAction;
import mage.cards.RateCard;
import mage.interfaces.MageClient;
import mage.interfaces.callback.CallbackClient;
import mage.interfaces.callback.ClientCallback;
import mage.remote.Connection;
import mage.remote.Connection.ProxyType;
import mage.util.DebugUtil;
import mage.utils.MageVersion;
import mage.view.GameEndView;
import mage.view.UserRequestMessage;
import net.java.balloontip.BalloonTip;
import net.java.balloontip.positioners.LeftAbovePositioner;
import net.java.balloontip.styles.EdgedBalloonStyle;
import net.java.truevfs.access.TArchiveDetector;
import net.java.truevfs.access.TConfig;
import net.java.truevfs.kernel.spec.FsAccessOption;
import org.apache.log4j.Logger;
import org.mage.card.arcane.ManaSymbols;
import org.mage.card.arcane.SvgUtils;
import org.mage.plugins.card.images.DownloadPicturesService;
import org.mage.plugins.card.info.CardInfoPaneImpl;
import org.mage.plugins.card.utils.CardImageUtils;
import org.mage.plugins.card.utils.impl.ImageManagerImpl;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.prefs.Preferences;
/**
* @author BetaSteward_at_googlemail.com, JayDi85
*/
public class MageFrame extends javax.swing.JFrame implements MageClient {
private static final String TITLE_NAME = "XMage";
private static final Logger LOGGER = Logger.getLogger(MageFrame.class);
private static final String LITE_MODE_ARG = "-lite";
private static final String GRAY_MODE_ARG = "-gray";
private static final String FILL_SCREEN_ARG = "-fullscreen";
private static final String SKIP_DONE_SYMBOLS = "-skipDoneSymbols";
private static final String USER_ARG = "-user";
private static final String PASSWORD_ARG = "-pw";
private static final String SERVER_ARG = "-server";
private static final String PORT_ARG = "-port";
private static final String DEBUG_ARG = "-debug"; // enable debug button in main menu
private static final String NOT_CONNECTED_TEXT = "<not connected>";
private static final String NOT_CONNECTED_BUTTON = "CONNECT TO SERVER";
private static MageFrame instance;
private final ConnectDialog connectDialog;
private final ErrorDialog errorDialog;
private static CallbackClient callbackClient;
private static final Preferences PREFS = Preferences.userNodeForPackage(MageFrame.class);
private JLabel title;
private Rectangle titleRectangle;
private static final MageVersion VERSION = new MageVersion(MageFrame.class);
private Connection currentConnection;
private static MagePane activeFrame;
private static boolean liteMode = false;
//TODO: make gray theme, implement theme selector in preferences dialog
private static boolean grayMode = false;
private static boolean fullscreenMode = false;
private static boolean skipSmallSymbolGenerationForExisting = false;
private static String startUser = null;
private static String startPassword = "";
private static String startServer = "localhost";
private static int startPort = -1;
private static boolean debugMode = false;
private JToggleButton switchPanelsButton = null; // from main menu
private static String SWITCH_PANELS_BUTTON_NAME = "Switch panels";
private static final Map<UUID, ChatPanelBasic> CHATS = new HashMap<>();
private static final Map<UUID, GamePanel> GAMES = new HashMap<>();
private static final Map<UUID, DraftPanel> DRAFTS = new HashMap<>();
private static final MageUI UI = new MageUI();
private static final ScheduledExecutorService PING_TASK_EXECUTOR = Executors.newSingleThreadScheduledExecutor();
private static UpdateMemUsageTask updateMemUsageTask;
private static long startTime;
private final BalloonTip balloonTip;
/**
* @return the session
*/
public static JDesktopPane getDesktop() {
return desktopPane;
}
public static Preferences getPreferences() {
return PREFS;
}
public static boolean isLite() {
return liteMode;
}
public static boolean isGray() {
return grayMode;
}
public static boolean isSkipSmallSymbolGenerationForExisting() {
return skipSmallSymbolGenerationForExisting;
}
@Override
public MageVersion getVersion() {
return VERSION;
}
public static MageFrame getInstance() {
return instance;
}
private void handleEvent(AWTEvent event) {
MagePane frame = activeFrame;
// support multiple mage panes
Object source = event.getSource();
if (source instanceof Component) {
Component component = (Component) source;
while (component != null) {
if (component instanceof MagePane) {
frame = (MagePane) component;
break;
}
component = component.getParent();
}
}
if (frame != null) {
frame.handleEvent(event);
}
}
public MageFrame() throws MageException {
File cacertsFile = new File(System.getProperty("user.dir") + "/release/cacerts").getAbsoluteFile();
if (!cacertsFile.exists()) { // When running from the jar file the contents of the /release folder will have been expanded into the home folder as part of packaging
cacertsFile = new File(System.getProperty("user.dir") + "/cacerts").getAbsoluteFile();
}
if (cacertsFile.exists()) {
LOGGER.info("Custom (or bundled) Java certificate file (cacerts) file found");
String cacertsPath = cacertsFile.getPath();
System.setProperty("javax.net.ssl.trustStore", cacertsPath);
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
} else {
LOGGER.info("custom Java certificate file not found at: " + cacertsFile.getAbsolutePath());
}
setWindowTitle();
EDTExceptionHandler.registerExceptionHandler();
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
exitApp();
}
});
Toolkit.getDefaultToolkit().addAWTEventListener(event -> handleEvent(event), AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK);
TConfig config = TConfig.current();
config.setArchiveDetector(new TArchiveDetector("zip"));
config.setAccessPreference(FsAccessOption.STORE, true);
try {
UIManager.put("desktop", new Color(0, 0, 0, 0));
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
UIManager.put("nimbusBlueGrey", PreferencesDialog.getCurrentTheme().getNimbusBlueGrey()); // buttons, scrollbar background, disabled inputs
UIManager.put("control", PreferencesDialog.getCurrentTheme().getControl()); // window bg
UIManager.put("nimbusLightBackground", PreferencesDialog.getCurrentTheme().getNimbusLightBackground()); // inputs, table rows
UIManager.put("info", PreferencesDialog.getCurrentTheme().getInfo()); // tooltips
UIManager.put("nimbusBase", PreferencesDialog.getCurrentTheme().getNimbusBase()); // title bars, scrollbar foreground
//UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
// stop JSplitPane from eating F6 and F8 or any other function keys
{
Object value = UIManager.get("SplitPane.ancestorInputMap");
if (value instanceof InputMap) {
InputMap map = (InputMap) value;
for (int vk = KeyEvent.VK_F2; vk <= KeyEvent.VK_F12; ++vk) {
map.remove(KeyStroke.getKeyStroke(vk, 0));
}
}
}
GUISizeHelper.calculateGUISizes();
// UIManager.put("Table.rowHeight", GUISizeHelper.tableRowHeight);
} catch (Exception ex) {
LOGGER.fatal(null, ex);
}
// other settings
if (ClientCallback.SIMULATE_BAD_CONNECTION) {
LOGGER.info("Network: bad connection mode enabled");
}
// DATA PREPARE
RepositoryUtil.bootstrapLocalDb();
// re-create database on empty (e.g. after new build cleaned db on startup)
if (RepositoryUtil.CARD_DB_RECREATE_BY_CLIENT_SIDE && RepositoryUtil.isDatabaseEmpty()) {
LOGGER.info("DB: creating cards database (it can take few minutes)...");
CardScanner.scan();
LOGGER.info("Done.");
}
// IMAGES CHECK
LOGGER.info("Images: search broken files...");
CardImageUtils.checkAndFixImageFiles();
bootstrapSetsAndFormats();
if (RateCard.PRELOAD_CARD_RATINGS_ON_STARTUP) {
RateCard.bootstrapCardsAndRatings();
}
SvgUtils.checkSvgSupport();
ManaSymbols.loadImages();
Plugins.instance.loadPlugins();
if (!Plugins.instance.isCardPluginLoaded()) {
throw new MageException("can't load card plugin");
}
initComponents();
// auto-update switch panels button with actual stats
desktopPane.addContainerListener(new ContainerAdapter() {
@Override
public void componentAdded(ContainerEvent e) {
if (desktopPane.getLayer(e.getComponent()) == JLayeredPane.DEFAULT_LAYER) {
updateSwitchPanelsButton();
}
}
@Override
public void componentRemoved(ContainerEvent e) {
if (desktopPane.getLayer(e.getComponent()) == JLayeredPane.DEFAULT_LAYER) {
updateSwitchPanelsButton();
}
}
});
desktopPane.setDesktopManager(new MageDesktopManager());
setSize(1024, 768);
SettingsManager.instance.setScreenWidthAndHeight(1024, 768);
DialogManager.updateParams(768, 1024, false);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
SessionHandler.startSession(this);
callbackClient = new CallbackClientImpl(this);
connectDialog = new ConnectDialog();
desktopPane.add(connectDialog, JLayeredPane.MODAL_LAYER);
errorDialog = new ErrorDialog();
errorDialog.setLocation(100, 100);
desktopPane.add(errorDialog, JLayeredPane.MODAL_LAYER);
UI.addComponent(MageComponents.DESKTOP_PANE, desktopPane);
PING_TASK_EXECUTOR.scheduleAtFixedRate(() -> SessionHandler.ping(), TablesPanel.PING_SERVER_SECS, TablesPanel.PING_SERVER_SECS, TimeUnit.SECONDS);
updateMemUsageTask = new UpdateMemUsageTask(jMemUsageLabel);
// create default server lobby and hide it until connect
tablesPane = new TablesPane();
desktopPane.add(tablesPane, javax.swing.JLayeredPane.DEFAULT_LAYER);
SwingUtilities.invokeLater(() -> {
this.hideServerLobby();
});
addTooltipContainer();
setBackground();
addMageLabel();
setAppIcon();
MageTray.instance.install();
desktopPane.add(ArrowBuilder.getBuilder().getArrowsManagerPanel(), JLayeredPane.PALETTE_LAYER);
desktopPane.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
int width = ((JComponent) e.getSource()).getWidth();
int height = ((JComponent) e.getSource()).getHeight();
SettingsManager.instance.setScreenWidthAndHeight(width, height);
if (!liteMode && !grayMode) {
backgroundPane.setSize(width, height);
}
updateCurrentFrameSize();
ArrowBuilder.getBuilder().setSize(width, height);
if (title != null) {
title.setBounds((int) (width - titleRectangle.getWidth()) / 2, (int) (height - titleRectangle.getHeight()) / 2, titleRectangle.width, titleRectangle.height);
}
}
});
// balloonTip = new BalloonTip(desktopPane, "", new ModernBalloonStyle(0, 0, Color.WHITE, Color.YELLOW, Color.BLUE), false);
balloonTip = new BalloonTip(desktopPane, "", new EdgedBalloonStyle(Color.WHITE, Color.BLUE), false);
balloonTip.setPositioner(new LeftAbovePositioner(0, 0));
balloonTip.setVisible(false);
// tooltips delay in ms
ToolTipManager.sharedInstance().setDismissDelay(Constants.TOOLTIPS_DELAY_MS);
mageToolbar.add(createSwitchPanelsButton(), 0);
mageToolbar.add(new javax.swing.JToolBar.Separator(), 1);
if (Plugins.instance.isCounterPluginLoaded()) {
int i = Plugins.instance.getGamesPlayed();
JLabel label = new JLabel(" Games played: " + i);
desktopPane.add(label, JLayeredPane.DEFAULT_LAYER + 1);
label.setVisible(true);
label.setForeground(Color.white);
label.setBounds(0, 0, 180, 30);
}
setGUISize();
setConnectButtonText(NOT_CONNECTED_BUTTON);
SwingUtilities.invokeLater(() -> {
disableButtons();
updateMemUsageTask.execute();
LOGGER.info("Client start up time: " + ((System.currentTimeMillis() - startTime) / 1000 + " seconds"));
if (autoConnect()) {
enableButtons();
} else {
connectDialog.showDialog();
}
setWindowTitle();
});
if (MacFullscreenUtil.isMacOSX()) {
MacFullscreenUtil.enableMacOSFullScreenMode(this);
if (fullscreenMode) {
MacFullscreenUtil.toggleMacOSFullScreenMode(this);
}
}
}
private void bootstrapSetsAndFormats() {
LOGGER.info("Loading sets and formats...");
ConstructedFormats.ensureLists();
}
private void setWindowTitle() {
setTitle(TITLE_NAME + " Client: "
+ (VERSION == null ? "<not available>" : VERSION.toString()) + " Server: "
+ ((SessionHandler.getSession() != null && SessionHandler.isConnected()) ? SessionHandler.getVersionInfo() : NOT_CONNECTED_TEXT));
}
private void updateTooltipContainerSizes() {
JPanel cardPreviewContainer;
BigCard bigCard;
JPanel cardPreviewContainerRotated;
BigCard bigCardRotated;
try {
cardPreviewContainer = (JPanel) UI.getComponent(MageComponents.CARD_PREVIEW_CONTAINER);
bigCard = (BigCard) UI.getComponent(MageComponents.CARD_PREVIEW_PANE);
cardPreviewContainerRotated = (JPanel) UI.getComponent(MageComponents.CARD_PREVIEW_CONTAINER_ROTATED);
bigCardRotated = (BigCard) UI.getComponent(MageComponents.CARD_PREVIEW_PANE_ROTATED);
} catch (InterruptedException e) {
LOGGER.fatal("Can't update tooltip panel sizes");
Thread.currentThread().interrupt();
return;
}
int height = GUISizeHelper.enlargedImageHeight;
int width = (int) ((float) height * (float) 0.64);
bigCard.setSize(width, height);
cardPreviewContainer.setBounds(0, 0, width + 80, height + 30);
bigCardRotated.setSize(height, width + 30);
cardPreviewContainerRotated.setBounds(0, 0, height + 80, width + 100 + 30);
}
private void addTooltipContainer() {
JEditorPane cardInfoPane = (JEditorPane) Plugins.instance.getCardInfoPane();
if (cardInfoPane == null) {
LOGGER.fatal("Can't find card tooltip plugin");
return;
}
cardInfoPane.setLocation(40, 40);
cardInfoPane.setBackground(new Color(0, 0, 0, 255)); // use non-transparent background to full draw, see bug example in #12261
UI.addComponent(MageComponents.CARD_INFO_PANE, cardInfoPane);
MageRoundPane popupContainer = new MageRoundPane();
popupContainer.setLayout(null);
popupContainer.add(cardInfoPane);
popupContainer.setVisible(false);
if (DebugUtil.GUI_POPUP_CONTAINER_DRAW_DEBUG_BORDER) {
popupContainer.setBorder(BorderFactory.createLineBorder(Color.red));
}
desktopPane.add(popupContainer, JLayeredPane.POPUP_LAYER);
UI.addComponent(MageComponents.POPUP_CONTAINER, popupContainer);
JPanel cardPreviewContainer = new JPanel();
cardPreviewContainer.setOpaque(false);
cardPreviewContainer.setLayout(null);
cardPreviewContainer.setVisible(false);
desktopPane.add(cardPreviewContainer, JLayeredPane.POPUP_LAYER);
UI.addComponent(MageComponents.CARD_PREVIEW_CONTAINER, cardPreviewContainer);
BigCard bigCard = new BigCard();
bigCard.setLocation(40, 40);
bigCard.setBackground(new Color(0, 0, 0, 0));
cardPreviewContainer.add(bigCard);
UI.addComponent(MageComponents.CARD_PREVIEW_PANE, bigCard);
JPanel cardPreviewContainerRotated = new JPanel();
cardPreviewContainerRotated.setOpaque(false);
cardPreviewContainerRotated.setLayout(null);
cardPreviewContainerRotated.setVisible(false);
desktopPane.add(cardPreviewContainerRotated, JLayeredPane.POPUP_LAYER);
UI.addComponent(MageComponents.CARD_PREVIEW_CONTAINER_ROTATED, cardPreviewContainerRotated);
BigCard bigCardRotated = new BigCard(true);
bigCardRotated.setLocation(40, 40);
bigCardRotated.setBackground(new Color(0, 0, 0, 0));
cardPreviewContainerRotated.add(bigCardRotated);
UI.addComponent(MageComponents.CARD_PREVIEW_PANE_ROTATED, bigCardRotated);
updateTooltipContainerSizes();
}
private void setGUISizeTooltipContainer() {
try {
int height = GUISizeHelper.enlargedImageHeight;
int width = (int) ((float) height * (float) 0.64);
JPanel cardPreviewContainer = (JPanel) UI.getComponent(MageComponents.CARD_PREVIEW_CONTAINER);
cardPreviewContainer.setBounds(0, 0, width + 80, height + 30);
BigCard bigCard = (BigCard) UI.getComponent(MageComponents.CARD_PREVIEW_PANE);
bigCard.setSize(width, height);
JPanel cardPreviewContainerRotated = (JPanel) UI.getComponent(MageComponents.CARD_PREVIEW_CONTAINER_ROTATED);
cardPreviewContainerRotated.setBounds(0, 0, height + 80, width + 100 + 30);
BigCard bigCardRotated = (BigCard) UI.getComponent(MageComponents.CARD_PREVIEW_PANE_ROTATED);
bigCardRotated.setSize(height, width + 30);
} catch (Exception e) {
LOGGER.warn("Error while changing tooltip container size.", e);
}
}
// Sets background for login screen
private void setBackground() {
if (liteMode || grayMode) {
return;
}
try {
// If user has custom background, use that, otherwise, use theme background
if (Plugins.instance.isThemePluginLoaded() &&
!PreferencesDialog.getCachedValue(PreferencesDialog.KEY_BACKGROUND_IMAGE_DEFAULT, "true").equals("true")) {
backgroundPane = (ImagePanel) Plugins.instance.updateTablePanel(new HashMap<>());
} else {
InputStream is = this.getClass().getResourceAsStream(PreferencesDialog.getCurrentTheme().getLoginBackgroundPath());
BufferedImage background = ImageIO.read(is);
backgroundPane = new ImagePanel(background, ImagePanelStyle.SCALED);
}
backgroundPane.setSize(1024, 768);
desktopPane.add(backgroundPane, JLayeredPane.DEFAULT_LAYER);
} catch (IOException e) {
LOGGER.fatal("Error while setting background.", e);
}
}
public static boolean isChristmasTime(Date currentTime) {
// from december 15 to january 15
Calendar cal = new GregorianCalendar();
cal.setTime(currentTime);
int currentYear = cal.get(Calendar.YEAR);
if (cal.get(Calendar.MONTH) == Calendar.JANUARY) {
currentYear = currentYear - 1;
}
Date chrisFrom = new GregorianCalendar(currentYear, Calendar.DECEMBER, 15).getTime();
Date chrisTo = new GregorianCalendar(currentYear + 1, Calendar.JANUARY, 15 + 1).getTime(); // end of the 15 day
return ((currentTime.equals(chrisFrom) || currentTime.after(chrisFrom))
&& currentTime.before(chrisTo));
}
private void addMageLabel() {
if (liteMode || grayMode) {
return;
}
String filename;
float ratio;
if (isChristmasTime(Calendar.getInstance().getTime())) {
// Christmas logo
LOGGER.info("Ho Ho Ho, Merry Christmas and a Happy New Year");
filename = "/label-xmage-christmas.png";
ratio = 539.0f / 318.0f;
} else {
// standard logo
filename = "/label-xmage.png";
ratio = 509.0f / 288.0f;
}
try {
InputStream is = this.getClass().getResourceAsStream(filename);
if (is != null) {
titleRectangle = new Rectangle(540, (int) (640 / ratio));
BufferedImage image = ImageIO.read(is);
//ImageIcon resized = new ImageIcon(image.getScaledInstance(titleRectangle.width, titleRectangle.height, java.awt.Image.SCALE_SMOOTH));
title = new JLabel();
title.setIcon(new ImageIcon(image));
backgroundPane.setLayout(null);
backgroundPane.add(title);
}
} catch (IOException e) {
LOGGER.fatal("Error while adding mage label.", e);
}
}
private void setAppIcon() {
Image image = ImageManagerImpl.instance.getAppImage();
setIconImage(image);
}
private AbstractButton createSwitchPanelsButton() {
this.switchPanelsButton = new JToggleButton(SWITCH_PANELS_BUTTON_NAME);
this.switchPanelsButton.addItemListener(e -> {
if (e.getStateChange() == ItemEvent.SELECTED) {
createAndShowSwitchPanelsMenu((JComponent) e.getSource(), this.switchPanelsButton);
}
});
this.switchPanelsButton.setFocusable(false);
this.switchPanelsButton.setHorizontalTextPosition(SwingConstants.LEADING);
return this.switchPanelsButton;
}
private void updateSwitchPanelsButton() {
if (this.switchPanelsButton != null) {
int totalCount = getPanelsCount(false);
int activeCount = getPanelsCount(true);
this.switchPanelsButton.setText(SWITCH_PANELS_BUTTON_NAME + String.format(" (%d)", totalCount));
this.switchPanelsButton.setToolTipText(String.format("Click to switch between panels (active panels: %d of %d)",
activeCount,
totalCount
));
}
}
private void createAndShowSwitchPanelsMenu(final JComponent component, final AbstractButton windowButton) {
JPopupMenu menu = new JPopupMenu();
Component[] windows = desktopPane.getComponentsInLayer(javax.swing.JLayeredPane.DEFAULT_LAYER);
MagePaneMenuItem menuItem;
// TODO: sort menu by games, not current component order
// lobby -> table 1 tourny, table 1 draft, table 1 game, table 2...
for (int i = 0; i < windows.length; i++) {
if (windows[i] instanceof MagePane) {
MagePane window = (MagePane) windows[i];
if (window.isVisible()) {
menuItem = new MagePaneMenuItem(window);
menuItem.setFont(GUISizeHelper.menuFont);
menuItem.setState(i == 0);
menuItem.addActionListener(ae -> {
MagePane frame = ((MagePaneMenuItem) ae.getSource()).getFrame();
setActive(frame);
});
//menuItem.setIcon(window.getFrameIcon());
menu.add(menuItem);
}
}
}
menu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
windowButton.setSelected(false);
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
windowButton.setSelected(false);
}
});
menu.show(component, 0, component.getHeight());
}
public static boolean isGameActive() {
return activeFrame instanceof GamePane;
}
public static void setActive(MagePane frame) {
// Always hide not hidden popup window or enlarged card view if a frame is set to active
try {
ActionCallback callback = Plugins.instance.getActionCallback();
if (callback instanceof MageActionCallback) {
((MageActionCallback) callback).hideEnlargedCard();
}
Component container = MageFrame.getUI().getComponent(MageComponents.POPUP_CONTAINER);
if (container.isVisible()) {
container.setVisible(false);
container.repaint();
}
} catch (InterruptedException e) {
LOGGER.fatal("MageFrame error", e);
Thread.currentThread().interrupt();
}
// Nothing to do
if (activeFrame == frame) {
return;
}
// Deactivate current frame if there is one
if (activeFrame != null) {
activeFrame.deactivated();
}
activeFrame = null;
// clean resources
ArrowBuilder.getBuilder().hideAllPanels();
MusicPlayer.stopBGM();
// if no new frame to activate (example: disconnection)
if (frame == null) {
return;
}
LOGGER.debug("Setting " + frame.getTitle() + " active");
activeFrame = frame;
desktopPane.moveToFront(activeFrame);
activeFrame.setBounds(0, 0, desktopPane.getWidth(), desktopPane.getHeight());
activeFrame.revalidate();
activeFrame.activated();
activeFrame.setVisible(true);
if (activeFrame instanceof GamePane) {
ArrowBuilder.getBuilder().showPanel(((GamePane) activeFrame).getGameId());
MusicPlayer.playBGM();
}
}
private void updateCurrentFrameSize() {
if (activeFrame != null) {
activeFrame.setBounds(0, 0, desktopPane.getWidth(), desktopPane.getHeight());
}
}
@Override
public void doLayout() {
super.doLayout();
updateCurrentFrameSize();
}
public static void deactivate(MagePane frame) {
frame.setVisible(false);
setActive(getTopMost(frame));
if (activeFrame != frame) {
frame.deactivated();
}
}
public static MagePane getTopMost(MagePane exclude) {
MagePane topmost = null;
int best = Integer.MAX_VALUE;
for (Component frame : desktopPane.getComponentsInLayer(JLayeredPane.DEFAULT_LAYER)) {
if (frame.isVisible()) {
int z = desktopPane.getComponentZOrder(frame);
if (z < best) {
// Exclude the tables pane if not connected, we never want to show it when not connected
if (frame instanceof MagePane && (SessionHandler.isConnected() || !(frame instanceof TablesPane))) {
best = z;
if (!frame.equals(exclude)) {
topmost = (MagePane) frame;
}
}
}
}
}
return topmost;
}
/**
* Shows a game for a player of the game
*
* @param gameId
* @param playerId
*/
public void showGame(UUID gameId, UUID playerId) {
GamePane gamePane = new GamePane();
desktopPane.add(gamePane, JLayeredPane.DEFAULT_LAYER);
gamePane.setVisible(true);
gamePane.showGame(gameId, playerId);
setActive(gamePane);
}
public void watchGame(UUID gameId) {
for (Component component : desktopPane.getComponents()) {
if (component instanceof GamePane
&& ((GamePane) component).getGameId().equals(gameId)) {
setActive((GamePane) component);
return;
}
}
GamePane gamePane = new GamePane();
desktopPane.add(gamePane, JLayeredPane.DEFAULT_LAYER);
gamePane.setVisible(true);
gamePane.watchGame(gameId);
setActive(gamePane);
}
public void replayGame(UUID gameId) {
GamePane gamePane = new GamePane();
desktopPane.add(gamePane, JLayeredPane.DEFAULT_LAYER);
gamePane.setVisible(true);
gamePane.replayGame(gameId);
setActive(gamePane);
}
public void showDraft(UUID draftId) {
DraftPane draftPane = new DraftPane();
desktopPane.add(draftPane, JLayeredPane.DEFAULT_LAYER);
draftPane.setVisible(true);
draftPane.showDraft(draftId);
setActive(draftPane);
}
public void endDraft(UUID draftId) {
// inform all open draft panes about
for (Component window : desktopPane.getComponentsInLayer(JLayeredPane.DEFAULT_LAYER)) {
if (window instanceof DraftPane) {
DraftPane draftPane = (DraftPane) window;
draftPane.removeDraft();
}
}
}
public void showTournament(UUID tournamentId) {
// existing tourney
TournamentPane tournamentPane = null;
for (Component component : desktopPane.getComponents()) {
if (component instanceof TournamentPane
&& ((TournamentPane) component).getTournamentId().equals(tournamentId)) {
tournamentPane = (TournamentPane) component;
}
}
// new tourney
if (tournamentPane == null) {
tournamentPane = new TournamentPane();
desktopPane.add(tournamentPane, JLayeredPane.DEFAULT_LAYER);
tournamentPane.setVisible(true);
tournamentPane.showTournament(tournamentId);
}
// if user connects on startup then there are possible multiple tables open, so keep only actual
// priority: game > constructing > draft > tourney
// TODO: activate panel by priority
setActive(tournamentPane);
}
public void showGameEndDialog(GameEndView gameEndView) {
GameEndDialog gameEndDialog = new GameEndDialog(gameEndView);
desktopPane.add(gameEndDialog, JLayeredPane.MODAL_LAYER);
gameEndDialog.showDialog();
}
public void showTableWaitingDialog(UUID roomId, UUID tableId, boolean isTournament) {
TableWaitingDialog tableWaitingDialog = new TableWaitingDialog();
desktopPane.add(tableWaitingDialog, JLayeredPane.MODAL_LAYER);
tableWaitingDialog.showDialog(roomId, tableId, isTournament);
}
public static boolean connect(Connection connection) {
boolean result = SessionHandler.connect(connection);
MageFrame.getInstance().setWindowTitle();
return result;
}
public static boolean stopConnecting() {
return SessionHandler.stopConnecting();
}
public boolean autoConnect() {
boolean autoConnectParamValue = startUser != null || Boolean.parseBoolean(PREFS.get("autoConnect", "false"));
boolean status = false;
if (autoConnectParamValue) {
LOGGER.info("Auto-connecting to " + MagePreferences.getServerAddress());
status = performConnect(false);
}
return status;
}
private boolean performConnect(boolean reconnect) {
if (currentConnection == null || !reconnect) {
String server = MagePreferences.getLastServerAddress();
int port = MagePreferences.getLastServerPort();
String userName = MagePreferences.getLastServerUser();
String password = MagePreferences.getLastServerPassword();
String proxyServer = PREFS.get("proxyAddress", "");
int proxyPort = Integer.parseInt(PREFS.get("proxyPort", "0"));
ProxyType proxyType = ProxyType.valueByText(PREFS.get("proxyType", "None"));
String proxyUsername = PREFS.get("proxyUsername", "");
String proxyPassword = PREFS.get("proxyPassword", "");
setCursor(new Cursor(Cursor.WAIT_CURSOR));
currentConnection = new Connection();
currentConnection.setUsername(userName);
currentConnection.setPassword(password);
currentConnection.setHost(server);
currentConnection.setPort(port);
String allMAC = "";
try {
allMAC = Connection.getMAC();
} catch (SocketException ex) {
}
currentConnection.setUserIdStr(System.getProperty("user.name") + ":" + System.getProperty("os.name") + ":" + MagePreferences.getUserNames() + ":" + allMAC);
currentConnection.setProxyType(proxyType);
currentConnection.setProxyHost(proxyServer);
currentConnection.setProxyPort(proxyPort);
currentConnection.setProxyUsername(proxyUsername);
currentConnection.setProxyPassword(proxyPassword);
setUserPrefsToConnection(currentConnection);
}
try {
LOGGER.debug("connecting (auto): " + currentConnection.getProxyType().toString()
+ ' ' + currentConnection.getProxyHost() + ' ' + currentConnection.getProxyPort() + ' ' + currentConnection.getProxyUsername());
if (MageFrame.connect(currentConnection)) {
prepareAndShowServerLobby();
return true;
} else {
showMessage("Unable connect to server: " + SessionHandler.getLastConnectError());
}
} finally {
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
return false;
}
public void setUserPrefsToConnection(Connection connection) {
connection.setUserData(PreferencesDialog.getUserData());
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
popupDebug = new javax.swing.JPopupMenu();
menuDebugTestModalDialog = new javax.swing.JMenuItem();
menuDebugTestCardRenderModesDialog = new javax.swing.JMenuItem();
desktopPane = new MageJDesktop();
mageToolbar = new javax.swing.JToolBar();
btnPreferences = new javax.swing.JButton();
jSeparator4 = new javax.swing.JToolBar.Separator();
btnConnect = new javax.swing.JButton();
jSeparator1 = new javax.swing.JToolBar.Separator();
btnDeckEditor = new javax.swing.JButton();
jSeparator2 = new javax.swing.JToolBar.Separator();
btnCollectionViewer = new javax.swing.JButton();
jSeparator5 = new javax.swing.JToolBar.Separator();
btnSendFeedback = new javax.swing.JButton();
jSeparator6 = new javax.swing.JToolBar.Separator();
btnSymbols = new javax.swing.JButton();
jSeparatorSymbols = new javax.swing.JToolBar.Separator();
btnImages = new javax.swing.JButton();
jSeparatorImages = new javax.swing.JToolBar.Separator();
btnAbout = new javax.swing.JButton();
jSeparator7 = new javax.swing.JToolBar.Separator();
btnDebug = new javax.swing.JButton();
separatorDebug = new javax.swing.JToolBar.Separator();
jMemUsageLabel = new javax.swing.JLabel();
menuDebugTestModalDialog.setText("Test Modal Dialogs");
menuDebugTestModalDialog.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuDebugTestModalDialogActionPerformed(evt);
}
});
popupDebug.add(menuDebugTestModalDialog);
menuDebugTestCardRenderModesDialog.setText("Test Card Render Modes");
menuDebugTestCardRenderModesDialog.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuDebugTestCardRenderModesDialogActionPerformed(evt);
}
});
popupDebug.add(menuDebugTestCardRenderModesDialog);
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setMinimumSize(new java.awt.Dimension(1024, 500));
desktopPane.setBackground(new java.awt.Color(204, 204, 204));
mageToolbar.setFloatable(false);
mageToolbar.setRollover(true);
mageToolbar.setFont(new java.awt.Font("Segoe UI", 0, 48)); // NOI18N
mageToolbar.setMaximumSize(new java.awt.Dimension(614, 60));
mageToolbar.setMinimumSize(new java.awt.Dimension(566, 60));
mageToolbar.setPreferredSize(new java.awt.Dimension(614, 60));
btnPreferences.setIcon(new javax.swing.ImageIcon(getClass().getResource("/menu/preferences.png"))); // NOI18N
btnPreferences.setText("Preferences");
btnPreferences.setToolTipText("By changing the settings in the preferences window you can adjust the look and behaviour of xmage.");
btnPreferences.setFocusable(false);
btnPreferences.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
btnPreferences.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnPreferencesActionPerformed(evt);
}
});
mageToolbar.add(btnPreferences);
mageToolbar.add(jSeparator4);
btnConnect.setIcon(new javax.swing.ImageIcon(getClass().getResource("/menu/connect.png"))); // NOI18N
btnConnect.setToolTipText("Connect to or disconnect from a XMage server.");
btnConnect.setFocusable(false);
btnConnect.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
btnConnect.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnConnectActionPerformed(evt);
}
});
mageToolbar.add(btnConnect);
mageToolbar.add(jSeparator1);
btnDeckEditor.setIcon(new javax.swing.ImageIcon(getClass().getResource("/menu/deck_editor.png"))); // NOI18N