vendor/github.com/go-rod/rod/lib/devices/device.go

101 lines · 2299 bytes

  1// Package devices ...
  2package devices
  3
  4import (
  5	"github.com/go-rod/rod/lib/proto"
  6	"github.com/ysmood/gson"
  7)
  8
  9// Device represents a emulated device.
 10type Device struct {
 11	Capabilities   []string
 12	UserAgent      string
 13	AcceptLanguage string
 14	Screen         Screen
 15	Title          string
 16
 17	landscape bool
 18	clear     bool
 19}
 20
 21// Screen represents the screen of a device.
 22type Screen struct {
 23	DevicePixelRatio float64
 24	Horizontal       ScreenSize
 25	Vertical         ScreenSize
 26}
 27
 28// ScreenSize represents the size of the screen.
 29type ScreenSize struct {
 30	Width  int
 31	Height int
 32}
 33
 34// Landscape clones the device and set it to landscape mode.
 35func (device Device) Landscape() Device {
 36	d := device
 37	d.landscape = true
 38	return d
 39}
 40
 41// MetricsEmulation config.
 42func (device Device) MetricsEmulation() *proto.EmulationSetDeviceMetricsOverride {
 43	if device.IsClear() {
 44		return nil
 45	}
 46
 47	var screen ScreenSize
 48	var orientation *proto.EmulationScreenOrientation
 49	if device.landscape {
 50		screen = device.Screen.Horizontal
 51		orientation = &proto.EmulationScreenOrientation{
 52			Angle: 90,
 53			Type:  proto.EmulationScreenOrientationTypeLandscapePrimary,
 54		}
 55	} else {
 56		screen = device.Screen.Vertical
 57		orientation = &proto.EmulationScreenOrientation{
 58			Angle: 0,
 59			Type:  proto.EmulationScreenOrientationTypePortraitPrimary,
 60		}
 61	}
 62
 63	return &proto.EmulationSetDeviceMetricsOverride{
 64		Width:             screen.Width,
 65		Height:            screen.Height,
 66		DeviceScaleFactor: device.Screen.DevicePixelRatio,
 67		ScreenOrientation: orientation,
 68		Mobile:            has(device.Capabilities, "mobile"),
 69	}
 70}
 71
 72// TouchEmulation config.
 73func (device Device) TouchEmulation() *proto.EmulationSetTouchEmulationEnabled {
 74	if device.IsClear() {
 75		return &proto.EmulationSetTouchEmulationEnabled{
 76			Enabled: false,
 77		}
 78	}
 79
 80	return &proto.EmulationSetTouchEmulationEnabled{
 81		Enabled:        has(device.Capabilities, "touch"),
 82		MaxTouchPoints: gson.Int(5),
 83	}
 84}
 85
 86// UserAgentEmulation config.
 87func (device Device) UserAgentEmulation() *proto.NetworkSetUserAgentOverride {
 88	if device.IsClear() {
 89		return nil
 90	}
 91
 92	return &proto.NetworkSetUserAgentOverride{
 93		UserAgent:      device.UserAgent,
 94		AcceptLanguage: device.AcceptLanguage,
 95	}
 96}
 97
 98// IsClear type.
 99func (device Device) IsClear() bool {
100	return device.clear
101}