dracon-terminal-engine 0.1.10

A terminal application framework for Rust with composable widgets, z-indexed compositor, themes, and TextEditor
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
#![allow(missing_docs)]

//! Utility functions for terminal UI rendering, file operations, and system interactions.

use chrono::{DateTime, Local};
use ratatui::{
    style::{Color, Modifier, Style},
    text::{Line, Span},
};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::time::SystemTime;

/// Icon rendering mode based on terminal capabilities.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub enum IconMode {
    /// Nerd Font icons (e.g.,  nf-fa-file)
    Nerd,
    /// Unicode box-drawing andmiscellaneous symbols
    Unicode,
    /// Plain ASCII characters
    ASCII,
}

/// File listing column types for display configuration.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub enum FileColumn {
    /// File name
    Name,
    /// File size in bytes
    Size,
    /// Last modified timestamp
    Modified,
    /// Creation timestamp
    Created,
    /// Unix-style permissions (rwxrwxrwx)
    Permissions,
}

/// Guesses the appropriate icon rendering mode based on terminal environment variables.
///
/// Checks `TERM`, `TERM_PROGRAM`, `TERMINAL_EMULATOR`, and `KONSOLE_VERSION`
/// to detect Nerd Font-compatible, Unicode, or ASCII-only terminals.
pub fn guess_icon_mode() -> IconMode {
    let term = std::env::var("TERM").unwrap_or_default().to_lowercase();
    let term_program = std::env::var("TERM_PROGRAM")
        .unwrap_or_default()
        .to_lowercase();

    if term.contains("kitty")
        || term.contains("alacritty")
        || term.contains("wezterm")
        || term.contains("konsole")
        || term.contains("foot")
        || term.contains("tmux")
        || term.contains("nerd")
        || term_program.contains("vscode")
        || term_program.contains("iterm")
        || term_program.contains("warp")
        || std::env::var("TERMINAL_EMULATOR")
            .map(|s| s.to_lowercase().contains("jetbrains"))
            .unwrap_or(false)
        || std::env::var("KONSOLE_VERSION").is_ok()
    {
        return IconMode::Nerd;
    }

    if std::env::var("COLORTERM").is_ok() {
        return IconMode::Unicode;
    }

    IconMode::ASCII
}

/// Tracks file selection state in a list or grid view.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct SelectionState {
    /// Currently focused/anchored item index
    pub selected: Option<usize>,
    /// Anchor point for shift-click range selection
    pub anchor: Option<usize>,
    /// Set of indices selected in multi-select mode
    pub multi: HashSet<usize>,
}

impl SelectionState {
    /// Creates a new empty selection state.
    pub fn new() -> Self {
        Self::default()
    }

    /// Clears all selection state including multi-select.
    pub fn clear(&mut self) {
        self.multi.clear();
        self.selected = None;
        self.anchor = None;
    }

    /// Clears only multi-selection, keeping anchor and single selection.
    pub fn clear_multi(&mut self) {
        self.multi.clear();
    }

    /// Returns true if no items are multi-selected.
    pub fn is_empty(&self) -> bool {
        self.multi.is_empty()
    }

    /// Returns the set of indices that are currently multi-selected.
    pub fn multi_selected_indices(&self) -> &HashSet<usize> {
        &self.multi
    }

    /// Adds an index to the multi-selection set.
    pub fn add(&mut self, idx: usize) {
        self.multi.insert(idx);
    }

    /// Selects all items from 0 to len-1.
    pub fn select_all(&mut self, len: usize) {
        self.multi = (0..len).collect();
    }

    /// Handles a click event at the given index with modifier keys.
    pub fn handle_click(&mut self, idx: usize, is_shift: bool, is_ctrl: bool, is_sticky: bool) {
        if is_ctrl || is_sticky {
            if let Some(s) = self.selected {
                self.multi.insert(s);
            }

            if self.multi.contains(&idx) {
                self.multi.remove(&idx);
            } else {
                self.multi.insert(idx);
            }
            self.selected = Some(idx);
            self.anchor = Some(idx);
        } else if is_shift {
            let anchor = self.anchor.unwrap_or(self.selected.unwrap_or(0));
            self.anchor = Some(anchor);
            self.multi.clear();
            for i in std::cmp::min(anchor, idx)..=std::cmp::max(anchor, idx) {
                self.multi.insert(i);
            }
            self.selected = Some(idx);
        } else {
            self.multi.clear();
            self.multi.insert(idx);
            self.selected = Some(idx);
            self.anchor = Some(idx);
        }
    }

    /// Handles keyboard navigation to the next index.
    pub fn handle_move(&mut self, next: usize, is_shift: bool) {
        let prev = self.selected;
        self.selected = Some(next);
        if is_shift {
            let anchor = self.anchor.unwrap_or(prev.unwrap_or(0));
            self.anchor = Some(anchor);
            self.multi.clear();
            for i in std::cmp::min(anchor, next)..=std::cmp::max(anchor, next) {
                self.multi.insert(i);
            }
        } else {
            self.multi.clear();
            self.anchor = Some(next);
        }
    }

