import{ObjectWrapper,Settings,Revealer,UIString,Throttler}from'../common/common.js';import{DockController}from'../components/components.js';import{userMetrics,UserMetrics,InspectorFrontendHost,Platform}from'../host/host.js';import{Geometry,Toolbar,UIUtils,Utils,ContextMenu,Widget,ZoomManager,Tooltip,ResizerWidget,RootView,SplitWidget,ListWidget,ARIAUtils,ViewManager}from'../ui/ui.js';import{InspectorBackend}from'../protocol_client/protocol_client.js';import{NetworkManager,SDKModel,EmulationModel,ResourceTreeModel,ScreenCaptureModel,CSSModel,OverlayModel,DOMModel}from'../sdk/sdk.js';import{StringUtilities}from'../platform/platform.js';import{ThrottlingManager}from'../mobile_throttling/mobile_throttling.js';import{CSSWorkspaceBinding}from'../bindings/bindings.js';import'../workspace/workspace.js';class EmulatedDevice{constructor(){this.title='';this.type=Type.Unknown;this.vertical={width:0,height:0,outlineInsets:null,outlineImage:null,hinge:null};this.horizontal={width:0,height:0,outlineInsets:null,outlineImage:null,hinge:null};this.deviceScaleFactor=1;this.capabilities=[Capability.Touch,Capability.Mobile];this.userAgent='';this.userAgentMetadata=null;this.modes=[];this.isDualScreen=false;this.verticalSpanned={width:0,height:0,outlineInsets:null,outlineImage:null,hinge:null};this.horizontalSpanned={width:0,height:0,outlineInsets:null,outlineImage:null,hinge:null};this._show=_Show.Default;this._showByDefault=true;this._extension=null;}
static fromJSONV1(json){try{function parseValue(object,key,type,defaultValue){if(typeof object!=='object'||object===null||!object.hasOwnProperty(key)){if(typeof defaultValue!=='undefined'){return defaultValue;}
throw new Error('Emulated device is missing required property \''+key+'\'');}
const value=object[key];if(typeof value!==type||value===null){throw new Error('Emulated device property \''+key+'\' has wrong type \''+typeof value+'\'');}
return value;}
function parseIntValue(object,key){const value=(parseValue(object,key,'number'));if(value!==Math.abs(value)){throw new Error('Emulated device value \''+key+'\' must be integer');}
return value;}
function parseInsets(json){return new Geometry.Insets(parseIntValue(json,'left'),parseIntValue(json,'top'),parseIntValue(json,'right'),parseIntValue(json,'bottom'));}
function parseRGBA(json){const result={};result.r=parseIntValue(json,'r');if(result.r<0||result.r>255){throw new Error('color has wrong r value: '+result.r);}
result.g=parseIntValue(json,'g');if(result.g<0||result.g>255){throw new Error('color has wrong g value: '+result.g);}
result.b=parseIntValue(json,'b');if(result.b<0||result.b>255){throw new Error('color has wrong b value: '+result.b);}
result.a=(parseValue(json,'a','number'));if(result.a<0||result.a>1){throw new Error('color has wrong a value: '+result.a);}
return(result);}
function parseHinge(json){const result={};result.width=parseIntValue(json,'width');if(result.width<0||result.width>MaxDeviceSize){throw new Error('Emulated device has wrong hinge width: '+result.width);}
result.height=parseIntValue(json,'height');if(result.height<0||result.height>MaxDeviceSize){throw new Error('Emulated device has wrong hinge height: '+result.height);}
result.x=parseIntValue(json,'x');if(result.x<0||result.x>MaxDeviceSize){throw new Error('Emulated device has wrong x offset: '+result.height);}
result.y=parseIntValue(json,'y');if(result.x<0||result.x>MaxDeviceSize){throw new Error('Emulated device has wrong y offset: '+result.height);}
if(json['contentColor']){result.contentColor=parseRGBA(json['contentColor']);}
if(json['outlineColor']){result.outlineColor=parseRGBA(json['outlineColor']);}
return(result);}
function parseOrientation(json){const result={};result.width=parseIntValue(json,'width');if(result.width<0||result.width>MaxDeviceSize||result.width<MinDeviceSize){throw new Error('Emulated device has wrong width: '+result.width);}
result.height=parseIntValue(json,'height');if(result.height<0||result.height>MaxDeviceSize||result.height<MinDeviceSize){throw new Error('Emulated device has wrong height: '+result.height);}
const outlineInsets=parseValue(json['outline'],'insets','object',null);if(outlineInsets){result.outlineInsets=parseInsets(outlineInsets);if(result.outlineInsets.left<0||result.outlineInsets.top<0){throw new Error('Emulated device has wrong outline insets');}
result.outlineImage=(parseValue(json['outline'],'image','string'));}
if(json['hinge']){result.hinge=parseHinge(parseValue(json,'hinge','object',undefined));}
return(result);}
const result=new EmulatedDevice();result.title=(parseValue(json,'title','string'));result.type=(parseValue(json,'type','string'));const rawUserAgent=(parseValue(json,'user-agent','string'));result.userAgent=NetworkManager.MultitargetNetworkManager.patchUserAgentWithChromeVersion(rawUserAgent);const templateUserAgentMetadata=parseValue(json,'user-agent-metadata','object',null);if(templateUserAgentMetadata){if(templateUserAgentMetadata.brands===undefined){templateUserAgentMetadata.brands=NetworkManager.MultitargetNetworkManager.getChromeBrands();}
if(templateUserAgentMetadata.fullVersion===undefined){templateUserAgentMetadata.fullVersion=NetworkManager.MultitargetNetworkManager.getChromeVersion();}}
result.userAgentMetadata=(templateUserAgentMetadata);const capabilities=parseValue(json,'capabilities','object',[]);if(!Array.isArray(capabilities)){throw new Error('Emulated device capabilities must be an array');}
result.capabilities=[];for(let i=0;i<capabilities.length;++i){if(typeof capabilities[i]!=='string'){throw new Error('Emulated device capability must be a string');}
result.capabilities.push(capabilities[i]);}
result.deviceScaleFactor=(parseValue(json['screen'],'device-pixel-ratio','number'));if(result.deviceScaleFactor<0||result.deviceScaleFactor>100){throw new Error('Emulated device has wrong deviceScaleFactor: '+result.deviceScaleFactor);}
result.vertical=parseOrientation(parseValue(json['screen'],'vertical','object'));result.horizontal=parseOrientation(parseValue(json['screen'],'horizontal','object'));result.isDualScreen=(parseValue(json,'dual-screen','boolean',false));if(result.isDualScreen){result.verticalSpanned=parseOrientation(parseValue(json['screen'],'vertical-spanned','object',null));result.horizontalSpanned=parseOrientation(parseValue(json['screen'],'horizontal-spanned','object',null));}
if(result.isDualScreen&&(!result.verticalSpanned||!result.horizontalSpanned)){throw new Error('Emulated device \''+result.title+'\'has dual screen without spanned orientations');}
const modes=parseValue(json,'modes','object',[]);if(!Array.isArray(modes)){throw new Error('Emulated device modes must be an array');}
result.modes=[];for(let i=0;i<modes.length;++i){const mode={};mode.title=(parseValue(modes[i],'title','string'));mode.orientation=(parseValue(modes[i],'orientation','string'));if(mode.orientation!==Vertical&&mode.orientation!==Horizontal&&mode.orientation!==VerticalSpanned&&mode.orientation!==HorizontalSpanned){throw new Error('Emulated device mode has wrong orientation \''+mode.orientation+'\'');}
const orientation=result.orientationByName(mode.orientation);mode.insets=parseInsets(parseValue(modes[i],'insets','object'));if(mode.insets.top<0||mode.insets.left<0||mode.insets.right<0||mode.insets.bottom<0||mode.insets.top+mode.insets.bottom>orientation.height||mode.insets.left+mode.insets.right>orientation.width){throw new Error('Emulated device mode \''+mode.title+'\'has wrong mode insets');}
mode.image=(parseValue(modes[i],'image','string',null));result.modes.push(mode);}
result._showByDefault=(parseValue(json,'show-by-default','boolean',undefined));result._show=(parseValue(json,'show','string',_Show.Default));return result;}catch(e){return null;}}
static deviceComparator(device1,device2){const order1=(device1._extension&&device1._extension.descriptor()['order'])||-1;const order2=(device2._extension&&device2._extension.descriptor()['order'])||-1;if(order1>order2){return 1;}
if(order2>order1){return-1;}
return device1.title<device2.title?-1:(device1.title>device2.title?1:0);}
extension(){return this._extension;}
setExtension(extension){this._extension=extension;}
modesForOrientation(orientation){const result=[];for(let index=0;index<this.modes.length;index++){if(this.modes[index].orientation===orientation){result.push(this.modes[index]);}}
return result;}
getSpanPartner(mode){switch(mode.orientation){case Vertical:return this.modesForOrientation(VerticalSpanned)[0];case Horizontal:return this.modesForOrientation(HorizontalSpanned)[0];case VerticalSpanned:return this.modesForOrientation(Vertical)[0];default:return this.modesForOrientation(Horizontal)[0];}}
getRotationPartner(mode){switch(mode.orientation){case HorizontalSpanned:return this.modesForOrientation(VerticalSpanned)[0];case VerticalSpanned:return this.modesForOrientation(HorizontalSpanned)[0];case Horizontal:return this.modesForOrientation(Vertical)[0];default:return this.modesForOrientation(Horizontal)[0];}}
_toJSON(){const json={};json['title']=this.title;json['type']=this.type;json['user-agent']=this.userAgent;json['capabilities']=this.capabilities;json['screen']={};json['screen']['device-pixel-ratio']=this.deviceScaleFactor;json['screen']['vertical']=this._orientationToJSON(this.vertical);json['screen']['horizontal']=this._orientationToJSON(this.horizontal);if(this.isDualScreen){json['screen']['vertical-spanned']=this._orientationToJSON(this.verticalSpanned);json['screen']['horizontal-spanned']=this._orientationToJSON(this.horizontalSpanned);}
json['modes']=[];for(let i=0;i<this.modes.length;++i){const mode={};mode['title']=this.modes[i].title;mode['orientation']=this.modes[i].orientation;mode['insets']={};mode['insets']['left']=this.modes[i].insets.left;mode['insets']['top']=this.modes[i].insets.top;mode['insets']['right']=this.modes[i].insets.right;mode['insets']['bottom']=this.modes[i].insets.bottom;if(this.modes[i].image){mode['image']=this.modes[i].image;}
json['modes'].push(mode);}
json['show-by-default']=this._showByDefault;json['dual-screen']=this.isDualScreen;json['show']=this._show;return json;}
_orientationToJSON(orientation){const json={};json['width']=orientation.width;json['height']=orientation.height;if(orientation.outlineInsets){json['outline']={};json['outline']['insets']={};json['outline']['insets']['left']=orientation.outlineInsets.left;json['outline']['insets']['top']=orientation.outlineInsets.top;json['outline']['insets']['right']=orientation.outlineInsets.right;json['outline']['insets']['bottom']=orientation.outlineInsets.bottom;json['outline']['image']=orientation.outlineImage;}
if(orientation.hinge){json['hinge']={};json['hinge']['width']=orientation.hinge.width;json['hinge']['height']=orientation.hinge.height;json['hinge']['x']=orientation.hinge.x;json['hinge']['y']=orientation.hinge.y;if(orientation.hinge.contentColor){json['hinge']['contentColor']={};json['hinge']['contentColor']['r']=orientation.hinge.contentColor.r;json['hinge']['contentColor']['g']=orientation.hinge.contentColor.g;json['hinge']['contentColor']['b']=orientation.hinge.contentColor.b;json['hinge']['contentColor']['a']=orientation.hinge.contentColor.a;}
if(orientation.hinge.outlineColor){json['hinge']['outlineColor']={};json['hinge']['outlineColor']['r']=orientation.hinge.outlineColor.r;json['hinge']['outlineColor']['g']=orientation.hinge.outlineColor.g;json['hinge']['outlineColor']['b']=orientation.hinge.outlineColor.b;json['hinge']['outlineColor']['a']=orientation.hinge.outlineColor.a;}}
return json;}
modeImage(mode){if(!mode.image){return'';}
if(!this._extension){return mode.image;}
return this._extension.module().substituteURL(mode.image);}
outlineImage(mode){const orientation=this.orientationByName(mode.orientation);if(!orientation.outlineImage){return'';}
if(!this._extension){return orientation.outlineImage;}
return this._extension.module().substituteURL(orientation.outlineImage);}
orientationByName(name){switch(name){case VerticalSpanned:return this.verticalSpanned;case HorizontalSpanned:return this.horizontalSpanned;case Vertical:return this.vertical;default:return this.horizontal;}}
show(){if(this._show===_Show.Default){return this._showByDefault;}
return this._show===_Show.Always;}
setShow(show){this._show=show?_Show.Always:_Show.Never;}
copyShowFrom(other){this._show=other._show;}
touch(){return this.capabilities.indexOf(Capability.Touch)!==-1;}
mobile(){return this.capabilities.indexOf(Capability.Mobile)!==-1;}}
const Horizontal='horizontal';const Vertical='vertical';const HorizontalSpanned='horizontal-spanned';const VerticalSpanned='vertical-spanned';const Type={Phone:'phone',Tablet:'tablet',Notebook:'notebook',Desktop:'desktop',Unknown:'unknown'};const Capability={Touch:'touch',Mobile:'mobile'};const _Show={Always:'Always',Default:'Default',Never:'Never'};let _instance;class EmulatedDevicesList extends ObjectWrapper.ObjectWrapper{constructor(){super();this._standardSetting=Settings.Settings.instance().createSetting('standardEmulatedDeviceList',[]);this._standard=new Set();this._listFromJSONV1(this._standardSetting.get(),this._standard);this._updateStandardDevices();this._customSetting=Settings.Settings.instance().createSetting('customEmulatedDeviceList',[]);this._custom=new Set();if(!this._listFromJSONV1(this._customSetting.get(),this._custom)){this.saveCustomDevices();}}
static instance(){if(!_instance){_instance=new EmulatedDevicesList();}
return _instance;}
_updateStandardDevices(){const devices=new Set();const extensions=self.runtime.extensions('emulated-device');for(const extension of extensions){const device=EmulatedDevice.fromJSONV1(extension.descriptor()['device']);device.setExtension(extension);devices.add(device);}
this._copyShowValues(this._standard,devices);this._standard=devices;this.saveStandardDevices();}
_listFromJSONV1(jsonArray,result){if(!Array.isArray(jsonArray)){return false;}
let success=true;for(let i=0;i<jsonArray.length;++i){const device=EmulatedDevice.fromJSONV1(jsonArray[i]);if(device){result.add(device);if(!device.modes.length){device.modes.push({title:'',orientation:Horizontal,insets:new Geometry.Insets(0,0,0,0),image:null});device.modes.push({title:'',orientation:Vertical,insets:new Geometry.Insets(0,0,0,0),image:null});}}else{success=false;}}
return success;}
standard(){return[...this._standard];}
custom(){return[...this._custom];}
revealCustomSetting(){Revealer.reveal(this._customSetting);}
addCustomDevice(device){this._custom.add(device);this.saveCustomDevices();}
removeCustomDevice(device){this._custom.delete(device);this.saveCustomDevices();}
saveCustomDevices(){const json=[];this._custom.forEach(device=>json.push(device._toJSON()));this._customSetting.set(json);this.dispatchEventToListeners(Events.CustomDevicesUpdated);}
saveStandardDevices(){const json=[];this._standard.forEach(device=>json.push(device._toJSON()));this._standardSetting.set(json);this.dispatchEventToListeners(Events.StandardDevicesUpdated);}
_copyShowValues(from,to){const fromDeviceById=new Map();for(const device of from){fromDeviceById.set(device.title,device);}
for(const toDevice of to){const fromDevice=fromDeviceById.get(toDevice.title);if(fromDevice){toDevice.copyShowFrom(fromDevice);}}}}
const Events={CustomDevicesUpdated:Symbol('CustomDevicesUpdated'),StandardDevicesUpdated:Symbol('StandardDevicesUpdated')};let Mode;let Orientation;var EmulatedDevices=Object.freeze({__proto__:null,EmulatedDevice:EmulatedDevice,Horizontal:Horizontal,Vertical:Vertical,HorizontalSpanned:HorizontalSpanned,VerticalSpanned:VerticalSpanned,Type:Type,Capability:Capability,_Show:_Show,EmulatedDevicesList:EmulatedDevicesList,Events:Events,Mode:Mode,Orientation:Orientation});class DeviceModeModel extends ObjectWrapper.ObjectWrapper{constructor(){super();this._screenRect=new Geometry.Rect(0,0,1,1);this._visiblePageRect=new Geometry.Rect(0,0,1,1);this._availableSize=new Geometry.Size(1,1);this._preferredSize=new Geometry.Size(1,1);this._initialized=false;this._appliedDeviceSize=new Geometry.Size(1,1);this._appliedDeviceScaleFactor=window.devicePixelRatio;this._appliedUserAgentType=UA.Desktop;this._experimentDualScreenSupport=Root.Runtime.experiments.isEnabled('dualScreenSupport');this._scaleSetting=Settings.Settings.instance().createSetting('emulation.deviceScale',1);if(!this._scaleSetting.get()){this._scaleSetting.set(1);}
this._scaleSetting.addChangeListener(this._scaleSettingChanged,this);this._widthSetting=Settings.Settings.instance().createSetting('emulation.deviceWidth',400);if(this._widthSetting.get()<MinDeviceSize){this._widthSetting.set(MinDeviceSize);}
if(this._widthSetting.get()>MaxDeviceSize){this._widthSetting.set(MaxDeviceSize);}
this._widthSetting.addChangeListener(this._widthSettingChanged,this);this._heightSetting=Settings.Settings.instance().createSetting('emulation.deviceHeight',0);if(this._heightSetting.get()&&this._heightSetting.get()<MinDeviceSize){this._heightSetting.set(MinDeviceSize);}
if(this._heightSetting.get()>MaxDeviceSize){this._heightSetting.set(MaxDeviceSize);}
this._heightSetting.addChangeListener(this._heightSettingChanged,this);this._uaSetting=Settings.Settings.instance().createSetting('emulation.deviceUA',UA.Mobile);this._uaSetting.addChangeListener(this._uaSettingChanged,this);this._deviceScaleFactorSetting=Settings.Settings.instance().createSetting('emulation.deviceScaleFactor',0);this._deviceScaleFactorSetting.addChangeListener(this._deviceScaleFactorSettingChanged,this);this._deviceOutlineSetting=Settings.Settings.instance().moduleSetting('emulation.showDeviceOutline');this._deviceOutlineSetting.addChangeListener(this._deviceOutlineSettingChanged,this);this._toolbarControlsEnabledSetting=Settings.Settings.instance().createSetting('emulation.toolbarControlsEnabled',true,Settings.SettingStorageType.Session);this._type=Type$1.None;this._device=null;this._mode=null;this._fitScale=1;this._touchEnabled=false;this._touchMobile=false;this._emulationModel=null;this._onModelAvailable=null;SDKModel.TargetManager.instance().observeModels(EmulationModel.EmulationModel,this);}
static widthValidator(value){let valid=false;let errorMessage;if(!/^[\d]+$/.test(value)){errorMessage=ls`Width must be a number.`;}else if(value>MaxDeviceSize){errorMessage=ls`Width must be less than or equal to ${MaxDeviceSize}.`;}else if(value<MinDeviceSize){errorMessage=ls`Width must be greater than or equal to ${MinDeviceSize}.`;}else{valid=true;}
return{valid,errorMessage};}
static heightValidator(value){let valid=false;let errorMessage;if(!/^[\d]+$/.test(value)){errorMessage=ls`Height must be a number.`;}else if(value>MaxDeviceSize){errorMessage=ls`Height must be less than or equal to ${MaxDeviceSize}.`;}else if(value<MinDeviceSize){errorMessage=ls`Height must be greater than or equal to ${MinDeviceSize}.`;}else{valid=true;}
return{valid,errorMessage};}
static scaleValidator(value){let valid=false;let errorMessage;const parsedValue=Number(value.trim());if(!value){valid=true;}else if(Number.isNaN(parsedValue)){errorMessage=ls`Device pixel ratio must be a number or blank.`;}else if(value>MaxDeviceScaleFactor){errorMessage=ls`Device pixel ratio must be less than or equal to ${MaxDeviceScaleFactor}.`;}else if(value<MinDeviceScaleFactor){errorMessage=ls`Device pixel ratio must be greater than or equal to ${MinDeviceScaleFactor}.`;}else{valid=true;}
return{valid,errorMessage};}
setAvailableSize(availableSize,preferredSize){this._availableSize=availableSize;this._preferredSize=preferredSize;this._initialized=true;this._calculateAndEmulate(false);}
emulate(type,device,mode,scale){const resetPageScaleFactor=this._type!==type||this._device!==device||this._mode!==mode;this._type=type;if(type===Type$1.Device){console.assert(device&&mode,'Must pass device and mode for device emulation');this._mode=mode;this._device=device;if(this._initialized){const orientation=device.orientationByName(mode.orientation);this._scaleSetting.set(scale||this._calculateFitScale(orientation.width,orientation.height,this._currentOutline(),this._currentInsets()));}}else{this._device=null;this._mode=null;}
if(type!==Type$1.None){userMetrics.actionTaken(UserMetrics.Action.DeviceModeEnabled);}
this._calculateAndEmulate(resetPageScaleFactor);}
setWidth(width){const max=Math.min(MaxDeviceSize,this._preferredScaledWidth());width=Math.max(Math.min(width,max),1);this._widthSetting.set(width);}
setWidthAndScaleToFit(width){width=Math.max(Math.min(width,MaxDeviceSize),1);this._scaleSetting.set(this._calculateFitScale(width,this._heightSetting.get()));this._widthSetting.set(width);}
setHeight(height){const max=Math.min(MaxDeviceSize,this._preferredScaledHeight());height=Math.max(Math.min(height,max),0);if(height===this._preferredScaledHeight()){height=0;}
this._heightSetting.set(height);}
setHeightAndScaleToFit(height){height=Math.max(Math.min(height,MaxDeviceSize),0);this._scaleSetting.set(this._calculateFitScale(this._widthSetting.get(),height));this._heightSetting.set(height);}
setScale(scale){this._scaleSetting.set(scale);}
device(){return this._device;}
mode(){return this._mode;}
type(){return this._type;}
screenImage(){return(this._device&&this._mode)?this._device.modeImage(this._mode):'';}
outlineImage(){return(this._device&&this._mode&&this._deviceOutlineSetting.get())?this._device.outlineImage(this._mode):'';}
outlineRect(){return this._outlineRect;}
screenRect(){return this._screenRect;}
visiblePageRect(){return this._visiblePageRect;}
scale(){return this._scale;}
fitScale(){return this._fitScale;}
appliedDeviceSize(){return this._appliedDeviceSize;}
appliedDeviceScaleFactor(){return this._appliedDeviceScaleFactor;}
appliedUserAgentType(){return this._appliedUserAgentType;}
isFullHeight(){return!this._heightSetting.get();}
_isMobile(){switch(this._type){case Type$1.Device:return this._device.mobile();case Type$1.None:return false;case Type$1.Responsive:return this._uaSetting.get()===UA.Mobile||this._uaSetting.get()===UA.MobileNoTouch;}
return false;}
enabledSetting(){return Settings.Settings.instance().createSetting('emulation.showDeviceMode',false);}
scaleSetting(){return this._scaleSetting;}
uaSetting(){return this._uaSetting;}
deviceScaleFactorSetting(){return this._deviceScaleFactorSetting;}
deviceOutlineSetting(){return this._deviceOutlineSetting;}
toolbarControlsEnabledSetting(){return this._toolbarControlsEnabledSetting;}
reset(){this._deviceScaleFactorSetting.set(0);this._scaleSetting.set(1);this.setWidth(400);this.setHeight(0);this._uaSetting.set(UA.Mobile);}
modelAdded(emulationModel){if(!this._emulationModel&&emulationModel.supportsDeviceEmulation()){this._emulationModel=emulationModel;if(this._onModelAvailable){const callback=this._onModelAvailable;this._onModelAvailable=null;callback();}
const resourceTreeModel=emulationModel.target().model(ResourceTreeModel.ResourceTreeModel);if(resourceTreeModel){resourceTreeModel.addEventListener(ResourceTreeModel.Events.FrameResized,this._onFrameResized,this);}}else{emulationModel.emulateTouch(this._touchEnabled,this._touchMobile);}}
modelRemoved(emulationModel){if(this._emulationModel===emulationModel){this._emulationModel=null;}}
inspectedURL(){return this._emulationModel?this._emulationModel.target().inspectedURL():null;}
_onFrameResized(){const overlayModel=this._emulationModel?this._emulationModel.overlayModel():null;if(!overlayModel||!this._type){return;}
if(this._type===Type$1.Device){const orientation=this._device.orientationByName(this._mode.orientation);this._showHingeIfApplicable(overlayModel,orientation);}}
_scaleSettingChanged(){this._calculateAndEmulate(false);}
_widthSettingChanged(){this._calculateAndEmulate(false);}
_heightSettingChanged(){this._calculateAndEmulate(false);}
_uaSettingChanged(){this._calculateAndEmulate(true);}
_deviceScaleFactorSettingChanged(){this._calculateAndEmulate(false);}
_deviceOutlineSettingChanged(){this._calculateAndEmulate(false);}
_preferredScaledWidth(){return Math.floor(this._preferredSize.width/(this._scaleSetting.get()||1));}
_preferredScaledHeight(){return Math.floor(this._preferredSize.height/(this._scaleSetting.get()||1));}
_currentOutline(){let outline=new Geometry.Insets(0,0,0,0);if(this._type!==Type$1.Device){return outline;}
const orientation=this._device.orientationByName(this._mode.orientation);if(this._deviceOutlineSetting.get()){outline=orientation.outlineInsets||outline;}
return outline;}
_currentInsets(){if(this._type!==Type$1.Device){return new Geometry.Insets(0,0,0,0);}
return this._mode.insets;}
_calculateAndEmulate(resetPageScaleFactor){if(!this._emulationModel){this._onModelAvailable=this._calculateAndEmulate.bind(this,resetPageScaleFactor);}
const mobile=this._isMobile();const overlayModel=this._emulationModel?this._emulationModel.overlayModel():null;if(this._type===Type$1.Device){const orientation=this._device.orientationByName(this._mode.orientation);const outline=this._currentOutline();const insets=this._currentInsets();this._fitScale=this._calculateFitScale(orientation.width,orientation.height,outline,insets);if(mobile){this._appliedUserAgentType=this._device.touch()?UA.Mobile:UA.MobileNoTouch;}else{this._appliedUserAgentType=this._device.touch()?UA.DesktopTouch:UA.Desktop;}
if(overlayModel){this._showHingeIfApplicable(overlayModel,orientation);}
this._applyDeviceMetrics(new Geometry.Size(orientation.width,orientation.height),insets,outline,this._scaleSetting.get(),this._device.deviceScaleFactor,mobile,this._mode.orientation===Horizontal?Protocol.Emulation.ScreenOrientationType.LandscapePrimary:Protocol.Emulation.ScreenOrientationType.PortraitPrimary,resetPageScaleFactor);this._applyUserAgent(this._device.userAgent,this._device.userAgentMetadata);this._applyTouch(this._device.touch(),mobile);}else if(this._type===Type$1.None){this._fitScale=this._calculateFitScale(this._availableSize.width,this._availableSize.height);this._appliedUserAgentType=UA.Desktop;this._applyDeviceMetrics(this._availableSize,new Geometry.Insets(0,0,0,0),new Geometry.Insets(0,0,0,0),1,0,mobile,null,resetPageScaleFactor);this._applyUserAgent('',null);this._applyTouch(false,false);}else if(this._type===Type$1.Responsive){let screenWidth=this._widthSetting.get();if(!screenWidth||screenWidth>this._preferredScaledWidth()){screenWidth=this._preferredScaledWidth();}
let screenHeight=this._heightSetting.get();if(!screenHeight||screenHeight>this._preferredScaledHeight()){screenHeight=this._preferredScaledHeight();}
const defaultDeviceScaleFactor=mobile?defaultMobileScaleFactor:0;this._fitScale=this._calculateFitScale(this._widthSetting.get(),this._heightSetting.get());this._appliedUserAgentType=this._uaSetting.get();this._applyDeviceMetrics(new Geometry.Size(screenWidth,screenHeight),new Geometry.Insets(0,0,0,0),new Geometry.Insets(0,0,0,0),this._scaleSetting.get(),this._deviceScaleFactorSetting.get()||defaultDeviceScaleFactor,mobile,screenHeight>=screenWidth?Protocol.Emulation.ScreenOrientationType.PortraitPrimary:Protocol.Emulation.ScreenOrientationType.LandscapePrimary,resetPageScaleFactor);this._applyUserAgent(mobile?_defaultMobileUserAgent:'',mobile?_defaultMobileUserAgentMetadata:null);this._applyTouch(this._uaSetting.get()===UA.DesktopTouch||this._uaSetting.get()===UA.Mobile,this._uaSetting.get()===UA.Mobile);}
if(overlayModel){overlayModel.setShowViewportSizeOnResize(this._type===Type$1.None);}
this.dispatchEventToListeners(Events$1.Updated);}
_calculateFitScale(screenWidth,screenHeight,outline,insets){const outlineWidth=outline?outline.left+outline.right:0;const outlineHeight=outline?outline.top+outline.bottom:0;const insetsWidth=insets?insets.left+insets.right:0;const insetsHeight=insets?insets.top+insets.bottom:0;let scale=Math.min(screenWidth?this._preferredSize.width/(screenWidth+outlineWidth):1,screenHeight?this._preferredSize.height/(screenHeight+outlineHeight):1);scale=Math.min(Math.floor(scale*100),100);let sharpScale=scale;while(sharpScale>scale*0.7){let sharp=true;if(screenWidth){sharp=sharp&&Number.isInteger((screenWidth-insetsWidth)*sharpScale/100);}
if(screenHeight){sharp=sharp&&Number.isInteger((screenHeight-insetsHeight)*sharpScale/100);}
if(sharp){return sharpScale/100;}
sharpScale-=1;}
return scale/100;}
setSizeAndScaleToFit(width,height){this._scaleSetting.set(this._calculateFitScale(width,height));this.setWidth(width);this.setHeight(height);}
_applyUserAgent(userAgent,userAgentMetadata){NetworkManager.MultitargetNetworkManager.instance().setUserAgentOverride(userAgent,userAgentMetadata);}
_applyDeviceMetrics(screenSize,insets,outline,scale,deviceScaleFactor,mobile,screenOrientation,resetPageScaleFactor){screenSize.width=Math.max(1,Math.floor(screenSize.width));screenSize.height=Math.max(1,Math.floor(screenSize.height));let pageWidth=screenSize.width-insets.left-insets.right;let pageHeight=screenSize.height-insets.top-insets.bottom;this._emulatedPageSize=new Geometry.Size(pageWidth,pageHeight);const positionX=insets.left;const positionY=insets.top;const screenOrientationAngle=screenOrientation===Protocol.Emulation.ScreenOrientationType.LandscapePrimary?90:0;this._appliedDeviceSize=screenSize;this._appliedDeviceScaleFactor=deviceScaleFactor||window.devicePixelRatio;this._screenRect=new Geometry.Rect(Math.max(0,(this._availableSize.width-screenSize.width*scale)/2),outline.top*scale,screenSize.width*scale,screenSize.height*scale);this._outlineRect=new Geometry.Rect(this._screenRect.left-outline.left*scale,0,(outline.left+screenSize.width+outline.right)*scale,(outline.top+screenSize.height+outline.bottom)*scale);this._visiblePageRect=new Geometry.Rect(positionX*scale,positionY*scale,Math.min(pageWidth*scale,this._availableSize.width-this._screenRect.left-positionX*scale),Math.min(pageHeight*scale,this._availableSize.height-this._screenRect.top-positionY*scale));this._scale=scale;if(scale===1&&this._availableSize.width>=screenSize.width&&this._availableSize.height>=screenSize.height){pageWidth=0;pageHeight=0;}
if(this._visiblePageRect.width===pageWidth*scale&&this._visiblePageRect.height===pageHeight*scale&&Number.isInteger(pageWidth*scale)&&Number.isInteger(pageHeight*scale)){pageWidth=0;pageHeight=0;}
if(!this._emulationModel){return;}
if(resetPageScaleFactor){this._emulationModel.resetPageScaleFactor();}
if(pageWidth||pageHeight||mobile||deviceScaleFactor||scale!==1||screenOrientation){const metrics={width:pageWidth,height:pageHeight,deviceScaleFactor:deviceScaleFactor,mobile:mobile,scale:scale,screenWidth:screenSize.width,screenHeight:screenSize.height,positionX:positionX,positionY:positionY,dontSetVisibleSize:true};if(screenOrientation){metrics.screenOrientation={type:screenOrientation,angle:screenOrientationAngle};}
this._emulationModel.emulateDevice(metrics);}else{this._emulationModel.emulateDevice(null);}}
exitHingeMode(){const overlayModel=this._emulationModel?this._emulationModel.overlayModel():null;if(overlayModel){overlayModel.showHingeForDualScreen(false);}}
async captureScreenshot(fullSize,clip){const screenCaptureModel=this._emulationModel?this._emulationModel.target().model(ScreenCaptureModel.ScreenCaptureModel):null;if(!screenCaptureModel){return null;}
const overlayModel=this._emulationModel?this._emulationModel.overlayModel():null;if(overlayModel){overlayModel.setShowViewportSizeOnResize(false);}
let deviceMetrics;if(fullSize){const metrics=await screenCaptureModel.fetchLayoutMetrics();if(!metrics){return null;}
const contentHeight=Math.min((1<<14)/this._appliedDeviceScaleFactor,metrics.contentHeight);deviceMetrics={width:Math.floor(metrics.contentWidth),height:Math.floor(contentHeight),deviceScaleFactor:this._appliedDeviceScaleFactor,mobile:this._isMobile(),};clip={x:0,y:0,width:deviceMetrics.width,height:deviceMetrics.height,scale:1};if(this._device){const screenOrientation=this._mode.orientation===Horizontal?Protocol.Emulation.ScreenOrientationType.LandscapePrimary:Protocol.Emulation.ScreenOrientationType.PortraitPrimary;const screenOrientationAngle=screenOrientation===Protocol.Emulation.ScreenOrientationType.LandscapePrimary?90:0;deviceMetrics.screenOrientation={type:screenOrientation,angle:screenOrientationAngle};}
await this._emulationModel.resetPageScaleFactor();await this._emulationModel.emulateDevice(deviceMetrics);}
const screenshot=await screenCaptureModel.captureScreenshot('png',100,clip);if(fullSize){if(this._device){const orientation=this._device.orientationByName(this._mode.orientation);deviceMetrics.width=orientation.width;deviceMetrics.height=orientation.height;}else{deviceMetrics.width=0;deviceMetrics.height=0;}
await this._emulationModel.emulateDevice(deviceMetrics);}
this._calculateAndEmulate(false);return screenshot;}
_applyTouch(touchEnabled,mobile){this._touchEnabled=touchEnabled;this._touchMobile=mobile;for(const emulationModel of SDKModel.TargetManager.instance().models(EmulationModel.EmulationModel)){emulationModel.emulateTouch(touchEnabled,mobile);}}
_showHingeIfApplicable(overlayModel,orientation){if(!this._experimentDualScreenSupport){return;}
if(orientation.hinge){overlayModel.showHingeForDualScreen(true,orientation.hinge);}else{overlayModel.showHingeForDualScreen(false);}}}
const Events$1={Updated:'Updated'};const Type$1={None:'None',Responsive:'Responsive',Device:'Device'};const UA={Mobile:UIString.UIString('Mobile'),MobileNoTouch:UIString.UIString('Mobile (no touch)'),Desktop:UIString.UIString('Desktop'),DesktopTouch:UIString.UIString('Desktop (touch)')};const MinDeviceSize=50;const MaxDeviceSize=9999;const MinDeviceScaleFactor=0;const MaxDeviceScaleFactor=10;const MaxDeviceNameLength=50;const _mobileUserAgent='Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36';const _defaultMobileUserAgent=NetworkManager.MultitargetNetworkManager.patchUserAgentWithChromeVersion(_mobileUserAgent);const _defaultMobileUserAgentMetadata={brands:NetworkManager.MultitargetNetworkManager.getChromeBrands(),fullVersion:NetworkManager.MultitargetNetworkManager.getChromeVersion(),platform:'Android',platformVersion:'6.0',architecture:'',model:'Nexus 5',mobile:true};const defaultMobileScaleFactor=2;var DeviceModeModel$1=Object.freeze({__proto__:null,DeviceModeModel:DeviceModeModel,Events:Events$1,Type:Type$1,UA:UA,MinDeviceSize:MinDeviceSize,MaxDeviceSize:MaxDeviceSize,MinDeviceScaleFactor:MinDeviceScaleFactor,MaxDeviceScaleFactor:MaxDeviceScaleFactor,MaxDeviceNameLength:MaxDeviceNameLength,_defaultMobileUserAgent:_defaultMobileUserAgent,_defaultMobileUserAgentMetadata:_defaultMobileUserAgentMetadata,defaultMobileScaleFactor:defaultMobileScaleFactor});class DeviceModeToolbar{constructor(model,showMediaInspectorSetting,showRulersSetting){this._model=model;this._showMediaInspectorSetting=showMediaInspectorSetting;this._showRulersSetting=showRulersSetting;this._experimentDualScreenSupport=Root.Runtime.experiments.isEnabled('dualScreenSupport');this._deviceOutlineSetting=this._model.deviceOutlineSetting();this._showDeviceScaleFactorSetting=Settings.Settings.instance().createSetting('emulation.showDeviceScaleFactor',false);this._showDeviceScaleFactorSetting.addChangeListener(this._updateDeviceScaleFactorVisibility,this);this._showUserAgentTypeSetting=Settings.Settings.instance().createSetting('emulation.showUserAgentType',false);this._showUserAgentTypeSetting.addChangeListener(this._updateUserAgentTypeVisibility,this);this._autoAdjustScaleSetting=Settings.Settings.instance().createSetting('emulation.autoAdjustScale',true);this._lastMode=new Map();this._element=document.createElement('div');this._element.classList.add('device-mode-toolbar');const leftContainer=this._element.createChild('div','device-mode-toolbar-spacer');leftContainer.createChild('div','device-mode-toolbar-spacer');const leftToolbar=new Toolbar.Toolbar('',leftContainer);leftToolbar.makeWrappable();this._fillLeftToolbar(leftToolbar);const mainToolbar=new Toolbar.Toolbar('',this._element);mainToolbar.makeWrappable();this._fillMainToolbar(mainToolbar);const rightContainer=this._element.createChild('div','device-mode-toolbar-spacer');const rightToolbar=new Toolbar.Toolbar('device-mode-toolbar-fixed-size',rightContainer);rightToolbar.makeWrappable();this._fillRightToolbar(rightToolbar);const modeToolbar=new Toolbar.Toolbar('device-mode-toolbar-fixed-size',rightContainer);modeToolbar.makeWrappable();this._fillModeToolbar(modeToolbar);rightContainer.createChild('div','device-mode-toolbar-spacer');const optionsToolbar=new Toolbar.Toolbar('device-mode-toolbar-options',rightContainer);optionsToolbar.makeWrappable();this._fillOptionsToolbar(optionsToolbar);this._emulatedDevicesList=EmulatedDevicesList.instance();this._emulatedDevicesList.addEventListener(Events.CustomDevicesUpdated,this._deviceListChanged,this);this._emulatedDevicesList.addEventListener(Events.StandardDevicesUpdated,this._deviceListChanged,this);this._persistenceSetting=Settings.Settings.instance().createSetting('emulation.deviceModeValue',{device:'',orientation:'',mode:''});this._model.toolbarControlsEnabledSetting().addChangeListener(updateToolbarsEnabled);updateToolbarsEnabled();function updateToolbarsEnabled(){const enabled=model.toolbarControlsEnabledSetting().get();leftToolbar.setEnabled(enabled);mainToolbar.setEnabled(enabled);rightToolbar.setEnabled(enabled);modeToolbar.setEnabled(enabled);optionsToolbar.setEnabled(enabled);}}
_createEmptyToolbarElement(){const element=document.createElement('div');element.classList.add('device-mode-empty-toolbar-element');return element;}
_fillLeftToolbar(toolbar){toolbar.appendToolbarItem(this._wrapToolbarItem(this._createEmptyToolbarElement()));this._deviceSelectItem=new Toolbar.ToolbarMenuButton(this._appendDeviceMenuItems.bind(this));this._deviceSelectItem.setGlyph('');this._deviceSelectItem.turnIntoSelect();this._deviceSelectItem.setDarkText();toolbar.appendToolbarItem(this._deviceSelectItem);}
_fillMainToolbar(toolbar){const widthInput=UIUtils.createInput('device-mode-size-input','text');widthInput.maxLength=4;widthInput.title=UIString.UIString('Width');this._updateWidthInput=UIUtils.bindInput(widthInput,this._applyWidth.bind(this),DeviceModeModel.widthValidator,true);this._widthInput=widthInput;this._widthItem=this._wrapToolbarItem(widthInput);toolbar.appendToolbarItem(this._widthItem);const xElement=document.createElement('div');xElement.classList.add('device-mode-x');xElement.textContent='×';this._xItem=this._wrapToolbarItem(xElement);toolbar.appendToolbarItem(this._xItem);const heightInput=UIUtils.createInput('device-mode-size-input','text');heightInput.maxLength=4;heightInput.title=UIString.UIString('Height (leave empty for full)');this._updateHeightInput=UIUtils.bindInput(heightInput,this._applyHeight.bind(this),validateHeight,true);this._heightInput=heightInput;this._heightItem=this._wrapToolbarItem(heightInput);toolbar.appendToolbarItem(this._heightItem);function validateHeight(value){if(!value){return{valid:true};}
return DeviceModeModel.heightValidator(value);}}
_applyWidth(value){const width=value?Number(value):0;this._model.setWidthAndScaleToFit(width);}
_applyHeight(value){const height=value?Number(value):0;this._model.setHeightAndScaleToFit(height);}
_fillRightToolbar(toolbar){toolbar.appendToolbarItem(this._wrapToolbarItem(this._createEmptyToolbarElement()));this._scaleItem=new Toolbar.ToolbarMenuButton(this._appendScaleMenuItems.bind(this));this._scaleItem.setTitle(UIString.UIString('Zoom'));this._scaleItem.setGlyph('');this._scaleItem.turnIntoSelect();this._scaleItem.setDarkText();toolbar.appendToolbarItem(this._scaleItem);toolbar.appendToolbarItem(this._wrapToolbarItem(this._createEmptyToolbarElement()));this._deviceScaleItem=new Toolbar.ToolbarMenuButton(this._appendDeviceScaleMenuItems.bind(this));this._deviceScaleItem.setVisible(this._showDeviceScaleFactorSetting.get());this._deviceScaleItem.setTitle(UIString.UIString('Device pixel ratio'));this._deviceScaleItem.setGlyph('');this._deviceScaleItem.turnIntoSelect();this._deviceScaleItem.setDarkText();toolbar.appendToolbarItem(this._deviceScaleItem);toolbar.appendToolbarItem(this._wrapToolbarItem(this._createEmptyToolbarElement()));this._uaItem=new Toolbar.ToolbarMenuButton(this._appendUserAgentMenuItems.bind(this));this._uaItem.setVisible(this._showUserAgentTypeSetting.get());this._uaItem.setTitle(UIString.UIString('Device type'));this._uaItem.setGlyph('');this._uaItem.turnIntoSelect();this._uaItem.setDarkText();toolbar.appendToolbarItem(this._uaItem);this._throttlingConditionsItem=ThrottlingManager.throttlingManager().createMobileThrottlingButton();toolbar.appendToolbarItem(this._throttlingConditionsItem);}
_fillModeToolbar(toolbar){toolbar.appendToolbarItem(this._wrapToolbarItem(this._createEmptyToolbarElement()));this._modeButton=new Toolbar.ToolbarButton('','largeicon-rotate-screen');this._modeButton.addEventListener(Toolbar.ToolbarButton.Events.Click,this._modeMenuClicked,this);toolbar.appendToolbarItem(this._modeButton);if(this._experimentDualScreenSupport){this._spanButton=new Toolbar.ToolbarButton('','largeicon-dual-screen');this._spanButton.addEventListener(Toolbar.ToolbarButton.Events.Click,this._spanClicked,this);toolbar.appendToolbarItem(this._spanButton);}}
_fillOptionsToolbar(toolbar){toolbar.appendToolbarItem(this._wrapToolbarItem(this._createEmptyToolbarElement()));const moreOptionsButton=new Toolbar.ToolbarMenuButton(this._appendOptionsMenuItems.bind(this));moreOptionsButton.setTitle(UIString.UIString('More options'));toolbar.appendToolbarItem(moreOptionsButton);}
_appendScaleMenuItems(contextMenu){if(this._model.type()===Type$1.Device){contextMenu.footerSection().appendItem(UIString.UIString('Fit to window (%.0f%%)',this._model.fitScale()*100),this._onScaleMenuChanged.bind(this,this._model.fitScale()),false);}
contextMenu.footerSection().appendCheckboxItem(ls`Auto-adjust zoom`,this._onAutoAdjustScaleChanged.bind(this),this._autoAdjustScaleSetting.get());const boundAppendScaleItem=appendScaleItem.bind(this);boundAppendScaleItem(UIString.UIString('50%'),0.5);boundAppendScaleItem(UIString.UIString('75%'),0.75);boundAppendScaleItem(UIString.UIString('100%'),1);boundAppendScaleItem(UIString.UIString('125%'),1.25);boundAppendScaleItem(UIString.UIString('150%'),1.5);function appendScaleItem(title,value){contextMenu.defaultSection().appendCheckboxItem(title,this._onScaleMenuChanged.bind(this,value),this._model.scaleSetting().get()===value,false);}}
_onScaleMenuChanged(value){this._model.scaleSetting().set(value);}
_onAutoAdjustScaleChanged(){this._autoAdjustScaleSetting.set(!this._autoAdjustScaleSetting.get());}
_appendDeviceScaleMenuItems(contextMenu){const deviceScaleFactorSetting=this._model.deviceScaleFactorSetting();const defaultValue=this._model.uaSetting().get()===UA.Mobile||this._model.uaSetting().get()===UA.MobileNoTouch?defaultMobileScaleFactor:window.devicePixelRatio;appendDeviceScaleFactorItem(contextMenu.headerSection(),UIString.UIString('Default: %.1f',defaultValue),0);appendDeviceScaleFactorItem(contextMenu.defaultSection(),UIString.UIString('1'),1);appendDeviceScaleFactorItem(contextMenu.defaultSection(),UIString.UIString('2'),2);appendDeviceScaleFactorItem(contextMenu.defaultSection(),UIString.UIString('3'),3);function appendDeviceScaleFactorItem(section,title,value){section.appendCheckboxItem(title,deviceScaleFactorSetting.set.bind(deviceScaleFactorSetting,value),deviceScaleFactorSetting.get()===value);}}
_appendUserAgentMenuItems(contextMenu){const uaSetting=this._model.uaSetting();appendUAItem(UA.Mobile,UA.Mobile);appendUAItem(UA.MobileNoTouch,UA.MobileNoTouch);appendUAItem(UA.Desktop,UA.Desktop);appendUAItem(UA.DesktopTouch,UA.DesktopTouch);function appendUAItem(title,value){contextMenu.defaultSection().appendCheckboxItem(title,uaSetting.set.bind(uaSetting,value),uaSetting.get()===value);}}
_appendOptionsMenuItems(contextMenu){const model=this._model;appendToggleItem(contextMenu.headerSection(),this._deviceOutlineSetting,UIString.UIString('Hide device frame'),UIString.UIString('Show device frame'),model.type()!==Type$1.Device);appendToggleItem(contextMenu.headerSection(),this._showMediaInspectorSetting,UIString.UIString('Hide media queries'),UIString.UIString('Show media queries'));appendToggleItem(contextMenu.headerSection(),this._showRulersSetting,UIString.UIString('Hide rulers'),UIString.UIString('Show rulers'));appendToggleItem(contextMenu.defaultSection(),this._showDeviceScaleFactorSetting,UIString.UIString('Remove device pixel ratio'),UIString.UIString('Add device pixel ratio'));appendToggleItem(contextMenu.defaultSection(),this._showUserAgentTypeSetting,UIString.UIString('Remove device type'),UIString.UIString('Add device type'));contextMenu.appendItemsAtLocation('deviceModeMenu');contextMenu.footerSection().appendItem(UIString.UIString('Reset to defaults'),this._reset.bind(this));contextMenu.footerSection().appendItem(ls`Close DevTools`,InspectorFrontendHost.InspectorFrontendHostInstance.closeWindow.bind(InspectorFrontendHost.InspectorFrontendHostInstance));function appendToggleItem(section,setting,title1,title2,disabled){if(typeof disabled==='undefined'){disabled=model.type()===Type$1.None;}
section.appendItem(setting.get()?title1:title2,setting.set.bind(setting,!setting.get()),disabled);}}
_reset(){this._deviceOutlineSetting.set(false);this._showDeviceScaleFactorSetting.set(false);this._showUserAgentTypeSetting.set(false);this._showMediaInspectorSetting.set(false);this._showRulersSetting.set(false);this._model.reset();}
_wrapToolbarItem(element){const container=createElement('div');const shadowRoot=Utils.createShadowRootWithCoreStyles(container,'emulation/deviceModeToolbar.css');shadowRoot.appendChild(element);return new Toolbar.ToolbarItem(container);}
_emulateDevice(device){const scale=this._autoAdjustScaleSetting.get()?undefined:this._model.scaleSetting().get();this._model.emulate(Type$1.Device,device,this._lastMode.get(device)||device.modes[0],scale);}
_switchToResponsive(){this._model.emulate(Type$1.Responsive,null,null);}
_filterDevices(devices){devices=devices.filter(function(d){return d.show();});devices.sort(EmulatedDevice.deviceComparator);return devices;}
_standardDevices(){return this._filterDevices(this._emulatedDevicesList.standard());}
_customDevices(){return this._filterDevices(this._emulatedDevicesList.custom());}
_allDevices(){return this._standardDevices().concat(this._customDevices());}
_appendDeviceMenuItems(contextMenu){contextMenu.headerSection().appendCheckboxItem(UIString.UIString('Responsive'),this._switchToResponsive.bind(this),this._model.type()===Type$1.Responsive,false);appendGroup.call(this,this._standardDevices());appendGroup.call(this,this._customDevices());contextMenu.footerSection().appendItem(UIString.UIString('Edit…'),this._emulatedDevicesList.revealCustomSetting.bind(this._emulatedDevicesList),false);function appendGroup(devices){if(!devices.length){return;}
const section=contextMenu.section();for(const device of devices){section.appendCheckboxItem(device.title,this._emulateDevice.bind(this,device),this._model.device()===device,false);}}}
_deviceListChanged(){const device=this._model.device();if(!device){return;}
const devices=this._allDevices();if(devices.indexOf(device)===-1){if(devices.length){this._emulateDevice(devices[0]);}else{this._model.emulate(Type$1.Responsive,null,null);}}}
_updateDeviceScaleFactorVisibility(){this._deviceScaleItem.setVisible(this._showDeviceScaleFactorSetting.get());}
_updateUserAgentTypeVisibility(){this._uaItem.setVisible(this._showUserAgentTypeSetting.get());}
_spanClicked(event){const device=this._model.device();if(!device.isDualScreen){return;}
const scale=this._autoAdjustScaleSetting.get()?undefined:this._model.scaleSetting().get();const newMode=device.getSpanPartner(this._model.mode());if(!newMode){return;}
this._model.emulate(this._model.type(),device,newMode,scale);return;}
_modeMenuClicked(event){const device=this._model.device();const model=this._model;const autoAdjustScaleSetting=this._autoAdjustScaleSetting;if(model.type()===Type$1.Responsive){const appliedSize=model.appliedDeviceSize();if(autoAdjustScaleSetting.get()){model.setSizeAndScaleToFit(appliedSize.height,appliedSize.width);}else{model.setWidth(appliedSize.height);model.setHeight(appliedSize.width);}
return;}
if((device.isDualScreen||device.modes.length===2)&&device.modes[0].orientation!==device.modes[1].orientation){const scale=autoAdjustScaleSetting.get()?undefined:model.scaleSetting().get();model.emulate(model.type(),model.device(),device.getRotationPartner(model.mode()),scale);return;}
const contextMenu=new ContextMenu.ContextMenu((event.data),false,this._modeButton.element.totalOffsetLeft(),this._modeButton.element.totalOffsetTop()+this._modeButton.element.offsetHeight);addOrientation(Vertical,UIString.UIString('Portrait'));addOrientation(Horizontal,UIString.UIString('Landscape'));contextMenu.show();function addOrientation(orientation,title){const modes=device.modesForOrientation(orientation);if(!modes.length){return;}
if(modes.length===1){addMode(modes[0],title);}else{for(let index=0;index<modes.length;index++){addMode(modes[index],title+' \u2013 '+modes[index].title);}}}
function addMode(mode,title){contextMenu.defaultSection().appendCheckboxItem(title,applyMode.bind(null,mode),model.mode()===mode,false);}
function applyMode(mode){const scale=autoAdjustScaleSetting.get()?undefined:model.scaleSetting().get();model.emulate(model.type(),model.device(),mode,scale);}}
element(){return this._element;}
update(){if(this._model.type()!==this._cachedModelType){this._cachedModelType=this._model.type();this._widthInput.disabled=this._model.type()!==Type$1.Responsive;this._heightInput.disabled=this._model.type()!==Type$1.Responsive;this._deviceScaleItem.setEnabled(this._model.type()===Type$1.Responsive);this._uaItem.setEnabled(this._model.type()===Type$1.Responsive);if(this._experimentDualScreenSupport){this._spanButton.setEnabled(false);}
if(this._model.type()===Type$1.Responsive){this._modeButton.setEnabled(true);this._modeButton.setTitle(ls`Rotate`);}else{this._modeButton.setEnabled(false);}}
const size=this._model.appliedDeviceSize();this._updateHeightInput(this._model.type()===Type$1.Responsive&&this._model.isFullHeight()?'':String(size.height));this._updateWidthInput(String(size.width));this._heightInput.placeholder=size.height;if(this._model.scale()!==this._cachedScale){this._scaleItem.setText(UIString.UIString('%.0f%%',this._model.scale()*100));this._cachedScale=this._model.scale();}
const deviceScale=this._model.appliedDeviceScaleFactor();if(deviceScale!==this._cachedDeviceScale){this._deviceScaleItem.setText(UIString.UIString('DPR: %.1f',deviceScale));this._cachedDeviceScale=deviceScale;}
const uaType=this._model.appliedUserAgentType();if(uaType!==this._cachedUaType){this._uaItem.setText(uaType);this._cachedUaType=uaType;}
let deviceItemTitle=UIString.UIString('None');if(this._model.type()===Type$1.Responsive){deviceItemTitle=UIString.UIString('Responsive');}
if(this._model.type()===Type$1.Device){deviceItemTitle=this._model.device().title;}
this._deviceSelectItem.setText(deviceItemTitle);if(this._model.device()!==this._cachedModelDevice){const device=this._model.device();if(device){const modeCount=device?device.modes.length:0;this._modeButton.setEnabled(modeCount>=2);this._modeButton.setTitle(modeCount===2?UIString.UIString('Rotate'):UIString.UIString('Screen orientation options'));if(this._experimentDualScreenSupport){if(device.isDualScreen){this._spanButton.setEnabled(true);}
this._spanButton.setTitle(UIString.UIString('Toggle dual-screen mode'));}}
this._cachedModelDevice=device;}
if(this._model.type()===Type$1.Device){this._lastMode.set((this._model.device()),(this._model.mode()));}
if(this._model.mode()!==this._cachedModelMode&&this._model.type()!==Type$1.None){this._cachedModelMode=this._model.mode();const value=this._persistenceSetting.get();if(this._model.device()){value.device=this._model.device().title;value.orientation=this._model.mode()?this._model.mode().orientation:'';value.mode=this._model.mode()?this._model.mode().title:'';}else{value.device='';value.orientation='';value.mode='';}
this._persistenceSetting.set(value);}}
restore(){for(const device of this._allDevices()){if(device.title===this._persistenceSetting.get().device){for(const mode of device.modes){if(mode.orientation===this._persistenceSetting.get().orientation&&mode.title===this._persistenceSetting.get().mode){this._lastMode.set(device,mode);this._emulateDevice(device);return;}}}}
this._model.emulate(Type$1.Responsive,null,null);}}
var DeviceModeToolbar$1=Object.freeze({__proto__:null,DeviceModeToolbar:DeviceModeToolbar});class MediaQueryInspector extends Widget.Widget{constructor(getWidthCallback,setWidthCallback){super(true);this.registerRequiredCSS('emulation/mediaQueryInspector.css');this.contentElement.classList.add('media-inspector-view');this.contentElement.addEventListener('click',this._onMediaQueryClicked.bind(this),false);this.contentElement.addEventListener('contextmenu',this._onContextMenu.bind(this),false);this._mediaThrottler=new Throttler.Throttler(0);this._getWidthCallback=getWidthCallback;this._setWidthCallback=setWidthCallback;this._scale=1;SDKModel.TargetManager.instance().observeModels(CSSModel.CSSModel,this);ZoomManager.ZoomManager.instance().addEventListener(ZoomManager.Events.ZoomChanged,this._renderMediaQueries.bind(this),this);}
modelAdded(cssModel){if(this._cssModel){return;}
this._cssModel=cssModel;this._cssModel.addEventListener(CSSModel.Events.StyleSheetAdded,this._scheduleMediaQueriesUpdate,this);this._cssModel.addEventListener(CSSModel.Events.StyleSheetRemoved,this._scheduleMediaQueriesUpdate,this);this._cssModel.addEventListener(CSSModel.Events.StyleSheetChanged,this._scheduleMediaQueriesUpdate,this);this._cssModel.addEventListener(CSSModel.Events.MediaQueryResultChanged,this._scheduleMediaQueriesUpdate,this);}
modelRemoved(cssModel){if(cssModel!==this._cssModel){return;}
this._cssModel.removeEventListener(CSSModel.Events.StyleSheetAdded,this._scheduleMediaQueriesUpdate,this);this._cssModel.removeEventListener(CSSModel.Events.StyleSheetRemoved,this._scheduleMediaQueriesUpdate,this);this._cssModel.removeEventListener(CSSModel.Events.StyleSheetChanged,this._scheduleMediaQueriesUpdate,this);this._cssModel.removeEventListener(CSSModel.Events.MediaQueryResultChanged,this._scheduleMediaQueriesUpdate,this);delete this._cssModel;}
setAxisTransform(scale){if(Math.abs(this._scale-scale)<1e-8){return;}
this._scale=scale;this._renderMediaQueries();}
_onMediaQueryClicked(event){const mediaQueryMarker=event.target.enclosingNodeOrSelfWithClass('media-inspector-bar');if(!mediaQueryMarker){return;}
const model=mediaQueryMarker._model;if(model.section()===Section.Max){this._setWidthCallback(model.maxWidthExpression().computedLength());return;}
if(model.section()===Section.Min){this._setWidthCallback(model.minWidthExpression().computedLength());return;}
const currentWidth=this._getWidthCallback();if(currentWidth!==model.minWidthExpression().computedLength()){this._setWidthCallback(model.minWidthExpression().computedLength());}else{this._setWidthCallback(model.maxWidthExpression().computedLength());}}
_onContextMenu(event){if(!this._cssModel||!this._cssModel.isEnabled()){return;}
const mediaQueryMarker=event.target.enclosingNodeOrSelfWithClass('media-inspector-bar');if(!mediaQueryMarker){return;}
const locations=mediaQueryMarker._locations;const uiLocations=new Map();for(let i=0;i<locations.length;++i){const uiLocation=CSSWorkspaceBinding.CSSWorkspaceBinding.instance().rawLocationToUILocation(locations[i]);if(!uiLocation){continue;}
const descriptor=StringUtilities.sprintf('%s:%d:%d',uiLocation.uiSourceCode.url(),uiLocation.lineNumber+1,uiLocation.columnNumber+1);uiLocations.set(descriptor,uiLocation);}
const contextMenuItems=[...uiLocations.keys()].sort();const contextMenu=new ContextMenu.ContextMenu(event);const subMenuItem=contextMenu.defaultSection().appendSubMenuItem(UIString.UIString('Reveal in source code'));for(let i=0;i<contextMenuItems.length;++i){const title=contextMenuItems[i];subMenuItem.defaultSection().appendItem(title,this._revealSourceLocation.bind(this,(uiLocations.get(title))));}
contextMenu.show();}
_revealSourceLocation(location){Revealer.reveal(location);}
_scheduleMediaQueriesUpdate(){if(!this.isShowing()){return;}
this._mediaThrottler.schedule(this._refetchMediaQueries.bind(this));}
_refetchMediaQueries(){if(!this.isShowing()||!this._cssModel){return Promise.resolve();}
return this._cssModel.mediaQueriesPromise().then(this._rebuildMediaQueries.bind(this));}
_squashAdjacentEqual(models){const filtered=[];for(let i=0;i<models.length;++i){const last=filtered.peekLast();if(!last||!last.equals(models[i])){filtered.push(models[i]);}}
return filtered;}
_rebuildMediaQueries(cssMedias){let queryModels=[];for(let i=0;i<cssMedias.length;++i){const cssMedia=cssMedias[i];if(!cssMedia.mediaList){continue;}
for(let j=0;j<cssMedia.mediaList.length;++j){const mediaQuery=cssMedia.mediaList[j];const queryModel=MediaQueryUIModel.createFromMediaQuery(cssMedia,mediaQuery);if(queryModel&&queryModel.rawLocation()){queryModels.push(queryModel);}}}
queryModels.sort(compareModels);queryModels=this._squashAdjacentEqual(queryModels);let allEqual=this._cachedQueryModels&&this._cachedQueryModels.length===queryModels.length;for(let i=0;allEqual&&i<queryModels.length;++i){allEqual=allEqual&&this._cachedQueryModels[i].equals(queryModels[i]);}
if(allEqual){return;}
this._cachedQueryModels=queryModels;this._renderMediaQueries();function compareModels(model1,model2){return model1.compareTo(model2);}}
_renderMediaQueries(){if(!this._cachedQueryModels||!this.isShowing()){return;}
const markers=[];let lastMarker=null;for(let i=0;i<this._cachedQueryModels.length;++i){const model=this._cachedQueryModels[i];if(lastMarker&&lastMarker.model.dimensionsEqual(model)){lastMarker.locations.push(model.rawLocation());lastMarker.active=lastMarker.active||model.active();}else{lastMarker={active:model.active(),model:model,locations:[model.rawLocation()]};markers.push(lastMarker);}}
this.contentElement.removeChildren();let container=null;for(let i=0;i<markers.length;++i){if(!i||markers[i].model.section()!==markers[i-1].model.section()){container=this.contentElement.createChild('div','media-inspector-marker-container');}
const marker=markers[i];const bar=this._createElementFromMediaQueryModel(marker.model);bar._model=marker.model;bar._locations=marker.locations;bar.classList.toggle('media-inspector-marker-inactive',!marker.active);container.appendChild(bar);}}
_zoomFactor(){return ZoomManager.ZoomManager.instance().zoomFactor()/this._scale;}
wasShown(){this._scheduleMediaQueriesUpdate();}
_createElementFromMediaQueryModel(model){const zoomFactor=this._zoomFactor();const minWidthValue=model.minWidthExpression()?model.minWidthExpression().computedLength()/zoomFactor:0;const maxWidthValue=model.maxWidthExpression()?model.maxWidthExpression().computedLength()/zoomFactor:0;const result=document.createElement('div');result.classList.add('media-inspector-bar');if(model.section()===Section.Max){result.createChild('div','media-inspector-marker-spacer');const markerElement=result.createChild('div','media-inspector-marker media-inspector-marker-max-width');markerElement.style.width=maxWidthValue+'px';markerElement.title=model.mediaText();appendLabel(markerElement,model.maxWidthExpression(),false,false);appendLabel(markerElement,model.maxWidthExpression(),true,true);result.createChild('div','media-inspector-marker-spacer');}
if(model.section()===Section.MinMax){result.createChild('div','media-inspector-marker-spacer');const leftElement=result.createChild('div','media-inspector-marker media-inspector-marker-min-max-width');leftElement.style.width=(maxWidthValue-minWidthValue)*0.5+'px';leftElement.title=model.mediaText();appendLabel(leftElement,model.minWidthExpression(),true,false);appendLabel(leftElement,model.maxWidthExpression(),false,true);result.createChild('div','media-inspector-marker-spacer').style.flex='0 0 '+minWidthValue+'px';const rightElement=result.createChild('div','media-inspector-marker media-inspector-marker-min-max-width');rightElement.style.width=(maxWidthValue-minWidthValue)*0.5+'px';rightElement.title=model.mediaText();appendLabel(rightElement,model.minWidthExpression(),true,false);appendLabel(rightElement,model.maxWidthExpression(),false,true);result.createChild('div','media-inspector-marker-spacer');}
if(model.section()===Section.Min){const leftElement=result.createChild('div','media-inspector-marker media-inspector-marker-min-width media-inspector-marker-min-width-left');leftElement.title=model.mediaText();appendLabel(leftElement,model.minWidthExpression(),false,false);result.createChild('div','media-inspector-marker-spacer').style.flex='0 0 '+minWidthValue+'px';const rightElement=result.createChild('div','media-inspector-marker media-inspector-marker-min-width media-inspector-marker-min-width-right');rightElement.title=model.mediaText();appendLabel(rightElement,model.minWidthExpression(),true,true);}
function appendLabel(marker,expression,atLeft,leftAlign){marker.createChild('div','media-inspector-marker-label-container '+(atLeft?'media-inspector-marker-label-container-left':'media-inspector-marker-label-container-right')).createChild('span','media-inspector-marker-label '+
(leftAlign?'media-inspector-label-left':'media-inspector-label-right')).textContent=expression.value()+expression.unit();}
return result;}}
const Section={Max:0,MinMax:1,Min:2};class MediaQueryUIModel{constructor(cssMedia,minWidthExpression,maxWidthExpression,active){this._cssMedia=cssMedia;this._minWidthExpression=minWidthExpression;this._maxWidthExpression=maxWidthExpression;this._active=active;if(maxWidthExpression&&!minWidthExpression){this._section=Section.Max;}else if(minWidthExpression&&maxWidthExpression){this._section=Section.MinMax;}else{this._section=Section.Min;}}
static createFromMediaQuery(cssMedia,mediaQuery){let maxWidthExpression=null;let maxWidthPixels=Number.MAX_VALUE;let minWidthExpression=null;let minWidthPixels=Number.MIN_VALUE;const expressions=mediaQuery.expressions();for(let i=0;i<expressions.length;++i){const expression=expressions[i];const feature=expression.feature();if(feature.indexOf('width')===-1){continue;}
const pixels=expression.computedLength();if(feature.startsWith('max-')&&pixels<maxWidthPixels){maxWidthExpression=expression;maxWidthPixels=pixels;}else if(feature.startsWith('min-')&&pixels>minWidthPixels){minWidthExpression=expression;minWidthPixels=pixels;}}
if(minWidthPixels>maxWidthPixels||(!maxWidthExpression&&!minWidthExpression)){return null;}
return new MediaQueryUIModel(cssMedia,minWidthExpression,maxWidthExpression,mediaQuery.active());}
equals(other){return this.compareTo(other)===0;}
dimensionsEqual(other){return this.section()===other.section()&&(!this.minWidthExpression()||(this.minWidthExpression().computedLength()===other.minWidthExpression().computedLength()))&&(!this.maxWidthExpression()||(this.maxWidthExpression().computedLength()===other.maxWidthExpression().computedLength()));}
compareTo(other){if(this.section()!==other.section()){return this.section()-other.section();}
if(this.dimensionsEqual(other)){const myLocation=this.rawLocation();const otherLocation=other.rawLocation();if(!myLocation&&!otherLocation){return this.mediaText().compareTo(other.mediaText());}
if(myLocation&&!otherLocation){return 1;}
if(!myLocation&&otherLocation){return-1;}
if(this.active()!==other.active()){return this.active()?-1:1;}
return myLocation.url.compareTo(otherLocation.url)||myLocation.lineNumber-otherLocation.lineNumber||myLocation.columnNumber-otherLocation.columnNumber;}
if(this.section()===Section.Max){return other.maxWidthExpression().computedLength()-this.maxWidthExpression().computedLength();}
if(this.section()===Section.Min){return this.minWidthExpression().computedLength()-other.minWidthExpression().computedLength();}
return this.minWidthExpression().computedLength()-other.minWidthExpression().computedLength()||other.maxWidthExpression().computedLength()-this.maxWidthExpression().computedLength();}
section(){return this._section;}
mediaText(){return this._cssMedia.text;}
rawLocation(){if(!this._rawLocation){this._rawLocation=this._cssMedia.rawLocation();}
return this._rawLocation;}
minWidthExpression(){return this._minWidthExpression;}
maxWidthExpression(){return this._maxWidthExpression;}
active(){return this._active;}}
var MediaQueryInspector$1=Object.freeze({__proto__:null,MediaQueryInspector:MediaQueryInspector,Section:Section,MediaQueryUIModel:MediaQueryUIModel});class DeviceModeView extends Widget.VBox{constructor(){super(true);this.wrapperInstance;this.setMinimumSize(150,150);this.element.classList.add('device-mode-view');this.registerRequiredCSS('emulation/deviceModeView.css');Tooltip.Tooltip.addNativeOverrideContainer(this.contentElement);this._model=self.singleton(DeviceModeModel);this._model.addEventListener(Events$1.Updated,this._updateUI,this);this._mediaInspector=new MediaQueryInspector(()=>this._model.appliedDeviceSize().width,this._model.setWidth.bind(this._model));this._showMediaInspectorSetting=Settings.Settings.instance().moduleSetting('showMediaQueryInspector');this._showMediaInspectorSetting.addChangeListener(this._updateUI,this);this._showRulersSetting=Settings.Settings.instance().moduleSetting('emulation.showRulers');this._showRulersSetting.addChangeListener(this._updateUI,this);this._topRuler=new Ruler(true,this._model.setWidthAndScaleToFit.bind(this._model));this._topRuler.element.classList.add('device-mode-ruler-top');this._leftRuler=new Ruler(false,this._model.setHeightAndScaleToFit.bind(this._model));this._leftRuler.element.classList.add('device-mode-ruler-left');this._createUI();ZoomManager.ZoomManager.instance().addEventListener(ZoomManager.Events.ZoomChanged,this._zoomChanged,this);}
_createUI(){this._toolbar=new DeviceModeToolbar(this._model,this._showMediaInspectorSetting,this._showRulersSetting);this.contentElement.appendChild(this._toolbar.element());this._contentClip=this.contentElement.createChild('div','device-mode-content-clip vbox');this._responsivePresetsContainer=this._contentClip.createChild('div','device-mode-presets-container');this._populatePresetsContainer();this._mediaInspectorContainer=this._contentClip.createChild('div','device-mode-media-container');this._contentArea=this._contentClip.createChild('div','device-mode-content-area');this._outlineImage=this._contentArea.createChild('img','device-mode-outline-image hidden fill');this._outlineImage.addEventListener('load',this._onImageLoaded.bind(this,this._outlineImage,true),false);this._outlineImage.addEventListener('error',this._onImageLoaded.bind(this,this._outlineImage,false),false);this._screenArea=this._contentArea.createChild('div','device-mode-screen-area');this._screenImage=this._screenArea.createChild('img','device-mode-screen-image hidden');this._screenImage.addEventListener('load',this._onImageLoaded.bind(this,this._screenImage,true),false);this._screenImage.addEventListener('error',this._onImageLoaded.bind(this,this._screenImage,false),false);this._bottomRightResizerElement=this._screenArea.createChild('div','device-mode-resizer device-mode-bottom-right-resizer');this._bottomRightResizerElement.createChild('div','');this._createResizer(this._bottomRightResizerElement,2,1);this._bottomLeftResizerElement=this._screenArea.createChild('div','device-mode-resizer device-mode-bottom-left-resizer');this._bottomLeftResizerElement.createChild('div','');this._createResizer(this._bottomLeftResizerElement,-2,1);this._rightResizerElement=this._screenArea.createChild('div','device-mode-resizer device-mode-right-resizer');this._rightResizerElement.createChild('div','');this._createResizer(this._rightResizerElement,2,0);this._leftResizerElement=this._screenArea.createChild('div','device-mode-resizer device-mode-left-resizer');this._leftResizerElement.createChild('div','');this._createResizer(this._leftResizerElement,-2,0);this._bottomResizerElement=this._screenArea.createChild('div','device-mode-resizer device-mode-bottom-resizer');this._bottomResizerElement.createChild('div','');this._createResizer(this._bottomResizerElement,0,1);this._bottomResizerElement.addEventListener('dblclick',this._model.setHeight.bind(this._model,0),false);this._bottomResizerElement.title=UIString.UIString('Double-click for full height');this._pageArea=this._screenArea.createChild('div','device-mode-page-area');this._pageArea.createChild('slot');}
_populatePresetsContainer(){const sizes=[320,375,425,768,1024,1440,2560];const titles=[UIString.UIString('Mobile S'),UIString.UIString('Mobile M'),UIString.UIString('Mobile L'),UIString.UIString('Tablet'),UIString.UIString('Laptop'),UIString.UIString('Laptop L'),UIString.UIString('4K')];this._presetBlocks=[];const inner=this._responsivePresetsContainer.createChild('div','device-mode-presets-container-inner');for(let i=sizes.length-1;i>=0;--i){const outer=inner.createChild('div','fill device-mode-preset-bar-outer');const block=outer.createChild('div','device-mode-preset-bar');block.createChild('span').textContent=titles[i]+' \u2013 '+sizes[i]+'px';block.addEventListener('click',applySize.bind(this,sizes[i]),false);block.__width=sizes[i];this._presetBlocks.push(block);}
function applySize(width,e){this._model.emulate(Type$1.Responsive,null,null);this._model.setWidthAndScaleToFit(width);e.consume();}}
_createResizer(element,widthFactor,heightFactor){const resizer=new ResizerWidget.ResizerWidget();resizer.addElement(element);let cursor=widthFactor?'ew-resize':'ns-resize';if(widthFactor*heightFactor>0){cursor='nwse-resize';}
if(widthFactor*heightFactor<0){cursor='nesw-resize';}
resizer.setCursor(cursor);resizer.addEventListener(ResizerWidget.Events.ResizeStart,this._onResizeStart,this);resizer.addEventListener(ResizerWidget.Events.ResizeUpdate,this._onResizeUpdate.bind(this,widthFactor,heightFactor));resizer.addEventListener(ResizerWidget.Events.ResizeEnd,this._onResizeEnd,this);return resizer;}
_onResizeStart(event){this._slowPositionStart=null;this._resizeStart=this._model.screenRect().size();}
_onResizeUpdate(widthFactor,heightFactor,event){if(event.data.shiftKey!==!!this._slowPositionStart){this._slowPositionStart=event.data.shiftKey?{x:event.data.currentX,y:event.data.currentY}:null;}
let cssOffsetX=event.data.currentX-event.data.startX;let cssOffsetY=event.data.currentY-event.data.startY;if(this._slowPositionStart){cssOffsetX=(event.data.currentX-this._slowPositionStart.x)/10+this._slowPositionStart.x-event.data.startX;cssOffsetY=(event.data.currentY-this._slowPositionStart.y)/10+this._slowPositionStart.y-event.data.startY;}
if(widthFactor){const dipOffsetX=cssOffsetX*ZoomManager.ZoomManager.instance().zoomFactor();let newWidth=this._resizeStart.width+dipOffsetX*widthFactor;newWidth=Math.round(newWidth/this._model.scale());if(newWidth>=MinDeviceSize&&newWidth<=MaxDeviceSize){this._model.setWidth(newWidth);}}
if(heightFactor){const dipOffsetY=cssOffsetY*ZoomManager.ZoomManager.instance().zoomFactor();let newHeight=this._resizeStart.height+dipOffsetY*heightFactor;newHeight=Math.round(newHeight/this._model.scale());if(newHeight>=MinDeviceSize&&newHeight<=MaxDeviceSize){this._model.setHeight(newHeight);}}}
exitHingeMode(){if(this._model){this._model.exitHingeMode();}}
_onResizeEnd(event){delete this._resizeStart;userMetrics.actionTaken(UserMetrics.Action.ResizedViewInResponsiveMode);}
_updateUI(){function applyRect(element,rect){element.style.left=rect.left+'px';element.style.top=rect.top+'px';element.style.width=rect.width+'px';element.style.height=rect.height+'px';}
if(!this.isShowing()){return;}
const zoomFactor=ZoomManager.ZoomManager.instance().zoomFactor();let callDoResize=false;const showRulers=this._showRulersSetting.get()&&this._model.type()!==Type$1.None;let contentAreaResized=false;let updateRulers=false;const cssScreenRect=this._model.screenRect().scale(1/zoomFactor);if(!cssScreenRect.isEqual(this._cachedCssScreenRect)){applyRect(this._screenArea,cssScreenRect);updateRulers=true;callDoResize=true;this._cachedCssScreenRect=cssScreenRect;}
const cssVisiblePageRect=this._model.visiblePageRect().scale(1/zoomFactor);if(!cssVisiblePageRect.isEqual(this._cachedCssVisiblePageRect)){applyRect(this._pageArea,cssVisiblePageRect);callDoResize=true;this._cachedCssVisiblePageRect=cssVisiblePageRect;}
const outlineRect=this._model.outlineRect().scale(1/zoomFactor);if(!outlineRect.isEqual(this._cachedOutlineRect)){applyRect(this._outlineImage,outlineRect);callDoResize=true;this._cachedOutlineRect=outlineRect;}
this._contentClip.classList.toggle('device-mode-outline-visible',!!this._model.outlineImage());const resizable=this._model.type()===Type$1.Responsive;if(resizable!==this._cachedResizable){this._rightResizerElement.classList.toggle('hidden',!resizable);this._leftResizerElement.classList.toggle('hidden',!resizable);this._bottomResizerElement.classList.toggle('hidden',!resizable);this._bottomRightResizerElement.classList.toggle('hidden',!resizable);this._bottomLeftResizerElement.classList.toggle('hidden',!resizable);this._cachedResizable=resizable;}
const mediaInspectorVisible=this._showMediaInspectorSetting.get()&&this._model.type()!==Type$1.None;if(mediaInspectorVisible!==this._cachedMediaInspectorVisible){if(mediaInspectorVisible){this._mediaInspector.show(this._mediaInspectorContainer);}else{this._mediaInspector.detach();}
contentAreaResized=true;callDoResize=true;this._cachedMediaInspectorVisible=mediaInspectorVisible;}
if(showRulers!==this._cachedShowRulers){this._contentClip.classList.toggle('device-mode-rulers-visible',showRulers);if(showRulers){this._topRuler.show(this._contentArea);this._leftRuler.show(this._contentArea);}else{this._topRuler.detach();this._leftRuler.detach();}
contentAreaResized=true;callDoResize=true;this._cachedShowRulers=showRulers;}
if(this._model.scale()!==this._cachedScale){updateRulers=true;callDoResize=true;for(const block of this._presetBlocks){block.style.width=block.__width*this._model.scale()+'px';}
this._cachedScale=this._model.scale();}
this._toolbar.update();this._loadImage(this._screenImage,this._model.screenImage());this._loadImage(this._outlineImage,this._model.outlineImage());this._mediaInspector.setAxisTransform(this._model.scale());if(callDoResize){this.doResize();}
if(updateRulers){this._topRuler.render(this._model.scale());this._leftRuler.render(this._model.scale());this._topRuler.element.positionAt(this._cachedCssScreenRect?this._cachedCssScreenRect.left:0,this._cachedCssScreenRect?this._cachedCssScreenRect.top:0);this._leftRuler.element.positionAt(this._cachedCssScreenRect?this._cachedCssScreenRect.left:0,this._cachedCssScreenRect?this._cachedCssScreenRect.top:0);}
if(contentAreaResized){this._contentAreaResized();}}
_loadImage(element,srcset){if(element.getAttribute('srcset')===srcset){return;}
element.setAttribute('srcset',srcset);if(!srcset){element.classList.toggle('hidden',true);}}
_onImageLoaded(element,success){element.classList.toggle('hidden',!success);}
setNonEmulatedAvailableSize(element){if(this._model.type()!==Type$1.None){return;}
const zoomFactor=ZoomManager.ZoomManager.instance().zoomFactor();const rect=element.getBoundingClientRect();const availableSize=new Geometry.Size(Math.max(rect.width*zoomFactor,1),Math.max(rect.height*zoomFactor,1));this._model.setAvailableSize(availableSize,availableSize);}
_contentAreaResized(){const zoomFactor=ZoomManager.ZoomManager.instance().zoomFactor();const rect=this._contentArea.getBoundingClientRect();const availableSize=new Geometry.Size(Math.max(rect.width*zoomFactor,1),Math.max(rect.height*zoomFactor,1));const preferredSize=new Geometry.Size(Math.max((rect.width-2*this._handleWidth)*zoomFactor,1),Math.max((rect.height-this._handleHeight)*zoomFactor,1));this._model.setAvailableSize(availableSize,preferredSize);}
_measureHandles(){const hidden=this._rightResizerElement.classList.contains('hidden');this._rightResizerElement.classList.toggle('hidden',false);this._bottomResizerElement.classList.toggle('hidden',false);this._handleWidth=this._rightResizerElement.offsetWidth;this._handleHeight=this._bottomResizerElement.offsetHeight;this._rightResizerElement.classList.toggle('hidden',hidden);this._bottomResizerElement.classList.toggle('hidden',hidden);}
_zoomChanged(){delete this._handleWidth;delete this._handleHeight;if(this.isShowing()){this._measureHandles();this._contentAreaResized();}}
onResize(){if(this.isShowing()){this._contentAreaResized();}}
wasShown(){this._measureHandles();this._toolbar.restore();}
willHide(){this._model.emulate(Type$1.None,null,null);}
async captureScreenshot(){const screenshot=await this._model.captureScreenshot(false);if(screenshot===null){return;}
const pageImage=new Image();pageImage.src='data:image/png;base64,'+screenshot;pageImage.onload=async()=>{const scale=pageImage.naturalWidth/this._model.screenRect().width;const outlineRect=this._model.outlineRect().scale(scale);const screenRect=this._model.screenRect().scale(scale);const visiblePageRect=this._model.visiblePageRect().scale(scale);const contentLeft=screenRect.left+visiblePageRect.left-outlineRect.left;const contentTop=screenRect.top+visiblePageRect.top-outlineRect.top;const canvas=createElement('canvas');canvas.width=Math.floor(outlineRect.width);canvas.height=Math.floor(outlineRect.height);const ctx=canvas.getContext('2d');ctx.imageSmoothingEnabled=false;if(this._model.outlineImage()){await this._paintImage(ctx,this._model.outlineImage(),outlineRect.relativeTo(outlineRect));}
if(this._model.screenImage()){await this._paintImage(ctx,this._model.screenImage(),screenRect.relativeTo(outlineRect));}
ctx.drawImage(pageImage,Math.floor(contentLeft),Math.floor(contentTop));this._saveScreenshot(canvas);};}
async captureFullSizeScreenshot(){const screenshot=await this._model.captureScreenshot(true);if(screenshot===null){return;}
return this._saveScreenshotBase64(screenshot);}
async captureAreaScreenshot(clip){const screenshot=await this._model.captureScreenshot(false,clip);if(screenshot===null){return;}
return this._saveScreenshotBase64(screenshot);}
_saveScreenshotBase64(screenshot){const pageImage=new Image();pageImage.src='data:image/png;base64,'+screenshot;pageImage.onload=()=>{const canvas=createElement('canvas');canvas.width=pageImage.naturalWidth;canvas.height=pageImage.naturalHeight;const ctx=canvas.getContext('2d');ctx.imageSmoothingEnabled=false;ctx.drawImage(pageImage,0,0);this._saveScreenshot(canvas);};}
_paintImage(ctx,src,rect){return new Promise(fulfill=>{const image=new Image();image.crossOrigin='Anonymous';image.srcset=src;image.onerror=fulfill;image.onload=()=>{ctx.drawImage(image,rect.left,rect.top,rect.width,rect.height);fulfill();};});}
_saveScreenshot(canvas){const url=this._model.inspectedURL();let fileName=url?StringUtilities.trimURL(url).removeURLFragment():'';if(this._model.type()===Type$1.Device){fileName+=UIString.UIString('(%s)',this._model.device().title);}
const link=createElement('a');link.download=fileName+'.png';canvas.toBlob(blob=>{link.href=URL.createObjectURL(blob);link.click();});}}
class Ruler extends Widget.VBox{constructor(horizontal,applyCallback){super();this.element.classList.add('device-mode-ruler');this._contentElement=this.element.createChild('div','device-mode-ruler-content').createChild('div','device-mode-ruler-inner');this._horizontal=horizontal;this._scale=1;this._count=0;this._throttler=new Throttler.Throttler(0);this._applyCallback=applyCallback;}
render(scale){this._scale=scale;this._throttler.schedule(this._update.bind(this));}
onResize(){this._throttler.schedule(this._update.bind(this));}
_update(){const zoomFactor=ZoomManager.ZoomManager.instance().zoomFactor();const size=this._horizontal?this._contentElement.offsetWidth:this._contentElement.offsetHeight;if(this._scale!==this._renderedScale||zoomFactor!==this._renderedZoomFactor){this._contentElement.removeChildren();this._count=0;this._renderedScale=this._scale;this._renderedZoomFactor=zoomFactor;}
const dipSize=size*zoomFactor/this._scale;const count=Math.ceil(dipSize/5);let step=1;if(this._scale<0.8){step=2;}
if(this._scale<0.6){step=4;}
if(this._scale<0.4){step=8;}
if(this._scale<0.2){step=16;}
if(this._scale<0.1){step=32;}
for(let i=count;i<this._count;i++){if(!(i%step)){this._contentElement.lastChild.remove();}}
for(let i=this._count;i<count;i++){if(i%step){continue;}
const marker=this._contentElement.createChild('div','device-mode-ruler-marker');if(i){if(this._horizontal){marker.style.left=(5*i)*this._scale/zoomFactor+'px';}else{marker.style.top=(5*i)*this._scale/zoomFactor+'px';}
if(!(i%20)){const text=marker.createChild('div','device-mode-ruler-text');text.textContent=i*5;text.addEventListener('click',this._onMarkerClick.bind(this,i*5),false);}}
if(!(i%10)){marker.classList.add('device-mode-ruler-marker-large');}else if(!(i%5)){marker.classList.add('device-mode-ruler-marker-medium');}}
this._count=count;return Promise.resolve();}
_onMarkerClick(size){this._applyCallback.call(null,size);}}
var DeviceModeView$1=Object.freeze({__proto__:null,DeviceModeView:DeviceModeView,Ruler:Ruler});class InspectedPagePlaceholder extends Widget.Widget{constructor(){super(true);this.registerRequiredCSS('emulation/inspectedPagePlaceholder.css');ZoomManager.ZoomManager.instance().addEventListener(ZoomManager.Events.ZoomChanged,this.onResize,this);this.restoreMinimumSize();}
onResize(){if(this._updateId){this.element.window().cancelAnimationFrame(this._updateId);}
this._updateId=this.element.window().requestAnimationFrame(this.update.bind(this,false));}
restoreMinimumSize(){this.setMinimumSize(150,150);}
clearMinimumSize(){this.setMinimumSize(1,1);}
_dipPageRect(){const zoomFactor=ZoomManager.ZoomManager.instance().zoomFactor();const rect=this.element.getBoundingClientRect();const bodyRect=this.element.ownerDocument.body.getBoundingClientRect();const left=Math.max(rect.left*zoomFactor,bodyRect.left*zoomFactor);const top=Math.max(rect.top*zoomFactor,bodyRect.top*zoomFactor);const bottom=Math.min(rect.bottom*zoomFactor,bodyRect.bottom*zoomFactor);const right=Math.min(rect.right*zoomFactor,bodyRect.right*zoomFactor);return{x:left,y:top,width:right-left,height:bottom-top};}
update(force){delete this._updateId;const rect=this._dipPageRect();const bounds={x:Math.round(rect.x),y:Math.round(rect.y),height:Math.max(1,Math.round(rect.height)),width:Math.max(1,Math.round(rect.width)),};if(force){--bounds.height;this.dispatchEventToListeners(Events$2.Update,bounds);++bounds.height;}
this.dispatchEventToListeners(Events$2.Update,bounds);}}
const instance=function(){return self.singleton(InspectedPagePlaceholder);};const Events$2={Update:Symbol('Update')};var InspectedPagePlaceholder$1=Object.freeze({__proto__:null,InspectedPagePlaceholder:InspectedPagePlaceholder,instance:instance,Events:Events$2});class DeviceModeWrapper extends Widget.VBox{constructor(inspectedPagePlaceholder){super();DeviceModeView.wrapperInstance=this;this._inspectedPagePlaceholder=inspectedPagePlaceholder;this._deviceModeView=null;this._toggleDeviceModeAction=self.UI.actionRegistry.action('emulation.toggle-device-mode');const model=self.singleton(DeviceModeModel);this._showDeviceModeSetting=model.enabledSetting();this._showDeviceModeSetting.setRequiresUserAction(!!Root.Runtime.queryParam('hasOtherClients'));this._showDeviceModeSetting.addChangeListener(this._update.bind(this,false));SDKModel.TargetManager.instance().addModelListener(OverlayModel.OverlayModel,OverlayModel.Events.ScreenshotRequested,this._screenshotRequestedFromOverlay,this);this._update(true);}
_toggleDeviceMode(){this._showDeviceModeSetting.set(!this._showDeviceModeSetting.get());}
_captureScreenshot(fullSize,clip){if(!this._deviceModeView){this._deviceModeView=new DeviceModeView();}
this._deviceModeView.setNonEmulatedAvailableSize(this._inspectedPagePlaceholder.element);if(fullSize){this._deviceModeView.captureFullSizeScreenshot();}else if(clip){this._deviceModeView.captureAreaScreenshot(clip);}else{this._deviceModeView.captureScreenshot();}
return true;}
_screenshotRequestedFromOverlay(event){const clip=(event.data);this._captureScreenshot(false,clip);}
_update(force){this._toggleDeviceModeAction.setToggled(this._showDeviceModeSetting.get());if(!force){const showing=this._deviceModeView&&this._deviceModeView.isShowing();if(this._showDeviceModeSetting.get()===showing){return;}}
if(this._showDeviceModeSetting.get()){if(!this._deviceModeView){this._deviceModeView=new DeviceModeView();}
this._deviceModeView.show(this.element);this._inspectedPagePlaceholder.clearMinimumSize();this._inspectedPagePlaceholder.show(this._deviceModeView.element);}else{if(this._deviceModeView){this._deviceModeView.exitHingeMode();this._deviceModeView.detach();}
this._inspectedPagePlaceholder.restoreMinimumSize();this._inspectedPagePlaceholder.show(this.element);}}}
class ActionDelegate{handleAction(context,actionId){if(DeviceModeView.wrapperInstance){switch(actionId){case'emulation.capture-screenshot':return DeviceModeView.wrapperInstance._captureScreenshot();case'emulation.capture-node-screenshot':{const node=self.UI.context.flavor(DOMModel.DOMNode);if(!node){return true;}
async function captureClip(){const object=await node.resolveToObject();const result=await object.callFunction(function(){const rect=this.getBoundingClientRect();const docRect=this.ownerDocument.documentElement.getBoundingClientRect();return JSON.stringify({x:rect.left-docRect.left,y:rect.top-docRect.top,width:rect.width,height:rect.height,scale:1});});const clip=(JSON.parse((result.object.value)));const response=await node.domModel().target().pageAgent().invoke_getLayoutMetrics({});const page_zoom=!response[InspectorBackend.ProtocolError]&&response.visualViewport.zoom||1;clip.x*=page_zoom;clip.y*=page_zoom;clip.width*=page_zoom;clip.height*=page_zoom;DeviceModeView.wrapperInstance._captureScreenshot(false,clip);}
captureClip();return true;}
case'emulation.capture-full-height-screenshot':return DeviceModeView.wrapperInstance._captureScreenshot(true);case'emulation.toggle-device-mode':DeviceModeView.wrapperInstance._toggleDeviceMode();return true;}}
return false;}}
var DeviceModeWrapper$1=Object.freeze({__proto__:null,DeviceModeWrapper:DeviceModeWrapper,ActionDelegate:ActionDelegate});let _appInstance;class AdvancedApp{constructor(){self.Components.dockController.addEventListener(DockController.Events.BeforeDockSideChanged,this._openToolboxWindow,this);}
static _instance(){if(!_appInstance){_appInstance=new AdvancedApp();}
return _appInstance;}
presentUI(document){const rootView=new RootView.RootView();this._rootSplitWidget=new SplitWidget.SplitWidget(false,true,'InspectorView.splitViewState',555,300,true);this._rootSplitWidget.show(rootView.element);this._rootSplitWidget.setSidebarWidget(self.UI.inspectorView);this._rootSplitWidget.setDefaultFocusedChild(self.UI.inspectorView);self.UI.inspectorView.setOwnerSplit(this._rootSplitWidget);this._inspectedPagePlaceholder=instance();this._inspectedPagePlaceholder.addEventListener(Events$2.Update,this._onSetInspectedPageBounds.bind(this),this);this._deviceModeView=new DeviceModeWrapper(this._inspectedPagePlaceholder);self.Components.dockController.addEventListener(DockController.Events.BeforeDockSideChanged,this._onBeforeDockSideChange,this);self.Components.dockController.addEventListener(DockController.Events.DockSideChanged,this._onDockSideChange,this);self.Components.dockController.addEventListener(DockController.Events.AfterDockSideChanged,this._onAfterDockSideChange,this);this._onDockSideChange();console.timeStamp('AdvancedApp.attachToBody');rootView.attachToDocument(document);rootView.focus();this._inspectedPagePlaceholder.update();}
_openToolboxWindow(event){if((event.data.to)!==DockController.State.Undocked){return;}
if(this._toolboxWindow){return;}
const url=window.location.href.replace('devtools_app.html','toolbox.html');this._toolboxWindow=window.open(url,undefined);}
toolboxLoaded(toolboxDocument){UIUtils.initializeUIUtils(toolboxDocument,Settings.Settings.instance().createSetting('uiTheme','default'));UIUtils.installComponentRootStyles((toolboxDocument.body));ContextMenu.ContextMenu.installHandler(toolboxDocument);Tooltip.Tooltip.installHandler(toolboxDocument);this._toolboxRootView=new RootView.RootView();this._toolboxRootView.attachToDocument(toolboxDocument);this._updateDeviceModeView();}
_updateDeviceModeView(){if(this._isDocked()){this._rootSplitWidget.setMainWidget(this._deviceModeView);}else if(this._toolboxRootView){this._deviceModeView.show(this._toolboxRootView.element);}}
_onBeforeDockSideChange(event){if((event.data.to)===DockController.State.Undocked&&this._toolboxRootView){this._rootSplitWidget.hideSidebar();this._inspectedPagePlaceholder.update();}
this._changingDockSide=true;}
_onDockSideChange(event){this._updateDeviceModeView();const toDockSide=event?(event.data.to):self.Components.dockController.dockSide();if(toDockSide===DockController.State.Undocked){this._updateForUndocked();}else if(this._toolboxRootView&&event&&(event.data.from)===DockController.State.Undocked){this._rootSplitWidget.hideSidebar();}else{this._updateForDocked(toDockSide);}}
_onAfterDockSideChange(event){if(!this._changingDockSide){return;}
if((event.data.from)===DockController.State.Undocked){this._updateForDocked((event.data.to));}
this._changingDockSide=false;this._inspectedPagePlaceholder.update();}
_updateForDocked(dockSide){this._rootSplitWidget.resizerElement().style.transform=dockSide===DockController.State.DockedToRight?'translateX(2px)':dockSide===DockController.State.DockedToLeft?'translateX(-2px)':'';this._rootSplitWidget.setVertical(dockSide===DockController.State.DockedToRight||dockSide===DockController.State.DockedToLeft);this._rootSplitWidget.setSecondIsSidebar(dockSide===DockController.State.DockedToRight||dockSide===DockController.State.DockedToBottom);this._rootSplitWidget.toggleResizer(this._rootSplitWidget.resizerElement(),true);this._rootSplitWidget.toggleResizer(self.UI.inspectorView.topResizerElement(),dockSide===DockController.State.DockedToBottom);this._rootSplitWidget.showBoth();}
_updateForUndocked(){this._rootSplitWidget.toggleResizer(this._rootSplitWidget.resizerElement(),false);this._rootSplitWidget.toggleResizer(self.UI.inspectorView.topResizerElement(),false);this._rootSplitWidget.hideMain();}
_isDocked(){return self.Components.dockController.dockSide()!==DockController.State.Undocked;}
_onSetInspectedPageBounds(event){if(this._changingDockSide){return;}
const window=this._inspectedPagePlaceholder.element.window();if(!window.innerWidth||!window.innerHeight){return;}
if(!this._inspectedPagePlaceholder.isShowing()){return;}
const bounds=(event.data);console.timeStamp('AdvancedApp.setInspectedPageBounds');InspectorFrontendHost.InspectorFrontendHostInstance.setInspectedPageBounds(bounds);}}
class AdvancedAppProvider{createApp(){return AdvancedApp._instance();}}
var AdvancedApp$1=Object.freeze({__proto__:null,AdvancedApp:AdvancedApp,AdvancedAppProvider:AdvancedAppProvider});class DevicesSettingsTab extends Widget.VBox{constructor(){super();this.element.classList.add('settings-tab-container');this.element.classList.add('devices-settings-tab');this.registerRequiredCSS('emulation/devicesSettingsTab.css');const header=this.element.createChild('header');header.createChild('h1').createTextChild(ls`Emulated Devices`);this.containerElement=this.element.createChild('div','settings-container-wrapper').createChild('div','settings-tab settings-content settings-container');const buttonsRow=this.containerElement.createChild('div','devices-button-row');this._addCustomButton=UIUtils.createTextButton(UIString.UIString('Add custom device...'),this._addCustomDevice.bind(this));buttonsRow.appendChild(this._addCustomButton);this._list=new ListWidget.ListWidget(this,false);this._list.registerRequiredCSS('emulation/devicesSettingsTab.css');this._list.element.classList.add('devices-list');this._list.show(this.containerElement);this._muteUpdate=false;this._emulatedDevicesList=EmulatedDevicesList.instance();this._emulatedDevicesList.addEventListener(Events.CustomDevicesUpdated,this._devicesUpdated,this);this._emulatedDevicesList.addEventListener(Events.StandardDevicesUpdated,this._devicesUpdated,this);this.setDefaultFocusedElement(this._addCustomButton);}
wasShown(){super.wasShown();this._devicesUpdated();}
_devicesUpdated(){if(this._muteUpdate){return;}
this._list.clear();let devices=this._emulatedDevicesList.custom().slice();for(let i=0;i<devices.length;++i){this._list.appendItem(devices[i],true);}
this._list.appendSeparator();devices=this._emulatedDevicesList.standard().slice();devices.sort(EmulatedDevice.deviceComparator);for(let i=0;i<devices.length;++i){this._list.appendItem(devices[i],false);}}
_muteAndSaveDeviceList(custom){this._muteUpdate=true;if(custom){this._emulatedDevicesList.saveCustomDevices();}else{this._emulatedDevicesList.saveStandardDevices();}
this._muteUpdate=false;}
_addCustomDevice(){const device=new EmulatedDevice();device.deviceScaleFactor=0;device.horizontal.width=700;device.horizontal.height=400;device.vertical.width=400;device.vertical.height=700;this._list.addNewItem(this._emulatedDevicesList.custom().length,device);}
_toNumericInputValue(value){return value?String(value):'';}
renderItem(item,editable){const device=(item);const label=document.createElement('label');label.classList.add('devices-list-item');const checkbox=label.createChild('input','devices-list-checkbox');checkbox.type='checkbox';checkbox.checked=device.show();checkbox.addEventListener('click',onItemClicked.bind(this),false);label.appendChild(document.createTextNode(device.title));return label;function onItemClicked(event){const show=checkbox.checked;device.setShow(show);this._muteAndSaveDeviceList(editable);event.consume();}}
removeItemRequested(item,index){this._emulatedDevicesList.removeCustomDevice((item));}
commitEdit(item,editor,isNew){const device=(item);device.title=editor.control('title').value.trim();device.vertical.width=editor.control('width').value?parseInt(editor.control('width').value,10):0;device.vertical.height=editor.control('height').value?parseInt(editor.control('height').value,10):0;device.horizontal.width=device.vertical.height;device.horizontal.height=device.vertical.width;device.deviceScaleFactor=editor.control('scale').value?parseFloat(editor.control('scale').value):0;device.userAgent=editor.control('user-agent').value;device.modes=[];device.modes.push({title:'',orientation:Vertical,insets:new Geometry.Insets(0,0,0,0),image:null});device.modes.push({title:'',orientation:Horizontal,insets:new Geometry.Insets(0,0,0,0),image:null});device.capabilities=[];const uaType=editor.control('ua-type').value;if(uaType===UA.Mobile||uaType===UA.MobileNoTouch){device.capabilities.push(Capability.Mobile);}
if(uaType===UA.Mobile||uaType===UA.DesktopTouch){device.capabilities.push(Capability.Touch);}
if(isNew){this._emulatedDevicesList.addCustomDevice(device);}else{this._emulatedDevicesList.saveCustomDevices();}
this._addCustomButton.scrollIntoViewIfNeeded();this._addCustomButton.focus();}
beginEdit(item){const device=(item);const editor=this._createEditor();editor.control('title').value=device.title;editor.control('width').value=this._toNumericInputValue(device.vertical.width);editor.control('height').value=this._toNumericInputValue(device.vertical.height);editor.control('scale').value=this._toNumericInputValue(device.deviceScaleFactor);editor.control('user-agent').value=device.userAgent;let uaType;if(device.mobile()){uaType=device.touch()?UA.Mobile:UA.MobileNoTouch;}else{uaType=device.touch()?UA.DesktopTouch:UA.Desktop;}
editor.control('ua-type').value=uaType;return editor;}
_createEditor(){if(this._editor){return this._editor;}
const editor=new ListWidget.Editor();this._editor=editor;const content=editor.contentElement();const fields=content.createChild('div','devices-edit-fields');fields.createChild('div','hbox').appendChild(editor.createInput('title','text',ls`Device Name`,titleValidator));const screen=fields.createChild('div','hbox');screen.appendChild(editor.createInput('width','text',ls`Width`,widthValidator));screen.appendChild(editor.createInput('height','text',ls`Height`,heightValidator));const dpr=editor.createInput('scale','text',ls`Device pixel ratio`,scaleValidator);dpr.classList.add('device-edit-fixed');screen.appendChild(dpr);const ua=fields.createChild('div','hbox');ua.appendChild(editor.createInput('user-agent','text',ls`User agent string`,()=>{return{valid:true};}));const uaTypeOptions=[UA.Mobile,UA.MobileNoTouch,UA.Desktop,UA.DesktopTouch];const uaType=editor.createSelect('ua-type',uaTypeOptions,()=>{return{valid:true};},ls`User agent type`);uaType.classList.add('device-edit-fixed');ua.appendChild(uaType);return editor;function titleValidator(item,index,input){let valid=false;let errorMessage;const value=input.value.trim();if(value.length>=MaxDeviceNameLength){errorMessage=ls`Device name must be less than ${MaxDeviceNameLength} characters.`;}else if(value.length===0){errorMessage=ls`Device name cannot be empty.`;}else{valid=true;}
return{valid,errorMessage};}
function widthValidator(item,index,input){return DeviceModeModel.widthValidator(input.value);}
function heightValidator(item,index,input){return DeviceModeModel.heightValidator(input.value);}
function scaleValidator(item,index,input){return DeviceModeModel.scaleValidator(input.value);}}}
var DevicesSettingsTab$1=Object.freeze({__proto__:null,DevicesSettingsTab:DevicesSettingsTab});class SensorsView extends Widget.VBox{constructor(){super(true);this.registerRequiredCSS('emulation/sensors.css');this.contentElement.classList.add('sensors-view');this._LocationSetting=Settings.Settings.instance().createSetting('emulation.locationOverride','');this._Location=EmulationModel.Location.parseSetting(this._LocationSetting.get());this._LocationOverrideEnabled=false;this._createLocationSection(this._Location);this.contentElement.createChild('div').classList.add('panel-section-separator');this._deviceOrientationSetting=Settings.Settings.instance().createSetting('emulation.deviceOrientationOverride','');this._deviceOrientation=EmulationModel.DeviceOrientation.parseSetting(this._deviceOrientationSetting.get());this._deviceOrientationOverrideEnabled=false;this._createDeviceOrientationSection();this.contentElement.createChild('div').classList.add('panel-section-separator');this._appendTouchControl();}
static instance(){if(!SensorsView._instanceObject){SensorsView._instanceObject=new SensorsView();}
return SensorsView._instanceObject;}
_createLocationSection(location){const geogroup=this.contentElement.createChild('section','sensors-group');const geogroupTitle=UIUtils.createLabel(ls`Location`,'sensors-group-title');geogroup.appendChild(geogroupTitle);const fields=geogroup.createChild('div','geo-fields');let selectedIndex=0;const noOverrideOption={title:UIString.UIString('No override'),location:NonPresetOptions.NoOverride};this._locationSelectElement=fields.createChild('select','chrome-select');ARIAUtils.bindLabelToControl(geogroupTitle,this._locationSelectElement);this._locationSelectElement.appendChild(new Option(noOverrideOption.title,noOverrideOption.location));this._customLocationsGroup=this._locationSelectElement.createChild('optgroup');this._customLocationsGroup.label=ls`Overrides`;const customLocations=Settings.Settings.instance().moduleSetting('emulation.locations');const manageButton=UIUtils.createTextButton(ls`Manage`,()=>Revealer.reveal(customLocations));ARIAUtils.setAccessibleName(manageButton,ls`Manage the list of locations`);fields.appendChild(manageButton);const fillCustomSettings=()=>{this._customLocationsGroup.removeChildren();for(const[i,customLocation]of customLocations.get().entries()){this._customLocationsGroup.appendChild(new Option(customLocation.title,JSON.stringify(customLocation)));if(location.latitude===customLocation.lat&&location.longitude===customLocation.long){selectedIndex=i+1;}}};customLocations.addChangeListener(fillCustomSettings);fillCustomSettings();const customLocationOption={title:UIString.UIString('Other…'),location:NonPresetOptions.Custom};this._locationSelectElement.appendChild(new Option(customLocationOption.title,customLocationOption.location));const group=this._locationSelectElement.createChild('optgroup');group.label=ls`Error`;group.appendChild(new Option(ls`Location unavailable`,NonPresetOptions.Unavailable));this._locationSelectElement.selectedIndex=selectedIndex;this._locationSelectElement.addEventListener('change',this._LocationSelectChanged.bind(this));this._fieldsetElement=fields.createChild('fieldset');this._fieldsetElement.disabled=!this._LocationOverrideEnabled;this._fieldsetElement.id='location-override-section';const latitudeGroup=this._fieldsetElement.createChild('div','latlong-group');const longitudeGroup=this._fieldsetElement.createChild('div','latlong-group');const timezoneGroup=this._fieldsetElement.createChild('div','latlong-group');const localeGroup=this._fieldsetElement.createChild('div','latlong-group');const cmdOrCtrl=Platform.isMac()?'\u2318':'Ctrl';const modifierKeyMessage=ls`Adjust with mousewheel or up/down keys. ${cmdOrCtrl}: ±10, Shift: ±1, Alt: ±0.01`;this._latitudeInput=UIUtils.createInput('','number');latitudeGroup.appendChild(this._latitudeInput);this._latitudeInput.setAttribute('step','any');this._latitudeInput.value=0;this._latitudeSetter=UIUtils.bindInput(this._latitudeInput,this._applyLocationUserInput.bind(this),EmulationModel.Location.latitudeValidator,true,0.1);this._latitudeSetter(String(location.latitude));this._latitudeInput.title=modifierKeyMessage;latitudeGroup.appendChild(UIUtils.createLabel(ls`Latitude`,'latlong-title',this._latitudeInput));this._longitudeInput=UIUtils.createInput('','number');longitudeGroup.appendChild(this._longitudeInput);this._longitudeInput.setAttribute('step','any');this._longitudeInput.value=0;this._longitudeSetter=UIUtils.bindInput(this._longitudeInput,this._applyLocationUserInput.bind(this),EmulationModel.Location.longitudeValidator,true,0.1);this._longitudeSetter(String(location.longitude));this._longitudeInput.title=modifierKeyMessage;longitudeGroup.appendChild(UIUtils.createLabel(ls`Longitude`,'latlong-title',this._longitudeInput));this._timezoneInput=UIUtils.createInput('','text');timezoneGroup.appendChild(this._timezoneInput);this._timezoneInput.value='Europe/Berlin';this._timezoneSetter=UIUtils.bindInput(this._timezoneInput,this._applyLocationUserInput.bind(this),EmulationModel.Location.timezoneIdValidator,false);this._timezoneSetter(location.timezoneId);timezoneGroup.appendChild(UIUtils.createLabel(ls`Timezone ID`,'timezone-title',this._timezoneInput));this._timezoneError=timezoneGroup.createChild('div','timezone-error');this._localeInput=UIUtils.createInput('','text');localeGroup.appendChild(this._localeInput);this._localeInput.value='en-US';this._localeSetter=UIUtils.bindInput(this._localeInput,this._applyLocationUserInput.bind(this),EmulationModel.Location.localeValidator,false);this._localeSetter(location.locale);localeGroup.appendChild(UIUtils.createLabel(ls`Locale`,'locale-title',this._localeInput));this._localeError=localeGroup.createChild('div','locale-error');}
_LocationSelectChanged(){this._fieldsetElement.disabled=false;this._timezoneError.textContent='';const value=this._locationSelectElement.options[this._locationSelectElement.selectedIndex].value;if(value===NonPresetOptions.NoOverride){this._LocationOverrideEnabled=false;this._clearFieldsetElementInputs();this._fieldsetElement.disabled=true;}else if(value===NonPresetOptions.Custom){this._LocationOverrideEnabled=true;const location=EmulationModel.Location.parseUserInput(this._latitudeInput.value.trim(),this._longitudeInput.value.trim(),this._timezoneInput.value.trim(),this._localeInput.value.trim());if(!location){return;}
this._Location=location;}else if(value===NonPresetOptions.Unavailable){this._LocationOverrideEnabled=true;this._Location=new EmulationModel.Location(0,0,'','',true);}else{this._LocationOverrideEnabled=true;const coordinates=JSON.parse(value);this._Location=new EmulationModel.Location(coordinates.lat,coordinates.long,coordinates.timezoneId,coordinates.locale,false);this._latitudeSetter(coordinates.lat);this._longitudeSetter(coordinates.long);this._timezoneSetter(coordinates.timezoneId);this._localeSetter(coordinates.locale);}
this._applyLocation();if(value===NonPresetOptions.Custom){this._latitudeInput.focus();}}
_applyLocationUserInput(){const location=EmulationModel.Location.parseUserInput(this._latitudeInput.value.trim(),this._longitudeInput.value.trim(),this._timezoneInput.value.trim(),this._localeInput.value.trim());if(!location){return;}
this._timezoneError.textContent='';this._setSelectElementLabel(this._locationSelectElement,NonPresetOptions.Custom);this._Location=location;this._applyLocation();}
_applyLocation(){if(this._LocationOverrideEnabled){this._LocationSetting.set(this._Location.toSetting());}else{this._LocationSetting.remove();}
for(const emulationModel of SDKModel.TargetManager.instance().models(EmulationModel.EmulationModel)){emulationModel.emulateLocation(this._LocationOverrideEnabled?this._Location:null).catch(err=>{switch(err.type){case'emulation-set-timezone':{this._timezoneError.textContent=err.message;break;}
case'emulation-set-locale':{this._localeError.textContent=err.message;break;}}});}}
_clearFieldsetElementInputs(){this._latitudeSetter(0);this._longitudeSetter(0);this._timezoneSetter('');this._localeSetter('');}
_createDeviceOrientationSection(){const orientationGroup=this.contentElement.createChild('section','sensors-group');const orientationTitle=UIUtils.createLabel(ls`Orientation`,'sensors-group-title');orientationGroup.appendChild(orientationTitle);const orientationContent=orientationGroup.createChild('div','orientation-content');const fields=orientationContent.createChild('div','orientation-fields');const orientationOffOption={title:UIString.UIString('Off'),orientation:NonPresetOptions.NoOverride};const customOrientationOption={title:UIString.UIString('Custom orientation'),orientation:NonPresetOptions.Custom,};this._orientationSelectElement=this.contentElement.createChild('select','chrome-select');ARIAUtils.bindLabelToControl(orientationTitle,this._orientationSelectElement);this._orientationSelectElement.appendChild(new Option(orientationOffOption.title,orientationOffOption.orientation));this._orientationSelectElement.appendChild(new Option(customOrientationOption.title,customOrientationOption.orientation));const orientationGroups=PresetOrientations;for(let i=0;i<orientationGroups.length;++i){const groupElement=this._orientationSelectElement.createChild('optgroup');groupElement.label=orientationGroups[i].title;const group=orientationGroups[i].value;for(let j=0;j<group.length;++j){groupElement.appendChild(new Option(group[j].title,group[j].orientation));}}
this._orientationSelectElement.selectedIndex=0;fields.appendChild(this._orientationSelectElement);this._orientationSelectElement.addEventListener('change',this._orientationSelectChanged.bind(this));this._deviceOrientationFieldset=this._createDeviceOrientationOverrideElement(this._deviceOrientation);this._stageElement=orientationContent.createChild('div','orientation-stage');this._orientationLayer=this._stageElement.createChild('div','orientation-layer');this._boxElement=this._orientationLayer.createChild('section','orientation-box orientation-element');this._boxElement.createChild('section','orientation-front orientation-element');this._boxElement.createChild('section','orientation-top orientation-element');this._boxElement.createChild('section','orientation-back orientation-element');this._boxElement.createChild('section','orientation-left orientation-element');this._boxElement.createChild('section','orientation-right orientation-element');this._boxElement.createChild('section','orientation-bottom orientation-element');UIUtils.installDragHandle(this._stageElement,this._onBoxDragStart.bind(this),event=>{this._onBoxDrag(event);},null,'-webkit-grabbing','-webkit-grab');fields.appendChild(this._deviceOrientationFieldset);this._enableOrientationFields(true);this._setBoxOrientation(this._deviceOrientation,false);}
_enableOrientationFields(disable){if(disable){this._deviceOrientationFieldset.disabled=true;this._stageElement.classList.add('disabled');this._stageElement.title=ls`Enable orientation to rotate`;}else{this._deviceOrientationFieldset.disabled=false;this._stageElement.classList.remove('disabled');this._stageElement.title=ls`Shift+drag horizontally to rotate around the y-axis`;}}
_orientationSelectChanged(){const value=this._orientationSelectElement.options[this._orientationSelectElement.selectedIndex].value;this._enableOrientationFields(false);if(value===NonPresetOptions.NoOverride){this._deviceOrientationOverrideEnabled=false;this._enableOrientationFields(true);}else if(value===NonPresetOptions.Custom){this._deviceOrientationOverrideEnabled=true;this._alphaElement.focus();}else{const parsedValue=JSON.parse(value);this._deviceOrientationOverrideEnabled=true;this._deviceOrientation=new EmulationModel.DeviceOrientation(parsedValue[0],parsedValue[1],parsedValue[2]);this._setDeviceOrientation(this._deviceOrientation,DeviceOrientationModificationSource.SelectPreset);}}
_applyDeviceOrientation(){if(this._deviceOrientationOverrideEnabled){this._deviceOrientationSetting.set(this._deviceOrientation.toSetting());}
for(const emulationModel of SDKModel.TargetManager.instance().models(EmulationModel.EmulationModel)){emulationModel.emulateDeviceOrientation(this._deviceOrientationOverrideEnabled?this._deviceOrientation:null);}}
_setSelectElementLabel(selectElement,labelValue){const optionValues=Array.prototype.map.call(selectElement.options,x=>x.value);selectElement.selectedIndex=optionValues.indexOf(labelValue);}
_applyDeviceOrientationUserInput(){this._setDeviceOrientation(EmulationModel.DeviceOrientation.parseUserInput(this._alphaElement.value.trim(),this._betaElement.value.trim(),this._gammaElement.value.trim()),DeviceOrientationModificationSource.UserInput);this._setSelectElementLabel(this._orientationSelectElement,NonPresetOptions.Custom);}
_resetDeviceOrientation(){this._setDeviceOrientation(new EmulationModel.DeviceOrientation(0,90,0),DeviceOrientationModificationSource.ResetButton);this._setSelectElementLabel(this._orientationSelectElement,'[0, 90, 0]');}
_setDeviceOrientation(deviceOrientation,modificationSource){if(!deviceOrientation){return;}
function roundAngle(angle){return Math.round(angle*10000)/10000;}
if(modificationSource!==DeviceOrientationModificationSource.UserInput){this._alphaSetter(roundAngle(deviceOrientation.alpha));this._betaSetter(roundAngle(deviceOrientation.beta));this._gammaSetter(roundAngle(deviceOrientation.gamma));}
const animate=modificationSource!==DeviceOrientationModificationSource.UserDrag;this._setBoxOrientation(deviceOrientation,animate);this._deviceOrientation=deviceOrientation;this._applyDeviceOrientation();ARIAUtils.alert(ls`Device orientation set to alpha: ${deviceOrientation.alpha}, beta: ${deviceOrientation.beta}, gamma: ${
            deviceOrientation.gamma}`,this._orientationSelectElement);}
_createAxisInput(parentElement,input,label){const div=parentElement.createChild('div','orientation-axis-input-container');div.appendChild(input);div.appendChild(UIUtils.createLabel(label,'',input));input.type='number';return UIUtils.bindInput(input,this._applyDeviceOrientationUserInput.bind(this),EmulationModel.DeviceOrientation.validator,true);}
_createDeviceOrientationOverrideElement(deviceOrientation){const fieldsetElement=createElement('fieldset');fieldsetElement.classList.add('device-orientation-override-section');const cellElement=fieldsetElement.createChild('td','orientation-inputs-cell');this._alphaElement=UIUtils.createInput();this._alphaElement.setAttribute('step','any');this._alphaSetter=this._createAxisInput(cellElement,this._alphaElement,UIString.UIString('\u03B1 (alpha)'));this._alphaSetter(String(deviceOrientation.alpha));this._betaElement=UIUtils.createInput();this._betaElement.setAttribute('step','any');this._betaSetter=this._createAxisInput(cellElement,this._betaElement,UIString.UIString('\u03B2 (beta)'));this._betaSetter(String(deviceOrientation.beta));this._gammaElement=UIUtils.createInput();this._gammaElement.setAttribute('step','any');this._gammaSetter=this._createAxisInput(cellElement,this._gammaElement,UIString.UIString('\u03B3 (gamma)'));this._gammaSetter(String(deviceOrientation.gamma));const resetButton=UIUtils.createTextButton(UIString.UIString('Reset'),this._resetDeviceOrientation.bind(this),'orientation-reset-button');ARIAUtils.setAccessibleName(resetButton,ls`Reset device orientation`);resetButton.setAttribute('type','reset');cellElement.appendChild(resetButton);return fieldsetElement;}
_setBoxOrientation(deviceOrientation,animate){if(animate){this._stageElement.classList.add('is-animating');}else{this._stageElement.classList.remove('is-animating');}
const matrix=new WebKitCSSMatrix();this._boxMatrix=matrix.rotate(-deviceOrientation.beta,deviceOrientation.gamma,-deviceOrientation.alpha);const eulerAngles=new Geometry.EulerAngles(deviceOrientation.alpha,deviceOrientation.beta,deviceOrientation.gamma);this._orientationLayer.style.transform=eulerAngles.toRotate3DString();}
_onBoxDrag(event){const mouseMoveVector=this._calculateRadiusVector(event.x,event.y);if(!mouseMoveVector){return true;}
event.consume(true);let axis,angle;if(event.shiftKey){axis=new Geometry.Vector(0,0,-1);angle=(this._mouseDownVector.x-mouseMoveVector.x)*ShiftDragOrientationSpeed;}else{axis=Geometry.crossProduct(this._mouseDownVector,mouseMoveVector);angle=Geometry.calculateAngle(this._mouseDownVector,mouseMoveVector);}
let currentMatrix=new WebKitCSSMatrix();currentMatrix=currentMatrix.rotate(-90,0,0).rotateAxisAngle(axis.x,axis.y,axis.z,angle).rotate(90,0,0).multiply(this._originalBoxMatrix);const eulerAngles=Geometry.EulerAngles.fromRotationMatrix(currentMatrix);const newOrientation=new EmulationModel.DeviceOrientation(-eulerAngles.alpha,-eulerAngles.beta,eulerAngles.gamma);this._setDeviceOrientation(newOrientation,DeviceOrientationModificationSource.UserDrag);this._setSelectElementLabel(this._orientationSelectElement,NonPresetOptions.Custom);return false;}
_onBoxDragStart(event){if(!this._deviceOrientationOverrideEnabled){return false;}
this._mouseDownVector=this._calculateRadiusVector(event.x,event.y);this._originalBoxMatrix=this._boxMatrix;if(!this._mouseDownVector){return false;}
event.consume(true);return true;}
_calculateRadiusVector(x,y){const rect=this._stageElement.getBoundingClientRect();const radius=Math.max(rect.width,rect.height)/2;const sphereX=(x-rect.left-rect.width/2)/radius;const sphereY=(y-rect.top-rect.height/2)/radius;const sqrSum=sphereX*sphereX+sphereY*sphereY;if(sqrSum>0.5){return new Geometry.Vector(sphereX,sphereY,0.5/Math.sqrt(sqrSum));}
return new Geometry.Vector(sphereX,sphereY,Math.sqrt(1-sqrSum));}
_appendTouchControl(){const groupElement=this.contentElement.createChild('div','sensors-group');const title=UIUtils.createLabel(ls`Touch`,'sensors-group-title');groupElement.appendChild(title);const fieldsElement=groupElement.createChild('div','sensors-group-fields');const select=fieldsElement.createChild('select','chrome-select');ARIAUtils.bindLabelToControl(title,select);select.appendChild(new Option(UIString.UIString('Device-based'),'auto'));select.appendChild(new Option(UIString.UIString('Force enabled'),'enabled'));select.addEventListener('change',applyTouch,false);const reloadWarning=groupElement.createChild('div','reload-warning hidden');reloadWarning.textContent=UIString.UIString('*Requires reload');ARIAUtils.markAsAlert(reloadWarning);function applyTouch(){for(const emulationModel of SDKModel.TargetManager.instance().models(EmulationModel.EmulationModel)){emulationModel.overrideEmulateTouch(select.value==='enabled');}
reloadWarning.classList.remove('hidden');const resourceTreeModel=SDKModel.TargetManager.instance().models(ResourceTreeModel.ResourceTreeModel)[0];if(resourceTreeModel){resourceTreeModel.once(ResourceTreeModel.Events.MainFrameNavigated).then(()=>reloadWarning.classList.add('hidden'));}}}}
const DeviceOrientationModificationSource={UserInput:'userInput',UserDrag:'userDrag',ResetButton:'resetButton',SelectPreset:'selectPreset'};const NonPresetOptions={NoOverride:'noOverride',Custom:'custom',Unavailable:'unavailable'};const PresetOrientations=[{title:ls`Presets`,value:[{title:UIString.UIString('Portrait'),orientation:'[0, 90, 0]'},{title:UIString.UIString('Portrait upside down'),orientation:'[180, -90, 0]'},{title:UIString.UIString('Landscape left'),orientation:'[0, 90, -90]'},{title:UIString.UIString('Landscape right'),orientation:'[0, 90, 90]'},{title:UIString.UIString('Display up'),orientation:'[0, 0, 0]'},{title:UIString.UIString('Display down'),orientation:'[0, 180, 0]'}]}];class ShowActionDelegate{handleAction(context,actionId){ViewManager.ViewManager.instance().showView('sensors');return true;}}
const ShiftDragOrientationSpeed=16;var SensorsView$1=Object.freeze({__proto__:null,SensorsView:SensorsView,DeviceOrientationModificationSource:DeviceOrientationModificationSource,NonPresetOptions:NonPresetOptions,PresetOrientations:PresetOrientations,ShowActionDelegate:ShowActionDelegate,ShiftDragOrientationSpeed:ShiftDragOrientationSpeed});class LocationsSettingsTab extends Widget.VBox{constructor(){super(true);this.registerRequiredCSS('emulation/locationsSettingsTab.css');this.contentElement.createChild('div','header').textContent=UIString.UIString('Custom locations');const addButton=UIUtils.createTextButton(UIString.UIString('Add location\u2026'),this._addButtonClicked.bind(this),'add-locations-button');this.contentElement.appendChild(addButton);this._list=new ListWidget.ListWidget(this);this._list.element.classList.add('locations-list');this._list.registerRequiredCSS('emulation/locationsSettingsTab.css');this._list.show(this.contentElement);this._customSetting=Settings.Settings.instance().moduleSetting('emulation.locations');this._customSetting.addChangeListener(this._locationsUpdated,this);this.setDefaultFocusedElement(addButton);}
wasShown(){super.wasShown();this._locationsUpdated();}
_locationsUpdated(){this._list.clear();const conditions=this._customSetting.get();for(let i=0;i<conditions.length;++i){this._list.appendItem(conditions[i],true);}
this._list.appendSeparator();}
_addButtonClicked(){this._list.addNewItem(this._customSetting.get().length,{title:'',lat:0,long:0,timezoneId:'',locale:''});}
renderItem(item,editable){const location=(item);const element=document.createElement('div');element.classList.add('locations-list-item');const title=element.createChild('div','locations-list-text locations-list-title');const titleText=title.createChild('div','locations-list-title-text');titleText.textContent=location.title;titleText.title=location.title;element.createChild('div','locations-list-separator');element.createChild('div','locations-list-text').textContent=location.lat;element.createChild('div','locations-list-separator');element.createChild('div','locations-list-text').textContent=location.long;element.createChild('div','locations-list-separator');element.createChild('div','locations-list-text').textContent=location.timezoneId;element.createChild('div','locations-list-separator');element.createChild('div','locations-list-text').textContent=location.locale;return element;}
removeItemRequested(item,index){const list=this._customSetting.get();list.splice(index,1);this._customSetting.set(list);}
commitEdit(item,editor,isNew){const location=(item);location.title=editor.control('title').value.trim();const lat=editor.control('lat').value.trim();location.lat=lat?parseFloat(lat):0;const long=editor.control('long').value.trim();location.long=long?parseFloat(long):0;const timezoneId=editor.control('timezoneId').value.trim();location.timezoneId=timezoneId;const locale=editor.control('locale').value.trim();location.locale=locale;const list=this._customSetting.get();if(isNew){list.push(location);}
this._customSetting.set(list);}
beginEdit(item){const location=(item);const editor=this._createEditor();editor.control('title').value=location.title;editor.control('lat').value=String(location.lat);editor.control('long').value=String(location.long);editor.control('timezoneId').value=location.timezoneId;editor.control('locale').value=location.locale;return editor;}
_createEditor(){if(this._editor){return this._editor;}
const editor=new ListWidget.Editor();this._editor=editor;const content=editor.contentElement();const titles=content.createChild('div','locations-edit-row');titles.createChild('div','locations-list-text locations-list-title').textContent=UIString.UIString('Location name');titles.createChild('div','locations-list-separator locations-list-separator-invisible');titles.createChild('div','locations-list-text').textContent=UIString.UIString('Lat');titles.createChild('div','locations-list-separator locations-list-separator-invisible');titles.createChild('div','locations-list-text').textContent=UIString.UIString('Long');titles.createChild('div','locations-list-separator locations-list-separator-invisible');titles.createChild('div','locations-list-text').textContent=UIString.UIString('Timezone ID');titles.createChild('div','locations-list-separator locations-list-separator-invisible');titles.createChild('div','locations-list-text').textContent=UIString.UIString('Locale');const fields=content.createChild('div','locations-edit-row');fields.createChild('div','locations-list-text locations-list-title locations-input-container').appendChild(editor.createInput('title','text',ls`Location name`,titleValidator));fields.createChild('div','locations-list-separator locations-list-separator-invisible');let cell=fields.createChild('div','locations-list-text locations-input-container');cell.appendChild(editor.createInput('lat','text',ls`Latitude`,latValidator));fields.createChild('div','locations-list-separator locations-list-separator-invisible');cell=fields.createChild('div','locations-list-text locations-list-text-longitude locations-input-container');cell.appendChild(editor.createInput('long','text',ls`Longitude`,longValidator));fields.createChild('div','locations-list-separator locations-list-separator-invisible');cell=fields.createChild('div','locations-list-text locations-input-container');cell.appendChild(editor.createInput('timezoneId','text',ls`Timezone ID`,timezoneIdValidator));fields.createChild('div','locations-list-separator locations-list-separator-invisible');cell=fields.createChild('div','locations-list-text locations-input-container');cell.appendChild(editor.createInput('locale','text',ls`Locale`,localeValidator));return editor;function titleValidator(item,index,input){const maxLength=50;const value=input.value.trim();let errorMessage;if(!value.length){errorMessage=ls`Location name cannot be empty`;}else if(value.length>maxLength){errorMessage=ls`Location name must be less than ${maxLength} characters`;}
if(errorMessage){return{valid:false,errorMessage};}
return{valid:true};}
function latValidator(item,index,input){const minLat=-90;const maxLat=90;const value=input.value.trim();const parsedValue=Number(value);if(!value){return{valid:true};}
let errorMessage;if(Number.isNaN(parsedValue)){errorMessage=ls`Latitude must be a number`;}else if(parseFloat(value)<minLat){errorMessage=ls`Latitude must be greater than or equal to ${minLat}`;}else if(parseFloat(value)>maxLat){errorMessage=ls`Latitude must be less than or equal to ${maxLat}`;}
if(errorMessage){return{valid:false,errorMessage};}
return{valid:true};}
function longValidator(item,index,input){const minLong=-180;const maxLong=180;const value=input.value.trim();const parsedValue=Number(value);if(!value){return{valid:true};}
let errorMessage;if(Number.isNaN(parsedValue)){errorMessage=ls`Longitude must be a number`;}else if(parseFloat(value)<minLong){errorMessage=ls`Longitude must be greater than or equal to ${minLong}`;}else if(parseFloat(value)>maxLong){errorMessage=ls`Longitude must be less than or equal to ${maxLong}`;}
if(errorMessage){return{valid:false,errorMessage};}
return{valid:true};}
function timezoneIdValidator(item,index,input){const value=input.value.trim();if(value===''||/[a-zA-Z]/.test(value)){return{valid:true};}
const errorMessage=ls`Timezone ID must contain alphabetic characters`;return{valid:false,errorMessage};}
function localeValidator(item,index,input){const value=input.value.trim();if(value===''||/[a-zA-Z]{2}/.test(value)){return{valid:true};}
const errorMessage=ls`Locale must contain alphabetic characters`;return{valid:false,errorMessage};}}}
let Item;var LocationsSettingsTab$1=Object.freeze({__proto__:null,LocationsSettingsTab:LocationsSettingsTab,Item:Item});export{AdvancedApp$1 as AdvancedApp,DeviceModeModel$1 as DeviceModeModel,DeviceModeToolbar$1 as DeviceModeToolbar,DeviceModeView$1 as DeviceModeView,DeviceModeWrapper$1 as DeviceModeWrapper,DevicesSettingsTab$1 as DevicesSettingsTab,EmulatedDevices,InspectedPagePlaceholder$1 as InspectedPagePlaceholder,LocationsSettingsTab$1 as LocationsSettingsTab,MediaQueryInspector$1 as MediaQueryInspector,SensorsView$1 as SensorsView};