tix 0.1.1

tix - cli alarm clock and timer with foreground and background modes
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
use chrono::{DateTime, Utc};
#[cfg(target_os = "linux")]
use notify_rust::{Hint, NotificationHandle};
#[cfg(any(target_os = "linux", target_os = "macos"))]
use notify_rust::{Notification, Timeout};
use rodio::{Decoder, DeviceSinkBuilder, MixerDeviceSink, Player, Source, source::SineWave};
use std::fs::File;
use std::io::{self, BufReader, Write};
use std::sync::{
    Arc,
    atomic::{AtomicBool, Ordering},
    mpsc,
};
use std::thread;
use std::time::{Duration, Instant};

use crate::config::resolve_sound_file_path;
use crate::display::ForegroundRenderer;
use crate::state::ActiveAlarmGuard;
use crate::types::{AlarmAudioConfig, AlarmNotificationConfig, AppResult, StopControl};

pub fn run_alarm_session(
    alarm_id: Option<&str>,
    target_utc: DateTime<Utc>,
    auto_stop_seconds: u64,
    audio: &AlarmAudioConfig,
    renderer: Option<&mut ForegroundRenderer>,
    log_events: bool,
    detached: bool,
    notifications: AlarmNotificationConfig,
) -> AppResult<()> {
    let control = install_stop_signal_handler()?;
    wait_until(target_utc, &control, renderer)?;
    if control.stop.load(Ordering::Relaxed) {
        if log_events {
            println!("alarm cancelled before trigger.");
        }
        return Ok(());
    }

    if log_events {
        println!("alarm ringing. press ctrl-c to stop.");
    }
    if detached {
        send_background_alarm_notification(alarm_id, notifications, &control);
    }
    ring_alarm(audio, auto_stop_seconds, &control, log_events);
    Ok(())
}

pub fn run_background_worker(
    alarm_id: String,
    target_utc: DateTime<Utc>,
    auto_stop_seconds: u64,
    audio: AlarmAudioConfig,
    notifications: AlarmNotificationConfig,
) -> AppResult<()> {
    let _guard = ActiveAlarmGuard::new(alarm_id.clone())?;
    run_alarm_session(
        Some(&alarm_id),
        target_utc,
        auto_stop_seconds,
        &audio,
        None,
        false,
        true,
        notifications,
    )
}

pub fn test_alarm_audio(audio: &AlarmAudioConfig) -> AppResult<()> {
    let audio = audio.clone();
    let (done_tx, done_rx) = mpsc::sync_channel(1);

    thread::spawn(move || {
        let result = match AlarmPlayer::new(&audio) {
            Ok(mut player) => player.start_test(),
            Err(err) => {
                eprintln!("tix: audio backend unavailable ({err}); using terminal bell fallback");
                bell_pulse();
                Ok(())
            }
        };
        let _ = done_tx.send(result);
    });

    match done_rx.recv_timeout(Duration::from_secs(3)) {
        Ok(result) => result,
        Err(mpsc::RecvTimeoutError::Timeout) => {
            eprintln!("tix: volume test timed out; using terminal bell fallback");
            bell_pulse();
            Ok(())
        }
        Err(mpsc::RecvTimeoutError::Disconnected) => {
            Err("volume test worker disconnected unexpectedly".to_string())
        }
    }
}

fn install_stop_signal_handler() -> AppResult<StopControl> {
    let stop = Arc::new(AtomicBool::new(false));
    let (wake_tx, wake_rx) = mpsc::sync_channel(1);
    let signal_stop = stop.clone();
    let signal_wake_tx = wake_tx.clone();

    ctrlc::set_handler(move || {
        signal_stop.store(true, Ordering::Relaxed);
        let _ = signal_wake_tx.try_send(());
    })
    .map_err(|err| format!("failed to install signal handler: {err}"))?;

    Ok(StopControl {
        stop,
        wake_tx,
        wake_rx,
    })
}

fn wait_until(
    target_utc: DateTime<Utc>,
    control: &StopControl,
    mut renderer: Option<&mut ForegroundRenderer>,
) -> AppResult<()> {
    if let Some(renderer) = renderer.as_deref_mut() {
        renderer
            .render(Utc::now())
            .map_err(|err| format!("failed to render foreground display: {err}"))?;
    }

    while !control.stop.load(Ordering::Relaxed) {
        let now = Utc::now();
        if now >= target_utc {
            break;
        }

        if let Some(renderer) = renderer.as_deref_mut() {
            renderer
                .render(now)
                .map_err(|err| format!("failed to render foreground display: {err}"))?;
        }

        let remaining = (target_utc - now).to_std().unwrap_or(Duration::ZERO);
        let coarse = next_wait_slice(remaining);
        let timeout = if let Some(renderer) = renderer.as_deref() {
            coarse.min(renderer.refresh_interval()).min(remaining)
        } else {
            coarse.min(remaining)
        };

        match control.wake_rx.recv_timeout(timeout) {
            Ok(()) | Err(mpsc::RecvTimeoutError::Timeout) => {}
            Err(mpsc::RecvTimeoutError::Disconnected) => break,
        }
    }

    if let Some(renderer) = renderer {
        renderer
            .clear()
            .map_err(|err| format!("failed to clear foreground display: {err}"))?;
    }
    Ok(())
}

