/ fetchx / src / main.rs
Swadhin Biswas feat(main): add display rendering call · 3/2/2026
cf94018
331 lines · 8.9 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
//! FetchX - A fast, feature-rich system information tool written in Rust.
//!
//! An exact clone of neofetch with extra features: emoji support, image display,
//! Nerd Font icons, and blazing fast performance.

mod ascii;
mod colors;
mod config;
mod display;
mod image_backend;
mod image_cache;
mod system;
mod utils;

use clap::Parser;
use config::Config;
use display::Display;
use system::SystemInfo;

/// FetchX - Fast system information tool with emoji & image support
#[derive(Parser, Debug)]
#[command(name = "fetchx")]
#[command(author = "FetchX Contributors")]
#[command(version = "0.2.0")]
#[command(about = "A fast, modern system information tool — neofetch clone in Rust", long_about = None)]
struct Args {
    /// Disable colors in output
    #[arg(long)]
    no_color: bool,

    /// Enable/disable bold text
    #[arg(long)]
    bold: Option<bool>,

    /// Image backend: ascii, kitty, sixel, chafa, off
    #[arg(short, long, value_name = "BACKEND")]
    backend: Option<String>,

    /// Image source: auto, ascii, wallpaper, or /path/to/image
    #[arg(short, long, value_name = "SOURCE")]
    source: Option<String>,

    /// Which distro's ASCII art to display
    #[arg(long, value_name = "DISTRO")]
    ascii_distro: Option<String>,

    /// Use emoji mode instead of ASCII art
    #[arg(long)]
    emoji: bool,

    /// Use Nerd Font icons for info labels
    #[arg(long)]
    nerd_font: bool,

    /// Path to custom image to display
    #[arg(short, long, value_name = "PATH")]
    custom_image: Option<String>,

    /// Only show the logo/ASCII art, no system info
    #[arg(short, long)]
    logo_only: bool,

    /// Gap between logo and info text
    #[arg(long, value_name = "NUM")]
    gap: Option<usize>,

    /// Separator between label and value
    #[arg(long, value_name = "SEP")]
    separator: Option<String>,

    /// Disable all formatting (for piping)
    #[arg(long)]
    stdout: bool,

    /// Show the config file path and exit
    #[arg(long)]
    show_config: bool,

    /// Print the default config to stdout and exit
    #[arg(long)]
    print_config: bool,

    /// Create the default config file if it doesn't exist and exit
    #[arg(long)]
    create_config: bool,

    /// Print output as JSON
    #[arg(long)]
    json: bool,

    /// Color block range start (0-15)
    #[arg(long)]
    block_range_start: Option<u8>,

    /// Color block range end (0-15)
    #[arg(long)]
    block_range_end: Option<u8>,

    /// Width of color blocks
    #[arg(long)]
    block_width: Option<usize>,

    /// Interactive image selector using fzf
    #[arg(long)]
    select_image: bool,

    /// Run as daemon (updates status file every 10 seconds)
    #[arg(long)]
    daemon: bool,

    /// Show tray status (compact output for system tray/widget)
    #[arg(long)]
    tray_status: bool,

    /// Initialize config with API image fetching (one-command setup)
    #[arg(long)]
    init_api_image: bool,

    /// Internal: background download helper (not for user use)
    #[arg(long, hide = true)]
    bg_download: bool,
}

