thag_rs 0.2.0

A versatile cross-platform playground and REPL for Rust snippets, expressions and programs. Accepts a script file or dynamic options.
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
/*[toml]
[dependencies]
thag_styling = { version = "0.2, thag-auto" }
inquire = "0.7"
serde = { version = "1.0", features = ["derive"] }
toml = "0.8"
clap = { version = "4.5", features = ["derive"] }
*/
/// Interactive theme editor for manual color role adjustments
///
/// This tool allows you to interactively edit theme color assignments,
/// particularly useful when automatic conversion doesn't quite match your preferences.
///
//# Purpose: Edit and customize theme color role assignments interactively
//# Categories: color, interactive, styling, theming, tools
use clap::Parser;
use inquire::{Confirm, Select};
use std::collections::HashMap;
use std::error::Error;
use std::fs;
use std::path::{Path, PathBuf};
use thag_styling::{hsl_to_rgb, rgb_to_hsl, ColorValue, Palette, Role, Style, StylingError, Theme};

#[derive(Parser, Debug)]
#[command(author, version, about = "Interactive theme editor", long_about = None)]
struct Cli {
    /// Input theme file (.toml format)
    #[arg(short, long, value_name = "FILE")]
    input: PathBuf,

    /// Output theme file (defaults to input file if not specified)
    #[arg(short, long, value_name = "FILE")]
    output: Option<PathBuf>,

    /// Create backup of original file
    #[arg(short, long, default_value_t = true)]
    backup: bool,
}

/// A color candidate with provenance information
#[derive(Clone, Debug)]
struct ColorCandidate {
    hex: String,
    rgb: [u8; 3],
    base_indices: Vec<String>, // e.g., ["base00", "base01"]
    roles: Vec<Role>,          // e.g., [Role::Subtle, Role::Commentary]
}

impl ColorCandidate {
    fn new(rgb: [u8; 3]) -> Self {
        Self {
            hex: format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]),
            rgb,
            base_indices: Vec::new(),
            roles: Vec::new(),
        }
    }

    fn display_name(&self) -> String {
        let mut parts = Vec::new();

        if !self.base_indices.is_empty() {
            parts.push(self.base_indices.join(", "));
        }

        if !self.roles.is_empty() {
            let roles_str = self
                .roles
                .iter()
                .map(|r| format!("{:?}", r))
                .collect::<Vec<_>>()
                .join(", ");
            parts.push(roles_str);
        }

        if parts.is_empty() {
            self.hex.clone()
        } else {
            format!("{} ({})", self.hex, parts.join(" | "))
        }
    }

    fn preview(&self) -> String {
        let style = Style::with_rgb(self.rgb);
        format!("{} {}", style.paint("████"), self.display_name())
    }
}

/// Main theme editor state
struct ThemeEditor {
    theme: Theme,
    original_palette: Palette,
    modified: bool,
}

impl ThemeEditor {
    fn new(theme: Theme) -> Self {
        let original_palette = theme.palette.clone();
        Self {
            theme,
            original_palette,
            modified: false,
        }
    }

    fn run(&mut self) -> Result<(), Box<dyn Error>> {
        println!("\n🎨 Theme Editor: {}\n", self.theme.name);
        self.show_theme_info();

        loop {
            let action = self.select_action()?;

            match action.as_str() {
                "Edit color role" => self.edit_role()?,
                "Adjust color" => self.adjust_color()?,
                "Swap two roles" => self.swap_roles()?,
                "Reset to original" => self.reset_palette()?,
                "Show current palette" => self.show_palette(),
                "Save and exit" => {
                    if self.save_and_exit()? {
                        break;
                    }
                }
                "Exit without saving" => {
                    if self.confirm_exit()? {
                        break;
                    }
                }
                _ => unreachable!(),
            }
        }

        Ok(())
    }

    fn show_theme_info(&self) {
        println!("📋 Theme: {}", self.theme.name);
        println!("🌓 Type: {:?}", self.theme.term_bg_luma);
        println!("🎨 Color Support: {:?}", self.theme.min_color_support);
        if let Some([r, g, b]) = self.theme.bg_rgbs.first() {
            println!("🖼️  Background: #{r:02x}{g:02x}{b:02x}");
        }
        println!();
    }