fn next_wait_slice(remaining: Duration) -> Duration {
    if remaining > Duration::from_secs(300) {
        Duration::from_secs(30)
    } else if remaining > Duration::from_secs(30) {
        Duration::from_secs(5)
    } else if remaining > Duration::from_secs(5) {
        Duration::from_secs(1)
    } else {
        Duration::from_millis(200)
    }
}

fn ring_alarm(
    audio: &AlarmAudioConfig,
    auto_stop_seconds: u64,
    control: &StopControl,
    log_events: bool,
) {
    let auto_stop = if auto_stop_seconds == 0 {
        None
    } else {
        Some(Duration::from_secs(auto_stop_seconds))
    };
    let started = Instant::now();

    let mut player = match AlarmPlayer::new(audio) {
        Ok(player) => player,
        Err(err) => {
            eprintln!("tix: audio backend unavailable ({err}); using terminal bell fallback");
            AlarmPlayer::BellOnly {
                next_pulse_at: Instant::now(),
            }
        }
    };

    player.start_ringing();

    while !control.stop.load(Ordering::Relaxed) {
        if let Some(limit) = auto_stop
            && started.elapsed() >= limit
        {
            if log_events {
                println!("alarm auto-stopped after {auto_stop_seconds}s.");
            }
            break;
        }

        player.tick();
        match control.wake_rx.recv_timeout(Duration::from_millis(200)) {
            Ok(()) | Err(mpsc::RecvTimeoutError::Timeout) => {}
            Err(mpsc::RecvTimeoutError::Disconnected) => break,
        }
    }
}

enum AlarmPlayer {
    Player {
        _sink: MixerDeviceSink,
        player: Player,
        playback: PlaybackKind,
    },
    BellOnly {
        next_pulse_at: Instant,
    },
}

enum PlaybackKind {
    CustomSound { sound_file: String },
    TonePulse,
}

impl AlarmPlayer {
    fn new(audio: &AlarmAudioConfig) -> AppResult<Self> {
        let mut sink = DeviceSinkBuilder::open_default_sink()
            .map_err(|err| format!("failed to open default audio output: {err}"))?;
        sink.log_on_drop(false);
        let player = Player::connect_new(sink.mixer());
        player.set_volume(audio.volume);

        let playback = match &audio.sound_file {
            Some(sound_file) => PlaybackKind::CustomSound {
                sound_file: sound_file.clone(),
            },
            None => PlaybackKind::TonePulse,
        };

        Ok(Self::Player {
            _sink: sink,
            player,
            playback,
        })
    }

    fn start_ringing(&mut self) {
        match self {
            AlarmPlayer::Player {
                player, playback, ..
            } => match playback {
                PlaybackKind::CustomSound { sound_file } => {
                    if let Err(err) = start_looping_sound(player, sound_file) {
                        eprintln!("tix: custom sound failed ({err}); falling back to tone");
                        *playback = PlaybackKind::TonePulse;
                        append_tone_pulse(player);
                    }
                }
                PlaybackKind::TonePulse => append_tone_pulse(player),
            },
            AlarmPlayer::BellOnly { .. } => {}
        }
    }

    fn start_test(&mut self) -> AppResult<()> {
        match self {
            AlarmPlayer::Player {
                player, playback, ..
            } => {
                let wait_for = match playback {
                    PlaybackKind::CustomSound { sound_file } => {
                        if let Err(err) = start_test_sound(player, sound_file) {
                            eprintln!(
                                "tix: custom sound test failed ({err}); testing fallback tone"
                            );
                            append_test_tone(player);
                            Duration::from_millis(900)
                        } else {
                            Duration::from_secs(2)
                        }
                    }
                    PlaybackKind::TonePulse => {
                        append_test_tone(player);
                        Duration::from_millis(900)
                    }
                };
                thread::sleep(wait_for);
                Ok(())
            }
            AlarmPlayer::BellOnly { .. } => {
                bell_pulse();
                Ok(())
            }
        }
    }

    fn tick(&mut self) {
        match self {
            AlarmPlayer::Player {
                player, playback, ..
            } => {
                if matches!(playback, PlaybackKind::TonePulse) && player.empty() {
                    append_tone_pulse(player);
                }
            }
            AlarmPlayer::BellOnly { next_pulse_at } => {
                let now = Instant::now();
                if now >= *next_pulse_at {
                    bell_pulse();
                    *next_pulse_at = now + Duration::from_secs(1);
                }
            }
        }
    }
}