    /// Toggles the selection state of the given index.
    pub fn toggle(&mut self, idx: usize) {
        if self.multi.contains(&idx) {
            self.multi.remove(&idx);
        } else {
            self.multi.insert(idx);
        }
    }
}

/// File category classification for icon and color styling.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub enum FileCategory {
    /// Compressed archives (zip, tar, gz, 7z, etc.)
    Archive,
    /// Image files (png, jpg, svg, gif, etc.)
    Image,
    /// Executable scripts (sh, py, js, rs, etc.)
    Script,
    /// Plain text and source code files
    Text,
    /// Document files (pdf, doc, xlsx, etc.)
    Document,
    /// Audio files (mp3, wav, flac, etc.)
    Audio,
    /// Video files (mp4, mkv, avi, etc.)
    Video,
    /// Unclassified files
    Other,
}

impl FileCategory {
    /// Returns the cyberpunk-style color associated with this file category.
    pub fn cyber_color(&self) -> Color {
        match self {
            FileCategory::Archive => Color::Rgb(255, 50, 80), // Neon Red
            FileCategory::Image => Color::Rgb(255, 0, 255),   // Magenta
            FileCategory::Script => Color::Rgb(0, 255, 100),  // Matrix Green
            FileCategory::Text => Color::Rgb(255, 215, 0),    // Gold
            FileCategory::Document => Color::Rgb(100, 200, 255), // Light Blue
            FileCategory::Audio => Color::Rgb(0, 150, 255),   // Electric Blue
            FileCategory::Video => Color::Rgb(180, 50, 255),  // Neon Purple
            FileCategory::Other => Color::Rgb(255, 255, 255), // Pure White
        }
    }
}

/// Categorizes a file by extension into Audio, Video, Image, Code, Doc, or Other.
pub fn get_file_category(path: &std::path::Path) -> FileCategory {
    let filename = path
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("")
        .to_lowercase();
    let ext = path
        .extension()
        .and_then(|s| s.to_str())
        .unwrap_or("")
        .to_lowercase();

    // Special cases for filenames without extensions or specific dotfiles
    match filename.as_str() {
        "license" | "dockerfile" | "makefile" | "makefile.am" | "makefile.in" | "flake.nix"
        | "flake.lock" => return FileCategory::Text,
        ".gitignore" | ".gitattributes" | ".gitconfig" | ".env" | ".dockerignore"
        | ".geminiignore" | ".directory" => return FileCategory::Text,
        _ => {}
    }

    match ext.as_str() {
        "zip" | "tar" | "gz" | "7z" | "rar" | "xz" | "bz2" => FileCategory::Archive,
        "png" | "jpg" | "jpeg" | "gif" | "webp" | "svg" | "bmp" => FileCategory::Image,
        "sh" | "py" | "pyw" | "rb" | "js" | "ts" | "pl" | "php" | "nix" => FileCategory::Script,
        "txt" | "md" | "rs" | "c" | "cpp" | "h" | "hpp" | "toml" | "yaml" | "yml" | "json"
        | "xml" | "html" | "css" | "conf" | "config" | "log" | "lock" | "env" | "gradle"
        | "properties" => FileCategory::Text,
        "pdf" | "doc" | "docx" | "odt" | "ods" | "odp" | "xlsx" | "xls" | "csv" => {
            FileCategory::Document
        }
        "mp3" | "wav" | "ogg" | "flac" | "m4a" | "aac" => FileCategory::Audio,
        "mp4" | "mkv" | "avi" | "mov" | "webm" | "flv" => FileCategory::Video,
        _ => FileCategory::Other,
    }
}

/// Returns a list of suggested applications to open files with the given extension.
pub fn get_open_with_suggestions(ext: &str) -> Vec<String> {
    match ext {
        "txt" | "md" | "rs" | "toml" | "json" | "c" | "cpp" | "py" | "js" | "ts" | "log"
        | "conf" | "yaml" | "yml" | "lock" | "env" | "gradle" | "properties" => {
            vec![
                "code", "vim", "nvim", "nano", "kate", "subl", "gedit", "emacs", "mousepad",
                "leafpad", "xed",
            ]
        }
        "png" | "jpg" | "jpeg" | "gif" | "webp" | "svg" | "bmp" | "ico" => {
            vec![
                "gwenview",
                "feh",
                "imv",
                "nomacs",
                "display",
                "eog",
                "ristretto",
                "gimp",
                "inkscape",
                "krita",
            ]
        }
        "pdf" | "epub" | "djvu" => vec![
            "okular", "evince", "zathura", "firefox", "chromium", "atril", "mupdf", "xreader",
        ],
        "mp4" | "mkv" | "avi" | "mov" | "webm" | "flv" | "m4v" => vec![
            "vlc",
            "mpv",
            "totem",
            "smplayer",
            "dragon",
            "celluloid",
            "kmplayer",
        ],
        "mp3" | "wav" | "ogg" | "flac" | "m4a" | "aac" => vec![
            "vlc",
            "clementine",
            "audacious",
            "rhythmbox",
            "strawberry",
            "lollypop",
            "sayonara",
        ],
        "zip" | "tar" | "gz" | "7z" | "rar" | "bz2" | "xz" => {
            vec!["ark", "file-roller", "engrampa", "xarchiver", "peazip"]
        }
        _ => vec![
            "xdg-open", "dolphin", "nautilus", "thunar", "pcmanfm", "code", "vim", "nvim",
        ],
    }
    .into_iter()
    .map(|s| s.to_string())
    .collect()
}

