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