    fn select_action(&self) -> Result<String, Box<dyn Error>> {
        let modified_indicator = if self.modified { " [MODIFIED]" } else { "" };

        let actions = vec![
            "Edit color role",
            "Adjust color",
            "Swap two roles",
            "Reset to original",
            "Show current palette",
            "Save and exit",
            "Exit without saving",
        ];

        let prompt = format!("What would you like to do?{}", modified_indicator);
        let selection = Select::new(&prompt, actions).prompt()?;

        Ok(selection.to_string())
    }

    fn edit_role(&mut self) -> Result<(), Box<dyn Error>> {
        // Select which role to edit
        let role = self.select_role("Which role would you like to edit?")?;

        // Get current color for this role
        let current_style = self.theme.style_for(role);
        let current_hex = Self::style_to_hex(&current_style);

        println!(
            "\nCurrent color for {:?}: {}",
            role,
            current_style.paint(format!("████ {}", current_hex))
        );

        // Load base_colors if available
        let _ = self.theme.load_base_colors();

        // Get all available colors from the palette
        let candidates = self.collect_color_candidates();

        if candidates.is_empty() {
            println!("❌ No color candidates available!");
            return Ok(());
        }

        let options: Vec<String> = candidates.iter().map(ColorCandidate::preview).collect();

        let selection = Select::new("Select new color:", options).prompt()?;

        // Find the selected candidate
        let selected = candidates
            .iter()
            .find(|c| c.preview() == selection)
            .ok_or("Color not found")?;

        // Update the role
        self.update_role(role, selected.rgb);
        self.modified = true;

        println!("✅ Updated {:?} to {}", role, selected.hex);

        Ok(())
    }

    fn adjust_color(&mut self) -> Result<(), Box<dyn Error>> {
        // Select which role to adjust
        let role = self.select_role("Which role would you like to adjust?")?;

        // Get current color
        let current_style = self.theme.style_for(role);
        let current_rgb = &current_style
            .rgb()
            .ok_or_else(|| StylingError::FromStr("No RGB value for Style".to_string()))?;
        let [r, g, b] = current_rgb;
        let current_hex = format!("#{r:02x}{g:02x}{b:02x}");

        println!(
            "\nCurrent color for {:?}: {}",
            role,
            current_style.paint(format!("████ {}", current_hex))
        );

        // Select adjustment type
        let adjustments = vec![
            "Lighten (+10%)",
            "Darken (-10%)",
            "Increase saturation (+10%)",
            "Decrease saturation (-10%)",
            "Custom adjustment",
            "Cancel",
        ];

        let selection = Select::new("How would you like to adjust?", adjustments).prompt()?;

        let adjusted_rgb = match selection {
            "Lighten (+10%)" => Self::adjust_lightness(*current_rgb, 0.10),
            "Darken (-10%)" => Self::adjust_lightness(*current_rgb, -0.10),
            "Increase saturation (+10%)" => Self::adjust_saturation(*current_rgb, 0.10),
            "Decrease saturation (-10%)" => Self::adjust_saturation(*current_rgb, -0.10),
            "Custom adjustment" => {
                Self::custom_color_adjustment(role, *current_rgb);
                return Ok(());
            }
            "Cancel" => return Ok(()),
            _ => unreachable!(),
        };

        // Show preview
        let adjusted_hex = format!(
            "#{:02x}{:02x}{:02x}",
            adjusted_rgb[0], adjusted_rgb[1], adjusted_rgb[2]
        );
        let adjusted_style = Style::with_rgb(adjusted_rgb);

        println!("\nBefore: {} {}", current_style.paint("████"), current_hex);
        println!("After:  {} {}", adjusted_style.paint("████"), adjusted_hex);

        let confirm = Confirm::new("Apply this adjustment?")
            .with_default(true)
            .prompt()?;

        if confirm {
            self.update_role(role, adjusted_rgb);
            self.modified = true;
            println!("✅ Adjusted {:?} to {}", role, adjusted_hex);
        }

        Ok(())
    }

