chromiumoxide/handler/
emulation.rs1use chromiumoxide_cdp::cdp::browser_protocol::emulation::{
2 ScreenOrientation, ScreenOrientationType, SetDeviceMetricsOverrideParams,
3 SetTouchEmulationEnabledParams,
4};
5use chromiumoxide_types::Method;
6
7use crate::cmd::CommandChain;
8use crate::handler::viewport::Viewport;
9use std::time::Duration;
10
11#[derive(Debug)]
12pub struct EmulationManager {
13 pub emulating_mobile: bool,
14 pub has_touch: bool,
15 pub needs_reload: bool,
16 pub request_timeout: Duration,
17}
18
19impl EmulationManager {
20 pub fn new(request_timeout: Duration) -> Self {
21 Self {
22 emulating_mobile: false,
23 has_touch: false,
24 needs_reload: false,
25 request_timeout,
26 }
27 }
28
29 pub fn init_commands(&mut self, viewport: &Viewport) -> CommandChain {
30 let mut chains = Vec::with_capacity(2);
31 let set_touch = SetTouchEmulationEnabledParams::new(viewport.emulating_mobile);
32 let orientation = if viewport.is_landscape {
33 ScreenOrientation::new(ScreenOrientationType::LandscapePrimary, 90)
34 } else {
35 ScreenOrientation::new(ScreenOrientationType::PortraitPrimary, 0)
36 };
37
38 if let Ok(set_device) = SetDeviceMetricsOverrideParams::builder()
39 .mobile(viewport.emulating_mobile)
40 .width(viewport.width)
41 .height(viewport.height)
42 .device_scale_factor(viewport.device_scale_factor.unwrap_or(1.))
43 .screen_orientation(orientation)
44 .build()
45 {
46 if let Ok(set_device_value) = serde_json::to_value(&set_device) {
47 chains.push((set_device.identifier(), set_device_value));
48 }
49 }
50
51 if let Ok(set_touch_value) = serde_json::to_value(&set_touch) {
52 chains.push((set_touch.identifier(), set_touch_value));
53 }
54
55 let chain = CommandChain::new(chains, self.request_timeout);
56
57 self.needs_reload = self.emulating_mobile != viewport.emulating_mobile
58 || self.has_touch != viewport.has_touch;
59 chain
60 }
61}