fn start_looping_sound(player: &Player, sound_file: &str) -> AppResult<()> {
    let file = open_sound_file(sound_file)?;
    let decoder = Decoder::new_looped(BufReader::new(file))
        .map_err(|err| format!("failed to decode sound file `{sound_file}`: {err}"))?;
    player.append(decoder);
    Ok(())
}

fn start_test_sound(player: &Player, sound_file: &str) -> AppResult<()> {
    let file = open_sound_file(sound_file)?;
    let decoder = Decoder::new(BufReader::new(file))
        .map_err(|err| format!("failed to decode sound file `{sound_file}`: {err}"))?;
    player.append(decoder.take_duration(Duration::from_secs(2)));
    Ok(())
}

fn open_sound_file(sound_file: &str) -> AppResult<File> {
    let path = resolve_sound_file_path(sound_file)?;
    File::open(&path).map_err(|err| format!("failed to open sound file {}: {err}", path.display()))
}

fn append_tone_pulse(player: &Player) {
    player.append(
        SineWave::new(880.0)
            .take_duration(Duration::from_millis(350))
            .amplify(1.0),
    );
}

fn append_test_tone(player: &Player) {
    player.append(
        SineWave::new(880.0)
            .take_duration(Duration::from_millis(750))
            .amplify(1.0),
    );
}

fn bell_pulse() {
    eprint!("\x07");
    let _ = io::stderr().flush();
}

fn send_background_alarm_notification(
    alarm_id: Option<&str>,
    notifications: AlarmNotificationConfig,
    control: &StopControl,
) {
    if !notifications.enabled {
        return;
    }

    if let Err(err) = notify_background_alarm(alarm_id, notifications, control) {
        eprintln!("tix: background notification failed ({err})");
    }
}

#[cfg(target_os = "macos")]
fn notify_background_alarm(
    alarm_id: Option<&str>,
    notifications: AlarmNotificationConfig,
    _control: &StopControl,
) -> io::Result<()> {
    let mut notification = Notification::new();
    notification
        .summary("tix alarm")
        .body(&notification_body(alarm_id, false, false))
        .timeout(notification_timeout(notifications.timeout_ms))
        .show()
        .map(|_| ())
        .map_err(|err| io::Error::other(format!("desktop notification failed: {err}")))
}

#[cfg(target_os = "linux")]
fn notify_background_alarm(
    alarm_id: Option<&str>,
    notifications: AlarmNotificationConfig,
    control: &StopControl,
) -> io::Result<()> {
    let mut notification = Notification::new();
    notification
        .summary("tix alarm")
        .body(&notification_body(
            alarm_id,
            notifications.clickable,
            notifications.show_stop_button,
        ))
        .timeout(notification_timeout(notifications.timeout_ms));

    if notifications.timeout_ms == 0 {
        notification.hint(Hint::Resident(true));
    }
    if notifications.clickable {
        // "default" maps body-click activation on XDG notification servers.
        notification.action("default", "Stop alarm");
        if notifications.show_stop_button {
            notification.action("stop", "Stop");
        }
    }

    let handle = notification
        .show()
        .map_err(|err| io::Error::other(format!("desktop notification failed: {err}")))?;
    if notifications.clickable {
        spawn_notification_action_listener(handle, control);
    }
    Ok(())
}

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn notify_background_alarm(
    _alarm_id: Option<&str>,
    _notifications: AlarmNotificationConfig,
    _control: &StopControl,
) -> io::Result<()> {
    Err(io::Error::other(
        "background notifications are not supported on this platform",
    ))
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
fn notification_timeout(timeout_ms: u32) -> Timeout {
    if timeout_ms == 0 {
        Timeout::Never
    } else {
        Timeout::Milliseconds(timeout_ms)
    }
}

fn notification_body(alarm_id: Option<&str>, clickable: bool, show_stop_button: bool) -> String {
    match alarm_id {
        Some(alarm_id) if clickable && show_stop_button => {
            format!("alarm ringing. click or press stop or run tix stop {alarm_id}")
        }
        Some(alarm_id) if clickable => {
            format!("alarm ringing. click to stop or run tix stop {alarm_id}")
        }
        Some(alarm_id) => format!("alarm ringing. run tix stop {alarm_id}"),
        None => "alarm ringing".to_string(),
    }
}

#[cfg(target_os = "linux")]
fn spawn_notification_action_listener(handle: NotificationHandle, control: &StopControl) {
    let stop = control.stop.clone();
    let wake_tx = control.wake_tx.clone();

    thread::spawn(move || {
        handle.wait_for_action(move |action| {
            if matches!(action, "default" | "stop") {
                stop.store(true, Ordering::Relaxed);
                let _ = wake_tx.try_send(());
            }
        });
    });
}