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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! The tab bar and tab switching: pinned tabs stay first and have no close button; drag a tab
//! to move it; right-click for pin, close others, close to the right and copy path; Ctrl+Tab
//! shows the tabs in most-recently-used order (hold Ctrl, press Tab to step, release to switch).
use egui::{Key, Modifiers, RichText};
use bigtext::file;
use super::i18n::{tr, trf};
use super::BigTextApp;
pub struct TabSwitcher {
/// Document ids, most recently used first.
pub order: Vec<u64>,
pub selected: usize,
/// The picked tab's row was wholly inside the list last frame (the self-test reads it).
pub selected_in_view: bool,
}
/// What the tab bar showed last frame (the self-test reads it too).
#[derive(Default)]
pub struct TabBarSeen {
/// The active document, to see when another one becomes active.
pub active: Option<u64>,
/// While the tabs do not fit: the room under their names for the scroll bar.
pub room: Option<f32>,
/// The active tab, with its × button, was wholly inside the visible part of the bar.
pub active_in_view: bool,
/// The list of all tabs was open.
pub list_open: bool,
/// The ▾ button that opens it, and the rows of the list wholly in view (tab, row).
pub list_button: Option<egui::Rect>,
pub list_rows: Vec<(usize, egui::Rect)>,
}
/// The list of all tabs in this frame.
#[derive(Default)]
struct TabList {
was_open: bool,
open: bool,
button: Option<egui::Rect>,
rows: Vec<(usize, egui::Rect)>,
pick: Option<usize>,
}
impl BigTextApp {
/// Keeps `mru` in step with the active tab and the open documents.
pub(super) fn track_mru(&mut self) {
let ids: Vec<u64> = self.docs.iter().map(|d| d.id).collect();
self.mru.retain(|id| ids.contains(id));
if let Some(id) = self.docs.get(self.active).map(|d| d.id) {
if self.mru.first() != Some(&id) {
self.mru.retain(|x| *x != id);
self.mru.insert(0, id);
}
}
for id in ids {
if !self.mru.contains(&id) {
self.mru.push(id);
}
}
}
fn activate(&mut self, id: u64) {
if let Some(i) = self.docs.iter().position(|d| d.id == id) {
self.active = i;
}
}
/// Ctrl+Tab / Ctrl+Shift+Tab: opens the switcher, or steps through it.
pub(crate) fn switch_tab(&mut self, forward: bool) {
if self.docs.len() < 2 {
return;
}
self.track_mru();
let n = self.mru.len();
match &mut self.switcher {
Some(s) => {
s.selected = if forward {
(s.selected + 1) % n
} else {
(s.selected + n - 1) % n
}
}
None => {
self.switcher = Some(TabSwitcher {
order: self.mru.clone(),
selected: if forward { 1 } else { n - 1 },
selected_in_view: false,
})
}
}
}
/// Keys while the switcher is open (before the text view sees them).
pub(super) fn switcher_keys(&mut self, ctx: &egui::Context) {
if self.switcher.is_none() {
return;
}
let (prev, next, up, down, enter, esc, ctrl) = ctx.input_mut(|i| {
(
// Ctrl+Shift+Tab first: egui ignores an extra Shift, so Ctrl+Tab took it too and
// stepped forward.
i.consume_key(Modifiers::CTRL | Modifiers::SHIFT, Key::Tab),
i.consume_key(Modifiers::CTRL, Key::Tab),
i.consume_key(Modifiers::NONE, Key::ArrowUp)
|| i.consume_key(Modifiers::CTRL, Key::ArrowUp),
i.consume_key(Modifiers::NONE, Key::ArrowDown)
|| i.consume_key(Modifiers::CTRL, Key::ArrowDown),
i.consume_key(Modifiers::NONE, Key::Enter),
i.consume_key(Modifiers::NONE, Key::Escape)
|| i.consume_key(Modifiers::CTRL, Key::Escape),
i.modifiers.ctrl,
)
});
if prev || up {
self.switch_tab(false);
} else if next || down {
self.switch_tab(true);
}
if esc {
self.switcher = None;
} else if enter || !ctrl {
// Releasing Ctrl switches, as in most editors.
if let Some(s) = self.switcher.take() {
if let Some(&id) = s.order.get(s.selected) {
self.activate(id);
}
}
}
}
pub(super) fn switcher_window(&mut self, ctx: &egui::Context) {
let Some(s) = &self.switcher else { return };
let mut pick = None;
let mut in_view = false;
// Below the switcher's 80 px from the top: its header, margins and a gap at the bottom.
let max_h = (ctx.content_rect().height() - 160.0).max(120.0);
egui::Area::new(egui::Id::new("tab-switcher"))
.anchor(egui::Align2::CENTER_TOP, egui::vec2(0.0, 80.0))
.order(egui::Order::Foreground)
.show(ctx, |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| {
ui.set_min_width(360.0);
ui.weak(tr("Hold Ctrl, press Tab to step, release to switch"));
ui.separator();
// Many tabs ran past the bottom of the window, the picked one out of sight:
// the list scrolls within the window and follows the pick.
let out = egui::ScrollArea::vertical()
.max_height(max_h)
.show(ui, |ui| {
let mut picked = None;
for (k, id) in s.order.iter().enumerate() {
let Some(d) = self.docs.iter().find(|d| d.id == *id) else {
continue;
};
let mut label = d.title.clone();
if d.is_modified() {
label.push_str(" *");
}
let r = ui.selectable_label(
k == s.selected,
RichText::new(label).strong(),
);
if r.clicked() {
pick = Some(*id);
}
let mut rect = r.rect;
if let Some(p) = d.path.as_deref() {
rect = rect.union(ui.weak(file::display_path(p)).rect);
}
if k == s.selected {
ui.scroll_to_rect(rect, None);
picked = Some(rect);
}
}
picked
});
in_view = out
.inner
.is_some_and(|r| out.inner_rect.expand(0.5).contains_rect(r));
});
});
if let Some(s) = &mut self.switcher {
s.selected_in_view = in_view;
}
if let Some(id) = pick {
self.switcher = None;
self.activate(id);
}
}
/// Pins or unpins a tab; pinned tabs stay at the front.
pub(crate) fn toggle_pin(&mut self, id: u64) {
let active = self.docs.get(self.active).map(|d| d.id);
if let Some(d) = self.docs.iter_mut().find(|d| d.id == id) {
d.pinned = !d.pinned;
}
self.docs.sort_by_key(|d| !d.pinned);
if let Some(a) = active {
self.activate(a);
}
self.persist_state();
}
/// Moves the tab at `from` to `to`, within its group (pinned or not).
pub(crate) fn move_tab(&mut self, from: usize, to: usize) {
if from >= self.docs.len() || to >= self.docs.len() || from == to {
return;
}
let pinned = self.docs[from].pinned;
let (lo, hi) = {
let n_pinned = self.docs.iter().filter(|d| d.pinned).count();
if pinned {
(0, n_pinned.saturating_sub(1))
} else {
(n_pinned, self.docs.len() - 1)
}
};
let to = to.clamp(lo, hi);
let active = self.docs.get(self.active).map(|d| d.id);
let d = self.docs.remove(from);
self.docs.insert(to, d);
if let Some(a) = active {
self.activate(a);
}
}
/// Closes the given tabs; ones with unsaved changes stay open (and are counted).
fn close_many(&mut self, ids: Vec<u64>) {
let mut kept = 0;
for id in ids {
match self.docs.iter().find(|d| d.id == id) {
Some(d) if d.is_modified() => kept += 1,
Some(_) => self.close_tab(id, false),
None => {}
}
}
if kept > 0 {
self.notify(
trf(
"{n} tabs with unsaved changes were kept open.",
&[("n", &kept.to_string())],
),
None,
);
}
}
/// Closes every unpinned tab but `keep`.
pub(crate) fn close_others(&mut self, keep: u64) {
let ids = self
.docs
.iter()
.filter(|d| d.id != keep && !d.pinned)
.map(|d| d.id)
.collect();
self.close_many(ids);
self.activate(keep);
}
/// Closes the unpinned tabs to the right of `of`.
pub(crate) fn close_to_right(&mut self, of: u64) {
let Some(i) = self.docs.iter().position(|d| d.id == of) else {
return;
};
let ids = self.docs[i + 1..]
.iter()
.filter(|d| !d.pinned)
.map(|d| d.id)
.collect();
self.close_many(ids);
}
/// The ▾ at the right end of the tab bar: every open tab in a list, to pick one with the
/// mouse when the bar cannot show them all. It opens on the active tab.
fn tab_list_button(&self, ui: &mut egui::Ui, list: &mut TabList) {
let r = ui.menu_button("▾", |ui| {
list.open = true;
let max_h = (ui.ctx().content_rect().height() - 160.0).max(120.0);
egui::ScrollArea::vertical()
.max_height(max_h)
.show(ui, |ui| {
for (i, d) in self.docs.iter().enumerate() {
let mut label = if d.pinned {
format!("📌 {}", d.title)
} else {
d.title.clone()
};
if d.is_modified() {
label.push_str(" *");
}
let r = ui.selectable_label(i == self.active, label);
if i == self.active && !list.was_open {
r.scroll_to_me(Some(egui::Align::Center));
}
if ui.clip_rect().contains_rect(r.rect) {
list.rows.push((i, r.rect));
}
let r = match d.path.as_deref() {
Some(p) => r.on_hover_text(file::display_path(p)),
None => r,
};
if r.clicked() {
list.pick = Some(i);
ui.close();
}
}
});
});
list.button = Some(r.response.rect);
r.response.on_hover_text(tr("All tabs"));
}
pub(super) fn tab_bar(&mut self, ui: &mut egui::Ui) {
let mut close = None;
let mut activate = None;
let mut moved = None;
let mut menu: Option<(u64, &'static str)> = None;
let active_id = self.docs.get(self.active).map(|d| d.id);
let active_link = self
.docs
.get(self.active)
.and_then(|d| d.link.as_ref())
.map(|l| l.partner);
// Once the tabs no longer fit, the scroll bar gets a strip of its own under the names:
// egui's default floating bar is drawn over them. Its handle stays faintly visible, so
// the strip shows there are more tabs than the window holds.
ui.spacing_mut().scroll = egui::style::ScrollStyle {
dormant_handle_opacity: 0.4,
..egui::style::ScrollStyle::solid()
};
// A tab that has just become the active one (opened, picked with Ctrl+Tab or a click on
// its cut-off edge) is scrolled into view, with its × button; scrolling by hand is kept.
let reveal = active_id.is_some() && active_id != self.tab_bar_seen.active;
let mut active_rect = None;
let mut list = TabList {
was_open: self.tab_bar_seen.list_open,
..TabList::default()
};
let mut out = None;
// The list of all tabs at the right end, the tabs in what is left.
ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
self.tab_list_button(ui, &mut list);
ui.with_layout(egui::Layout::left_to_right(egui::Align::Min), |ui| {
out = Some(egui::ScrollArea::horizontal().show(ui, |ui| {
ui.horizontal(|ui| {
for (i, d) in self.docs.iter().enumerate() {
let mut label = if d.pinned {
format!("📌 {}", d.title)
} else {
d.title.clone()
};
if d.is_modified() {
label.push_str(" *");
}
let unseen = d.alerts.as_ref().map_or(0, |a| a.unseen);
let label = if unseen > 0 {
let mut job = egui::text::LayoutJob::default();
let style = ui.style();
egui::RichText::new(format!("{label} ")).append_to(
&mut job,
style,
egui::FontSelection::Default,
egui::Align::Center,
);
egui::RichText::new(format!("🔔{unseen}"))
.color(ui.visuals().error_fg_color)
.strong()
.append_to(
&mut job,
style,
egui::FontSelection::Default,
egui::Align::Center,
);
egui::WidgetText::from(job)
} else {
egui::WidgetText::from(label)
};
let r = ui.add(
egui::Button::selectable(i == self.active, label)
.sense(egui::Sense::click_and_drag()),
);
if i == self.active {
active_rect = Some(r.rect);
}
r.dnd_set_drag_payload(i);
if r.dnd_hover_payload::<usize>()
.is_some_and(|from| *from != i)
{
let x =
if r.dnd_hover_payload::<usize>().is_some_and(|from| *from < i)
{
r.rect.right()
} else {
r.rect.left()
};
ui.painter().vline(
x,
r.rect.y_range(),
egui::Stroke::new(2.0, ui.visuals().selection.stroke.color),
);
}
if let Some(from) = r.dnd_release_payload::<usize>() {
moved = Some((*from, i));
}
if r.clicked() {
activate = Some(i);
}
if r.middle_clicked() && !d.pinned {
close = Some(d.id);
}
// An untitled tab has no path, and an empty tooltip is a bare box.
let r = match d.path.as_deref() {
Some(p) => r.on_hover_text(file::display_path(p)),
None => r,
};
let link_here =
active_id != Some(d.id) && d.is_ready() && !d.hex && !d.table;
let linked_here = active_link == Some(d.id);
r.context_menu(|ui| {
let id = d.id;
let mut item = |ui: &mut egui::Ui, label: &'static str| {
if ui.button(tr(label)).clicked() {
menu = Some((id, label));
ui.close();
}
};
item(ui, if d.pinned { "Unpin tab" } else { "Pin tab" });
if linked_here {
item(ui, "Unlink");
} else if link_here {
item(ui, "Link scrolling with this tab");
}
ui.separator();
item(ui, "Close");
item(ui, "Close other tabs");
item(ui, "Close tabs to the right");
if d.path.is_some() {
ui.separator();
item(ui, "Copy path");
item(ui, "Show in folder");
item(ui, "Open terminal here");
item(ui, "Open with the default app");
}
});
if !d.pinned {
let x = ui.small_button("×");
if x.clicked() {
close = Some(d.id);
}
if i == self.active {
active_rect = active_rect.map(|a| a.union(x.rect));
}
}
if i == self.active && reveal {
if let Some(a) = active_rect {
ui.scroll_to_rect(a, None);
}
}
ui.separator();
}
});
}));
});
});
let Some(out) = out else {
return;
};
// The names end where the bar's strip starts (`inner_rect` leaves the bar out).
self.tab_bar_seen = TabBarSeen {
list_open: list.open,
list_button: list.button,
list_rows: list.rows,
active: active_id,
room: (out.content_size.x > out.inner_rect.width() + 0.5)
.then(|| ui.min_rect().bottom() - out.inner_rect.bottom()),
active_in_view: active_rect
.is_some_and(|a| out.inner_rect.expand(0.5).contains_rect(a)),
};
if let Some(i) = activate.or(list.pick) {
self.active = i;
}
if let Some((from, to)) = moved {
self.move_tab(from, to);
}
if let Some(id) = close {
self.close_tab(id, false);
}
if let Some((id, what)) = menu {
match what {
"Pin tab" | "Unpin tab" => self.toggle_pin(id),
"Link scrolling with this tab" => self.link_with(id, self.link_mode),
"Unlink" => self.unlink(),
"Close" => self.close_tab(id, false),
"Close other tabs" => self.close_others(id),
"Close tabs to the right" => self.close_to_right(id),
"Show in folder" => self.shell_doc(id, super::shell::ShellAction::Reveal),
"Open terminal here" => self.shell_doc(id, super::shell::ShellAction::Terminal),
"Open with the default app" => {
self.shell_doc(id, super::shell::ShellAction::Default)
}
"Copy path" => {
if let Some(p) = self
.docs
.iter()
.find(|d| d.id == id)
.and_then(|d| d.unpacked_from.as_deref().or(d.path.as_deref()))
{
ui.ctx().copy_text(file::display_path(p));
}
}
_ => {}
}
}
}
}