    fn custom_color_adjustment(_role: Role, current_rgb: [u8; 3]) {
        let [h, s, l] = rgb_to_hsl(current_rgb);

        println!(
            "\nCurrent HSL: H={:.0}° S={:.0}% L={:.0}%",
            h,
            s * 100.0,
            l * 100.0
        );
        println!("Enter adjustments (press Enter to skip):");

        // Note: In a real implementation, you'd use inquire's text input
        // For simplicity, using preset adjustments
        println!("⚠️  Custom adjustment not fully implemented. Use preset adjustments.");
    }

    fn swap_roles(&mut self) -> Result<(), Box<dyn Error>> {
        println!("\n🔄 Swap two role colors");

        let role1 = self.select_role("Select first role: ")?;
        let role2 = self.select_role("Select second role:")?;

        if role1 == role2 {
            println!("⚠️  Cannot swap a role with itself!");
            return Ok(());
        }

        // Get current colors
        let style1 = self.theme.style_for(role1);
        let style2 = self.theme.style_for(role2);

        // Extract RGB values
        let rgb1 = &style1
            .rgb()
            .ok_or_else(|| StylingError::FromStr("No RGB value for Style".to_string()))?;
        let rgb2 = &style2
            .rgb()
            .ok_or_else(|| StylingError::FromStr("No RGB value for Style".to_string()))?;

        // Swap them
        self.update_role(role1, *rgb2);
        self.update_role(role2, *rgb1);
        self.modified = true;

        println!("✅ Swapped {:?}{:?}", role1, role2);

        Ok(())
    }

    fn reset_palette(&mut self) -> Result<(), Box<dyn Error>> {
        if !self.modified {
            println!("ℹ️  Palette has not been modified.");
            return Ok(());
        }

        let confirm = Confirm::new("Reset all changes to original palette?")
            .with_default(false)
            .prompt()?;

        if confirm {
            self.theme.palette = self.original_palette.clone();
            self.modified = false;
            println!("✅ Palette reset to original");
        }

        Ok(())
    }

    fn show_palette(&self) {
        println!("\n📊 Current Palette:\n");

        let roles = vec![
            Role::Heading1,
            Role::Heading2,
            Role::Heading3,
            Role::Error,
            Role::Warning,
            Role::Success,
            Role::Info,
            Role::Emphasis,
            Role::Code,
            Role::Normal,
            Role::Subtle,
            Role::Hint,
            Role::Debug,
            Role::Link,
            Role::Quote,
            Role::Commentary,
        ];

        for role in roles {
            let style = self.theme.style_for(role);
            let hex = Self::style_to_hex(&style);
            println!(
                "  {:12} │ {} {}",
                format!("{:?}", role),
                style.paint("████"),
                hex
            );
        }

        println!();
    }

    fn save_and_exit(&self) -> Result<bool, Box<dyn Error>> {
        if !self.modified {
            println!("ℹ️  No changes to save.");
            return Ok(true);
        }

        let confirm = Confirm::new("Save changes?").with_default(true).prompt()?;

        if confirm {
            // Save will be handled by the caller
            println!("✅ Changes will be saved");
            Ok(true)
        } else {
            Ok(false)
        }
    }

    fn confirm_exit(&self) -> Result<bool, Box<dyn Error>> {
        if self.modified {
            let confirm = Confirm::new("Exit without saving changes?")
                .with_default(false)
                .prompt()?;
            Ok(confirm)
        } else {
            Ok(true)
        }
    }

    fn select_role(&self, prompt: &str) -> Result<Role, Box<dyn Error>> {
        let roles = vec![
            ("Heading1", Role::Heading1),
            ("Heading2", Role::Heading2),
            ("Heading3", Role::Heading3),
            ("Error", Role::Error),
            ("Warning", Role::Warning),
            ("Success", Role::Success),
            ("Info", Role::Info),
            ("Emphasis", Role::Emphasis),
            ("Code", Role::Code),
            ("Normal", Role::Normal),
            ("Subtle", Role::Subtle),
            ("Hint", Role::Hint),
            ("Debug", Role::Debug),
            ("Link", Role::Link),
            ("Quote", Role::Quote),
            ("Commentary", Role::Commentary),
        ];

        let options: Vec<String> = roles
            .iter()
            .map(|(name, role)| {
                let style = self.theme.style_for(*role);
                let hex = Self::style_to_hex(&style);
                format!("{:12} {} {}", name, style.paint("██"), hex)
            })
            .collect();

        let selection = Select::new(prompt, options).prompt()?;

        // Extract role from selection
        let role_name = selection.split_whitespace().next().unwrap();
        let role = roles
            .iter()
            .find(|(name, _)| name == &role_name)
            .map(|(_, role)| *role)
            .ok_or("Role not found")?;

        Ok(role)
    }

