rollcli 0.3.3

A command-line dice roller for tabletop RPGs with advantage/disadvantage and probability estimation
Documentation
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
use roll::{
    DiceExpr, RollStats, compute_distribution, estimate_probability, exact_probability,
    parse_expr, roll_stats, roll_verbose,
};
use std::collections::BTreeMap;
use std::time::Instant;

// ── App mode ─────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Screen {
    Roller,
    History,
    Help,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RollerFocus {
    Input,
    Presets,
}

// ── Roll history entry ───────────────────────────────────────────────────────

#[derive(Clone)]
#[allow(dead_code)]
pub struct RollEntry {
    pub expression: String,
    pub total: i64,
    pub breakdown: String,
    pub stats: RollStats,
    pub timestamp: Instant,
    /// The kept dice per group, for nat/min/max coloring.
    pub kept_dice: Vec<Vec<u32>>,
    /// The sides of each dice group (parallel to kept_dice).
    pub group_sides: Vec<u32>,
    /// Whether this was a "natural" max (all dice rolled their maximum).
    pub is_nat_max: bool,
    /// Whether this was a "natural" min (all dice rolled 1).
    pub is_nat_min: bool,
}

// ── Distribution data ────────────────────────────────────────────────────────

pub struct DistData {
    pub expr_str: String,
    pub counts: BTreeMap<i64, u64>,
    pub target: Option<i64>,
    pub target_prob: Option<f64>,
}

// ── Preset entry ─────────────────────────────────────────────────────────────

#[derive(Clone)]
pub struct PresetEntry {
    pub name: String,
    pub expression: String,
}

// ── Application state ────────────────────────────────────────────────────────

pub struct App {
    pub screen: Screen,
    pub prev_screen: Screen,
    pub input: String,
    pub cursor_pos: usize,
    pub roll_history: Vec<RollEntry>,
    pub input_history: Vec<String>,
    pub input_history_idx: Option<usize>,
    pub error_msg: Option<String>,
    pub should_quit: bool,

    // Distribution view
    pub dist: Option<DistData>,

    // Preset view
    pub presets: Vec<PresetEntry>,
    pub preset_selected: usize,
    pub preset_confirm_delete: bool,

    // Roller focus (input vs presets sidebar)
    pub roller_focus: RollerFocus,

    // History scroll
    pub history_scroll: usize,

    // Config
    pub sims: u64,
}

const MAX_HISTORY: usize = 50;

impl App {
    pub fn new(initial_expr: Option<&str>, sims: u64) -> Self {
        let mut app = Self {
            screen: Screen::Roller,
            prev_screen: Screen::Roller,
            input: String::new(),
            cursor_pos: 0,
            roll_history: Vec::new(),
            input_history: Vec::new(),
            input_history_idx: None,
            error_msg: None,
            should_quit: false,
            dist: None,
            presets: Vec::new(),
            preset_selected: 0,
            preset_confirm_delete: false,
            roller_focus: RollerFocus::Input,
            history_scroll: 0,
            sims,
        };
        if let Some(expr) = initial_expr {
            app.input = expr.to_string();
            app.cursor_pos = expr.len();
        }
        app
    }

    // ── Input editing ────────────────────────────────────────────────────────

    pub fn insert_char(&mut self, c: char) {
        self.error_msg = None;
        self.input.insert(self.cursor_pos, c);
        self.cursor_pos += c.len_utf8();
    }

    pub fn delete_char_before(&mut self) {
        if self.cursor_pos > 0 {
            let prev = self.input[..self.cursor_pos]
                .char_indices()
                .last()
                .map(|(i, _)| i)
                .unwrap_or(0);
            self.input.remove(prev);
            self.cursor_pos = prev;
        }
    }

    pub fn delete_char_after(&mut self) {
        if self.cursor_pos < self.input.len() {
            self.input.remove(self.cursor_pos);
        }
    }

    pub fn move_cursor_left(&mut self) {
        if self.cursor_pos > 0 {
            self.cursor_pos = self.input[..self.cursor_pos]
                .char_indices()
                .last()
                .map(|(i, _)| i)
                .unwrap_or(0);
        }
    }

    pub fn move_cursor_right(&mut self) {
        if self.cursor_pos < self.input.len() {
            self.cursor_pos = self.input[self.cursor_pos..]
                .char_indices()
                .nth(1)
                .map(|(i, _)| self.cursor_pos + i)
                .unwrap_or(self.input.len());
        }
    }

    pub fn move_cursor_home(&mut self) {
        self.cursor_pos = 0;
    }

    pub fn move_cursor_end(&mut self) {
        self.cursor_pos = self.input.len();
    }