use unicode_width::UnicodeWidthChar;

/// Returns the visual width of a character, with high paranoia for any Non-ASCII characters.
pub fn get_visual_width(c: char) -> usize {
    if c.is_ascii() {
        return 1;
    }
    UnicodeWidthChar::width(c).unwrap_or(1)
}

/// Removes control characters from a string, preserving displayable characters.
pub fn squarify(s: &str) -> String {
    s.chars().filter(|c| !c.is_control()).collect()
}

/// Truncates a string to fit a visual width, adding an optional suffix if truncated.
pub fn truncate_to_width(s: &str, max_width: usize, suffix: &str) -> String {
    let mut total_width = 0;
    for c in s.chars() {
        total_width += get_visual_width(c);
    }

    if total_width <= max_width {
        return s.to_string();
    }

    let suffix_width = suffix.chars().map(get_visual_width).sum::<usize>();
    if max_width <= suffix_width {
        return ".".to_string();
    }

    let mut truncated = String::new();
    let mut cur_width = 0;
    for c in s.chars() {
        let cw = get_visual_width(c);
        if cur_width + cw + suffix_width <= max_width {
            truncated.push(c);
            cur_width += cw;
        } else {
            break;
        }
    }
    format!("{}{}", truncated, suffix)
}

/// Checks if a command exists in the system PATH.
pub fn command_exists(cmd: &str) -> bool {
    if let Ok(path) = std::env::var("PATH") {
        for p in path.split(':') {
            let p_str = format!("{}/{}", p, cmd);
            if std::path::Path::new(&p_str).exists() {
                return true;
            }
        }
    }
    false
}

/// Spawns a detached process with the given command and arguments.
/// No waiting, no stdout/stderr capture, no stdin.
pub fn spawn_detached(cmd: &str, args: Vec<String>) {
    let _ = std::process::Command::new(cmd)
        .args(args)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .stdin(std::process::Stdio::null())
        .spawn();
}

/// Formats a byte size into a human-readable string (B, KB, MB, GB, TB).
pub fn format_size(size: u64) -> String {
    if size >= 1073741824 {
        format!("{:.1} GB", size as f64 / 1073741824.0)
    } else if size >= 1048576 {
        format!("{:.1} MB", size as f64 / 1048576.0)
    } else if size >= 1024 {
        format!("{:.1} KB", size as f64 / 1024.0)
    } else {
        format!("{} B", size)
    }
}

/// Formats a timestamp into a compact "YYYY-MM-DD HH:MM" string.
pub fn format_time(time: SystemTime) -> String {
    let datetime: DateTime<Local> = time.into();
    datetime.format("%Y-%m-%d %H:%M").to_string()
}

/// Formats a timestamp into a smart display: "HH:MM" if today, "YYYY-MM-DD" otherwise.
pub fn format_datetime_smart(time: SystemTime) -> String {
    use chrono::Datelike;
    let dt: DateTime<Local> = time.into();
    let now = Local::now();
    if dt.year() == now.year() && dt.month() == now.month() && dt.day() == now.day() {
        dt.format("%H:%M").to_string()
    } else {
        dt.format("%Y-%m-%d").to_string()
    }
}

/// Formats a Unix file mode into an rwx-style permission string (e.g., "rwxr-xr--").
pub fn format_permissions(mode: u32) -> String {
    let r = |b| if b & 4 != 0 { "r" } else { "-" };
    let w = |b| if b & 2 != 0 { "w" } else { "-" };
    let x = |b| if b & 1 != 0 { "x" } else { "-" };
    format!(
        "{}{}{}{}{}{}{}{}{}",
        r((mode >> 6) & 0o7),
        w((mode >> 6) & 0o7),
        x((mode >> 6) & 0o7),
        r((mode >> 3) & 0o7),
        w((mode >> 3) & 0o7),
        x((mode >> 3) & 0o7),
        r(mode & 0o7),
        w(mode & 0o7),
        x(mode & 0o7)
    )
}

use std::sync::OnceLock;
use syntect::easy::HighlightLines;
use syntect::highlighting::{FontStyle, ThemeSet};
use syntect::parsing::SyntaxSet;
use syntect::util::LinesWithEndings;

