fernctl/error/
notify.rs

1//! # Notification Integration for Errors
2//!
3//! This module provides the [`Notifiable`] trait and [`Notification`] struct,
4//! enabling errors to be displayed as desktop notifications.
5//!
6//! ## Design Rationale
7//!
8//! Errors in a desktop shell should be visible to users, not buried in logs.
9//! By implementing [`Notifiable`] on error types, we can:
10//!
11//! 1. Display rich, actionable notifications when things go wrong
12//! 2. Categorize notifications by severity for appropriate presentation
13//! 3. Provide suggestions that help users fix problems themselves
14//!
15//! ## Integration Flow
16//!
17//! ```text
18//! ConfigError implements Notifiable
19//!         │
20//!         ▼
21//! error.to_notification()
22//!         │
23//!         ▼
24//! NotifyPort::send(notification)
25//!         │
26//!         ▼
27//! D-Bus adapter → Desktop notification service
28//! ```
29//!
30//! ## Example
31//!
32//! ```rust,ignore
33//! use fernctl::error::{ConfigError, Notifiable, Notification};
34//!
35//! let error = ConfigError::InvalidColor {
36//!     value: "#gg0000".to_string(),
37//!     span: None,
38//!     source_code: None,
39//! };
40//!
41//! // Convert to notification
42//! let notification = error.to_notification();
43//!
44//! // Send via notification port
45//! notify_port.send(notification)?;
46//! ```
47
48use super::Severity;
49use serde::{Deserialize, Serialize};
50use std::time::SystemTime;
51
52/// Trait for types that can be converted to user-facing notifications.
53///
54/// Implement this trait on error types to enable rich desktop notifications.
55/// The trait provides all the information needed to display a helpful,
56/// actionable notification to the user.
57///
58/// # Required Methods
59///
60/// | Method | Purpose |
61/// |--------|---------|
62/// | [`severity`](Notifiable::severity) | How serious is this? |
63/// | [`title`](Notifiable::title) | Short summary for notification header |
64/// | [`body`](Notifiable::body) | Detailed explanation |
65///
66/// # Optional Methods
67///
68/// | Method | Purpose | Default |
69/// |--------|---------|---------|
70/// | [`suggestion`](Notifiable::suggestion) | How to fix it | `None` |
71/// | [`code`](Notifiable::code) | Error code for docs | `None` |
72///
73/// # Example Implementation
74///
75/// ```rust,ignore
76/// use fernctl::error::{Notifiable, Severity};
77///
78/// struct MyError {
79///     message: String,
80/// }
81///
82/// impl Notifiable for MyError {
83///     fn severity(&self) -> Severity {
84///         Severity::Error
85///     }
86///
87///     fn title(&self) -> String {
88///         "Something Went Wrong".to_string()
89///     }
90///
91///     fn body(&self) -> String {
92///         self.message.clone()
93///     }
94///
95///     fn suggestion(&self) -> Option<String> {
96///         Some("Try restarting the shell".to_string())
97///     }
98///
99///     fn code(&self) -> Option<&'static str> {
100///         Some("my::error::code")
101///     }
102/// }
103/// ```
104pub trait Notifiable {
105    /// Returns the severity level of this notification.
106    ///
107    /// Severity determines the visual presentation and behavior:
108    ///
109    /// - [`Info`](Severity::Info) — Subtle, may auto-dismiss
110    /// - [`Warning`](Severity::Warning) — Visible, yellow/orange styling
111    /// - [`Error`](Severity::Error) — Prominent, red styling, requires attention
112    /// - [`Fatal`](Severity::Fatal) — Critical, may block other UI
113    fn severity(&self) -> Severity;
114
115    /// Returns a short title for the notification header.
116    ///
117    /// This should be concise (ideally under 50 characters) and immediately
118    /// convey the nature of the notification.
119    ///
120    /// # Good Titles
121    ///
122    /// - "Invalid Color"
123    /// - "Config Loaded"
124    /// - "Module Failed: Clock"
125    ///
126    /// # Bad Titles
127    ///
128    /// - "Error" (too vague)
129    /// - "The color value you specified in config.toml is not valid" (too long)
130    fn title(&self) -> String;
131
132    /// Returns the detailed body text of the notification.
133    ///
134    /// This should explain what happened. For errors, include specifics about
135    /// what went wrong. Keep it readable — avoid raw error dumps.
136    fn body(&self) -> String;
137
138    /// Returns an optional suggestion for fixing the problem.
139    ///
140    /// When present, this should be an actionable instruction the user can
141    /// follow. Be specific and helpful.
142    ///
143    /// # Good Suggestions
144    ///
145    /// - "Use hex format: #RRGGBB"
146    /// - "Did you mean `color`?"
147    /// - "Check that QuickShell is running"
148    ///
149    /// # Bad Suggestions
150    ///
151    /// - "Fix the error" (not actionable)
152    /// - "See documentation" (too vague — link to specific docs instead)
153    fn suggestion(&self) -> Option<String> {
154        None
155    }
156
157    /// Returns an optional error code for documentation lookup.
158    ///
159    /// Error codes follow the pattern `category::subcategory::name` and can
160    /// be used to find detailed documentation.
161    ///
162    /// # Example Codes
163    ///
164    /// - `fern::config::invalid_color`
165    /// - `fern::io::permission_denied`
166    /// - `fern::ipc::timeout`
167    fn code(&self) -> Option<&'static str> {
168        None
169    }
170
171    /// Converts this notifiable into a [`Notification`] struct.
172    ///
173    /// This is a convenience method that creates a notification with all
174    /// fields populated from the trait methods.
175    ///
176    /// # Example
177    ///
178    /// ```rust,ignore
179    /// let notification = error.to_notification();
180    /// notify_port.send(notification)?;
181    /// ```
182    fn to_notification(&self) -> Notification {
183        Notification {
184            severity: self.severity(),
185            title: self.title(),
186            body: self.body(),
187            suggestion: self.suggestion(),
188            code: self.code().map(String::from),
189            timestamp: SystemTime::now(),
190        }
191    }
192}
193
194/// A notification ready to be sent to the desktop notification service.
195///
196/// `Notification` is a plain data struct containing all information needed
197/// to display a notification. It is serializable for IPC transmission.
198///
199/// # Creating Notifications
200///
201/// Notifications are typically created from types implementing [`Notifiable`]:
202///
203/// ```rust,ignore
204/// let notification = error.to_notification();
205/// ```
206///
207/// But you can also create them directly:
208///
209/// ```rust,ignore
210/// let notification = Notification::new(
211///     Severity::Info,
212///     "Config Loaded",
213///     "Successfully loaded configuration from config.toml",
214/// );
215/// ```
216///
217/// # Serialization
218///
219/// Notifications serialize to JSON for D-Bus transmission:
220///
221/// ```rust,ignore
222/// let json = serde_json::to_string(&notification)?;
223/// // {"severity":"info","title":"...","body":"...",...}
224/// ```
225#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
226pub struct Notification {
227    /// Severity level determining visual presentation.
228    pub severity: Severity,
229
230    /// Short title for the notification header.
231    pub title: String,
232
233    /// Detailed body text.
234    pub body: String,
235
236    /// Optional actionable suggestion.
237    #[serde(skip_serializing_if = "Option::is_none")]
238    pub suggestion: Option<String>,
239
240    /// Optional error code for documentation lookup.
241    #[serde(skip_serializing_if = "Option::is_none")]
242    pub code: Option<String>,
243
244    /// When the notification was created.
245    #[serde(with = "system_time_serde")]
246    pub timestamp: SystemTime,
247}
248
249impl Notification {
250    /// Creates a new notification with the given severity, title, and body.
251    ///
252    /// # Arguments
253    ///
254    /// * `severity` — How serious is this notification
255    /// * `title` — Short summary for the header
256    /// * `body` — Detailed explanation
257    ///
258    /// # Example
259    ///
260    /// ```rust
261    /// use fernctl::error::{Notification, Severity};
262    ///
263    /// let notification = Notification::new(
264    ///     Severity::Info,
265    ///     "Config Loaded",
266    ///     "Successfully loaded configuration",
267    /// );
268    /// ```
269    #[must_use]
270    pub fn new(
271        severity: Severity,
272        title: impl Into<String>,
273        body: impl Into<String>,
274    ) -> Self {
275        Self {
276            severity,
277            title: title.into(),
278            body: body.into(),
279            suggestion: None,
280            code: None,
281            timestamp: SystemTime::now(),
282        }
283    }
284
285    /// Creates an informational notification.
286    ///
287    /// Convenience constructor for [`Severity::Info`] notifications.
288    ///
289    /// # Example
290    ///
291    /// ```rust
292    /// use fernctl::error::Notification;
293    ///
294    /// let notification = Notification::info("Config Loaded", "All modules initialized");
295    /// ```
296    #[must_use]
297    pub fn info(title: impl Into<String>, body: impl Into<String>) -> Self {
298        Self::new(Severity::Info, title, body)
299    }
300
301    /// Creates a warning notification.
302    ///
303    /// Convenience constructor for [`Severity::Warning`] notifications.
304    ///
305    /// # Example
306    ///
307    /// ```rust
308    /// use fernctl::error::Notification;
309    ///
310    /// let notification = Notification::warning(
311    ///     "Unknown Key",
312    ///     "Configuration contains unknown key 'colour'",
313    /// );
314    /// ```
315    #[must_use]
316    pub fn warning(title: impl Into<String>, body: impl Into<String>) -> Self {
317        Self::new(Severity::Warning, title, body)
318    }
319
320    /// Creates an error notification.
321    ///
322    /// Convenience constructor for [`Severity::Error`] notifications.
323    ///
324    /// # Example
325    ///
326    /// ```rust
327    /// use fernctl::error::Notification;
328    ///
329    /// let notification = Notification::error(
330    ///     "Invalid Color",
331    ///     "Color '#gg0000' is not valid hex",
332    /// );
333    /// ```
334    #[must_use]
335    pub fn error(title: impl Into<String>, body: impl Into<String>) -> Self {
336        Self::new(Severity::Error, title, body)
337    }
338
339    /// Adds a suggestion to this notification.
340    ///
341    /// # Example
342    ///
343    /// ```rust
344    /// use fernctl::error::Notification;
345    ///
346    /// let notification = Notification::error("Invalid Color", "...")
347    ///     .with_suggestion("Use hex format: #RRGGBB");
348    /// ```
349    #[must_use]
350    pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
351        self.suggestion = Some(suggestion.into());
352        self
353    }
354
355    /// Adds an error code to this notification.
356    ///
357    /// # Example
358    ///
359    /// ```rust
360    /// use fernctl::error::Notification;
361    ///
362    /// let notification = Notification::error("Invalid Color", "...")
363    ///     .with_code("fern::config::invalid_color");
364    /// ```
365    #[must_use]
366    pub fn with_code(mut self, code: impl Into<String>) -> Self {
367        self.code = Some(code.into());
368        self
369    }
370
371    /// Returns `true` if this notification indicates an error condition.
372    ///
373    /// # Example
374    ///
375    /// ```rust
376    /// use fernctl::error::{Notification, Severity};
377    ///
378    /// let info = Notification::info("Test", "Test");
379    /// let error = Notification::error("Test", "Test");
380    ///
381    /// assert!(!info.is_error());
382    /// assert!(error.is_error());
383    /// ```
384    #[must_use]
385    pub fn is_error(&self) -> bool {
386        self.severity.is_error()
387    }
388}
389
390impl std::fmt::Display for Notification {
391    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
392        write!(f, "{} {}: {}", self.severity.icon(), self.title, self.body)
393    }
394}
395
396/// Serde support for `SystemTime`.
397///
398/// The `pub` visibility is required for serde's `#[serde(with = "...")]` attribute.
399#[allow(unreachable_pub)]
400mod system_time_serde {
401    use serde::{Deserialize, Deserializer, Serialize, Serializer};
402    use std::time::{Duration, SystemTime, UNIX_EPOCH};
403
404    pub fn serialize<S>(time: &SystemTime, serializer: S) -> Result<S::Ok, S::Error>
405    where
406        S: Serializer,
407    {
408        let duration = time.duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO);
409        duration.as_secs().serialize(serializer)
410    }
411
412    pub fn deserialize<'de, D>(deserializer: D) -> Result<SystemTime, D::Error>
413    where
414        D: Deserializer<'de>,
415    {
416        let secs = u64::deserialize(deserializer)?;
417        Ok(UNIX_EPOCH + Duration::from_secs(secs))
418    }
419}
420
421#[cfg(test)]
422mod tests {
423    use super::*;
424
425    #[test]
426    fn notification_new() {
427        let n = Notification::new(Severity::Error, "Title", "Body");
428        assert_eq!(n.severity, Severity::Error);
429        assert_eq!(n.title, "Title");
430        assert_eq!(n.body, "Body");
431        assert!(n.suggestion.is_none());
432        assert!(n.code.is_none());
433    }
434
435    #[test]
436    fn notification_builders() {
437        let n = Notification::error("Title", "Body")
438            .with_suggestion("Fix it")
439            .with_code("fern::test");
440
441        assert_eq!(n.suggestion, Some("Fix it".to_string()));
442        assert_eq!(n.code, Some("fern::test".to_string()));
443    }
444
445    #[test]
446    fn notification_display() {
447        let n = Notification::warning("Test", "Test body");
448        let display = n.to_string();
449        assert!(display.contains("Test"));
450        assert!(display.contains("Test body"));
451    }
452
453    #[test]
454    fn notification_serialization_roundtrip() {
455        let original = Notification::error("Title", "Body")
456            .with_suggestion("Fix it")
457            .with_code("fern::test");
458
459        let json = serde_json::to_string(&original).expect("serialize");
460        let restored: Notification = serde_json::from_str(&json).expect("deserialize");
461
462        assert_eq!(original.severity, restored.severity);
463        assert_eq!(original.title, restored.title);
464        assert_eq!(original.body, restored.body);
465        assert_eq!(original.suggestion, restored.suggestion);
466        assert_eq!(original.code, restored.code);
467    }
468}