chaser_oxide/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 chain = CommandChain::new(
48 vec![
49 (
50 set_device.identifier(),
51 serde_json::to_value(set_device).unwrap(),
52 ),
53 (
54 set_touch.identifier(),
55 serde_json::to_value(set_touch).unwrap(),
56 ),
57 ],
58 self.request_timeout,
59 );
60
61 self.needs_reload = self.emulating_mobile != viewport.emulating_mobile
62 || self.has_touch != viewport.has_touch;
63 chain
64 }
65}