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
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use fltk::{self, prelude::*, window};
use piki_gui::page_ui::PageUI;
use crate::autosave::AutoSaveState;
thread_local! {
/// Guards against more than one picker being open at a time. Repeatedly
/// triggering the shortcut would otherwise stack pickers, because on macOS
/// the native system menu fires the Cmd-P key equivalent before FLTK's
/// modal window can intercept it.
static PICKER_OPEN: Cell<bool> = const { Cell::new(false) };
}
/// The application menu saved while the picker is open, so it can be restored
/// verbatim on close. On macOS this is the previous `NSMenu`; elsewhere nothing
/// needs to be tracked.
#[cfg(target_os = "macos")]
type SavedAppMenu = Option<objc2::rc::Retained<objc2_app_kit::NSMenu>>;
#[cfg(not(target_os = "macos"))]
type SavedAppMenu = ();
/// Hide the application's menu bar so its keyboard shortcuts cannot fire while
/// the modal picker is open, returning the previous menu so it can be restored
/// untouched. Marking the FLTK window modal is not enough on macOS: the native
/// system menu dispatches key equivalents (e.g. Cmd-P) before FLTK's modal grab
/// can swallow them, which is what lets pickers stack today.
#[cfg(target_os = "macos")]
fn suspend_app_menu() -> SavedAppMenu {
use objc2::MainThreadMarker;
use objc2_app_kit::NSApplication;
let mtm = MainThreadMarker::new()?;
let app = NSApplication::sharedApplication(mtm);
let previous = app.mainMenu();
app.setMainMenu(None);
previous
}
/// Restore the menu captured by [`suspend_app_menu`].
#[cfg(target_os = "macos")]
fn restore_app_menu(saved: &SavedAppMenu) {
use objc2::MainThreadMarker;
use objc2_app_kit::NSApplication;
let Some(mtm) = MainThreadMarker::new() else {
return;
};
NSApplication::sharedApplication(mtm).setMainMenu(saved.as_deref());
}
#[cfg(not(target_os = "macos"))]
fn suspend_app_menu() -> SavedAppMenu {}
#[cfg(not(target_os = "macos"))]
fn restore_app_menu(_saved: &SavedAppMenu) {}
/// Modal quick page picker with fuzzy filtering and keyboard navigation.
pub fn show_page_picker(
app_state: Rc<RefCell<super::AppState>>,
autosave_state: Rc<RefCell<AutoSaveState>>,
active_editor: Rc<RefCell<Rc<RefCell<dyn PageUI>>>>,
statusbar: Rc<RefCell<super::statusbar::StatusBar>>,
parent: &window::Window,
) {
use fltk::{
browser::HoldBrowser,
enums::{CallbackTrigger, Event, Key},
input::Input,
window::Window,
};
// Only one picker may be open at a time. Without this guard, pressing the
// shortcut again while the picker is up would open another one on top.
if PICKER_OPEN.with(|open| open.replace(true)) {
return;
}
// Collect all pages once
let all_pages: Vec<String> = app_state
.borrow()
.store
.list_all_documents()
.unwrap_or_else(|_| vec![]);
// Create a modal dialog centered on parent
let width = 520;
let height = 420;
let px = parent.x() + (parent.w() - width) / 2;
let py = parent.y() + (parent.h() - height) / 2;
let mut win = Window::new(px.max(0), py.max(0), width, height, Some("Open Page"));
win.begin();
win.make_modal(true);
let mut input = Input::new(10, 10, width - 20, 28, None);
let mut list = HoldBrowser::new(10, 50, width - 20, height - 60, None);
list.set_scrollbar_size(12);
// Disable the application menu (and therefore its keyboard shortcuts) for as
// long as the picker is open, so it behaves like a real modal: app shortcuts
// such as Cmd-P no longer reach the window underneath. The menu is restored
// verbatim when the picker closes.
// On non-macOS `suspend_app_menu()` returns `()`; wrapping a unit value is
// intentional here so the type is uniform across platforms.
#[allow(clippy::unit_arg)]
let saved_menu: Rc<RefCell<SavedAppMenu>> = Rc::new(RefCell::new(suspend_app_menu()));
// Single entry point for closing the picker: restore the menu, clear the
// open guard and hide the window. Idempotent, so it is safe to call from
// every close path (Escape, Enter, double-click, window close button).
let close_picker: Rc<RefCell<dyn FnMut()>> = {
let mut win = win.clone();
let saved_menu = saved_menu.clone();
Rc::new(RefCell::new(move || {
if !PICKER_OPEN.with(|open| open.replace(false)) {
return; // already closed
}
restore_app_menu(&saved_menu.borrow());
win.hide();
}))
};
// Helper: populate list with provided items and maintain selection
let mut populate_list = {
let mut list = list.clone();
move |items: &Vec<String>, selected_index: Option<usize>| {
list.clear();
for s in items {
list.add(s);
}
if let Some(idx) = selected_index {
if !items.is_empty() {
let i = (idx.min(items.len() - 1) + 1) as i32; // 1-based
list.select(i);
list.top_line(i);
}
} else if !items.is_empty() {
list.select(1);
list.top_line(1);
}
}
};
// Simple fuzzy match: subsequence match with light scoring
fn fuzzy_score(query: &str, candidate: &str) -> Option<i32> {
if query.is_empty() {
return Some(0);
}
let mut score = 0i32;
let mut qi = 0usize;
let q = query.to_lowercase();
let c = candidate.to_lowercase();
let qb = q.as_bytes();
let cb = c.as_bytes();
for (i, &ch) in cb.iter().enumerate() {
if qi < qb.len() && ch == qb[qi] {
// Reward matches earlier and consecutive
score += 10 - ((i as i32).min(9));
// Bonus for start of word or after '/'
if i == 0 || cb.get(i - 1) == Some(&b'/') {
score += 5;
}
qi += 1;
if qi == qb.len() {
break;
}
}
}
if qi == qb.len() {
// Prefer prefix and exact
if c.starts_with(&q) {
score += 20;
}
if c == q {
score += 50;
}
Some(score)
} else {
None
}
}
// Current filtered results and selection index (0-based)
let results: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(all_pages.clone()));
let selection: Rc<RefCell<usize>> = Rc::new(RefCell::new(0));
// Initial population
populate_list(&results.borrow(), Some(*selection.borrow()));
// Filtering callback when input changes
{
let results = results.clone();
let mut list = list.clone();
input.set_trigger(CallbackTrigger::Changed);
input.set_callback(move |inp| {
let q = inp.value();
let mut items: Vec<(i32, String)> = Vec::new();
if q.trim().is_empty() {
for s in &all_pages {
items.push((0, s.clone()));
}
} else {
for s in &all_pages {
if let Some(sc) = fuzzy_score(&q, s) {
items.push((sc, s.clone()));
}
}
}
// Sort by score desc then name asc
items.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1)));
let filtered: Vec<String> = items.into_iter().map(|(_, s)| s).collect();
*results.borrow_mut() = filtered;
// Reset selection to top
list.clear();
for s in results.borrow().iter() {
list.add(s);
}
if list.size() > 0 {
list.select(1);
list.top_line(1);
}
});
}
// Accept helper: open current selection and close dialog
let accept_cb: Rc<RefCell<dyn FnMut()>> = {
let app_state = app_state.clone();
let autosave_state = autosave_state.clone();
let active_editor = active_editor.clone();
let statusbar = statusbar.clone();
let close_picker = close_picker.clone();
let list_for_accept = list.clone();
Rc::new(RefCell::new(move || {
let idx = list_for_accept.value(); // 1-based
let name_opt = if idx > 0 {
list_for_accept.text(idx)
} else {
None
};
if let Some(name) = name_opt {
(close_picker.borrow_mut())();
super::load_page_helper(
&name,
&app_state,
&autosave_state,
&active_editor,
&statusbar,
None,
);
}
}))
};
// Keyboard handling on input: up/down/select/esc
{
let mut list = list.clone();
let accept_cb = accept_cb.clone();
let close_picker = close_picker.clone();
input.handle(move |_, ev| match ev {
Event::KeyDown => {
let key = fltk::app::event_key();
match key {
Key::Down => {
let sz = list.size();
if sz > 0 {
let cur = list.value().max(1);
let next = (cur + 1).min(sz);
list.select(next);
list.top_line(next);
}
true
}
Key::Up => {
let sz = list.size();
if sz > 0 {
let cur = list.value().max(1);
let prev = (cur - 1).max(1);
list.select(prev);
list.top_line(prev);
}
true
}
Key::Enter => {
(accept_cb.borrow_mut())();
true
}
Key::Escape => {
// Cancel
(close_picker.borrow_mut())();
true
}
_ => false,
}
}
_ => false,
});
}
// Double-click or Enter on list accepts
{
let accept_cb = accept_cb.clone();
let close_picker = close_picker.clone();
list.handle(move |_, ev| match ev {
Event::Push => {
if fltk::app::event_clicks() {
(accept_cb.borrow_mut())();
true
} else {
false
}
}
Event::KeyDown => {
if fltk::app::event_key() == Key::Enter {
(accept_cb.borrow_mut())();
true
} else if fltk::app::event_key() == Key::Escape {
// Close on Esc
(close_picker.borrow_mut())();
true
} else {
false
}
}
_ => false,
});
}
win.end();
{
// Closing via the window's close button must also restore the menu and
// clear the open guard.
let close_picker = close_picker.clone();
win.set_callback(move |_| {
(close_picker.borrow_mut())();
});
}
win.show();
let _ = input.take_focus();
}