    // ── Input history navigation ─────────────────────────────────────────────

    pub fn history_up(&mut self) {
        if self.input_history.is_empty() {
            return;
        }
        let idx = match self.input_history_idx {
            None => self.input_history.len() - 1,
            Some(0) => return,
            Some(i) => i - 1,
        };
        self.input_history_idx = Some(idx);
        self.input = self.input_history[idx].clone();
        self.cursor_pos = self.input.len();
    }

    pub fn history_down(&mut self) {
        let Some(idx) = self.input_history_idx else {
            return;
        };
        if idx + 1 >= self.input_history.len() {
            self.input_history_idx = None;
            self.input.clear();
            self.cursor_pos = 0;
        } else {
            self.input_history_idx = Some(idx + 1);
            self.input = self.input_history[idx + 1].clone();
            self.cursor_pos = self.input.len();
        }
    }

    // ── Rolling ──────────────────────────────────────────────────────────────

    pub fn submit_roll(&mut self) {
        let input = self.input.trim().to_string();
        if input.is_empty() {
            return;
        }

        // Resolve preset names
        let resolved = self
            .presets
            .iter()
            .find(|p| p.name.to_lowercase() == input.to_lowercase())
            .map(|p| p.expression.clone())
            .unwrap_or_else(|| input.clone());

        let expr = match parse_expr(&resolved) {
            Ok(e) => e,
            Err(e) => {
                self.error_msg = Some(format!("{e}"));
                return;
            }
        };

        let mut rng = rand::rng();
        let (total, breakdown) = roll_verbose(&expr, &mut rng);
        let stats = roll_stats(&expr);

        // For nat detection, do an extra roll_once to get kept dice
        // (roll_verbose doesn't expose them). We use the breakdown from roll_verbose
        // for display, and parse the kept dice from a separate roll for coloring
        // of the *displayed* result. Since roll_verbose already consumed the roll,
        // we parse the kept dice from the breakdown string instead.
        let (kept_dice, group_sides) = parse_kept_from_breakdown(&breakdown, &expr);
        let is_nat_max = is_natural_max(&kept_dice, &group_sides);
        let is_nat_min = is_natural_min(&kept_dice);

        // Auto-compute distribution for the rolled expression
        let dist_counts = compute_distribution(&expr, self.sims, &mut rng);
        self.dist = Some(DistData {
            expr_str: resolved.clone(),
            counts: dist_counts,
            target: None,
            target_prob: None,
        });

        let entry = RollEntry {
            expression: resolved,
            total,
            breakdown,
            stats,
            timestamp: Instant::now(),
            kept_dice,
            group_sides,
            is_nat_max,
            is_nat_min,
        };

        self.roll_history.push(entry);
        if self.roll_history.len() > MAX_HISTORY {
            self.roll_history.remove(0);
        }

        // Push to input history (deduplicate consecutive)
        if self.input_history.last().map(|s| s.as_str()) != Some(&input) {
            self.input_history.push(input);
        }
        self.input_history_idx = None;

        self.input.clear();
        self.cursor_pos = 0;
        self.error_msg = None;
        self.history_scroll = 0;
    }

    // ── Distribution navigation ───────────────────────────────────────────────

    pub fn dist_set_target(&mut self, target: i64) {
        if let Some(ref mut dist) = self.dist {
            let expr = match parse_expr(&dist.expr_str) {
                Ok(e) => e,
                Err(_) => return,
            };
            let prob = exact_probability(&expr, target).unwrap_or_else(|| {
                let mut rng = rand::rng();
                estimate_probability(&expr, target, self.sims, &mut rng)
            });
            dist.target = Some(target);
            dist.target_prob = Some(prob);
        }
    }

    pub fn dist_move_target(&mut self, delta: i64) {
        if let Some(ref dist) = self.dist {
            let keys: Vec<i64> = dist.counts.keys().copied().collect();
            if keys.is_empty() {
                return;
            }
            let current = dist.target.unwrap_or_else(|| keys[keys.len() / 2]);
            let pos = keys.partition_point(|&k| k < current);
            let new_pos = (pos as i64 + delta).clamp(0, keys.len() as i64 - 1) as usize;
            let new_target = keys[new_pos];
            self.dist_set_target(new_target);
        }
    }

    // ── Distribution ─────────────────────────────────────────────────────────

    pub fn open_history(&mut self) {
        self.prev_screen = self.screen;
        self.screen = Screen::History;
    }

    pub fn toggle_presets_focus(&mut self) {
        self.roller_focus = match self.roller_focus {
            RollerFocus::Input => {
                self.reload_presets();
                RollerFocus::Presets
            }
            RollerFocus::Presets => {
                self.preset_confirm_delete = false;
                RollerFocus::Input
            }
        };
    }

