qbrsh 0.1.0

A fast, keyboard-driven web browser
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
//! The single, owned application state.
//!
//! All mutable application state lives here as plain owned fields. There is no
//! `Rc<RefCell<_>>` sharing of state across subsystems; the dispatch loop holds
//! the sole `&mut State`. Subsystems are added to [`State`] as they are ported;
//! the skeleton establishes the ownership shape with the fields the core already
//! exercises (mode, tabs, input, command line, status, config).

use std::collections::{BTreeMap, HashMap};

use crate::core::bindings::default_bindings;
use crate::core::command::HintTarget;
use crate::core::completion::CompletionState;
use crate::core::key::Key;
use crate::core::msg::{JsPurpose, RequestId};
use crate::core::trie::BindingTrie;

/// Input modes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    Normal,
    Insert,
    Command,
    Hint,
}

/// Tracks the current mode and the one to return to on leave.
#[derive(Debug, Clone, Copy)]
pub struct ModeState {
    pub current: Mode,
    pub previous: Mode,
}

impl Default for ModeState {
    fn default() -> Self {
        Self {
            current: Mode::Normal,
            previous: Mode::Normal,
        }
    }
}

impl ModeState {
    /// Enter a new mode, remembering the current one as previous.
    pub fn enter(&mut self, mode: Mode) {
        if mode != self.current {
            self.previous = self.current;
            self.current = mode;
        }
    }

    /// Leave the current mode, returning to Normal.
    pub fn leave(&mut self) {
        self.previous = self.current;
        self.current = Mode::Normal;
    }
}

/// Stable identifier for a tab, shared between the state model and the engine's
/// web views.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct TabId(pub u64);

/// A single tab's model. The actual web view is owned by the engine layer and
/// correlated to this model by [`TabId`].
#[derive(Debug, Clone)]
pub struct Tab {
    pub id: TabId,
    pub url: String,
    pub title: String,
    pub loading: bool,
    pub progress: f64,
    pub crashed: bool,
}

impl Tab {
    fn new(id: TabId, url: &str) -> Self {
        Self {
            id,
            url: url.to_string(),
            title: String::new(),
            loading: false,
            progress: 0.0,
            crashed: false,
        }
    }
}

/// A recently-closed tab, retained so it can be reopened with `undo`.
#[derive(Debug, Clone)]
pub struct ClosedTab {
    pub url: String,
}

/// Maximum number of closed tabs retained for undo.
const UNDO_LIMIT: usize = 100;

/// The ordered set of open tabs plus the active selection.
#[derive(Debug, Default)]
pub struct Tabs {
    tabs: Vec<Tab>,
    active: usize,
    next_id: u64,
    undo_stack: Vec<ClosedTab>,
}

impl Tabs {
    /// Create a tab model for `url` and return its id. Does not change focus.
    pub fn open(&mut self, url: &str) -> TabId {
        let id = TabId(self.next_id);
        self.next_id += 1;
        self.tabs.push(Tab::new(id, url));
        id
    }

    /// Number of open tabs.
    pub fn len(&self) -> usize {
        self.tabs.len()
    }

    /// The active tab, if any.
    pub fn active(&self) -> Option<&Tab> {
        self.tabs.get(self.active)
    }

    /// The id of the active tab, if any.
    pub fn active_id(&self) -> Option<TabId> {
        self.active().map(|t| t.id)
    }

    /// The zero-based index of the active tab. Consumed by the tab-bar renderer.
    pub fn active_index(&self) -> usize {
        self.active
    }

    /// Mutable access to a tab by id.
    pub fn get_mut(&mut self, id: TabId) -> Option<&mut Tab> {
        self.tabs.iter_mut().find(|t| t.id == id)
    }

    /// Focus the last tab (used after opening a foreground tab).
    pub fn focus_last(&mut self) {
        if !self.tabs.is_empty() {
            self.active = self.tabs.len() - 1;
        }
    }

    /// Focus a tab by 1-based index. Returns the focused tab id, if valid.
    pub fn focus_index_1based(&mut self, index: usize) -> Option<TabId> {
        let idx = index.checked_sub(1)?;
        let tab = self.tabs.get(idx)?;
        self.active = idx;
        Some(tab.id)
    }