static SYNTAX_SET: OnceLock<SyntaxSet> = OnceLock::new();
static THEME_SET: OnceLock<ThemeSet> = OnceLock::new();

// In-memory clipboard fallback for headless/test environments.
static CLIPBOARD: OnceLock<std::sync::Mutex<String>> = OnceLock::new();

fn get_clipboard_store() -> &'static std::sync::Mutex<String> {
    CLIPBOARD.get_or_init(|| std::sync::Mutex::new(String::new()))
}

/// Highlights code content using syntect and returns styled ratatui Lines.
/// Supports syntax highlighting for 50+ languages with cyberpunk color tweaks.
pub fn highlight_code<'a>(content: &'a str, extension: &str) -> Vec<Line<'a>> {
    let ps = SYNTAX_SET.get_or_init(SyntaxSet::load_defaults_newlines);
    let ts = THEME_SET.get_or_init(ThemeSet::load_defaults);

    let ext_lower = extension.to_lowercase();

    // 1. Try by extension
    let mut syntax = ps.find_syntax_by_extension(&ext_lower);

    // 2. Try by name (case-insensitive-ish)
    if syntax.is_none() {
        syntax = ps
            .find_syntax_by_name(extension)
            .or_else(|| ps.find_syntax_by_name(&ext_lower));
    }

    // If not found, try common mappings
    if syntax.is_none() {
        syntax = match ext_lower.as_str() {
            "makefile" | "make" => ps.find_syntax_by_extension("make"),
            "dockerfile" | "dockerignore" => ps
                .find_syntax_by_extension("dockerfile")
                .or_else(|| ps.find_syntax_by_extension("sh")),
            "cargo.toml" | "cargo" | "toml" | "lock" | "ini" | "inf" => ps
                .find_syntax_by_extension("toml")
                .or_else(|| ps.find_syntax_by_name("Ini")),
            "flake.lock" | "json" | "jsonc" | "ipynb" => ps.find_syntax_by_extension("json"),
            "xml" | "svg" | "plist" | "xaml" | "csproj" | "fsproj" | "vbproj" | "pom"
            | "pom.xml" | "xsd" | "xsl" => ps.find_syntax_by_extension("xml"),
            "nix" | "flake.nix" | "configuration.nix" | "home.nix" | "default.nix" => {
                ps.find_syntax_by_extension("nix")
                    .or_else(|| ps.find_syntax_by_name("Nix"))
                    .or_else(|| ps.find_syntax_by_extension("rb")) // Desperate fallback to Ruby
            }
            "yaml" | "yml" => ps.find_syntax_by_extension("yaml"),
            "gitignore" | "gitattributes" | "gitconfig" | "conf" | "config" | "env" | ".env"
            | "properties" | "prefs" => ps.find_syntax_by_extension("sh"),
            "ts" | "tsx" | "typescript" => ps.find_syntax_by_extension("ts"),
            "js" | "jsx" | "javascript" => ps.find_syntax_by_extension("js"),
            "go" | "golang" => ps.find_syntax_by_extension("go"),
            "sql" | "mysql" | "psql" => ps.find_syntax_by_extension("sql"),
            "md" | "markdown" | "rmd" => ps.find_syntax_by_extension("md"),
            "html" | "htm" | "xhtml" => ps.find_syntax_by_extension("html"),
            "css" | "scss" | "sass" | "less" => ps.find_syntax_by_extension("css"),
            "sh" | "bash" | "zsh" | "fish" | "command" | "bashrc" | "zshrc" | "profile" => {
                ps.find_syntax_by_extension("sh")
            }
            "py" | "python" | "pyw" | "cgi" => ps.find_syntax_by_extension("py"),
            "rs" | "rust" => ps.find_syntax_by_extension("rs"),
            "c" | "h" => ps.find_syntax_by_extension("c"),
            "cpp" | "cc" | "cxx" | "hpp" | "hh" | "hxx" => ps.find_syntax_by_extension("cpp"),
            "cs" | "csharp" => ps.find_syntax_by_extension("cs"),
            "java" | "jsp" => ps.find_syntax_by_extension("java"),
            "kt" | "kotlin" | "kts" => ps.find_syntax_by_extension("kotlin"),
            "swift" => ps.find_syntax_by_extension("swift"),
            "php" | "phtml" | "php4" | "php5" => ps.find_syntax_by_extension("php"),
            "rb" | "ruby" | "gemspec" | "rakefile" => ps.find_syntax_by_extension("rb"),
            "pl" | "perl" | "pm" | "t" => ps.find_syntax_by_extension("pl"),
            "lua" => ps.find_syntax_by_extension("lua"),
            "gradle" => ps
                .find_syntax_by_extension("groovy")
                .or_else(|| ps.find_syntax_by_extension("java")),
            "diff" | "patch" => ps.find_syntax_by_extension("diff"),
            _ => None,
        };
    }

    // 4. Try by first line (shebang)
    if syntax.is_none() {
        if let Some(first_line) = content.lines().next() {
            syntax = ps.find_syntax_by_first_line(first_line);
        }
    }

    let syntax = syntax.unwrap_or_else(|| ps.find_syntax_plain_text());

    let mut h = HighlightLines::new(syntax, &ts.themes["base16-mocha.dark"]);

    let mut lines = Vec::new();
    let is_markdown = syntax.name.contains("Markdown");

    for line in LinesWithEndings::from(content) {
        let Ok(ranges) = h.highlight_line(line, ps) else {
            continue;
        };
        let mut spans = Vec::new();

        for (style, text) in ranges {
            let r = style.foreground.r;
            let g = style.foreground.g;
            let b = style.foreground.b;

            let mut r_f = r as f32;
            let mut g_f = g as f32;
            let mut b_f = b as f32;

            if is_markdown {
                // SPECIAL "VIBRANT PRO" STYLE FOR MARKDOWN

                let max_c = r_f.max(g_f).max(b_f);

                let min_c = r_f.min(g_f).min(b_f);

                let diff = max_c - min_c;

                // Even more aggressive white for standard text

                if diff < 30.0 || max_c < 180.0 {
                    // Pure white for standard text and greyed out bits

                    r_f = 255.0;
                    g_f = 255.0;
                    b_f = 255.0;
                } else {
                    // Distinguish elements by syntect's default hues

                    if r_f > g_f && r_f > b_f {
                        // Reddish -> Headers or Strong

                        r_f = 255.0;
                        g_f = 0.0;
                        b_f = 255.0; // Magenta Headers
                    } else if g_f > r_f && g_f > b_f {
                        // Greenish -> Lists or Quotes

                        r_f = 150.0;
                        g_f = 255.0;
                        b_f = 0.0; // Lime Lists
                    } else if b_f > r_f && b_f > g_f {
                        // Bluish -> Links or Code

                        r_f = 0.0;
                        g_f = 255.0;
                        b_f = 255.0; // Cyan Links
                    }
                }
            } else {
                // "ULTRA-VIBRANT-SYNTAX" Heuristic:
                let r_f32 = r as f32;
                let g_f32 = g as f32;
                let b_f32 = b as f32;

                let max_c = r_f32.max(g_f32).max(b_f32);
                let min_c = r_f32.min(g_f32).min(b_f32);
                let diff = max_c - min_c;

                if diff < 20.0 {
                    // Muted tones (comments, punctuation)
                    if max_c < 140.0 {
                        // Muted Blue-Grey for comments
                        r_f = 100.0;
                        g_f = 120.0;
                        b_f = 140.0;
                    } else {
                        // Standard text -> Off-white
                        r_f = 230.0;
                        g_f = 235.0;
                        b_f = 240.0;
                    }
                } else {
                    // Saturated Mapping
                    if r_f32 > g_f32 && r_f32 > b_f32 {
                        if g_f32 > 120.0 {
                            // Bright Yellow/Orange (Types/Classes)
                            r_f = 255.0;
                            g_f = 215.0;
                            b_f = 0.0;
                        } else {
                            // Vibrant Pink/Red (Keywords/Storage)
                            r_f = 255.0;
                            g_f = 45.0;
                            b_f = 85.0;
                        }
                    } else if g_f32 > r_f32 && g_f32 > b_f32 {
                        // Matrix Green (Strings/Values)
                        r_f = 0.0;
                        g_f = 255.0;
                        b_f = 135.0;
                    } else if b_f32 > r_f32 && b_f32 > g_f32 {
                        if r_f32 > 130.0 {
                            // Neon Purple (Functions/Methods)
                            r_f = 180.0;
                            g_f = 100.0;
                            b_f = 255.0;
                        } else {
                            // Electric Blue (Variables/Constants)
                            r_f = 0.0;
                            g_f = 180.0;
                            b_f = 255.0;
                        }
                    }

                    // Boost saturation to max
                    let cur_max = r_f.max(g_f).max(b_f).max(1.0);
                    let boost = 255.0 / cur_max;
                    r_f *= boost;
                    g_f *= boost;
                    b_f *= boost;
                }
            }

            let fg = Color::Rgb(
                r_f.clamp(0.0, 255.0) as u8,
                g_f.clamp(0.0, 255.0) as u8,
                b_f.clamp(0.0, 255.0) as u8,
            );
            let mut ratatui_style = Style::default().fg(fg);

            if style.font_style.contains(FontStyle::BOLD) {
                ratatui_style = ratatui_style.add_modifier(Modifier::BOLD);
            }
            if style.font_style.contains(FontStyle::ITALIC) {
                ratatui_style = ratatui_style.add_modifier(Modifier::ITALIC);
            }
            if style.font_style.contains(FontStyle::UNDERLINE) {
                ratatui_style = ratatui_style.add_modifier(Modifier::UNDERLINED);
            }

            // Remove trailing newline from text if it exists to avoid double spacing in Ratatui
            let clean_text = text.trim_end_matches('\n').trim_end_matches('\r');
            if !clean_text.is_empty() || text == " " {
                spans.push(Span::styled(clean_text.to_string(), ratatui_style));
            }
        }
        lines.push(Line::from(spans));
    }
    lines
}

