Skip to main content

red_level/
lib.rs

1use clap::Parser;
2
3#[derive(Parser, Debug)]
4#[command(
5    name = "red-level",
6    about = "system-level dimming and color adjusting.",
7    version
8)]
9struct Args {
10    /// Brightness level in percentage (1 to 100)
11    #[arg(short, long, default_value_t = 100)]
12    brightness: u8,
13
14    /// Use only the red channel
15    #[arg(short, long, conflicts_with_all = ["red", "green", "blue", "levels"])]
16    red_only: bool,
17
18    /// Use only the red channel
19    #[arg(long, conflicts_with_all = ["red_only", "green", "blue", "levels"])]
20    red: bool,
21
22    /// Use only the green channel
23    #[arg(long, conflicts_with_all = ["red_only", "red", "blue", "levels"])]
24    green: bool,
25
26    /// Use only the blue channel
27    #[arg(long, conflicts_with_all = ["red_only", "red", "green", "levels"])]
28    blue: bool,
29
30    /// Set red, green, and blue channel levels as percentages
31    #[arg(
32        long,
33        value_names = ["RED", "GREEN", "BLUE"],
34        num_args = 3,
35        value_parser = clap::value_parser!(u8).range(0..=100),
36        conflicts_with_all = ["red_only", "red", "green", "blue"]
37    )]
38    levels: Option<Vec<u8>>,
39
40    /// Reset screen color and brightness back to standard system defaults
41    #[arg(long)]
42    reset: bool,
43
44    /// Start the filter as a detached background process
45    #[arg(long, conflicts_with_all = ["stop", "reset"])]
46    start: bool,
47
48    /// Stop the background filter process and restore the display
49    #[arg(long, conflicts_with_all = ["start", "reset"])]
50    stop: bool,
51
52    #[arg(long, hide = true)]
53    daemon: bool,
54}
55
56pub fn run() {
57    let args = Args::parse();
58    let channel_levels = resolve_channel_levels(&args);
59
60    #[cfg(target_family = "unix")]
61    {
62        let start = args.start || (!args.daemon && !args.stop && !args.reset);
63        if start {
64            unix_daemon::start_daemon(args.brightness, channel_levels);
65            return;
66        }
67        if args.stop {
68            unix_daemon::stop_daemon();
69            return;
70        }
71    }
72
73    #[cfg(not(target_family = "unix"))]
74    if args.start || args.stop {
75        eprintln!("Error: Background process management is currently available only on Unix-like operating systems (macOS/Linux).");
76        std::process::exit(1);
77    }
78
79    let clamped_brightness = args.brightness.clamp(1, 100);
80    let scale = if args.reset {
81        1.0
82    } else {
83        clamped_brightness as f64 / 100.0
84    };
85    let channel_scales = if args.reset {
86        [1.0; 3]
87    } else {
88        channel_levels.map(|level| scale * level as f64 / 100.0)
89    };
90
91    if args.reset {
92        println!("Resetting screen filter and restoring original gamma curves...");
93    } else {
94        println!(
95            "Applying filter -> Brightness: {}% | RGB levels: {}% {}% {}%",
96            clamped_brightness, channel_levels[0], channel_levels[1], channel_levels[2]
97        );
98    }
99
100    #[cfg(target_os = "windows")]
101    {
102        windows_impl::apply_filter(channel_scales);
103    }
104
105    #[cfg(target_os = "macos")]
106    {
107        macos_impl::apply_filter(channel_scales);
108    }
109
110    #[cfg(target_os = "linux")]
111    {
112        linux_impl::apply_filter(channel_scales);
113    }
114
115    #[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
116    {
117        eprintln!(
118            "Error: This application is currently only optimized for macOS, Windows, and Linux platforms."
119        );
120        std::process::exit(1);
121    }
122
123    // If running in foreground or daemon loop on non-Windows desktop platforms
124    #[cfg(target_family = "unix")]
125    {
126        if !args.reset {
127            if args.daemon {
128                loop {
129                    std::thread::park();
130                }
131            }
132
133            #[cfg(feature = "ctrlc")]
134            {
135                println!("Filter active. Press Ctrl+C to restore the display.");
136
137                // Catch termination signals to restore screen smoothly
138                let _ = ctrlc::set_handler(move || {
139                    println!("\nRestoring screen defaults...");
140                    #[cfg(target_os = "macos")]
141                    macos_impl::apply_filter([1.0; 3]);
142                    #[cfg(target_os = "linux")]
143                    linux_impl::apply_filter([1.0; 3]);
144                    std::process::exit(0);
145                });
146
147                loop {
148                    std::thread::park();
149                }
150            }
151        }
152    }
153}
154
155fn resolve_channel_levels(args: &Args) -> [u8; 3] {
156    if let Some(levels) = &args.levels {
157        return [levels[0], levels[1], levels[2]];
158    }
159    if args.red || args.red_only {
160        return [100, 0, 0];
161    }
162    if args.green {
163        return [0, 100, 0];
164    }
165    if args.blue {
166        return [0, 0, 100];
167    }
168    [100; 3]
169}
170
171// ==========================================
172// UNIX BACKGROUND DAEMON MANAGEMENT (macOS / Linux)
173// ==========================================
174#[cfg(target_family = "unix")]
175mod unix_daemon {
176    use std::fs;
177    use std::os::unix::process::CommandExt;
178    use std::path::PathBuf;
179    use std::process::{Command, Stdio};
180
181    const SIGTERM: i32 = 15;
182    const STOP_ATTEMPTS: usize = 40;
183    const STOP_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(50);
184
185    unsafe extern "C" {
186        fn getuid() -> u32;
187        fn kill(pid: i32, signal: i32) -> i32;
188        fn setsid() -> i32;
189    }
190
191    fn pid_file() -> PathBuf {
192        let uid = unsafe { getuid() };
193        std::env::temp_dir().join(format!("red-level-{uid}.pid"))
194    }
195
196    fn read_running_pid() -> Option<i32> {
197        let path = pid_file();
198        let pid = fs::read_to_string(&path).ok()?.trim().parse().ok()?;
199        if unsafe { kill(pid, 0) } == 0 {
200            Some(pid)
201        } else {
202            let _ = fs::remove_file(path);
203            None
204        }
205    }
206
207    fn stop_process(pid: i32) -> Result<(), String> {
208        if unsafe { kill(pid, SIGTERM) } != 0 {
209            return Err(std::io::Error::last_os_error().to_string());
210        }
211
212        for _ in 0..STOP_ATTEMPTS {
213            if unsafe { kill(pid, 0) } != 0 {
214                return Ok(());
215            }
216            std::thread::sleep(STOP_POLL_INTERVAL);
217        }
218
219        Err(format!(
220            "process {pid} did not stop within {} seconds",
221            STOP_ATTEMPTS as f32 * STOP_POLL_INTERVAL.as_secs_f32()
222        ))
223    }
224
225    fn remove_pid_file() -> Result<(), std::io::Error> {
226        match fs::remove_file(pid_file()) {
227            Ok(()) => Ok(()),
228            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
229            Err(error) => Err(error),
230        }
231    }
232
233    fn restore_display() {
234        #[cfg(target_os = "macos")]
235        super::macos_impl::apply_filter([1.0; 3]);
236        #[cfg(target_os = "linux")]
237        super::linux_impl::apply_filter([1.0; 3]);
238    }
239
240    pub fn start_daemon(brightness: u8, channel_levels: [u8; 3]) {
241        if let Some(pid) = read_running_pid() {
242            println!("Stopping existing red-level process {pid}...");
243            if let Err(error) = stop_process(pid) {
244                eprintln!("Error: Failed to stop existing red-level process: {error}");
245                std::process::exit(1);
246            }
247            if let Err(error) = remove_pid_file() {
248                eprintln!("Error: Failed to remove the existing PID file: {error}");
249                std::process::exit(1);
250            }
251            restore_display();
252        }
253
254        let executable = match std::env::current_exe() {
255            Ok(path) => path,
256            Err(error) => {
257                eprintln!("Error: Failed to locate red-level: {error}");
258                std::process::exit(1);
259            }
260        };
261
262        let mut command = Command::new(executable);
263        command
264            .arg("--daemon")
265            .arg("--brightness")
266            .arg(brightness.clamp(1, 100).to_string())
267            .arg("--levels")
268            .args(channel_levels.map(|level| level.to_string()))
269            .stdin(Stdio::null())
270            .stdout(Stdio::null())
271            .stderr(Stdio::null());
272
273        unsafe {
274            command.pre_exec(|| {
275                if setsid() == -1 {
276                    return Err(std::io::Error::last_os_error());
277                }
278                Ok(())
279            });
280        }
281
282        let child = match command.spawn() {
283            Ok(child) => child,
284            Err(error) => {
285                eprintln!("Error: Failed to start red-level background daemon: {error}");
286                std::process::exit(1);
287            }
288        };
289
290        if let Err(error) = fs::write(pid_file(), child.id().to_string()) {
291            unsafe {
292                kill(child.id() as i32, SIGTERM);
293            }
294            eprintln!("Error: Failed to save the red-level process ID: {error}");
295            std::process::exit(1);
296        }
297
298        println!(
299            "red-level daemon started successfully with process ID {}.",
300            child.id()
301        );
302    }
303
304    pub fn stop_daemon() {
305        let Some(pid) = read_running_pid() else {
306            eprintln!("Error: red-level is not running in the background.");
307            std::process::exit(1);
308        };
309
310        if let Err(error) = stop_process(pid) {
311            eprintln!("Error: Failed to stop red-level: {error}");
312            std::process::exit(1);
313        }
314
315        restore_display();
316
317        if let Err(error) = remove_pid_file() {
318            eprintln!("Warning: Failed to remove the red-level PID lockfile: {error}");
319        }
320        println!("red-level daemon stopped; the display has been restored.");
321    }
322}
323
324// ==========================================
325// WINDOWS GDI ENGINE
326// ==========================================
327#[cfg(target_os = "windows")]
328mod windows_impl {
329    use std::ffi::c_void;
330    use windows::Win32::Graphics::Gdi::GetDC;
331    use windows::Win32::UI::ColorSystem::SetDeviceGammaRamp;
332
333    pub fn apply_filter(channel_scales: [f64; 3]) {
334        let hdc = unsafe { GetDC(None) };
335        if hdc.is_invalid() {
336            eprintln!("Error: Failed to acquire display device context (HDC).");
337            return;
338        }
339
340        let mut ramp = [0u16; 768];
341
342        for i in 0..256 {
343            let val = (i as f64 / 255.0) * 65535.0;
344
345            ramp[i] = (val * channel_scales[0]).round() as u16;
346            ramp[i + 256] = (val * channel_scales[1]).round() as u16;
347            ramp[i + 512] = (val * channel_scales[2]).round() as u16;
348        }
349
350        let result = unsafe { SetDeviceGammaRamp(hdc, ramp.as_ptr() as *const c_void) };
351        if result.as_bool() {
352            println!("System display filter applied successfully.");
353        } else {
354            eprintln!(
355                "Error: SetDeviceGammaRamp failed. Native HDR or administrative limits may apply."
356            );
357        }
358    }
359}
360
361// ==========================================
362// macOS COREGRAPHICS FFI ENGINE
363// ==========================================
364#[cfg(target_os = "macos")]
365mod macos_impl {
366    type CGDirectDisplayID = u32;
367    type CGError = i32;
368
369    #[link(name = "CoreGraphics", kind = "framework")]
370    unsafe extern "C" {
371        fn CGMainDisplayID() -> CGDirectDisplayID;
372        fn CGSetDisplayTransferByTable(
373            display: CGDirectDisplayID,
374            table_size: u32,
375            red_table: *const f32,
376            green_table: *const f32,
377            blue_table: *const f32,
378        ) -> CGError;
379    }
380
381    pub fn apply_filter(channel_scales: [f64; 3]) {
382        let display_id = unsafe { CGMainDisplayID() };
383        const TABLE_SIZE: usize = 256;
384
385        let mut red_table = [0.0f32; TABLE_SIZE];
386        let mut green_table = [0.0f32; TABLE_SIZE];
387        let mut blue_table = [0.0f32; TABLE_SIZE];
388
389        for i in 0..TABLE_SIZE {
390            let val = i as f32 / (TABLE_SIZE - 1) as f32;
391
392            red_table[i] = val * channel_scales[0] as f32;
393            green_table[i] = val * channel_scales[1] as f32;
394            blue_table[i] = val * channel_scales[2] as f32;
395        }
396
397        let result = unsafe {
398            CGSetDisplayTransferByTable(
399                display_id,
400                TABLE_SIZE as u32,
401                red_table.as_ptr(),
402                green_table.as_ptr(),
403                blue_table.as_ptr(),
404            )
405        };
406
407        if result == 0 {
408            println!("System display filter applied successfully.");
409        } else {
410            eprintln!(
411                "Error: CGSetDisplayTransferByTable failed with code {}.",
412                result
413            );
414        }
415    }
416}
417
418// ==========================================
419// LINUX X11 / XRANDR FFI ENGINE
420// ==========================================
421#[cfg(target_os = "linux")]
422mod linux_impl {
423    use std::os::raw::{c_char, c_int, c_ulong, c_void};
424
425    type Display = c_void;
426    type Window = c_ulong;
427    type RRAnyID = c_ulong;
428    type RRCrtc = RRAnyID;
429
430    #[repr(C)]
431    struct XRRScreenResources {
432        timestamp: c_ulong,
433        config_timestamp: c_ulong,
434        ncrtc: c_int,
435        crtcs: *mut RRCrtc,
436        noutput: c_int,
437        outputs: *mut c_ulong,
438        nmode: c_int,
439        modes: *mut c_void,
440    }
441
442    #[repr(C)]
443    struct XRRCrtcGamma {
444        size: c_int,
445        red: *mut u16,
446        green: *mut u16,
447        blue: *mut u16,
448    }
449
450    #[link(name = "X11")]
451    unsafe extern "C" {
452        fn XOpenDisplay(display_name: *const c_char) -> *mut Display;
453        fn XDefaultRootWindow(display: *mut Display) -> Window;
454        fn XCloseDisplay(display: *mut Display);
455    }
456
457    #[link(name = "Xrandr")]
458    unsafe extern "C" {
459        fn XRRGetScreenResourcesCurrent(
460            display: *mut Display,
461            window: Window,
462        ) -> *mut XRRScreenResources;
463        fn XRRFreeScreenResources(resources: *mut XRRScreenResources);
464        fn XRRGetCrtcGammaSize(display: *mut Display, crtc: RRCrtc) -> c_int;
465        fn XRRAllocGamma(size: c_int) -> *mut XRRCrtcGamma;
466        fn XRRFreeGamma(gamma: *mut XRRCrtcGamma);
467        fn XRRSetCrtcGamma(display: *mut Display, crtc: RRCrtc, gamma: *mut XRRCrtcGamma);
468    }
469
470    pub fn apply_filter(channel_scales: [f64; 3]) {
471        unsafe {
472            let display = XOpenDisplay(std::ptr::null());
473            if display.is_null() {
474                eprintln!("Error: Cannot open standard X11 display context connection.");
475                return;
476            }
477
478            let root = XDefaultRootWindow(display);
479            let resources = XRRGetScreenResourcesCurrent(display, root);
480            if resources.is_null() {
481                eprintln!("Error: Failed to obtain screen layout resources via X11 RandR.");
482                XCloseDisplay(display);
483                return;
484            }
485
486            let ncrtc = (*resources).ncrtc;
487            let crtcs = std::slice::from_raw_parts((*resources).crtcs, ncrtc as usize);
488
489            for &crtc in crtcs {
490                let gamma_size = XRRGetCrtcGammaSize(display, crtc);
491                if gamma_size <= 0 {
492                    continue;
493                }
494
495                let gamma = XRRAllocGamma(gamma_size);
496                if gamma.is_null() {
497                    continue;
498                }
499
500                let red_slice = std::slice::from_raw_parts_mut((*gamma).red, gamma_size as usize);
501                let green_slice =
502                    std::slice::from_raw_parts_mut((*gamma).green, gamma_size as usize);
503                let blue_slice = std::slice::from_raw_parts_mut((*gamma).blue, gamma_size as usize);
504
505                for i in 0..gamma_size as usize {
506                    let val = (i as f64 / (gamma_size - 1) as f64) * 65535.0;
507                    red_slice[i] = (val * channel_scales[0]).round() as u16;
508                    green_slice[i] = (val * channel_scales[1]).round() as u16;
509                    blue_slice[i] = (val * channel_scales[2]).round() as u16;
510                }
511
512                XRRSetCrtcGamma(display, crtc, gamma);
513                XRRFreeGamma(gamma);
514            }
515
516            XRRFreeScreenResources(resources);
517            XCloseDisplay(display);
518            println!("System display filter applied successfully.");
519        }
520    }
521}