fernctl/ports/outbound.rs
1//! # Outbound Ports — Driven Services
2//!
3//! Outbound ports define how the domain can **use** external services. They
4//! represent capabilities the application needs but doesn't implement itself:
5//! persistence, notifications, inter-process communication.
6//!
7//! ## Overview
8//!
9//! ```text
10//! ┌──────────────┐
11//! │ DOMAIN │
12//! │ Theme │
13//! │ Validation │
14//! └──────┬───────┘
15//! │
16//! ╔══════════════════════════╧══════════════════════════════╗
17//! ║ OUTBOUND PORTS ║
18//! ║ ║
19//! ║ PersistPort ────► Save themes to disk ║
20//! ║ NotifyPort ─────► Show desktop notifications ║
21//! ║ IpcPort ────────► Communicate with QuickShell ║
22//! ║ ║
23//! ╚═════╤════════════════════╤════════════════════╤═════════╝
24//! │ │ │
25//! ┌─────▼──────┐ ┌─────▼──────┐ ┌─────▼──────┐
26//! │FileAdapter │ │NotifAdapter│ │DbusAdapter │
27//! │ │ │ │ │ │
28//! │ Writes to │ │ Sends via │ │ Calls via │
29//! │ filesystem │ │ D-Bus │ │ D-Bus │
30//! └─────┬──────┘ └─────┬──────┘ └─────┬──────┘
31//! │ │ │
32//! ┌─────▼──────┐ ┌─────▼──────┐ ┌─────▼──────┐
33//! │ Filesystem │ │ Desktop │ │ QuickShell │
34//! │ │ │Notification│ │ │
35//! │ ~/.config/ │ │ Service │ │ D-Bus │
36//! │ fern/ │ │ │ │ Service │
37//! └────────────┘ └────────────┘ └────────────┘
38//! ```
39//!
40//! ## Dependency Inversion
41//!
42//! Outbound ports demonstrate the **Dependency Inversion Principle**:
43//!
44//! - The domain depends on *abstractions* (port traits)
45//! - Adapters depend on the domain (they implement port traits)
46//! - External systems are accessed only through adapters
47//!
48//! This means the domain never knows about file systems, D-Bus, or any
49//! specific technology. It just calls trait methods.
50//!
51//! ```rust,ignore
52//! // Domain code - doesn't know about D-Bus
53//! fn reload_theme(ipc: &impl IpcPort, theme: &Theme) -> Result<()> {
54//! ipc.send_reload(theme)?;
55//! Ok(())
56//! }
57//!
58//! // Adapter - implements the port using D-Bus
59//! struct DbusIpcAdapter { /* D-Bus connection */ }
60//!
61//! impl IpcPort for DbusIpcAdapter {
62//! fn send_reload(&self, theme: &Theme) -> Result<()> {
63//! // D-Bus specific code here
64//! }
65//! }
66//! ```
67//!
68//! ## Port Responsibilities
69//!
70//! | Port | Responsibility | External System |
71//! |------|----------------|-----------------|
72//! | [`PersistPort`] | Save/load theme files | Filesystem |
73//! | [`NotifyPort`] | Send desktop notifications | Notification daemon |
74//! | [`IpcPort`] | Communicate with QuickShell | D-Bus |
75//!
76//! ## Testing with Mocks
77//!
78//! Because ports are traits, they're easy to mock for testing:
79//!
80//! ```rust,ignore
81//! use std::sync::atomic::{AtomicUsize, Ordering};
82//!
83//! struct MockNotifyPort {
84//! call_count: AtomicUsize,
85//! }
86//!
87//! impl NotifyPort for MockNotifyPort {
88//! fn send(&self, _: Notification) -> Result<()> {
89//! self.call_count.fetch_add(1, Ordering::SeqCst);
90//! Ok(())
91//! }
92//! }
93//!
94//! #[test]
95//! fn sends_notification_on_error() {
96//! let mock = MockNotifyPort { call_count: AtomicUsize::new(0) };
97//! // ... test code that should send a notification ...
98//! assert_eq!(mock.call_count.load(Ordering::SeqCst), 1);
99//! }
100//! ```
101
102use crate::domain::theme::Theme;
103use crate::error::{Notification, Result};
104use std::path::Path;
105
106// ============================================================================
107// PersistPort Trait
108// ============================================================================
109
110/// Port for persisting configuration and themes to storage.
111///
112/// `PersistPort` abstracts over different storage backends, enabling the
113/// domain to save and load themes without knowing the underlying storage
114/// mechanism.
115///
116/// # Implementations
117///
118/// - **Filesystem** — Writes JSON files to `~/.config/fern/`
119/// - **XDG** — Follows XDG Base Directory Specification
120/// - **Memory** — In-memory storage for testing
121///
122/// # File Structure
123///
124/// The recommended file structure for persisted themes:
125///
126/// ```text
127/// ~/.config/fern/
128/// ├── config.toml # User configuration (source of truth)
129/// ├── config.json # Generated JSON for QuickShell
130/// └── themes/
131/// ├── dark.json # Built-in dark theme
132/// ├── light.json # Built-in light theme
133/// └── custom.json # User-created themes
134/// ```
135///
136/// # Example
137///
138/// ```rust,ignore
139/// use fernctl::ports::outbound::PersistPort;
140/// use fernctl::adapters::FileSystemAdapter;
141///
142/// let adapter = FileSystemAdapter::new();
143///
144/// // Save a theme
145/// adapter.save_theme(&theme, "~/.config/fern/config.json")?;
146///
147/// // Load a theme
148/// let loaded = adapter.load_theme("~/.config/fern/config.json")?;
149/// ```
150pub trait PersistPort: Send + Sync {
151 /// Saves a theme to the specified path.
152 ///
153 /// The theme is serialized to JSON format for QuickShell compatibility.
154 ///
155 /// # Arguments
156 ///
157 /// * `theme` — The theme to save
158 /// * `path` — The file path to write to
159 ///
160 /// # Errors
161 ///
162 /// Returns [`FernError::Io`] if the file cannot be written.
163 ///
164 /// # Example
165 ///
166 /// ```rust,ignore
167 /// adapter.save_theme(&theme, "config.json")?;
168 /// ```
169 fn save_theme(&self, theme: &Theme, path: impl AsRef<Path>) -> Result<()>;
170
171 /// Loads a theme from the specified path.
172 ///
173 /// # Arguments
174 ///
175 /// * `path` — The file path to read from
176 ///
177 /// # Returns
178 ///
179 /// The loaded [`Theme`].
180 ///
181 /// # Errors
182 ///
183 /// - [`FernError::Io`] if the file cannot be read
184 /// - [`ConfigError`] if the file content is invalid
185 fn load_theme(&self, path: impl AsRef<Path>) -> Result<Theme>;
186
187 /// Returns the default configuration directory.
188 ///
189 /// This follows platform conventions:
190 /// - Linux: `~/.config/fern/`
191 /// - macOS: `~/Library/Application Support/fern/`
192 /// - Windows: `%APPDATA%\fern\`
193 ///
194 /// # Returns
195 ///
196 /// The path to the configuration directory, or `None` if it cannot be
197 /// determined.
198 fn config_dir(&self) -> Option<std::path::PathBuf>;
199
200 /// Ensures the configuration directory exists.
201 ///
202 /// Creates the directory and any parent directories if they don't exist.
203 ///
204 /// # Errors
205 ///
206 /// Returns [`FernError::Io`] if the directory cannot be created.
207 fn ensure_config_dir(&self) -> Result<std::path::PathBuf>;
208
209 /// Checks if a configuration file exists.
210 ///
211 /// # Arguments
212 ///
213 /// * `path` — The file path to check
214 ///
215 /// # Returns
216 ///
217 /// `true` if the file exists and is readable.
218 fn exists(&self, path: impl AsRef<Path>) -> bool;
219}
220
221// ============================================================================
222// NotifyPort Trait
223// ============================================================================
224
225/// Port for sending desktop notifications.
226///
227/// `NotifyPort` provides a way to display notifications to the user. This is
228/// used for:
229///
230/// - Configuration errors that need user attention
231/// - Successful theme reloads
232/// - Warnings about deprecated options
233///
234/// # Notification Levels
235///
236/// | Level | Use Case | User Impact |
237/// |-------|----------|-------------|
238/// | Info | Success messages | Brief, auto-dismiss |
239/// | Warning | Potential issues | Visible but non-blocking |
240/// | Error | Problems requiring action | Persistent, prominent |
241///
242/// # Desktop Integration
243///
244/// The notification adapter should use the system notification service:
245///
246/// - **Linux**: D-Bus `org.freedesktop.Notifications`
247/// - **macOS**: `NSUserNotificationCenter`
248/// - **Windows**: Toast notifications
249///
250/// # Example
251///
252/// ```rust,ignore
253/// use fernctl::ports::outbound::NotifyPort;
254/// use fernctl::error::Notification;
255///
256/// // Send an info notification
257/// let notification = Notification::info(
258/// "Theme Loaded",
259/// "Dark theme applied successfully",
260/// );
261/// adapter.send(notification)?;
262///
263/// // Send an error notification
264/// let notification = Notification::error(
265/// "Invalid Color",
266/// "Color '#gg0000' is not valid",
267/// ).with_suggestion("Use hex format: #RRGGBB");
268/// adapter.send(notification)?;
269/// ```
270///
271/// # Suppressing Notifications
272///
273/// Users may want to disable notifications. Adapters should respect a
274/// configuration option for this:
275///
276/// ```rust,ignore
277/// if !config.notifications_enabled {
278/// return Ok(()); // Silently succeed
279/// }
280/// ```
281pub trait NotifyPort: Send + Sync {
282 /// Sends a notification to the desktop notification service.
283 ///
284 /// # Arguments
285 ///
286 /// * `notification` — The notification to display
287 ///
288 /// # Errors
289 ///
290 /// Returns an error if the notification cannot be sent. However,
291 /// notification failures are typically non-fatal — the application
292 /// should continue even if notifications are unavailable.
293 ///
294 /// # Example
295 ///
296 /// ```rust,ignore
297 /// let notification = Notification::info("Test", "Hello world");
298 /// if let Err(e) = adapter.send(notification) {
299 /// // Log but don't fail
300 /// log::warn!("Could not send notification: {}", e);
301 /// }
302 /// ```
303 fn send(&self, notification: Notification) -> Result<()>;
304
305 /// Sends an info-level notification.
306 ///
307 /// Convenience method for sending simple informational notifications.
308 ///
309 /// # Arguments
310 ///
311 /// * `title` — The notification title
312 /// * `body` — The notification body text
313 ///
314 /// # Example
315 ///
316 /// ```rust,ignore
317 /// adapter.info("Theme Loaded", "Configuration applied")?;
318 /// ```
319 fn info(&self, title: impl Into<String>, body: impl Into<String>) -> Result<()> {
320 self.send(Notification::info(title, body))
321 }
322
323 /// Sends a warning-level notification.
324 ///
325 /// Convenience method for sending warning notifications.
326 ///
327 /// # Arguments
328 ///
329 /// * `title` — The notification title
330 /// * `body` — The notification body text
331 ///
332 /// # Example
333 ///
334 /// ```rust,ignore
335 /// adapter.warning("Deprecated Option", "The 'colour' key is deprecated")?;
336 /// ```
337 fn warning(&self, title: impl Into<String>, body: impl Into<String>) -> Result<()> {
338 self.send(Notification::warning(title, body))
339 }
340
341 /// Sends an error-level notification.
342 ///
343 /// Convenience method for sending error notifications.
344 ///
345 /// # Arguments
346 ///
347 /// * `title` — The notification title
348 /// * `body` — The notification body text
349 ///
350 /// # Example
351 ///
352 /// ```rust,ignore
353 /// adapter.error("Config Error", "Invalid color format")?;
354 /// ```
355 fn error(&self, title: impl Into<String>, body: impl Into<String>) -> Result<()> {
356 self.send(Notification::error(title, body))
357 }
358
359 /// Checks if notifications are available on this system.
360 ///
361 /// # Returns
362 ///
363 /// `true` if the notification service is available and responding.
364 ///
365 /// # Example
366 ///
367 /// ```rust,ignore
368 /// if adapter.is_available() {
369 /// adapter.send(notification)?;
370 /// } else {
371 /// eprintln!("{}", notification); // Fallback to stderr
372 /// }
373 /// ```
374 fn is_available(&self) -> bool {
375 true // Adapters can override with actual check
376 }
377}
378
379// ============================================================================
380// IpcPort Trait
381// ============================================================================
382
383/// Port for inter-process communication with QuickShell.
384///
385/// `IpcPort` provides communication between `fernctl` and the running
386/// QuickShell instance. This enables:
387///
388/// - Live theme reloading without restarting the shell
389/// - Querying current shell state
390/// - Sending commands to the shell
391///
392/// # Communication Protocol
393///
394/// The default implementation uses D-Bus for IPC:
395///
396/// ```text
397/// fernctl QuickShell
398/// │ │
399/// │ D-Bus: org.fern.Shell │
400/// │ ───────────────────────────────► │
401/// │ Method: ReloadTheme │
402/// │ Params: { path: "..." } │
403/// │ │
404/// │ Response: { success: true } │
405/// │ ◄─────────────────────────────── │
406/// │ │
407/// ```
408///
409/// # Alternative Transports
410///
411/// While D-Bus is the primary transport, adapters can implement other
412/// mechanisms:
413///
414/// - **Unix Socket**: Direct socket communication
415/// - **File Watching**: QuickShell watches a file for changes
416/// - **Signals**: Unix signals for simple commands
417///
418/// # Example
419///
420/// ```rust,ignore
421/// use fernctl::ports::outbound::IpcPort;
422/// use fernctl::adapters::DbusIpcAdapter;
423///
424/// let ipc = DbusIpcAdapter::new()?;
425///
426/// // Reload theme
427/// ipc.reload_theme(&theme)?;
428///
429/// // Check if shell is running
430/// if ipc.is_shell_running() {
431/// ipc.send_command("refresh")?;
432/// }
433/// ```
434///
435/// # Error Handling
436///
437/// IPC operations can fail for various reasons:
438///
439/// | Error | Cause | Recovery |
440/// |-------|-------|----------|
441/// | Not running | QuickShell not started | Start the shell |
442/// | Timeout | Shell not responding | Restart the shell |
443/// | Protocol error | Version mismatch | Update fernctl |
444pub trait IpcPort: Send + Sync {
445 /// Signals QuickShell to reload its theme.
446 ///
447 /// This sends the updated theme to QuickShell for live application.
448 /// The shell will re-read the configuration and update all components.
449 ///
450 /// # Arguments
451 ///
452 /// * `theme` — The new theme to apply
453 ///
454 /// # Errors
455 ///
456 /// - [`FernError::Ipc`] if QuickShell is not running
457 /// - [`FernError::Ipc`] if the reload times out
458 ///
459 /// # Example
460 ///
461 /// ```rust,ignore
462 /// // Save theme to disk first
463 /// persist.save_theme(&theme, config_path)?;
464 ///
465 /// // Then signal reload
466 /// ipc.reload_theme(&theme)?;
467 /// ```
468 fn reload_theme(&self, theme: &Theme) -> Result<()>;
469
470 /// Sends a raw command to QuickShell.
471 ///
472 /// Commands are shell-specific strings that trigger actions.
473 ///
474 /// # Built-in Commands
475 ///
476 /// | Command | Effect |
477 /// |---------|--------|
478 /// | `refresh` | Refresh all modules |
479 /// | `restart` | Restart the shell |
480 /// | `quit` | Gracefully exit |
481 ///
482 /// # Arguments
483 ///
484 /// * `command` — The command string to send
485 ///
486 /// # Errors
487 ///
488 /// Returns an error if the command cannot be sent or is rejected.
489 ///
490 /// # Example
491 ///
492 /// ```rust,ignore
493 /// ipc.send_command("refresh")?;
494 /// ```
495 fn send_command(&self, command: &str) -> Result<()>;
496
497 /// Checks if QuickShell is currently running.
498 ///
499 /// This performs a lightweight check (e.g., pinging the D-Bus service)
500 /// to determine if the shell is available for commands.
501 ///
502 /// # Returns
503 ///
504 /// `true` if QuickShell is running and responding.
505 ///
506 /// # Example
507 ///
508 /// ```rust,ignore
509 /// if !ipc.is_shell_running() {
510 /// eprintln!("QuickShell is not running");
511 /// return Ok(()); // Theme saved, will be applied on next start
512 /// }
513 /// ```
514 fn is_shell_running(&self) -> bool;
515
516 /// Returns the version of the running QuickShell instance.
517 ///
518 /// Useful for compatibility checks and debugging.
519 ///
520 /// # Returns
521 ///
522 /// The version string, or `None` if the shell is not running or
523 /// the version cannot be determined.
524 ///
525 /// # Example
526 ///
527 /// ```rust,ignore
528 /// if let Some(version) = ipc.shell_version() {
529 /// println!("QuickShell version: {}", version);
530 /// }
531 /// ```
532 fn shell_version(&self) -> Option<String>;
533
534 /// Pings the shell to check connectivity.
535 ///
536 /// This is a more thorough check than [`is_shell_running`], verifying
537 /// that the shell can receive and respond to messages.
538 ///
539 /// # Returns
540 ///
541 /// The round-trip time in milliseconds, or an error if the ping failed.
542 ///
543 /// # Example
544 ///
545 /// ```rust,ignore
546 /// match ipc.ping() {
547 /// Ok(ms) => println!("Shell responded in {}ms", ms),
548 /// Err(e) => eprintln!("Shell not responding: {}", e),
549 /// }
550 /// ```
551 fn ping(&self) -> Result<u64>;
552}
553
554// ============================================================================
555// Null Implementations for Testing
556// ============================================================================
557
558/// A no-op implementation of [`NotifyPort`] for testing.
559///
560/// This adapter accepts all notifications but doesn't actually send them.
561/// Useful for unit tests where notification delivery isn't being tested.
562///
563/// # Example
564///
565/// ```rust
566/// use fernctl::ports::outbound::{NotifyPort, NullNotifyPort};
567/// use fernctl::error::Notification;
568///
569/// let notifier = NullNotifyPort;
570/// let notification = Notification::info("Test", "Body");
571///
572/// // This succeeds but does nothing
573/// notifier.send(notification).unwrap();
574/// ```
575#[derive(Debug, Clone, Copy, Default)]
576pub struct NullNotifyPort;
577
578impl NotifyPort for NullNotifyPort {
579 fn send(&self, _notification: Notification) -> Result<()> {
580 Ok(())
581 }
582
583 fn is_available(&self) -> bool {
584 false
585 }
586}
587
588/// A no-op implementation of [`IpcPort`] for testing.
589///
590/// This adapter simulates a disconnected shell. All operations succeed
591/// but [`is_shell_running`] returns `false`.
592///
593/// # Example
594///
595/// ```rust
596/// use fernctl::ports::outbound::{IpcPort, NullIpcPort};
597///
598/// let ipc = NullIpcPort;
599/// assert!(!ipc.is_shell_running());
600/// ```
601#[derive(Debug, Clone, Copy, Default)]
602pub struct NullIpcPort;
603
604impl IpcPort for NullIpcPort {
605 fn reload_theme(&self, _theme: &Theme) -> Result<()> {
606 Ok(())
607 }
608
609 fn send_command(&self, _command: &str) -> Result<()> {
610 Ok(())
611 }
612
613 fn is_shell_running(&self) -> bool {
614 false
615 }
616
617 fn shell_version(&self) -> Option<String> {
618 None
619 }
620
621 fn ping(&self) -> Result<u64> {
622 Err(crate::error::FernError::ipc("shell not running"))
623 }
624}
625
626// ============================================================================
627// Tests
628// ============================================================================
629
630#[cfg(test)]
631mod tests {
632 use super::*;
633
634 #[test]
635 fn null_notify_port_accepts_notifications() {
636 let notifier = NullNotifyPort;
637 let notification = Notification::info("Test", "Body");
638 assert!(notifier.send(notification).is_ok());
639 }
640
641 #[test]
642 fn null_notify_port_reports_unavailable() {
643 let notifier = NullNotifyPort;
644 assert!(!notifier.is_available());
645 }
646
647 #[test]
648 fn null_ipc_port_reports_not_running() {
649 let ipc = NullIpcPort;
650 assert!(!ipc.is_shell_running());
651 assert!(ipc.shell_version().is_none());
652 }
653
654 #[test]
655 fn null_ipc_port_ping_fails() {
656 let ipc = NullIpcPort;
657 assert!(ipc.ping().is_err());
658 }
659}