Skip to main content

cuqueclicker_lib/ui/
mod.rs

1pub mod achievements;
2pub mod biscuit;
3pub mod border;
4pub mod debug_pane;
5pub mod effects;
6pub mod hands;
7pub mod prestige;
8pub mod sidebar;
9pub mod stats;
10pub mod toast;
11pub mod upgrades;
12
13use ratatui::{prelude::*, widgets::*};
14
15use crate::format;
16use crate::game::state::{Buff, GameState, HUD_FLASH_TICKS, TICK_HZ};
17use crate::i18n::t;
18
19// Hardcoded as "0.0.0" in source; release.yml patches Cargo.toml before
20// building so CARGO_PKG_VERSION reflects the real version in shipped
21// binaries. A 0.0.0 build advertises itself as "(dev)" in the HUD.
22const VERSION: &str = env!("CARGO_PKG_VERSION");
23
24fn hud_title() -> String {
25    if VERSION == "0.0.0" {
26        // Dev builds include the git branch (or short SHA on detached HEAD)
27        // so two instances built from different branches can be told apart
28        // at a glance — useful for side-by-side comparison.
29        match crate::build_info::GIT_BRANCH {
30            Some(branch) => format!(" CuqueClicker v0.0.0 (dev, {branch}) "),
31            None => " CuqueClicker v0.0.0 (dev) ".into(),
32        }
33    } else {
34        format!(" CuqueClicker v{VERSION} ")
35    }
36}
37
38#[derive(Copy, Clone, PartialEq, Eq, Debug)]
39pub enum Mode {
40    Game,
41    Stats,
42    Achievements,
43    Upgrades,
44    Prestige,
45}
46
47/// Click target for a help-bar hint or for the prestige-reset confirm
48/// line. Mirrors the keyboard shortcuts so the mouse-first player has
49/// equivalent reach to every action a key would fire.
50#[derive(Clone, Copy, PartialEq, Eq, Debug)]
51pub enum HelpAction {
52    /// Open the named mode (or close it back to Game if already there).
53    OpenMode(Mode),
54    /// Catch whatever golden is on screen.
55    GrabGolden,
56    /// Confirm-and-claim prestige reset (only when prestige_available > 0).
57    PrestigeReset,
58    /// Quit the program.
59    Quit,
60}
61
62/// Per-frame layout snapshot produced by [`draw`]. Single source of truth
63/// for every clickable region on screen + the play-area envelope.
64///
65/// The platform shells (`app.rs`, `wasm_app.rs`) **store this verbatim**
66/// and call [`crate::input::InputContext::from_layout`] to project it
67/// into the per-event input context. Adding a new clickable region only
68/// touches this struct + `InputContext` + the projection — never the
69/// platform code. (We were burned by the alternative once: a missing
70/// `green_coin_rect` field on the wasm-side `InputContext` constructor
71/// crashed the wasm build after the native code shipped just fine.)
72#[derive(Default)]
73pub struct DrawOutput {
74    pub biscuit_rect: Rect,
75    pub golden_rect: Rect,
76    /// On-screen Green Coin marker rect, or zero-rect when no coin is
77    /// visible. Hit-tested by the click router exactly like `golden_rect`
78    /// — clicking either one routes through `Action::CatchGolden`, which
79    /// the sim resolves by trying both catch paths.
80    pub green_coin_rect: Rect,
81    /// The whole left column where the biscuit + hands + particles live —
82    /// i.e. "the box that displays the ass." Used by the input router so
83    /// the scroll-wheel zoom fires anywhere in this region (including the
84    /// vast empty space around a small biscuit at low zoom), and only the
85    /// right-hand sidebar opts out of zoom.
86    pub play_area: Rect,
87    /// `(upgrade_idx, screen_row_rect)` pairs for the Upgrades panel —
88    /// populated only when the active mode renders that panel; empty
89    /// otherwise. The click router hit-tests these for `BuyUpgrade`.
90    /// First element of each tuple is also the digit-shortcut target,
91    /// kept aligned with `visible_upgrades`.
92    pub upgrade_rows: Vec<(usize, Rect)>,
93    /// `(fingerer_idx, screen_row_rect)` for the Game-mode sidebar.
94    pub fingerer_rows: Vec<(usize, Rect)>,
95    /// (action, rect) for every clickable help-bar hint at the bottom of
96    /// the play column. Mouse-first players use these to switch panels,
97    /// catch goldens, prestige-reset, and quit — all of which used to be
98    /// keyboard-only. Empty rects when the hint is non-actionable
99    /// (e.g. `[Space/Click] finger` is informational, not a click target).
100    pub help_hits: Vec<(HelpAction, Rect)>,
101    /// Click rect for the `Press [r] to reset and claim` confirm line in
102    /// the Prestige panel. Default rect when not in Prestige mode or no
103    /// prestige is available.
104    pub prestige_reset_rect: Rect,
105}
106
107fn wrapped_height(text: &str, width: u16) -> u16 {
108    if width == 0 {
109        return text.lines().count().max(1) as u16;
110    }
111    let mut total: u16 = 0;
112    for line in text.split('\n') {
113        let mut row_len: u16 = 0;
114        let mut rows: u16 = 1;
115        for word in line.split_whitespace() {
116            let wlen = word.chars().count() as u16;
117            if row_len == 0 {
118                row_len = wlen.min(width);
119            } else if row_len + 1 + wlen <= width {
120                row_len += 1 + wlen;
121            } else {
122                rows += 1;
123                row_len = wlen.min(width);
124            }
125        }
126        total = total.saturating_add(rows);
127    }
128    total.max(1)
129}
130
131fn draw_zoom_indicator(frame: &mut Frame, area: Rect, label: &str) {
132    let text = format!("zoom {}", label);
133    let w = text.chars().count() as u16;
134    if area.width < w || area.height == 0 {
135        return;
136    }
137    let col = area.x + area.width - w;
138    let row = area.y + area.height - 1;
139    let buf = frame.buffer_mut();
140    buf.set_string(
141        col,
142        row,
143        &text,
144        Style::default().fg(Color::Rgb(120, 120, 120)),
145    );
146}
147
148pub fn draw(
149    frame: &mut Frame,
150    state: &GameState,
151    mode: Mode,
152    zoom_idx: usize,
153    debug: bool,
154    mouse_pos: Option<(u16, u16)>,
155) -> DrawOutput {
156    let lang = t();
157    let area = frame.area();
158    let cols = Layout::horizontal([Constraint::Min(1), Constraint::Length(38)]).split(area);
159
160    let help_text = match mode {
161        Mode::Game => lang.help_game,
162        Mode::Stats => lang.help_stats,
163        Mode::Achievements => lang.help_ach,
164        Mode::Upgrades => lang.help_upgrades,
165        Mode::Prestige => lang.help_prestige,
166    };
167    let help_height = wrapped_height(help_text, cols[0].width).max(1);
168    let left = Layout::vertical([
169        Constraint::Length(3),
170        Constraint::Min(1),
171        Constraint::Length(help_height),
172    ])
173    .split(cols[0]);
174
175    // J5 count-up: render the smoothed `displayed_*` values rather than the
176    // raw current values. Big jumps (golden, max-buy, F4) ease in instead of
177    // snapping. Tween itself runs in `state.tick()`.
178    //
179    // Color sweep: TWO competing channels — green for cuques going UP
180    // (income, golden, F4), red for cuques going DOWN (purchase,
181    // prestige reset). Whichever channel is stronger this frame drives
182    // the lerp toward white. So a buy that lands during a still-decaying
183    // gain flash correctly flips the digits red as the spend channel
184    // overtakes the fading gain. Both lerp toward bright white at t=0,
185    // which matches the resting (no-flash) style — no hard cut.
186    let gain_t = (state.cuques_flash_ticks as f32 / HUD_FLASH_TICKS as f32).clamp(0.0, 1.0);
187    let spend_t = (state.cuques_spend_flash_ticks as f32 / HUD_FLASH_TICKS as f32).clamp(0.0, 1.0);
188    const FLASH_GAIN: (f32, f32, f32) = (80.0, 255.0, 80.0); // bright green
189    const FLASH_SPEND: (f32, f32, f32) = (255.0, 90.0, 90.0); // urgent red
190    const FLASH_REST: (f32, f32, f32) = (255.0, 255.0, 255.0);
191    let (peak, t) = if spend_t > gain_t {
192        (FLASH_SPEND, spend_t)
193    } else {
194        (FLASH_GAIN, gain_t)
195    };
196    let mix = 1.0 - t;
197    let r = peak.0 + (FLASH_REST.0 - peak.0) * mix;
198    let g = peak.1 + (FLASH_REST.1 - peak.1) * mix;
199    let b = peak.2 + (FLASH_REST.2 - peak.2) * mix;
200    let cuques_style = Style::default()
201        .fg(Color::Rgb(
202            r.clamp(0.0, 255.0) as u8,
203            g.clamp(0.0, 255.0) as u8,
204            b.clamp(0.0, 255.0) as u8,
205        ))
206        .add_modifier(Modifier::BOLD);
207    let mut hud_spans: Vec<Span> = vec![
208        Span::raw(format!("{}: ", lang.hud_cuques)),
209        Span::styled(format::big(state.displayed_cuques), cuques_style),
210        Span::raw(format!(
211            "   {}: {}",
212            lang.hud_fps,
213            format::rate(state.displayed_fps)
214        )),
215    ];
216    if state.prestige > 0 {
217        hud_spans.push(Span::styled(
218            format!(
219                "   {}: {} (+{:.0}%)",
220                lang.prestige_title.trim(),
221                state.prestige,
222                state.prestige as f64
223            ),
224            Style::default()
225                .fg(Color::Rgb(255, 215, 0))
226                .add_modifier(Modifier::BOLD),
227        ));
228    }
229    for b in &state.buffs {
230        let secs = b.ticks_remaining().div_ceil(TICK_HZ);
231        let (label, color) = match b {
232            Buff::ClickFrenzy { mult, .. } => (
233                format!("  [!! FRENZY x{} {}s]", *mult as u64, secs),
234                Color::Rgb(255, 80, 80),
235            ),
236        };
237        hud_spans.push(Span::styled(
238            label,
239            Style::default().fg(color).add_modifier(Modifier::BOLD),
240        ));
241    }
242    // Active timed per-fingerer modifiers — Purple Coin Buff golden today,
243    // anything else timed in the future. Phase 5 of #21 will replace this
244    // with a dedicated HUD strip; for now we mirror the legacy chip layout
245    // so UX continuity holds across phases.
246    for (id, st) in &state.fingerers_state {
247        for m in &st.modifiers {
248            let crate::game::modifier::ModifierDuration::Ticks(remaining) = m.duration else {
249                continue;
250            };
251            let secs = remaining.div_ceil(TICK_HZ);
252            let idx = crate::game::fingerer::FINGERERS
253                .iter()
254                .position(|f| f.id == id);
255            let name = idx
256                .and_then(|i| lang.fingerer_names.get(i).copied())
257                .unwrap_or("?");
258            // Pick a number to show: prefer the strongest single MulFactor
259            // effect (matches the old "x7" presentation); fall back to a
260            // count-of-effects marker for purely additive sources.
261            let mul = m.effects.iter().find_map(|e| match e {
262                crate::game::modifier::ModifierEffect::MulFactor(v) => Some(*v),
263                _ => None,
264            });
265            let label = match mul {
266                Some(v) => format!("  [++ {} x{} {}s]", name, v as u64, secs),
267                None => format!("  [++ {} {}s]", name, secs),
268            };
269            let color = match m.source {
270                crate::game::modifier::ModifierSource::PurpleCoin => Color::Rgb(220, 140, 255),
271                crate::game::modifier::ModifierSource::GreenCoin => Color::Rgb(120, 230, 140),
272            };
273            hud_spans.push(Span::styled(
274                label,
275                Style::default().fg(color).add_modifier(Modifier::BOLD),
276            ));
277        }
278    }
279    let title = hud_title();
280    border::draw_animated(frame, left[0], state, &title);
281    let hud_inner = Rect {
282        x: left[0].x + 1,
283        y: left[0].y + 1,
284        width: left[0].width.saturating_sub(2),
285        height: left[0].height.saturating_sub(2),
286    };
287    let hud = Paragraph::new(Line::from(hud_spans));
288    frame.render_widget(hud, hud_inner);
289
290    let biscuit_rect = biscuit::draw(frame, left[1], state, zoom_idx);
291    hands::draw(frame, left[1], biscuit_rect, state);
292    effects::draw_particles(frame, biscuit_rect, &state.particles);
293    effects::draw_misclicks(frame, &state.misclick_particles);
294    draw_zoom_indicator(
295        frame,
296        left[1],
297        biscuit::level_label(zoom_idx).unwrap_or("100%"),
298    );
299
300    if debug {
301        debug_pane::draw(frame, left[1]);
302    }
303    let golden_rect = match &state.golden {
304        Some(g) => biscuit::draw_golden(frame, g, biscuit_rect),
305        None => Rect::default(),
306    };
307    let green_coin_rect = match &state.green_coin {
308        Some(c) => biscuit::draw_green_coin(frame, c, biscuit_rect),
309        None => Rect::default(),
310    };
311
312    // J1: achievement toast overlay. Lives in `left[1]` (biscuit/main area)
313    // so it covers nothing important on the right; auto-dismisses after
314    // TOAST_TICKS via the sim. We render *after* biscuit/golden so it
315    // always sits on top.
316    toast::draw(frame, left[1], state);
317
318    // Custom help-bar render: lay out `[X] label` tokens left-to-right,
319    // wrapping at the rect width, paint each with mode-aware styling
320    // (active mode bolded), and return per-token click rects so the
321    // mouse-first player can drive the game without ever touching a key.
322    let help_hits = draw_help(frame, left[2], help_text, mode, mouse_pos);
323
324    let mut upgrade_rows: Vec<(usize, Rect)> = Vec::new();
325    let mut fingerer_rows: Vec<(usize, Rect)> = Vec::new();
326    let mut prestige_reset_rect = Rect::default();
327    match mode {
328        Mode::Game => fingerer_rows = sidebar::draw(frame, cols[1], state, mouse_pos),
329        Mode::Stats => stats::draw(frame, cols[1], state),
330        Mode::Achievements => achievements::draw(frame, cols[1], state),
331        Mode::Upgrades => upgrade_rows = upgrades::draw(frame, cols[1], state, mouse_pos),
332        Mode::Prestige => prestige_reset_rect = prestige::draw(frame, cols[1], state, mouse_pos),
333    }
334
335    DrawOutput {
336        biscuit_rect,
337        golden_rect,
338        green_coin_rect,
339        play_area: left[1],
340        upgrade_rows,
341        fingerer_rows,
342        help_hits,
343        prestige_reset_rect,
344    }
345}
346
347/// Custom help-bar renderer.
348///
349/// Splits the help string into "tokens" (each token is a contiguous
350/// non-whitespace run of `[X] label words`, separated from the next by
351/// a double space or a newline — the convention used in `i18n::Lang`'s
352/// help strings). Each token is laid out left-to-right with wrap at
353/// the rect's width, painted at the resolved screen position, and
354/// matched against a (mode, key) → action table. Clickable tokens get
355/// a slightly brighter color and BOLD; the token under the mouse
356/// cursor gets an additional brightness lift + bg fill so the player
357/// reads it as a button.
358fn draw_help(
359    frame: &mut Frame,
360    area: Rect,
361    text: &str,
362    mode: Mode,
363    mouse_pos: Option<(u16, u16)>,
364) -> Vec<(HelpAction, Rect)> {
365    let mut hits: Vec<(HelpAction, Rect)> = Vec::new();
366    if area.width == 0 || area.height == 0 {
367        return hits;
368    }
369    let buf = frame.buffer_mut();
370    let mut cursor_x: u16 = 0;
371    let mut cursor_y: u16 = 0;
372    for line in text.split('\n') {
373        // Tokens are separated by a literal `  ` (two spaces). Single
374        // spaces inside a token are content (e.g. "back to game").
375        for token in line.split("  ") {
376            let token = token.trim();
377            if token.is_empty() {
378                continue;
379            }
380            let w = token.chars().count() as u16;
381            // Wrap if the token wouldn't fit on the current line.
382            if cursor_x + w > area.width && cursor_x > 0 {
383                cursor_y += 1;
384                cursor_x = 0;
385            }
386            if cursor_y >= area.height {
387                break;
388            }
389            let action = map_help_token(token, mode);
390            // Hide `[q] quit` (or its localized equivalent) on platforms
391            // where the wasm/native runner has no authority to exit —
392            // see `platform::Capabilities::can_quit`. Skipping renders
393            // AND skips appending to `help_hits`, so the next token
394            // slides into the position cursor without leaving a gap.
395            if matches!(action, Some(HelpAction::Quit)) && !crate::platform::CAPABILITIES.can_quit {
396                continue;
397            }
398            let active = matches!(action, Some(HelpAction::OpenMode(m)) if m == mode);
399            let token_rect = Rect {
400                x: area.x + cursor_x,
401                y: area.y + cursor_y,
402                width: w.min(area.width.saturating_sub(cursor_x)),
403                height: 1,
404            };
405            // Style picker:
406            //  - active mode hint                : bright yellow, BOLD
407            //  - actionable (clickable)          : light gray, BOLD
408            //  - informational                   : dark gray
409            //  - hovered                         : color lifted, bg tint
410            // Hover lift fires ONLY on actionable hints — informational
411            // tokens like `[Space/Click] finger` and `[Shift] x10` are
412            // descriptive labels with no click handler, so brightening
413            // them on hover would advertise a button that doesn't exist.
414            let hovered = action.is_some()
415                && mouse_pos
416                    .map(|(mx, my)| {
417                        mx >= token_rect.x
418                            && mx < token_rect.x + token_rect.width
419                            && my == token_rect.y
420                    })
421                    .unwrap_or(false);
422            let mut style = if active {
423                Style::default()
424                    .fg(Color::Rgb(255, 220, 120))
425                    .add_modifier(Modifier::BOLD)
426            } else if action.is_some() {
427                Style::default()
428                    .fg(Color::Rgb(180, 180, 180))
429                    .add_modifier(Modifier::BOLD)
430            } else {
431                Style::default().fg(Color::DarkGray)
432            };
433            if hovered {
434                style = style
435                    .fg(Color::Rgb(255, 255, 255))
436                    .bg(Color::Rgb(40, 40, 50))
437                    .add_modifier(Modifier::BOLD);
438            }
439            buf.set_string(token_rect.x, token_rect.y, token, style);
440            if let Some(a) = action {
441                hits.push((a, token_rect));
442            }
443            cursor_x += w + 2; // double-space separator
444        }
445        cursor_y += 1;
446        cursor_x = 0;
447        if cursor_y >= area.height {
448            break;
449        }
450    }
451    hits
452}
453
454/// Match a help-bar token like `"[u] upgrades"` to a `HelpAction`,
455/// disambiguated by the current mode (so `[s] stats` opens Stats from
456/// Game but `[s/Esc] back to game` from Stats returns to Game).
457fn map_help_token(token: &str, mode: Mode) -> Option<HelpAction> {
458    // Extract the bracketed key. We accept the first `[...]` group;
459    // everything after the first `]` is descriptive label.
460    let open = token.find('[')?;
461    let close = token[open + 1..].find(']')? + open + 1;
462    let key = &token[open + 1..close];
463    // Universal hints first.
464    if key.eq_ignore_ascii_case("q") {
465        return Some(HelpAction::Quit);
466    }
467    // Back-to-game from any non-Game mode (the `[X/Esc] back ...` pattern
468    // covers stats / achievements / upgrades / prestige).
469    if mode != Mode::Game && (key.contains("Esc") || key.contains("esc")) {
470        return Some(HelpAction::OpenMode(Mode::Game));
471    }
472    // Single-letter mode openers, only meaningful from Game.
473    match (mode, key) {
474        (Mode::Game, "u") | (Mode::Game, "U") => Some(HelpAction::OpenMode(Mode::Upgrades)),
475        (Mode::Game, "p") | (Mode::Game, "P") => Some(HelpAction::OpenMode(Mode::Prestige)),
476        (Mode::Game, "s") | (Mode::Game, "S") => Some(HelpAction::OpenMode(Mode::Stats)),
477        (Mode::Game, "a") | (Mode::Game, "A") => Some(HelpAction::OpenMode(Mode::Achievements)),
478        (Mode::Game, "g") | (Mode::Game, "G") => Some(HelpAction::GrabGolden),
479        (Mode::Prestige, "r") | (Mode::Prestige, "R") => Some(HelpAction::PrestigeReset),
480        _ => None,
481    }
482}