/// Draws a labeled stat bar (e.g., CPU, memory) using Unicode block characters.
pub fn draw_stat_bar(
    label: &str,
    value: f32,
    max: f32,
    width: u16,
    text_color: Color,
) -> Line<'static> {
    let bar_width = width.saturating_sub(label.len() as u16 + 7); // Subtract label, spaces, and percentage text
    let ratio = (value / max).clamp(0.0, 1.0);
    let filled = (ratio * bar_width as f32).round() as usize;

    let mut spans = vec![Span::styled(
        format!("{} ", label),
        Style::default().fg(Color::DarkGray),
    )];

    for i in 0..bar_width as usize {
        let symbol = if i < filled { "â–ˆ" } else { "â–‘" };
        let color = if ratio < 0.4 {
            Color::Rgb(0, 255, 150) // Cyber Green
        } else if ratio < 0.7 {
            Color::Rgb(255, 255, 0) // Yellow
        } else {
            Color::Rgb(255, 0, 85) // Neon Red
        };

        if i < filled {
            spans.push(Span::styled(symbol, Style::default().fg(color)));
        } else {
            spans.push(Span::styled(
                symbol,
                Style::default().fg(Color::Rgb(30, 30, 35)),
            ));
        }
    }

    spans.push(Span::styled(
        format!(" {:>3.0}%", ratio * 100.0),
        Style::default().fg(text_color).add_modifier(Modifier::BOLD),
    ));
    Line::from(spans)
}
/// Returns true if the first 8KB of bytes contain any null bytes (binary content).
pub fn is_binary_content(bytes: &[u8]) -> bool {
    // Basic binary check: check for null bytes in the first 8KB
    bytes.iter().take(8192).any(|&b| b == 0)
}

