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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
//! Tab element for switching between views.
use super::context::{BasicContext, Context};
use super::{share, Element, ElementPtr, ViewLimits, ViewStretch};
use crate::support::color::Color;
use crate::support::point::Point;
use crate::support::rect::Rect;
use crate::support::theme::get_theme;
use crate::view::{CursorTracking, KeyInfo, MouseButton, MouseButtonKind, TextInfo};
use std::any::Any;
use std::sync::RwLock;
/// Tab position.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TabPosition {
#[default]
Top,
Bottom,
Left,
Right,
}
/// Callback type for tab changes.
pub type TabChangeCallback = Box<dyn Fn(usize) + Send + Sync>;
/// Callback type for a tab's close ("x") button being clicked. Receives the
/// closed tab's index *before* removal.
pub type TabCloseCallback = Box<dyn Fn(usize) + Send + Sync>;
/// A single tab.
pub struct Tab {
label: String,
content: Option<ElementPtr>,
closable: bool,
}
impl Tab {
/// Creates a new tab.
pub fn new(label: impl Into<String>) -> Self {
Self {
label: label.into(),
content: None,
closable: false,
}
}
/// Sets the tab content.
pub fn content<E: Element + 'static>(mut self, content: E) -> Self {
self.content = Some(share(content));
self
}
/// Sets the tab content from an already-shared `ElementPtr`, without
/// wrapping it in a second `Arc` via `share()`. Needed when the host app
/// keeps its own handle to the same widget (e.g. an `Arc<CodeEditor>` it
/// calls `set_text`/`get_text` on from callbacks) -- the same situation
/// `VTile::from_vec`/`HTile::from_vec` exist for, since there's no
/// blanket `Element` impl for `ElementPtr` itself.
pub fn content_ptr(mut self, content: ElementPtr) -> Self {
self.content = Some(content);
self
}
/// Shows a close ("x") button on this tab; clicking it fires
/// `TabBar::on_close` instead of activating the tab. Needed for an
/// editor-style tab bar (one tab per open file) where tabs are closed
/// individually, unlike a fixed set of view tabs.
pub fn closable(mut self, closable: bool) -> Self {
self.closable = closable;
self
}
}
/// A tabbed container element.
pub struct TabBar {
/// Behind a lock (not a plain `Vec`) so tabs can be added/removed at
/// runtime through `&self` -- widgets are shared as `Arc<dyn Element>`
/// once mounted, so an owning `&mut self` is never available again
/// after construction. Needed for an IDE tab bar, where files get
/// opened/closed while the app is running.
tabs: RwLock<Vec<Tab>>,
active_index: RwLock<usize>,
hovered_index: RwLock<Option<usize>>,
hovered_close: RwLock<Option<usize>>,
position: TabPosition,
active_color: Color,
inactive_color: Color,
hover_color: Color,
text_color: Color,
background_color: Color,
tab_height: f32,
tab_padding: f32,
corner_radius: f32,
close_button_size: f32,
on_change: Option<TabChangeCallback>,
on_close: Option<TabCloseCallback>,
}
impl TabBar {
/// Creates a new tab bar.
pub fn new() -> Self {
let theme = get_theme();
Self {
tabs: RwLock::new(Vec::new()),
active_index: RwLock::new(0),
hovered_index: RwLock::new(None),
hovered_close: RwLock::new(None),
position: TabPosition::Top,
active_color: theme.active_tab_color,
inactive_color: theme.inactive_tab_color,
hover_color: theme.tab_hilite_color,
text_color: theme.label_font_color,
background_color: theme.panel_color,
tab_height: 32.0,
tab_padding: 16.0,
corner_radius: 4.0,
close_button_size: 14.0,
on_change: None,
on_close: None,
}
}
/// Adds tabs.
pub fn tabs(self, tabs: Vec<Tab>) -> Self {
*self.tabs.write().unwrap() = tabs;
self
}
/// Sets the close-button callback (only relevant for tabs created with
/// `Tab::closable(true)`).
pub fn on_close<F: Fn(usize) + Send + Sync + 'static>(mut self, callback: F) -> Self {
self.on_close = Some(Box::new(callback));
self
}
/// Appends a new tab at runtime and returns its index. Does not change
/// which tab is active.
pub fn add_tab(&self, tab: Tab) -> usize {
let mut tabs = self.tabs.write().unwrap();
tabs.push(tab);
tabs.len() - 1
}
/// Removes the tab at `index` at runtime. Keeps the active index
/// pointing at the same logical tab it did before the removal: a tab
/// closed *before* the active one shifts the active index down by one;
/// closing the active tab itself activates whichever tab slides into
/// its place (or the new last tab, if it was the last one open).
pub fn remove_tab(&self, index: usize) {
let mut tabs = self.tabs.write().unwrap();
if index >= tabs.len() {
return;
}
tabs.remove(index);
let len = tabs.len();
drop(tabs);
let mut active = self.active_index.write().unwrap();
if len == 0 {
*active = 0;
} else if index < *active {
*active -= 1;
} else if index == *active {
*active = (*active).min(len - 1);
}
}
/// Returns the current number of tabs.
pub fn tab_count(&self) -> usize {
self.tabs.read().unwrap().len()
}
/// Sets the tab position.
pub fn position(mut self, position: TabPosition) -> Self {
self.position = position;
self
}
/// Sets the active color.
pub fn active_color(mut self, color: Color) -> Self {
self.active_color = color;
self
}
/// Sets the inactive color.
pub fn inactive_color(mut self, color: Color) -> Self {
self.inactive_color = color;
self
}
/// Sets the change callback.
pub fn on_change<F: Fn(usize) + Send + Sync + 'static>(mut self, callback: F) -> Self {
self.on_change = Some(Box::new(callback));
self
}
/// Returns the active tab index.
pub fn get_active(&self) -> usize {
*self.active_index.read().unwrap()
}
/// Sets the active tab index.
pub fn set_active(&self, index: usize) {
if index < self.tabs.read().unwrap().len() {
*self.active_index.write().unwrap() = index;
}
}
fn tab_bar_rect(&self, ctx: &Context) -> Rect {
match self.position {
TabPosition::Top => Rect::new(
ctx.bounds.left,
ctx.bounds.top,
ctx.bounds.right,
ctx.bounds.top + self.tab_height,
),
TabPosition::Bottom => Rect::new(
ctx.bounds.left,
ctx.bounds.bottom - self.tab_height,
ctx.bounds.right,
ctx.bounds.bottom,
),
TabPosition::Left => Rect::new(
ctx.bounds.left,
ctx.bounds.top,
ctx.bounds.left + 100.0,
ctx.bounds.bottom,
),
TabPosition::Right => Rect::new(
ctx.bounds.right - 100.0,
ctx.bounds.top,
ctx.bounds.right,
ctx.bounds.bottom,
),
}
}
fn content_rect(&self, ctx: &Context) -> Rect {
match self.position {
TabPosition::Top => Rect::new(
ctx.bounds.left,
ctx.bounds.top + self.tab_height,
ctx.bounds.right,
ctx.bounds.bottom,
),
TabPosition::Bottom => Rect::new(
ctx.bounds.left,
ctx.bounds.top,
ctx.bounds.right,
ctx.bounds.bottom - self.tab_height,
),
TabPosition::Left => Rect::new(
ctx.bounds.left + 100.0,
ctx.bounds.top,
ctx.bounds.right,
ctx.bounds.bottom,
),
TabPosition::Right => Rect::new(
ctx.bounds.left,
ctx.bounds.top,
ctx.bounds.right - 100.0,
ctx.bounds.bottom,
),
}
}
/// Computes tab `index`'s rect given an already-locked `tabs` slice.
/// Takes the slice rather than locking `self.tabs` itself so callers
/// that already hold the read guard (draw/hit-test/click, which need it
/// for more than just this calculation) don't have to take a second,
/// nested lock on the same `RwLock` -- std's `RwLock` doesn't guarantee
/// that's deadlock-free if a writer happens to be queued in between.
fn tab_rect(&self, ctx: &Context, tabs: &[Tab], index: usize) -> Rect {
let bar = self.tab_bar_rect(ctx);
let theme = get_theme();
match self.position {
TabPosition::Top | TabPosition::Bottom => {
let mut x = bar.left;
for (i, tab) in tabs.iter().enumerate() {
let width = tab.label.len() as f32 * theme.label_font_size * 0.6
+ self.tab_padding * 2.0
+ if tab.closable {
self.close_button_size + self.tab_padding * 0.5
} else {
0.0
};
if i == index {
return Rect::new(x, bar.top, x + width, bar.bottom);
}
x += width;
}
}
TabPosition::Left | TabPosition::Right => {
let mut y = bar.top;
for i in 0..tabs.len() {
if i == index {
return Rect::new(bar.left, y, bar.right, y + self.tab_height);
}
y += self.tab_height;
}
}
}
Rect::zero()
}
/// The close ("x") button's hit/draw rect within a tab's own rect, or
/// `Rect::zero()` if that tab isn't closable.
fn close_rect(&self, tabs: &[Tab], index: usize, tab_rect: Rect) -> Rect {
if !tabs.get(index).is_some_and(|t| t.closable) {
return Rect::zero();
}
let size = self.close_button_size;
let y = tab_rect.center().y - size / 2.0;
Rect::new(
tab_rect.right - self.tab_padding * 0.5 - size,
y,
tab_rect.right - self.tab_padding * 0.5,
y + size,
)
}
fn draw_tabs(&self, ctx: &Context, tabs: &[Tab]) {
let mut canvas = ctx.canvas.borrow_mut();
let theme = get_theme();
let bar = self.tab_bar_rect(ctx);
let active = *self.active_index.read().unwrap();
let hovered = *self.hovered_index.read().unwrap();
let hovered_close = *self.hovered_close.read().unwrap();
// Tab bar background
canvas.fill_style(self.background_color);
canvas.fill_rect(bar);
// Draw each tab
for (i, tab) in tabs.iter().enumerate() {
let rect = self.tab_rect(ctx, tabs, i);
let is_active = i == active;
let is_hovered = hovered == Some(i) && !is_active;
// Tab background
let bg_color = if is_active {
self.active_color
} else if is_hovered {
self.hover_color
} else {
self.inactive_color
};
let tab_rect = match self.position {
TabPosition::Top => Rect::new(
rect.left + 1.0,
rect.top + 2.0,
rect.right - 1.0,
rect.bottom,
),
TabPosition::Bottom => Rect::new(
rect.left + 1.0,
rect.top,
rect.right - 1.0,
rect.bottom - 2.0,
),
_ => rect.inset(1.0, 1.0),
};
canvas.fill_style(bg_color);
canvas.fill_round_rect(tab_rect, self.corner_radius);
// Tab text
let text_color = if is_active {
self.text_color
} else {
self.text_color.with_alpha(0.7)
};
canvas.fill_style(text_color);
canvas.font_size(theme.label_font_size);
let x = rect.left + self.tab_padding;
let y = rect.center().y + theme.label_font_size * 0.35;
canvas.fill_text(&tab.label, Point::new(x, y));
if tab.closable {
let close = self.close_rect(tabs, i, rect);
let close_color = if hovered_close == Some(i) {
self.text_color
} else {
self.text_color.with_alpha(0.5)
};
canvas.fill_style(close_color);
canvas.font_size(theme.label_font_size * 0.9);
canvas.fill_text(
"\u{00d7}",
Point::new(close.left, close.center().y + theme.label_font_size * 0.32),
);
}
}
}
fn draw_content(&self, ctx: &Context, tabs: &[Tab]) {
let active = *self.active_index.read().unwrap();
if let Some(tab) = tabs.get(active) {
if let Some(ref content) = tab.content {
let content_rect = self.content_rect(ctx);
let content_ctx = ctx.with_bounds(content_rect);
content.draw(&content_ctx);
}
}
}
}
impl Default for TabBar {
fn default() -> Self {
Self::new()
}
}
impl Element for TabBar {
fn limits(&self, _ctx: &BasicContext) -> ViewLimits {
ViewLimits {
min: Point::new(200.0, 100.0),
max: Point::new(super::FULL_EXTENT, super::FULL_EXTENT),
}
}
fn stretch(&self) -> ViewStretch {
ViewStretch::new(1.0, 1.0)
}
fn draw(&self, ctx: &Context) {
let tabs = self.tabs.read().unwrap();
self.draw_content(ctx, &tabs);
self.draw_tabs(ctx, &tabs);
}
fn hit_test(
&self,
ctx: &Context,
p: Point,
_leaf: bool,
_control: bool,
) -> Option<&dyn Element> {
// Unlike the other containers here, `tabs` sits behind a `RwLock`
// (needed so `add_tab`/`remove_tab` can mutate it through `&self` at
// runtime -- see that field's doc comment) rather than being a
// plain owned `Vec`, so there's no way to hand back a `&dyn Element`
// borrowed from a tab's content with a lifetime tied to `&self`: the
// read guard needed to reach it doesn't live that long. So, like
// `List` (which has the same kind of `RwLock<Vec<_>>` item storage),
// this reports itself as the hit target rather than forwarding into
// nested content; `draw`/`handle_click` (which don't need to return
// a reference) still fully delegate to the active tab's content.
if ctx.bounds.contains(p) {
Some(self)
} else {
None
}
}
fn wants_control(&self) -> bool {
true
}
fn handle_click(&self, ctx: &Context, btn: MouseButton) -> bool {
if btn.button != MouseButtonKind::Left {
return false;
}
if !btn.down {
return true;
}
// Check if clicking on a tab (or its close button)
{
let tabs = self.tabs.read().unwrap();
for i in 0..tabs.len() {
let rect = self.tab_rect(ctx, &tabs, i);
if !rect.contains(btn.pos) {
continue;
}
if self.close_rect(&tabs, i, rect).contains(btn.pos) {
drop(tabs);
if let Some(ref callback) = self.on_close {
callback(i);
}
self.remove_tab(i);
return true;
}
let old_active = *self.active_index.read().unwrap();
if i != old_active {
*self.active_index.write().unwrap() = i;
if let Some(ref callback) = self.on_change {
callback(i);
}
}
return true;
}
}
// Forward to content
let active = *self.active_index.read().unwrap();
let tabs = self.tabs.read().unwrap();
if let Some(tab) = tabs.get(active) {
if let Some(ref content) = tab.content {
let content_rect = self.content_rect(ctx);
let content_ctx = ctx.with_bounds(content_rect);
if content.handle_click(&content_ctx, btn) {
return true;
}
}
}
true
}
// Without these, an editor placed as a tab's content (e.g. MKIDE's
// per-file `CodeEditor`s) never received a single keystroke or scroll
// event: `handle_click` above already forwards to the active tab's
// content, which sets *that* content's own internal focus state and
// makes it look focused (caret and all) -- but with no `handle_key`/
// `handle_text` override here, the default `Element` impls (`false`,
// unconditionally) meant every keystroke was silently swallowed before
// ever reaching the content. Looked exactly like a read-only editor.
fn key(&mut self, ctx: &Context, k: KeyInfo) -> bool {
self.handle_key(ctx, k)
}
fn handle_key(&self, ctx: &Context, k: KeyInfo) -> bool {
let active = *self.active_index.read().unwrap();
let tabs = self.tabs.read().unwrap();
let Some(tab) = tabs.get(active) else {
return false;
};
let Some(ref content) = tab.content else {
return false;
};
let content_rect = self.content_rect(ctx);
let content_ctx = ctx.with_bounds(content_rect);
content.handle_key(&content_ctx, k)
}
fn text(&mut self, ctx: &Context, info: TextInfo) -> bool {
self.handle_text(ctx, info)
}
fn handle_text(&self, ctx: &Context, info: TextInfo) -> bool {
let active = *self.active_index.read().unwrap();
let tabs = self.tabs.read().unwrap();
let Some(tab) = tabs.get(active) else {
return false;
};
let Some(ref content) = tab.content else {
return false;
};
let content_rect = self.content_rect(ctx);
let content_ctx = ctx.with_bounds(content_rect);
content.handle_text(&content_ctx, info)
}
fn scroll(&mut self, ctx: &Context, dir: Point, p: Point) -> bool {
self.handle_scroll(ctx, dir, p)
}
fn handle_scroll(&self, ctx: &Context, dir: Point, p: Point) -> bool {
let active = *self.active_index.read().unwrap();
let tabs = self.tabs.read().unwrap();
let Some(tab) = tabs.get(active) else {
return false;
};
let Some(ref content) = tab.content else {
return false;
};
let content_rect = self.content_rect(ctx);
if !content_rect.contains(p) {
return false;
}
let content_ctx = ctx.with_bounds(content_rect);
content.handle_scroll(&content_ctx, dir, p)
}
fn clear_focus(&self) {
if let Some(tab) = self
.tabs
.read()
.unwrap()
.get(*self.active_index.read().unwrap())
{
if let Some(ref content) = tab.content {
content.clear_focus();
}
}
}
fn cursor(&mut self, ctx: &Context, p: Point, status: CursorTracking) -> bool {
match status {
CursorTracking::Leaving => {
*self.hovered_index.write().unwrap() = None;
*self.hovered_close.write().unwrap() = None;
}
_ => {
let mut hovered = self.hovered_index.write().unwrap();
let mut hovered_close = self.hovered_close.write().unwrap();
*hovered = None;
*hovered_close = None;
let tabs = self.tabs.read().unwrap();
for i in 0..tabs.len() {
let rect = self.tab_rect(ctx, &tabs, i);
if rect.contains(p) {
*hovered = Some(i);
if self.close_rect(&tabs, i, rect).contains(p) {
*hovered_close = Some(i);
}
break;
}
}
}
}
true
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
/// Creates a tab bar.
pub fn tab_bar() -> TabBar {
TabBar::new()
}
/// Creates a tab.
pub fn tab(label: impl Into<String>) -> Tab {
Tab::new(label)
}
#[cfg(test)]
mod tab_bar_focus_forwarding_tests {
use super::*;
use crate::element::code_editor::code_editor;
use crate::support::canvas::Canvas;
use crate::view::{KeyAction, KeyCode, MouseButtonKind, TextInfo};
use std::cell::RefCell;
/// A `CodeEditor` hosted as a tab's content used to never receive a
/// single keystroke -- `TabBar` forwarded clicks (so the editor looked
/// focused, caret and all) but had no `handle_key`/`handle_text`
/// override, so the default no-op `Element` impls silently swallowed
/// every keystroke before it reached the editor. Indistinguishable
/// from the editor being read-only. This reproduces that exact path.
#[test]
fn typing_through_tab_bar_reaches_active_tab_content() {
let editor = share(code_editor().text(""));
let bar = TabBar::new().tabs(vec![Tab::new("file.rs").content_ptr(editor.clone())]);
let view = crate::view::View::new(crate::support::point::Extent::new(700.0, 400.0));
let canvas = RefCell::new(Canvas::new(700, 400).unwrap());
let bounds = Rect::new(0.0, 0.0, 700.0, 400.0);
let ctx = Context::new(&view, &canvas, bounds);
let click_pos = Point::new(60.0, 200.0);
let down = MouseButton {
down: true,
click_count: 1,
button: MouseButtonKind::Left,
modifiers: 0,
pos: click_pos,
};
assert!(
bar.handle_click(&ctx, down),
"click into the content area should be handled"
);
assert!(
bar.handle_text(
&ctx,
TextInfo {
codepoint: 'h',
modifiers: 0
}
),
"typed text should reach the active tab's content"
);
assert!(
bar.handle_key(
&ctx,
KeyInfo {
key: KeyCode::Left,
action: KeyAction::Press,
modifiers: 0
}
),
"arrow keys should reach the active tab's content"
);
assert_eq!(
editor
.as_any()
.downcast_ref::<crate::element::code_editor::CodeEditor>()
.unwrap()
.get_text(),
"h"
);
}
}