-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlaunch.js
29 lines (29 loc) · 49.5 KB
/
launch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import"./strings.m.js";import{loadTimeData}from"chrome://resources/ash/common/load_time_data.m.js";mojo.internal.exportModule("mojoBase.mojom");mojoBase.mojom.UnguessableTokenSpec={$:{}};mojo.internal.Struct(mojoBase.mojom.UnguessableTokenSpec.$,"UnguessableToken",[mojo.internal.StructField("high",0,0,mojo.internal.Uint64,BigInt(0),false),mojo.internal.StructField("low",8,0,mojo.internal.Uint64,BigInt(0),false)],[[0,24]]);mojoBase.mojom.UnguessableToken=class{constructor(){this.high;this.low}};mojo.internal.exportModule("blink.mojom");blink.mojom.FileSystemAccessTransferTokenPendingReceiver=class{constructor(handle){this.handle=mojo.internal.interfaceSupport.getEndpointForReceiver(handle)}bindInBrowser(scope="context"){mojo.internal.interfaceSupport.bind(this.handle,blink.mojom.FileSystemAccessTransferToken.$interfaceName,scope)}};blink.mojom.FileSystemAccessTransferTokenRemote=class{constructor(handle=undefined){this.proxy=new mojo.internal.interfaceSupport.InterfaceRemoteBase(blink.mojom.FileSystemAccessTransferTokenPendingReceiver,handle);this.$=new mojo.internal.interfaceSupport.InterfaceRemoteBaseWrapper(this.proxy);this.onConnectionError=this.proxy.getConnectionErrorEventRouter()}getInternalID(){return this.proxy.sendMessage(0,blink.mojom.FileSystemAccessTransferToken_GetInternalID_ParamsSpec.$,blink.mojom.FileSystemAccessTransferToken_GetInternalID_ResponseParamsSpec.$,[])}clone(tokenClone){this.proxy.sendMessage(1,blink.mojom.FileSystemAccessTransferToken_Clone_ParamsSpec.$,null,[tokenClone])}};blink.mojom.FileSystemAccessTransferTokenReceiver=class{constructor(impl){this.helper_internal_=new mojo.internal.interfaceSupport.InterfaceReceiverHelperInternal(blink.mojom.FileSystemAccessTransferTokenRemote);this.$=new mojo.internal.interfaceSupport.InterfaceReceiverHelper(this.helper_internal_);this.helper_internal_.registerHandler(0,blink.mojom.FileSystemAccessTransferToken_GetInternalID_ParamsSpec.$,blink.mojom.FileSystemAccessTransferToken_GetInternalID_ResponseParamsSpec.$,impl.getInternalID.bind(impl));this.helper_internal_.registerHandler(1,blink.mojom.FileSystemAccessTransferToken_Clone_ParamsSpec.$,null,impl.clone.bind(impl));this.onConnectionError=this.helper_internal_.getConnectionErrorEventRouter()}};blink.mojom.FileSystemAccessTransferToken=class{static get $interfaceName(){return"blink.mojom.FileSystemAccessTransferToken"}static getRemote(){let remote=new blink.mojom.FileSystemAccessTransferTokenRemote;remote.$.bindNewPipeAndPassReceiver().bindInBrowser();return remote}};blink.mojom.FileSystemAccessTransferTokenCallbackRouter=class{constructor(){this.helper_internal_=new mojo.internal.interfaceSupport.InterfaceReceiverHelperInternal(blink.mojom.FileSystemAccessTransferTokenRemote);this.$=new mojo.internal.interfaceSupport.InterfaceReceiverHelper(this.helper_internal_);this.router_=new mojo.internal.interfaceSupport.CallbackRouter;this.getInternalID=new mojo.internal.interfaceSupport.InterfaceCallbackReceiver(this.router_);this.helper_internal_.registerHandler(0,blink.mojom.FileSystemAccessTransferToken_GetInternalID_ParamsSpec.$,blink.mojom.FileSystemAccessTransferToken_GetInternalID_ResponseParamsSpec.$,this.getInternalID.createReceiverHandler(true));this.clone=new mojo.internal.interfaceSupport.InterfaceCallbackReceiver(this.router_);this.helper_internal_.registerHandler(1,blink.mojom.FileSystemAccessTransferToken_Clone_ParamsSpec.$,null,this.clone.createReceiverHandler(false));this.onConnectionError=this.helper_internal_.getConnectionErrorEventRouter()}removeListener(id){return this.router_.removeListener(id)}};blink.mojom.FileSystemAccessTransferToken_GetInternalID_ParamsSpec={$:{}};blink.mojom.FileSystemAccessTransferToken_GetInternalID_ResponseParamsSpec={$:{}};blink.mojom.FileSystemAccessTransferToken_Clone_ParamsSpec={$:{}};mojo.internal.Struct(blink.mojom.FileSystemAccessTransferToken_GetInternalID_ParamsSpec.$,"FileSystemAccessTransferToken_GetInternalID_Params",[],[[0,8]]);blink.mojom.FileSystemAccessTransferToken_GetInternalID_Params=class{constructor(){}};mojo.internal.Struct(blink.mojom.FileSystemAccessTransferToken_GetInternalID_ResponseParamsSpec.$,"FileSystemAccessTransferToken_GetInternalID_ResponseParams",[mojo.internal.StructField("id",0,0,mojoBase.mojom.UnguessableTokenSpec.$,null,false)],[[0,16]]);blink.mojom.FileSystemAccessTransferToken_GetInternalID_ResponseParams=class{constructor(){this.id}};mojo.internal.Struct(blink.mojom.FileSystemAccessTransferToken_Clone_ParamsSpec.$,"FileSystemAccessTransferToken_Clone_Params",[mojo.internal.StructField("tokenClone",0,0,mojo.internal.InterfaceRequest(blink.mojom.FileSystemAccessTransferTokenPendingReceiver),null,false)],[[0,16]]);blink.mojom.FileSystemAccessTransferToken_Clone_Params=class{constructor(){this.tokenClone}};
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
const PRODUCT_NAME="ChromeOS_MediaApp";function reportCrashError(...errors){if(!errors||errors.length===0){return}let message="";for(let i=1;i<errors.length;i++){const errorArg=errors[i];if(errorArg!==undefined){if(errorArg instanceof Error){message+=`\n${errorArg.name}: ${errorArg.message}`}else if(typeof errorArg==="string"){message+=", "+errorArg}else{try{message+="\n"+JSON.stringify(errorArg)}catch(e){message+="<object loop?>"}}}}let firstError=errors[0];let errorObject;let errorMessage;let prefix="";if(firstError instanceof PromiseRejectionEvent){prefix="Unhandled rejection: ";firstError=firstError.reason}else if(typeof firstError==="object"&&firstError!==null&&firstError.constructor){prefix=firstError.constructor.name+": "}if(firstError instanceof Error||firstError instanceof ErrorEvent||firstError instanceof DOMException){errorMessage=`[${firstError.name||""}] ${firstError.message}`;errorObject=firstError;if(!errorObject.stack){errorObject.stack=(new Error).stack}}else{try{errorMessage=`Unexpected: ${JSON.stringify(firstError)}`}catch(e){errorMessage=`Unexpected: <object loop?>`}}if(!errorObject){errorObject=new Error}const params={product:PRODUCT_NAME,url:self.location.href,message:prefix+errorMessage+message,lineNumber:errorObject.lineNumber||0,stackTrace:errorObject.stack||"",columnNumber:errorObject.columnNumber||0};chrome.crashReportPrivate.reportError(params,(()=>{}))}function captureConsoleErrors(realConsoleError,report){console.error=(...errors)=>{realConsoleError(...errors);report(...errors,"(from console)")}}captureConsoleErrors(console.error,reportCrashError);window.addEventListener("error",reportCrashError);window.addEventListener("unhandledrejection",reportCrashError);const TEST_ONLY$1={reportCrashError:reportCrashError,captureConsoleErrors:captureConsoleErrors};var error_reporter=Object.freeze({__proto__:null,TEST_ONLY:TEST_ONLY$1});
// Copyright 2020 The Chromium Authors
function serializeError(error){return{message:error.message||"",name:error.name||"",stack:error.stack||""}}class NativeResolver{constructor(){this.resolve;this.reject;this.promise=new Promise(((resolve,reject)=>{this.resolve=resolve;this.reject=reject}))}}function assertCast(condition){if(!condition){throw new Error("Failed assertion")}return condition}const ReservedMessageTypes={RESPONSE_TYPE:"___response",ERROR_TYPE:"___error"};function isGeneratedMessage(messageType){return messageType.substr(0,3)==="___"}function throwIfReserved(messageType){if(isGeneratedMessage(messageType)){throw new Error(`Unexpected reserved message type: '${messageType}'`)}}class MessagePipe{constructor(targetOrigin,target,rethrowErrors=true){if(!target){const frame=document.querySelector(`iframe[src^='${targetOrigin}']`);if(!frame||!frame.contentWindow){throw new Error("Unable to locate target content window.")}target=assertCast(frame.contentWindow)}this.target_=target;this.targetOrigin_=targetOrigin;this.rethrowErrors=rethrowErrors;this.logClientError=object=>console.error(JSON.stringify(object));this.messageHandlers_=new Map;this.pendingMessages_=new Map;this.nextMessageId_=0;this.messageListener_=m=>this.receiveMessage_(m);console.assert(this.target_!==window,"target !== window");window.addEventListener("message",this.messageListener_)}registerHandler(messageType,handler){throwIfReserved(messageType);if(this.messageHandlers_.has(messageType)){throw new Error(`A handler already exists for ${messageType}`)}this.messageHandlers_.set(messageType,handler)}async sendMessage(messageType,message={}){try{return await this.sendMessageImpl(messageType,message)}catch(errorResponse){const error=new Error(`${messageType}: ${errorResponse.message}`);error.name=errorResponse.name||"Unknown Error";error.stack+=`\nError from ${this.targetOrigin_}\n${errorResponse.stack}`;throw error}}async sendMessageImpl(messageType,message={}){throwIfReserved(messageType);const messageId=this.nextMessageId_++;const resolver=new NativeResolver;this.pendingMessages_.set(messageId,resolver);this.postToTarget_(messageType,message,messageId);return resolver.promise}detach(){window.removeEventListener("message",this.messageListener_)}handleMessageResponse_(messageType,message,messageId){const{RESPONSE_TYPE:RESPONSE_TYPE,ERROR_TYPE:ERROR_TYPE}=ReservedMessageTypes;const resolver=this.pendingMessages_.get(messageId);if(messageType===RESPONSE_TYPE){resolver.resolve(message)}else if(messageType===ERROR_TYPE){this.logClientError(message);resolver.reject(message)}else{console.error(`Response for message ${messageId} received with invalid message type ${messageType}`)}this.pendingMessages_.delete(messageId)}async callHandlerForMessageType_(messageType,message,messageId){const{RESPONSE_TYPE:RESPONSE_TYPE,ERROR_TYPE:ERROR_TYPE}=ReservedMessageTypes;let response;let error=null;let sawError=false;try{response=await this.messageHandlers_.get(messageType)(message)}catch(err){sawError=true;error=err;response=serializeError(err)}this.postToTarget_(sawError?ERROR_TYPE:RESPONSE_TYPE,response,messageId);if(sawError&&this.rethrowErrors){this.logClientError(error);throw error}}receiveMessage_(event){const e=event;if(typeof e.data!=="object"||!e.data||typeof e.data.type!=="string"){return}const{messageId:messageId,type:type,message:message}=e.data;const{ERROR_TYPE:ERROR_TYPE}=ReservedMessageTypes;if(e.origin!==this.targetOrigin_&&this.targetOrigin_!=="*"){return}if(isGeneratedMessage(type)&&this.pendingMessages_.has(messageId)){this.handleMessageResponse_(type,message,messageId);return}if(isGeneratedMessage(type)){console.error(`Response with type ${type} for unknown message received.`);return}if(!this.messageHandlers_.has(type)){const error=new Error(`No handler registered for message type '${type}'`);const errorResponse=serializeError(error);this.postToTarget_(ERROR_TYPE,errorResponse,messageId);return}this.callHandlerForMessageType_(type,message,messageId)}postToTarget_(messageType,message,messageId){const messageWrapper={messageId:messageId,type:messageType,message:message||{}};this.target_.postMessage(messageWrapper,this.targetOrigin_)}}
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
const Message={DELETE_FILE:"delete-file",EDIT_IN_PHOTOS:"edit-in-photos",IFRAME_READY:"iframe-ready",IS_FILE_ARC_WRITABLE:"is-file-arc-writable",IS_FILE_BROWSER_WRITABLE:"is-file-browser-writable",LOAD_EXTRA_FILES:"load-extra-files",LOAD_FILES:"load-files",MAYBE_TRIGGER_PDF_HATS:"maybe-trigger-pdf-hats",NAVIGATE:"navigate",NOTIFY_CURRENT_FILE:"notify-current-file",OPEN_ALLOWED_FILE:"open-allowed-file",OPEN_FEEDBACK_DIALOG:"open-feedback-dialog",OPEN_FILES_WITH_PICKER:"open-files-with-picker",OPEN_IN_SANDBOXED_VIEWER:"open-in-sandboxed-viewer",OVERWRITE_FILE:"overwrite-file",RELOAD_MAIN_FRAME:"reload-main-frame",RENAME_FILE:"rename-file",REQUEST_SAVE_FILE:"request-save-file",SAVE_AS:"save-as",TOGGLE_BROWSER_FULLSCREEN_MODE:"toggle-browser-fullscreen-mode"};const RenameResult={FILE_NO_LONGER_IN_LAST_OPENED_DIRECTORY:-1,SUCCESS:0,FILE_EXISTS:1};mojo.internal.exportModule("ash.mediaAppUi.mojom");ash.mediaAppUi.mojom.PageHandlerFactoryPendingReceiver=class{constructor(handle){this.handle=mojo.internal.interfaceSupport.getEndpointForReceiver(handle)}bindInBrowser(scope="context"){mojo.internal.interfaceSupport.bind(this.handle,ash.mediaAppUi.mojom.PageHandlerFactory.$interfaceName,scope)}};ash.mediaAppUi.mojom.PageHandlerFactoryRemote=class{constructor(handle=undefined){this.proxy=new mojo.internal.interfaceSupport.InterfaceRemoteBase(ash.mediaAppUi.mojom.PageHandlerFactoryPendingReceiver,handle);this.$=new mojo.internal.interfaceSupport.InterfaceRemoteBaseWrapper(this.proxy);this.onConnectionError=this.proxy.getConnectionErrorEventRouter()}createPageHandler(handler){this.proxy.sendMessage(0,ash.mediaAppUi.mojom.PageHandlerFactory_CreatePageHandler_ParamsSpec.$,null,[handler])}};ash.mediaAppUi.mojom.PageHandlerFactoryReceiver=class{constructor(impl){this.helper_internal_=new mojo.internal.interfaceSupport.InterfaceReceiverHelperInternal(ash.mediaAppUi.mojom.PageHandlerFactoryRemote);this.$=new mojo.internal.interfaceSupport.InterfaceReceiverHelper(this.helper_internal_);this.helper_internal_.registerHandler(0,ash.mediaAppUi.mojom.PageHandlerFactory_CreatePageHandler_ParamsSpec.$,null,impl.createPageHandler.bind(impl));this.onConnectionError=this.helper_internal_.getConnectionErrorEventRouter()}};ash.mediaAppUi.mojom.PageHandlerFactory=class{static get $interfaceName(){return"ash.media_app_ui.mojom.PageHandlerFactory"}static getRemote(){let remote=new ash.mediaAppUi.mojom.PageHandlerFactoryRemote;remote.$.bindNewPipeAndPassReceiver().bindInBrowser();return remote}};ash.mediaAppUi.mojom.PageHandlerFactoryCallbackRouter=class{constructor(){this.helper_internal_=new mojo.internal.interfaceSupport.InterfaceReceiverHelperInternal(ash.mediaAppUi.mojom.PageHandlerFactoryRemote);this.$=new mojo.internal.interfaceSupport.InterfaceReceiverHelper(this.helper_internal_);this.router_=new mojo.internal.interfaceSupport.CallbackRouter;this.createPageHandler=new mojo.internal.interfaceSupport.InterfaceCallbackReceiver(this.router_);this.helper_internal_.registerHandler(0,ash.mediaAppUi.mojom.PageHandlerFactory_CreatePageHandler_ParamsSpec.$,null,this.createPageHandler.createReceiverHandler(false));this.onConnectionError=this.helper_internal_.getConnectionErrorEventRouter()}removeListener(id){return this.router_.removeListener(id)}};ash.mediaAppUi.mojom.PageHandlerPendingReceiver=class{constructor(handle){this.handle=mojo.internal.interfaceSupport.getEndpointForReceiver(handle)}bindInBrowser(scope="context"){mojo.internal.interfaceSupport.bind(this.handle,ash.mediaAppUi.mojom.PageHandler.$interfaceName,scope)}};ash.mediaAppUi.mojom.PageHandlerRemote=class{constructor(handle=undefined){this.proxy=new mojo.internal.interfaceSupport.InterfaceRemoteBase(ash.mediaAppUi.mojom.PageHandlerPendingReceiver,handle);this.$=new mojo.internal.interfaceSupport.InterfaceRemoteBaseWrapper(this.proxy);this.onConnectionError=this.proxy.getConnectionErrorEventRouter()}openFeedbackDialog(){return this.proxy.sendMessage(0,ash.mediaAppUi.mojom.PageHandler_OpenFeedbackDialog_ParamsSpec.$,ash.mediaAppUi.mojom.PageHandler_OpenFeedbackDialog_ResponseParamsSpec.$,[])}toggleBrowserFullscreenMode(){return this.proxy.sendMessage(1,ash.mediaAppUi.mojom.PageHandler_ToggleBrowserFullscreenMode_ParamsSpec.$,ash.mediaAppUi.mojom.PageHandler_ToggleBrowserFullscreenMode_ResponseParamsSpec.$,[])}maybeTriggerPdfHats(){return this.proxy.sendMessage(2,ash.mediaAppUi.mojom.PageHandler_MaybeTriggerPdfHats_ParamsSpec.$,ash.mediaAppUi.mojom.PageHandler_MaybeTriggerPdfHats_ResponseParamsSpec.$,[])}isFileArcWritable(token){return this.proxy.sendMessage(3,ash.mediaAppUi.mojom.PageHandler_IsFileArcWritable_ParamsSpec.$,ash.mediaAppUi.mojom.PageHandler_IsFileArcWritable_ResponseParamsSpec.$,[token])}isFileBrowserWritable(token){return this.proxy.sendMessage(4,ash.mediaAppUi.mojom.PageHandler_IsFileBrowserWritable_ParamsSpec.$,ash.mediaAppUi.mojom.PageHandler_IsFileBrowserWritable_ResponseParamsSpec.$,[token])}editInPhotos(token,mimeType){return this.proxy.sendMessage(5,ash.mediaAppUi.mojom.PageHandler_EditInPhotos_ParamsSpec.$,ash.mediaAppUi.mojom.PageHandler_EditInPhotos_ResponseParamsSpec.$,[token,mimeType])}};ash.mediaAppUi.mojom.PageHandlerReceiver=class{constructor(impl){this.helper_internal_=new mojo.internal.interfaceSupport.InterfaceReceiverHelperInternal(ash.mediaAppUi.mojom.PageHandlerRemote);this.$=new mojo.internal.interfaceSupport.InterfaceReceiverHelper(this.helper_internal_);this.helper_internal_.registerHandler(0,ash.mediaAppUi.mojom.PageHandler_OpenFeedbackDialog_ParamsSpec.$,ash.mediaAppUi.mojom.PageHandler_OpenFeedbackDialog_ResponseParamsSpec.$,impl.openFeedbackDialog.bind(impl));this.helper_internal_.registerHandler(1,ash.mediaAppUi.mojom.PageHandler_ToggleBrowserFullscreenMode_ParamsSpec.$,ash.mediaAppUi.mojom.PageHandler_ToggleBrowserFullscreenMode_ResponseParamsSpec.$,impl.toggleBrowserFullscreenMode.bind(impl));this.helper_internal_.registerHandler(2,ash.mediaAppUi.mojom.PageHandler_MaybeTriggerPdfHats_ParamsSpec.$,ash.mediaAppUi.mojom.PageHandler_MaybeTriggerPdfHats_ResponseParamsSpec.$,impl.maybeTriggerPdfHats.bind(impl));this.helper_internal_.registerHandler(3,ash.mediaAppUi.mojom.PageHandler_IsFileArcWritable_ParamsSpec.$,ash.mediaAppUi.mojom.PageHandler_IsFileArcWritable_ResponseParamsSpec.$,impl.isFileArcWritable.bind(impl));this.helper_internal_.registerHandler(4,ash.mediaAppUi.mojom.PageHandler_IsFileBrowserWritable_ParamsSpec.$,ash.mediaAppUi.mojom.PageHandler_IsFileBrowserWritable_ResponseParamsSpec.$,impl.isFileBrowserWritable.bind(impl));this.helper_internal_.registerHandler(5,ash.mediaAppUi.mojom.PageHandler_EditInPhotos_ParamsSpec.$,ash.mediaAppUi.mojom.PageHandler_EditInPhotos_ResponseParamsSpec.$,impl.editInPhotos.bind(impl));this.onConnectionError=this.helper_internal_.getConnectionErrorEventRouter()}};ash.mediaAppUi.mojom.PageHandler=class{static get $interfaceName(){return"ash.media_app_ui.mojom.PageHandler"}static getRemote(){let remote=new ash.mediaAppUi.mojom.PageHandlerRemote;remote.$.bindNewPipeAndPassReceiver().bindInBrowser();return remote}};ash.mediaAppUi.mojom.PageHandlerCallbackRouter=class{constructor(){this.helper_internal_=new mojo.internal.interfaceSupport.InterfaceReceiverHelperInternal(ash.mediaAppUi.mojom.PageHandlerRemote);this.$=new mojo.internal.interfaceSupport.InterfaceReceiverHelper(this.helper_internal_);this.router_=new mojo.internal.interfaceSupport.CallbackRouter;this.openFeedbackDialog=new mojo.internal.interfaceSupport.InterfaceCallbackReceiver(this.router_);this.helper_internal_.registerHandler(0,ash.mediaAppUi.mojom.PageHandler_OpenFeedbackDialog_ParamsSpec.$,ash.mediaAppUi.mojom.PageHandler_OpenFeedbackDialog_ResponseParamsSpec.$,this.openFeedbackDialog.createReceiverHandler(true));this.toggleBrowserFullscreenMode=new mojo.internal.interfaceSupport.InterfaceCallbackReceiver(this.router_);this.helper_internal_.registerHandler(1,ash.mediaAppUi.mojom.PageHandler_ToggleBrowserFullscreenMode_ParamsSpec.$,ash.mediaAppUi.mojom.PageHandler_ToggleBrowserFullscreenMode_ResponseParamsSpec.$,this.toggleBrowserFullscreenMode.createReceiverHandler(true));this.maybeTriggerPdfHats=new mojo.internal.interfaceSupport.InterfaceCallbackReceiver(this.router_);this.helper_internal_.registerHandler(2,ash.mediaAppUi.mojom.PageHandler_MaybeTriggerPdfHats_ParamsSpec.$,ash.mediaAppUi.mojom.PageHandler_MaybeTriggerPdfHats_ResponseParamsSpec.$,this.maybeTriggerPdfHats.createReceiverHandler(true));this.isFileArcWritable=new mojo.internal.interfaceSupport.InterfaceCallbackReceiver(this.router_);this.helper_internal_.registerHandler(3,ash.mediaAppUi.mojom.PageHandler_IsFileArcWritable_ParamsSpec.$,ash.mediaAppUi.mojom.PageHandler_IsFileArcWritable_ResponseParamsSpec.$,this.isFileArcWritable.createReceiverHandler(true));this.isFileBrowserWritable=new mojo.internal.interfaceSupport.InterfaceCallbackReceiver(this.router_);this.helper_internal_.registerHandler(4,ash.mediaAppUi.mojom.PageHandler_IsFileBrowserWritable_ParamsSpec.$,ash.mediaAppUi.mojom.PageHandler_IsFileBrowserWritable_ResponseParamsSpec.$,this.isFileBrowserWritable.createReceiverHandler(true));this.editInPhotos=new mojo.internal.interfaceSupport.InterfaceCallbackReceiver(this.router_);this.helper_internal_.registerHandler(5,ash.mediaAppUi.mojom.PageHandler_EditInPhotos_ParamsSpec.$,ash.mediaAppUi.mojom.PageHandler_EditInPhotos_ResponseParamsSpec.$,this.editInPhotos.createReceiverHandler(true));this.onConnectionError=this.helper_internal_.getConnectionErrorEventRouter()}removeListener(id){return this.router_.removeListener(id)}};ash.mediaAppUi.mojom.PageHandlerFactory_CreatePageHandler_ParamsSpec={$:{}};ash.mediaAppUi.mojom.PageHandler_OpenFeedbackDialog_ParamsSpec={$:{}};ash.mediaAppUi.mojom.PageHandler_OpenFeedbackDialog_ResponseParamsSpec={$:{}};ash.mediaAppUi.mojom.PageHandler_ToggleBrowserFullscreenMode_ParamsSpec={$:{}};ash.mediaAppUi.mojom.PageHandler_ToggleBrowserFullscreenMode_ResponseParamsSpec={$:{}};ash.mediaAppUi.mojom.PageHandler_MaybeTriggerPdfHats_ParamsSpec={$:{}};ash.mediaAppUi.mojom.PageHandler_MaybeTriggerPdfHats_ResponseParamsSpec={$:{}};ash.mediaAppUi.mojom.PageHandler_IsFileArcWritable_ParamsSpec={$:{}};ash.mediaAppUi.mojom.PageHandler_IsFileArcWritable_ResponseParamsSpec={$:{}};ash.mediaAppUi.mojom.PageHandler_IsFileBrowserWritable_ParamsSpec={$:{}};ash.mediaAppUi.mojom.PageHandler_IsFileBrowserWritable_ResponseParamsSpec={$:{}};ash.mediaAppUi.mojom.PageHandler_EditInPhotos_ParamsSpec={$:{}};ash.mediaAppUi.mojom.PageHandler_EditInPhotos_ResponseParamsSpec={$:{}};mojo.internal.Struct(ash.mediaAppUi.mojom.PageHandlerFactory_CreatePageHandler_ParamsSpec.$,"PageHandlerFactory_CreatePageHandler_Params",[mojo.internal.StructField("handler",0,0,mojo.internal.InterfaceRequest(ash.mediaAppUi.mojom.PageHandlerPendingReceiver),null,false)],[[0,16]]);ash.mediaAppUi.mojom.PageHandlerFactory_CreatePageHandler_Params=class{constructor(){this.handler}};mojo.internal.Struct(ash.mediaAppUi.mojom.PageHandler_OpenFeedbackDialog_ParamsSpec.$,"PageHandler_OpenFeedbackDialog_Params",[],[[0,8]]);ash.mediaAppUi.mojom.PageHandler_OpenFeedbackDialog_Params=class{constructor(){}};mojo.internal.Struct(ash.mediaAppUi.mojom.PageHandler_OpenFeedbackDialog_ResponseParamsSpec.$,"PageHandler_OpenFeedbackDialog_ResponseParams",[mojo.internal.StructField("errorMessage",0,0,mojo.internal.String,null,true)],[[0,16]]);ash.mediaAppUi.mojom.PageHandler_OpenFeedbackDialog_ResponseParams=class{constructor(){this.errorMessage}};mojo.internal.Struct(ash.mediaAppUi.mojom.PageHandler_ToggleBrowserFullscreenMode_ParamsSpec.$,"PageHandler_ToggleBrowserFullscreenMode_Params",[],[[0,8]]);ash.mediaAppUi.mojom.PageHandler_ToggleBrowserFullscreenMode_Params=class{constructor(){}};mojo.internal.Struct(ash.mediaAppUi.mojom.PageHandler_ToggleBrowserFullscreenMode_ResponseParamsSpec.$,"PageHandler_ToggleBrowserFullscreenMode_ResponseParams",[],[[0,8]]);ash.mediaAppUi.mojom.PageHandler_ToggleBrowserFullscreenMode_ResponseParams=class{constructor(){}};mojo.internal.Struct(ash.mediaAppUi.mojom.PageHandler_MaybeTriggerPdfHats_ParamsSpec.$,"PageHandler_MaybeTriggerPdfHats_Params",[],[[0,8]]);ash.mediaAppUi.mojom.PageHandler_MaybeTriggerPdfHats_Params=class{constructor(){}};mojo.internal.Struct(ash.mediaAppUi.mojom.PageHandler_MaybeTriggerPdfHats_ResponseParamsSpec.$,"PageHandler_MaybeTriggerPdfHats_ResponseParams",[],[[0,8]]);ash.mediaAppUi.mojom.PageHandler_MaybeTriggerPdfHats_ResponseParams=class{constructor(){}};mojo.internal.Struct(ash.mediaAppUi.mojom.PageHandler_IsFileArcWritable_ParamsSpec.$,"PageHandler_IsFileArcWritable_Params",[mojo.internal.StructField("token",0,0,mojo.internal.InterfaceProxy(blink.mojom.FileSystemAccessTransferTokenRemote),null,false)],[[0,16]]);ash.mediaAppUi.mojom.PageHandler_IsFileArcWritable_Params=class{constructor(){this.token}};mojo.internal.Struct(ash.mediaAppUi.mojom.PageHandler_IsFileArcWritable_ResponseParamsSpec.$,"PageHandler_IsFileArcWritable_ResponseParams",[mojo.internal.StructField("writable",0,0,mojo.internal.Bool,false,false)],[[0,16]]);ash.mediaAppUi.mojom.PageHandler_IsFileArcWritable_ResponseParams=class{constructor(){this.writable}};mojo.internal.Struct(ash.mediaAppUi.mojom.PageHandler_IsFileBrowserWritable_ParamsSpec.$,"PageHandler_IsFileBrowserWritable_Params",[mojo.internal.StructField("token",0,0,mojo.internal.InterfaceProxy(blink.mojom.FileSystemAccessTransferTokenRemote),null,false)],[[0,16]]);ash.mediaAppUi.mojom.PageHandler_IsFileBrowserWritable_Params=class{constructor(){this.token}};mojo.internal.Struct(ash.mediaAppUi.mojom.PageHandler_IsFileBrowserWritable_ResponseParamsSpec.$,"PageHandler_IsFileBrowserWritable_ResponseParams",[mojo.internal.StructField("writable",0,0,mojo.internal.Bool,false,false)],[[0,16]]);ash.mediaAppUi.mojom.PageHandler_IsFileBrowserWritable_ResponseParams=class{constructor(){this.writable}};mojo.internal.Struct(ash.mediaAppUi.mojom.PageHandler_EditInPhotos_ParamsSpec.$,"PageHandler_EditInPhotos_Params",[mojo.internal.StructField("token",0,0,mojo.internal.InterfaceProxy(blink.mojom.FileSystemAccessTransferTokenRemote),null,false),mojo.internal.StructField("mimeType",8,0,mojo.internal.String,null,false)],[[0,24]]);ash.mediaAppUi.mojom.PageHandler_EditInPhotos_Params=class{constructor(){this.token;this.mimeType}};mojo.internal.Struct(ash.mediaAppUi.mojom.PageHandler_EditInPhotos_ResponseParamsSpec.$,"PageHandler_EditInPhotos_ResponseParams",[],[[0,8]]);ash.mediaAppUi.mojom.PageHandler_EditInPhotos_ResponseParams=class{constructor(){}};
// Copyright 2020 The Chromium Authors
const mediaAppPageHandler=new ash.mediaAppUi.mojom.PageHandlerRemote;ash.mediaAppUi.mojom.PageHandlerFactory.getRemote().createPageHandler(mediaAppPageHandler.$.bindNewPipeAndPassReceiver());
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
window.addEventListener("simulate-type-error-for-test",(event=>{event.notAFunction()}));window.addEventListener("simulate-unhandled-rejection-for-test",(event=>{new Promise((resolve=>{const error=new Error("fake_throw");error.name="FakeErrorName";throw error}))}));window.addEventListener("simulate-unhandled-rejection-with-dom-exception-for-test",(event=>{new Promise((resolve=>{throw new DOMException("Not a file.","NotAFile")}))}));
// Copyright 2019 The Chromium Authors
const DEFAULT_APP_ICON="app";const EMPTY_WRITE_ERROR_NAME="EmptyWriteError";const AUDIO_EXTENSIONS=[".flac",".m4a",".mp3",".oga",".ogg",".opus",".wav",".weba",".m4a"];const IMAGE_EXTENSIONS=[".jpg",".png",".webp",".gif",".avif",".bmp",".ico",".svg",".jpeg",".jpe",".jfif",".jif",".jfi",".pjpeg",".pjp",".arw",".cr2",".dng",".nef",".nrw",".orf",".raf",".rw2",".svgz"];const VIDEO_EXTENSIONS=[".3gp",".avi",".m4v",".mkv",".mov",".mp4",".mpeg",".mpeg4",".mpg",".mpg4",".ogv",".ogx",".ogm",".webm"];const PDF_EXTENSIONS=[".pdf"];const OPEN_ACCEPT_ARGS={AUDIO:{description:loadTimeData.getString("fileFilterAudio"),accept:{"audio/*":AUDIO_EXTENSIONS}},IMAGE:{description:loadTimeData.getString("fileFilterImage"),accept:{"image/*":IMAGE_EXTENSIONS}},VIDEO:{description:loadTimeData.getString("fileFilterVideo"),accept:{"video/*":VIDEO_EXTENSIONS}},PDF:{description:"PDF",accept:{"application/pdf":PDF_EXTENSIONS}},ALL_EX_TEXT:{description:"All",accept:{"*/*":[...AUDIO_EXTENSIONS,...IMAGE_EXTENSIONS,...VIDEO_EXTENSIONS,...PDF_EXTENSIONS]}}};const SortOrder={A_FIRST:1,Z_FIRST:2,NEWEST_FIRST:3};const currentFiles=[];let appTitle;let sortOrder=SortOrder.A_FIRST;let entryIndex=-1;let globalLaunchNumber=-1;let currentDirectoryHandle=null;const tokenMap=new Map;
/**
* A pipe through which we can send messages to the guest frame.
* Use an undefined `target` to find the <iframe> automatically.
* Do not rethrow errors, since handlers installed here are expected to
* throw exceptions that are handled on the other side of the pipe. And
* nothing `awaits` async callHandlerForMessageType_(), so they will always
* be reported as `unhandledrejection` and trigger a crash report.
*/const guestMessagePipe=new MessagePipe("chrome-untrusted://media-app",undefined,false);
// event listener before the <iframe> is added to the DOM.
guestMessagePipe.registerHandler(Message.IFRAME_READY,(()=>{}));let appIconType=DEFAULT_APP_ICON;function updateAppIcon(mediaQueryList){const isDark=mediaQueryList.matches&&appIconType!==DEFAULT_APP_ICON?"_dark":"";const icon=document.querySelector("link[rel=icon]");icon.href=`system_assets/${appIconType}_icon${isDark}.svg`}const darkMediaQuery=window.matchMedia("(prefers-color-scheme: dark)");guestMessagePipe.registerHandler(Message.NOTIFY_CURRENT_FILE,(message=>{const notifyMsg=message;const title=document.querySelector("title");appTitle=appTitle||title.text;title.text=notifyMsg.name||appTitle;appIconType=notifyMsg.type?notifyMsg.type.split("/")[0]:"file";if(title.text===appTitle){appIconType=DEFAULT_APP_ICON}else if(notifyMsg.type==="application/pdf"){appIconType="pdf"}else if(!["audio","image","video","file"].includes(appIconType)){appIconType="file"}updateAppIcon(darkMediaQuery)}));darkMediaQuery.addEventListener("change",updateAppIcon);guestMessagePipe.registerHandler(Message.OPEN_FEEDBACK_DIALOG,(()=>{let response=mediaAppPageHandler.openFeedbackDialog();if(response===null){response={errorMessage:"Null response received"}}return response}));guestMessagePipe.registerHandler(Message.TOGGLE_BROWSER_FULLSCREEN_MODE,(()=>{mediaAppPageHandler.toggleBrowserFullscreenMode()}));guestMessagePipe.registerHandler(Message.OPEN_IN_SANDBOXED_VIEWER,(message=>{window.open(`./viewpdfhost.html?${new URLSearchParams(message)}`,"_blank","popup=1")}));guestMessagePipe.registerHandler(Message.RELOAD_MAIN_FRAME,(()=>{window.location.reload()}));guestMessagePipe.registerHandler(Message.MAYBE_TRIGGER_PDF_HATS,(()=>{mediaAppPageHandler.maybeTriggerPdfHats()}));guestMessagePipe.registerHandler(Message.EDIT_IN_PHOTOS,(message=>{const editInPhotosMsg=message;const fileHandle=fileHandleForToken(editInPhotosMsg.token);const transferToken=new blink.mojom.FileSystemAccessTransferTokenRemote(Mojo.getFileSystemAccessTransferToken(fileHandle));return mediaAppPageHandler.editInPhotos(transferToken,editInPhotosMsg.mimeType)}));guestMessagePipe.registerHandler(Message.IS_FILE_ARC_WRITABLE,(message=>{const writableMsg=message;const fileHandle=fileHandleForToken(writableMsg.token);const transferToken=new blink.mojom.FileSystemAccessTransferTokenRemote(Mojo.getFileSystemAccessTransferToken(fileHandle));return mediaAppPageHandler.isFileArcWritable(transferToken)}));guestMessagePipe.registerHandler(Message.IS_FILE_BROWSER_WRITABLE,(message=>{const writableMsg=message;const fileHandle=fileHandleForToken(writableMsg.token);const transferToken=new blink.mojom.FileSystemAccessTransferTokenRemote(Mojo.getFileSystemAccessTransferToken(fileHandle));return mediaAppPageHandler.isFileBrowserWritable(transferToken)}));guestMessagePipe.registerHandler(Message.OVERWRITE_FILE,(async message=>{const overwrite=message;const originalHandle=fileHandleForToken(overwrite.token);try{await saveBlobToFile(originalHandle,overwrite.blob)}catch(e){if(e.name===EMPTY_WRITE_ERROR_NAME){throw e}console.warn("Showing a picker due to",e);return pickFileForFailedOverwrite(originalHandle.name,e.name,overwrite)}}));async function pickFileForFailedOverwrite(fileName,errorName,overwrite){const fileHandle=await pickWritableFile(fileName,overwrite.blob.type,overwrite.token,[]);await saveBlobToFile(fileHandle,overwrite.blob);tokenMap.set(overwrite.token,fileHandle);const entry=currentFiles.find((i=>i.token===overwrite.token));if(entry){entry.handle=fileHandle}return{renamedTo:fileHandle.name,errorName:errorName}}guestMessagePipe.registerHandler(Message.DELETE_FILE,(async message=>{const deleteMsg=message;const{handle:handle,directory:directory}=assertFileAndDirectoryMutable(deleteMsg.token,"Delete");if(!await isHandleInCurrentDirectory(handle)){console.warn(`"${handle.name}" not found in the last opened folder.`);const error=new Error("Ignoring delete request: file not found");error.name="NotFoundError";throw error}await directory.removeEntry(handle.name);currentFiles.splice(entryIndex,1);await advance(0)}));guestMessagePipe.registerHandler(Message.RENAME_FILE,(async message=>{const renameMsg=message;const{handle:handle,directory:directory}=assertFileAndDirectoryMutable(renameMsg.token,"Rename");if(await filenameExistsInCurrentDirectory(renameMsg.newFilename)){return{renameResult:RenameResult.FILE_EXISTS}}const originalFile=await maybeGetFileFromFileHandle(handle);let originalFileIndex=currentFiles.findIndex((fd=>fd.token===renameMsg.token));if(!originalFile||originalFileIndex<0){return{renameResult:RenameResult.FILE_NO_LONGER_IN_LAST_OPENED_DIRECTORY}}const renamedFileHandle=await directory.getFileHandle(renameMsg.newFilename,{create:true});const writer=await renamedFileHandle.createWritable();const sink=writer;const source=originalFile;await source.stream().pipeTo(sink);if(await isHandleInCurrentDirectory(handle)){await directory.removeEntry(originalFile.name)}tokenMap.set(renameMsg.token,renamedFileHandle);originalFileIndex=currentFiles.findIndex((fd=>fd.token===renameMsg.token));if(originalFileIndex<0){return{renameResult:RenameResult.SUCCESS}}currentFiles.splice(originalFileIndex,1,{token:renameMsg.token,file:null,handle:renamedFileHandle,inCurrentDirectory:true});return{renameResult:RenameResult.SUCCESS}}));guestMessagePipe.registerHandler(Message.NAVIGATE,(async message=>{const navigate=message;await advance(navigate.direction,navigate.currentFileToken)}));guestMessagePipe.registerHandler(Message.REQUEST_SAVE_FILE,(async message=>{const{suggestedName:suggestedName,mimeType:mimeType,startInToken:startInToken,accept:accept}=message;const handle=await pickWritableFile(suggestedName,mimeType,startInToken,accept);const response={pickedFileContext:{token:generateToken(handle),file:assertCast(await handle.getFile()),name:handle.name,error:"",canDelete:false,canRename:false}};return response}));guestMessagePipe.registerHandler(Message.SAVE_AS,(async message=>{const{blob:blob,oldFileToken:oldFileToken,pickedFileToken:pickedFileToken}=message;const oldFileDescriptor=currentFiles.find((fd=>fd.token===oldFileToken));const pickedFileDescriptor={token:oldFileToken||tokenGenerator.next().value,file:null,handle:tokenMap.get(pickedFileToken)};const oldFileIndex=currentFiles.findIndex((fd=>fd.token===oldFileToken));tokenMap.set(pickedFileDescriptor.token,pickedFileDescriptor.handle);if(oldFileDescriptor){oldFileDescriptor.token=generateToken(oldFileDescriptor.handle)}try{await saveBlobToFile(pickedFileDescriptor.handle,blob)}catch(e){if(oldFileDescriptor&&oldFileToken){oldFileDescriptor.token=oldFileToken;tokenMap.set(oldFileToken,oldFileDescriptor.handle)}throw e}currentFiles.splice(oldFileIndex+1,0,pickedFileDescriptor);entryIndex=oldFileIndex+1;const response={newFilename:pickedFileDescriptor.handle.name};return response}));guestMessagePipe.registerHandler(Message.OPEN_FILES_WITH_PICKER,(async m=>{const{startInToken:startInToken,accept:accept,isSingleFile:isSingleFile}=m;const acceptTypes=accept.map((k=>OPEN_ACCEPT_ARGS[k])).filter((a=>!!a));const options={multiple:!isSingleFile};if(startInToken){options.startIn=fileHandleForToken(startInToken)}if(acceptTypes.length>0){options.excludeAcceptAllOption=true;options.types=acceptTypes}const handles=await window.showOpenFilePicker(options);const newDescriptors=[];for(const handle of handles){newDescriptors.push({token:generateToken(handle),file:null,handle:handle,inCurrentDirectory:false})}if(newDescriptors.length===0){return}currentFiles.splice(0,currentFiles.length,...newDescriptors);entryIndex=0;await sendSnapshotToGuest([...currentFiles],++globalLaunchNumber)}));guestMessagePipe.registerHandler(Message.OPEN_ALLOWED_FILE,(async message=>{const{fileToken:fileToken}=message;const handle=fileHandleForToken(fileToken);const response={file:(await getFileFromHandle(handle)).file};return response}));function pickWritableFile(suggestedName,mimeType,startInToken,accept){const JPG_EXTENSIONS=[".jpg",".jpeg",".jpe",".jfif",".jif",".jfi",".pjpeg",".pjp"];const ACCEPT_ARGS={JPG:{description:"JPG",accept:{"image/jpeg":JPG_EXTENSIONS}},PNG:{description:"PNG",accept:{"image/png":[".png"]}},WEBP:{description:"WEBP",accept:{"image/webp":[".webp"]}},PDF:{description:"PDF",accept:{"application/pdf":[".pdf"]}}};const acceptTypes=accept.map((k=>ACCEPT_ARGS[k])).filter((a=>!!a));const options={suggestedName:suggestedName};if(startInToken){options.startIn=fileHandleForToken(startInToken)}if(acceptTypes.length>0){options.excludeAcceptAllOption=true;options.types=acceptTypes}else{for(const a of Object.values(ACCEPT_ARGS)){if(a.accept[mimeType]){options.excludeAcceptAllOption=true;options.types=[a]}}}return window.showSaveFilePicker(options)}const tokenGenerator=function*(){const randomBuffer=new Uint32Array(1e3);while(true){assertCast(crypto).getRandomValues(randomBuffer);for(let i=0;i<randomBuffer.length;++i){const token=randomBuffer[i];if(token&&!tokenMap.has(token)){yield Number(token)}}}}();function generateToken(handle){const token=tokenGenerator.next().value;tokenMap.set(token,handle);return token}function getMimeTypeFromFilename(filename){const mapping={avif:"image/avif",crx:"application/x-chrome-extension",css:"text/css",flac:"audio/flac",gif:"image/gif",htm:"text/html",html:"text/html",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",m4a:"audio/x-m4a",m4v:"video/mp4",mht:"multipart/related",mhtml:"multipart/related",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",oga:"audio/ogg",ogg:"audio/ogg",ogm:"video/ogg",ogv:"video/ogg",opus:"audio/ogg",png:"image/png",shtm:"text/html",shtml:"text/html",wasm:"application/wasm",wav:"audio/wav",webm:"video/webm",webp:"image/webp",xht:"application/xhtml+xml",xhtm:"application/xhtml+xml",xhtml:"application/xhtml+xml",xml:"text/xml",epub:"application/epub+zip",woff:"application/font-woff",gz:"application/gzip",tgz:"application/gzip",json:"application/json",bin:"application/octet-stream",exe:"application/octet-stream",com:"application/octet-stream",pdf:"application/pdf",p7m:"application/pkcs7-mime",p7c:"application/pkcs7-mime",p7z:"application/pkcs7-mime",p7s:"application/pkcs7-signature",ps:"application/postscript",eps:"application/postscript",ai:"application/postscript",rdf:"application/rdf+xml",rss:"application/rss+xml",apk:"application/vnd.android.package-archive",xul:"application/vnd.mozilla.xul+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",zip:"application/zip",weba:"audio/webm",bmp:"image/bmp",jfif:"image/jpeg",pjpeg:"image/jpeg",pjp:"image/jpeg",svg:"image/svg+xml",svgz:"image/svg+xml",tiff:"image/tiff",tif:"image/tiff",ico:"image/vnd.microsoft.icon",eml:"message/rfc822",ics:"text/calendar",ehtml:"text/html",txt:"text/plain",text:"text/plain",sh:"text/x-sh",xsl:"text/xml",xbl:"text/xml",xslt:"text/xml",mpeg:"video/mpeg",mpg:"video/mpeg",mkv:"video/x-matroska","3gp":"video/3gpp",mov:"video/quicktime",avi:"video/x-msvideo",mpeg4:"video/mp4",mpg4:"video/mp4"};const fileParts=filename.split(".");if(fileParts.length<2){return null}const extension=fileParts[fileParts.length-1].toLowerCase();const mimeType=mapping[extension];return mimeType!==undefined?mimeType:null}function fileHandleForToken(token){const handle=tokenMap.get(token);if(!handle){throw new DOMException(`No handle for token(${token})`,"NotFoundError")}return handle}async function saveBlobToFile(handle,data){if(data.size===0){const error=new Error("saveBlobToFile(): Refusing to write zero bytes.");error.name=EMPTY_WRITE_ERROR_NAME;throw error}const writer=await handle.createWritable();await writer.write(data);await writer.truncate(data.size);await writer.close()}function warnIfUncommon(e,fileName){const commonErrors=["NotFoundError","NotAllowedError","NotAFile"];if(commonErrors.includes(e.name)){return}console.warn(`Unexpected ${e.name} on ${fileName}: ${e.message}`)}async function refreshFile(fd){if(fd.file){return}fd.lastError="";try{fd.file=(await getFileFromHandle(fd.handle)).file}catch(e){fd.lastError=e.name;warnIfUncommon(e,fd.handle.name)}}async function sendFilesToGuest(){return sendSnapshotToGuest([...currentFiles],globalLaunchNumber)}function fileDescriptorToFileContext(fd){return{token:fd.token,file:fd.file,name:fd.handle.name,error:fd.lastError||"",canDelete:fd.inCurrentDirectory||false,canRename:fd.inCurrentDirectory||false}}async function sendSnapshotToGuest(snapshot,localLaunchNumber,extraFiles=false){const focusIndex=entryIndex;let targetIndex=-1;if(focusIndex>=0&&focusIndex<snapshot.length){targetIndex=focusIndex}else if(snapshot.length!==0){targetIndex=0}if(targetIndex>=0){const descriptor=snapshot[targetIndex];await refreshFile(descriptor);await refreshLoadRequiredAssociatedFiles(snapshot,descriptor.handle.name,extraFiles);if(extraFiles){snapshot.shift()}}if(localLaunchNumber!==globalLaunchNumber){return}const loadFilesMessage={currentFileIndex:focusIndex,files:snapshot.map(fileDescriptorToFileContext)};for(const fd of snapshot){fd.file=null}await window.firstMessageReceived;if(extraFiles){await guestMessagePipe.sendMessage(Message.LOAD_EXTRA_FILES,loadFilesMessage)}else{await guestMessagePipe.sendMessage(Message.LOAD_FILES,loadFilesMessage)}}function assertFileAndDirectoryMutable(editFileToken,operation){if(!currentDirectoryHandle){throw new Error(`${operation} failed. File without launch directory.`)}return{handle:fileHandleForToken(editFileToken),directory:currentDirectoryHandle}}async function isHandleInCurrentDirectory(handle){const file=await maybeGetFileFromFileHandle(handle);if(!file){return false}const currentFilename=file.name;const fileHandle=await getFileHandleFromCurrentDirectory(currentFilename);return fileHandle?fileHandle.isSameEntry(handle):false}async function filenameExistsInCurrentDirectory(filename){return await getFileHandleFromCurrentDirectory(filename,true)!==null}async function getFileHandleFromCurrentDirectory(filename,suppressError=false){if(!currentDirectoryHandle){return null}try{return await currentDirectoryHandle.getFileHandle(filename,{create:false})}catch(e){if(!suppressError){if(e.name==="TypeError"&&e.message==="Name is not allowed."){console.warn(e);throw new DOMException("File has a reserved name and can not be opened","InvalidModificationError")}console.error(e)}return null}}async function getFileFromHandle(fileSystemHandle){if(!fileSystemHandle||fileSystemHandle.kind!=="file"){throw new DOMException("Not a file.","NotAFile")}const handle=fileSystemHandle;const file=await handle.getFile();return{file:file,handle:handle}}async function maybeGetFileFromFileHandle(handle){let file;try{file=await handle.getFile()}catch(e){if(e.name==="NotFoundError"){file=null}else{throw e}}return file}function isSubtitleFile(fileName){return/\.vtt$/.test(fileName.toLowerCase())}function isVideoFile(fileName){return/^video\//.test(getMimeTypeFromFilename(fileName))}function isImageFile(fileName){return/\.(arw|cr2|dng|nef|nrw|orf|raf|rw2)$/.test(fileName.toLowerCase())||/^image\//.test(getMimeTypeFromFilename(fileName))}function isAudioFile(fileName){return/^audio\//.test(getMimeTypeFromFilename(fileName))}function isVideoOrImage(fileName){return isImageFile(fileName)||isVideoFile(fileName)||isSubtitleFile(fileName)}function isFileRelated(focusFile,siblingFileName){const siblingFileType=getMimeTypeFromFilename(siblingFileName);return focusFile.name===siblingFileName||!!focusFile.type&&!!siblingFileType&&focusFile.type===siblingFileType||isVideoOrImage(focusFile.name)&&isVideoOrImage(siblingFileName)}const ProcessOtherFilesResult={ABORT:-2,FOCUS_FILE_MISSING:-1,FOCUS_FILE_RELEVANT:0};async function processOtherFilesInDirectory(directory,focusFile,localLaunchNumber){if(!focusFile||!focusFile.name){return ProcessOtherFilesResult.ABORT}let relatedFiles=[];try{for await(const handle of directory.values()){if(localLaunchNumber!==globalLaunchNumber){return ProcessOtherFilesResult.ABORT}if(handle.kind!=="file"){continue}const fileHandle=handle;if(isFileRelated(focusFile,handle.name)){relatedFiles.push({token:generateToken(fileHandle),file:null,handle:fileHandle,inCurrentDirectory:true})}}}catch(e){console.warn(e,"(failed to traverse directory)")}if(currentFiles.length>1){const atLoadCurrentFiles=currentFiles.slice(1);relatedFiles=relatedFiles.filter((f=>!atLoadCurrentFiles.find((c=>c.handle.name===f.handle.name))))}if(localLaunchNumber!==globalLaunchNumber){return ProcessOtherFilesResult.ABORT}await sortFiles(relatedFiles);const name=focusFile.name;const focusIndex=relatedFiles.findIndex((i=>i.handle.name===name));entryIndex=0;if(focusIndex===-1){currentFiles.push(...relatedFiles);return ProcessOtherFilesResult.FOCUS_FILE_MISSING}else{currentFiles.push(...relatedFiles.slice(focusIndex+1));currentFiles.push(...relatedFiles.slice(0,focusIndex));return ProcessOtherFilesResult.FOCUS_FILE_RELEVANT}}async function sortFiles(files){if(sortOrder===SortOrder.NEWEST_FIRST){for(const descriptor of files){try{descriptor.file=(await getFileFromHandle(descriptor.handle)).file}catch(e){warnIfUncommon(e,descriptor.handle.name)}}}files.sort(((a,b)=>{if(sortOrder===SortOrder.NEWEST_FIRST){if(!a.file&&!b.file){return 0}else if(!b.file){return-1}else if(!a.file){return 1}else if(a.file.lastModified===b.file.lastModified){return a.file.name.localeCompare(b.file.name)}return b.file.lastModified-a.file.lastModified}const direction=sortOrder===SortOrder.A_FIRST?1:-1;return direction*a.handle.name.localeCompare(b.handle.name,[],{usage:"sort",numeric:true,sensitivity:"base"})}))}async function loadOtherRelatedFiles(directory,focusFile,focusHandle,localLaunchNumber){const processResult=await processOtherFilesInDirectory(directory,focusFile,localLaunchNumber);if(localLaunchNumber!==globalLaunchNumber||processResult===ProcessOtherFilesResult.ABORT){return}const shallowCopy=[...currentFiles];await sendSnapshotToGuest(shallowCopy,localLaunchNumber,processResult===ProcessOtherFilesResult.FOCUS_FILE_RELEVANT)}function setCurrentDirectory(directory,focusFile){currentFiles.length=0;currentFiles.push({token:generateToken(focusFile.handle),file:focusFile.file,handle:focusFile.handle,inCurrentDirectory:true});currentDirectoryHandle=directory;entryIndex=0}function requiredAssociatedFileName(focusFileName){if(!isVideoFile(focusFileName)){return""}return focusFileName.replace(/\.[^\.]+$/,".vtt")}async function detectLoadRequiredAssociatedFiles(directory,focusFileName){const vttFileName=requiredAssociatedFileName(focusFileName);if(!vttFileName){return}try{const vttFileHandle=await directory.getFileHandle(vttFileName);currentFiles.push({token:generateToken(vttFileHandle),file:null,handle:vttFileHandle,inCurrentDirectory:true})}catch(e){}}async function refreshLoadRequiredAssociatedFiles(snapshot,focusFileName,forExtraFilesMessage){const vttFileName=requiredAssociatedFileName(focusFileName);if(!vttFileName){return}const index=snapshot.findIndex((d=>d.handle.name===vttFileName));if(index>=0){await refreshFile(snapshot[index]);if(forExtraFilesMessage){snapshot.splice(index,1)}}}async function launchWithDirectory(directory,handle){const localLaunchNumber=++globalLaunchNumber;let asFile;try{asFile=await getFileFromHandle(handle)}catch(e){console.warn(`${handle.name}: ${e.message}`);sendSnapshotToGuest([{token:-1,file:null,handle:handle,error:e.name}],localLaunchNumber);return}setCurrentDirectory(directory,asFile);await detectLoadRequiredAssociatedFiles(directory,handle.name);await sendSnapshotToGuest([...currentFiles],localLaunchNumber);await loadOtherRelatedFiles(directory,asFile.file,asFile.handle,localLaunchNumber)}async function launchWithMultipleSelection(directory,handles){currentFiles.length=0;for(const handle of handles){if(handle&&handle.kind==="file"){const fileHandle=handle;currentFiles.push({token:generateToken(fileHandle),file:null,handle:fileHandle})}}await sortFiles(currentFiles);entryIndex=currentFiles.length>0?0:-1;currentDirectoryHandle=directory;await sendFilesToGuest()}async function advance(direction,currentFileToken){let currIndex=entryIndex;if(currentFileToken){const fileIndex=currentFiles.findIndex((fd=>fd.token===currentFileToken));currIndex=fileIndex===-1?currIndex:fileIndex}if(currentFiles.length){entryIndex=(currIndex+direction)%currentFiles.length;if(entryIndex<0){entryIndex+=currentFiles.length}}else{entryIndex=-1}await sendFilesToGuest()}async function launchConsumer(params){if(!params||!params.files||params.files.length<2){console.error("Invalid launch (missing files): ",params);return}if(assertCast(params.files[0]).kind!=="directory"){console.error("Invalid launch: files[0] is not a directory: ",params);return}const directory=params.files[0];const maybeFocusEntry=assertCast(params.files[1]);if(params.files.length===2&&!isAudioFile(maybeFocusEntry.name)){try{await launchWithDirectory(directory,maybeFocusEntry)}catch(e){console.error(e,"(launchWithDirectory aborted)")}}else{try{await launchWithMultipleSelection(directory,params.files.slice(1))}catch(e){console.error(e,"(launchWithMultipleSelection aborted)")}}}function wrappedLaunchConsumer(params){launchConsumer(params).catch((e=>{console.error(e,"(launch aborted)")}))}function installLaunchHandler(){if(!window.launchQueue){console.error("FileHandling API missing.");return}window.launchQueue.setConsumer(wrappedLaunchConsumer)}installLaunchHandler();const guest=assertCast(document.querySelector('iframe[src^="chrome-untrusted://media-app"]'));guest.addEventListener("load",(()=>{guest.focus()}));const TEST_ONLY={Message:Message,SortOrder:SortOrder,advance:advance,currentDirectoryHandle:currentDirectoryHandle,currentFiles:currentFiles,fileHandleForToken:fileHandleForToken,globalLaunchNumber:globalLaunchNumber,guestMessagePipe:guestMessagePipe,launchConsumer:launchConsumer,launchWithDirectory:launchWithDirectory,loadOtherRelatedFiles:loadOtherRelatedFiles,pickWritableFile:pickWritableFile,processOtherFilesInDirectory:processOtherFilesInDirectory,sendFilesToGuest:sendFilesToGuest,setCurrentDirectory:setCurrentDirectory,sortOrder:sortOrder,tokenGenerator:tokenGenerator,tokenMap:tokenMap,mediaAppPageHandler:mediaAppPageHandler,error_reporter:error_reporter,getGlobalLaunchNumber:()=>globalLaunchNumber,incrementLaunchNumber:()=>++globalLaunchNumber,setCurrentDirectoryHandle:d=>{currentDirectoryHandle=d},setSortOrder:s=>{sortOrder=s},getEntryIndex:()=>entryIndex,setEntryIndex:i=>{entryIndex=i}};window["advance"]=advance;export{TEST_ONLY};