firefox-webdriver 0.1.4

High-performance Firefox WebDriver in Rust
Documentation
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
//! Browser window management and control.
//!
//! Each [`Window`] owns:
//! - One Firefox process (child process)
//! - Reference to shared ConnectionPool
//! - One profile directory (temporary or persistent)
//!
//! # Example
//!
//! ```no_run
//! use firefox_webdriver::Driver;
//!
//! # async fn example() -> firefox_webdriver::Result<()> {
//! let driver = Driver::builder()
//!     .binary("/usr/bin/firefox")
//!     .extension("./extension")
//!     .build()
//!     .await?;
//!
//! let window = driver.window()
//!     .headless()
//!     .window_size(1920, 1080)
//!     .spawn()
//!     .await?;
//!
//! let tab = window.tab();
//! tab.goto("https://example.com").await?;
//!
//! window.close().await?;
//! # Ok(())
//! # }
//! ```

// ============================================================================
// Imports
// ============================================================================

use std::fmt;
use std::path::PathBuf;
use std::sync::Arc;

use parking_lot::Mutex;
use rustc_hash::FxHashMap;
use serde_json::Value;
use tokio::process::Child;
use tracing::{debug, info};
use uuid::Uuid;

use crate::driver::{Driver, FirefoxOptions, Profile};
use crate::error::{Error, Result};
use crate::identifiers::{FrameId, InterceptId, SessionId, TabId};
use crate::protocol::{
    BrowsingContextCommand, Command, ProxyCommand, Request, Response, SessionCommand,
};
use crate::transport::ConnectionPool;

use super::Tab;
use super::proxy::ProxyConfig;

// ============================================================================
// ProcessGuard
// ============================================================================

/// Guards a child process and ensures it is killed when dropped.
struct ProcessGuard {
    /// The child process handle.
    child: Option<Child>,
    /// Process ID for logging.
    pid: u32,
}

impl ProcessGuard {
    /// Creates a new process guard.
    fn new(child: Child) -> Self {
        let pid = child.id().unwrap_or(0);
        debug!(pid, "Process guard created");
        Self {
            child: Some(child),
            pid,
        }
    }

    /// Returns the process ID.
    #[inline]
    fn pid(&self) -> u32 {
        self.pid
    }
}

impl Drop for ProcessGuard {
    fn drop(&mut self) {
        if let Some(mut child) = self.child.take()
            && let Err(e) = child.start_kill()
        {
            debug!(pid = self.pid, error = %e, "Failed to send kill signal in Drop");
        }
    }
}

// ============================================================================
// Types
// ============================================================================

/// Internal shared state for a window.
pub(crate) struct WindowInner {
    /// Unique identifier for this window.
    pub uuid: Uuid,
    /// Session ID.
    pub session_id: SessionId,
    /// Protected process handle.
    process: Mutex<ProcessGuard>,
    /// Connection pool (shared with Driver and other Windows).
    pub pool: Arc<ConnectionPool>,
    /// Profile directory.
    #[allow(dead_code)]
    profile: Profile,
    /// All tabs in this window.
    tabs: Mutex<FxHashMap<TabId, Tab>>,
    /// The initial tab created when Firefox opens.
    pub initial_tab_id: TabId,
    /// Mapping from InterceptId to handler key for targeted removal.
    pub intercept_handlers: Mutex<FxHashMap<InterceptId, String>>,
}

// ============================================================================
// Window
// ============================================================================

/// A handle to a Firefox browser window.
///
/// The window owns a Firefox process and profile, and holds a reference
/// to the shared ConnectionPool for WebSocket communication.
/// When dropped, the process is automatically killed.
///
/// # Example
///
/// ```no_run
/// # use firefox_webdriver::Driver;
/// # async fn example() -> firefox_webdriver::Result<()> {
/// # let driver = Driver::builder().binary("/usr/bin/firefox").extension("./ext").build().await?;
/// let window = driver.window().headless().spawn().await?;
///
/// // Get the initial tab
/// let tab = window.tab();
///
/// // Create a new tab
/// let new_tab = window.new_tab().await?;
///
/// // Close the window
/// window.close().await?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct Window {
    /// Shared inner state.
    pub(crate) inner: Arc<WindowInner>,
}

// ============================================================================
// Window - Display
// ============================================================================

impl fmt::Debug for Window {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Window")
            .field("uuid", &self.inner.uuid)
            .field("session_id", &self.inner.session_id)
            .field("port", &self.inner.pool.port())
            .finish_non_exhaustive()
    }
}

// ============================================================================
// Window - Constructor
// ============================================================================

