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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
|
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::process::Stdio;
use std::sync::Mutex;
use tauri::{Emitter, Manager, State, Window}; // Added Emitter
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::Command;
use serde::Serialize; // Added Serialize
#[cfg(target_os = "windows")]
use std::os::windows::process::CommandExt;
/// Helper macro to emit launcher log events
macro_rules! emit_log {
($window:expr, $msg:expr) => {
let _ = $window.emit("launcher-log", $msg);
println!("[Launcher] {}", $msg);
};
}
mod core;
mod utils;
// Global storage for MS refresh token (not in Account struct to keep it separate)
pub struct MsRefreshTokenState {
pub token: Mutex<Option<String>>,
}
impl Default for MsRefreshTokenState {
fn default() -> Self {
Self::new()
}
}
impl MsRefreshTokenState {
pub fn new() -> Self {
Self {
token: Mutex::new(None),
}
}
}
/// Check if a string contains unresolved placeholders in the form ${...}
///
/// After the replacement phase, if a string still contains ${...}, it means
/// that placeholder variable was not found in the replacements map and is
/// therefore unresolved. We should skip adding such arguments to avoid
/// passing malformed arguments to the game launcher.
fn has_unresolved_placeholder(s: &str) -> bool {
// Look for the opening sequence
if let Some(start_pos) = s.find("${") {
// Check if there's a closing brace after the opening sequence
if s[start_pos + 2..].find('}').is_some() {
// Found a complete ${...} pattern - this is an unresolved placeholder
return true;
}
// Found ${ but no closing } - also treat as unresolved/malformed
return true;
}
// No ${ found - the string is fully resolved
false
}
#[tauri::command]
async fn start_game(
window: Window,
auth_state: State<'_, core::auth::AccountState>,
config_state: State<'_, core::config::ConfigState>,
version_id: String,
) -> Result<String, String> {
emit_log!(
window,
format!("Starting game launch for version: {}", version_id)
);
// Check for active account
emit_log!(window, "Checking for active account...".to_string());
let account = auth_state
.active_account
.lock()
.unwrap()
.clone()
.ok_or("No active account found. Please login first.")?;
emit_log!(
window,
format!("Account found: {}", account.username())
);
let config = config_state.config.lock().unwrap().clone();
emit_log!(window, format!("Java path: {}", config.java_path));
emit_log!(
window,
format!("Memory: {}MB - {}MB", config.min_memory, config.max_memory)
);
// Get App Data Directory (e.g., ~/.local/share/com.dropout.launcher or similar)
// The identifier is set in tauri.conf.json.
// If not accessible, use a specific logic.
let app_handle = window.app_handle();
let game_dir = app_handle
.path()
.app_data_dir()
.map_err(|e| format!("Failed to get app data dir: {}", e))?;
// Ensure game directory exists
tokio::fs::create_dir_all(&game_dir)
.await
.map_err(|e| e.to_string())?;
emit_log!(window, format!("Game directory: {:?}", game_dir));
// 1. Load version (supports both vanilla and modded versions with inheritance)
emit_log!(
window,
format!("Loading version details for {}...", version_id)
);
// First, load the local version to get the original inheritsFrom value
// (before merge clears it)
let original_inherits_from = match core::manifest::load_local_version(&game_dir, &version_id).await {
Ok(local_version) => local_version.inherits_from.clone(),
Err(_) => None,
};
let version_details = core::manifest::load_version(&game_dir, &version_id)
.await
.map_err(|e| e.to_string())?;
emit_log!(
window,
format!(
"Version details loaded: main class = {}",
version_details.main_class
)
);
// Determine the actual minecraft version for client.jar
// (for modded versions, this is the parent vanilla version)
let minecraft_version = original_inherits_from
.unwrap_or_else(|| version_id.clone());
// 2. Prepare download tasks
emit_log!(window, "Preparing download tasks...".to_string());
let mut download_tasks = Vec::new();
// --- Client Jar ---
// Get downloads from version_details (may be inherited)
let downloads = version_details
.downloads
.as_ref()
.ok_or("Version has no downloads information")?;
let client_jar = &downloads.client;
let mut client_path = game_dir.join("versions");
client_path.push(&minecraft_version);
client_path.push(format!("{}.jar", minecraft_version));
download_tasks.push(core::downloader::DownloadTask {
url: client_jar.url.clone(),
path: client_path.clone(),
sha1: client_jar.sha1.clone(),
sha256: None,
});
// --- Libraries ---
println!("Processing libraries...");
let libraries_dir = game_dir.join("libraries");
let mut native_libs_paths = Vec::new(); // Store paths to native jars for extraction
for lib in &version_details.libraries {
if core::rules::is_library_allowed(&lib.rules) {
// 1. Standard Library - check for explicit downloads first
if let Some(downloads) = &lib.downloads {
if let Some(artifact) = &downloads.artifact {
let path_str = artifact
.path
.clone()
.unwrap_or_else(|| format!("{}.jar", lib.name));
let mut lib_path = libraries_dir.clone();
lib_path.push(path_str);
download_tasks.push(core::downloader::DownloadTask {
url: artifact.url.clone(),
path: lib_path,
sha1: artifact.sha1.clone(),
sha256: None,
});
}
// 2. Native Library (classifiers)
// e.g. "natives-linux": { ... }
if let Some(classifiers) = &downloads.classifiers {
// Determine the key based on OS
// Linux usually "natives-linux", Windows "natives-windows", Mac "natives-osx" (or macos)
let os_key = if cfg!(target_os = "linux") {
"natives-linux"
} else if cfg!(target_os = "windows") {
"natives-windows"
} else if cfg!(target_os = "macos") {
"natives-osx" // or natives-macos? check json
} else {
""
};
if let Some(native_artifact_value) = classifiers.get(os_key) {
// Parse it as DownloadArtifact
if let Ok(native_artifact) =
serde_json::from_value::<core::game_version::DownloadArtifact>(
native_artifact_value.clone(),
)
{
let path_str = native_artifact.path.clone().unwrap(); // Natives usually have path
let mut native_path = libraries_dir.clone();
native_path.push(&path_str);
download_tasks.push(core::downloader::DownloadTask {
url: native_artifact.url,
path: native_path.clone(),
sha1: native_artifact.sha1,
sha256: None,
});
native_libs_paths.push(native_path);
}
}
}
} else {
// 3. Library without explicit downloads (mod loader libraries)
// Use Maven coordinate resolution
if let Some(url) =
core::maven::resolve_library_url(&lib.name, None, lib.url.as_deref())
{
if let Some(lib_path) = core::maven::get_library_path(&lib.name, &libraries_dir)
{
download_tasks.push(core::downloader::DownloadTask {
url,
path: lib_path,
sha1: None, // Maven libraries often don't have SHA1 in the JSON
sha256: None,
});
}
}
}
}
}
// --- Assets ---
println!("Fetching asset index...");
let assets_dir = game_dir.join("assets");
let objects_dir = assets_dir.join("objects");
let indexes_dir = assets_dir.join("indexes");
// Get asset index (may be inherited from parent)
let asset_index = version_details
.asset_index
.as_ref()
.ok_or("Version has no asset index information")?;
// Download Asset Index JSON
let asset_index_path = indexes_dir.join(format!("{}.json", asset_index.id));
// Check if index exists or download it
// Note: We need the content of this file to parse it.
// If we just add it to download_tasks, we can't parse it *now*.
// So we must download it immediately (await) before processing objects.
let asset_index_content: String = if asset_index_path.exists() {
tokio::fs::read_to_string(&asset_index_path)
.await
.map_err(|e| e.to_string())?
} else {
println!("Downloading asset index from {}", asset_index.url);
let content = reqwest::get(&asset_index.url)
.await
.map_err(|e| e.to_string())?
.text()
.await
.map_err(|e| e.to_string())?;
// Save it for next time
tokio::fs::create_dir_all(&indexes_dir)
.await
.map_err(|e| e.to_string())?;
tokio::fs::write(&asset_index_path, &content)
.await
.map_err(|e| e.to_string())?;
content
};
#[derive(serde::Deserialize, Debug)]
struct AssetObject {
hash: String,
#[allow(dead_code)]
size: u64,
}
#[derive(serde::Deserialize, Debug)]
struct AssetIndexJson {
objects: std::collections::HashMap<String, AssetObject>,
}
let asset_index_parsed: AssetIndexJson =
serde_json::from_str(&asset_index_content).map_err(|e| e.to_string())?;
println!("Processing {} assets...", asset_index_parsed.objects.len());
for (_name, object) in asset_index_parsed.objects {
let hash = object.hash;
let prefix = &hash[0..2];
let path = objects_dir.join(prefix).join(&hash);
let url = format!(
"https://resources.download.minecraft.net/{}/{}",
prefix, hash
);
download_tasks.push(core::downloader::DownloadTask {
url,
path,
sha1: Some(hash),
sha256: None,
});
}
emit_log!(
window,
format!(
"Total download tasks: {} (Client + Libraries + Assets)",
download_tasks.len()
)
);
// 4. Start Download
emit_log!(
window,
format!(
"Starting downloads with {} concurrent threads...",
config.download_threads
)
);
core::downloader::download_files(
window.clone(),
download_tasks,
config.download_threads as usize,
)
.await
.map_err(|e| e.to_string())?;
emit_log!(window, "All downloads completed successfully".to_string());
// 5. Extract Natives
emit_log!(window, "Extracting native libraries...".to_string());
let natives_dir = game_dir.join("versions").join(&version_id).join("natives");
// Clean old natives if they exist to prevent conflicts
if natives_dir.exists() {
tokio::fs::remove_dir_all(&natives_dir)
.await
.map_err(|e| e.to_string())?;
}
tokio::fs::create_dir_all(&natives_dir)
.await
.map_err(|e| e.to_string())?;
for path in native_libs_paths {
if path.exists() {
println!("Extracting native: {:?}", path);
utils::zip::extract_zip(&path, &natives_dir)?;
}
}
// 6. Construct Classpath
let cp_separator = if cfg!(target_os = "windows") {
";"
} else {
":"
};
let mut classpath_entries = Vec::new();
// Add libraries
for lib in &version_details.libraries {
if core::rules::is_library_allowed(&lib.rules) {
if let Some(downloads) = &lib.downloads {
// Standard library with explicit downloads
if let Some(artifact) = &downloads.artifact {
let path_str = artifact
.path
.clone()
.unwrap_or_else(|| format!("{}.jar", lib.name));
let lib_path = libraries_dir.join(path_str);
classpath_entries.push(lib_path.to_string_lossy().to_string());
}
} else {
// Library without explicit downloads (mod loader libraries)
// Use Maven coordinate resolution
if let Some(lib_path) = core::maven::get_library_path(&lib.name, &libraries_dir) {
classpath_entries.push(lib_path.to_string_lossy().to_string());
}
}
}
}
// Add client jar
classpath_entries.push(client_path.to_string_lossy().to_string());
let classpath = classpath_entries.join(cp_separator);
// 7. Prepare Arguments
let mut args = Vec::new();
let natives_path = natives_dir.to_string_lossy().to_string();
// 7a. JVM Arguments - Parse from version.json for full compatibility
// First add arguments from version.json if available
if let Some(args_obj) = &version_details.arguments {
if let Some(jvm_args) = &args_obj.jvm {
parse_jvm_arguments(jvm_args, &mut args, &natives_path, &classpath);
}
}
// Add memory settings (these override any defaults)
args.push(format!("-Xmx{}M", config.max_memory));
args.push(format!("-Xms{}M", config.min_memory));
// Ensure natives path is set if not already in jvm args
if !args.iter().any(|a| a.contains("-Djava.library.path")) {
args.push(format!("-Djava.library.path={}", natives_path));
}
// Ensure classpath is set if not already
if !args.iter().any(|a| a == "-cp" || a == "-classpath") {
args.push("-cp".to_string());
args.push(classpath.clone());
}
// 7b. Main Class
args.push(version_details.main_class.clone());
// 7c. Game Arguments
// Replacements map
let mut replacements = std::collections::HashMap::new();
replacements.insert("${auth_player_name}", account.username());
replacements.insert("${version_name}", version_id.clone());
replacements.insert("${game_directory}", game_dir.to_string_lossy().to_string());
replacements.insert("${assets_root}", assets_dir.to_string_lossy().to_string());
replacements.insert("${assets_index_name}", asset_index.id.clone());
replacements.insert("${auth_uuid}", account.uuid());
replacements.insert("${auth_access_token}", account.access_token());
replacements.insert("${user_type}", "mojang".to_string());
replacements.insert("${version_type}", "release".to_string());
replacements.insert("${user_properties}", "{}".to_string()); // Correctly pass empty JSON object for user properties
if let Some(minecraft_arguments) = &version_details.minecraft_arguments {
// Legacy string
for part in minecraft_arguments.split_whitespace() {
let mut arg = part.to_string();
for (key, val) in &replacements {
arg = arg.replace(key, val);
}
args.push(arg);
}
} else if let Some(args_obj) = &version_details.arguments {
if let Some(game_args) = &args_obj.game {
// Can be array of strings or objects
if let Some(list) = game_args.as_array() {
for item in list {
if let Some(s) = item.as_str() {
let mut arg = s.to_string();
for (key, val) in &replacements {
arg = arg.replace(key, val);
}
args.push(arg);
} else if let Some(obj) = item.as_object() {
// Check rules
// Simplified: if it has "value", and rules pass.
// For now, assuming rules pass if no "rules" field or simplistic check
// Ideally we should implement a helper to check rules for args just like libs
let allow = if let Some(rules_val) = obj.get("rules") {
if let Ok(rules) = serde_json::from_value::<Vec<core::game_version::Rule>>(
rules_val.clone(),
) {
core::rules::is_library_allowed(&Some(rules))
} else {
true // Parse error, assume allow? or disallow.
}
} else {
true
};
if allow {
if let Some(val) = obj.get("value") {
if let Some(s) = val.as_str() {
let mut arg = s.to_string();
for (key, replacement) in &replacements {
arg = arg.replace(key, replacement);
}
// Skip arguments with unresolved placeholders
if !has_unresolved_placeholder(&arg) {
args.push(arg);
}
} else if let Some(arr) = val.as_array() {
for sub in arr {
if let Some(s) = sub.as_str() {
let mut arg = s.to_string();
for (key, replacement) in &replacements {
arg = arg.replace(key, replacement);
}
// Skip arguments with unresolved placeholders
if !has_unresolved_placeholder(&arg) {
args.push(arg);
}
}
}
}
}
}
}
}
}
}
}
emit_log!(
window,
format!("Preparing to launch game with {} arguments...", args.len())
);
// Debug: Log arguments (only first few to avoid spam)
if args.len() > 10 {
emit_log!(window, format!("First 10 args: {:?}", &args[..10]));
}
// Spawn the process
emit_log!(
window,
format!("Starting Java process: {}", config.java_path)
);
let mut command = Command::new(&config.java_path);
command.args(&args);
command.current_dir(&game_dir); // Run in game directory
command.stdout(Stdio::piped());
command.stderr(Stdio::piped());
// On Windows, use CREATE_NO_WINDOW flag to hide the console window
#[cfg(target_os = "windows")]
{
const CREATE_NO_WINDOW: u32 = 0x08000000;
command.creation_flags(CREATE_NO_WINDOW);
emit_log!(
window,
"Applied CREATE_NO_WINDOW flag for Windows".to_string()
);
}
// Spawn and handle output
let mut child = command
.spawn()
.map_err(|e| format!("Failed to launch java: {}", e))?;
emit_log!(window, "Java process started successfully".to_string());
let stdout = child
.stdout
.take()
.expect("child did not have a handle to stdout");
let stderr = child
.stderr
.take()
.expect("child did not have a handle to stderr");
// Emit launcher log that game is running
emit_log!(
window,
"Game is now running, capturing output...".to_string()
);
let window_rx = window.clone();
tokio::spawn(async move {
let mut reader = BufReader::new(stdout).lines();
while let Ok(Some(line)) = reader.next_line().await {
let _ = window_rx.emit("game-stdout", line);
}
// Emit log when stdout stream ends (game closing)
let _ = window_rx.emit("launcher-log", "Game stdout stream ended");
});
let window_rx_err = window.clone();
let window_exit = window.clone();
tokio::spawn(async move {
let mut reader = BufReader::new(stderr).lines();
while let Ok(Some(line)) = reader.next_line().await {
let _ = window_rx_err.emit("game-stderr", line);
}
// Emit log when stderr stream ends
let _ = window_rx_err.emit("launcher-log", "Game stderr stream ended");
});
// Monitor game process exit
tokio::spawn(async move {
match child.wait().await {
Ok(status) => {
let msg = format!("Game process exited with status: {}", status);
let _ = window_exit.emit("launcher-log", &msg);
let _ = window_exit.emit("game-exited", status.code().unwrap_or(-1));
}
Err(e) => {
let msg = format!("Error waiting for game process: {}", e);
let _ = window_exit.emit("launcher-log", &msg);
}
}
});
Ok(format!("Launched Minecraft {} successfully!", version_id))
}
/// Parse JVM arguments from version.json
fn parse_jvm_arguments(
jvm_args: &serde_json::Value,
args: &mut Vec<String>,
natives_path: &str,
classpath: &str,
) {
let mut replacements = std::collections::HashMap::new();
replacements.insert("${natives_directory}", natives_path.to_string());
replacements.insert("${classpath}", classpath.to_string());
replacements.insert("${launcher_name}", "DropOut".to_string());
replacements.insert("${launcher_version}", env!("CARGO_PKG_VERSION").to_string());
if let Some(list) = jvm_args.as_array() {
for item in list {
if let Some(s) = item.as_str() {
// Simple string argument
let mut arg = s.to_string();
for (key, val) in &replacements {
arg = arg.replace(key, val);
}
// Skip memory args as we set them explicitly
if !arg.starts_with("-Xmx") && !arg.starts_with("-Xms") {
args.push(arg);
}
} else if let Some(obj) = item.as_object() {
// Conditional argument with rules
let allow = if let Some(rules_val) = obj.get("rules") {
if let Ok(rules) =
serde_json::from_value::<Vec<core::game_version::Rule>>(rules_val.clone())
{
core::rules::is_library_allowed(&Some(rules))
} else {
false
}
} else {
true
};
if allow {
if let Some(val) = obj.get("value") {
if let Some(s) = val.as_str() {
let mut arg = s.to_string();
for (key, replacement) in &replacements {
arg = arg.replace(key, replacement);
}
if !arg.starts_with("-Xmx") && !arg.starts_with("-Xms") {
args.push(arg);
}
} else if let Some(arr) = val.as_array() {
for sub in arr {
if let Some(s) = sub.as_str() {
let mut arg = s.to_string();
for (key, replacement) in &replacements {
arg = arg.replace(key, replacement);
}
if !arg.starts_with("-Xmx") && !arg.starts_with("-Xms") {
args.push(arg);
}
}
}
}
}
}
}
}
}
}
#[tauri::command]
async fn get_versions() -> Result<Vec<core::manifest::Version>, String> {
match core::manifest::fetch_version_manifest().await {
Ok(manifest) => Ok(manifest.versions),
Err(e) => Err(e.to_string()),
}
}
/// Check if a version is installed (has client.jar)
#[tauri::command]
async fn check_version_installed(window: Window, version_id: String) -> Result<bool, String> {
let app_handle = window.app_handle();
let game_dir = app_handle
.path()
.app_data_dir()
.map_err(|e| format!("Failed to get app data dir: {}", e))?;
// For modded versions, check the parent vanilla version
let minecraft_version = if version_id.starts_with("fabric-loader-") {
// Format: fabric-loader-X.X.X-1.20.4
version_id.split('-').last().unwrap_or(&version_id).to_string()
} else if version_id.contains("-forge-") {
// Format: 1.20.4-forge-49.0.38
version_id.split("-forge-").next().unwrap_or(&version_id).to_string()
} else {
version_id.clone()
};
let client_jar = game_dir
.join("versions")
.join(&minecraft_version)
.join(format!("{}.jar", minecraft_version));
Ok(client_jar.exists())
}
/// Install a version (download client, libraries, assets) without launching
#[tauri::command]
async fn install_version(
window: Window,
config_state: State<'_, core::config::ConfigState>,
version_id: String,
) -> Result<(), String> {
emit_log!(
window,
format!("Starting installation for version: {}", version_id)
);
let config = config_state.config.lock().unwrap().clone();
let app_handle = window.app_handle();
let game_dir = app_handle
.path()
.app_data_dir()
.map_err(|e| format!("Failed to get app data dir: {}", e))?;
// Ensure game directory exists
tokio::fs::create_dir_all(&game_dir)
.await
.map_err(|e| e.to_string())?;
emit_log!(window, format!("Game directory: {:?}", game_dir));
// Load version (supports both vanilla and modded versions with inheritance)
emit_log!(
window,
format!("Loading version details for {}...", version_id)
);
// First, try to fetch the vanilla version from Mojang and save it locally
let version_details = match core::manifest::load_local_version(&game_dir, &version_id).await {
Ok(v) => v,
Err(_) => {
// Not found locally, fetch from Mojang
emit_log!(window, format!("Fetching version {} from Mojang...", version_id));
let fetched = core::manifest::fetch_vanilla_version(&version_id)
.await
.map_err(|e| e.to_string())?;
// Save the version JSON locally
emit_log!(window, format!("Saving version JSON..."));
core::manifest::save_local_version(&game_dir, &fetched)
.await
.map_err(|e| e.to_string())?;
fetched
}
};
// Now load the full version with inheritance resolved
let version_details = core::manifest::load_version(&game_dir, &version_id)
.await
.map_err(|e| e.to_string())?;
emit_log!(
window,
format!(
"Version details loaded: main class = {}",
version_details.main_class
)
);
// Determine the actual minecraft version for client.jar
let minecraft_version = version_details
.inherits_from
.clone()
.unwrap_or_else(|| version_id.clone());
// Prepare download tasks
emit_log!(window, "Preparing download tasks...".to_string());
let mut download_tasks = Vec::new();
// --- Client Jar ---
let downloads = version_details
.downloads
.as_ref()
.ok_or("Version has no downloads information")?;
let client_jar = &downloads.client;
let mut client_path = game_dir.join("versions");
client_path.push(&minecraft_version);
client_path.push(format!("{}.jar", minecraft_version));
download_tasks.push(core::downloader::DownloadTask {
url: client_jar.url.clone(),
path: client_path.clone(),
sha1: client_jar.sha1.clone(),
sha256: None,
});
// --- Libraries ---
let libraries_dir = game_dir.join("libraries");
for lib in &version_details.libraries {
if core::rules::is_library_allowed(&lib.rules) {
if let Some(downloads) = &lib.downloads {
if let Some(artifact) = &downloads.artifact {
let path_str = artifact
.path
.clone()
.unwrap_or_else(|| format!("{}.jar", lib.name));
let mut lib_path = libraries_dir.clone();
lib_path.push(path_str);
download_tasks.push(core::downloader::DownloadTask {
url: artifact.url.clone(),
path: lib_path,
sha1: artifact.sha1.clone(),
sha256: None,
});
}
// Native Library (classifiers)
if let Some(classifiers) = &downloads.classifiers {
let os_key = if cfg!(target_os = "linux") {
"natives-linux"
} else if cfg!(target_os = "windows") {
"natives-windows"
} else if cfg!(target_os = "macos") {
"natives-osx"
} else {
""
};
if let Some(native_artifact_value) = classifiers.get(os_key) {
if let Ok(native_artifact) =
serde_json::from_value::<core::game_version::DownloadArtifact>(
native_artifact_value.clone(),
)
{
let path_str = native_artifact.path.clone().unwrap();
let mut native_path = libraries_dir.clone();
native_path.push(&path_str);
download_tasks.push(core::downloader::DownloadTask {
url: native_artifact.url,
path: native_path.clone(),
sha1: native_artifact.sha1,
sha256: None,
});
}
}
}
} else {
// Library without explicit downloads (mod loader libraries)
if let Some(url) =
core::maven::resolve_library_url(&lib.name, None, lib.url.as_deref())
{
if let Some(lib_path) = core::maven::get_library_path(&lib.name, &libraries_dir)
{
download_tasks.push(core::downloader::DownloadTask {
url,
path: lib_path,
sha1: None,
sha256: None,
});
}
}
}
}
}
// --- Assets ---
let assets_dir = game_dir.join("assets");
let objects_dir = assets_dir.join("objects");
let indexes_dir = assets_dir.join("indexes");
let asset_index = version_details
.asset_index
.as_ref()
.ok_or("Version has no asset index information")?;
let asset_index_path = indexes_dir.join(format!("{}.json", asset_index.id));
let asset_index_content: String = if asset_index_path.exists() {
tokio::fs::read_to_string(&asset_index_path)
.await
.map_err(|e| e.to_string())?
} else {
emit_log!(window, format!("Downloading asset index..."));
let content = reqwest::get(&asset_index.url)
.await
.map_err(|e| e.to_string())?
.text()
.await
.map_err(|e| e.to_string())?;
tokio::fs::create_dir_all(&indexes_dir)
.await
.map_err(|e| e.to_string())?;
tokio::fs::write(&asset_index_path, &content)
.await
.map_err(|e| e.to_string())?;
content
};
#[derive(serde::Deserialize)]
struct AssetObject {
hash: String,
}
#[derive(serde::Deserialize)]
struct AssetIndexJson {
objects: std::collections::HashMap<String, AssetObject>,
}
let asset_index_parsed: AssetIndexJson =
serde_json::from_str(&asset_index_content).map_err(|e| e.to_string())?;
emit_log!(
window,
format!("Processing {} assets...", asset_index_parsed.objects.len())
);
for (_name, object) in asset_index_parsed.objects {
let hash = object.hash;
let prefix = &hash[0..2];
let path = objects_dir.join(prefix).join(&hash);
let url = format!(
"https://resources.download.minecraft.net/{}/{}",
prefix, hash
);
download_tasks.push(core::downloader::DownloadTask {
url,
path,
sha1: Some(hash),
sha256: None,
});
}
emit_log!(
window,
format!(
"Total download tasks: {} (Client + Libraries + Assets)",
download_tasks.len()
)
);
// Start Download
emit_log!(
window,
format!(
"Starting downloads with {} concurrent threads...",
config.download_threads
)
);
core::downloader::download_files(
window.clone(),
download_tasks,
config.download_threads as usize,
)
.await
.map_err(|e| e.to_string())?;
emit_log!(
window,
format!("Installation of {} completed successfully!", version_id)
);
Ok(())
}
#[tauri::command]
async fn login_offline(
window: Window,
state: State<'_, core::auth::AccountState>,
username: String,
) -> Result<core::auth::Account, String> {
let uuid = core::auth::generate_offline_uuid(&username);
let account = core::auth::Account::Offline(core::auth::OfflineAccount { username, uuid });
*state.active_account.lock().unwrap() = Some(account.clone());
// Save to storage
let app_handle = window.app_handle();
let app_dir = app_handle
.path()
.app_data_dir()
.map_err(|e| e.to_string())?;
let storage = core::account_storage::AccountStorage::new(app_dir);
storage.add_or_update_account(&account, None)?;
Ok(account)
}
#[tauri::command]
async fn get_active_account(
state: State<'_, core::auth::AccountState>,
) -> Result<Option<core::auth::Account>, String> {
Ok(state.active_account.lock().unwrap().clone())
}
#[tauri::command]
async fn logout(window: Window, state: State<'_, core::auth::AccountState>) -> Result<(), String> {
// Get current account UUID before clearing
let uuid = state
.active_account
.lock()
.unwrap()
.as_ref()
.map(|a| a.uuid());
*state.active_account.lock().unwrap() = None;
// Remove from storage
if let Some(uuid) = uuid {
let app_handle = window.app_handle();
let app_dir = app_handle
.path()
.app_data_dir()
.map_err(|e| e.to_string())?;
let storage = core::account_storage::AccountStorage::new(app_dir);
storage.remove_account(&uuid)?;
}
Ok(())
}
#[tauri::command]
async fn get_settings(
state: State<'_, core::config::ConfigState>,
) -> Result<core::config::LauncherConfig, String> {
Ok(state.config.lock().unwrap().clone())
}
#[tauri::command]
async fn save_settings(
state: State<'_, core::config::ConfigState>,
config: core::config::LauncherConfig,
) -> Result<(), String> {
*state.config.lock().unwrap() = config;
state.save()?;
Ok(())
}
#[tauri::command]
async fn start_microsoft_login() -> Result<core::auth::DeviceCodeResponse, String> {
core::auth::start_device_flow().await
}
#[tauri::command]
async fn complete_microsoft_login(
window: Window,
state: State<'_, core::auth::AccountState>,
ms_refresh_state: State<'_, MsRefreshTokenState>,
device_code: String,
) -> Result<core::auth::Account, String> {
// Helper to emit auth progress
let emit_progress = |step: &str| {
let _ = window.emit("auth-progress", step);
};
// 1. Poll (once) for token
emit_progress("Receiving token from Microsoft...");
let token_resp = core::auth::exchange_code_for_token(&device_code).await?;
emit_progress("Token received successfully!");
// Store MS refresh token
let ms_refresh_token = token_resp.refresh_token.clone();
*ms_refresh_state.token.lock().unwrap() = ms_refresh_token.clone();
// 2. Xbox Live Auth
emit_progress("Authenticating with Xbox Live...");
let (xbl_token, uhs) = core::auth::method_xbox_live(&token_resp.access_token).await?;
emit_progress("Xbox Live authentication successful!");
// 3. XSTS Auth
emit_progress("Authenticating with XSTS...");
let xsts_token = core::auth::method_xsts(&xbl_token).await?;
emit_progress("XSTS authentication successful!");
// 4. Minecraft Auth
emit_progress("Authenticating with Minecraft...");
let mc_token = core::auth::login_minecraft(&xsts_token, &uhs).await?;
emit_progress("Minecraft authentication successful!");
// 5. Get Profile
emit_progress("Fetching Minecraft profile...");
let profile = core::auth::fetch_profile(&mc_token).await?;
emit_progress(&format!("Welcome, {}!", profile.name));
// 6. Create Account
let account = core::auth::Account::Microsoft(core::auth::MicrosoftAccount {
username: profile.name,
uuid: profile.id,
access_token: mc_token, // This is the MC Access Token
refresh_token: token_resp.refresh_token.clone(),
expires_at: (std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs()
+ token_resp.expires_in) as i64,
});
// 7. Save to state
*state.active_account.lock().unwrap() = Some(account.clone());
// 8. Save to storage
let app_handle = window.app_handle();
let app_dir = app_handle
.path()
.app_data_dir()
.map_err(|e| e.to_string())?;
let storage = core::account_storage::AccountStorage::new(app_dir);
storage.add_or_update_account(&account, ms_refresh_token)?;
Ok(account)
}
/// Refresh token for current Microsoft account
#[tauri::command]
async fn refresh_account(
window: Window,
state: State<'_, core::auth::AccountState>,
ms_refresh_state: State<'_, MsRefreshTokenState>,
) -> Result<core::auth::Account, String> {
// Get stored MS refresh token
let app_handle = window.app_handle();
let app_dir = app_handle
.path()
.app_data_dir()
.map_err(|e| e.to_string())?;
let storage = core::account_storage::AccountStorage::new(app_dir.clone());
let (_stored_account, ms_refresh) = storage
.get_active_account()
.ok_or("No active account found")?;
let ms_refresh_token = ms_refresh.ok_or("No refresh token available")?;
// Perform full refresh
let (new_account, new_ms_refresh) = core::auth::refresh_full_auth(&ms_refresh_token).await?;
let account = core::auth::Account::Microsoft(new_account);
// Update state
*state.active_account.lock().unwrap() = Some(account.clone());
*ms_refresh_state.token.lock().unwrap() = Some(new_ms_refresh.clone());
// Update storage
storage.add_or_update_account(&account, Some(new_ms_refresh))?;
Ok(account)
}
/// Detect Java installations on the system
#[tauri::command]
async fn detect_java(app_handle: tauri::AppHandle) -> Result<Vec<core::java::JavaInstallation>, String> {
Ok(core::java::detect_all_java_installations(&app_handle))
}
/// Get recommended Java for a specific Minecraft version
#[tauri::command]
async fn get_recommended_java(
required_major_version: Option<u64>,
) -> Result<Option<core::java::JavaInstallation>, String> {
Ok(core::java::get_recommended_java(required_major_version))
}
/// Get Adoptium Java download info
#[tauri::command]
async fn fetch_adoptium_java(
major_version: u32,
image_type: String,
) -> Result<core::java::JavaDownloadInfo, String> {
let img_type = match image_type.to_lowercase().as_str() {
"jdk" => core::java::ImageType::Jdk,
_ => core::java::ImageType::Jre,
};
core::java::fetch_java_release(major_version, img_type).await
}
/// Download and install Adoptium Java
#[tauri::command]
async fn download_adoptium_java(
app_handle: tauri::AppHandle,
major_version: u32,
image_type: String,
custom_path: Option<String>,
) -> Result<core::java::JavaInstallation, String> {
let img_type = match image_type.to_lowercase().as_str() {
"jdk" => core::java::ImageType::Jdk,
_ => core::java::ImageType::Jre,
};
let path = custom_path.map(std::path::PathBuf::from);
core::java::download_and_install_java(&app_handle, major_version, img_type, path).await
}
/// Get available Adoptium Java versions
#[tauri::command]
async fn fetch_available_java_versions() -> Result<Vec<u32>, String> {
core::java::fetch_available_versions().await
}
/// Fetch Java catalog with platform availability (uses cache)
#[tauri::command]
async fn fetch_java_catalog(
app_handle: tauri::AppHandle,
) -> Result<core::java::JavaCatalog, String> {
core::java::fetch_java_catalog(&app_handle, false).await
}
/// Refresh Java catalog (bypass cache)
#[tauri::command]
async fn refresh_java_catalog(
app_handle: tauri::AppHandle,
) -> Result<core::java::JavaCatalog, String> {
core::java::fetch_java_catalog(&app_handle, true).await
}
/// Cancel current Java download
#[tauri::command]
async fn cancel_java_download() -> Result<(), String> {
core::java::cancel_current_download();
Ok(())
}
/// Get pending Java downloads
#[tauri::command]
async fn get_pending_java_downloads(
app_handle: tauri::AppHandle,
) -> Result<Vec<core::downloader::PendingJavaDownload>, String> {
Ok(core::java::get_pending_downloads(&app_handle))
}
/// Resume pending Java downloads
#[tauri::command]
async fn resume_java_downloads(
app_handle: tauri::AppHandle,
) -> Result<Vec<core::java::JavaInstallation>, String> {
core::java::resume_pending_downloads(&app_handle).await
}
/// Get Minecraft versions supported by Fabric
#[tauri::command]
async fn get_fabric_game_versions() -> Result<Vec<core::fabric::FabricGameVersion>, String> {
core::fabric::fetch_supported_game_versions()
.await
.map_err(|e| e.to_string())
}
/// Get available Fabric loader versions
#[tauri::command]
async fn get_fabric_loader_versions() -> Result<Vec<core::fabric::FabricLoaderVersion>, String> {
core::fabric::fetch_loader_versions()
.await
.map_err(|e| e.to_string())
}
/// Get Fabric loaders available for a specific Minecraft version
#[tauri::command]
async fn get_fabric_loaders_for_version(
game_version: String,
) -> Result<Vec<core::fabric::FabricLoaderEntry>, String> {
core::fabric::fetch_loaders_for_game_version(&game_version)
.await
.map_err(|e| e.to_string())
}
/// Install Fabric loader for a specific Minecraft version
#[tauri::command]
async fn install_fabric(
window: Window,
game_version: String,
loader_version: String,
) -> Result<core::fabric::InstalledFabricVersion, String> {
emit_log!(
window,
format!(
"Installing Fabric {} for Minecraft {}...",
loader_version, game_version
)
);
let app_handle = window.app_handle();
let game_dir = app_handle
.path()
.app_data_dir()
.map_err(|e| format!("Failed to get app data dir: {}", e))?;
let result = core::fabric::install_fabric(&game_dir, &game_version, &loader_version)
.await
.map_err(|e| e.to_string())?;
emit_log!(
window,
format!("Fabric installed successfully: {}", result.id)
);
Ok(result)
}
/// List installed Fabric versions
#[tauri::command]
async fn list_installed_fabric_versions(window: Window) -> Result<Vec<String>, String> {
let app_handle = window.app_handle();
let game_dir = app_handle
.path()
.app_data_dir()
.map_err(|e| format!("Failed to get app data dir: {}", e))?;
core::fabric::list_installed_fabric_versions(&game_dir)
.await
.map_err(|e| e.to_string())
}
/// Installed version info
#[derive(serde::Serialize)]
struct InstalledVersion {
id: String,
#[serde(rename = "type")]
version_type: String, // "release", "snapshot", "fabric", "forge", "modpack"
}
/// List all installed versions from the data directory
/// Simply lists all folders in the versions directory without validation
#[tauri::command]
async fn list_installed_versions(window: Window) -> Result<Vec<InstalledVersion>, String> {
let app_handle = window.app_handle();
let game_dir = app_handle
.path()
.app_data_dir()
.map_err(|e| format!("Failed to get app data dir: {}", e))?;
let versions_dir = game_dir.join("versions");
let mut installed = Vec::new();
if !versions_dir.exists() {
return Ok(installed);
}
let mut entries = tokio::fs::read_dir(&versions_dir)
.await
.map_err(|e| e.to_string())?;
while let Some(entry) = entries.next_entry().await.map_err(|e| e.to_string())? {
// Only include directories
if !entry.file_type().await.map_err(|e| e.to_string())?.is_dir() {
continue;
}
let name = entry.file_name().to_string_lossy().to_string();
let version_dir = entry.path();
// Determine version type based on folder name or JSON content
let version_type = if name.starts_with("fabric-loader-") {
"fabric".to_string()
} else if name.contains("-forge") || name.contains("forge-") {
"forge".to_string()
} else {
// Try to read JSON to get type, otherwise guess from name
let json_path = version_dir.join(format!("{}.json", name));
if json_path.exists() {
if let Ok(content) = tokio::fs::read_to_string(&json_path).await {
if let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) {
json.get("type")
.and_then(|t| t.as_str())
.unwrap_or("modpack")
.to_string()
} else {
"modpack".to_string()
}
} else {
"modpack".to_string()
}
} else {
// No JSON file - treat as modpack/custom
"modpack".to_string()
}
};
installed.push(InstalledVersion {
id: name,
version_type,
});
}
// Sort: modded/modpack first, then by version id descending
installed.sort_by(|a, b| {
let a_priority = match a.version_type.as_str() {
"fabric" | "forge" => 0,
"modpack" => 1,
_ => 2,
};
let b_priority = match b.version_type.as_str() {
"fabric" | "forge" => 0,
"modpack" => 1,
_ => 2,
};
match a_priority.cmp(&b_priority) {
std::cmp::Ordering::Equal => b.id.cmp(&a.id), // Descending order
other => other,
}
});
Ok(installed)
}
/// Check if Fabric is installed for a specific version
#[tauri::command]
async fn is_fabric_installed(
window: Window,
game_version: String,
loader_version: String,
) -> Result<bool, String> {
let app_handle = window.app_handle();
let game_dir = app_handle
.path()
.app_data_dir()
.map_err(|e| format!("Failed to get app data dir: {}", e))?;
Ok(core::fabric::is_fabric_installed(
&game_dir,
&game_version,
&loader_version,
))
}
/// Get Minecraft versions supported by Forge
#[tauri::command]
async fn get_forge_game_versions() -> Result<Vec<String>, String> {
core::forge::fetch_supported_game_versions()
.await
.map_err(|e| e.to_string())
}
/// Get available Forge versions for a specific Minecraft version
#[tauri::command]
async fn get_forge_versions_for_game(
game_version: String,
) -> Result<Vec<core::forge::ForgeVersion>, String> {
core::forge::fetch_forge_versions(&game_version)
.await
.map_err(|e| e.to_string())
}
/// Install Forge for a specific Minecraft version
#[tauri::command]
async fn install_forge(
window: Window,
config_state: State<'_, core::config::ConfigState>,
game_version: String,
forge_version: String,
) -> Result<core::forge::InstalledForgeVersion, String> {
emit_log!(
window,
format!(
"Installing Forge {} for Minecraft {}...",
forge_version, game_version
)
);
let app_handle = window.app_handle();
let game_dir = app_handle
.path()
.app_data_dir()
.map_err(|e| format!("Failed to get app data dir: {}", e))?;
// Get Java path from config or detect
let config = config_state.config.lock().unwrap().clone();
let java_path_str = if !config.java_path.is_empty() && config.java_path != "java" {
config.java_path.clone()
} else {
// Try to find a suitable Java installation
let javas = core::java::detect_all_java_installations(&app_handle);
if let Some(java) = javas.first() {
java.path.clone()
} else {
return Err("No Java installation found. Please configure Java in settings.".to_string());
}
};
let java_path = std::path::PathBuf::from(&java_path_str);
emit_log!(window, "Running Forge installer...".to_string());
// Run the Forge installer to properly patch the client
core::forge::run_forge_installer(&game_dir, &game_version, &forge_version, &java_path)
.await
.map_err(|e| format!("Forge installer failed: {}", e))?;
emit_log!(window, "Forge installer completed, creating version profile...".to_string());
// Now create the version JSON
let result = core::forge::install_forge(&game_dir, &game_version, &forge_version)
.await
.map_err(|e| e.to_string())?;
emit_log!(
window,
format!("Forge installed successfully: {}", result.id)
);
Ok(result)
}
#[derive(serde::Serialize)]
struct GithubRelease {
tag_name: String,
name: String,
published_at: String,
body: String,
html_url: String,
}
#[tauri::command]
async fn get_github_releases() -> Result<Vec<GithubRelease>, String> {
let client = reqwest::Client::new();
let res = client
.get("https://api.github.com/repos/HsiangNianian/DropOut/releases")
.header("User-Agent", "DropOut-Launcher")
.send()
.await
.map_err(|e| e.to_string())?;
if !res.status().is_success() {
return Err(format!("GitHub API returned status: {}", res.status()));
}
let releases: Vec<serde_json::Value> = res.json().await.map_err(|e| e.to_string())?;
let mut result = Vec::new();
for r in releases {
if let (Some(tag), Some(name), Some(date), Some(body), Some(url)) = (
r["tag_name"].as_str(),
r["name"].as_str(),
r["published_at"].as_str(),
r["body"].as_str(),
r["html_url"].as_str()
) {
result.push(GithubRelease {
tag_name: tag.to_string(),
name: name.to_string(),
published_at: date.to_string(),
body: body.to_string(),
html_url: url.to_string(),
});
}
}
Ok(result)
}
#[derive(Serialize)]
struct PastebinResponse {
url: String,
}
#[tauri::command]
async fn upload_to_pastebin(
state: State<'_, core::config::ConfigState>,
content: String,
) -> Result<PastebinResponse, String> {
// Check content length limit
if content.len() > 500 * 1024 {
return Err("Log file too large (max 500KB)".to_string());
}
// Extract config values before any async calls to avoid holding MutexGuard across await
let (service, api_key) = {
let config = state.config.lock().unwrap();
(
config.log_upload_service.clone(),
config.pastebin_api_key.clone(),
)
};
let client = reqwest::Client::new();
match service.as_str() {
"pastebin.com" => {
let api_key = api_key
.ok_or("Pastebin API Key not configured in settings")?;
let res = client
.post("https://pastebin.com/api/api_post.php")
.form(&[
("api_dev_key", api_key.as_str()),
("api_option", "paste"),
("api_paste_code", content.as_str()),
("api_paste_private", "1"), // Unlisted
("api_paste_name", "DropOut Launcher Log"),
("api_paste_expire_date", "1W"),
])
.send()
.await
.map_err(|e| e.to_string())?;
if !res.status().is_success() {
return Err(format!("Pastebin upload failed: {}", res.status()));
}
let url = res.text().await.map_err(|e| e.to_string())?;
if url.starts_with("Bad API Request") {
return Err(format!("Pastebin API error: {}", url));
}
Ok(PastebinResponse { url })
}
// Default to paste.rs
_ => {
let res = client
.post("https://paste.rs/")
.body(content)
.send()
.await
.map_err(|e| e.to_string())?;
if !res.status().is_success() {
return Err(format!("paste.rs upload failed: {}", res.status()));
}
let url = res.text().await.map_err(|e| e.to_string())?;
let url = url.trim().to_string();
Ok(PastebinResponse { url })
}
}
}
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_shell::init())
.manage(core::auth::AccountState::new())
.manage(MsRefreshTokenState::new())
.setup(|app| {
let config_state = core::config::ConfigState::new(app.handle());
app.manage(config_state);
// Load saved account on startup
let app_dir = app.path().app_data_dir().unwrap();
let storage = core::account_storage::AccountStorage::new(app_dir);
if let Some((stored_account, ms_refresh)) = storage.get_active_account() {
let account = stored_account.to_account();
let auth_state: State<core::auth::AccountState> = app.state();
*auth_state.active_account.lock().unwrap() = Some(account);
// Store MS refresh token
if let Some(token) = ms_refresh {
let ms_state: State<MsRefreshTokenState> = app.state();
*ms_state.token.lock().unwrap() = Some(token);
}
println!("[Startup] Loaded saved account");
}
// Check for pending Java downloads and notify frontend
let pending = core::java::get_pending_downloads(&app.app_handle());
if !pending.is_empty() {
println!("[Startup] Found {} pending Java download(s)", pending.len());
let _ = app.emit("pending-java-downloads", pending.len());
}
Ok(())
})
.invoke_handler(tauri::generate_handler![
start_game,
get_versions,
check_version_installed,
install_version,
list_installed_versions,
login_offline,
get_active_account,
logout,
get_settings,
save_settings,
start_microsoft_login,
complete_microsoft_login,
refresh_account,
// Java commands
detect_java,
get_recommended_java,
fetch_adoptium_java,
download_adoptium_java,
fetch_available_java_versions,
fetch_java_catalog,
refresh_java_catalog,
cancel_java_download,
get_pending_java_downloads,
resume_java_downloads,
// Fabric commands
get_fabric_game_versions,
get_fabric_loader_versions,
get_fabric_loaders_for_version,
install_fabric,
list_installed_fabric_versions,
is_fabric_installed,
// Forge commands
get_forge_game_versions,
get_forge_versions_for_game,
install_forge,
get_github_releases,
upload_to_pastebin
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
|