    // ── Presets ──────────────────────────────────────────────────────────────

    pub fn open_presets(&mut self) {
        self.reload_presets();
        self.roller_focus = RollerFocus::Presets;
        self.preset_confirm_delete = false;
        if self.preset_selected >= self.presets.len() {
            self.preset_selected = 0;
        }
    }

    pub fn reload_presets(&mut self) {
        let loaded = super::load_presets_list();
        self.presets = loaded;
    }

    pub fn preset_select_up(&mut self) {
        if self.preset_selected > 0 {
            self.preset_selected -= 1;
            self.preset_confirm_delete = false;
        }
    }

    pub fn preset_select_down(&mut self) {
        if !self.presets.is_empty() && self.preset_selected < self.presets.len() - 1 {
            self.preset_selected += 1;
            self.preset_confirm_delete = false;
        }
    }

    pub fn preset_roll_selected(&mut self) {
        if let Some(preset) = self.presets.get(self.preset_selected) {
            self.input = preset.expression.clone();
            self.cursor_pos = self.input.len();
            self.roller_focus = RollerFocus::Input;
            self.submit_roll();
        }
    }

    pub fn preset_delete_selected(&mut self) {
        if self.preset_confirm_delete {
            if let Some(preset) = self.presets.get(self.preset_selected) {
                super::delete_preset(&preset.name);
                self.reload_presets();
                if self.preset_selected >= self.presets.len() && self.preset_selected > 0 {
                    self.preset_selected -= 1;
                }
            }
            self.preset_confirm_delete = false;
        } else {
            self.preset_confirm_delete = true;
        }
    }

    // ── Screen navigation ────────────────────────────────────────────────────

    pub fn go_back(&mut self) {
        self.screen = Screen::Roller;
        self.prev_screen = Screen::Roller;
        self.error_msg = None;
    }

    pub fn toggle_help(&mut self) {
        if self.screen == Screen::Help {
            self.go_back();
        } else {
            self.prev_screen = self.screen;
            self.screen = Screen::Help;
        }
    }

    // ── History scroll ───────────────────────────────────────────────────────

    pub fn scroll_history_up(&mut self) {
        if self.history_scroll + 1 < self.roll_history.len() {
            self.history_scroll += 1;
        }
    }

    pub fn scroll_history_down(&mut self) {
        if self.history_scroll > 0 {
            self.history_scroll -= 1;
        }
    }

    pub fn latest_roll(&self) -> Option<&RollEntry> {
        self.roll_history.last()
    }

    /// Returns how many milliseconds ago the latest roll was made (for flash animation).
    pub fn latest_roll_age_ms(&self) -> Option<u128> {
        self.roll_history
            .last()
            .map(|e| e.timestamp.elapsed().as_millis())
    }
}

// ── Nat detection helpers ────────────────────────────────────────────────────

/// Parse kept dice values from the breakdown string produced by roll_verbose.
/// Breakdown looks like "[3, 5] + [2]" or "[17 vs 12]" for adv/dis.
fn parse_kept_from_breakdown(breakdown: &str, expr: &DiceExpr) -> (Vec<Vec<u32>>, Vec<u32>) {
    // For advantage/disadvantage with "vs", just parse the first set
    let working = if breakdown.contains(" vs ") {
        breakdown.split(" vs ").next().unwrap_or(breakdown)
    } else {
        breakdown
    };

    let mut kept_dice = Vec::new();
    let group_sides: Vec<u32> = expr.groups.iter().map(|g| g.sides).collect();

    // Split on " + " to get each group's "[x, y, z]"
    for part in working.split(" + ") {
        let trimmed = part.trim().trim_start_matches('[').trim_end_matches(']');
        let dice: Vec<u32> = trimmed
            .split(',')
            .filter_map(|s| s.trim().parse().ok())
            .collect();
        kept_dice.push(dice);
    }

    (kept_dice, group_sides)
}

fn is_natural_max(kept_dice: &[Vec<u32>], group_sides: &[u32]) -> bool {
    if kept_dice.is_empty() {
        return false;
    }
    kept_dice
        .iter()
        .zip(group_sides.iter())
        .all(|(dice, &sides)| !dice.is_empty() && dice.iter().all(|&d| d == sides))
}

fn is_natural_min(kept_dice: &[Vec<u32>]) -> bool {
    if kept_dice.is_empty() {
        return false;
    }
    kept_dice
        .iter()
        .all(|dice| !dice.is_empty() && dice.iter().all(|&d| d == 1))
}