    /// Move focus forward `count` tabs, wrapping. Returns the new active id.
    pub fn next(&mut self, count: u32) -> Option<TabId> {
        if self.tabs.is_empty() {
            return None;
        }
        self.active = (self.active + count as usize) % self.tabs.len();
        self.active_id()
    }

    /// Move focus backward `count` tabs, wrapping. Returns the new active id.
    pub fn prev(&mut self, count: u32) -> Option<TabId> {
        if self.tabs.is_empty() {
            return None;
        }
        let len = self.tabs.len();
        let back = (count as usize) % len;
        self.active = (self.active + len - back) % len;
        self.active_id()
    }

    /// Close the active tab, retaining it for undo. Returns its id and the id to
    /// focus next, if any.
    pub fn close_active(&mut self) -> Option<(TabId, Option<TabId>)> {
        if self.tabs.is_empty() {
            return None;
        }
        let closed = self.tabs.remove(self.active);
        self.push_undo(&closed);
        if self.active >= self.tabs.len() && !self.tabs.is_empty() {
            self.active = self.tabs.len() - 1;
        }
        let next = self.active_id();
        Some((closed.id, next))
    }

    /// Close all tabs except the active one, retaining them for undo. Returns the
    /// ids of the closed tabs.
    pub fn close_others(&mut self) -> Vec<TabId> {
        if self.tabs.len() < 2 {
            return Vec::new();
        }
        let kept = self.tabs.swap_remove(self.active);
        let removed = std::mem::take(&mut self.tabs);
        let closed_ids = removed.iter().map(|t| t.id).collect();
        for tab in &removed {
            self.push_undo(tab);
        }
        self.tabs = vec![kept];
        self.active = 0;
        closed_ids
    }

    /// Move the active tab by `delta` positions, clamped to the ends. Returns
    /// true if the order changed.
    pub fn move_active(&mut self, delta: i32) -> bool {
        let len = self.tabs.len();
        if len < 2 {
            return false;
        }
        let target = (self.active as i32 + delta).clamp(0, len as i32 - 1) as usize;
        if target == self.active {
            return false;
        }
        let tab = self.tabs.remove(self.active);
        self.tabs.insert(target, tab);
        self.active = target;
        true
    }

    /// Pop the most recently closed tab for reopening.
    pub fn undo(&mut self) -> Option<ClosedTab> {
        self.undo_stack.pop()
    }

    /// The URLs of all open tabs, in order.
    pub fn urls(&self) -> Vec<String> {
        self.tabs.iter().map(|t| t.url.clone()).collect()
    }

    fn push_undo(&mut self, tab: &Tab) {
        self.undo_stack.push(ClosedTab {
            url: tab.url.clone(),
        });
        if self.undo_stack.len() > UNDO_LIMIT {
            self.undo_stack.remove(0);
        }
    }
}

/// The command-line input state.
#[derive(Debug, Default)]
pub struct CommandLine {
    pub text: String,
    pub active: bool,
}

/// Pending key input: the partial key sequence and the count prefix.
#[derive(Debug, Default)]
pub struct InputState {
    pub pending: Vec<Key>,
    pub count: String,
}

/// Transient status-bar state not derived directly from the active tab.
#[derive(Debug, Default)]
pub struct StatusLine {
    pub scroll_percent: Option<u8>,
}

/// Active hint-mode state: the follow action, the available labels, and the
/// label characters typed so far.
#[derive(Debug, Default)]
pub struct HintState {
    pub target: HintTarget,
    pub labels: Vec<String>,
    pub input: String,
}

impl HintState {
    /// Reset to an empty, inactive hint state.
    pub fn reset(&mut self) {
        self.labels.clear();
        self.input.clear();
    }
}

/// A saved bookmark.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bookmark {
    pub url: String,
    pub title: String,
}

/// Chrome colors (CSS color strings).
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(default)]
pub struct Colors {
    pub background: String,
    pub foreground: String,
    pub accent: String,
}

impl Default for Colors {
    fn default() -> Self {
        Self {
            background: "#1a1a2e".to_string(),
            foreground: "#e0e0e0".to_string(),
            accent: "#ffd76e".to_string(),
        }
    }
}

