forked from RSCPlus/rscplus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLauncher.java
More file actions
2189 lines (1920 loc) · 81.1 KB
/
Launcher.java
File metadata and controls
2189 lines (1920 loc) · 81.1 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
/**
* rscplus
*
* <p>This file is part of rscplus.
*
* <p>rscplus is free software: you can redistribute it and/or modify it under the terms of the GNU
* General Public License as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* <p>rscplus is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public License along with rscplus. If not,
* see <http://www.gnu.org/licenses/>.
*
* <p>Authors: see <https://github.com/RSCPlus/rscplus>
*/
package Client;
import static Client.ServerExtensions.BINARY_TYPE;
import static Client.ServerExtensions.BinaryInfo;
import static Client.ServerExtensions.Extension;
import static Client.Util.isMacOS;
import static Client.Util.isWindowsOS;
import static Client.Util.osScaleMul;
import Client.Extensions.OpenRSCOfficialUtils;
import Client.Extensions.WorldType;
import Game.Client;
import Game.Game;
import Game.GameApplet;
import Game.SoundEffects;
import com.apple.eawt.Application;
import com.sun.jna.platform.win32.GDI32;
import com.sun.jna.platform.win32.WinDef;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.PopupMenu;
import java.awt.Toolkit;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.font.GlyphVector;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import org.json.JSONArray;
/** Singleton main class which renders a loading window and the game client window. */
public class Launcher extends JFrame implements Runnable {
// Launcher properties
public static final String JAR_NAME = "rscplus.jar";
public static Extension binaryFlavor;
public static Double binaryVersion;
public static String binaryPrefix = "";
public static String appName = "RSCPlus";
public static Extension worldSubscriptionId;
public static File initWorldLock;
public static Map<Extension, Map<WorldType, Boolean>> knownWorldTypes = new LinkedHashMap<>();
public static Map<URI, List<World>> downloadedWorlds =
Collections.synchronizedMap(new LinkedHashMap<>());
public static List<File> subWorldFiles = new ArrayList<>();
public static Set<World> blockedWorlds = new HashSet<>();
private static final Set<LauncherError> launcherWarnings = new HashSet<>();
private static final List<Integer> updatedWorldSubHashes = new ArrayList<>();
private static Integer lastConnHash = null;
private static boolean warnUserWorldChanged = false;
// Singletons
private static Launcher instance;
private static ScaledWindow scaledWindow;
private static ConfigWindow configWindow;
private static WorldMapWindow worldMapWindow;
private static QueueWindow queueWindow;
public static Font controlsFont;
// App icons
public static String iconPath = null;
public static String largeIconPath = null;
public static String smallIconPath = null;
public static String iconAbsolutePath = null;
public static ImageIcon scaled_option_icon = null;
public static ImageIcon icon_warn = null;
public static ImageIcon scaled_icon_warn = null;
private static List<Image> windowIcons = null;
// bank filter/sort icons
public static ImageIcon icon_satchel = null;
public static ImageIcon icon_satchel_time = null;
public static ImageIcon icon_no_satchel = null;
public static ImageIcon icon_runes_weapons_armour = null;
public static ImageIcon icon_lobster_potion = null;
public static ImageIcon icon_herblaw = null;
public static ImageIcon icon_resources_tools = null;
public static ImageIcon icon_tools = null;
public static ImageIcon icon_resources = null;
public static ImageIcon icon_banksearch = null;
public static ImageIcon icon_filter_reset = null;
public static ImageIcon icon_release = null;
public static ImageIcon icon_release_desc = null;
public static ImageIcon icon_item_value = null;
public static ImageIcon icon_item_value_rev = null;
public static ImageIcon icon_alphabetical = null;
public static ImageIcon icon_alphabetical_rev = null;
public static ImageIcon icon_efficient = null;
public static ImageIcon icon_user_custom = null;
// TODO: Replace usage of these with Renderer.drawShadowText
public static ImageIcon icon_filter_text = null;
public static ImageIcon icon_sort_text = null;
public static int numCores;
private JProgressBar m_progressBar;
private JClassLoader m_classLoader;
public static double OSScalingFactor = 1.0;
public static boolean forceDisableNimbus = false;
private Launcher() {
// Empty private constructor to prevent extra instances from being created.
}
/** Renders the launcher progress bar window, then calls {@link #run()}. */
public void init() {
Logger.Info("Starting " + appName);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setBackground(Color.BLACK);
// Set window icons
setIconImages(getWindowIcons());
// Store absolute path to the regular icon for notifications
URL iconURL = getResource(iconPath);
if (iconURL != null) {
try {
iconAbsolutePath = new File(iconURL.getPath()).getCanonicalPath();
} catch (IOException e) {
Logger.Warn("Failed to load icon for usage with notify-send");
}
}
// Set scaled icon used in JOptionPanes
URL optionIconURL = getResource(largeIconPath);
if (optionIconURL != null) {
try {
BufferedImage iconOptionsBI = ImageIO.read(optionIconURL);
scaled_option_icon =
new ImageIcon(
iconOptionsBI.getScaledInstance(
osScaleMul(iconOptionsBI.getWidth()),
osScaleMul(iconOptionsBI.getHeight()),
Image.SCALE_DEFAULT));
} catch (IOException e) {
// No-op
}
}
// Set warning icon
iconURL = getResource("/assets/icon_warn.png");
if (iconURL != null) {
icon_warn = new ImageIcon(iconURL);
// Set scaled warning icon for JOptionPanes
try {
BufferedImage warnIconBI = ImageIO.read(iconURL);
scaled_icon_warn =
new ImageIcon(
warnIconBI.getScaledInstance(
osScaleMul(warnIconBI.getWidth()),
osScaleMul(warnIconBI.getHeight()),
Image.SCALE_DEFAULT));
} catch (IOException e) {
// No-op
}
}
iconURL = getResource("/assets/bank/filter.png");
if (iconURL != null) {
icon_filter_text = new ImageIcon(iconURL);
}
iconURL = getResource("/assets/bank/satchel.png");
if (iconURL != null) {
icon_satchel = new ImageIcon(iconURL);
}
iconURL = getResource("/assets/bank/satchel.time.png");
if (iconURL != null) {
icon_satchel_time = new ImageIcon(iconURL);
}
iconURL = getResource("/assets/bank/no.satchel.png");
if (iconURL != null) {
icon_no_satchel = new ImageIcon(iconURL);
}
iconURL = getResource("/assets/bank/runes.weapons.armour.png");
if (iconURL != null) {
icon_runes_weapons_armour = new ImageIcon(iconURL);
}
iconURL = getResource("/assets/bank/lobster.potion.png");
if (iconURL != null) {
icon_lobster_potion = new ImageIcon(iconURL);
}
iconURL = getResource("/assets/bank/herblaw.png");
if (iconURL != null) {
icon_herblaw = new ImageIcon(iconURL);
}
iconURL = getResource("/assets/bank/resources.tools.png");
if (iconURL != null) {
icon_resources_tools = new ImageIcon(iconURL);
}
iconURL = getResource("/assets/bank/tools.png");
if (iconURL != null) {
icon_tools = new ImageIcon(iconURL);
}
iconURL = getResource("/assets/bank/resources.png");
if (iconURL != null) {
icon_resources = new ImageIcon(iconURL);
}
iconURL = getResource("/assets/bank/magnifying.lens.png");
if (iconURL != null) {
icon_banksearch = new ImageIcon(iconURL);
}
iconURL = getResource("/assets/bank/reset.png");
if (iconURL != null) {
icon_filter_reset = new ImageIcon(iconURL);
}
iconURL = getResource("/assets/bank/sort.png");
if (iconURL != null) {
icon_sort_text = new ImageIcon(iconURL);
}
iconURL = getResource("/assets/bank/release.png");
if (iconURL != null) {
icon_release = new ImageIcon(iconURL);
}
iconURL = getResource("/assets/bank/release.desc.png");
if (iconURL != null) {
icon_release_desc = new ImageIcon(iconURL);
}
iconURL = getResource("/assets/bank/item.value.png");
if (iconURL != null) {
icon_item_value = new ImageIcon(iconURL);
}
iconURL = getResource("/assets/bank/item.value.rev.png");
if (iconURL != null) {
icon_item_value_rev = new ImageIcon(iconURL);
}
iconURL = getResource("/assets/bank/alphabetical.png");
if (iconURL != null) {
icon_alphabetical = new ImageIcon(iconURL);
}
iconURL = getResource("/assets/bank/alphabetical.rev.png");
if (iconURL != null) {
icon_alphabetical_rev = new ImageIcon(iconURL);
}
iconURL = getResource("/assets/bank/efficient.png");
if (iconURL != null) {
icon_efficient = new ImageIcon(iconURL);
}
iconURL = getResource("/assets/bank/user.config.png");
if (iconURL != null) {
icon_user_custom = new ImageIcon(iconURL);
}
// Extract libraries that only work outside the jar
extractJInputNatives();
// Load jf fonts
GameApplet.loadJagexFonts();
// Set size
if (isUsingAppImage()) {
// Make wider to accommodate possible larger download size
getContentPane().setPreferredSize(osScaleMul(new Dimension(350, 32)));
} else {
getContentPane().setPreferredSize(osScaleMul(new Dimension(315, 32)));
}
setTitle(appName + " Launcher");
setResizable(false);
pack();
setLocationRelativeTo(null);
// Add progress bar
m_progressBar = new JProgressBar();
m_progressBar.setStringPainted(true);
m_progressBar.setBorderPainted(true);
m_progressBar.setForeground(Color.GRAY);
m_progressBar.setBackground(Color.BLACK);
if (Util.isUsingFlatLAFTheme()) {
m_progressBar.setFont(new Font(Font.SERIF, Font.PLAIN, osScaleMul(14)));
}
m_progressBar.setString("Initializing");
getContentPane().add(m_progressBar);
setVisible(true);
new Thread(this).start();
}
/** @return {@link List} of {@link Image} objects used for swing window frames icons */
public static synchronized List<Image> getWindowIcons() {
if (windowIcons != null) {
return windowIcons;
}
List<Image> loadedIcons = new ArrayList<>();
URL iconURL = getResource(iconPath);
URL largeIconURL = getResource(largeIconPath);
URL smallIconURL = getResource(smallIconPath);
if (iconURL != null && smallIconURL != null) {
loadedIcons.add(new ImageIcon(iconURL).getImage());
loadedIcons.add(new ImageIcon(largeIconURL).getImage());
loadedIcons.add(new ImageIcon(smallIconURL).getImage());
}
windowIcons = loadedIcons;
return loadedIcons;
}
/** Generates a config file if needed and launches the main client window. */
@Override
public void run() {
if (Settings.UPDATE_CONFIRMATION.get(Settings.currentProfile)) {
Client.firstTimeRunningRSCPlus = true;
String automaticUpdateMessage =
appName
+ " has an automatic update feature.<br/>"
+ "<br/>"
+ "When enabled, "
+ appName
+ " will prompt for and install updates when launching the client.<br/>"
+ "The updates are obtained from our 'Latest' release on GitHub.<br/>"
+ "<br/>"
+ "Would you like to enable this feature?<br/>"
+ "<br/>"
+ "<b>NOTE:</b> This option can be toggled in the Settings interface under the General tab.";
JPanel automaticUpdatePanel = Util.createOptionMessagePanel(automaticUpdateMessage);
int response =
JOptionPane.showConfirmDialog(
this,
automaticUpdatePanel,
appName,
JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE,
scaled_option_icon);
if (response == JOptionPane.YES_OPTION || response == JOptionPane.CLOSED_OPTION) {
Settings.CHECK_UPDATES.put(Settings.currentProfile, true);
JPanel updateInfoPanel =
Util.createOptionMessagePanel(
appName + " is set to check for updates on GitHub at every launch!");
JOptionPane.showMessageDialog(
this, updateInfoPanel, appName, JOptionPane.INFORMATION_MESSAGE, scaled_option_icon);
} else if (response == JOptionPane.NO_OPTION) {
Settings.CHECK_UPDATES.put(Settings.currentProfile, false);
String automaticUpdateDeniedMessage =
appName
+ " will not check for updates automatically.<br/>"
+ "<br/>"
+ "You will not get notified when new releases are available. To update your client, you<br/>"
+ "will need to do it manually by replacing '"
+ JAR_NAME
+ "' in your "
+ appName
+ " directory"
+ (isUsingBinary()
? ",<br/>or re-downloading the application installer.<br/>"
: ".<br/>")
+ "<br/>"
+ "You can enable GitHub updates again in the Settings interface under the General tab.";
JPanel automaticUpdateDeniedPanel =
Util.createOptionMessagePanel(automaticUpdateDeniedMessage);
JOptionPane.showMessageDialog(
this,
automaticUpdateDeniedPanel,
appName,
JOptionPane.INFORMATION_MESSAGE,
scaled_icon_warn);
}
Settings.UPDATE_CONFIRMATION.put(Settings.currentProfile, false);
Settings.save();
}
if (Settings.CHECK_UPDATES.get(Settings.currentProfile)) {
setStatus("Checking for " + appName + " update...");
checkForUpdate(true, false);
}
setStatus("Creating JConfig...");
JConfig config = Game.getInstance().getJConfig();
config.create(Settings.WORLD.get(Settings.currentProfile));
m_classLoader = new JClassLoader(Thread.currentThread().getContextClassLoader());
if (!m_classLoader.fetch("/assets/rsclassic-1091943135.jar")) {
error("Unable to fetch Jar");
}
setStatus("Launching game...");
Game game = Game.getInstance();
try {
Class<?> client = m_classLoader.loadClass(config.getJarClass());
game.setApplet((Applet) client.newInstance());
} catch (Exception e) {
e.printStackTrace();
error("Unable to launch game");
return;
}
setVisible(false);
dispose();
// Ensure current world selection matches previous launch, warn if not
validateWorldSelection();
game.start();
}
/**
* Compares the local value of {@link Settings#VERSION_NUMBER} to the value on the GitHub master
* branch, as well as {@link Launcher#binaryVersion} to the published version for a given binary.
*
* <p>Used to check if there is a newer version of the client or installer available.
*
* @param promptForUpdate if the user should be prompted to accept an application or client update
* @param announceIfUpToDate if a message should be displayed in chat if the client is up-to-date
*/
public void checkForUpdate(boolean promptForUpdate, boolean announceIfUpToDate) {
boolean binaryNeedsUpdate = false;
// Check for application update first when client is running within a binary
if (isUsingBinary()) {
final BinaryInfo binaryInfo = ServerExtensions.getBinaryInfo(binaryFlavor);
final Double latestBinaryVersion = fetchLatestVersionNumber(binaryInfo);
if (latestBinaryVersion != null && binaryVersion < latestBinaryVersion) {
binaryNeedsUpdate = true;
if (promptForUpdate) {
promptForUpdate(binaryInfo, binaryVersion, latestBinaryVersion);
} else {
announceUpdateAvailable("application", binaryVersion, latestBinaryVersion);
}
} else if (binaryVersion.equals(latestBinaryVersion) && announceIfUpToDate) {
announceSameVersion("application", latestBinaryVersion);
}
}
// If no binary update is needed, check for JAR update, unless ran from within an AppImage
// (can't upgrade its JAR)
if (!binaryNeedsUpdate && !isUsingAppImage()) {
final Double latestJARVersion = fetchLatestVersionNumber(null);
if (latestJARVersion != null && Settings.VERSION_NUMBER < latestJARVersion) {
if (promptForUpdate) {
promptForUpdate(null, Settings.VERSION_NUMBER, latestJARVersion);
} else {
announceUpdateAvailable("client", Settings.VERSION_NUMBER, latestJARVersion);
}
} else if (new Double(Settings.VERSION_NUMBER).equals(latestJARVersion)
&& announceIfUpToDate) {
announceSameVersion("client", latestJARVersion);
}
}
}
/**
* Fetches the value of {@link Settings#VERSION_NUMBER} or the binary version number.
*
* <p>Used to check the newest version of the client JAR or binary installer.
*
* @param binaryInfo {@link BinaryInfo} when checking for binary updates or {@code null} for
* client updates
* @return the current version number
*/
private static Double fetchLatestVersionNumber(BinaryInfo binaryInfo) {
try {
double currentVersion = 0.0;
final URL updateURL;
if (binaryInfo == null) {
// In our current client version, we are looking at the source file of Settings.java in the
// main repository in order to parse what the current version numbers are.
updateURL =
new URL(
"https://raw.githubusercontent.com/RSCPlus/rscplus/master/src/Client/Settings.java");
} else {
// For checking binary versions
updateURL = new URL(binaryInfo.getDownloadURI() + binaryInfo.getOSVersionFileName());
}
// Open connection
URLConnection connection = updateURL.openConnection();
connection.setConnectTimeout(3000);
connection.setReadTimeout(3000);
try (BufferedReader in =
new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
if (binaryInfo == null) {
while ((line = in.readLine()) != null) {
if (line.contains("VERSION_NUMBER")) {
currentVersion =
Double.parseDouble(line.substring(line.indexOf('=') + 1, line.indexOf(';')));
Logger.Info(String.format("@|green Current Client Version: %f|@", currentVersion));
break;
}
}
} else {
if ((line = in.readLine()) != null) {
currentVersion = Double.parseDouble(line);
Logger.Info(String.format("@|green Current Application Version: %f|@", currentVersion));
clearWarning(LauncherError.BINARY_UPDATE_CHECK);
}
}
return currentVersion;
}
} catch (Exception e) {
Logger.Warn(
"Error checking latest version for the " + (binaryInfo == null ? "jar" : "binary"));
e.printStackTrace();
Client.displayMessage(
"@dre@Error checking latest "
+ (binaryInfo == null ? "client" : "application")
+ " version",
0);
// For error rendering
if (binaryInfo != null && !hasWarning(LauncherError.BINARY_UPDATE_CHECK)) {
setWarning(LauncherError.BINARY_UPDATE_CHECK);
}
return null;
}
}
/**
* Display messages within the client to update whether an announcement is available or not
*
* @param updateType {@link String} value of {@code application} or {@code client}
* @param currentVersion {@link Double} value indicating the current application or client version
* @param latestVersion {@link Double} value indicating the latest application or client version
*/
private static void announceUpdateAvailable(
String updateType, Double currentVersion, Double latestVersion) {
Client.displayMessage(
"@gre@A new version of the " + binaryPrefix + "RSC+ " + updateType + " is available!",
Client.CHAT_QUEST);
Client.displayMessage(
"The latest version is @gre@" + Util.formatVersion(latestVersion), Client.CHAT_QUEST);
Client.displayMessage(
"~034~ Your version is @red@" + Util.formatVersion(currentVersion), Client.CHAT_QUEST);
if (Settings.CHECK_UPDATES.get(Settings.currentProfile)) {
Client.displayMessage(
"~034~ You will receive the update next time you restart " + appName, Client.CHAT_QUEST);
}
}
/**
* Display a message within the client to inform the user that their application or client is
* up-to-date
*
* @param updateType {@link String} value of {@code application} or {@code client}
* @param latestVersion {@link Double} value indicating the latest application or client version
*/
private static void announceSameVersion(String updateType, Double latestVersion) {
Client.displayMessage(
"Your " + updateType + " is up to date: @gre@" + Util.formatVersion(latestVersion),
Client.CHAT_QUEST);
}
/**
* Prompt the user to update the application or client and perform update tasks if they agreed to
* it and the download process was successful
*
* @param binaryInfo {@link BinaryInfo} when checking for binary updates or {@code null} for
* client updates
* @param currentVersion {@link Double} value indicating the current application or client version
* @param latestVersion {@link Double} value indicating the latest application or client version
*/
private void promptForUpdate(
BinaryInfo binaryInfo, final double currentVersion, final double latestVersion) {
setStatus(appName + " update is available");
final boolean shouldUpdateBinary = binaryInfo != null;
final String updateType = shouldUpdateBinary ? "application" : "client";
String clientUpdateMessage =
"An "
+ appName
+ " "
+ updateType
+ " update is available!<br/>"
+ "<br/>"
+ "Latest: "
+ Util.formatVersion(latestVersion)
+ "<br/>"
+ "Installed: "
+ Util.formatVersion(currentVersion)
+ "<br/>"
+ "<br/>"
+ "Would you like to update now?";
JPanel clientUpdatePanel = Util.createOptionMessagePanel(clientUpdateMessage);
int response =
JOptionPane.showConfirmDialog(
this,
clientUpdatePanel,
appName,
JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE,
scaled_option_icon);
if (response == JOptionPane.YES_OPTION) {
// Perform update here
File downloadLocation = downloadRSCPlusUpdate(binaryInfo);
if (downloadLocation != null) {
String updateSuccessMessage;
if (shouldUpdateBinary && (isWindowsOS() || isMacOS())) {
updateSuccessMessage =
"The installer has finished downloading."
+ "<br/><br/>"
+ appName
+ " will now begin the "
+ (isWindowsOS() ? "auto-" : "")
+ "update process.<br/><br/>"
+ "Once the update is complete, please relaunch the game.";
} else {
updateSuccessMessage =
appName
+ " has been updated successfully!"
+ "<br/><br/>"
+ "The client requires a restart, and will now exit.";
}
JPanel updateSuccessPanel = Util.createOptionMessagePanel(updateSuccessMessage);
JOptionPane.showMessageDialog(
this, updateSuccessPanel, appName, JOptionPane.INFORMATION_MESSAGE, scaled_option_icon);
// Add a shutdown hook to swap AppImages
if (shouldUpdateBinary && isUsingAppImage()) {
Runtime.getRuntime()
.addShutdownHook(
new Thread(
() -> {
final String appImagePath =
System.getenv("OWD")
+ File.separator
+ binaryInfo.getBinaryDownloads().get(BINARY_TYPE.LINUX_APP_IMAGE);
File currentAppImage = new File(appImagePath);
File newAppImage =
new File(appImagePath + BinaryInfo.LINUX_APP_IMAGE_SUFFIX);
try {
// Delete the current AppImage
boolean deleteSuccess = currentAppImage.delete();
if (deleteSuccess) {
// Rename the download AppImage -> current
newAppImage.renameTo(currentAppImage);
// Reapply permissions
Util.execCmd(new String[] {"chmod", "+x", appImagePath});
}
} catch (Exception e) {
Logger.Error(
"Error occurred while attempting to swap to the newly-downloaded AppImage");
e.printStackTrace();
}
}));
} else if (shouldUpdateBinary) {
if (Util.isMacOS()) {
Runtime.getRuntime()
.addShutdownHook(
new Thread(
() -> {
try {
// Attempt to mount the downloaded DMG
Util.execCmd(
new String[] {"open", downloadLocation.getCanonicalPath()});
} catch (IOException ex) {
try {
// Fallback to opening the download location
Util.execCmd(new String[] {"open", downloadLocation.getParent()});
} catch (IOException ex2) {
// Application is closing anyway
}
}
}));
} else if (Util.isWindowsOS()) {
Runtime runTime = Runtime.getRuntime();
try {
// Leverages Innosetup feature to automatically update the application
String command =
downloadLocation.getCanonicalPath()
+ " /SP- /silent /noicons \"/dir=expand:"
+ Settings.sanitizeDirTextValue(Settings.Dir.CONFIG_DIR)
+ "\"";
runTime.exec(command);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
System.exit(0);
} else {
final String updateFailureMessage =
appName
+ " has failed to update"
+ (shouldUpdateBinary ? ".<br/>" : ", please try again later.<br/>")
+ "<br/>"
+ (shouldUpdateBinary
? "If this message persists, try re-downloading and re-installing the application.<br/><br/>"
: "")
+ "Would you like to continue without updating?";
JPanel updateFailurePanel = Util.createOptionMessagePanel(updateFailureMessage);
response =
JOptionPane.showConfirmDialog(
this,
updateFailurePanel,
appName,
JOptionPane.YES_NO_OPTION,
JOptionPane.ERROR_MESSAGE,
scaled_icon_warn);
if (response == JOptionPane.NO_OPTION || response == JOptionPane.CLOSED_OPTION) {
System.exit(0);
}
}
}
}
/**
* Changes the launcher progress bar text and pauses the thread for 5 seconds.
*
* @param text the text to change the progress bar text to
*/
public void error(String text) {
setStatus("Error: " + text);
try {
Thread.sleep(5000);
System.exit(0);
} catch (Exception e) {
}
}
/**
* Changes the launcher progress bar text.
*
* @param text the text to change the progress bar text to
*/
public void setStatus(final String text) {
SwingUtilities.invokeLater(
new Runnable() {
@Override
public void run() {
m_progressBar.setString(text);
}
});
}
/**
* Download the application or client update, prompting the user for a download location when
* necessary
*
* @param binaryInfo {@link BinaryInfo} when download a binary update or {@code null} for client
* updates
* @return a {@link File} for the chosen download location or {@code null} if cancelled
*/
private File downloadRSCPlusUpdate(BinaryInfo binaryInfo) {
boolean success = true;
setStatus("Starting " + appName + " update...");
setProgress(0, 1);
File downloadLocation = null;
// Resolve download URL based on user's system and launch type
try {
final URL url;
if (binaryInfo == null) {
// Only download the new JAR
url = new URL("https://github.com/RSCPlus/rscplus/releases/download/Latest/" + JAR_NAME);
downloadLocation = new File(Settings.Dir.JAR + File.separator + JAR_NAME);
} else {
// Determine download type for the binary / installer
// Note: the following logic assumes that OS-specific definitions exist, since it would only
// reach this code block if being launched from within a binary for the OS type.
final Map<BINARY_TYPE, String> binaryDownloads = binaryInfo.getBinaryDownloads();
if (isUsingAppImage()) {
url =
new URL(
binaryInfo.getDownloadURI() + binaryDownloads.get(BINARY_TYPE.LINUX_APP_IMAGE));
// Save the new AppImage with a suffix - can't hotswap during runtime
downloadLocation =
new File(
System.getenv("OWD")
+ File.separator
+ binaryDownloads.get(BINARY_TYPE.LINUX_APP_IMAGE)
+ BinaryInfo.LINUX_APP_IMAGE_SUFFIX);
} else {
final String osDownload;
if (Util.isMacOS()) {
if (System.getProperty("os.arch").contains("aarch")) {
osDownload = binaryDownloads.get(BINARY_TYPE.MACOS_ARM);
} else {
osDownload = binaryDownloads.get(BINARY_TYPE.MACOS_X64);
}
} else if (Util.isWindowsOS()) {
if (System.getProperty("os.arch").contains("64")) {
osDownload = binaryDownloads.get(BINARY_TYPE.WINDOWS_X64);
} else {
osDownload = binaryDownloads.get(BINARY_TYPE.WINDOWS_X32);
}
} else {
throw new RuntimeException("Could not detect OS for application updates");
}
url = new URL(binaryInfo.getDownloadURI() + osDownload);
JPanel chooseDownloadLocationPanel =
Util.createOptionMessagePanel("Please select a download location for the installer.");
JOptionPane.showMessageDialog(
this,
chooseDownloadLocationPanel,
appName,
JOptionPane.INFORMATION_MESSAGE,
scaled_option_icon);
JFileChooser downloadDirChooser = new JFileChooser();
downloadDirChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
downloadLocation = validateDownloadLocation(downloadDirChooser, osDownload);
// User cancelled file selection, skip the download and return
if (downloadLocation == null) {
return null;
}
}
}
// Open connection, download the file
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(3000);
connection.setReadTimeout(3000);
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
throw new RuntimeException("Connection returned HTTP response: [" + responseCode + "]");
}
int size = connection.getContentLength();
if (size == 0) {
throw new RuntimeException("Connection returned empty content");
}
int offset = 0;
byte[] data = new byte[size];
try (InputStream input = connection.getInputStream()) {
int readSize;
while ((readSize = input.read(data, offset, size - offset)) != -1) {
offset += readSize;
setStatus(
"Updating " + appName + "(" + (offset / 1024) + "KiB / " + (size / 1024) + "KiB)");
setProgress(offset, size);
}
}
if (offset != size) {
success = false;
} else {
try (FileOutputStream output = new FileOutputStream(downloadLocation)) {
output.write(data);
output.close();
setStatus(appName + " update complete");
}
}
} catch (Exception e) {
Logger.Error("Error occurred while downloading the " + appName + " update");
e.printStackTrace();
success = false;
}
return success ? downloadLocation : null;
}
/**
* Validates the chosen binary installer download location, looping until an acceptable location
* is chosen or the user cancels the process
*
* @param downloadDirChooser {@link JFileChooser} instance used for selecting the download
* location
* @param osDownload Location for the OS-specific download, as defined in {@link
* ServerExtensions#getBinaryInfo(Extension)}
* @return {@link File} pointing to the chosen download location
*/
private File validateDownloadLocation(JFileChooser downloadDirChooser, String osDownload) {
int choice = downloadDirChooser.showOpenDialog(this);
if (choice == JFileChooser.APPROVE_OPTION) {
File chosenDir = downloadDirChooser.getSelectedFile();
if (ConfigWindow.validateChosenDirectory(chosenDir)) {
File downloadLocation = new File(chosenDir.getAbsolutePath() + File.separator + osDownload);
return downloadLocation;
} else {
return validateDownloadLocation(downloadDirChooser, osDownload);
}
} else {
return null;
}
}
/**
* Sets the progress value of the launcher progress bar.
*
* @param value the number of tasks that have been completed
* @param total the total number of tasks to complete
*/
public void setProgress(final long value, final long total) {
SwingUtilities.invokeLater(
new Runnable() {
@Override
public void run() {
if (total == 0) {
m_progressBar.setValue(0);
return;
}
m_progressBar.setValue((int) (value * 100 / total));
}
});
}
public JClassLoader getClassLoader() {
return m_classLoader;
}
/* Uses JNA to acquire accurate scale factor for JRE 8 */
public static double getScaleFactor() {
WinDef.HDC hdc = GDI32.INSTANCE.CreateCompatibleDC(null);
if (hdc != null) {
float actual = GDI32.INSTANCE.GetDeviceCaps(hdc, 10);
float logical = GDI32.INSTANCE.GetDeviceCaps(hdc, 117);
GDI32.INSTANCE.DeleteDC(hdc);
if (logical != 0 && logical / actual > 1) {
return (double) logical / actual;
}
}
return Toolkit.getDefaultToolkit().getScreenResolution() / 96.0d;
}
/**
* Validates the current world selection on startup, ensuring that it matches the
* previously-selected world from the prior client launch. When the selection has changed, an
* attempt will be made to locate a world with matching connection settings, in case it was just
* the ordering that changed. If the world cannot be found, a message is presented to the user,
* warning them to double-check the world file. Doing so helps minimize the risk that a user may
* submit their credentials for one game server to another.
*/