rmcl 0.3.0

A fully featured Minecraft launcher TUI
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
// state machine and input handling for the new instance wizard.
// flow: Name -> Loader -> Version -> LoaderVersion -> Confirm
// version lists are fetched lazily from the network when you reach that step.

use crate::instance::{
    loader::{GameVersion, get_installer},
    models::ModLoader,
};
use crate::tui::widgets::instances;
use crossterm::event::{KeyCode, KeyEvent};
use std::sync::LazyLock;
use std::sync::{Arc, Mutex};
use tui_prompts::{FocusState, State as PromptState, TextState};

pub(crate) static WIZARD_STATE: LazyLock<Arc<Mutex<WizardState>>> =
    LazyLock::new(|| Arc::new(Mutex::new(WizardState::default())));
// populated on confirm, consumed by the main event loop to actually create the instance
pub(crate) static WIZARD_RESULT: LazyLock<Arc<Mutex<Option<WizardParams>>>> =
    LazyLock::new(|| Arc::new(Mutex::new(None)));

#[derive(Debug, Clone)]
pub struct WizardParams {
    pub name: String,
    pub game_version: String,
    pub loader: ModLoader,
    pub loader_version: Option<String>,
}

#[derive(Debug, Default, Clone, PartialEq)]
pub enum WizardStep {
    #[default]
    Name,
    Version,
    Loader,
    LoaderVersion,
    Confirm,
}

#[derive(Debug, Clone, Default)]
pub enum LoadState<T> {
    #[default]
    Idle,
    Loading,
    Loaded(T),
    Error(String),
}

#[derive(Debug, Clone)]
pub struct WizardState {
    pub step: WizardStep,
    pub name_state: TextState<'static>,
    pub versions: LoadState<Vec<GameVersion>>,
    pub version_idx: usize,
    pub show_snapshots: bool,
    pub loader_idx: usize,
    pub loader_versions: LoadState<Vec<String>>,
    pub loader_version_idx: usize,
    pub version_search: crate::tui::widgets::search::SearchState,
}

impl Default for WizardState {
    fn default() -> Self {
        Self {
            step: WizardStep::Name,
            name_state: TextState::new().with_focus(FocusState::Focused),
            versions: LoadState::Idle,
            version_idx: 0,
            show_snapshots: false,
            loader_idx: 0,
            loader_versions: LoadState::Idle,
            loader_version_idx: 0,
            version_search: crate::tui::widgets::search::SearchState::default(),
        }
    }
}

impl WizardState {
    pub fn reset(&mut self) {
        *self = WizardState::default();
    }

    pub fn selected_version(&self) -> Option<&GameVersion> {
        if let LoadState::Loaded(ref versions) = self.versions {
            let visible: Vec<_> = versions
                .iter()
                .filter(|v| self.show_snapshots || v.stable)
                .collect();
            visible.get(self.version_idx).copied()
        } else {
            None
        }
    }

    pub fn selected_loader(&self) -> ModLoader {
        const LOADERS: [ModLoader; 5] = [
            ModLoader::Vanilla,
            ModLoader::Fabric,
            ModLoader::Forge,
            ModLoader::NeoForge,
            ModLoader::Quilt,
        ];
        LOADERS[self.loader_idx % 5]
    }

    pub fn selected_loader_version(&self) -> Option<String> {
        if let LoadState::Loaded(ref versions) = self.loader_versions {
            versions.get(self.loader_version_idx).cloned()
        } else {
            None
        }
    }
}

pub fn handle_key(key_event: &KeyEvent, instances_state: &mut instances::State) {
    let mut state = match WIZARD_STATE.lock() {
        Ok(state) => state,
        Err(e) => {
            tracing::error!("Wizard state lock poisoned: {}", e);
            instances_state.show_popup = false;
            return;
        }
    };

    match state.step {
        WizardStep::Name => handle_name_key(&mut state, key_event, instances_state),
        WizardStep::Version => handle_version_key(&mut state, key_event, instances_state),
        WizardStep::Loader => handle_loader_key(&mut state, key_event, instances_state),
        WizardStep::LoaderVersion => {
            handle_loader_version_key(&mut state, key_event, instances_state)
        }
        WizardStep::Confirm => handle_confirm_key(&mut state, key_event, instances_state),
    }
}

pub fn take_result() -> Option<WizardParams> {
    match WIZARD_RESULT.lock() {
        Ok(mut r) => r.take(),
        Err(_) => None,
    }
}

fn handle_name_key(
    state: &mut WizardState,
    key_event: &KeyEvent,
    instances_state: &mut instances::State,
) {
    match key_event.code {
        KeyCode::Esc => {
            close_popup(state, instances_state);
        }
        KeyCode::Enter => {
            if state.name_state.value().trim().is_empty() {
                return;
            }
            state.step = WizardStep::Loader;
        }
        _ => {
            state.name_state.handle_key_event(*key_event);
        }
    }
}