/// Chrome font.
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(default)]
pub struct Font {
    pub family: String,
    pub size: u32,
}

impl Default for Font {
    fn default() -> Self {
        Self {
            family: "monospace".to_string(),
            size: 11,
        }
    }
}

/// How a site permission request is answered.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PermissionPolicy {
    /// Prompt the user (currently falls back to deny: there is no prompt mode).
    Ask,
    Allow,
    #[default]
    Deny,
}

impl PermissionPolicy {
    /// Parse a policy from a `:set` value.
    pub fn parse(value: &str) -> Result<Self, String> {
        match value {
            "ask" => Ok(Self::Ask),
            "allow" => Ok(Self::Allow),
            "deny" => Ok(Self::Deny),
            other => Err(format!("invalid permission policy: {other}")),
        }
    }
}

/// Per-site permission policy: a default plus host-suffix-keyed overrides.
#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Deserialize)]
#[serde(default)]
pub struct Permissions {
    pub default: PermissionPolicy,
    pub sites: BTreeMap<String, PermissionPolicy>,
}

impl Permissions {
    /// Resolve the policy for `host`, matching a site rule by exact host or
    /// subdomain suffix, else the default.
    pub fn policy_for(&self, host: &str) -> PermissionPolicy {
        self.sites
            .iter()
            .find(|(site, _)| host == site.as_str() || host.ends_with(&format!(".{site}")))
            .map(|(_, p)| *p)
            .unwrap_or(self.default)
    }
}

/// User configuration, deserialized from TOML and adjustable at runtime.
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(default)]
pub struct Config {
    pub homepage: String,
    pub colors: Colors,
    pub font: Font,
    pub permissions: Permissions,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            homepage: "https://duckduckgo.com".to_string(),
            colors: Colors::default(),
            font: Font::default(),
            permissions: Permissions::default(),
        }
    }
}

impl Config {
    /// Set a configuration value by dotted key at runtime. Returns an error for
    /// unknown keys or invalid values.
    pub fn set(&mut self, key: &str, value: &str) -> Result<(), String> {
        match key {
            "homepage" | "general.homepage" => self.homepage = value.to_string(),
            "colors.background" => self.colors.background = value.to_string(),
            "colors.foreground" => self.colors.foreground = value.to_string(),
            "colors.accent" => self.colors.accent = value.to_string(),
            "font.family" => self.font.family = value.to_string(),
            "font.size" => {
                self.font.size = value
                    .parse()
                    .map_err(|_| format!("invalid font.size: {value}"))?
            }
            "permissions.default" => self.permissions.default = PermissionPolicy::parse(value)?,
            key if key.starts_with("permissions.") => {
                let host = &key["permissions.".len()..];
                self.permissions
                    .sites
                    .insert(host.to_string(), PermissionPolicy::parse(value)?);
            }
            _ => return Err(format!("unknown setting: {key}")),
        }
        Ok(())
    }
}

/// The complete application state.
#[derive(Debug, Default)]
pub struct State {
    pub mode: ModeState,
    pub tabs: Tabs,
    /// Filled once the binding trie is ported (input subsystem).
    pub input: InputState,
    pub command_line: CommandLine,
    pub status: StatusLine,
    pub hints: HintState,
    pub completion: CompletionState,
    /// Named shortcuts to URLs (name → url).
    pub quickmarks: BTreeMap<String, String>,
    /// Saved bookmarks.
    pub bookmarks: Vec<Bookmark>,
    pub config: Config,
    /// Normal-mode key bindings.
    pub bindings: BindingTrie,
    /// Purposes of in-flight JS evaluations, keyed by request id.
    pub pending_js: HashMap<RequestId, JsPurpose>,
    next_request_id: u64,
    /// Whether web-content dark mode is active.
    pub dark_mode: bool,
    /// Cleared to false to request shutdown.
    pub running: bool,
}

impl State {
    /// Create the initial state from configuration.
    pub fn new(config: Config) -> Self {
        Self {
            config,
            bindings: default_bindings(),
            running: true,
            ..Self::default()
        }
    }

    /// Allocate a fresh request id for correlating an async result.
    pub fn alloc_request_id(&mut self) -> RequestId {
        let id = RequestId(self.next_request_id);
        self.next_request_id += 1;
        id
    }
}