fn main() {
    let args = Args::parse();

    // Handle special flags
    if args.show_config {
        let path = Config::config_path();
        println!("Config file: {}", path.display());
        return;
    }

    if args.print_config {
        println!("{}", Config::example_config());
        return;
    }

    if args.create_config {
        match Config::create_default_config() {
            Ok(path) => {
                println!("Config file created at: {}", path.display());
            }
            Err(e) => {
                eprintln!("Error creating config: {}", e);
                std::process::exit(1);
            }
        }
        return;
    }

    if args.bg_download {
        // Internal: called as a detached child process to download image
        if let Err(e) = image_cache::download_image_from_api() {
            eprintln!("fetchx bg-download error: {}", e);
        }
        return;
    }

    if args.init_api_image {
        init_api_image_config();
        return;
    }

    if args.select_image {
        select_image_interactive();
        return;
    }

    if args.daemon {
        run_daemon();
        return;
    }

    if args.tray_status {
        show_tray_status();
        return;
    }

    // Load config, then override with CLI args
    let mut config = Config::load_or_default();
    apply_args_to_config(&mut config, &args);

    // Auto-detect terminal capabilities if backend is "auto"
    if config.image_backend == "auto" {
        let capabilities = image_cache::detect_terminal_capabilities();
        config.image_backend = capabilities.backend.clone();
    }

    // Only use API image fetching when user explicitly configured it:
    //   image_backend must be a graphics backend (not "ascii" / "off")
    //   AND image_source must be "auto" (API mode)
    //   AND no custom_image already set by user
    let uses_graphics_backend = matches!(
        config.image_backend.as_str(),
        "kitty" | "sixel" | "chafa" | "w3m" | "iterm2"
    );
    let uses_api_source = config.image_source == "auto";

    if uses_graphics_backend && uses_api_source && config.custom_image.is_none() {
        // Use cached image from previous run (instant, no delay)
        if let Some(cached_img) = image_cache::get_available_image() {
            config.custom_image = Some(cached_img.to_string_lossy().to_string());
        }

        // Download a new image in background for next run (non-blocking, zero delay)
        image_cache::download_image_background();
    }

    // Gather system info
    let sys_info = SystemInfo::collect();

    if args.json {
        print_json(&sys_info);
        return;
    }

    // Render
    let display = Display::new(&config);
    display.render(&sys_info);
}

fn apply_args_to_config(config: &mut Config, args: &Args) {
    // Boolean flags: only set if explicitly passed
    if args.no_color || args.stdout {
        config.no_color = true;
    }
    if args.stdout {
        config.stdout = true;
        config.bold = false;
    }
    if let Some(bold) = args.bold {
        config.bold = bold;
    }
    if let Some(ref backend) = args.backend {
        config.image_backend = backend.clone();
    }
    if let Some(ref source) = args.source {
        config.image_source = source.clone();
    }
    if let Some(ref distro) = args.ascii_distro {
        config.ascii_distro = distro.clone();
    }
    if args.emoji {
        config.emoji_mode = true;
    }
    if args.nerd_font {
        config.nerd_font = true;
    }
    if args.custom_image.is_some() {
        config.custom_image = args.custom_image.clone();
    }
    if args.logo_only {
        config.logo_only = true;
    }
    if let Some(gap) = args.gap {
        config.gap = gap;
    }
    if let Some(ref sep) = args.separator {
        config.separator = sep.clone();
    }
    if let Some(start) = args.block_range_start {
        config.block_range.0 = start;
    }
    if let Some(end) = args.block_range_end {
        config.block_range.1 = end;
    }
    if let Some(width) = args.block_width {
        config.block_width = width;
    }
}

fn print_json(info: &SystemInfo) {
    let gpu_str = info.gpu.join(", ");
    println!("{{");
    let fields: Vec<(&str, &str)> = vec![
        ("os", &info.os),
        ("host", &info.host),
        ("kernel", &info.kernel),
        ("uptime", &info.uptime),
        ("packages", &info.packages),
        ("shell", &info.shell),
        ("resolution", &info.resolution),
        ("de", &info.de),
        ("wm", &info.wm),
        ("wm_theme", &info.wm_theme),
        ("theme", &info.theme),
        ("icons", &info.icons),
        ("terminal", &info.terminal),
        ("terminal_font", &info.term_font),
        ("cpu", &info.cpu),
        ("gpu", &gpu_str),
        ("memory", &info.memory),
        ("disk", &info.disk),
        ("battery", &info.battery),
        ("local_ip", &info.local_ip),
        ("public_ip", &info.public_ip),
        ("locale", &info.locale),
        ("song", &info.song),
        ("users", &info.users),
    ];
    for (i, (key, val)) in fields.iter().enumerate() {
        let comma = if i < fields.len() - 1 { "," } else { "" };
        let escaped = val.replace('\\', "\\\\").replace('"', "\\\"");
        println!("  \"{}\": \"{}\"{}", key, escaped, comma);
    }
    println!("}}");
}

/// Interactive image selector using fzf
fn select_image_interactive() {
    use std::fs;
    use std::process::{Command, Stdio};

    let mut image_paths = Vec::new();

    // Scan common image directories
    let search_dirs = vec![
        dirs::download_dir(),
        dirs::picture_dir(),
        dirs::home_dir().map(|h| h.join("Desktop")),
    ];

    for dir_opt in search_dirs {
        if let Some(dir) = dir_opt {
            if let Ok(entries) = fs::read_dir(&dir) {
                for entry in entries.flatten() {
                    let path = entry.path();
                    if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
                        if matches!(