/// Recursively copies a directory or file to a destination path.
pub fn copy_recursive(src: &std::path::Path, dst: &std::path::Path) -> std::io::Result<()> {
    if src.is_dir() {
        std::fs::create_dir_all(dst)?;
        for entry in std::fs::read_dir(src)? {
            let entry = entry?;
            let ty = entry.file_type()?;
            if ty.is_dir() {
                copy_recursive(&entry.path(), &dst.join(entry.file_name()))?;
            } else {
                std::fs::copy(entry.path(), dst.join(entry.file_name()))?;
            }
        }
    } else {
        std::fs::copy(src, dst)?;
    }
    Ok(())
}

/// Recursively moves a file or directory, with cross-device fallback via copy+delete.
pub fn move_recursive(src: &std::path::Path, dst: &std::path::Path) -> std::io::Result<()> {
    if src == dst {
        return Ok(());
    }

    // Attempt atomic rename first
    if let Err(e) = std::fs::rename(src, dst) {
        // Fallback for cross-device moves (EXDEV = 18)
        let err_code = e.raw_os_error();
        if err_code == Some(18) || e.kind() == std::io::ErrorKind::Other {
            // Safety: Ensure source exists
            if !src.exists() {
                return Err(e);
            }
            // Safety: Don't move into self
            if dst.starts_with(src) {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    "Cannot move into self",
                ));
            }

            copy_recursive(src, dst)?;
            if src.is_dir() {
                std::fs::remove_dir_all(src)?;
            } else {
                std::fs::remove_file(src)?;
            }
        } else {
            return Err(e);
        }
    }
    Ok(())
}
/// Deletes a word backwards from the current cursor position in a string.
pub fn delete_word_backwards(s: &mut String) {
    if s.is_empty() {
        return;
    }
    let mut i = s.len();

    // Skip trailing whitespace
    while i > 0 {
        let prev = s[..i].chars().next_back().unwrap();
        if prev.is_whitespace() {
            i -= prev.len_utf8();
        } else {
            break;
        }
    }
    // Skip the word
    while i > 0 {
        let prev = s[..i].chars().next_back().unwrap();
        if !prev.is_whitespace() {
            i -= prev.len_utf8();
        } else {
            break;
        }
    }
    s.truncate(i);
}

