-
-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathcentral_panel.rs
More file actions
3599 lines (3283 loc) · 192 KB
/
Copy pathcentral_panel.rs
File metadata and controls
3599 lines (3283 loc) · 192 KB
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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Central panel rendering for the Ferrite application.
//!
//! This module renders the main editor content area including the tab bar,
//! editor widget (raw/rendered/split views), CSV viewer, tree viewer,
//! minimap, and navigation buttons.
use super::helpers::{get_formatting_state_for, modifier_symbol};
use super::types::{DeferredFormatAction, HeadingNavRequest};
use super::FerriteApp;
use crate::config::{ShortcutCommand, ViewMode};
use crate::editor::{
show_split_sync_footer, EditorWidget, Minimap, SearchHighlights, SemanticMinimap,
SplitSyncFooterOutput, SPLIT_SYNC_FOOTER_HEIGHT,
};
use crate::markdown::{
get_structured_file_type, get_tabular_file_type, rendered_editor_id, CodeExecutionUi,
CsvViewer, EditorMode, MarkdownEditor, TreeViewer, WikilinkContext,
};
use crate::preview::{ScrollOrigin, SyncScrollState};
use crate::state::{SpecialTabKind, TabContent, TabKind};
use crate::theme::ThemeColors;
use crate::ui::phosphor_icons::{phosphor_font, X};
use crate::ui::{
render_action_menu_with_shortcuts, set_overlay_blocks_nav_buttons, ActionContext,
ActionRegistry, ContextActionId, FileOperationResult, FormatToolbar, GoToLineResult,
RibbonAction,
};
use eframe::egui;
use log::{debug, info, trace, warn};
use rust_i18n::t;
use std::path::{Path, PathBuf};
// ─────────────────────────────────────────────────────────────────────────────
// Image Viewer Texture Cache
// ─────────────────────────────────────────────────────────────────────────────
#[derive(Clone)]
struct ImageViewerTexture {
texture: Option<egui::TextureHandle>,
width: u32,
height: u32,
error: Option<String>,
}
fn load_viewer_image(ctx: &egui::Context, path: &Path) -> Result<ImageViewerTexture, String> {
let bytes = std::fs::read(path).map_err(|e| format!("Failed to read: {}", e))?;
let img = image::load_from_memory(&bytes).map_err(|e| format!("Failed to decode: {}", e))?;
let rgba = img.to_rgba8();
let (width, height) = rgba.dimensions();
let pixels: Vec<egui::Color32> = rgba
.pixels()
.map(|p| egui::Color32::from_rgba_unmultiplied(p[0], p[1], p[2], p[3]))
.collect();
let color_image = egui::ColorImage {
size: [width as usize, height as usize],
source_size: egui::vec2(width as f32, height as f32),
pixels,
};
let texture_name = format!("img_viewer_{}", path.display());
let texture = ctx.load_texture(&texture_name, color_image, egui::TextureOptions::LINEAR);
Ok(ImageViewerTexture {
texture: Some(texture),
width,
height,
error: None,
})
}
// ─────────────────────────────────────────────────────────────────────────────
// PDF Viewer Texture Cache
// ─────────────────────────────────────────────────────────────────────────────
#[derive(Clone)]
struct PdfPageTexture {
texture: Option<egui::TextureHandle>,
width: u32,
height: u32,
/// Cache key fields (reserved for texture invalidation).
_page_index: usize,
_zoom: f32,
error: Option<String>,
}
fn render_pdf_page(
ctx: &egui::Context,
path: &Path,
page_index: usize,
zoom: f32,
) -> PdfPageTexture {
use hayro::hayro_interpret::hayro_syntax::Pdf;
use hayro::hayro_interpret::InterpreterSettings;
use hayro::RenderSettings;
let bytes = match std::fs::read(path) {
Ok(b) => b,
Err(e) => {
return PdfPageTexture {
texture: None,
width: 0,
height: 0,
_page_index: page_index,
_zoom: zoom,
error: Some(format!("Failed to read file: {}", e)),
}
}
};
let pdf_data = std::sync::Arc::new(bytes);
let pdf = match Pdf::new(pdf_data) {
Ok(p) => p,
Err(e) => {
return PdfPageTexture {
texture: None,
width: 0,
height: 0,
_page_index: page_index,
_zoom: zoom,
error: Some(format!("Failed to parse PDF: {:?}", e)),
}
}
};
let pages = pdf.pages();
if page_index >= pages.len() {
return PdfPageTexture {
texture: None,
width: 0,
height: 0,
_page_index: page_index,
_zoom: zoom,
error: Some(format!(
"Page {} out of range (total: {})",
page_index + 1,
pages.len()
)),
};
}
let page = &pages[page_index];
let interpreter_settings = InterpreterSettings::default();
let render_settings = RenderSettings {
x_scale: zoom,
y_scale: zoom,
bg_color: {
use hayro::vello_cpu::color::{AlphaColor, Srgb};
AlphaColor::<Srgb>::new([1.0, 1.0, 1.0, 1.0])
},
..Default::default()
};
let pixmap = hayro::render(page, &interpreter_settings, &render_settings);
let width = pixmap.width() as u32;
let height = pixmap.height() as u32;
let rgba_data = pixmap.data_as_u8_slice();
let pixels: Vec<egui::Color32> = rgba_data
.chunks_exact(4)
.map(|c| egui::Color32::from_rgba_premultiplied(c[0], c[1], c[2], c[3]))
.collect();
let color_image = egui::ColorImage {
size: [width as usize, height as usize],
source_size: egui::vec2(width as f32, height as f32),
pixels,
};
let texture_name = format!("pdf_page_{}_{}_{:.2}", path.display(), page_index, zoom);
let texture = ctx.load_texture(&texture_name, color_image, egui::TextureOptions::LINEAR);
PdfPageTexture {
texture: Some(texture),
width,
height,
_page_index: page_index,
_zoom: zoom,
error: None,
}
}
impl FerriteApp {
fn render_untitled_tab_rename_dialog(&mut self, ctx: &egui::Context) {
let Some((tab_idx, mut buffer)) = self.state.ui.rename_untitled_tab.take() else {
return;
};
let mut open = true;
let mut apply_clicked = false;
let mut cancel_clicked = false;
egui::Window::new(t!("dialog.rename_untitled_tab.title"))
.open(&mut open)
.collapsible(false)
.resizable(false)
.default_width(360.0)
.anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO)
.order(egui::Order::Foreground)
.show(ctx, |ui| {
if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
cancel_clicked = true;
ui.ctx().input_mut(|i| {
i.consume_key(egui::Modifiers::NONE, egui::Key::Escape);
});
}
ui.label(t!("dialog.rename_untitled_tab.hint"));
ui.add_space(6.0);
let text_response =
ui.add(egui::TextEdit::singleline(&mut buffer).desired_width(f32::INFINITY));
text_response.request_focus();
if ui.input(|i| i.key_pressed(egui::Key::Enter)) {
apply_clicked = true;
ui.ctx().input_mut(|i| {
i.consume_key(egui::Modifiers::NONE, egui::Key::Enter);
});
}
ui.add_space(8.0);
ui.horizontal(|ui| {
if ui.button(t!("dialog.rename_untitled_tab.apply")).clicked() {
apply_clicked = true;
}
if ui.button(t!("dialog.confirm.cancel")).clicked() {
cancel_clicked = true;
}
});
});
if apply_clicked {
self.state.apply_untitled_tab_rename(tab_idx, buffer);
} else if open && !cancel_clicked {
self.state.ui.rename_untitled_tab = Some((tab_idx, buffer));
}
}
/// Render the central panel containing tabs and editor content.
///
/// Returns a deferred format action if one was requested.
pub(crate) fn render_central_panel(
&mut self,
ui: &mut egui::Ui,
is_dark: bool,
) -> Option<DeferredFormatAction> {
let ctx = ui.ctx().clone();
let zen_mode = self.state.is_zen_mode();
let mut deferred_format_action: Option<DeferredFormatAction> = None;
let mut pending_wikilink_target: Option<String> = None;
let overlay_blocks_nav = self.quick_switcher.is_open()
|| self.command_palette.is_open()
|| self.search_panel.is_open();
set_overlay_blocks_nav_buttons(&ctx, overlay_blocks_nav);
self.render_untitled_tab_rename_dialog(&ctx);
// Get the theme-appropriate fill color from the current visuals
let fill_color = ctx.global_style().visuals.panel_fill;
egui::CentralPanel::default()
.frame(egui::Frame::default().inner_margin(egui::Margin::ZERO).fill(fill_color))
.show_inside(ui, |ui| {
// Tab bar - uses custom wrapping layout for multi-line support
// Hidden in Zen Mode for distraction-free editing
let mut tab_to_close: Option<usize> = None;
let mut tab_swap: Option<(usize, usize)> = None;
let mut tab_context_copy_path: Option<PathBuf> = None;
let mut tab_context_reveal_path: Option<PathBuf> = None;
let mut tab_context_new_tab = false;
let mut tab_context_menu_opened_this_frame = false;
if !zen_mode {
// Collect tab info first to avoid borrow issues
let tab_count = self.state.tab_count();
let active_index = self.state.active_tab_index();
let tab_titles: Vec<(usize, usize, String, bool, Option<PathBuf>)> = (0..tab_count)
.filter_map(|i| {
self.state
.tab(i)
.map(|tab| (i, tab.id, tab.title(), i == active_index, tab.path.clone()))
})
.collect();
// Custom wrapping tab bar
let available_width = ui.available_width();
let tab_height = 24.0;
let tab_spacing = 4.0;
let close_btn_width = 18.0;
let tab_padding = 16.0; // horizontal padding inside tab
let min_text_width = 60.0;
// Pre-calculate tab widths using actual text measurement
// This ensures consistent sizing between layout and render passes
let tab_widths: Vec<f32> = tab_titles
.iter()
.map(|(_, _, title, _, _)| {
let text_galley = ui.fonts_mut(|f| {
f.layout_no_wrap(
title.clone(),
egui::FontId::default(),
egui::Color32::WHITE // color doesn't affect measurement
)
});
let text_width = text_galley.size().x.max(min_text_width);
text_width + close_btn_width + tab_padding
})
.collect();
// Calculate tab positions for layout
let mut current_x = 0.0;
let mut current_row = 0;
let mut tab_positions: Vec<(f32, usize)> = Vec::new(); // (x position, row)
for tab_width in &tab_widths {
// Check if we need to wrap to next row
if current_x + tab_width > available_width && current_x > 0.0 {
current_x = 0.0;
current_row += 1;
}
tab_positions.push((current_x, current_row));
current_x += tab_width + tab_spacing;
}
// Add position for the + button
let plus_btn_width = 24.0;
if current_x + plus_btn_width > available_width && current_x > 0.0 {
current_row += 1;
}
let total_rows = current_row + 1;
let total_height = (total_rows as f32) * (tab_height + 2.0);
// Allocate space for all tab rows
let (tab_bar_rect, _) = ui.allocate_exact_size(
egui::vec2(available_width, total_height),
egui::Sense::hover()
);
// Render tabs
let is_dark = ui.visuals().dark_mode;
let selected_bg = ui.visuals().selection.bg_fill;
let hover_bg = if is_dark {
egui::Color32::from_rgb(60, 60, 70)
} else {
egui::Color32::from_rgb(220, 220, 230)
};
let text_color = ui.visuals().text_color();
for (((tab_idx, tab_id, title, selected, tab_path), (x_pos, row)), tab_width) in tab_titles
.iter()
.zip(tab_positions.iter())
.zip(tab_widths.iter())
{
// Use pre-calculated tab width for consistency
let tab_width = *tab_width;
let tab_rect = egui::Rect::from_min_size(
tab_bar_rect.min + egui::vec2(*x_pos, (*row as f32) * (tab_height + 2.0)),
egui::vec2(tab_width, tab_height)
);
// Split click/right-click from drag handling so the context
// menu stays responsive while drag reorder still works.
let tab_click_response = ui.interact(
tab_rect,
egui::Id::new("tab_click").with(*tab_id),
egui::Sense::click()
);
let tab_drag_response = ui.interact(
tab_rect,
egui::Id::new("tab_drag").with(*tab_id),
egui::Sense::drag()
);
let tab_hovered = tab_click_response.hovered() || tab_drag_response.hovered();
if tab_click_response.double_clicked() {
if let Some(tab) = self.state.tab(*tab_idx) {
if matches!(tab.kind, TabKind::Document)
&& tab.path.is_none()
&& matches!(tab.tab_content, TabContent::Ready)
{
self.state.ui.rename_untitled_tab = Some((
*tab_idx,
tab.untitled_rename_buffer_initial(),
));
}
}
}
let tab_secondary_clicked = tab_click_response.secondary_clicked()
|| ui.input(|i| {
i.pointer.button_clicked(egui::PointerButton::Secondary)
&& i.pointer
.interact_pos()
.is_some_and(|pos| tab_rect.contains(pos))
});
if tab_secondary_clicked {
self.state.set_active_tab(*tab_idx);
self.pending_cjk_check = true;
let popup_pos = ui
.ctx()
.input(|i| i.pointer.interact_pos())
.unwrap_or(tab_rect.left_bottom());
self.state.ui.tab_context_menu = Some((*tab_idx, popup_pos));
tab_context_menu_opened_this_frame = true;
ui.ctx().request_repaint();
}
// Handle drag-and-drop for tab reordering
if tab_drag_response.dragged() {
egui::DragAndDrop::set_payload(ui.ctx(), *tab_idx);
// Show drag cursor
ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
}
// Check if another tab is being dropped on this one
let mut is_drop_target = false;
if tab_hovered && ui.ctx().input(|i| i.pointer.any_released()) {
if
let Some(dragged_tab_idx) = egui::DragAndDrop::payload::<usize>(
ui.ctx()
)
{
let dragged_idx = *dragged_tab_idx;
if dragged_idx != *tab_idx {
tab_swap = Some((dragged_idx, *tab_idx));
}
}
}
if tab_hovered {
if egui::DragAndDrop::payload::<usize>(ui.ctx()).is_some() {
is_drop_target = true;
}
}
// Draw tab background
if is_drop_target {
// Show drop indicator
let indicator_color = if is_dark {
egui::Color32::from_rgb(80, 120, 200)
} else {
egui::Color32::from_rgb(100, 150, 230)
};
ui.painter().rect_filled(tab_rect, 4.0, indicator_color);
} else if *selected {
ui.painter().rect_filled(tab_rect, 4.0, selected_bg);
} else if tab_hovered {
ui.painter().rect_filled(tab_rect, 4.0, hover_bg);
}
// Draw tab title - use available width minus close button and padding
let title_available_width = tab_width - close_btn_width - tab_padding;
let title_rect = egui::Rect::from_min_size(
tab_rect.min + egui::vec2(8.0, 4.0),
egui::vec2(title_available_width, tab_height - 8.0)
);
ui.painter().text(
title_rect.left_center(),
egui::Align2::LEFT_CENTER,
title,
egui::FontId::default(),
text_color
);
// Draw close button
let close_rect = egui::Rect::from_min_size(
egui::pos2(tab_rect.right() - close_btn_width - 4.0, tab_rect.top() + 4.0),
egui::vec2(close_btn_width, tab_height - 8.0)
);
let close_response = ui.interact(
close_rect,
egui::Id::new("tab_close").with(*tab_id),
egui::Sense::click()
);
let close_color = if close_response.hovered() {
egui::Color32::from_rgb(220, 80, 80)
} else {
text_color
};
ui.painter().text(
close_rect.center(),
egui::Align2::CENTER_CENTER,
X,
phosphor_font(12.0),
close_color
);
// Handle interactions
let primary_pressed_in_tab = ui.input(|i| {
i.pointer.button_pressed(egui::PointerButton::Primary)
&& i.pointer.interact_pos().is_some_and(|pos| {
tab_rect.contains(pos) && !close_rect.contains(pos)
})
});
if primary_pressed_in_tab
|| (tab_click_response.clicked() && !close_response.hovered())
{
self.state.set_active_tab(*tab_idx);
self.pending_cjk_check = true;
}
if close_response.clicked() || tab_click_response.middle_clicked() {
tab_to_close = Some(*tab_idx);
}
if close_response.hovered() {
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
} else if tab_hovered {
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
}
if tab_hovered && !close_response.hovered() {
if let Some(path) = tab_path {
egui::Tooltip::always_open(
ui.ctx().clone(),
ui.layer_id(),
egui::Id::new("tab_path_tooltip").with(*tab_id),
egui::PopupAnchor::Pointer,
)
.show(|ui| {
ui.set_max_width(480.0);
ui.label(path.display().to_string());
});
}
}
}
// Draw + button - use pre-calculated tab widths for consistency
let plus_x = if tab_positions.is_empty() || tab_widths.is_empty() {
0.0
} else {
let last_pos = tab_positions.last().unwrap();
let last_width = *tab_widths.last().unwrap();
if last_pos.0 + last_width + tab_spacing + plus_btn_width > available_width {
0.0 // Wrap to next row
} else {
last_pos.0 + last_width + tab_spacing
}
};
let plus_row = if tab_positions.is_empty() {
0
} else if plus_x == 0.0 && !tab_positions.is_empty() {
tab_positions.last().unwrap().1 + 1
} else {
tab_positions.last().unwrap().1
};
let plus_rect = egui::Rect::from_min_size(
tab_bar_rect.min + egui::vec2(plus_x, (plus_row as f32) * (tab_height + 2.0)),
egui::vec2(plus_btn_width, tab_height)
);
let plus_response = ui.interact(
plus_rect,
egui::Id::new("new_tab_btn"),
egui::Sense::click()
);
if plus_response.hovered() {
ui.painter().rect_filled(plus_rect, 4.0, hover_bg);
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
}
ui.painter().text(
plus_rect.center(),
egui::Align2::CENTER_CENTER,
"+",
egui::FontId::default(),
text_color
);
if plus_response.clicked() {
tab_context_new_tab = true;
}
plus_response
.clone()
.on_hover_text(t!("tooltip.new_tab").to_string());
if let Some((tab_idx, popup_pos)) = self.state.ui.tab_context_menu {
let menu_id = ui.make_persistent_id("tab_strip_context_menu");
let tab_path = self.state.tab(tab_idx).and_then(|tab| tab.path.clone());
let mut selected_action: Option<ContextActionId> = None;
let actions = ActionRegistry::actions_for(ActionContext::Tab {
has_file_path: tab_path.is_some(),
});
let area_response = egui::Area::new(menu_id)
.order(egui::Order::Foreground)
.fixed_pos(popup_pos)
.interactable(true)
.show(ui.ctx(), |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| {
ui.set_min_width(230.0);
selected_action = render_action_menu_with_shortcuts(
ui,
&actions,
Some(&self.state.settings.keyboard_shortcuts),
);
});
});
match selected_action {
Some(ContextActionId::NewTab) => tab_context_new_tab = true,
Some(ContextActionId::CloseTab) => tab_to_close = Some(tab_idx),
Some(ContextActionId::CopyPath) => {
tab_context_copy_path = tab_path.clone();
}
Some(ContextActionId::RevealInExplorer) => {
tab_context_reveal_path = tab_path.clone();
}
None => {}
}
let action_clicked = tab_context_new_tab
|| tab_to_close == Some(tab_idx)
|| tab_context_copy_path.is_some()
|| tab_context_reveal_path.is_some();
let escape_pressed = ui.input(|i| i.key_pressed(egui::Key::Escape));
let outside_pressed = !tab_context_menu_opened_this_frame
&& ui.input(|i| {
i.pointer.any_pressed()
&& i.pointer
.interact_pos()
.is_some_and(|pos| !area_response.response.rect.contains(pos))
});
if action_clicked || escape_pressed || outside_pressed {
self.state.ui.tab_context_menu = None;
}
}
if tab_context_new_tab {
self.state.new_tab();
}
// Handle tab swap (drag-and-drop reorder)
if let Some((from_idx, to_idx)) = tab_swap {
if self.state.swap_tabs(from_idx, to_idx) {
debug!("Reordered tabs: {} <-> {}", from_idx, to_idx);
}
}
// Handle tab close action
if let Some(index) = tab_to_close {
self.state.ui.tab_context_menu = None;
// Get tab_id before closing for viewer state cleanup
let tab_id = self.state
.tabs()
.get(index)
.map(|t| t.id);
self.state.close_tab(index);
if let Some(id) = tab_id {
self.cleanup_tab_state(id, Some(ui.ctx()));
}
}
if let Some(path) = tab_context_copy_path {
ui.ctx().copy_text(path.display().to_string());
}
if let Some(path) = tab_context_reveal_path {
if let Err(e) = open::that(&path) {
warn!("Failed to reveal tab in explorer: {}", e);
self.state
.show_error(t!("error.explorer_failed", error = e.to_string()).to_string());
} else {
debug!("Revealed tab in explorer: {}", path.display());
}
}
// Draw a visible separator line between tabs and editor
// Uses stronger contrast than default egui separator for accessibility
ui.add_space(2.0);
{
let separator_color = if is_dark {
egui::Color32::from_rgb(60, 60, 60)
} else {
egui::Color32::from_rgb(160, 160, 160) // ~3.2:1 contrast on white
};
let rect = ui.available_rect_before_wrap();
let y = rect.min.y;
ui.painter().line_segment(
[egui::pos2(rect.min.x, y), egui::pos2(rect.max.x, y)],
egui::Stroke::new(1.0, separator_color)
);
}
ui.add_space(3.0);
} else {
self.state.ui.tab_context_menu = None;
} // End of tab bar (hidden in Zen Mode)
// Check if active tab is a special tab (settings, about, etc.)
// If so, render the special tab content instead of the editor
let active_tab_kind = self.state
.active_tab()
.map(|t| t.kind.clone())
.unwrap_or(TabKind::Document);
// Check if the active tab is loading or has a load error
let active_tab_content = self.state
.active_tab()
.map(|t| t.tab_content.clone());
if let TabKind::Special(special_kind) = active_tab_kind {
self.render_special_tab_content(ui, special_kind);
} else if matches!(active_tab_kind, TabKind::ImageViewer(_)) {
self.render_image_viewer_tab(ui, &ctx);
} else if matches!(active_tab_kind, TabKind::PdfViewer(_)) {
self.render_pdf_viewer_tab(ui, &ctx);
} else if let Some(crate::state::TabContent::Loading(ref progress)) = active_tab_content {
self.render_loading_tab(ui, progress);
ctx.request_repaint_after(std::time::Duration::from_millis(100));
} else if let Some(crate::state::TabContent::Error(ref error)) = active_tab_content {
Self::render_load_error_tab(ui, error);
} else {
// Recovery-vs-disk conflict banner (task 106.5).
// Rendered above the editor so the user can decide between
// `Keep Recovered` and `Reload from Disk` without it blocking
// input — they can keep typing while the banner is visible.
self.render_recovery_conflict_banner(ui);
// Editor widget - extract settings values to avoid borrow conflicts
let font_size = self.state.settings.font_size;
let font_family = self.state.settings.font_family.clone();
let word_wrap = self.state.settings.word_wrap;
let theme = self.state.settings.theme;
let show_line_numbers = self.state.settings.show_line_numbers;
let auto_close_brackets = self.state.settings.auto_close_brackets;
let vim_mode = self.state.settings.vim_mode;
// Get theme colors for line number styling
let theme_colors = ThemeColors::from_theme(
theme,
ui.visuals(),
self.state.settings.ferrite_accent_rgb(),
);
// Prepare search highlights if find panel is open
let search_highlights = if
self.state.ui.show_find_replace &&
!self.state.ui.find_state.matches.is_empty()
{
let highlights = SearchHighlights {
matches: self.state.ui.find_state.matches.clone(),
current_match: self.state.ui.find_state.current_match,
scroll_to_match: self.state.ui.scroll_to_match,
};
// Clear scroll flag after using it
self.state.ui.scroll_to_match = false;
Some(highlights)
} else {
None
};
// Extract pending scroll request before mutable borrow
let scroll_to_line = self.pending_scroll_to_line.take();
// Get tab metadata before mutable borrow
let tab_info = self.state
.active_tab()
.map(|t| {
(
t.id,
t.view_mode,
t.path.as_ref().and_then(|p| get_structured_file_type(p)),
t.path.as_ref().and_then(|p| get_tabular_file_type(p)),
t.transient_highlight_range(),
)
});
if
let Some((tab_id, view_mode, structured_type, tabular_type, transient_hl)) =
tab_info
{
match view_mode {
ViewMode::Raw => {
// Raw mode: use the plain EditorWidget with optional minimap
let zen_max_column_width = self.state.settings.zen_max_column_width;
let max_line_width = self.state.settings.max_line_width;
// Capture scroll offset before mutable borrow for scroll detection
let prev_scroll_offset = self.state
.active_tab()
.map(|t| t.scroll_offset)
.unwrap_or(0.0);
// Get folding settings (before mutable borrow)
let folding_enabled = self.state.settings.folding_enabled;
let show_fold_indicators =
self.state.settings.folding_show_indicators && folding_enabled;
let fold_headings = self.state.settings.fold_headings;
let fold_code_blocks = self.state.settings.fold_code_blocks;
let fold_lists = self.state.settings.fold_lists;
let fold_indentation = self.state.settings.fold_indentation;
// Get bracket matching setting
let highlight_matching_pairs =
self.state.settings.highlight_matching_pairs;
// Get syntax highlighting settings
let syntax_highlighting_enabled =
self.state.settings.syntax_highlighting_enabled;
let syntax_theme = if self.state.settings.syntax_theme.is_empty() {
None
} else {
Some(self.state.settings.syntax_theme.clone())
};
let default_syntax_language =
self.state.settings.default_syntax_language.clone();
// Get minimap settings (hidden in Zen Mode)
// Disable minimap for large files to avoid per-frame content iteration
let is_tab_large_file = self.state
.active_tab()
.map(|t| t.is_large_file())
.unwrap_or(false);
let minimap_enabled =
self.state.settings.minimap_enabled &&
!zen_mode &&
!is_tab_large_file;
let minimap_width = self.state.settings.minimap_width;
let minimap_mode = self.state.settings.minimap_mode;
// Check if file is markdown (for auto mode minimap selection)
// Check extension directly to avoid any caching issues
let is_markdown_file = self.state
.active_tab()
.map(|tab| {
match &tab.path {
Some(path) => {
// Check extension directly
let ext_result = path
.extension()
.and_then(|e| e.to_str())
.map(
|ext|
ext.eq_ignore_ascii_case("md") ||
ext.eq_ignore_ascii_case("markdown")
)
.unwrap_or(false); // No extension = not markdown
trace!(
"Minimap file type check: path={:?}, ext={:?}, is_markdown={}",
path.file_name(),
path.extension(),
ext_result
);
ext_result
}
None => {
trace!(
"Minimap file type check: unsaved file, defaulting to markdown"
);
true // Unsaved files default to markdown
}
}
})
.unwrap_or(true);
// Determine whether to use semantic minimap based on mode setting
let use_semantic_minimap = minimap_mode.use_semantic(is_markdown_file);
// Get tab data needed for minimap before mutable borrow
// For semantic: structure-based minimap with headings
// For pixel: code overview minimap
let semantic_minimap_data = if minimap_enabled && use_semantic_minimap {
self.state.active_tab().map(|t| {
// Extract outline for semantic minimap
let outline = crate::editor::extract_outline_for_file(
&t.content,
t.path.as_deref()
);
let total_lines = t.content.lines().count();
(
outline,
t.scroll_offset,
t.content_height,
t.raw_line_height,
t.cursor_position.0 + 1, // Convert 0-indexed to 1-indexed line
total_lines,
)
})
} else {
None
};
let pixel_minimap_data = if minimap_enabled && !use_semantic_minimap {
self.state
.active_tab()
.map(|t| {
(
t.content.clone(),
t.scroll_offset,
t.viewport_height,
t.content_height,
t.raw_line_height,
)
})
} else {
None
};
// Get search matches for pixel minimap visualization
let minimap_search_matches: Vec<(usize, usize)> = if
minimap_enabled &&
!use_semantic_minimap
{
self.state.ui.find_state.matches.clone()
} else {
Vec::new()
};
let minimap_current_match = self.state.ui.find_state.current_match;
// Track minimap scroll request
let mut minimap_nav_request: Option<HeadingNavRequest> = None;
let mut minimap_scroll_to_offset: Option<f32> = None;
let mut ime_text_for_font_loading: Option<String> = None;
// Clone tab path before mutable borrow for syntax highlighting
let tab_path_for_syntax = self.state
.active_tab()
.and_then(|t| t.path.clone());
// Collect diagnostics for the active tab's file (cloned to avoid borrow conflict)
let mut tab_diagnostics: Vec<crate::lsp::state::DiagnosticEntry> =
tab_path_for_syntax
.as_ref()
.and_then(|p| self.state.diagnostics.get(p))
.map(|d| d.to_vec())
.unwrap_or_default();
// Append Mermaid parse-time validation diagnostics
// for markdown files so the raw editor shows
// squiggles under broken ```mermaid``` blocks.
if is_markdown_file {
if let Some(content) = self.state
.active_tab()
.map(|t| t.content.clone())
{
tab_diagnostics.extend(
crate::markdown::compute_mermaid_diagnostics(&content),
);
}
}
// Raw mode: FerriteEditor owns undo via EditHistory
// — no central-panel snapshot needed.
// Format toolbar state (markdown files only, hidden in Zen Mode)
let show_format_toolbar = is_markdown_file && !zen_mode;
let format_toolbar_expanded = self.state.settings.format_toolbar_visible;
let raw_formatting_state = if show_format_toolbar {
self.state.active_tab().map(|tab| {
get_formatting_state_for(
&tab.content,
tab.cursor_position.0,
tab.cursor_position.1,
)
})
} else {
None
};
let mut format_bar_toggled = false;
let mut format_bar_action: Option<RibbonAction> = None;
let mut vim_label_for_status: Option<&'static str> = None;
let mut content_changed_in_editor = false;
if let Some(tab) = self.state.active_tab_mut() {
// Update folds if dirty
if folding_enabled && tab.folds_dirty() {
tab.update_folds(
fold_headings,
fold_code_blocks,
fold_lists,
fold_indentation
);
}
// Calculate format toolbar height
let format_bar_height = if show_format_toolbar {
if format_toolbar_expanded { 32.0 } else { 18.0 }
} else {
0.0
};
// Calculate layout for editor and minimap
let total_rect = ui.available_rect_before_wrap();
// Reserve space for format toolbar at the bottom
let content_rect = egui::Rect::from_min_max(
total_rect.min,
egui::pos2(total_rect.max.x, total_rect.max.y - format_bar_height),
);
let format_bar_rect = if show_format_toolbar {
Some(egui::Rect::from_min_max(
egui::pos2(total_rect.min.x, total_rect.max.y - format_bar_height),
total_rect.max,
))
} else {
None
};
let editor_width = if minimap_enabled {