    fn collect_color_candidates(&self) -> Vec<ColorCandidate> {
        let mut color_map: HashMap<String, ColorCandidate> = HashMap::new();

        // First, collect colors from base_colors if available
        if let Some(base_colors) = &self.theme.base_colors {
            for (i, rgb) in base_colors.iter().enumerate() {
                let hex = format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]);
                let base_name = format!("base{:02X}", i);

                color_map
                    .entry(hex.clone())
                    .or_insert_with(|| ColorCandidate::new(*rgb))
                    .base_indices
                    .push(base_name);
            }
        }

        // Then, add roles that use each color
        let all_roles = vec![
            Role::Heading1,
            Role::Heading2,
            Role::Heading3,
            Role::Error,
            Role::Warning,
            Role::Success,
            Role::Info,
            Role::Emphasis,
            Role::Code,
            Role::Normal,
            Role::Subtle,
            Role::Hint,
            Role::Debug,
            Role::Link,
            Role::Quote,
            Role::Commentary,
        ];

        for role in all_roles {
            let style = self.theme.style_for(role);
            if let Some(color_info) = &style.foreground {
                if let ColorValue::TrueColor { rgb } = &color_info.value {
                    let hex = format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]);

                    color_map
                        .entry(hex.clone())
                        .or_insert_with(|| ColorCandidate::new(*rgb))
                        .roles
                        .push(role);
                }
            }
        }

        // Convert to vector and sort by provenance richness
        let mut candidates: Vec<ColorCandidate> = color_map.into_values().collect();
        candidates.sort_by(|a, b| {
            // Prioritize colors with base indices, then by number of roles
            let a_score = (if a.base_indices.is_empty() { 0 } else { 100 }) + a.roles.len();
            let b_score = (if b.base_indices.is_empty() { 0 } else { 100 }) + b.roles.len();
            b_score.cmp(&a_score)
        });

        candidates
    }

    /// Adjust lightness by a factor (e.g., 0.10 for +10%, -0.10 for -10%)
    fn adjust_lightness(rgb: [u8; 3], factor: f32) -> [u8; 3] {
        let [h, s, l] = rgb_to_hsl(rgb);
        let new_l = (l + factor).clamp(0.1, 0.9); // Keep reasonable bounds
        hsl_to_rgb(h, s, new_l)
    }

    /// Adjust saturation by a factor (e.g., 0.10 for +10%, -0.10 for -10%)
    fn adjust_saturation(rgb: [u8; 3], factor: f32) -> [u8; 3] {
        let [h, s, l] = rgb_to_hsl(rgb);
        let new_s = (s + factor).clamp(0.0, 1.0);
        hsl_to_rgb(h, new_s, l)
    }

    fn update_role(&mut self, role: Role, rgb: [u8; 3]) {
        let style = self.theme.style_for(role);
        let mut new_style = Style::with_rgb(rgb);

        // Preserve attributes
        if style.bold {
            new_style = new_style.bold();
        }
        if style.italic {
            new_style = new_style.italic();
        }
        if style.dim {
            new_style = new_style.dim();
        }
        if style.underline {
            new_style = new_style.underline();
        }

        // Update the palette
        match role {
            Role::Heading1 => self.theme.palette.heading1 = new_style,
            Role::Heading2 => self.theme.palette.heading2 = new_style,
            Role::Heading3 => self.theme.palette.heading3 = new_style,
            Role::Error => self.theme.palette.error = new_style,
            Role::Warning => self.theme.palette.warning = new_style,
            Role::Success => self.theme.palette.success = new_style,
            Role::Info => self.theme.palette.info = new_style,
            Role::Emphasis => self.theme.palette.emphasis = new_style,
            Role::Code => self.theme.palette.code = new_style,
            Role::Normal => self.theme.palette.normal = new_style,
            Role::Subtle => self.theme.palette.subtle = new_style,
            Role::Hint => self.theme.palette.hint = new_style,
            Role::Debug => self.theme.palette.debug = new_style,
            Role::Link => self.theme.palette.link = new_style,
            Role::Quote => self.theme.palette.quote = new_style,
            Role::Commentary => self.theme.palette.commentary = new_style,
        }
    }

    fn style_to_hex(style: &Style) -> String {
        style
            .foreground
            .as_ref()
            .and_then(|color_info| {
                if let ColorValue::TrueColor { rgb } = &color_info.value {
                    let [r, g, b] = rgb;
                    Some(format!("#{r:02x}{g:02x}{b:02x}"))
                } else {
                    None
                }
            })
            .unwrap_or_else(|| "#000000".to_string())
    }

    // fn extract_rgb(style: &Style) -> Result<[u8; 3], Box<dyn Error>> {
    //     style
    //         .foreground
    //         .as_ref()
    //         .and_then(|color_info| {
    //             if let ColorValue::TrueColor { rgb } = &color_info.value {
    //                 Some(*rgb)
    //             } else {
    //                 None
    //             }
    //         })
    //         .ok_or_else(|| "Could not extract RGB from style".into())
    // }
}