fn handle_version_key(
    state: &mut WizardState,
    key_event: &KeyEvent,
    instances_state: &mut instances::State,
) {
    // Search mode: route char input to search query
    if state.version_search.active {
        match key_event.code {
            KeyCode::Esc => {
                state.version_search.deactivate();
                clamp_version_index(state);
                return;
            }
            KeyCode::Backspace => {
                state.version_search.pop();
                clamp_version_index(state);
                return;
            }
            KeyCode::Char('j') | KeyCode::Down => {
                // fall through to navigation below
            }
            KeyCode::Char('k') | KeyCode::Up => {
                // fall through to navigation below
            }
            KeyCode::Char(c) => {
                state.version_search.push(c);
                state.version_idx = 0; // reset to top of filtered list
                return;
            }
            _ => {}
        }
    }

    let visible_count = visible_versions(state).len();

    match key_event.code {
        KeyCode::Esc => {
            close_popup(state, instances_state);
        }
        KeyCode::Left | KeyCode::Char('h') if !state.version_search.active => {
            state.step = WizardStep::Loader;
        }
        KeyCode::Char('j') | KeyCode::Down if visible_count > 0 => {
            state.version_idx = (state.version_idx + 1).min(visible_count.saturating_sub(1));
        }
        KeyCode::Char('k') | KeyCode::Up => {
            state.version_idx = state.version_idx.saturating_sub(1);
        }
        KeyCode::Char('s') if !state.version_search.active => {
            state.show_snapshots = !state.show_snapshots;
            clamp_version_index(state);
        }
        KeyCode::Char('/') if !state.version_search.active => {
            state.version_search.activate();
            state.version_idx = 0;
        }
        KeyCode::Enter | KeyCode::Right | KeyCode::Char('l') if !state.version_search.active => {
            if state.selected_version().is_none() {
                return;
            }
            state.loader_versions = LoadState::Idle;
            state.loader_version_idx = 0;
            if state.selected_loader() == ModLoader::Vanilla {
                state.step = WizardStep::Confirm;
            } else {
                state.step = WizardStep::LoaderVersion;
                let game_version = state.selected_version().map(|v| v.id.clone());
                let loader = state.selected_loader();
                if let Some(gv) = game_version {
                    ensure_loader_versions_loaded(state, loader, gv);
                }
            }
        }
        KeyCode::Enter if state.version_search.active => {
            state.version_search.active = false;
        }
        _ => {}
    }
}

fn handle_loader_key(
    state: &mut WizardState,
    key_event: &KeyEvent,
    instances_state: &mut instances::State,
) {
    match key_event.code {
        KeyCode::Esc => close_popup(state, instances_state),
        KeyCode::Left | KeyCode::Char('h') => state.step = WizardStep::Name,
        KeyCode::Char('j') | KeyCode::Down => {
            state.loader_idx = (state.loader_idx + 1).min(4);
        }
        KeyCode::Char('k') | KeyCode::Up => {
            state.loader_idx = state.loader_idx.saturating_sub(1);
        }
        KeyCode::Enter | KeyCode::Right | KeyCode::Char('l') => {
            state.versions = LoadState::Idle;
            state.version_idx = 0;
            state.version_search.deactivate();
            state.version_search.active = false;
            state.step = WizardStep::Version;
            ensure_versions_loaded(state);
        }
        _ => {}
    }
}

fn handle_loader_version_key(
    state: &mut WizardState,
    key_event: &KeyEvent,
    instances_state: &mut instances::State,
) {
    if state.selected_loader() == ModLoader::Vanilla {
        state.step = WizardStep::Confirm;
        return;
    }

    let version_count = match &state.loader_versions {
        LoadState::Loaded(versions) => versions.len(),
        _ => 0,
    };

    match key_event.code {
        KeyCode::Esc => close_popup(state, instances_state),
        KeyCode::Left | KeyCode::Char('h') => state.step = WizardStep::Version,
        KeyCode::Char('j') | KeyCode::Down if version_count > 0 => {
            state.loader_version_idx =
                (state.loader_version_idx + 1).min(version_count.saturating_sub(1));
        }
        KeyCode::Char('k') | KeyCode::Up => {
            state.loader_version_idx = state.loader_version_idx.saturating_sub(1);
        }
        KeyCode::Enter | KeyCode::Right | KeyCode::Char('l') => {
            if state.selected_loader_version().is_none() {
                return;
            }
            state.step = WizardStep::Confirm;
        }
        _ => {}
    }
}

fn handle_confirm_key(
    state: &mut WizardState,
    key_event: &KeyEvent,
    instances_state: &mut instances::State,
) {
    match key_event.code {
        KeyCode::Esc => close_popup(state, instances_state),
        KeyCode::Left | KeyCode::Char('h') => {
            if state.selected_loader() == ModLoader::Vanilla {
                state.step = WizardStep::Version;
            } else {
                state.step = WizardStep::LoaderVersion;
            }
        }
        KeyCode::Enter => {
            let selected_version = match state.selected_version() {
                Some(version) => version.id.clone(),
                None => return,
            };

            let params = WizardParams {
                name: state.name_state.value().trim().to_string(),
                game_version: selected_version,
                loader: state.selected_loader(),
                loader_version: if state.selected_loader() == ModLoader::Vanilla {
                    None
                } else {
                    state.selected_loader_version()
                },
            };

            match WIZARD_RESULT.lock() {
                Ok(mut result) => {
                    *result = Some(params);
                }
                Err(e) => {
                    tracing::error!("Wizard result lock poisoned: {}", e);
                }
            }

            close_popup(state, instances_state);
        }
        _ => {}
    }
}

