flatland3-gfx 0.2.26

Flatland3 Macroquad + egui graphical play client
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
//! Macroquad + egui play loop for Flatland3.

use std::net::SocketAddr;
use std::time::Instant;

use clap::Parser;
use flatland_client_lib::{default_game_server_addr, load_client_settings};
use flatland_client_ui::{
    ActiveOverlay, InputAction, UiKeyCode, UiKeyEvent, UiKeyEventKind, UiKeyModifiers,
    UiMouseButton, UiPointerEvent,
};
use flatland_gfx_engine::{
    blocks_map_click, blocks_map_zoom, drain_pending_input, is_map_zoom_key, letter_key_held,
    menu_blocking, route_editor_active, screen_to_world, zoom_from_input, DisconnectGate,
    GfxInputResult, GfxRenderer,
};
use flatland_play_loop::{
    build_play_hud, movement_interval_elapsed, should_dispatch_to_net, PlayHudInput, PlayLocalState,
};
use flatland_protocol::ChatChannel;
use macroquad::prelude::*;

use crate::network::{ConnectionUi, GfxNet, NetCmd};
use crate::onboarding;
use crate::window_prefs::{apply_saved_position, capture_window_geometry, save_window_geometry};

#[derive(Debug, Clone, Parser)]
pub struct GfxPlayArgs {
    #[arg(short, long)]
    pub name: Option<String>,

    #[arg(long, default_value_t = default_game_server_addr())]
    pub server: SocketAddr,

    #[arg(long)]
    pub no_reconnect: bool,

    /// Skip automatic asset sync before connecting
    #[arg(long)]
    pub skip_asset_sync: bool,
}

enum SessionEnd {
    /// Window closed / process exit path.
    Quit,
    /// Return to character select (session kept).
    SwitchCharacter,
    /// Session revoked — return to login.
    Logout,
    /// Lost game connection — return to login gate (credentials kept).
    Disconnected,
}

pub async fn run(args: GfxPlayArgs) -> anyhow::Result<()> {
    let keys = load_client_settings().keys;
    let mut renderer = GfxRenderer::init().await;
    let mut window_position_applied = false;
    let mut last_window_save = Instant::now();
    let mut last_saved_geometry = capture_window_geometry();
    let mut force_character_select = false;
    let mut status_hint: Option<String> = None;

    loop {
        let chosen = onboarding::run(onboarding::OnboardingOpts {
            preferred_name: args.name.as_deref(),
            force_character_select,
            status_hint: status_hint.take(),
        })
        .await?;
        force_character_select = false;

        let end = run_play_session(
            args.clone(),
            chosen,
            &keys,
            &mut renderer,
            &mut window_position_applied,
            &mut last_window_save,
            &mut last_saved_geometry,
        )
        .await?;

        match end {
            SessionEnd::Quit => break,
            SessionEnd::SwitchCharacter => {
                force_character_select = true;
            }
            SessionEnd::Logout => {
                let rt = tokio::runtime::Builder::new_multi_thread()
                    .enable_all()
                    .build()?;
                if let Err(err) = rt.block_on(flatland_cli::session_auth::logout()) {
                    eprintln!("flatland3-gfx: logout: {err:#}");
                }
            }
            SessionEnd::Disconnected => {
                status_hint = Some(
                    "Disconnected from the game server — sign in or pick a character to retry."
                        .into(),
                );
            }
        }
    }

    save_window_geometry(capture_window_geometry());
    renderer.flush_ui_prefs();
    Ok(())
}

