-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathshell.js
More file actions
1 lines (1 loc) · 12.4 KB
/
shell.js
File metadata and controls
1 lines (1 loc) · 12.4 KB
1
import initVFS from"./init_vfs.js";import ERR_CODES from"./errno.js";import{LRUCache}from"../thirdparty/no-minify/lru-cache.js";import*as Emmet from"../thirdparty/emmet.es.js";import{initTrustRing}from"./trust_ring.js";initTrustRing().catch(console.error),initVFS();const MAX_ALLOWED_TAURI_WINDOWS=30,CLI_ARGS_QUERY_PARAM="CLI_ARGS",CLI_CWD_QUERY_PARAM="CLI_CWD";let cliArgs,cliCWD,singleInstanceCLIHandler,quitTimeAppUpdateHandler;const PHOENIX_WINDOW_PREFIX="phcode-",PHOENIX_EXTENSION_WINDOW_PREFIX="extn-";async function _getTauriWindowLabel(prefix){const tauriWindowLabels=await window.__TAURI__.invoke("_get_window_labels"),windowLabels={};for(let label of tauriWindowLabels)label.startsWith(prefix)&&(windowLabels[label]=!0);for(let i=1;i<=MAX_ALLOWED_TAURI_WINDOWS;i++){const windowLabel=`${prefix}${i}`;if(!windowLabels[windowLabel])return windowLabel}throw new Error("Could not get a free window label to create tauri window")}async function openURLInPhoenixWindow(url,{windowTitle:windowTitle,fullscreen:fullscreen,resizable:resizable,height:height,minHeight:minHeight,width:width,minWidth:minWidth,acceptFirstMouse:acceptFirstMouse,preferTabs:preferTabs,_prefixPvt:_prefixPvt=PHOENIX_EXTENSION_WINDOW_PREFIX}={}){const defaultHeight=900,defaultWidth=1366;if(window.__TAURI__){const windowLabel=await _getTauriWindowLabel(_prefixPvt),tauriWindow=new window.__TAURI__.window.WebviewWindow(windowLabel,{url:url,title:windowTitle||windowLabel||url,fullscreen:fullscreen,resizable:void 0===resizable||resizable,height:height||900,minHeight:minHeight||600,width:width||1366,minWidth:minWidth||800,acceptFirstMouse:void 0===acceptFirstMouse||acceptFirstMouse,fileDropEnabled:!1});return tauriWindow.isTauriWindow=!0,tauriWindow}let features="toolbar=no,location=no, status=no, menubar=no, scrollbars=yes";features=`${features}, width=${width||1366}, height=${height||900}`,(void 0===resizable||resizable)&&(features+=", resizable=yes"),preferTabs&&(features="");const nativeWindow=window.open(url,"_blank",features);return nativeWindow.isTauriWindow=!1,nativeWindow}Phoenix.libs={LRUCache:LRUCache,Emmet:{expand:Emmet.default,module:Emmet},hljs:window.hljs,iconv:fs.utils.iconv,picomatch:fs.utils.picomatch},Phoenix.globalAPI={},Phoenix.app={getNodeState:function(cbfn){cbfn(new Error("Node cannot be run in phoenix browser mode"))},getProcessID:function(){if(!Phoenix.isNativeApp)throw new Error("getProcessID is not supported in browsers");return window.__TAURI__.invoke("get_process_id")},registerQuitTimeAppUpdateHandler:function(handler){if(!Phoenix.isNativeApp)throw new Error("registerQuitTimeAppUpdateHandler is not supported in browsers");quitTimeAppUpdateHandler=handler},toggleDevtools:async function(){if(!Phoenix.isNativeApp)throw new Error("toggle_devtools is not supported in browsers");return window.__TAURI__.invoke("toggle_devtools",{})},closeWindow:async function(forceClose){if(!Phoenix.isNativeApp)throw new Error("closeWindow is not supported in browsers");let instanceCount=0,extensionWindowCount=0;try{instanceCount=await Phoenix.app.getPhoenixInstanceCount();const allTauriWindowsLabels=await window.__TAURI__.invoke("_get_window_labels");for(let tauriWindowLabel of allTauriWindowsLabels)tauriWindowLabel&&tauriWindowLabel.startsWith(PHOENIX_EXTENSION_WINDOW_PREFIX)&&extensionWindowCount++}catch(e){console.error("Ignoring Error while Phoenix.app.closeWindow: ",e)}if(1!==instanceCount||extensionWindowCount)window.__TAURI__.window.getCurrent().close();else{if(!forceClose&&quitTimeAppUpdateHandler)try{await quitTimeAppUpdateHandler()}catch(e){console.error(e)}window.__TAURI__.process.exit(0)}},focusWindow:function(){if(!Phoenix.isNativeApp)return Promise.reject(new Error("focusWindow is not supported in browsers"));window.__TAURI__.window.getCurrent().setAlwaysOnTop(!0),window.__TAURI__.window.getCurrent().setFocus(),window.__TAURI__.window.getCurrent().setAlwaysOnTop(!1)},getCommandLineArgs:async function(){if(!Phoenix.isNativeApp)return null;const phoenixURL=new URL(location.href),cliQueryParam=phoenixURL.searchParams.get("CLI_ARGS");cliQueryParam&&(cliArgs=JSON.parse(decodeURIComponent(cliQueryParam)));const cliCWDQueryParam=phoenixURL.searchParams.get("CLI_CWD");return cliCWDQueryParam&&(cliCWD=JSON.parse(decodeURIComponent(cliCWDQueryParam))),cliArgs?{cwd:cliCWD,args:cliArgs}:(cliArgs=null,cliCWD=await window.__TAURI__.invoke("get_current_working_dir"),cliArgs=await window.__TAURI__.invoke("_get_commandline_args"),{cwd:cliCWD,args:cliArgs})},setSingleInstanceCLIArgsHandler:function(handlerFn){if(singleInstanceCLIHandler)throw new Error("A single instance handler is already registered!");handlerFn&&(singleInstanceCLIHandler=handlerFn),Phoenix.isNativeApp&&(window.__TAURI__.event.listen("single-instance",({payload:payload})=>{handlerFn(payload.args,payload.cwd)}),window.__TAURI__.event.listen("scheme-request-received",receivedEvent=>{console.log("Macos received Event from OS:",receivedEvent);const fileURL=receivedEvent.payload,fileURLArray=receivedEvent.payload.fileURLArray;window.__TAURI__.tauri.invoke("get_mac_deep_link_requests");const eventToUse=["macOSEvent"];if("string"==typeof fileURL)eventToUse.push(decodeURIComponent(fileURL.replace("file://","")));else if(fileURLArray)for(let fileUrlEntry of fileURLArray)eventToUse.push(decodeURIComponent(fileUrlEntry.replace("file://","")));handlerFn(eventToUse,"")}),window.__TAURI__.tauri.invoke("get_mac_deep_link_requests").then(filesURLList=>{filesURLList.length&&Phoenix.app.isPrimaryDesktopPhoenixWindow().then(isPrimary=>{if(isPrimary){const eventToUse=["macOSEvent"];for(let fileUrlEntry of filesURLList)eventToUse.push(decodeURIComponent(fileUrlEntry.replace("file://","")));handlerFn(eventToUse,"")}else window.__TAURI__.event.emit("scheme-request-received",{fileURLArray:filesURLList})})}))},clipboardReadText:function(){return Phoenix.isNativeApp?window.__TAURI__.clipboard.readText():window.navigator&&window.navigator.clipboard?window.navigator.clipboard.readText():Promise.reject(new Error("clipboardReadText: Not supported."))},clipboardReadFiles:function(){return new Promise((resolve,reject)=>{Phoenix.isNativeApp?window.__TAURI__.tauri.invoke("_get_clipboard_files").then(files=>{if(!files)return void resolve(files);const vfsPaths=[];for(let platformPath of files)vfsPaths.push(Phoenix.VFS.getTauriVirtualPath(platformPath));resolve(vfsPaths)}).catch(reject):resolve()})},copyToClipboard:function(textToCopy){if(Phoenix.isNativeApp)return window.__TAURI__.clipboard.writeText(textToCopy);if(window.navigator&&window.navigator.clipboard)return window.navigator.clipboard.writeText(textToCopy);const textArea=document.createElement("textarea");return textArea.value=textToCopy,document.body.appendChild(textArea),textArea.select(),document.execCommand("copy"),document.body.removeChild(textArea),Promise.resolve()},isFullscreen:function(){return Phoenix.isNativeApp?window.__TAURI__.window.appWindow.isFullscreen():Promise.resolve(!!document.fullscreenElement)},setFullscreen:function(enable){return Phoenix.isNativeApp?window.__TAURI__.window.appWindow.setFullscreen(enable):enable?document.documentElement.requestFullscreen():document.exitFullscreen?document.exitFullscreen():Promise.resolve()},getDisplayLocation:function(fullVFSPath){return fullVFSPath.startsWith(Phoenix.VFS.getTauriDir())?Phoenix.fs.getTauriPlatformPath(fullVFSPath):fullVFSPath.startsWith(Phoenix.VFS.getMountDir())?fullVFSPath.replace(Phoenix.VFS.getMountDir(),""):`${path.basename(fullVFSPath)} - ${window.Strings.STORED_IN_YOUR_BROWSER}`},getDisplayPath:function(fullOrRelativeVFSPath){return fullOrRelativeVFSPath?fullOrRelativeVFSPath.startsWith(Phoenix.VFS.getTauriDir())?Phoenix.fs.getTauriPlatformPath(fullOrRelativeVFSPath):fullOrRelativeVFSPath.startsWith(Phoenix.VFS.getMountDir())?fullOrRelativeVFSPath.replace(Phoenix.VFS.getMountDir(),""):fullOrRelativeVFSPath:""},canMoveToTrash:function(fullVFSPath){return!!(Phoenix.isNativeApp&&fullVFSPath&&fullVFSPath.startsWith(Phoenix.VFS.getTauriDir()))},moveToTrash:async function(fullVFSPath){if(!Phoenix.isNativeApp)throw new Error("moveToTrash is not supported in browsers");if(!fullVFSPath)throw new Error("Please specify a path to move to trash");if(!fullVFSPath.startsWith(Phoenix.VFS.getTauriDir()))throw new Error("moveToTrash only works with tauri paths, but got: "+fullVFSPath);const platformPath=Phoenix.fs.getTauriPlatformPath(fullVFSPath);return window.__TAURI__.invoke("move_to_trash",{deletePath:platformPath})},setWindowTitle:async function(title){window.document.title=title,Phoenix.isNativeApp&&await window.__TAURI__.window.appWindow.setTitle(title)},getWindowTitle:async function(){return Phoenix.isNativeApp?window.__TAURI__.window.appWindow.title():window.document.title},openPathInFileBrowser:function(fullVFSPath){return new Promise((resolve,reject)=>{if(!window.__TAURI__||!fullVFSPath.startsWith(Phoenix.VFS.getTauriDir()))return void reject("openPathInFileBrowser is only currently supported in Native builds for tauri paths!");if(fullVFSPath.toLowerCase().startsWith("http://")||fullVFSPath.toLowerCase().startsWith("https://")||fullVFSPath.toLowerCase().startsWith("file://"))return void reject("Please use openPathInFileBrowser API to open URLs");const platformPath=Phoenix.fs.getTauriPlatformPath(fullVFSPath);window.__TAURI__.tauri.invoke("show_in_folder",{path:platformPath}).then(resolve).catch(reject)})},openURLInDefaultBrowser:function(url,tabIdentifier="_blank"){return new Promise((resolve,reject)=>{window.__TAURI__?url.toLowerCase().startsWith("http://")||url.toLowerCase().startsWith("https://")?window.__TAURI__.shell.open(url).then(resolve).catch(reject):reject("openURLInDefaultBrowser: URL should be http or https, but was "+url):resolve(window.open(url,tabIdentifier,"noopener,noreferrer"))})},isPrimaryDesktopPhoenixWindow:async function(){if(!Phoenix.isNativeApp)return console.error("isPrimaryDesktopPhoenixWindow is not supported in browsers!"),!0;const currentWindowLabel=window.__TAURI__.window.getCurrent().label;if("main"===currentWindowLabel)return!0;const allTauriWindowsLabels=await window.__TAURI__.invoke("_get_window_labels");if(allTauriWindowsLabels.includes("main"))return!1;for(let tauriWindowLabel of allTauriWindowsLabels)if(tauriWindowLabel&&tauriWindowLabel.startsWith("phcode-")&¤tWindowLabel!==tauriWindowLabel&¤tWindowLabel>tauriWindowLabel)return!1;return!0},getPhoenixInstanceCount:async function(){if(!Phoenix.isNativeApp)return console.error("getPhoenixInstanceCount is not supported in browsers!"),!0;let windowCount=0;const allTauriWindowsLabels=await window.__TAURI__.invoke("_get_window_labels");for(let tauriWindowLabel of allTauriWindowsLabels)tauriWindowLabel&&(tauriWindowLabel.startsWith("phcode-")||"main"===tauriWindowLabel)&&windowCount++;return windowCount},getPlatformArch:async function(){return Phoenix.isNativeApp?window.__TAURI__.os.arch():(console.error("getPlatformArch is not supported in browsers!"),!0)},openNewPhoenixEditorWindow:async function(preferredWidth,preferredHeight,_cliArgsArray,_cwd){const phoenixURL=new URL(location.href);if(_cliArgsArray){const cliVal=encodeURIComponent(JSON.stringify(_cliArgsArray));phoenixURL.searchParams.set("CLI_ARGS",cliVal)}else phoenixURL.searchParams.delete("CLI_ARGS");if(_cwd){const cliVal=encodeURIComponent(JSON.stringify(_cwd));phoenixURL.searchParams.set("CLI_CWD",cliVal)}else phoenixURL.searchParams.delete("CLI_CWD");await openURLInPhoenixWindow(phoenixURL.href,{width:preferredWidth,height:preferredHeight,preferTabs:!0,_prefixPvt:"phcode-"})},openURLInPhoenixWindow:openURLInPhoenixWindow,zoomWebView:function(scaleFactor=1){if(!Phoenix.isNativeApp)throw new Error("zoomWebView is not supported in browsers");if(scaleFactor<.1||scaleFactor>2)throw new Error("zoomWebView scale factor should be between .1 and 2");return window.__TAURI__.tauri.invoke("zoom_window",{scaleFactor:scaleFactor})},_openUrlInBrowserWin:function(url,browser){if(!Phoenix.isNativeApp)throw new Error("_openUrlInBrowserWin is not supported in browsers");if("win"!==Phoenix.platform)throw new Error("_openUrlInBrowserWin is only supported in windows");return window.__TAURI__.invoke("_open_url_in_browser_win",{url:url,browser:browser})},getApplicationSupportDirectory:Phoenix.VFS.getAppSupportDir,getExtensionsDirectory:Phoenix.VFS.getExtensionDir,getUserDocumentsDirectory:Phoenix.VFS.getUserDocumentsDirectory,getUserProjectsDirectory:Phoenix.VFS.getUserProjectsDirectory,getTempDirectory:Phoenix.VFS.getTempDir,ERR_CODES:ERR_CODES,getTimeSinceStartup:function(){return Date.now()-Phoenix.startTime},language:navigator.language},window.appshell||(window.appshell=Phoenix);