impl Window {
    /// Creates a new window handle.
    pub(crate) fn new(
        pool: Arc<ConnectionPool>,
        process: Child,
        profile: Profile,
        session_id: SessionId,
        initial_tab_id: TabId,
    ) -> Self {
        let uuid = Uuid::new_v4();
        let initial_tab = Tab::new(initial_tab_id, FrameId::main(), session_id, None);
        let mut tabs = FxHashMap::default();
        tabs.insert(initial_tab_id, initial_tab);

        debug!(
            uuid = %uuid,
            session_id = %session_id,
            tab_id = %initial_tab_id,
            port = pool.port(),
            "Window created"
        );

        Self {
            inner: Arc::new(WindowInner {
                uuid,
                session_id,
                process: Mutex::new(ProcessGuard::new(process)),
                pool,
                profile,
                tabs: Mutex::new(tabs),
                initial_tab_id,
                intercept_handlers: Mutex::new(FxHashMap::default()),
            }),
        }
    }
}

// ============================================================================
// Window - Accessors
// ============================================================================

impl Window {
    /// Returns the session ID.
    #[inline]
    #[must_use]
    pub fn session_id(&self) -> SessionId {
        self.inner.session_id
    }

    /// Returns the Rust-side unique UUID.
    #[inline]
    #[must_use]
    pub fn uuid(&self) -> &Uuid {
        &self.inner.uuid
    }

    /// Returns the WebSocket port (shared across all windows).
    #[inline]
    #[must_use]
    pub fn port(&self) -> u16 {
        self.inner.pool.port()
    }

    /// Returns the Firefox process ID.
    #[inline]
    #[must_use]
    pub fn pid(&self) -> u32 {
        self.inner.process.lock().pid()
    }
}

// ============================================================================
// Window - Lifecycle
// ============================================================================

impl Window {
    /// Closes the window and kills the Firefox process.
    ///
    /// # Errors
    ///
    /// Returns an error if the process cannot be killed.
    pub async fn close(&self) -> Result<()> {
        debug!(uuid = %self.inner.uuid, "Closing window");

        // Remove from pool first
        self.inner.pool.remove(self.inner.session_id);

        // Take the child process out of the guard inside a sync block,
        // so we don't hold the parking_lot::Mutex across an .await point.
        let child = {
            let mut guard = self.inner.process.lock();
            guard.child.take()
        };

        // Now await outside the lock
        if let Some(mut child) = child {
            let pid = child.id().unwrap_or(0);
            debug!(pid, "Killing Firefox process");
            if let Err(e) = child.kill().await {
                debug!(pid, error = %e, "Failed to kill process");
            }
            if let Err(e) = child.wait().await {
                debug!(pid, error = %e, "Failed to wait for process");
            }
            info!(pid, "Process terminated");
        }

        info!(uuid = %self.inner.uuid, "Window closed");
        Ok(())
    }
}

// ============================================================================
// Window - Tab Management
// ============================================================================

impl Window {
    /// Returns the initial tab for this window.
    #[must_use]
    pub fn tab(&self) -> Tab {
        Tab::new(
            self.inner.initial_tab_id,
            FrameId::main(),
            self.inner.session_id,
            Some(self.clone()),
        )
    }

    /// Creates a new tab in this window.
    ///
    /// # Errors
    ///
    /// Returns an error if tab creation fails.
    pub async fn new_tab(&self) -> Result<Tab> {
        let command = Command::BrowsingContext(BrowsingContextCommand::NewTab);
        let response = self.send_command(command).await?;

        let tab_id_u32 = response
            .result
            .as_ref()
            .and_then(|v| v.get("tabId"))
            .and_then(|v| v.as_u64())
            .ok_or_else(|| Error::protocol("Expected tabId in NewTab response"))?;

        let new_tab_id = TabId::new(tab_id_u32 as u32)
            .ok_or_else(|| Error::protocol("Invalid tabId in NewTab response"))?;

        let tab = Tab::new(
            new_tab_id,
            FrameId::main(),
            self.inner.session_id,
            Some(self.clone()),
        );

        self.inner.tabs.lock().insert(new_tab_id, tab.clone());
        debug!(session_id = %self.inner.session_id, tab_id = %new_tab_id, "New tab created");
        Ok(tab)
    }

    /// Returns the number of tabs in this window.
    #[inline]
    #[must_use]
    pub fn tab_count(&self) -> usize {
        self.inner.tabs.lock().len()
    }

    /// Steals logs from extension (returns and clears).
    ///
    /// Useful for debugging extension issues.
    pub async fn steal_logs(&self) -> Result<Vec<Value>> {
        let command = Command::Session(SessionCommand::StealLogs);
        let response = self.send_command(command).await?;
        let logs = response
            .result
            .as_ref()
            .and_then(|v| v.get("logs"))
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();
        Ok(logs)
    }
}

