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 orientation = if viewport.is_landscape {
31 ScreenOrientation::new(ScreenOrientationType::LandscapePrimary, 90)
32 } else {
33 ScreenOrientation::new(ScreenOrientationType::PortraitPrimary, 0)
34 };
35
36 let set_device = SetDeviceMetricsOverrideParams::builder()
37 .mobile(viewport.emulating_mobile)
38 .width(viewport.width)
39 .height(viewport.height)
40 .device_scale_factor(viewport.device_scale_factor.unwrap_or(1.))
41 .screen_orientation(orientation)
42 .build()
43 .unwrap();
44
45 let set_touch = SetTouchEmulationEnabledParams::new(true);
46
47 let mut chains = Vec::with_capacity(2);
48
49 if let Ok(set_device_value) = serde_json::to_value(&set_device) {
50 chains.push((set_device.identifier(), set_device_value));
51 }
52
53 if let Ok(set_touch_value) = serde_json::to_value(&set_touch) {
54 chains.push((set_touch.identifier(), set_touch_value));
55 }
56
57 let chain = CommandChain::new(chains, self.request_timeout);
58
59 self.needs_reload = self.emulating_mobile != viewport.emulating_mobile
60 || self.has_touch != viewport.has_touch;
61 chain
62 }
63}