fn close_popup(state: &mut WizardState, instances_state: &mut instances::State) {
    state.reset();
    instances_state.show_popup = false;
}

pub(crate) fn visible_versions(state: &WizardState) -> Vec<GameVersion> {
    let q = state.version_search.query.to_lowercase();
    match &state.versions {
        LoadState::Loaded(versions) => versions
            .iter()
            .filter(|v| state.show_snapshots || v.stable)
            .filter(|v| q.is_empty() || v.id.to_lowercase().contains(&q))
            .cloned()
            .collect(),
        _ => Vec::new(),
    }
}

pub(crate) fn clamp_version_index(state: &mut WizardState) {
    let count = visible_versions(state).len();
    if count == 0 {
        state.version_idx = 0;
    } else if state.version_idx >= count {
        state.version_idx = count.saturating_sub(1);
    }
}

pub(crate) fn clamp_loader_version_index(state: &mut WizardState) {
    if let LoadState::Loaded(versions) = &state.loader_versions {
        if versions.is_empty() {
            state.loader_version_idx = 0;
        } else if state.loader_version_idx >= versions.len() {
            state.loader_version_idx = versions.len().saturating_sub(1);
        }
    } else {
        state.loader_version_idx = 0;
    }
}

// only fires on the Idle -> Loading transition to avoid spamming requests.
// the spawned task writes results back into WIZARD_STATE when done.
pub(crate) fn ensure_versions_loaded(state: &mut WizardState) {
    if !matches!(state.versions, LoadState::Idle) {
        return;
    }

    state.versions = LoadState::Loading;
    let versions_arc = WIZARD_STATE.clone();
    let loader = state.selected_loader();
    tokio::spawn(async move {
        let client = crate::net::HttpClient::new();
        let installer = get_installer(loader);
        match installer.get_game_versions(&client).await {
            Ok(mut versions) => match versions_arc.lock() {
                Ok(mut s) => {
                    sort_versions_semver(&mut versions);
                    s.versions = LoadState::Loaded(versions);
                    clamp_version_index(&mut s);
                }
                Err(e) => {
                    tracing::error!("Wizard state lock poisoned: {}", e);
                }
            },
            Err(e) => match versions_arc.lock() {
                Ok(mut s) => {
                    s.versions = LoadState::Error(e.to_string());
                }
                Err(lock_error) => {
                    tracing::error!("Wizard state lock poisoned: {}", lock_error);
                }
            },
        }
    });
}

pub(crate) fn ensure_loader_versions_loaded(
    state: &mut WizardState,
    loader: ModLoader,
    game_version: String,
) {
    if !matches!(state.loader_versions, LoadState::Idle) {
        return;
    }

    state.loader_versions = LoadState::Loading;
    let versions_arc = WIZARD_STATE.clone();
    tokio::spawn(async move {
        let client = crate::net::HttpClient::new();
        let installer = get_installer(loader);
        match installer.get_versions(&client, &game_version).await {
            Ok(versions) => match versions_arc.lock() {
                Ok(mut s) => {
                    s.loader_versions = LoadState::Loaded(versions);
                    clamp_loader_version_index(&mut s);
                }
                Err(e) => {
                    tracing::error!("Wizard state lock poisoned: {}", e);
                }
            },
            Err(e) => match versions_arc.lock() {
                Ok(mut s) => {
                    s.loader_versions = LoadState::Error(e.to_string());
                }
                Err(lock_error) => {
                    tracing::error!("Wizard state lock poisoned: {}", lock_error);
                }
            },
        }
    });
}

// quick and dirty semver compare. doesn't handle pre-release tags or anything
// fancy, just splits on dots and compares numerically. good enough for mc versions.
fn compare_semver(a: &str, b: &str) -> std::cmp::Ordering {
    let parse_parts = |s: &str| -> Vec<u64> {
        s.split('.')
            .map(|p| p.parse::<u64>().unwrap_or(0))
            .collect()
    };
    let a_parts = parse_parts(a);
    let b_parts = parse_parts(b);
    for (ap, bp) in a_parts.iter().zip(b_parts.iter()) {
        match ap.cmp(bp) {
            std::cmp::Ordering::Equal => continue,
            other => return other,
        }
    }
    a_parts.len().cmp(&b_parts.len())
}

fn sort_versions_semver(versions: &mut [GameVersion]) {
    versions.sort_by(|a, b| compare_semver(&b.id, &a.id));
}