/// Opens a new terminal window (alacritty, kitty, gnome-terminal, etc.) at the given path.
/// If `new_tab` is true, opens in a new tab rather than a new window.
/// Optionally runs `command` in the new terminal.
pub fn spawn_terminal_at(path: &std::path::Path, new_tab: bool, command: Option<&str>) -> bool {
    let log = |msg: &str| {
        use std::io::Write;
        if let Ok(mut file) = std::fs::OpenOptions::new()
            .append(true)
            .create(true)
            .open("debug.log")
        {
            let _ = writeln!(file, "[{}] [TERM_SPAWN] {}", chrono::Local::now(), msg);
        }
    };

    log(&format!(
        "Spawning terminal at {:?} (new_tab={}, command={:?})",
        path, new_tab, command
    ));

    // 1. Context-aware Tab Spawning
    if new_tab {
        // Konsole
        if let (Ok(service), Ok(window)) = (
            std::env::var("KONSOLE_DBUS_SERVICE"),
            std::env::var("KONSOLE_DBUS_WINDOW"),
        ) {
            log(&format!(
                "Konsole detected: service={}, window={}",
                service, window
            ));

            // Use dbus-send instead of qdbus — qdbus is known to crash
            // on some Qt/KDE versions. dbus-send is a low-level tool that
            // does not link against Qt and avoids the crash.
            let dbus_cmd = "dbus-send";
            log(&format!("Using DBus command: {}", dbus_cmd));

            let dest = &service;

            // Step 1: Create new session via dbus-send
            // dbus-send returns "int32 N" not just "N" like qdbus
            let session_args = vec![
                "--session".to_string(),
                format!("--dest={}", dest),
                "--type=method_call".to_string(),
                "--print-reply".to_string(),
                window.clone(),
                "org.kde.konsole.Window.newSession".to_string(),
                format!("string:\"\""),
                format!("string:{}", path.to_string_lossy()),
            ];

            match std::process::Command::new(dbus_cmd)
                .args(&session_args)
                .output()
            {
                Ok(output) => {
                    if output.status.success() {
                        let stdout = String::from_utf8_lossy(&output.stdout);
                        // dbus-send --print-reply returns something like:
                        //   method return time=1234.567 sender=... destination=... int32 44
                        // We need to extract "44" from the last int32 token
                        let session_id = stdout
                            .split_whitespace()
                            .filter_map(|tok| tok.parse::<u32>().ok())
                            .next_back()
                            .map(|id| id.to_string())
                            .unwrap_or_default();
                        log(&format!("New session created, ID: {}", session_id));

                        if !session_id.is_empty() {
                            if let Some(cmd_str) = command {
                                let session_path = format!("/Sessions/{}", session_id);
                                let _ = std::process::Command::new(dbus_cmd)
                                    .args([
                                        "--session",
                                        &format!("--dest={}", dest),
                                        "--type=method_call",
                                        &session_path,
                                        "org.kde.konsole.Session.runCommand",
                                        &format!("string:{}", cmd_str),
                                    ])
                                    .spawn();
                            }
                        }

                        // Try to raise the window
                        let _ = std::process::Command::new(dbus_cmd)
                            .args([
                                "--session",
                                &format!("--dest={}", dest),
                                "--type=method_call",
                                "/konsole/MainWindow_1",
                                "org.qtproject.Qt.QWidget.raise",
                            ])
                            .spawn();

                        return true;
                    } else {
                        log(&format!(
                            "dbus-send command failed: {}",
                            String::from_utf8_lossy(&output.stderr)
                        ));
                    }
                }
                Err(e) => log(&format!("Failed to execute {}: {}", dbus_cmd, e)),
            }
        }

        // Kitty
        if std::env::var("KITTY_WINDOW_ID").is_ok() {
            log("Kitty detected");
            let mut args = vec![
                "@".to_string(),
                "launch".to_string(),
                "--type=tab".to_string(),
                "--cwd".to_string(),
                path.to_string_lossy().to_string(),
            ];
            if let Some(cmd) = command {
                args.push(cmd.to_string());
            }
            match std::process::Command::new("kitty").args(&args).spawn() {
                Ok(_) => {
                    log("Kitty tab spawned");
                    return true;
                }
                Err(e) => log(&format!("Failed to spawn kitty tab: {}", e)),
            }
        }

        // Wezterm
        if std::env::var("WEZTERM_PANE").is_ok() {
            log("Wezterm detected");
            let mut args = vec![
                "cli".to_string(),
                "spawn".to_string(),
                "--cwd".to_string(),
                path.to_string_lossy().to_string(),
            ];
            if let Some(cmd) = command {
                args.push("--".to_string());
                args.push(cmd.to_string());
            }
            match std::process::Command::new("wezterm").args(&args).spawn() {
                Ok(_) => {
                    log("Wezterm tab spawned");
                    return true;
                }
                Err(e) => log(&format!("Failed to spawn wezterm tab: {}", e)),
            }
        }
    }

    // 2. Generic Spawning (fallback or new window)
    log("Using generic spawning fallback");
    let terminals = [
        "x-terminal-emulator",
        "gnome-terminal",
        "konsole",
        "alacritty",
        "kitty",
        "wezterm",
        "xfce4-terminal",
        "termite",
        "urxvt",
    ];
    for term in terminals {
        let mut args = Vec::new();

        match term {
            "gnome-terminal" => {
                if new_tab {
                    args.push("--tab".to_string());
                }
                args.push(format!("--working-directory={}", path.to_string_lossy()));
                if let Some(cmd) = command {
                    args.push("--".to_string());
                    args.push(cmd.to_string());
                }
            }
            "konsole" => {
                if new_tab {
                    args.push("--new-tab".to_string());
                }
                args.push("--workdir".to_string());
                args.push(path.to_string_lossy().to_string());
                if let Some(cmd) = command {
                    args.push("-e".to_string());
                    args.push(cmd.to_string());
                }
            }
            "xfce4-terminal" => {
                if new_tab {
                    args.push("--tab".to_string());
                }
                args.push("--working-directory".to_string());
                args.push(path.to_string_lossy().to_string());
                if let Some(cmd) = command {
                    args.push("-e".to_string());
                    args.push(cmd.to_string());
                }
            }
            "kitty" => {
                args.push("--directory".to_string());
                args.push(path.to_string_lossy().to_string());
                if let Some(cmd) = command {
                    args.push(cmd.to_string());
                }
            }
            "wezterm" => {
                args.push("start".to_string());
                args.push("--cwd".to_string());
                args.push(path.to_string_lossy().to_string());
                if let Some(cmd) = command {
                    args.push(cmd.to_string());
                }
            }
            _ => {
                args.push("--working-directory".to_string());
                args.push(path.to_string_lossy().to_string());
                if let Some(cmd) = command {
                    args.push("-e".to_string());
                    args.push(cmd.to_string());
                }
            }
        }

        if std::process::Command::new(term)
            .args(&args)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .stdin(std::process::Stdio::null())
            .spawn()
            .is_ok()
        {
            return true;
        }
    }
    false
}