// ============================================================================
// Window - Proxy
// ============================================================================

impl Window {
    /// Sets a proxy for all tabs in this window.
    ///
    /// Window-level proxy applies to all tabs unless overridden by tab-level proxy.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use firefox_webdriver::ProxyConfig;
    ///
    /// // HTTP proxy for all tabs
    /// window.set_proxy(ProxyConfig::http("proxy.example.com", 8080)).await?;
    ///
    /// // SOCKS5 proxy with auth
    /// window.set_proxy(
    ///     ProxyConfig::socks5("proxy.example.com", 1080)
    ///         .with_credentials("user", "pass")
    ///         .with_proxy_dns(true)
    /// ).await?;
    /// ```
    pub async fn set_proxy(&self, config: ProxyConfig) -> Result<()> {
        debug!(
            session_id = %self.inner.session_id,
            proxy_type = %config.proxy_type.as_str(),
            host = %config.host,
            port = config.port,
            "Setting window proxy"
        );

        let command = Command::Proxy(ProxyCommand::SetWindowProxy {
            proxy_type: config.proxy_type.as_str().to_string(),
            host: config.host,
            port: config.port,
            username: config.username,
            password: config.password,
            proxy_dns: config.proxy_dns,
        });

        self.send_command(command).await?;
        Ok(())
    }

    /// Clears the proxy for this window.
    ///
    /// After clearing, all tabs use direct connection (unless they have tab-level proxy).
    pub async fn clear_proxy(&self) -> Result<()> {
        debug!(session_id = %self.inner.session_id, "Clearing window proxy");
        let command = Command::Proxy(ProxyCommand::ClearWindowProxy);
        self.send_command(command).await?;
        Ok(())
    }
}

// ============================================================================
// Window - Internal
// ============================================================================

impl Window {
    /// Sends a command via the connection pool and waits for the response.
    pub(crate) async fn send_command(&self, command: Command) -> Result<Response> {
        let request = Request::new(self.inner.initial_tab_id, FrameId::main(), command);
        self.inner.pool.send(self.inner.session_id, request).await
    }
}

// ============================================================================
// WindowBuilder
// ============================================================================

/// Builder for spawning browser windows.
///
/// # Example
///
/// ```no_run
/// # use firefox_webdriver::Driver;
/// # async fn example() -> firefox_webdriver::Result<()> {
/// # let driver = Driver::builder().binary("/usr/bin/firefox").extension("./ext").build().await?;
/// let window = driver.window()
///     .headless()
///     .window_size(1920, 1080)
///     .profile("./my_profile")
///     .spawn()
///     .await?;
/// # Ok(())
/// # }
/// ```
pub struct WindowBuilder<'a> {
    /// Reference to the driver.
    driver: &'a Driver,
    /// Firefox launch options.
    options: FirefoxOptions,
    /// Optional custom profile path.
    profile: Option<PathBuf>,
}

// ============================================================================
// WindowBuilder - Implementation
// ============================================================================

impl<'a> WindowBuilder<'a> {
    /// Creates a new window builder.
    pub(crate) fn new(driver: &'a Driver) -> Self {
        Self {
            driver,
            options: FirefoxOptions::new(),
            profile: None,
        }
    }

    /// Enables headless mode.
    ///
    /// Firefox runs without a visible window.
    #[must_use]
    pub fn headless(mut self) -> Self {
        self.options = self.options.with_headless();
        self
    }

    /// Sets the window size.
    ///
    /// # Arguments
    ///
    /// * `width` - Window width in pixels
    /// * `height` - Window height in pixels
    #[must_use]
    pub fn window_size(mut self, width: u32, height: u32) -> Self {
        self.options = self.options.with_window_size(width, height);
        self
    }

    /// Uses a custom profile directory.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to profile directory
    #[must_use]
    pub fn profile(mut self, path: impl Into<PathBuf>) -> Self {
        self.profile = Some(path.into());
        self
    }

    /// Spawns the window.
    ///
    /// # Errors
    ///
    /// Returns an error if window creation fails.
    pub async fn spawn(self) -> Result<Window> {
        self.driver.spawn_window(self.options, self.profile).await
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::Window;

    #[test]
    fn test_window_is_clone() {
        fn assert_clone<T: Clone>() {}
        assert_clone::<Window>();
    }

    #[test]
    fn test_window_is_debug() {
        fn assert_debug<T: std::fmt::Debug>() {}
        assert_debug::<Window>();
    }
}