fn load_theme(path: &Path) -> Result<Theme, Box<dyn Error>> {
    if !path.exists() {
        return Err(format!("File not found: {}", path.display()).into());
    }

    let theme = Theme::load_from_file(path)?;
    Ok(theme)
}

fn save_theme(theme: &Theme, path: &Path, create_backup: bool) -> Result<(), Box<dyn Error>> {
    // Create backup if requested
    if create_backup && path.exists() {
        let backup_path = path.with_extension("toml.backup");
        fs::copy(path, &backup_path)?;
        println!("📦 Backup created: {}", backup_path.display());
    }

    // Read the original file
    let content = fs::read_to_string(path)?;
    let mut doc: toml::Value = toml::from_str(&content)?;

    // Update the palette section
    if let Some(palette) = doc.get_mut("palette").and_then(|p| p.as_table_mut()) {
        update_palette_in_toml(palette, &theme.palette);
    }

    // Write back
    let new_content = toml::to_string_pretty(&doc)?;
    fs::write(path, new_content)?;

    println!("💾 Theme saved: {}", path.display());
    Ok(())
}

fn update_palette_in_toml(
    palette: &mut toml::map::Map<String, toml::Value>,
    new_palette: &Palette,
) {
    let roles = vec![
        ("heading1", &new_palette.heading1),
        ("heading2", &new_palette.heading2),
        ("heading3", &new_palette.heading3),
        ("error", &new_palette.error),
        ("warning", &new_palette.warning),
        ("success", &new_palette.success),
        ("info", &new_palette.info),
        ("emphasis", &new_palette.emphasis),
        ("code", &new_palette.code),
        ("normal", &new_palette.normal),
        ("subtle", &new_palette.subtle),
        ("hint", &new_palette.hint),
        ("debug", &new_palette.debug),
        ("link", &new_palette.link),
        ("quote", &new_palette.quote),
        ("commentary", &new_palette.commentary),
    ];

    for (role_name, style) in roles {
        if let Some(color_info) = &style.foreground {
            if let ColorValue::TrueColor { rgb } = &color_info.value {
                if let Some(role_table) = palette.get_mut(role_name).and_then(|r| r.as_table_mut())
                {
                    if let Some(rgb_array) =
                        role_table.get_mut("rgb").and_then(|r| r.as_array_mut())
                    {
                        *rgb_array = vec![
                            toml::Value::Integer(i64::from(rgb[0])),
                            toml::Value::Integer(i64::from(rgb[1])),
                            toml::Value::Integer(i64::from(rgb[2])),
                        ];
                    }
                }
            }
        }
    }
}

fn main() -> Result<(), Box<dyn Error>> {
    let cli = Cli::parse();

    println!("🎨 Thag Theme Editor\n");

    // Load the theme
    let theme = load_theme(&cli.input)?;

    // Create editor
    let mut editor = ThemeEditor::new(theme);

    // Run interactive editor
    editor.run()?;

    // Save if modified
    if editor.modified {
        let output_path = cli.output.as_ref().unwrap_or(&cli.input);
        save_theme(&editor.theme, output_path, cli.backup)?;
    } else {
        println!("ℹ️  No changes made.");
    }

    Ok(())
}