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
|
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::process::Stdio;
use tauri::{Emitter, Manager, State, Window}; // Added Emitter
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::Command;
mod core;
mod launcher;
mod utils;
#[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> {
println!("Backend received StartGame for {}", version_id);
// Check for active account
let account = auth_state
.active_account
.lock()
.unwrap()
.clone()
.ok_or("No active account found. Please login first.")?;
let config = config_state.config.lock().unwrap().clone();
// 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())?;
println!("Game Directory: {:?}", game_dir);
// 1. Fetch manifest to find the version URL
let manifest = core::manifest::fetch_version_manifest()
.await
.map_err(|e| e.to_string())?;
// Find the version info
let version_info = manifest
.versions
.iter()
.find(|v| v.id == version_id)
.ok_or_else(|| format!("Version {} not found in manifest", version_id))?;
// 2. Fetch specific version JSON (client.jar info)
let version_url = &version_info.url;
let version_details: core::game_version::GameVersion = reqwest::get(version_url)
.await
.map_err(|e| e.to_string())?
.json()
.await
.map_err(|e| e.to_string())?;
// 3. Prepare download tasks
let mut download_tasks = Vec::new();
// --- Client Jar ---
let client_jar = version_details.downloads.client;
let mut client_path = game_dir.join("versions");
client_path.push(&version_id);
client_path.push(format!("{}.jar", version_id));
download_tasks.push(core::downloader::DownloadTask {
url: client_jar.url,
path: client_path.clone(),
sha1: Some(client_jar.sha1),
});
// --- 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
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: Some(artifact.sha1.clone()),
});
}
// 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: Some(native_artifact.sha1),
});
native_libs_paths.push(native_path);
}
}
}
}
}
}
// --- 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");
// Download Asset Index JSON
let asset_index_path = indexes_dir.join(format!("{}.json", version_details.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 {}",
version_details.asset_index.url
);
let content = reqwest::get(&version_details.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,
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),
});
}
println!(
"Total download tasks (Client + Libs + Assets): {}",
download_tasks.len()
);
// 4. Start Download
core::downloader::download_files(window.clone(), download_tasks)
.await
.map_err(|e| e.to_string())?;
// 5. Extract Natives
println!("Extracting natives...");
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 {
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());
}
}
}
}
// 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 (Simplified for now)
// We inject standard convenient defaults.
// TODO: Parse 'arguments.jvm' from version.json for full compatibility (Mac M1 support etc)
args.push(format!("-Djava.library.path={}", natives_path));
args.push(format!("-Xmx{}M", config.max_memory));
args.push(format!("-Xms{}M", config.min_memory));
args.push("-cp".to_string());
args.push(classpath);
// 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.clone());
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}",
version_details.asset_index.id.clone(),
);
replacements.insert("${auth_uuid}", account.uuid.clone());
replacements.insert("${auth_access_token}", "null".to_string()); // Offline
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);
}
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);
}
args.push(arg);
}
}
}
}
}
}
}
}
}
}
println!("Launching game with {} args...", args.len());
// Debug: Print arguments to help diagnose issues
println!("Launch Args: {:?}", args);
// Spawn the process
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());
// Spawn and handle output
let mut child = command
.spawn()
.map_err(|e| format!("Failed to launch java: {}", e))?;
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");
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);
}
});
let window_rx_err = 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);
}
});
Ok(format!("Launched Minecraft {} successfully!", version_id))
}
#[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()),
}
}
#[tauri::command]
async fn login_offline(
state: State<'_, core::auth::AccountState>,
username: String,
) -> Result<core::auth::OfflineAccount, String> {
let uuid = core::auth::generate_offline_uuid(&username);
let account = core::auth::OfflineAccount { username, uuid };
*state.active_account.lock().unwrap() = Some(account.clone());
Ok(account)
}
#[tauri::command]
async fn get_active_account(
state: State<'_, core::auth::AccountState>,
) -> Result<Option<core::auth::OfflineAccount>, String> {
Ok(state.active_account.lock().unwrap().clone())
}
#[tauri::command]
async fn logout(state: State<'_, core::auth::AccountState>) -> Result<(), String> {
*state.active_account.lock().unwrap() = None;
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(())
}
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_shell::init())
.manage(core::auth::AccountState::new())
.setup(|app| {
let config_state = core::config::ConfigState::new(app.handle());
app.manage(config_state);
Ok(())
})
.invoke_handler(tauri::generate_handler![
start_game,
get_versions,
login_offline,
get_active_account,
logout,
get_settings,
save_settings
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
|