async fn run_play_session(
    args: GfxPlayArgs,
    chosen: Option<flatland_cli::characters::CharacterSummary>,
    keys: &flatland_client_lib::ClientKeyBindings,
    renderer: &mut GfxRenderer,
    window_position_applied: &mut bool,
    last_window_save: &mut Instant,
    last_saved_geometry: &mut flatland_client_lib::GfxWindowPrefs,
) -> anyhow::Result<SessionEnd> {
    let (net, ready_rx) = GfxNet::spawn_connecting(args, chosen)?;
    // Keep painting while the net thread syncs assets / connects — blocking here
    // used to freeze the window on a blank "spinner" after character select.
    loop {
        match ready_rx.try_recv() {
            Ok(Ok(())) => break,
            Ok(Err(err)) => {
                // Show a retry gate instead of killing the whole process.
                let msg = err.to_string();
                loop {
                    let gate = DisconnectGate {
                        reconnecting: false,
                        attempt: 0,
                        next_secs: 0.0,
                        reason: Some("failed to connect"),
                        last_error: Some(msg.as_str()),
                    };
                    renderer.draw_offline_gate(gate);
                    let menu_actions = renderer.take_menu_actions();
                    if menu_actions.return_to_login
                        || menu_actions.logout
                        || menu_actions.retry_connect
                        || is_key_pressed(KeyCode::Escape)
                        || is_key_pressed(KeyCode::R)
                    {
                        drop(net);
                        return Ok(SessionEnd::Disconnected);
                    }
                    if is_key_pressed(KeyCode::Q) {
                        drop(net);
                        return Ok(SessionEnd::Quit);
                    }
                    next_frame().await;
                }
            }
            Err(std::sync::mpsc::TryRecvError::Empty) => {}
            Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                anyhow::bail!("gfx network thread exited before ready");
            }
        }
        clear_background(Color::from_rgba(8, 9, 12, 255));
        egui_macroquad::ui(|ctx| {
            flatland_gfx_engine::configure_egui(ctx);
            let theme = flatland_gfx_engine::GfxTheme::default();
            egui::Area::new(egui::Id::new("gfx_connecting"))
                .anchor(egui::Align2::CENTER_CENTER, egui::vec2(0.0, 0.0))
                .show(ctx, |ui| {
                    ui.vertical_centered(|ui| {
                        ui.add(egui::Spinner::new().size(28.0));
                        ui.add_space(10.0);
                        ui.colored_label(theme.accent, "Connecting to game…");
                        ui.label(
                            egui::RichText::new("Syncing sprites / opening session")
                                .color(theme.text_muted)
                                .italics(),
                        );
                    });
                });
        });
        egui_macroquad::draw();
        next_frame().await;
    }

    // Sync finished before ready — reload catalog now so paperdolls/sprites appear
    // immediately (init ran before the net thread downloaded the bundle).
    if let Some(local) = flatland_client_lib::read_local_state() {
        renderer
            .maybe_reload_sprites_for_publish_rev(0, local.publish_rev)
            .await;
    } else if let Some(rev) = flatland_client_lib::read_repo_publish_rev() {
        renderer.maybe_reload_sprites_for_publish_rev(0, rev).await;
    }

    let mut local = PlayLocalState::new(keys.clone());
    renderer.hud_view = local.hud_view;
    let mut movement_sent_at = Instant::now();
    // Suppress hotkeys until letter keys from login are released (e.g. `i`/`l` in passwords).
    let mut suppress_login_keys = true;
    drain_pending_input();

    'play: loop {
        let Some(snapshot) = net.snapshot() else {
            let gate = DisconnectGate {
                reconnecting: false,
                attempt: 0,
                next_secs: 0.0,
                reason: Some("network thread stopped"),
                last_error: Some("No live session — return to login or restart."),
            };
            renderer.draw_offline_gate(gate);
            let menu_actions = renderer.take_menu_actions();
            if menu_actions.return_to_login || menu_actions.logout || is_key_pressed(KeyCode::Escape)
            {
                net.send(NetCmd::Shutdown);
                drop(net);
                return Ok(SessionEnd::Disconnected);
            }
            if menu_actions.retry_connect || is_key_pressed(KeyCode::R) {
                net.send(NetCmd::Shutdown);
                drop(net);
                return Ok(SessionEnd::Disconnected);
            }
            next_frame().await;
            continue;
        };
        let state = &snapshot.game;
        let disconnect_gate = match &snapshot.presentation.connection {
            ConnectionUi::Connected if state.connected => None,
            ConnectionUi::Connected => Some(DisconnectGate {
                reconnecting: true,
                attempt: 0,
                next_secs: 1.0,
                reason: state.disconnect_reason.as_deref(),
                last_error: None,
            }),
            ConnectionUi::Reconnecting {
                attempt,
                reason,
                next_secs,
                last_error,
            } => Some(DisconnectGate {
                reconnecting: true,
                attempt: *attempt,
                next_secs: *next_secs,
                reason: reason.as_deref().or(state.disconnect_reason.as_deref()),
                last_error: last_error.as_deref(),
            }),
            ConnectionUi::Lost {
                reason,
                last_error,
            } => Some(DisconnectGate {
                reconnecting: false,
                attempt: 0,
                next_secs: 0.0,
                reason: reason.as_deref().or(state.disconnect_reason.as_deref()),
                last_error: last_error.as_deref(),
            }),
        };
        let disconnected = disconnect_gate.is_some() || !state.connected;
        if suppress_login_keys {
            drain_pending_input();
            if !letter_key_held() {
                suppress_login_keys = false;
            }
        }
        // While disconnected, ignore gameplay input except overlay actions.
        // Never block key polling for social chat — typing is routed via MenuKey.
        // (Passing composer_open here used to drop every key once say> appeared.)
        let chat_mode = local.chat.active || state.social_chat.composer_open();
        let input = if disconnected {
            flatland_gfx_engine::GfxInputFrame::default()
        } else {
            renderer.poll_input(suppress_login_keys)
        };
        let block_zoom = blocks_map_zoom(state, chat_mode, &local.map_target);
        let zoom_result = if block_zoom {
            GfxInputResult::default()
        } else {
            zoom_from_input(&input, renderer.map_zoom)
        };
        renderer.apply_input_result(zoom_result);

        let route_editing = route_editor_active(state);

        if !disconnected && is_key_pressed(KeyCode::Escape) {
            if renderer.show_connection_settings {
                renderer.show_connection_settings = false;
            } else if route_editing {
                net.send(NetCmd::Esc);
            } else if state.show_npc_chat
                || state.show_npc_verb_menu
                || state.player_verbs.open
                || state.social_chat.composer_open()
                || state.trade_ui.panel.is_some()
                || state.show_shop_menu
                || state.bank_panel.is_some()
                || state.storage_panel.is_some()
                || (state.show_quest_offer
                    && (state.show_npc_chat || state.npc_verb_target.is_some()))
            {
                net.send(NetCmd::Esc);
            } else if local.map_target.active {
                local.clear_nav();
                net.send(NetCmd::CancelAutoNav);
            } else if local.chat.active {
                local.chat.close();
            } else if renderer.show_help {
                renderer.show_help = false;
            } else if state.show_loadout_menu
                || state.show_rotation_editor
                || state.show_stats
            {
                let overlay = if state.show_loadout_menu {
                    ActiveOverlay::Loadout
                } else if state.show_rotation_editor {
                    ActiveOverlay::RotationEditor(state.rotation_editor.mode)
                } else {
                    ActiveOverlay::Stats
                };
                let esc = UiKeyEvent {
                    kind: UiKeyEventKind::Press,
                    code: UiKeyCode::Esc,
                    modifiers: UiKeyModifiers::default(),
                };
                match local.movement.apply_ui_key(esc, overlay, false) {
                    InputAction::Quit => {}
                    action => net.send(NetCmd::Action(action)),
                }
                local.movement.reset();
            } else {
                net.send(NetCmd::Esc);
                local.clear_nav();
            }
        }

        if !disconnected && is_key_pressed(KeyCode::F2) {
            renderer.show_connection_settings = !renderer.show_connection_settings;
        }

        for key in input.keys {
            // Esc is handled once above via `NetCmd::Esc`. `key_repeats` also emits Esc into
            // `input.keys`, so forwarding it again would pop two layers (e.g. talk→verb→exit).
            if key.kind == UiKeyEventKind::Press && matches!(key.code, UiKeyCode::Esc) {
                continue;
            }

            if local.chat.active {
                if let Some(text) = local.chat.handle_key(key) {
                    net.send(NetCmd::Say(ChatChannel::Nearby, text, None));
                }
                continue;
            }

            // Social chat: every key goes to the buffer (no gameplay binds).
            if state.social_chat.composer_open() {
                net.send(NetCmd::MenuKey(key));
                continue;
            }

            // Inline trade accept (Y/N) — only when not typing chat.
            if state.social_chat.pending_trade.is_some()
                && matches!(key.code, UiKeyCode::Char('y' | 'Y' | 'n' | 'N'))
            {
                net.send(NetCmd::MenuKey(key));
                continue;
            }

            if state.player_verbs.open || state.trade_ui.panel.is_some() {
                net.send(NetCmd::MenuKey(key));
                continue;
            }

            if route_editing {
                if key.kind == UiKeyEventKind::Press {
                    if local.map_target.active {
                        match key.code {
                            UiKeyCode::Enter => {
                                let (_, _, pz) = state.player_position_with_z();
                                net.send(NetCmd::RouteEditorWaypoint {
                                    x: local.map_target.cursor_x,
                                    y: local.map_target.cursor_y,
                                    z: pz,
                                });
                                local.map_target.deactivate();
                            }
                            UiKeyCode::Char('m') | UiKeyCode::Esc => {
                                local.map_target.deactivate();
                            }
                            UiKeyCode::Up | UiKeyCode::Char('k') | UiKeyCode::Char('w') => {
                                local.map_target.nudge(
                                    0,
                                    1,
                                    state.world_width_m,
                                    state.world_height_m,
                                );
                            }
                            UiKeyCode::Down | UiKeyCode::Char('j') => {
                                local.map_target.nudge(
                                    0,
                                    -1,
                                    state.world_width_m,
                                    state.world_height_m,
                                );
                            }
                            UiKeyCode::Left | UiKeyCode::Char('a') => {
                                local.map_target.nudge(
                                    -1,
                                    0,
                                    state.world_width_m,
                                    state.world_height_m,
                                );
                            }
                            UiKeyCode::Right | UiKeyCode::Char('d') => {
                                local.map_target.nudge(
                                    1,
                                    0,
                                    state.world_width_m,
                                    state.world_height_m,
                                );
                            }
                            _ => {}
                        }
                    } else {
                        match key.code {
                            UiKeyCode::Char('m') => {
                                let (px, py, _) = state.player_position_with_z();
                                local.map_target.activate_at(px, py);
                            }
                            // Forward all other route-editor keys to the menu dispatcher
                            // (j/k select, d delete, t rest, etc.). `s`/`l`/`u` are a
                            // historical subset and still arrive here too.
                            _ => {
                                net.send(NetCmd::MenuKey(key));
                            }
                        }
                    }
                }
                continue;
            }

            if menu_blocking(state) {
                net.send(NetCmd::MenuKey(key));
                continue;
            }

            if key.kind == UiKeyEventKind::Press && matches!(key.code, UiKeyCode::Char(';')) {
                renderer.show_use_radius = !renderer.show_use_radius;
                continue;
            }

            if is_map_zoom_key(&key) && !state.show_rotation_editor {
                continue;
            }

            let overlay = if state.show_loadout_menu {
                ActiveOverlay::Loadout
            } else if state.show_rotation_editor {
                ActiveOverlay::RotationEditor(state.rotation_editor.mode)
            } else if state.show_stats {
                ActiveOverlay::Stats
            } else {
                ActiveOverlay::None
            };
            match local
                .movement
                .apply_ui_key(key, overlay, local.map_target.active)
            {
                InputAction::Quit => break 'play,
                InputAction::ToggleHelp => renderer.show_help = !renderer.show_help,
                InputAction::ToggleHudLog => {
                    net.send(NetCmd::Action(InputAction::ToggleHudLog));
                }
                InputAction::CycleHudView => {
                    local.cycle_hud_view();
                    renderer.hud_view = local.hud_view;
                }
                InputAction::ToggleMapTarget => {
                    if local.map_target.active {
                        local.map_target.deactivate();
                    } else {
                        let (px, py, _) = state.player_position_with_z();
                        local.map_target.activate_at(px, py);
                    }
                }
                InputAction::ConfirmMapTarget => {
                    if local.map_target.active {
                        local.auto_nav_goal =
                            Some((local.map_target.cursor_x, local.map_target.cursor_y));
                        net.send(NetCmd::AutoNavTo {
                            x: local.map_target.cursor_x,
                            y: local.map_target.cursor_y,
                        });
                        local.map_target.deactivate();
                    }
                }
                InputAction::CancelMapTarget | InputAction::CancelAutoNav => {
                    local.clear_nav();
                    net.send(NetCmd::CancelAutoNav);
                }
                InputAction::StopMovement => {
                    local.clear_nav();
                    net.send(NetCmd::StopMovement);
                }
                InputAction::StartChat { whisper } => {
                    net.send(NetCmd::Action(InputAction::StartChat { whisper }));
                }
                InputAction::ToggleSprintMode => local.movement.toggle_sprint_mode(),
                InputAction::MapTargetNudge { dx, dy } => {
                    local
                        .map_target
                        .nudge(dx, dy, state.world_width_m, state.world_height_m);
                }
                other => {
                    if should_dispatch_to_net(other) {
                        net.send(NetCmd::Action(other));
                    }
                }
            }
        }

        for ptr in input.pointers {
            match ptr {
                UiPointerEvent::Move { x, y } => {
                    local.mouse_hover = screen_to_world(
                        &renderer.map_grid,
                        x,
                        y,
                        &state,
                        &renderer.world_rect,
                        &renderer.camera,
                    );
                }
                UiPointerEvent::Click {
                    x,
                    y,
                    button,
                    shift,
                } => {
                    if let Some((wx, wy)) = screen_to_world(
                        &renderer.map_grid,
                        x,
                        y,
                        &state,
                        &renderer.world_rect,
                        &renderer.camera,
                    ) {
                        if route_editing && button == UiMouseButton::Left {
                            net.send(NetCmd::RouteEditorMapClick { x: wx, y: wy });
                            continue;
                        }
                        if blocks_map_click(state, local.chat.active, false) {
                            continue;
                        }
                        match button {
                            UiMouseButton::Left => {
                                let slot = if shift { 2 } else { 1 };
                                if let Some((target_id, label)) =
                                    state.pick_combat_target_at(wx, wy, slot, 1.75)
                                {
                                    net.send(NetCmd::SetCombatTargetSlot {
                                        slot_index: slot,
                                        target_id,
                                        label,
                                    });
                                    local.map_target.deactivate();
                                } else if !shift {
                                    local.auto_nav_goal = Some((wx, wy));
                                    net.send(NetCmd::AutoNavTo { x: wx, y: wy });
                                    local.map_target.deactivate();
                                }
                            }
                            UiMouseButton::Right => {
                                local.clear_nav();
                                net.send(NetCmd::CancelAutoNav);
                            }
                            UiMouseButton::Middle => {}
                        }
                    }
                }
                UiPointerEvent::Scroll { .. } => {}
            }
        }

        let movement_blocked = disconnected
            || menu_blocking(state)
            || route_editing
            || state.show_loadout_menu
            || state.show_rotation_editor
            || state.show_stats
            || local.chat.active
            || state.social_chat.composer_open()
            || state.player_verbs.open
            || state.trade_ui.panel.is_some()
            || local.map_target.active;

        let now = Instant::now();
        if !movement_blocked {
            use macroquad::input::KeyCode::{
                A, D, Down, J, Left, LeftShift, Right, RightShift, S, U, Up, W,
            };
            local.movement.sync_physical_holds(
                is_key_down(W) || is_key_down(Up),
                is_key_down(S) || is_key_down(Down),
                is_key_down(A) || is_key_down(Left),
                is_key_down(D) || is_key_down(Right),
                is_key_down(U),
                is_key_down(J),
                is_key_down(LeftShift) || is_key_down(RightShift),
            );
            if movement_interval_elapsed(movement_sent_at, now) {
                movement_sent_at = now;
                let (f, s) = local.movement.current().components();
                net.send(NetCmd::Movement {
                    forward: f,
                    strafe: s,
                    vertical: local.movement.vertical_axis(),
                    sprint: local.movement.sprinting(),
                });
            }
        } else {
            // Menus: fall back to idle expiry so WASD cannot stick under an overlay.
            local.movement.expire_idle(local.movement.idle_timeout());
        }

        let (px, py) = state.player_position();
        let (facing_f, facing_s) = if let Some((f, s)) = snapshot.presentation.auto_nav_facing_axes
        {
            (f, s)
        } else {
            let (lf, ls) = local.movement.last_move_axes();
            let (cf, cs) = local.movement.current().components();
            if cf.abs() > f32::EPSILON || cs.abs() > f32::EPSILON {
                (cf, cs)
            } else {
                (lf, ls)
            }
        };
        let now_ms = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as u64)
            .unwrap_or(0);
        renderer.update_camera(
            px,
            py,
            facing_f,
            facing_s,
            now_ms,
            state.effective_inside_building().as_deref(),
        );

        let movement_input = local.movement.current();
        let hud = build_play_hud(PlayHudInput {
            movement_label: movement_input.label(),
            sprint_mode: local.movement.sprint_mode(),
            map_target: &local.map_target,
            auto_nav_goal: local.auto_nav_goal,
            mouse_hover: local.mouse_hover,
            view_mode: local.hud_view,
        });
        let chat_line = if state.social_chat.composer_open() {
            format!(
                "{}> {}",
                state.social_chat.prompt_prefix(),
                state.social_chat.buffer
            )
        } else {
            local.chat.prompt_line()
        };

        if local.was_harvesting && !state.harvest_in_progress {
            renderer.trigger_harvest_flash();
        }
        local.was_harvesting = state.harvest_in_progress;
        renderer
            .maybe_reload_sprites_for_publish_rev(state.content_rev, state.publish_rev)
            .await;
        renderer.tick_fx(get_frame_time());
        for cue in net.drain_audio_cues() {
            if let Some(bank) = renderer.tones_ref() {
                bank.play(cue);
            }
        }
        renderer.draw_frame(state, &hud, &chat_line, disconnect_gate);
        let menu_actions = renderer.take_menu_actions();
        if let Some(idx) = menu_actions.keychain_select {
            net.send(NetCmd::KeychainSelect(idx));
        }
        for click in menu_actions.route_editor {
            net.send(NetCmd::RouteEditorClick(click));
        }
        if menu_actions.retry_connect || (disconnected && is_key_pressed(KeyCode::R)) {
            net.send(NetCmd::RetryConnect);
        }
        if menu_actions.return_to_login || (disconnected && is_key_pressed(KeyCode::Escape)) {
            renderer.show_connection_settings = false;
            net.send(NetCmd::Shutdown);
            drop(net);
            return Ok(SessionEnd::Disconnected);
        }
        if menu_actions.logout {
            renderer.show_connection_settings = false;
            net.send(NetCmd::Shutdown);
            drop(net);
            return Ok(SessionEnd::Logout);
        }
        if menu_actions.switch_character {
            renderer.show_connection_settings = false;
            net.send(NetCmd::Shutdown);
            drop(net);
            return Ok(SessionEnd::SwitchCharacter);
        }

        if !*window_position_applied {
            apply_saved_position();
            *window_position_applied = true;
        }
        let geometry = capture_window_geometry();
        if geometry.width != last_saved_geometry.width
            || geometry.height != last_saved_geometry.height
            || geometry.x != last_saved_geometry.x
            || geometry.y != last_saved_geometry.y
        {
            *last_saved_geometry = geometry;
            if last_window_save.elapsed() >= std::time::Duration::from_millis(500) {
                save_window_geometry(last_saved_geometry.clone());
                *last_window_save = Instant::now();
            }
        }

        next_frame().await;
    }

    save_window_geometry(capture_window_geometry());
    renderer.flush_ui_prefs();
    Ok(SessionEnd::Quit)
}