/// Checks if a file is likely binary or too large to preview comfortably.
/// Returns (is_binary, is_too_large, size_in_mb)
pub fn check_file_suitability(path: &std::path::Path, max_bytes: u64) -> (bool, bool, u64) {
    if let Ok(metadata) = std::fs::metadata(path) {
        let size = metadata.len();
        if size > max_bytes {
            return (false, true, size / (1024 * 1024));
        }

        if let Ok(content) = std::fs::read(path) {
            return (is_binary_content(&content), false, size / (1024 * 1024));
        }
    }
    (false, false, 0)
}

/// Sets clipboard text via OSC 52, wl-copy, xclip, pbcopy, or in-memory fallback.
pub fn set_clipboard_text(text: &str) {
    // 1. Try OSC 52 (Internal via stdout)
    {
        use std::io::Write;
        let mut stdout = std::io::stdout();
        let _ = crate::visuals::osc::copy_to_clipboard(&mut stdout, text);
        let _ = stdout.flush();
    }

    // 2. Try Local Tools (for desktop environments)
    let tool_result = std::process::Command::new("wl-copy")
        .arg(text)
        .spawn()
        .or_else(|_| {
            std::process::Command::new("xclip")
                .arg("-selection")
                .arg("clipboard")
                .stdin(std::process::Stdio::piped())
                .spawn()
                .map(|mut child| {
                    use std::io::Write;
                    if let Some(mut stdin) = child.stdin.take() {
                        let _ = stdin.write_all(text.as_bytes());
                    }
                    child
                })
        })
        .or_else(|_| {
            std::process::Command::new("pbcopy")
                .stdin(std::process::Stdio::piped())
                .spawn()
                .map(|mut child| {
                    use std::io::Write;
                    if let Some(mut stdin) = child.stdin.take() {
                        let _ = stdin.write_all(text.as_bytes());
                    }
                    child
                })
        });

    // 3. Fallback to in-memory store (for headless / test environments)
    if tool_result.is_err() {
        if let Ok(mut store) = get_clipboard_store().lock() {
            *store = text.to_string();
        }
    }
}

/// Gets clipboard text via wl-paste, xclip, pbpaste, or in-memory fallback.
pub fn get_clipboard_text() -> Option<String> {
    std::process::Command::new("wl-paste")
        .output()
        .or_else(|_| {
            std::process::Command::new("xclip")
                .arg("-o")
                .arg("-selection")
                .arg("clipboard")
                .output()
        })
        .or_else(|_| std::process::Command::new("pbpaste").output())
        .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
        .ok()
        .or_else(|| {
            // Fallback to in-memory store (for headless / test environments)
            get_clipboard_store().lock().ok().map(|store| store.clone())
        })
}

/// Clears the in-memory clipboard fallback (useful for tests).
pub fn clear_clipboard_text() {
    if let Ok(mut store) = get_clipboard_store().lock() {
        store.clear();
    }
}

/// Gets the primary X11/Wayland selection text (for middle-click paste).
pub fn get_primary_selection_text() -> Option<String> {
    std::process::Command::new("wl-paste")
        .arg("--primary")
        .output()
        .or_else(|_| {
            std::process::Command::new("xclip")
                .arg("-o")
                .arg("-selection")
                .arg("primary")
                .output()
        })
        .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
        .ok()
}