├── app ├── .gitignore ├── dist │ └── .gitignore ├── src │ ├── windows │ │ ├── run.bat │ │ ├── uninstall.bat │ │ ├── README.txt │ │ └── install.bat │ ├── linux │ │ ├── run.sh │ │ ├── uninstall.sh │ │ ├── README.txt │ │ └── install.sh │ ├── macos │ │ ├── run.sh │ │ ├── uninstall.command │ │ ├── README.txt │ │ └── install.command │ ├── common │ │ ├── manifest.template.json │ │ └── fsa-host.py │ └── fsa-host.py.spec ├── README.md ├── requirements-win-py3.txt └── build.py ├── src ├── assets │ └── .gitignore ├── icon.png ├── demo │ ├── worker0.js │ ├── config.js │ ├── worker.js │ ├── file.html │ └── file.js ├── lib │ ├── enum.js │ ├── code-editor │ │ ├── editor.css │ │ └── editor.js │ ├── external.js │ ├── util.js │ └── worker.js ├── manifest.json ├── background │ ├── main.js │ └── api │ │ └── tab.js ├── view │ ├── popup.html │ ├── prompt.js │ ├── popup.js │ ├── options.html │ ├── prompt.html │ ├── options.js │ ├── doc.html │ └── file-picker.js └── content-script │ └── main.js ├── .gitignore ├── .github └── images │ └── access_control.png ├── Makefile ├── README.md └── LICENSE /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /app/dist/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.git* -------------------------------------------------------------------------------- /src/assets/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.git* -------------------------------------------------------------------------------- /app/src/windows/run.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | 3 | python -u "%~dp0/fsa-host.py" 4 | -------------------------------------------------------------------------------- /src/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ichaoX/ext-file/HEAD/src/icon.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | .venv* 3 | .web-extension-id 4 | web-ext-artifacts 5 | *.DS_Store 6 | -------------------------------------------------------------------------------- /app/src/linux/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | cd "$(dirname $0)" 5 | 6 | env python -u ./fsa-host.py 7 | -------------------------------------------------------------------------------- /app/src/macos/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | cd "$(dirname $0)" 5 | 6 | env python -u ./fsa-host.py 7 | -------------------------------------------------------------------------------- /.github/images/access_control.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ichaoX/ext-file/HEAD/.github/images/access_control.png -------------------------------------------------------------------------------- /app/README.md: -------------------------------------------------------------------------------- 1 | [Native messaging](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging) -------------------------------------------------------------------------------- /app/src/windows/uninstall.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | 3 | setlocal 4 | 5 | cd "%~dp0" 6 | 7 | reg delete HKCU\Software\Mozilla\NativeMessagingHosts\webext.fsa.app /f 8 | 9 | pause 10 | -------------------------------------------------------------------------------- /app/requirements-win-py3.txt: -------------------------------------------------------------------------------- 1 | altgraph==0.17.4 2 | importlib-metadata==6.8.0 3 | packaging==23.2 4 | pefile==2023.2.7 5 | pyinstaller==6.1.0 6 | pyinstaller-hooks-contrib==2023.10 7 | pywin32-ctypes==0.2.2 8 | zipp==3.17.0 9 | -------------------------------------------------------------------------------- /app/src/common/manifest.template.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "webext.fsa.app", 3 | "description": "File System Access Native Messaging Host", 4 | "path": "__APP_PATH__", 5 | "type": "stdio", 6 | "allowed_extensions": [ 7 | "file@example.com", 8 | "framework@example.com" 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /app/src/linux/uninstall.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | cd "$(dirname $0)" 5 | 6 | MANIFEST_DIR="$HOME/.mozilla/native-messaging-hosts" 7 | 8 | [ "$UID" == "0" ] && MANIFEST_DIR="/usr/lib/mozilla/native-messaging-hosts" 9 | 10 | rm -f "$MANIFEST_DIR/webext.fsa.app.json" 11 | 12 | echo "Uninstalled." 13 | -------------------------------------------------------------------------------- /app/src/macos/uninstall.command: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | cd "$(dirname $0)" 5 | 6 | MANIFEST_DIR="$HOME/Library/Application Support/Mozilla/NativeMessagingHosts" 7 | 8 | [ "$UID" == "0" ] && MANIFEST_DIR="/Library/Application Support/Mozilla/NativeMessagingHosts" 9 | 10 | rm -f "$MANIFEST_DIR/webext.fsa.app.json" 11 | 12 | echo "Uninstalled." 13 | -------------------------------------------------------------------------------- /src/demo/worker0.js: -------------------------------------------------------------------------------- 1 | let worker = new Worker('worker.js'); 2 | 3 | self.addEventListener('message', (message) => { 4 | console.debug('worker0 -> worker', message); 5 | worker.postMessage(message.data); 6 | }); 7 | 8 | worker.addEventListener("message", (message) => { 9 | console.debug('worker0 <- worker', message); 10 | self.postMessage(message.data); 11 | }); 12 | -------------------------------------------------------------------------------- /src/demo/config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * manifest.json: 3 | * "content_security_policy": "script-src 'self' blob:; object-src 'self';", 4 | */ 5 | let FS_CONFIG = { 6 | WORKER_ENABLED: true, 7 | /* 8 | WORKER_SCRIPTS: [ 9 | browser.runtime.getURL('/assets/file-system-access.js?'), 10 | ], 11 | */ 12 | DEBUG_ENABLED: true, 13 | FILE_CACHE_EXPIRE: 60, 14 | EXPOSE_NAMESPACE: '__FS', 15 | }; 16 | -------------------------------------------------------------------------------- /app/src/windows/README.txt: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | To install the project, follow these steps: 4 | 5 | 1. Copy this directory to where you want to install it. 6 | 2. Run the `install.bat` script. 7 | 8 | This script will add a registry where the browser can find this helper app. 9 | 10 | # Uninstallation 11 | 12 | To uninstall the project, perform the following steps: 13 | 14 | 1. Run the `uninstall.bat` script. 15 | -------------------------------------------------------------------------------- /app/src/linux/README.txt: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | To install the project, follow these steps: 4 | 5 | 1. Copy this directory to where you want to install it. 6 | 2. Run the installation script by executing the following command: 7 | 8 | ``` bash 9 | ./install.sh 10 | ``` 11 | 12 | This script will add a manifest file where the browser can find this helper app. 13 | 14 | # Uninstallation 15 | 16 | To uninstall the project, perform the following steps: 17 | 18 | 1. Run the uninstallation script by executing the following command: 19 | 20 | ```bash 21 | ./uninstall.sh 22 | ``` 23 | -------------------------------------------------------------------------------- /src/lib/enum.js: -------------------------------------------------------------------------------- 1 | const FileSystemHandleKindEnum = { 2 | FILE: 'file', 3 | DIRECTORY: 'directory', 4 | }; 5 | const FileSystemPermissionModeEnum = { 6 | READ: 'read', 7 | READWRITE: 'readwrite', 8 | }; 9 | const PermissionStateEnum = { 10 | GRANTED: 'granted', 11 | DENIED: 'denied', 12 | PROMPT: 'prompt', 13 | }; 14 | const WriteCommandTypeEnum = { 15 | WRITE: "write", 16 | SEEK: "seek", 17 | TRUNCATE: "truncate", 18 | }; 19 | const StreamStateEnum = { 20 | WRITABLE: "writable", 21 | CLOSED: "closed", 22 | ERRORING: "erroring", 23 | ERRORED: "errored", 24 | }; 25 | -------------------------------------------------------------------------------- /app/src/macos/README.txt: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | To install the project, follow these steps: 4 | 5 | 1. Copy this directory to where you want to install it. (Note: Due to macOS security features, this may not work if installed in the "Desktop", "Documents" ,or "Downloads" directories.) 6 | 2. Run the installation script by executing the following command: 7 | 8 | ``` bash 9 | ./install.command 10 | ``` 11 | 12 | This script will add a manifest file where the browser can find this helper app. 13 | 14 | # Uninstallation 15 | 16 | To uninstall the project, perform the following steps: 17 | 18 | 1. Run the uninstallation script by executing the following command: 19 | 20 | ```bash 21 | ./uninstall.command 22 | ``` 23 | -------------------------------------------------------------------------------- /src/lib/code-editor/editor.css: -------------------------------------------------------------------------------- 1 | /** 2 | * Code Editor Extension 3 | * @version: 1.2 4 | */ 5 | 6 | .ext-code-editor { 7 | min-height: 300px; 8 | height: 300px; 9 | width: 100%; 10 | resize: vertical; 11 | overflow-y: hidden; 12 | background-color: #eee; 13 | box-sizing: border-box; 14 | } 15 | 16 | .ext-code-editor iframe { 17 | width: 100%; 18 | height: 100%; 19 | border: none; 20 | } 21 | 22 | .ext-code-editor--loading { 23 | animation: ext-code-editor--loading 1s infinite alternate; 24 | pointer-events: none; 25 | } 26 | 27 | .ext-code-editor--disconnected { 28 | opacity: 0.2; 29 | } 30 | 31 | @keyframes ext-code-editor--loading { 32 | 0% { 33 | opacity: 0; 34 | } 35 | 36 | 100% { 37 | opacity: 0.5; 38 | } 39 | } -------------------------------------------------------------------------------- /app/src/windows/install.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | 3 | setlocal 4 | 5 | cd "%~dp0" 6 | 7 | set /p choice="Do you want to install to this directory (y/n)? " 8 | 9 | if /i "%choice%"=="y" ( 10 | echo Installing... 11 | ) else if /i "%choice%"=="n" ( 12 | echo Canceled. 13 | pause 14 | goto :eof 15 | ) else ( 16 | echo Invalid choice. Please choose y or n. 17 | pause 18 | goto :eof 19 | ) 20 | 21 | set "APP_PATH=%CD%\fsa-host.exe" 22 | 23 | if not exist "%APP_PATH%" ( 24 | set "APP_PATH=%CD%\run.bat" 25 | ) 26 | 27 | set "MANIFEST_PATH=%CD%\manifest.json" 28 | 29 | powershell -Command "(Get-Content 'manifest.template.json') -replace '\"__APP_PATH__\"', '\"%APP_PATH:\=\\%\"' | Set-Content 'manifest.json'" ^ 30 | && reg add HKCU\Software\Mozilla\NativeMessagingHosts\webext.fsa.app /ve /t REG_SZ /d "%MANIFEST_PATH%" /f 31 | 32 | pause -------------------------------------------------------------------------------- /app/src/linux/install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | cd "$(dirname $0)" 5 | 6 | read -p "Do you want to install to this directory (y/n)? " choice 7 | 8 | if [ "$choice" == "y" ]; then 9 | echo "Installing..." 10 | elif [ "$choice" == "n" ]; then 11 | echo "Canceled." 12 | exit 0 13 | else 14 | echo "Invalid choice. Please choose y or n." 15 | exit 1 16 | fi 17 | 18 | APP_PATH="$(realpath fsa-host.py)" 19 | 20 | /usr/bin/env -S env &> /dev/null || APP_PATH="$(realpath run.sh)" 21 | 22 | chmod +x "$APP_PATH" 23 | 24 | MANIFEST="$(cat ./manifest.template.json)" 25 | 26 | MANIFEST_DIR="$HOME/.mozilla/native-messaging-hosts" 27 | 28 | [ "$UID" == "0" ] && MANIFEST_DIR="/usr/lib/mozilla/native-messaging-hosts" 29 | 30 | mkdir -p "$MANIFEST_DIR" 31 | 32 | echo "${MANIFEST//\"__APP_PATH__\"/$(printf '"%s"' "${APP_PATH//\"/\\\"}")}" > "$MANIFEST_DIR/webext.fsa.app.json" 33 | 34 | echo "Installed." 35 | -------------------------------------------------------------------------------- /app/src/macos/install.command: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | cd "$(dirname $0)" 5 | 6 | echo -n "Do you want to install to this directory (y/n)? " 7 | read choice 8 | 9 | if [ "$choice" == "y" ]; then 10 | echo "Installing..." 11 | elif [ "$choice" == "n" ]; then 12 | echo "Canceled." 13 | exit 0 14 | else 15 | echo "Invalid choice. Please choose y or n." 16 | exit 1 17 | fi 18 | 19 | APP_PATH="$PWD/fsa-host.py" 20 | 21 | /usr/bin/env -S env &> /dev/null || APP_PATH="$PWD/run.sh" 22 | 23 | chmod +x "$APP_PATH" 24 | 25 | MANIFEST="$(cat ./manifest.template.json)" 26 | 27 | MANIFEST_DIR="$HOME/Library/Application Support/Mozilla/NativeMessagingHosts" 28 | 29 | [ "$UID" == "0" ] && MANIFEST_DIR="/Library/Application Support/Mozilla/NativeMessagingHosts" 30 | 31 | mkdir -p "$MANIFEST_DIR" 32 | 33 | echo "${MANIFEST//\"__APP_PATH__\"/$(printf '"%s"' "${APP_PATH//\"/\\\"}")}" > "$MANIFEST_DIR/webext.fsa.app.json" 34 | 35 | echo "Installed." 36 | -------------------------------------------------------------------------------- /app/src/fsa-host.py.spec: -------------------------------------------------------------------------------- 1 | # -*- mode: python ; coding: utf-8 -*- 2 | 3 | 4 | a = Analysis( 5 | [os.path.join(SPECPATH, 'common/fsa-host.py')], 6 | pathex=[], 7 | binaries=[], 8 | datas=[], 9 | hiddenimports=[], 10 | hookspath=[], 11 | hooksconfig={}, 12 | runtime_hooks=[], 13 | excludes=[], 14 | noarchive=False, 15 | ) 16 | pyz = PYZ(a.pure) 17 | 18 | exe = EXE( 19 | pyz, 20 | a.scripts, 21 | [('u', None, 'OPTION'), ], 22 | a.binaries, 23 | a.datas, 24 | [], 25 | exclude_binaries=True, 26 | name='fsa-host', 27 | debug=False, 28 | bootloader_ignore_signals=False, 29 | strip=False, 30 | upx=True, 31 | console=True, 32 | disable_windowed_traceback=False, 33 | argv_emulation=False, 34 | target_arch=None, 35 | codesign_identity=None, 36 | entitlements_file=None, 37 | contents_directory='lib', 38 | ) 39 | coll = COLLECT( 40 | exe, 41 | a.binaries, 42 | a.datas, 43 | strip=False, 44 | upx=True, 45 | upx_exclude=[], 46 | name='fsa-host', 47 | ) 48 | -------------------------------------------------------------------------------- /src/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "description": "The File System Access API allows web apps to interact with files on the local device.", 3 | "manifest_version": 2, 4 | "name": "File System Access", 5 | "icons": { 6 | "32": "/icon.png" 7 | }, 8 | "version": "0.9.4", 9 | "permissions": [ 10 | "nativeMessaging", 11 | "storage", 12 | "webNavigation", 13 | "" 14 | ], 15 | "content_scripts": [], 16 | "background": { 17 | "scripts": [ 18 | "/lib/enum.js", 19 | "/lib/util.js", 20 | "/background/api/fs.js", 21 | "/background/api/tab.js", 22 | "/background/main.js" 23 | ] 24 | }, 25 | "page_action": { 26 | "default_popup": "/view/popup.html", 27 | "browser_style": true, 28 | "default_icon": { 29 | "32": "/icon.png" 30 | } 31 | }, 32 | "options_ui": { 33 | "open_in_tab": true, 34 | "page": "/view/options.html" 35 | }, 36 | "web_accessible_resources": [ 37 | "*" 38 | ], 39 | "externally_connectable": { 40 | "ids": [ 41 | "*" 42 | ] 43 | }, 44 | "browser_specific_settings": { 45 | "gecko": { 46 | "id": "file@example.com" 47 | } 48 | } 49 | } -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | APP_DIR := $(shell realpath app) 2 | WEBEXT_DIR := $(shell realpath src) 3 | 4 | channel ?= unlisted 5 | 6 | .PHONY: build 7 | build: build_webext 8 | 9 | .PHONY: build_app 10 | build_app: 11 | python "${APP_DIR}/build.py" 12 | chmod o+w -R "${APP_DIR}/dist/"* 13 | 14 | .PHONY: build_lib_ext 15 | build_lib_ext: 16 | cd "${WEBEXT_DIR}" && \ 17 | echo "/**\n * File System Access Extension\n * @version: $$(grep -oP '(?<="version": ")[\.\d]+' manifest.json)\n */\n" > assets/file-system-access.js && \ 18 | cat lib/enum.js lib/api/fs.js lib/external.js lib/worker.js >> assets/file-system-access.js 19 | 20 | .PHONY: build_assets 21 | build_assets: build_lib_ext build_app 22 | rm -f ${WEBEXT_DIR}/assets/*.zip && \ 23 | cd "${APP_DIR}/dist/" && \ 24 | for dir in */; do \ 25 | zip -r "${WEBEXT_DIR}/assets/helper-app-lite-$${dir%/}.zip" "$$dir"; \ 26 | done 27 | 28 | .PHONY: build_webext 29 | build_webext: build_assets 30 | cd "${WEBEXT_DIR}" && \ 31 | web-ext build -o -i '!assets/*' 32 | 33 | .PHONY: build_win_app 34 | build_win_app: 35 | cd "${APP_DIR}/dist/" && \ 36 | [ -f windows/*.exe ] && \ 37 | rm -f helper-app-full-windows.zip && \ 38 | zip -r helper-app-full-windows.zip "windows" 39 | 40 | .PHONY: sign 41 | sign: build_assets 42 | cd "${WEBEXT_DIR}" && \ 43 | web-ext sign --api-key "$(api-key)" --api-secret "$(api-secret)" --channel "$(channel)" -i '!assets/*' 44 | -------------------------------------------------------------------------------- /src/demo/worker.js: -------------------------------------------------------------------------------- 1 | let parseHandle = (handle) => { 2 | if (!self.__FS || !self.__FS.parseHandle) return handle; 3 | return self.__FS.parseHandle(handle); 4 | }; 5 | 6 | self.onmessage = async (message) => { 7 | console.debug('worker', message); 8 | self.lastMessage = message; 9 | 10 | let { action, data } = message.data || {}; 11 | let request = message.data; 12 | let response = { action, request, data: null }; 13 | switch (action) { 14 | case 'workerReadFile': { 15 | let fileHandle = parseHandle(data); 16 | console.time("worker-readFile"); 17 | try { 18 | let file = await fileHandle.getFile(); 19 | response.data = file; 20 | console.log(`size: ${file.size}`); 21 | } finally { 22 | console.timeEnd("worker-readFile"); 23 | } 24 | break; 25 | } 26 | case 'workerReadDir': { 27 | let dirHandle = parseHandle(data); 28 | response.data = []; 29 | console.time("worker-readDir"); 30 | try { 31 | let i = 0; 32 | for await (let [key, handle] of dirHandle) { 33 | response.data.push([key, handle]); 34 | i++; 35 | } 36 | console.log(`num: ${i}`); 37 | } finally { 38 | console.timeEnd("worker-readDir"); 39 | } 40 | break; 41 | } 42 | } 43 | self.postMessage(response) 44 | }; -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Firefox File System Access Extension 2 | 3 | This extension brings the [File System Access API](https://wicg.github.io/file-system-access/) to Firefox that helps web apps such as [vscode.dev](https://vscode.dev) read and write local files and folders. 4 | 5 | ![Access Control](.github/images/access_control.png) 6 | 7 | ## Main features 8 | 9 | * Implemented `showOpenFilePicker()`, `showDirectoryPicker()`, `showSaveFilePicker()` and related interfaces. 10 | 11 | * Set to enable specific File System Access features on matching web pages. 12 | 13 | * Provides File System Access API for other compatible WebExtensions. 14 | 15 | ## Notes 16 | 17 | * The local file operations required by this extension cannot be performed in the browser, and a [helper app](app) needs to be installed to assist in the related work. 18 | 19 | * The optional Code Editor feature is provided by the [Code Editor](https://addons.mozilla.org/firefox/addon/code-editor/) extension. 20 | 21 | ## Limitations 22 | 23 | * By default, `FileSystemHandle` will lose its instance methods after cloning (e.g. using `IndexedDB` or `postMessage`), and requires additional configuration of the `FS_CONFIG.CLONE_ENABLED`. 24 | Web developers can use `__FILE_SYSTEM_TOOLS__.parseHandle(handle)` to restore the instance methods. 25 | 26 | * Limited Worker context support and requires additional configuration of the `FS_CONFIG.WORKER_ENABLED`. 27 | 28 | * Read file size is limited by the `FS_CONFIG.FILE_SIZE_LIMIT`. 29 | Web developers can read large file streams and slices with `handle.getFile({ _allowNonNative: true })`, 30 | and write large file in-place with `handle.createWritable({ _inPlace: true, keepExistingData: true })`. 31 | 32 | * `DataTransferItem.prototype.getAsFileSystemHandle` is not implemented. 33 | -------------------------------------------------------------------------------- /app/build.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import logging 4 | import os 5 | import shutil 6 | import sys 7 | 8 | rootDir = os.path.dirname(os.path.abspath(__file__)) 9 | srcDir = os.path.join(rootDir, 'src') 10 | commonAssetDir = os.path.join(srcDir, 'common') 11 | 12 | distDir = os.path.join(rootDir, 'dist') 13 | windowsDir = os.path.join(distDir, 'windows') 14 | linuxDir = os.path.join(distDir, 'linux') 15 | macDir = os.path.join(distDir, 'macos') 16 | 17 | appFileName = 'fsa-host.py' 18 | manifestFileName = 'manifest.template.json' 19 | 20 | 21 | def copytree(src, dst): 22 | for item in os.listdir(src): 23 | s = os.path.join(src, item) 24 | d = os.path.join(dst, item) 25 | if os.path.isdir(s): 26 | shutil.copytree(s, d) 27 | else: 28 | shutil.copy2(s, d) 29 | 30 | 31 | platformDir = windowsDir 32 | platformAssetDir = os.path.join(srcDir, 'windows') 33 | 34 | if os.path.isdir(platformDir): 35 | shutil.rmtree(platformDir) 36 | os.makedirs(platformDir) 37 | 38 | copytree(commonAssetDir, platformDir) 39 | copytree(platformAssetDir, platformDir) 40 | 41 | if sys.platform == 'win32': 42 | try: 43 | import PyInstaller.__main__ 44 | PyInstaller.__main__.run([ 45 | # os.path.join(commonAssetDir, appFileName), 46 | os.path.join(srcDir, appFileName + '.spec'), 47 | '--distpath', platformDir, 48 | '--workpath', os.path.join(rootDir, 'build'), 49 | # '--specpath', srcDir, 50 | # '--onedir', 51 | # '--contents-directory', 'lib', 52 | ]) 53 | except Exception as e: 54 | logging.exception('pyinstaller failed to execute') 55 | 56 | _ = os.path.join(platformDir, os.path.splitext(appFileName)[0]) 57 | if os.path.isdir(_): 58 | for name in os.listdir(_): 59 | shutil.move(os.path.join(_, name), platformDir) 60 | os.rmdir(_) 61 | 62 | platformDir = linuxDir 63 | platformAssetDir = os.path.join(srcDir, 'linux') 64 | 65 | if os.path.isdir(platformDir): 66 | shutil.rmtree(platformDir) 67 | os.makedirs(platformDir) 68 | 69 | copytree(commonAssetDir, platformDir) 70 | copytree(platformAssetDir, platformDir) 71 | 72 | 73 | platformDir = macDir 74 | platformAssetDir = os.path.join(srcDir, 'macos') 75 | 76 | if os.path.isdir(platformDir): 77 | shutil.rmtree(platformDir) 78 | os.makedirs(platformDir) 79 | 80 | copytree(commonAssetDir, platformDir) 81 | copytree(platformAssetDir, platformDir) 82 | -------------------------------------------------------------------------------- /src/background/main.js: -------------------------------------------------------------------------------- 1 | console.log('background start'); 2 | 3 | let asyncMessage = (handler) => { 4 | let result; 5 | try { 6 | result = handler(); 7 | } catch (e) { 8 | result = { code: 500, data: e }; 9 | } 10 | if (!result) return; 11 | return (async () => { 12 | try { 13 | result = await result; 14 | } catch (e) { 15 | console.warn(e); 16 | result = { code: 500, data: e }; 17 | } 18 | if (typeof structuredClone === 'undefined' && result.code !== 200 && result.data instanceof Error) { 19 | result.data = "" + result.data; 20 | } 21 | return result; 22 | })(); 23 | }; 24 | 25 | util.addListener(browser.runtime.onMessage, (message, sender, sendResponse) => { 26 | util.log(message); 27 | return asyncMessage(() => { 28 | message.data = message.data || {}; 29 | let action = message.action.split("."); 30 | if (action.length > 2) action.push(action.splice(1).join('.')); 31 | switch (action[0]) { 32 | case 'fs': 33 | message.action = action[1]; 34 | return FSApi.onMessage(message, sender, sendResponse); 35 | case 'ext:fs': 36 | message.action = action[1]; 37 | return FSApi.onMessageExternal(message, sender, sendResponse); 38 | case 'tab': 39 | message.action = action[1]; 40 | return Tab.onMessage(message, sender, sendResponse); 41 | } 42 | }); 43 | }); 44 | 45 | util.addListener(browser.runtime.onMessageExternal, (message, sender, sendResponse) => { 46 | util.log(message); 47 | return asyncMessage(() => { 48 | message.data = message.data || {}; 49 | let action = message.action.split("."); 50 | if (action.length > 2) action.push(action.splice(1).join('.')); 51 | switch (action[0]) { 52 | case 'ext:fs': 53 | message.action = action[1]; 54 | return FSApi.onMessageExternal(message, sender, sendResponse); 55 | } 56 | }); 57 | }); 58 | 59 | util.addListener(browser.runtime.onInstalled, async (details) => { 60 | console.log(details); 61 | if (details && details.reason === 'install') { 62 | try { 63 | await FSApi.tryGetConstants(); 64 | FSApi.disconnect(); 65 | } catch (e) { 66 | console.warn(e); 67 | } 68 | } 69 | }); 70 | -------------------------------------------------------------------------------- /src/demo/file.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | DEMO 7 | 8 | 9 | 26 | 27 | 28 | 29 | 30 | 31 |
32 | 33 | 34 | | 35 | 36 | | 37 | 38 | 39 | | 40 | 41 |
42 | 43 | 44 |
45 | 46 | 47 | 48 | | 49 | 50 | 51 |
52 | 53 | 54 | 55 |
56 | 57 | 58 | 59 | | 60 | 61 | | 62 | 63 | | 64 | 65 |
66 | 67 | 68 |
69 | 70 | 71 | 72 | | 73 | 74 | 75 | 76 | | 77 | 78 | 79 |
80 | 81 | 82 | 83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /src/lib/external.js: -------------------------------------------------------------------------------- 1 | if (self.__fs_init && self.importScripts) { 2 | const __fs_init = self.__fs_init; 3 | self.__fs_init = (fs_options = {}, ...args) => { 4 | Object.assign(fs_options, { isExternal: true }); 5 | return __fs_init(fs_options, ...args); 6 | }; 7 | } else if (self.__fs_init) { 8 | 9 | const extensionId = "file@example.com"; 10 | 11 | const scope = self; 12 | const getConfig = (name = null, def = undefined, type = null) => { 13 | if ('undefined' !== typeof FS_CONFIG && FS_CONFIG) { 14 | if (name === null) { 15 | return FS_CONFIG; 16 | } else if (FS_CONFIG.hasOwnProperty(name) && (!type || type === typeof FS_CONFIG[name])) { 17 | return FS_CONFIG[name]; 18 | } 19 | } 20 | return def; 21 | }; 22 | const debug = (...args) => { 23 | if (!getConfig('DEBUG_ENABLED')) return; 24 | let i = args.length; 25 | while (args[--i] === undefined && i >= 0) args.pop(); 26 | console.debug(...args); 27 | }; 28 | 29 | let extMessage = getConfig('EXTENSION_TIP', 'Using the "File System Access API" requires the "File System Access" extension (https://addons.mozilla.org/en-US/firefox/addon/file-system-access/) and helper app to be installed.'); 30 | 31 | let sendMessage = async (action, data) => { 32 | try { 33 | if (!action.startsWith('ext:')) action = `ext:${action}`; 34 | // console.log('request', action, data); 35 | let response; 36 | try { 37 | response = await browser.runtime.sendMessage(extensionId, { action, data, origin: scope.origin || location.origin }, {}); 38 | } catch (e) { 39 | if (typeof extMessage === "string" && extMessage 40 | && /Receiving end does not exist/i.test((e && e.message) || "") 41 | ) { 42 | let message = `${extMessage} \n\nError details: \n${e.message}`; 43 | throw new Error(message); 44 | } 45 | throw e; 46 | } 47 | if (response.code !== 200) { 48 | console.warn(response); 49 | throw response.data || response; 50 | } 51 | extMessage = false; 52 | // console.log('response', response); 53 | return response.data; 54 | } catch (e) { 55 | if (e && e.trace) { 56 | // XXX 57 | debug(e.trace); 58 | e = e.message; 59 | } 60 | throw e instanceof Error ? scope.Error(e.message) : e; 61 | } 62 | } 63 | 64 | let fs_options = { 65 | scope, 66 | getConfig, 67 | debug, 68 | sendMessage, 69 | isExternal: true, 70 | }; 71 | 72 | self.__fs_init(fs_options); 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/view/popup.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 82 | 83 | 84 | 85 | 117 | 118 | 119 | 120 | 121 | 122 | -------------------------------------------------------------------------------- /src/view/prompt.js: -------------------------------------------------------------------------------- 1 | let urlObj = new URL(location.href); 2 | let origin = urlObj.searchParams.get("origin"); 3 | let $container = document.body; 4 | let _resolveData = {}; 5 | let getResolveData = (key) => (_resolveData[key] ? _resolveData[key]() : null); 6 | 7 | let renderText = (key, text, attr = false) => { 8 | [...$container.querySelectorAll(`[data-text="${key}"]`)].map(e => { 9 | if (attr) { 10 | e.setAttribute('data-value', text); 11 | } else { 12 | e.textContent = text; 13 | } 14 | }); 15 | }; 16 | 17 | (async () => { 18 | let prompt = await util.sendMessage('fs.getPrompt', { origin }); 19 | if (!prompt) { 20 | // XXX 21 | self.open('about:blank', '_self').close(); 22 | return; 23 | } 24 | let type = prompt.type; 25 | let m = prompt.message; 26 | console.log(prompt); 27 | $container = document.querySelector(`.container.${type}`); 28 | $container.style.display = ''; 29 | $container.setAttribute('data-message-action', m.action); 30 | let $n = $container.querySelector('[autofocus]'); 31 | if ($n) $n.focus(); 32 | renderText('origin', origin); 33 | if (Array.isArray(prompt.resolveKeys)) { 34 | [...$container.querySelectorAll("[data-action].hide")].forEach($n => { 35 | if (prompt.resolveKeys.includes($n.getAttribute("data-action"))) { 36 | $n.classList.remove('hide'); 37 | } 38 | }); 39 | } 40 | let autoClose = false; 41 | let resolvePrompt = async (action, data) => { 42 | try { 43 | autoClose = await util.sendMessage('fs.resolvePrompt', { 44 | origin, 45 | id: prompt.id, 46 | key: action, 47 | data, 48 | }); 49 | if (autoClose) self.close(); 50 | } catch (e) { 51 | console.warn(e); 52 | alert(e); 53 | } 54 | } 55 | self.onbeforeunload = () => { 56 | if (!autoClose) resolvePrompt('cancel'); 57 | }; 58 | document.body.addEventListener('click', async (event) => { 59 | let target = event.target; 60 | let action; 61 | while (target && !(action = target.getAttribute('data-action'))) { 62 | target = target.parentElement 63 | } 64 | if (!action) return; 65 | event.preventDefault(); 66 | event.stopPropagation(); 67 | let data = await getResolveData(action); 68 | await resolvePrompt(action, data); 69 | }); 70 | if (prompt.sender && prompt.sender.tab) { 71 | let sender = prompt.sender; 72 | let $a = $container.querySelector('a[data-action="viewTab"]'); 73 | if (sender.url) $a.href = sender.url; 74 | if (sender.tab.title) $a.title = sender.tab.title; 75 | renderText('tab-detail', `id=${sender.tab.id}:${sender.frameId}`); 76 | if (sender.id) { 77 | renderText('sender-id', sender.id); 78 | if (sender.id !== browser.runtime.id) { 79 | renderText('external', sender.id, true); 80 | } 81 | } 82 | } 83 | try { 84 | switch (prompt.type) { 85 | case 'request-permission': { 86 | let { mode, path } = m.data || {}; 87 | let modeText = mode === FileSystemPermissionModeEnum.READ ? 'view' : 'edit'; 88 | renderText('perm-mode', modeText); 89 | renderText('perm-mode-detail', `${modeText} (${mode})`); 90 | renderText('perm-mode-detail', modeText, true); 91 | renderText('path', path); 92 | break; 93 | } 94 | case 'file-picker': { 95 | await initFilePicker(m); 96 | break; 97 | } 98 | } 99 | } catch (e) { 100 | console.warn(e); 101 | alert(e); 102 | } 103 | })(); 104 | -------------------------------------------------------------------------------- /src/view/popup.js: -------------------------------------------------------------------------------- 1 | let render = async () => { 2 | let tabInfo = (await browser.tabs.query({ active: true, currentWindow: true }))[0]; 3 | let infos = await util.sendMessage('tab.queryPermissions', { tabId: tabInfo.id }); 4 | if (!Object.values(infos).find(info => !!info.granted)) self.close(); 5 | document.body.innerHTML = ''; 6 | let splitPath = (path) => { 7 | let level = []; 8 | let match = path.match(/^(\/\/[^\/]*|[a-z]:|\/)/i); 9 | let prefix = match && match[1] ? match[1] : ''; 10 | if (prefix !== "") level.push(prefix); 11 | path = path.slice(prefix.length); 12 | if (path !== "") level.push(...path.split(new RegExp(`(?=[/])`))); 13 | return level; 14 | }; 15 | let isMinor = (path, list, inList = false) => { 16 | let paths = splitPath(path).reduce((p, a, i) => (p.push((p[i - 1] || "") + a), p), []); 17 | for (let i of list) { 18 | if (inList && i === path) continue; 19 | if (paths.includes(i)) { 20 | return true; 21 | } 22 | } 23 | return false; 24 | }; 25 | for (let origin in infos) { 26 | let info = infos[origin]; 27 | if (!info.granted) continue; 28 | let template = document.querySelector('#origin-permission').content.cloneNode(true); 29 | let paths = []; 30 | let mode; 31 | mode = template.querySelector(".mode.readwrite"); 32 | if (info.permission[FileSystemPermissionModeEnum.READWRITE].length > 0) { 33 | let list = info.permission[FileSystemPermissionModeEnum.READWRITE].sort(); 34 | let ul = mode.querySelector("ul"); 35 | let li = ul.querySelector("li"); 36 | li.remove(); 37 | for (let path of list) { 38 | let item = li.cloneNode(true); 39 | item.querySelector("[data-path]").setAttribute("data-path", path); 40 | item.querySelector(".path").textContent = path; 41 | if (isMinor(path, list, true) || isMinor(path, paths)) item.classList.add("minor"); 42 | ul.appendChild(item); 43 | } 44 | paths.push(...list); 45 | } else { 46 | mode.remove(); 47 | } 48 | mode = template.querySelector(".mode.read"); 49 | if (info.permission[FileSystemPermissionModeEnum.READ].length > 0) { 50 | let list = info.permission[FileSystemPermissionModeEnum.READ].sort(); 51 | let ul = mode.querySelector("ul"); 52 | let li = ul.querySelector("li"); 53 | li.remove(); 54 | for (let path of list) { 55 | let item = li.cloneNode(true); 56 | item.querySelector("[data-path]").setAttribute("data-path", path); 57 | item.querySelector(".path").textContent = path; 58 | if (isMinor(path, list, true) || isMinor(path, paths)) item.classList.add("minor"); 59 | ul.appendChild(item); 60 | } 61 | paths.push(...list); 62 | } else { 63 | mode.remove(); 64 | } 65 | template.querySelector(".origin").textContent = origin; 66 | [...template.querySelectorAll("[data-origin]")].forEach(n => n.setAttribute("data-origin", origin)); 67 | document.body.appendChild(template); 68 | } 69 | }; 70 | 71 | render(); 72 | 73 | self.addEventListener('click', async function (event) { 74 | let target = event.target; 75 | let data = JSON.parse(JSON.stringify(target.dataset)); 76 | if (data.action) { 77 | Object.entries(data).forEach(([k, v]) => { 78 | // XXX 79 | if (k.endsWith('.ctrl')) { 80 | if (event.ctrlKey) data[k.replace(/\.[^.]*$/, '')] = v; 81 | delete data[k]; 82 | } 83 | if (k.endsWith('.shift')) { 84 | if (event.shiftKey) data[k.replace(/\.[^.]*$/, '')] = v; 85 | delete data[k]; 86 | } 87 | }); 88 | await util.sendMessage(data.action, data); 89 | render(); 90 | } 91 | }); 92 | -------------------------------------------------------------------------------- /src/background/api/tab.js: -------------------------------------------------------------------------------- 1 | const action = { 2 | update(options) { 3 | if (!options.tabId) return; 4 | let tabId = options.tabId; 5 | if (options.title !== undefined) { 6 | let details = { tabId, title: options.title }; 7 | if (browser.pageAction) browser.pageAction.setTitle(details); 8 | } 9 | if (options.icon !== undefined) { 10 | let details = { tabId, path: options.icon }; 11 | if (browser.pageAction) browser.pageAction.setIcon(details); 12 | } 13 | // XXX blank 14 | if (browser.pageAction) browser.pageAction.show(tabId); 15 | }, 16 | disable(tabId) { 17 | if (browser.pageAction) browser.pageAction.hide(tabId); 18 | }, 19 | onClicked(handler) { 20 | if (browser.pageAction) browser.pageAction.onClicked.addListener(handler); 21 | }, 22 | }; 23 | 24 | const Tab = { 25 | originMap: {}, 26 | register(url, tabId, frameId = 0) { 27 | if (!url || tabId <= 0) return; 28 | let origin = (new URL(url)).origin; 29 | if (!this.originMap[tabId]) { 30 | this.originMap[tabId] = {}; 31 | if (frameId > 0) { 32 | browser.webNavigation.getAllFrames({ tabId }).then(frameInfos => { 33 | // XXX origin 34 | frameInfos.forEach(frameInfo => Tab.register(frameInfo.url, tabId, frameInfo.frameId)); 35 | }); 36 | } 37 | } 38 | this.originMap[tabId][frameId] = origin; 39 | }, 40 | onChange(tabId) { 41 | if (Array.isArray(tabId)) { 42 | tabId.forEach(id => this.onChange(id)); 43 | return; 44 | } 45 | if (!this.originMap[tabId]) return; 46 | let origins = Object.values(this.originMap[tabId]); 47 | origins = Array.from(new Set(origins)); 48 | let hasPermission = origins.find(origin => FSApi.hasPermission(origin)); 49 | if (hasPermission) { 50 | action.update({ tabId }); 51 | } else { 52 | action.disable(tabId); 53 | } 54 | }, 55 | onRemoved(tabId) { 56 | delete this.originMap[tabId]; 57 | }, 58 | getFrameOrigin(tabId, frameId = 0) { 59 | if (!this.originMap[tabId]) return false; 60 | return this.originMap[tabId][frameId]; 61 | }, 62 | originThrotte: {}, 63 | onOriginUpdated(origin, delay = 500) { 64 | if (delay && this.originThrotte[origin]) return; 65 | if (this.originThrotte[origin]) { 66 | clearTimeout(this.originThrotte[origin]); 67 | delete this.originThrotte[origin]; 68 | } 69 | this.originThrotte[origin] = setTimeout(() => { 70 | delete this.originThrotte[origin]; 71 | let tabIds = []; 72 | for (let tabId in this.originMap) { 73 | for (let frameId in this.originMap[tabId]) { 74 | if (this.originMap[tabId][frameId] == origin) { 75 | tabIds.push(parseInt(tabId)); 76 | break; 77 | } 78 | } 79 | } 80 | this.onChange(tabIds); 81 | }, delay || 0); 82 | }, 83 | async onMessage(message, sender, sendResponse) { 84 | if ('function' === typeof this.action[message.action]) { 85 | return await this.action[message.action](message, sender); 86 | } 87 | throw 'Not implemented'; 88 | }, 89 | action: { 90 | get t() { 91 | return Tab; 92 | }, 93 | async queryPermissions(message) { 94 | let tabId = message.data.tabId; 95 | let result = {}; 96 | let map = this.t.originMap[tabId]; 97 | if (map) { 98 | for (let frameId in map) { 99 | let origin = map[frameId]; 100 | if (!result[origin]) { 101 | result[origin] = { 102 | granted: FSApi.hasPermission(origin), 103 | permission: FSApi.getOriginPermission(origin, PermissionStateEnum.GRANTED), 104 | frameIds: [], 105 | }; 106 | } 107 | result[origin].frameIds.push(frameId); 108 | } 109 | } 110 | return util.wrapResponse(result); 111 | }, 112 | }, 113 | }; 114 | 115 | try { 116 | util.addListener(browser.webNavigation.onCommitted, (details) => { 117 | // XXX origin 118 | Tab.register(details.url, details.tabId, details.frameId); 119 | Tab.onChange(details.tabId); 120 | if (details.frameId === 0) FSApi.onUnload(details.tabId); 121 | }); 122 | } catch (e) { 123 | console.warn(e); 124 | } 125 | 126 | util.addListener(browser.tabs.onRemoved, (tabId, removeInfo) => { 127 | Tab.onRemoved(tabId); 128 | FSApi.onUnload(tabId); 129 | }); 130 | 131 | /* 132 | (async () => { 133 | let tabInfos = await browser.tabs.query({}); 134 | tabInfos.forEach(async tabInfo => { 135 | let frameInfos = await browser.webNavigation.getAllFrames({ tabId: tabInfo.id }); 136 | // XXX origin 137 | if (!frameInfos.length) Tab.register(tabInfo.url, tabInfo.id); 138 | else frameInfos.forEach(frameInfo => Tab.register(frameInfo.url, tabInfo.id, frameInfo.frameId)); 139 | }); 140 | })(); 141 | */ 142 | -------------------------------------------------------------------------------- /src/lib/util.js: -------------------------------------------------------------------------------- 1 | const util = { 2 | addListener(event, listener, ...extra) { 3 | if (!event) { 4 | console.trace('Event does not exist!'); 5 | return; 6 | } 7 | event.addListener(listener, ...extra); 8 | let destroy = () => { 9 | if (event.hasListener(listener)) { 10 | event.removeListener(listener); 11 | } 12 | }; 13 | this.destroy(destroy); 14 | return { 15 | destroy, 16 | }; 17 | }, 18 | _context: 'global', 19 | _contexts: {}, 20 | context(context) { 21 | if (context !== undefined) { 22 | let _context = this._context; 23 | this._context = context; 24 | return _context; 25 | } else { 26 | if (!this._contexts[this._context]) this._contexts[this._context] = {}; 27 | return this._contexts[this._context]; 28 | } 29 | }, 30 | destroy(callback = null) { 31 | let context = this.context(); 32 | if (!context.destroyList) context.destroyList = []; 33 | if (callback) { 34 | context.destroyList.push(callback); 35 | } else { 36 | while (callback = context.destroyList.pop()) { 37 | try { 38 | callback(); 39 | } catch (e) { 40 | console.warn(e); 41 | } 42 | } 43 | } 44 | return this; 45 | }, 46 | async toDataURL(blob) { 47 | return await new Promise((resolve, reject) => { 48 | const reader = new FileReader(); 49 | reader.onloadend = () => resolve(reader.result); 50 | reader.onerror = (e) => reject(e); 51 | reader.readAsDataURL(blob); 52 | }); 53 | }, 54 | async url2Blob(url, options = {}) { 55 | // XXX 56 | let response = await fetch(url, options); 57 | if (!options.ignoreFail && !response.ok) throw response; 58 | return await response.blob(); 59 | }, 60 | async base64Encode(data) { 61 | let url = await this.toDataURL(data); 62 | return url.slice(url.indexOf(',') + 1); 63 | }, 64 | async base64Decode(base64, type = '') { 65 | // return await this.url2Blob(`data:${type};base64,${base64}`); 66 | let bc = atob(base64); 67 | let ba = new Uint8Array(bc.length); 68 | for (let i = 0; i < bc.length; i++) { 69 | ba[i] = bc.charCodeAt(i); 70 | } 71 | return new Blob([ba], { type }); 72 | }, 73 | _storageArea: browser.storage.sync ? 'sync' : 'local', 74 | _storagePrefix: '', 75 | _defaultConfig: { 76 | content_script_match: { 77 | matches: [ 78 | "https://*/*", 79 | "*://*.localhost/*", 80 | "*://127.0.0.1/*" 81 | ], 82 | // excludeMatches: [], 83 | // includeGlobs: [], 84 | // excludeGlobs: [], 85 | allFrames: true, 86 | js: [{ 87 | code: `/** 88 | * @type {FS_CONFIG} 89 | */ 90 | let FS_CONFIG = { 91 | API_ENABLED: !!self.isSecureContext, 92 | CLONE_ENABLED: ['vscode.dev'].includes(location.hostname), 93 | WORKER_ENABLED: ['vscode.dev'].includes(location.hostname), 94 | FILE_SIZE_LIMIT: 30 * 1024 ** 2, 95 | FILE_CACHE_EXPIRE: 5 * 60, 96 | EXPOSE_NAMESPACE: true, 97 | }; 98 | `, 99 | }], 100 | }, 101 | code_editor: false, 102 | prompt_tab: 'auto', 103 | internal_file_picker: 'auto', 104 | app_tips: true, 105 | }, 106 | async getSetting(key, def = null, area = null) { 107 | if (!area) area = this._storageArea; 108 | let newkey = `${this._storagePrefix}${key}`; 109 | return (await browser.storage[area].get({ [newkey]: def || this._defaultConfig[key] || null }))[newkey]; 110 | }, 111 | async setSetting(key, data, area = null) { 112 | let def = undefined; 113 | if (area === null) def = this._defaultConfig[key] 114 | if (!area) area = this._storageArea; 115 | if (def !== undefined && JSON.stringify(def) === JSON.stringify(data)) { 116 | return await browser.storage[area].remove([key]); 117 | } 118 | key = `${this._storagePrefix}${key}`; 119 | return await browser.storage[area].set({ [key]: data }); 120 | }, 121 | async getSiteConfig(origin, type, def = null) { 122 | return await this.getSetting(`${type}:${origin}`, def, 'local'); 123 | }, 124 | async setSiteConfig(origin, type, data) { 125 | return await this.setSetting(`${type}:${origin}`, data, 'local'); 126 | }, 127 | async sendMessage(action, data) { 128 | try { 129 | let response = await browser.runtime.sendMessage({ action, data }); 130 | return this.unwrapResponse(response); 131 | } catch (e) { 132 | throw e; 133 | } 134 | }, 135 | wrapResponse(data = null, code = 200) { 136 | return { data, code }; 137 | }, 138 | unwrapResponse(response) { 139 | if (response?.code !== 200) { 140 | console.warn(response); 141 | throw response?.data || response; 142 | } 143 | return response.data; 144 | }, 145 | debug: false, 146 | get log() { 147 | return this.debug ? console.debug.bind(console) : () => null; 148 | }, 149 | }; 150 | -------------------------------------------------------------------------------- /src/content-script/main.js: -------------------------------------------------------------------------------- 1 | if (self.__fs_init) { 2 | 3 | const scope = self; 4 | const getConfig = (name = null, def = undefined, type = null) => { 5 | if ('undefined' !== typeof FS_CONFIG && FS_CONFIG) { 6 | if (name === null) { 7 | return FS_CONFIG; 8 | } else if (FS_CONFIG.hasOwnProperty(name) && (!type || type === typeof FS_CONFIG[name])) { 9 | return FS_CONFIG[name]; 10 | } 11 | } 12 | return def; 13 | }; 14 | const debug = (...args) => { 15 | if (!getConfig('DEBUG_ENABLED')) return; 16 | let i = args.length; 17 | while (args[--i] === undefined && i >= 0) args.pop(); 18 | console.debug(...args); 19 | }; 20 | const AsyncFunction = (async () => { }).constructor; 21 | const AsyncGeneratorFunction = (async function* () { }).constructor; 22 | const getWrapped = o => o.wrappedJSObject; 23 | const cloneIntoScope = (o, deep = true) => { 24 | if (!deep) { 25 | return cloneInto(o, scope, { cloneFunctions: true }); 26 | } 27 | switch (typeof o) { 28 | case 'function': 29 | if (o.wrappedJSObject) return o; 30 | if (o.constructor === AsyncFunction) return wrapAsyncFunction(o); 31 | if (o.constructor === AsyncGeneratorFunction) return wrapAsyncGeneratorFunction(o); 32 | return cloneIntoScope(o, false); 33 | case 'object': 34 | if (!o) return o; 35 | // XXX __proto__ 36 | if (o.wrappedJSObject) return o; 37 | let result = cloneIntoScope(o, false); 38 | for (let k in o) { 39 | if (typeof o[k] === 'function' && o[k].constructor !== Function) { 40 | result.wrappedJSObject[k] = cloneIntoScope(o[k], true); 41 | } 42 | } 43 | Object.getOwnPropertySymbols(o).forEach((k) => result.wrappedJSObject[k] = cloneIntoScope(o[k], true)); 44 | /* 45 | if (o.__proto__ && o.__proto__.wrappedJSObject) result.wrappedJSObject.__proto__ = o.__proto__; 46 | */ 47 | return result; 48 | default: 49 | return o; 50 | } 51 | }; 52 | const exportIntoScope = (name, o) => { 53 | scope.wrappedJSObject[name] = cloneIntoScope(o); 54 | // exportFunction(f, scope, { defineAs: name }) 55 | }; 56 | const setProto = (o, proto, wrappedJSObjectOnly = false) => { 57 | if (proto) { 58 | if (!wrappedJSObjectOnly) o.__proto__ = proto; 59 | o.wrappedJSObject.__proto__ = proto; 60 | } 61 | return o; 62 | }; 63 | const wrapPromise = (p, clone = true) => new scope.Promise(async (resolve, reject) => { 64 | try { 65 | let result = await p; 66 | if (clone) result = cloneIntoScope(result); 67 | resolve(result); 68 | } catch (e) { 69 | debug(e); 70 | reject(e); 71 | } 72 | }); 73 | const wrapAsyncFunction = (f) => { 74 | return cloneIntoScope(function (...args) { 75 | return wrapPromise(f.bind(this)(...args)); 76 | }); 77 | }; 78 | const wrapAsyncGeneratorFunction = (g) => { 79 | return cloneIntoScope(function (...args) { 80 | let generator = g.bind(this)(...args); 81 | let wrapProp = (prop) => { 82 | return async function (...args) { 83 | let result = await generator[prop](...args); 84 | let value = result.value; 85 | delete result.value; 86 | result = cloneIntoScope(result); 87 | result.wrappedJSObject.value = cloneIntoScope(value); 88 | return result; 89 | }; 90 | }; 91 | let generatorProp = cloneIntoScope({ 92 | next: wrapProp('next'), 93 | return: wrapProp('return'), 94 | throw: wrapProp('throw'), 95 | [Symbol.asyncIterator]() { 96 | return generatorProp; 97 | }, 98 | }); 99 | return setProto(cloneIntoScope({}), generatorProp); 100 | }); 101 | }; 102 | let sendMessage = async (action, data) => { 103 | try { 104 | let response = await browser.runtime.sendMessage({ action, data, origin: scope.origin || location.origin }); 105 | if (response.code !== 200) { 106 | console.warn(response); 107 | throw response.data || response; 108 | } 109 | return response.data; 110 | } catch (e) { 111 | if (e && e.trace) { 112 | // XXX 113 | debug(e.trace); 114 | e = e.message; 115 | } 116 | throw e instanceof Error ? scope.Error(e.message) : cloneIntoScope(e); 117 | } 118 | } 119 | let workerScripts = [ 120 | browser.runtime.getURL('/lib/enum.js'), 121 | browser.runtime.getURL('/lib/api/fs.js'), 122 | browser.runtime.getURL('/lib/worker.js'), 123 | ]; 124 | 125 | let fs_options = { 126 | scope, 127 | getConfig, 128 | debug, 129 | getWrapped, 130 | cloneIntoScope, 131 | exportIntoScope, 132 | setProto, 133 | sendMessage, 134 | workerScripts, 135 | }; 136 | 137 | self.__fs_init(fs_options); 138 | 139 | } -------------------------------------------------------------------------------- /src/view/options.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | File System Access Options 9 | 123 | 124 | 125 | 126 | 127 | 128 | 129 |
130 |
131 | Helper App 132 |
133 | 137 | 141 |
142 |
143 | 144 | 145 |
146 | 150 |
151 |
152 | Accessibility 153 | 160 | 168 | 174 |
175 |
176 | Content Script 177 | 183 | 189 |
190 |
191 | 192 | 193 | 194 | 195 |
196 |
197 | 198 | 199 | 200 | -------------------------------------------------------------------------------- /src/lib/worker.js: -------------------------------------------------------------------------------- 1 | if (self.importScripts) { 2 | let scope = self; 3 | 4 | let __baseURI = undefined; 5 | let __fetch = scope.fetch; 6 | let __importScripts = scope.importScripts; 7 | let __postMessage = scope.postMessage; 8 | let __addEventListener = scope.addEventListener; 9 | let __removeEventListener = scope.removeEventListener; 10 | let __debug = scope.console?.debug?.bind(scope.console); 11 | let __warn = scope.console?.warn?.bind(scope.console); 12 | 13 | const getConfig = (name = null, def = undefined, type = null) => { 14 | if ('undefined' !== typeof FS_CONFIG && FS_CONFIG) { 15 | if (name === null) { 16 | return FS_CONFIG; 17 | } else if (FS_CONFIG.hasOwnProperty(name) && (!type || type === typeof FS_CONFIG[name])) { 18 | return FS_CONFIG[name]; 19 | } 20 | } 21 | return def; 22 | }; 23 | let debug = (...args) => { 24 | if (!getConfig('DEBUG_ENABLED')) return; 25 | let i = args.length; 26 | while (args[--i] === undefined && i >= 0) args.pop(); 27 | if (__debug) __debug(...args); 28 | }; 29 | let warn = __warn; 30 | 31 | debug('worker start'); 32 | 33 | scope.fetch = (resource, ...options) => { 34 | debug('fetch', resource, ...options); 35 | if (typeof resource === 'string') { 36 | resource = (new URL(resource, __baseURI)).href; 37 | } 38 | return __fetch(resource, ...options); 39 | }; 40 | scope.importScripts = (...urls) => { 41 | debug('importScripts', ...urls); 42 | urls = urls.map(url => (new URL(url, __baseURI)).href); 43 | return __importScripts(...urls); 44 | }; 45 | 46 | let actionName = '_fsAction'; 47 | 48 | let port = { 49 | resolves: {}, 50 | _i: 0, 51 | _w: Math.round(Math.random() * 1000), 52 | createId() { 53 | this._i = (this._i + 1) % (1000 - 100); 54 | return `worker_${this._w}-${Date.now()}-${Math.round(100 + this._i)}`; 55 | }, 56 | async request(m) { 57 | let id = this.createId(); 58 | let message = { 59 | id, 60 | [actionName]: 'sendMessage', 61 | data: m, 62 | }; 63 | return await new Promise((resolve, reject) => { 64 | this.resolves[id] = resolve; 65 | try { 66 | __postMessage(message); 67 | } catch (e) { 68 | delete this.resolves[id]; 69 | reject(e); 70 | } 71 | }); 72 | }, 73 | onMessage(response) { 74 | if (response && response[actionName]) { 75 | let options = response.data; 76 | switch (response[actionName]) { 77 | case 'script': 78 | let url = options?.url; 79 | if (!url) break; 80 | try { 81 | if (!__baseURI) __baseURI = url; 82 | importScripts(url); 83 | dispatchMessageEvent(true); 84 | } catch (e) { 85 | warn(e); 86 | // XXX 87 | (async () => { 88 | try { 89 | debug('eval', url); 90 | let code = await (await sendMessage('page.fetch', { url })).text(); 91 | if (code) code = `//# sourceURL=${url}\n${code}`; 92 | (new scope.Function(code))(); 93 | } catch (e) { 94 | warn(e); 95 | } finally { 96 | dispatchMessageEvent(true); 97 | } 98 | })(); 99 | } 100 | break; 101 | case 'response': 102 | let id = response.id; 103 | if (!this.resolves[id]) return; 104 | this.resolves[id](response); 105 | delete this.resolves[id]; 106 | } 107 | return true; 108 | } 109 | }, 110 | }; 111 | 112 | let messageData = { 113 | loaded: false, 114 | context: scope, 115 | events: [], 116 | onmessage: null, 117 | listeners: [], 118 | }; 119 | let dispatchMessageEvent = function (event) { 120 | if (event === true) { 121 | messageData.loaded = true; 122 | for (let event of messageData.events) { 123 | try { 124 | dispatchMessageEvent.bind(messageData.context)(event); 125 | } catch (e) { 126 | warn(e); 127 | } 128 | } 129 | messageData.events = []; 130 | return; 131 | } 132 | if (!messageData.loaded) { 133 | messageData.context = this; 134 | messageData.events.push(event); 135 | return; 136 | } 137 | // XXX 138 | if (messageData.onmessage) { 139 | try { 140 | messageData.onmessage.bind(this)(event); 141 | } catch (e) { 142 | warn(e); 143 | } 144 | } 145 | // FIXME 146 | for (let listener of messageData.listeners) { 147 | try { 148 | listener[0].bind(this)(event); 149 | } catch (e) { 150 | warn(e); 151 | } 152 | } 153 | }; 154 | 155 | scope.postMessage = function (data, ...args) { 156 | // XXX 157 | if (data && data[actionName]) { 158 | warn('block self.postMessage', [data, ...args]); 159 | return; 160 | } 161 | return __postMessage(data, ...args); 162 | }; 163 | __addEventListener.bind(scope)('message', function (event) { 164 | if (port.onMessage(event.data)) return; 165 | dispatchMessageEvent.bind(true)(event); 166 | }); 167 | scope.addEventListener = function (type, listener, ...args) { 168 | if (type === 'message') { 169 | messageData.listeners.push([listener, ...args]); 170 | } else { 171 | __addEventListener.bind(this)(type, listener, ...args); 172 | } 173 | }; 174 | scope.removeEventListener = function (type, listener, ...args) { 175 | if (type === 'message') { 176 | for (let i in messageData.listeners) { 177 | // FIXME 178 | if (messageData.listeners[i][0] === listener) { 179 | messageData.listeners.splice(i, 1); 180 | break; 181 | } 182 | } 183 | messageData.listeners.push([listener, ...args]); 184 | } else { 185 | __removeEventListener.bind(this)(type, listener, ...args); 186 | } 187 | }; 188 | Object.defineProperty(scope, 'onmessage', { 189 | enumerable: false, 190 | configurable: true, 191 | set(value) { 192 | messageData.onmessage = value; 193 | }, 194 | get() { 195 | return messageData.onmessage; 196 | }, 197 | }); 198 | 199 | let sendMessage = async (action, data) => { 200 | try { 201 | let response = await port.request({ action, data }); 202 | if (response.code !== 200) { 203 | warn(response); 204 | throw response.data || response; 205 | } 206 | return response.data; 207 | } catch (e) { 208 | if (e && e.trace) { 209 | debug(e.trace); 210 | e = e.message; 211 | } 212 | throw e instanceof Error ? scope.Error(e.message) : e; 213 | } 214 | } 215 | 216 | if (self.__fs_init) { 217 | let fs_options = { 218 | scope, 219 | debug, 220 | warn, 221 | sendMessage, 222 | get baseURI() { 223 | return __baseURI; 224 | }, 225 | isExternal: true, 226 | }; 227 | self.__fs_init(fs_options); 228 | } 229 | 230 | } 231 | -------------------------------------------------------------------------------- /src/demo/file.js: -------------------------------------------------------------------------------- 1 | let $textarea = document.querySelector('textarea'); 2 | let $dir = document.querySelector('select.dir'); 3 | let $name = document.querySelector('input.name'); 4 | let $state = document.querySelector('output.state'); 5 | let $fileName = document.querySelector('output.file'); 6 | let $dirName = document.querySelector('output.dir'); 7 | 8 | let dirHandle, dirHandle0, fileHandle, file, writeable; 9 | 10 | let refreshForm = () => { 11 | let scope = { 12 | dirHandle, 13 | fileHandle, 14 | writeable, 15 | }; 16 | [...document.querySelectorAll('[data-var]')].map(e => { 17 | e.disabled = !scope[e.getAttribute('data-var')]; 18 | }); 19 | }; 20 | 21 | let readFile = async (fileHandle) => { 22 | $fileName.value = fileHandle.name; 23 | console.time("readFile"); 24 | try { 25 | file = await fileHandle.getFile(); 26 | $textarea.value = await file.text(); 27 | console.log(`size: ${file.size}`); 28 | } finally { 29 | console.timeEnd("readFile"); 30 | } 31 | }; 32 | 33 | let readDir = async (dirHandle) => { 34 | $dirName.value = dirHandle.name; 35 | $dir.textContent = ""; 36 | { 37 | let option = document.createElement("option"); 38 | option.value = '.'; 39 | option.textContent = '.'; 40 | option.selected = true; 41 | $dir.appendChild(option); 42 | } 43 | if (dirHandle0) { 44 | let level = (await dirHandle0.resolve(dirHandle)); 45 | if (level && level.length > 0) { 46 | $dirName.value = dirHandle0.name + "/" + level.join('/'); 47 | let option = document.createElement("option"); 48 | option.value = '..'; 49 | option.textContent = '..'; 50 | $dir.appendChild(option); 51 | } 52 | } 53 | console.time("readDir"); 54 | try { 55 | let i = 0; 56 | for await (let [key, handle] of dirHandle) { 57 | // console.debug(key, handle); 58 | let option = document.createElement("option"); 59 | option.value = key; 60 | option.textContent = key + (handle.kind == 'directory' ? '/' : ''); 61 | $dir.appendChild(option); 62 | i++; 63 | } 64 | console.log(`num: ${i}`); 65 | } finally { 66 | console.timeEnd("readDir"); 67 | } 68 | }; 69 | 70 | document.body.addEventListener('click', async (event) => { 71 | let target = event.target; 72 | if (target.nodeName !== 'BUTTON') return; 73 | let action = target.textContent.trim(); 74 | try { 75 | switch (action) { 76 | case 'openFile': { 77 | [fileHandle] = await showOpenFilePicker({ id: "demo" }); 78 | await readFile(fileHandle); 79 | return; 80 | } 81 | case 'openFiles': { 82 | const r = await showOpenFilePicker({ 83 | id: "demo", 84 | multiple: true, 85 | types: [ 86 | { 87 | description: 'Text Files', 88 | accept: { 89 | 'text/plain': ['.txt', '.text'], 90 | 'text/html': ['.html', '.htm'], 91 | } 92 | }, 93 | { 94 | description: 'Images', 95 | accept: { 96 | 'image/*': ['.png', '.gif', '.jpeg', '.jpg'], 97 | } 98 | }, 99 | { 100 | accept: { 101 | 'image/svg+xml': '.svg', 102 | } 103 | }, 104 | { 105 | accept: { 106 | 'image/svg+xml': [], 107 | } 108 | }, 109 | /* 110 | { 111 | accept: { 112 | 'image/svg+xml': 'bad,' 113 | } 114 | }, 115 | */ 116 | ], 117 | excludeAcceptAllOption: true, 118 | }); 119 | console.info(r); 120 | [fileHandle] = r; 121 | await readFile(fileHandle); 122 | return; 123 | } 124 | case 'saveAs': { 125 | fileHandle = await showSaveFilePicker({ id: "demo2", suggestedName: 'test.txt', }); 126 | await readFile(fileHandle); 127 | return; 128 | } 129 | 130 | case 'moveFile': { 131 | let args = []; 132 | try { 133 | args.push(await showDirectoryPicker({ id: "demo-move" })); 134 | } catch (e) { 135 | console.log('skip dirHandle', e); 136 | } 137 | args.push(prompt('new name')); 138 | await fileHandle.move(...args); 139 | await readFile(fileHandle); 140 | return; 141 | } 142 | case 'moveDir': { 143 | let args = []; 144 | try { 145 | args.push(await showDirectoryPicker({ id: "demo-move" })); 146 | } catch (e) { 147 | console.log('skip dirHandle', e); 148 | } 149 | args.push(prompt('new name')); 150 | await dirHandle.move(...args); 151 | await readDir(dirHandle); 152 | return; 153 | } 154 | 155 | case 'removeFile': { 156 | await fileHandle.remove(); 157 | fileHandle = null; 158 | return; 159 | } 160 | case 'removeDir': { 161 | await dirHandle.remove(); 162 | dirHandle = null; 163 | return; 164 | } 165 | case 'removeDirRecursive': { 166 | await dirHandle.remove({ recursive: true }); 167 | dirHandle = null; 168 | return; 169 | } 170 | 171 | case 'openDir': { 172 | dirHandle0 = dirHandle = await showDirectoryPicker({ id: "demo-dir1" }); 173 | await readDir(dirHandle); 174 | return; 175 | } 176 | case 'newFile': { 177 | fileHandle = await dirHandle.getFileHandle($name.value, { create: true }); 178 | await readDir(dirHandle); 179 | await readFile(fileHandle); 180 | return; 181 | } 182 | case 'newDir': { 183 | dirHandle = await dirHandle.getDirectoryHandle($name.value, { create: true }); 184 | await readDir(dirHandle); 185 | return; 186 | } 187 | case 'removeEntry': { 188 | await dirHandle.removeEntry($name.value); 189 | await readDir(dirHandle); 190 | return; 191 | } 192 | case 'removeEntryRecursive': { 193 | await dirHandle.removeEntry($name.value, { recursive: true }); 194 | await readDir(dirHandle); 195 | return; 196 | } 197 | 198 | case 'createWritable': { 199 | writeable = await fileHandle.createWritable(); 200 | return; 201 | } 202 | case 'createWritableInPlace': { 203 | writeable = await fileHandle.createWritable({ _inPlace: true, keepExistingData: true }); 204 | return; 205 | } 206 | case 'createWritableKeepExistingData': { 207 | writeable = await fileHandle.createWritable({ keepExistingData: true }); 208 | return; 209 | } 210 | case 'seek': { 211 | let position = prompt("position"); 212 | await writeable.seek(position); 213 | $state.value = `SEEK: ${parseInt(position)}`; 214 | return; 215 | } 216 | case 'truncate': { 217 | let size = prompt("size"); 218 | await writeable.truncate(size); 219 | $state.value = "TRUNCATED"; 220 | return; 221 | } 222 | case 'write': { 223 | await writeable.write($textarea.value); 224 | $state.value = "WRITED"; 225 | return; 226 | } 227 | case 'close': { 228 | await writeable.close(); 229 | writeable = null; 230 | $state.value = "CLOSED"; 231 | if (fileHandle) await readFile(fileHandle); 232 | return; 233 | } 234 | case 'abort': { 235 | await writeable.abort('reason'); 236 | writeable = null; 237 | $state.value = "ABORTED"; 238 | if (fileHandle) await readFile(fileHandle); 239 | return; 240 | } 241 | 242 | case 'workerReadFile': { 243 | worker.postMessage({ 244 | action, 245 | data: fileHandle, 246 | }); 247 | return; 248 | } 249 | case 'workerReadDir': { 250 | worker.postMessage({ 251 | action, 252 | data: dirHandle, 253 | }); 254 | return; 255 | } 256 | } 257 | } catch (e) { 258 | console.warn(e); 259 | alert("" + e); 260 | } finally { 261 | refreshForm(); 262 | } 263 | }); 264 | 265 | $dir.addEventListener('change', async (event) => { 266 | try { 267 | let key = event.target.value; 268 | // console.log(key); 269 | let handle; 270 | switch (key) { 271 | case ".": { 272 | handle = dirHandle; 273 | break; 274 | } 275 | case "..": { 276 | if (!dirHandle0) return; 277 | let level = await dirHandle0.resolve(dirHandle); 278 | console.info(level); 279 | handle = dirHandle0; 280 | while (level.length > 1) { 281 | handle = await handle.getDirectoryHandle(level.shift()); 282 | } 283 | break; 284 | } 285 | default: { 286 | try { 287 | handle = await dirHandle.getFileHandle(key); 288 | } catch (e) { 289 | handle = await dirHandle.getDirectoryHandle(key); 290 | } 291 | break; 292 | } 293 | } 294 | if (handle.kind === "file") { 295 | fileHandle = handle; 296 | await readFile(fileHandle); 297 | } else { 298 | dirHandle = handle; 299 | await readDir(dirHandle); 300 | } 301 | } catch (e) { 302 | console.warn(e); 303 | alert("" + e); 304 | } finally { 305 | refreshForm(); 306 | } 307 | }); 308 | 309 | refreshForm(); 310 | 311 | let worker = new Worker('worker0.js'); 312 | worker.addEventListener("message", (message) => { 313 | console.debug(message, message.data); 314 | }); 315 | -------------------------------------------------------------------------------- /app/src/common/fsa-host.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S python -u 2 | 3 | # Note that running python with the `-u` flag is required on Windows, 4 | # in order to ensure that stdin and stdout are opened in binary, rather 5 | # than text, mode. 6 | 7 | import atexit 8 | import base64 9 | import json 10 | import mimetypes 11 | import os 12 | import shutil 13 | import sys 14 | import struct 15 | import tempfile 16 | import time 17 | import threading 18 | import traceback 19 | 20 | __version__ = '0.9.4' 21 | 22 | try: 23 | import queue 24 | except ImportError: 25 | import Queue as queue 26 | 27 | stdin = sys.stdin 28 | stdout = sys.stdout 29 | 30 | try: 31 | stdin = stdin.buffer 32 | stdout = stdout.buffer 33 | except AttributeError: 34 | pass 35 | 36 | # Read a message from stdin and decode it. 37 | 38 | 39 | def getMessage(): 40 | rawLength = stdin.read(4) 41 | if not rawLength: 42 | # sys.exit(0) 43 | return None 44 | messageLength = struct.unpack('=I', rawLength)[0] 45 | if not messageLength: 46 | return None 47 | message = stdin.read(messageLength).decode('utf-8') 48 | return json.loads(message) 49 | 50 | # Encode a message for transmission, given its content. 51 | 52 | 53 | def encodeMessage(messageContent): 54 | # https://docs.python.org/3/library/json.html#basic-usage 55 | # To get the most compact JSON representation, you should specify 56 | # (',', ':') to eliminate whitespace. 57 | # We want the most compact representation because the browser rejects 58 | # messages that exceed 1 MB. 59 | encodedContent = json.dumps( 60 | messageContent, separators=(',', ':')).encode('utf-8') 61 | encodedLength = struct.pack('=I', len(encodedContent)) 62 | return {'length': encodedLength, 'content': encodedContent} 63 | 64 | # Send an encoded message to stdout. 65 | 66 | 67 | outputLock = threading.Lock() 68 | 69 | 70 | def sendMessage(encodedMessage): 71 | with outputLock: 72 | stdout.write(encodedMessage['length']) 73 | stdout.write(encodedMessage['content']) 74 | stdout.flush() 75 | 76 | 77 | def response(data, messageId, code=200): 78 | # XXX 79 | if type(data) == bytes: 80 | data = data.decode('utf-8') 81 | encodedMessage = encodeMessage({ 82 | 'id': messageId, 83 | 'code': code, 84 | 'data': data, 85 | }) 86 | MAX_SIZE = 1024*1024 87 | if len(encodedMessage['content']) <= MAX_SIZE: 88 | sendMessage(encodedMessage) 89 | else: 90 | CHUNK_SIZE = int(MAX_SIZE/2) 91 | encode = None 92 | if type(data) != str: 93 | data = json.dumps(data, separators=(',', ':')) 94 | encode = 'json' 95 | baseMessageId = '%s' % messageId 96 | nextMessageId = '%s' % messageId 97 | dataLength = len(data) 98 | for i in range(0, dataLength, CHUNK_SIZE): 99 | chunk = data[i:i+CHUNK_SIZE] 100 | messageId = nextMessageId 101 | nextMessageId = "%s:%s" % (baseMessageId, i) 102 | message = { 103 | 'id': messageId, 104 | 'code': code, 105 | 'data': chunk, 106 | } 107 | if i+CHUNK_SIZE < dataLength: 108 | message['code'] = 206 109 | message['next_id'] = nextMessageId 110 | elif bool(encode): 111 | message['encode'] = encode 112 | sendMessage(encodeMessage(message)) 113 | 114 | 115 | def parseWellKnownDirectory(name, verify=False): 116 | if not isinstance(name, basestring if 'basestring' in vars(__builtins__) else str): 117 | name = "documents" 118 | # XXX 119 | path = { 120 | "desktop": "~/Desktop", 121 | "documents": "~/Documents", 122 | "downloads": "~/Downloads", 123 | "music": "~/Music", 124 | "pictures": "~/Pictures", 125 | "videos": "~/Videos", 126 | }.get(name, name) 127 | path = os.path.expanduser(path) 128 | if not os.path.isdir(path): 129 | path = os.path.expanduser("~") 130 | if verify and not os.path.isdir(path): 131 | path = os.path.abspath(".") 132 | return path 133 | 134 | 135 | def parseTypes(types, excludeAcceptAllOption=False): 136 | try: 137 | if not types: 138 | return [] 139 | # TODO MIME 140 | filetypes = [(t.get("description", ""), tuple(s for ss in list(t.get( 141 | "accept", {}).values()) for s in (ss if type(ss) == list else [ss]))) for t in types] 142 | if not excludeAcceptAllOption: 143 | filetypes.append(('All Files', '*')) 144 | return filetypes 145 | except: 146 | return [] 147 | 148 | 149 | pickerActions = ['showDirectoryPicker', 150 | 'showOpenFilePicker', 'showSaveFilePicker'] 151 | root = None 152 | filedialog = None 153 | temp_files = set() 154 | 155 | 156 | def task(message): 157 | messageId = message.get('id') 158 | action = message.get('action') 159 | data = message.get('data', dict()) 160 | result = None 161 | if action == 'version': 162 | result = __version__ 163 | elif action == 'constants': 164 | result = { 165 | 'version': __version__, 166 | 'separator': os.sep, 167 | } 168 | elif action in pickerActions: 169 | global filedialog 170 | global root 171 | if not root: 172 | try: 173 | from tkinter import Tk, filedialog 174 | except ImportError: 175 | from Tkinter import Tk 176 | import tkFileDialog as filedialog 177 | root = Tk() 178 | root.withdraw() 179 | root.update() 180 | time.sleep(0.2) 181 | root.deiconify() 182 | root.wm_attributes('-topmost', True) 183 | root.focus_force() 184 | root.withdraw() 185 | if action == 'showDirectoryPicker': 186 | result = filedialog.askdirectory( 187 | title=data.get('title'), 188 | initialdir=parseWellKnownDirectory(data.get('startIn')), 189 | mustexist=True, 190 | ) 191 | if not result: 192 | result = None 193 | elif action == 'showOpenFilePicker': 194 | options = { 195 | 'title': data.get('title'), 196 | 'initialdir': parseWellKnownDirectory(data.get('startIn')), 197 | 'filetypes': parseTypes(data.get('types'), data.get('excludeAcceptAllOption', False)), 198 | 'initialfile': data.get('initialfile'), 199 | } 200 | if data.get('multiple', False): 201 | result = filedialog.askopenfilenames(**options) 202 | else: 203 | path = filedialog.askopenfilename(**options) 204 | result = [path] if path else path 205 | if not result: 206 | result = None 207 | elif action == 'showSaveFilePicker': 208 | result = filedialog.asksaveasfilename( 209 | title=data.get('title'), 210 | filetypes=parseTypes(data.get('types'), data.get( 211 | 'excludeAcceptAllOption', False)), 212 | initialdir=parseWellKnownDirectory(data.get('startIn')), 213 | initialfile=data.get("suggestedName", data.get('initialfile')), 214 | ) 215 | if not result: 216 | result = None 217 | root.update() 218 | elif action == 'scandir': 219 | path = data.get('path') 220 | _result = os.listdir(path) 221 | if data.get('kind'): 222 | result = [] 223 | for _ in _result: 224 | item = path+'/'+_ 225 | if os.path.isfile(item): 226 | kind = 1 227 | elif os.path.isdir(item): 228 | kind = 2 229 | else: 230 | kind = 0 231 | result.append([_, kind]) 232 | else: 233 | result = _result 234 | elif action == 'getKind': 235 | path = data.get('path') 236 | if os.path.isfile(path): 237 | result = 'file' 238 | elif os.path.isdir(path): 239 | result = 'directory' 240 | elif action == 'isfile': 241 | result = os.path.isfile(data.get('path')) 242 | elif action == 'isdir': 243 | result = os.path.isdir(data.get('path')) 244 | elif action == 'exists': 245 | result = os.path.exists(data.get('path')) 246 | elif action == 'abspath': 247 | path = data.get('path') 248 | if data.get('startIn', False): 249 | result = parseWellKnownDirectory(path, True) 250 | else: 251 | if data.get('expand', False): 252 | path = os.path.expandvars(path) 253 | path = os.path.expanduser(path) 254 | result = os.path.abspath(path) 255 | elif action == 'stat': 256 | path = data.get('path') 257 | info = os.stat(path) 258 | result = { 259 | 'mtime': info.st_mtime, 260 | 'size': info.st_size, 261 | } 262 | if info.st_mode >> 12 == 8: 263 | mimeinfo = mimetypes.guess_type(path) 264 | # XXX 265 | mime = mimeinfo[0] if mimeinfo[1] is None else None 266 | if mime != None: 267 | result['type'] = mime 268 | elif action == 'read': 269 | with open(data.get('path'), data.get('mode', 'rb')) as f: 270 | offset = data.get('offset') 271 | if offset: 272 | f.seek(offset) 273 | result = f.read(data.get('size', -1)) 274 | if data.get('encode') == 'base64': 275 | result = base64.b64encode(result) 276 | elif action == 'write': 277 | with open(data.get('path'), data.get('mode', 'wb')) as f: 278 | offset = data.get('offset') 279 | if offset != None: 280 | # XXX 281 | f.seek(offset) 282 | s = data.get('data', '') 283 | if data.get('encode') == 'base64': 284 | s = base64.b64decode(s) 285 | result = f.write(s) 286 | elif action == 'truncate': 287 | with open(data.get('path'), data.get('mode', 'r+b')) as f: 288 | size = data.get('size', 0) 289 | result = f.truncate(size) 290 | # XXX 291 | f.seek(0, os.SEEK_END) 292 | diff = size-f.tell() 293 | if diff > 0: 294 | f.write(b'\x00' * diff) 295 | elif action == 'mktemp': 296 | # XXX 297 | fd, result = tempfile.mkstemp(prefix="fsa") 298 | try: 299 | os.close(fd) 300 | path = data.get('path') 301 | if path: 302 | shutil.copyfile(path, result) 303 | temp_files.add(result) 304 | except: 305 | os.remove(result) 306 | raise 307 | elif action == 'mkdir': 308 | path = data.get('path') 309 | if not os.path.isdir(path): 310 | os.makedirs(path) 311 | elif action == 'touch': 312 | path = data.get('path') 313 | if not os.path.isfile(path): 314 | open(path, 'a').close() 315 | elif action == 'rm': 316 | path = data.get('path') 317 | if os.path.isdir(path): 318 | if data.get('recursive', False): 319 | shutil.rmtree(path) 320 | else: 321 | os.rmdir(path) 322 | else: 323 | os.remove(path) 324 | if path in temp_files: 325 | temp_files.remove(path) 326 | elif action == 'mv': 327 | src = data.get('src') 328 | dst = data.get('dst') 329 | if not data.get('overwrite', False): 330 | if os.path.exists(dst): 331 | raise OSError("dst exists") 332 | else: 333 | # XXX 334 | pass 335 | shutil.move(src, dst) 336 | if src in temp_files: 337 | temp_files.remove(src) 338 | elif action == 'echo': 339 | result = data 340 | else: 341 | response("Not implemented", messageId, 400) 342 | return 343 | response(result, messageId) 344 | 345 | 346 | def onError(e, messageId, code=500): 347 | response({ 348 | "message": "%s %s" % (e.__class__.__name__, e), 349 | "trace": traceback.format_exc(), 350 | }, messageId, code) 351 | 352 | 353 | def onExit(): 354 | for _ in temp_files: 355 | try: 356 | if os.path.isfile(_): 357 | os.remove(_) 358 | except: 359 | pass 360 | 361 | 362 | def main(): 363 | MAX_WORKERS = 5 364 | isTkMainThread = sys.platform == 'darwin' 365 | taskQueue = queue.Queue() 366 | tkQueue = queue.Queue(2) 367 | 368 | def worker(q, once=False): 369 | while True: 370 | if once: 371 | try: 372 | message = q.get_nowait() 373 | except queue.Empty: 374 | return 375 | else: 376 | message = q.get() 377 | try: 378 | task(message) 379 | except Exception as e: 380 | onError(e, message.get("id")) 381 | finally: 382 | q.task_done() 383 | if once: 384 | break 385 | 386 | for _ in range(MAX_WORKERS): 387 | t = threading.Thread(target=worker, args=(taskQueue,)) 388 | t.daemon = True 389 | t.start() 390 | 391 | if not isTkMainThread: 392 | tkThread = threading.Thread(target=worker, args=(tkQueue,)) 393 | tkThread.daemon = True 394 | tkThread.start() 395 | 396 | atexit.register(onExit) 397 | 398 | while True: 399 | message = getMessage() 400 | if message is None: 401 | break 402 | messageId = None 403 | try: 404 | messageId = message.get("id") 405 | if message.get('action') in pickerActions: 406 | tkQueue.put(message, False) 407 | else: 408 | taskQueue.put(message) 409 | except Exception as e: 410 | onError(e, messageId) 411 | if isTkMainThread: 412 | worker(tkQueue, True) 413 | 414 | taskQueue.join() 415 | 416 | # if root: 417 | # root.update() 418 | # root.destroy() 419 | 420 | 421 | if __name__ == "__main__": 422 | main() 423 | -------------------------------------------------------------------------------- /src/view/prompt.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Request Access 9 | 10 | 11 | 12 | 13 | 14 | 391 | 392 | 393 | 394 | 414 | 456 | 457 | 458 | -------------------------------------------------------------------------------- /src/view/options.js: -------------------------------------------------------------------------------- 1 | self.name = "options"; 2 | 3 | let $form = document.querySelector("form"); 4 | let $save = $form.querySelector(".save"); 5 | let contentScriptKey = 'content_script_match'; 6 | let $contentScriptSection = document.querySelector(".content-script-options"); 7 | let $contentScriptOptions = $contentScriptSection.querySelector(`[data-setting="content_script_match"]`); 8 | let $contentScriptEnv = $contentScriptSection.querySelector(`[data-setting="content_script_match.js"]`); 9 | 10 | $form.addEventListener("change", (event) => { 11 | event.preventDefault(); 12 | $save.disabled = false; 13 | }); 14 | 15 | self.addEventListener("beforeunload", (event) => { 16 | if (!$save.disabled) { 17 | event.preventDefault(); 18 | return (event.returnValue = ""); 19 | } 20 | }); 21 | 22 | $form.onkeydown = (event) => { 23 | if (event.ctrlKey && event.key == "s") { 24 | $save.click(); 25 | event.preventDefault(); 26 | } 27 | } 28 | 29 | $save.onclick = async (event) => { 30 | try { 31 | await util.sendMessage("fs.updateOptions", getFormData()); 32 | $save.disabled = true; 33 | // alert('Saved'); 34 | } catch (e) { 35 | console.error(e); 36 | alert(e.message); 37 | // throw e; 38 | } 39 | }; 40 | 41 | $form.querySelector(".reset").onclick = async function (event) { 42 | setFormData(util._defaultConfig) 43 | } 44 | 45 | let setFormData = (o) => { 46 | console.debug(o) 47 | for (let k in o) { 48 | switch (k) { 49 | case contentScriptKey: { 50 | let options = JSON.parse(JSON.stringify(o[k])) || {}; 51 | let env = ''; 52 | if (Array.isArray(options.js)) { 53 | env = options.js.shift()?.code; 54 | if (!options.js.length) delete options.js; 55 | } 56 | $contentScriptEnv.value = env || ''; 57 | $contentScriptEnv.dispatchEvent(new Event('change', { bubbles: true })); 58 | $contentScriptOptions.value = JSON.stringify(options, null, " "); 59 | $contentScriptOptions.dispatchEvent(new Event('change', { bubbles: true })); 60 | break; 61 | } 62 | default: { 63 | let $n = $form.querySelector(`[data-setting="${k}"]`); 64 | if (!$n) break; 65 | let v = o[k]; 66 | if ($n.type == "checkbox") { 67 | $n.checked = !!v; 68 | } else { 69 | $n.value = v; 70 | $n.dispatchEvent(new Event("change", { bubbles: true })); 71 | } 72 | } 73 | } 74 | } 75 | }; 76 | 77 | let getFormData = () => { 78 | let settings = {}; 79 | [...$form.querySelectorAll("[data-setting]")].map((n) => { 80 | let key = n.getAttribute("data-setting"); 81 | if (key.includes('.')) return; 82 | let v = n.type == "checkbox" ? n.checked : n.value; 83 | settings[key] = v; 84 | }); 85 | let options = JSON.parse($contentScriptOptions.value); 86 | if (!Array.isArray(options.js)) options.js = []; 87 | if ("" === $contentScriptEnv.value.trim() && !options.js.length) { 88 | delete options.js; 89 | } else { 90 | options.js.unshift({ code: $contentScriptEnv.value }); 91 | } 92 | settings[contentScriptKey] = options; 93 | return settings; 94 | }; 95 | 96 | (async () => { 97 | let $section = document.querySelector(".app-options"); 98 | let $state = $section.querySelector('.state'); 99 | let $items = $state.querySelectorAll('[data-state]'); 100 | let getState = async (verfiy = false) => { 101 | [].forEach.call($items, $n => { 102 | $n.setAttribute('data-status', ''); 103 | $n.textContent = '...' 104 | }); 105 | let state = {}; 106 | let getConstants = async () => { 107 | try { 108 | let info = await util.sendMessage("fs.constants"); 109 | Object.assign(state, info); 110 | } catch (e) { 111 | console.warn(e); 112 | state.error = e; 113 | } 114 | }; 115 | if (verfiy) await getConstants(); 116 | try { 117 | let info = await util.sendMessage("fs.getState"); 118 | Object.assign(state, info); 119 | } catch (e) { 120 | console.warn(e); 121 | if (!state.error) state.error = e; 122 | } 123 | if (!verfiy && state.connected) await getConstants(); 124 | state.text = state.connected ? 'Running' : undefined; 125 | if (state.error && !state.connected) { 126 | state.error = `${state.error}`; 127 | if (/\bNo such native application\b/i.test(state.error)) { 128 | state.text = 'Not Installed'; 129 | } else { 130 | state.text = state.error; 131 | } 132 | } 133 | console.log(state); 134 | $section.querySelector(".stop").disabled = !state.connected; 135 | [].forEach.call($items, $n => { 136 | let key = $n.getAttribute('data-state'); 137 | let status = !state.error && state[key] ? 'ok' : (state.error ? 'error' : ''); 138 | switch (key) { 139 | case 'version': { 140 | let minVer = '0.9.4'; 141 | let $help = document.querySelector('.help.version'); 142 | let pad = (v) => v.replace(/\d+/g, (d) => d.padStart(6, '0')); 143 | if (status === 'ok' && pad(state[key]) < pad(minVer)) { 144 | status = 'warn'; 145 | $help.textContent = `(Some features require v${minVer} or higher)`; 146 | } else { 147 | $help.textContent = ``; 148 | } 149 | break; 150 | } 151 | } 152 | $n.setAttribute('data-status', status); 153 | $n.textContent = state[key] || 'Unknown'; 154 | }); 155 | }; 156 | $section.querySelector(".start").onclick = function (event) { 157 | getState(true); 158 | }; 159 | $section.querySelector(".stop").onclick = async function (event) { 160 | try { 161 | let info = await util.sendMessage("fs.disconnect"); 162 | console.log(info); 163 | } catch (e) { 164 | alert(e.message); 165 | } 166 | await getState(); 167 | }; 168 | getState(); 169 | })(); 170 | 171 | (async () => { 172 | let settings = {}; 173 | 174 | await Promise.all([...$form.querySelectorAll("[data-setting]")].map(async (n) => { 175 | let key = n.getAttribute("data-setting"); 176 | if (key.includes('.')) return; 177 | settings[key] = await util.getSetting(key); 178 | })); 179 | 180 | setFormData(settings); 181 | $save.disabled = true; 182 | 183 | if (!settings.code_editor) return; 184 | 185 | let createCodeEditor = ($n) => { 186 | let key = $n.getAttribute('data-setting'); 187 | let language = $n.getAttribute('data-language'); 188 | let currentValue = null; 189 | let editor = codeEditor.create($n, { 190 | options: { 191 | language, 192 | minimap: { 193 | enabled: false, 194 | }, 195 | quickSuggestions: true, 196 | }, 197 | events: { 198 | async input(event) { 199 | $n.value = currentValue = await editor.getValue(); 200 | $n.dispatchEvent(new Event('change', { bubbles: true })); 201 | }, 202 | }, 203 | keybindingRules: [ 204 | { 205 | keybinding: "CtrlCmd+KeyS", 206 | command() { 207 | $save.click(); 208 | }, 209 | }, 210 | ], 211 | }); 212 | $n.onchange = function () { 213 | if (this.value === currentValue) return; 214 | editor.updateOptions({ 215 | value: this.value, 216 | }); 217 | }; 218 | switch (key) { 219 | case 'content_script_match': { 220 | editor.util.languages.json.setDiagnosticsOptions({ 221 | validate: true, 222 | schemas: [ 223 | { 224 | uri: "http://example.com/array_string.json", 225 | schema: { 226 | type: "array", 227 | items: { 228 | type: "string", 229 | }, 230 | }, 231 | }, 232 | { 233 | uri: "http://example.com/ExtensionFileOrCode.json", 234 | schema: { 235 | type: "object", 236 | properties: { 237 | file: { 238 | type: "string", 239 | }, 240 | code: { 241 | type: "string", 242 | }, 243 | }, 244 | }, 245 | }, 246 | { 247 | uri: "http://example.com/RegisteredContentScriptOptions.json", 248 | fileMatch: true, 249 | schema: { 250 | type: "object", 251 | required: ["matches"], 252 | additionalProperties: false, 253 | properties: { 254 | matches: { 255 | description: "An array of match patterns", 256 | $ref: "http://example.com/array_string.json", 257 | }, 258 | excludeMatches: { 259 | description: "An array of match patterns", 260 | $ref: "http://example.com/array_string.json", 261 | }, 262 | includeGlobs: { 263 | description: "An array of globs", 264 | $ref: "http://example.com/array_string.json", 265 | }, 266 | excludeGlobs: { 267 | description: "An array of globs", 268 | $ref: "http://example.com/array_string.json", 269 | }, 270 | css: { 271 | description: "The list of CSS files to inject", 272 | type: "array", 273 | items: { 274 | $ref: "http://example.com/ExtensionFileOrCode.json", 275 | }, 276 | }, 277 | js: { 278 | description: "The list of JS files to inject", 279 | type: "array", 280 | items: { 281 | $ref: "http://example.com/ExtensionFileOrCode.json", 282 | }, 283 | }, 284 | allFrames: { 285 | description: "If allFrames is `true`, implies that the JavaScript or CSS should be injected into all frames of current page. By default, it's `false` and is only injected into the top frame.", 286 | type: "boolean", 287 | }, 288 | matchAboutBlank: { 289 | description: "If matchAboutBlank is true, then the code is also injected in about:blank and about:srcdoc frames if your extension has access to its parent document. Code cannot be inserted in top-level about:-frames. By default it is `false`.", 290 | type: "boolean", 291 | }, 292 | // runAt 293 | cookieStoreId: { 294 | description: "Limit the set of matched tabs to those that belong to the given cookie store id", 295 | oneOf: [ 296 | { 297 | $ref: "http://example.com/array_string.json", 298 | }, 299 | { 300 | type: "string", 301 | }, 302 | ], 303 | }, 304 | }, 305 | }, 306 | }, 307 | ], 308 | }); 309 | break; 310 | } 311 | case 'content_script_match.js': { 312 | editor.util.languages.javascript.addExtraLib(` 313 | type FS_CONFIG = { 314 | API_ENABLED?: boolean, 315 | OVERRIDE_ENABLED?: boolean, 316 | CLONE_ENABLED?: boolean, 317 | WORKER_ENABLED?: boolean, 318 | FILE_SIZE_LIMIT?: number, 319 | FILE_CHUNK_SIZE?: number, 320 | FILE_CACHE_EXPIRE?: number, 321 | NON_NATIVE_FILE?: 'never' | 'auto' | 'always', 322 | WRITE_BUFFER_TYPE?: 'memory' | 'tempfile' | 'inplace', 323 | EXPOSE_NAMESPACE?: string | boolean, 324 | DEBUG_ENABLED?: boolean, 325 | }; 326 | `, 327 | 'local.d.ts', true); 328 | break; 329 | } 330 | } 331 | }; 332 | 333 | let observer = new IntersectionObserver((entries, opts) => { 334 | entries.forEach(entry => { 335 | let target = entry.target; 336 | let rect = target.getBoundingClientRect(); 337 | // console.debug(target, rect); 338 | if (rect.top == 0 && rect.bottom == 0) return; 339 | createCodeEditor(target); 340 | observer.unobserve(target); 341 | }); 342 | }, { threshold: 0.05 }); 343 | 344 | [...$form.querySelectorAll("textarea.editor")].map(n => observer.observe(n)); 345 | 346 | })(); 347 | -------------------------------------------------------------------------------- /src/view/doc.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | File System Access Extension 9 | 150 | 151 | 152 | 153 |

File System Access Extension

154 |

155 | This extension brings the File System 156 | Access API to Firefox that helps web apps such as vscode.dev read and write local files and folders. 158 |

159 |

160 | This extension is open source 161 | and you can file bug reports or feature requests on the GitHub issue. 163 |

164 |

Limitations

165 | 190 |

Helper App

191 |

192 | The local file operations required by this extension cannot be performed in the browser, and a helper app needs to be installed to assist in the related work. 194 |

195 |

196 | After the helper app is installed, the extension will automatically run the helper app when necessary. 197 |

198 |

Install the helper app

199 |

200 | Select the installer below based on your operating system and follow the README documentation inside. 201 |

202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 225 | 226 | 227 | 228 | 229 | 230 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 248 | 249 | 250 |
SystemTypeLinkPrerequisite
WindowsFullReleases
LiteDownload 222 | Python 2 or 3 installed and added to PATH. 223 | Tkinter module installation is optional1. 224 |
LinuxLiteDownload 231 | Tkinter module installation is optional1. 232 |
macOSLiteDownload
OtherNote: You can refer to other installer for similar system and Manifest 246 | location for installation. 247 |
251 |
    252 |
  1. Optional Tkinter module for show native file picker.
  2. 253 |
254 |

Check the helper app

255 |

256 | Open the options page and check the state of the Helper 257 | App. 258 |

259 | 274 |

Content Script

275 |

Match patterns

276 |

277 | This configuration item instructs the browser to enable the extension only on web pages whose URL matches a 278 | given pattern. 279 |

280 |

281 | See the contentScriptOptions for details of all keys, which must conform to JSON syntax when filled in on the options page. 287 |

288 |

Configuration parameters

289 |

290 | This configuration item instructs the extension to enable specific features on matching web pages. 291 |

292 |

293 | Define the FS_CONFIG object with a declaration variable statement, 296 | which must conform to JavaScript syntax when filled in on the options page. 299 |

300 | 301 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 329 | 330 | 331 | 332 | 333 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 360 | 361 | 362 | 363 | 364 | 368 | 369 | 370 | 371 | 372 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 |
302 | Available keys for FS_CONFIG object 303 |
Key NameTypeDescription
API_ENABLEDbooleanEnable polyfill for File System API.
OVERRIDE_ENABLEDbooleanOverride native FileSystem* API to Object.
CLONE_ENABLEDboolean 327 | Preserve instance methods when cloning FileSystem*Handle. 328 |
WORKER_ENABLEDboolean 334 | Inject File System API into worker.
FILE_SIZE_LIMITnumberLimit file size when reading.
FILE_CHUNK_SIZEnumberThe size of the data chunk for each read or write.
FILE_CACHE_EXPIREnumberClear cache for files not accessed beyond timeout.
NON_NATIVE_FILE'never' | 'auto' | 'always' 356 | Improved performance in reading metadata by simulating the 357 | File interface, 358 | but incompatible with some web pages. 359 |
WRITE_BUFFER_TYPE'memory' | 'tempfile' | 'inplace' 365 | The type of buffer to use when FileSystemFileHandle.createWritable(). 366 | If set to 'inplace', the original file may be corrupted by improper aborting. 367 |
EXPOSE_NAMESPACEstring | booleanExposing utility object to the global scope. If set to true then the namespace is 373 | __FILE_SYSTEM_TOOLS__. 374 |
DEBUG_ENABLEDbooleanEnable Debug mode.
383 |

384 | Features marked as Experimental may have side effects and should only be enabled on 385 | necessary web pages. 386 |

387 | 388 | 389 | -------------------------------------------------------------------------------- /src/view/file-picker.js: -------------------------------------------------------------------------------- 1 | let initFilePicker = async (message) => { 2 | let action = message.action; 3 | let options = message.data || {}; 4 | if (!options.mode) options.mode = action === 'showSaveFilePicker' ? FileSystemPermissionModeEnum.READWRITE : FileSystemPermissionModeEnum.READ; 5 | let modeText = options.mode === FileSystemPermissionModeEnum.READ ? 'view' : 'edit'; 6 | renderText('perm-mode', modeText); 7 | renderText('perm-mode-detail', `${modeText} (${options.mode})`); 8 | renderText('perm-mode-detail', modeText, true); 9 | // XXX 10 | { 11 | let $title = $container.querySelector(`[data-text="title"]`); 12 | let $origin = $title.querySelector(`[data-text="origin"]`); 13 | let $mode = $title.querySelector(`[data-text="perm-mode-detail"]`); 14 | if (options.titleTemplate) { 15 | $title.textContent = ""; 16 | for (let chunk of options.titleTemplate.split(/(\{[^}]+\})/)) { 17 | if (chunk === '{origin}' && !$origin.isConnected) { 18 | $title.appendChild($origin); 19 | } else if (chunk === '{mode}' && !$mode.isConnected) { 20 | $title.appendChild($mode); 21 | } else { 22 | $title.insertAdjacentText('beforeend', chunk); 23 | } 24 | } 25 | } 26 | } 27 | 28 | if (self.__fs_init) { 29 | let fs_options = { 30 | scope: self, 31 | debug: util.log.bind(util), 32 | warn: console.warn, 33 | sendMessage: async (action, data) => { 34 | // XXX 35 | if (action == 'fs.queryPermission' && data?.mode === FileSystemPermissionModeEnum.READ) { 36 | return PermissionStateEnum.GRANTED; 37 | } 38 | return await util.sendMessage(action, data); 39 | }, 40 | exportInternalTools: true, 41 | }; 42 | self.__fs_init(fs_options); 43 | } 44 | 45 | let $location = $container.querySelector(`.location input`); 46 | let $name = $container.querySelector(`.select-items input[name="name"]`); 47 | let $types = $container.querySelector(`.select-items select[name="types"]`); 48 | let $table = $container.querySelector(".file-list"); 49 | let $list = $container.querySelector(".file-list .list-data"); 50 | let $select = $container.querySelector(`[data-action="select"]`); 51 | let verifyData = null; 52 | 53 | let renderFileList = async () => { 54 | $list.textContent = ""; 55 | let allowTypes = $types.value ? JSON.parse($types.value) : true; 56 | let renderItem = (handle) => { 57 | let $item = document.createElement('div'); 58 | $item.classList.add('list-item', handle.kind); 59 | let name = handle.name; 60 | if (handle.kind === FileSystemHandleKindEnum.FILE && ( 61 | action === 'showDirectoryPicker' || !( 62 | allowTypes === true || 63 | allowTypes.some(ext => name.toLowerCase().endsWith(ext)) 64 | )) 65 | ) { 66 | // TODO 67 | $item.classList.add('disabled'); 68 | return; 69 | } 70 | let $name = document.createElement('div'); 71 | $name.classList.add('name'); 72 | let $size = document.createElement('div'); 73 | let $mtime = document.createElement('div'); 74 | let $type = document.createElement('div'); 75 | $name.textContent = name; 76 | $name.title = name; 77 | $item.appendChild($name); 78 | $item.appendChild($size); 79 | $item.appendChild($mtime); 80 | $item.appendChild($type); 81 | $list.appendChild($item); 82 | setTimeout(async () => { 83 | // XXX 84 | if (!$item.isConnected) return; 85 | let fileSize = (size) => { 86 | let i = Math.floor(Math.log(size || 1) / Math.log(1024)); 87 | return (size / Math.pow(1024, i)).toFixed(2) * 1 + ['B', 'KB', 'MB', 'GB', 'TB'][i]; 88 | }; 89 | try { 90 | let meta; 91 | if (handle.kind === FileSystemHandleKindEnum.FILE) { 92 | let file = await handle.getFile({ _allowNonNative: true }); 93 | meta = file; 94 | $size.title = `${file.size} bytes`; 95 | $size.textContent = fileSize(file.size); 96 | $size.setAttribute('data-value', file.size); 97 | $size.title = `${file.size} bytes`; 98 | $size.textContent = fileSize(file.size); 99 | $type.title = file.type; 100 | $type.textContent = file.type; 101 | } else { 102 | meta = await __FILE_SYSTEM_TOOLS__.getMetadata(handle); 103 | } 104 | if (!$item.isConnected) return; 105 | let mtime = (new Date(meta.lastModified)).toLocaleString('en-GB'); 106 | $mtime.textContent = mtime; 107 | $mtime.title = mtime; 108 | $mtime.setAttribute('data-value', meta.lastModified); 109 | _sortFileList(); 110 | } catch (e) { 111 | console.warn(e); 112 | } 113 | }, 100); 114 | }; 115 | let dir = $location.value; 116 | try { 117 | $list.classList.add('loading'); 118 | // XXX 119 | let listdrives = false; 120 | if (dir.trim() === "") { 121 | try { 122 | let r = await util.sendMessage('fs.abspath', { path: "C:/" }) 123 | listdrives = r.startsWith("C:"); 124 | } catch (e) { 125 | console.warn(e); 126 | } 127 | dir = listdrives ? "" : "/"; 128 | } 129 | let dirHandle; 130 | if (dir === "") { 131 | dirHandle = { 132 | values: async function* () { 133 | let letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; 134 | for (let letter of letters.split('')) { 135 | let path = `${letter}:/`; 136 | try { 137 | if (await util.sendMessage('fs.isdir', { path })) { 138 | yield await __FILE_SYSTEM_TOOLS__.createFileSystemHandle(path, FileSystemHandleKindEnum.DIRECTORY); 139 | } 140 | } catch (e) { 141 | console.warn(e); 142 | } 143 | } 144 | }, 145 | } 146 | } else { 147 | let expand = /^[~$%]/.test(dir); 148 | dir = await util.sendMessage('fs.abspath', { 149 | path: dir.replace(/[\\/]?$/, '/'), 150 | expand, 151 | }); 152 | if (!expand && /[$%]/.test(dir) && !await util.sendMessage('fs.exists', { path: dir })) { 153 | expand = true; 154 | dir = await util.sendMessage('fs.abspath', { 155 | path: dir, 156 | expand, 157 | }); 158 | } 159 | dirHandle = await __FILE_SYSTEM_TOOLS__.createFileSystemHandle(dir, FileSystemHandleKindEnum.DIRECTORY); 160 | dir = await __FILE_SYSTEM_TOOLS__.meta(dirHandle).path(); 161 | } 162 | $location.value = dir; 163 | renderSelectedItem(); 164 | for await (let handle of dirHandle.values()) { 165 | if ($location.value != dir) break; 166 | util.log(handle); 167 | renderItem(handle) 168 | } 169 | } catch (e) { 170 | console.error(e); 171 | alert(e?.message || e); 172 | } finally { 173 | if ($location.value == dir) { 174 | $list.classList.remove('loading'); 175 | sortFileList(); 176 | } 177 | } 178 | }; 179 | let renderSelectedItem = async () => { 180 | $select.disabled = true; 181 | let value = null; 182 | let name = ""; 183 | const dir = $location.value; 184 | try { 185 | switch (action) { 186 | case 'showOpenFilePicker': { 187 | let names = [...$list.querySelectorAll('.list-item.selected .name')].map($n => $n.title); 188 | value = await Promise.all(names.map(name => { 189 | return __FILE_SYSTEM_TOOLS__.joinName(dir, name); 190 | })); 191 | $list.classList[value.length > 0 ? 'add' : 'remove']('selected'); 192 | if (value.length == 0) { 193 | value = null; 194 | } else if (value.length == 1) { 195 | name = names[0]; 196 | } else { 197 | name = names.map(e => `"${e}"`).join(" "); 198 | } 199 | break; 200 | } 201 | case 'showDirectoryPicker': { 202 | value = $location.value; 203 | if (await util.sendMessage('fs.isdir', { path: value })) { 204 | name = await __FILE_SYSTEM_TOOLS__.basename(value); 205 | if (!name) name = value; 206 | } else { 207 | value = null; 208 | } 209 | break; 210 | } 211 | case 'showSaveFilePicker': { 212 | if (!verifyData) { 213 | verifyData = async (value) => { 214 | if (await util.sendMessage('fs.exists', { path: value })) { 215 | if (!confirm(`"${value}" already exists.\nDo you want to replace it?`)) { 216 | throw 'abort'; 217 | } 218 | } 219 | }; 220 | } 221 | let names = [...$list.querySelectorAll('.list-item.selected .name')].map($n => $n.title); 222 | if (names.length > 0) { 223 | $name.value = names[0]; 224 | } 225 | if (!!$name.value && !!$location.value) { 226 | name = $name.value; 227 | if (!names.length) name = name.trim(); 228 | value = await __FILE_SYSTEM_TOOLS__.joinName($location.value, name); 229 | } 230 | break; 231 | } 232 | } 233 | } catch (e) { 234 | console.warn(e); 235 | value = null; 236 | } 237 | if ($location.value != dir) return; 238 | _resolveData['select'] = async () => { 239 | if (verifyData) await verifyData(value); 240 | return value; 241 | }; 242 | $select.disabled = !value; 243 | $name.value = value ? name : ""; 244 | }; 245 | let sortFileList = () => { 246 | let orderBy = $table.getAttribute('data-order-by'); 247 | let order = $table.getAttribute('data-order'); 248 | if (!order) return; 249 | orderBy = parseInt(orderBy); 250 | let getValue = ($item) => { 251 | let $n = $item.children[orderBy]; 252 | let v = $n.getAttribute('data-value'); 253 | if (v !== null) { 254 | if (/^-?\d+(\.\d*)?$/.test(v)) v = parseFloat(v); 255 | } else { 256 | v = $n.title; 257 | } 258 | return v; 259 | } 260 | [...$list.children] 261 | .sort((a, b) => { 262 | let va = getValue(a); 263 | let vb = getValue(b); 264 | if (va == vb) { 265 | if (va === vb) return 0; 266 | if (va === "") va = -Infinity; 267 | if (vb === "") vb = -Infinity; 268 | } 269 | return (order == 'desc' ? va < vb : va > vb) ? 1 : -1; 270 | }) 271 | .forEach(node => $list.appendChild(node)); 272 | }; 273 | let debounce = (fn, wait) => { 274 | let timer = null; 275 | return function (...args) { 276 | if (timer !== null) clearTimeout(timer); 277 | timer = setTimeout(() => { 278 | fn.call(this, ...args); 279 | }, wait); 280 | }; 281 | }; 282 | let _sortFileList = debounce(sortFileList, 500); 283 | 284 | if (options.multiple) $container.classList.add('multiple'); 285 | if (Array.isArray(options.types)) { 286 | console.debug(options.types); 287 | $types.textContent = ''; 288 | let excludeAcceptAllOption = !!options.excludeAcceptAllOption; 289 | try { 290 | for (let type of options.types) { 291 | if (!type.accept) { 292 | excludeAcceptAllOption = false; 293 | continue; 294 | } 295 | let types = []; 296 | for (let mime in type.accept) { 297 | let ext = type.accept[mime]; 298 | if (!ext || !(ext = Array.isArray(ext) ? ext : [ext]) || ext.length == 0) { 299 | excludeAcceptAllOption = false; 300 | continue; 301 | } 302 | types.push(...ext.filter(e => e.startsWith('.')).map(e => e.toLowerCase())); 303 | } 304 | if (types.length === 0) continue; 305 | let description = `${type.description || ''} (${types.join(', ')})`; 306 | let $option = document.createElement('option'); 307 | $option.textContent = description; 308 | $option.value = JSON.stringify(types); 309 | $types.appendChild($option); 310 | } 311 | } catch (e) { 312 | console.error(e); 313 | excludeAcceptAllOption = false; 314 | } 315 | if (!excludeAcceptAllOption) { 316 | let $option = document.createElement('option'); 317 | $option.textContent = 'All Files'; 318 | $option.value = ''; 319 | $types.appendChild($option); 320 | } 321 | $types.addEventListener('change', renderFileList); 322 | } 323 | if (action === 'showSaveFilePicker') { 324 | $name.readOnly = false; 325 | if (options.suggestedName && typeof options.suggestedName === 'string') { 326 | $name.value = options.suggestedName; 327 | } 328 | } 329 | $location.value = options.startIn; 330 | renderFileList(); 331 | $container.querySelector('.location .up').addEventListener('click', async () => { 332 | let path = await __FILE_SYSTEM_TOOLS__.dirname($location.value); 333 | if (path === $location.value) path = ""; 334 | if (path && !await util.sendMessage('fs.isdir', { path })) { 335 | console.warn(`"${path}" is not a directory.`); 336 | return; 337 | } 338 | $location.value = path 339 | renderFileList(); 340 | }); 341 | $name.addEventListener('input', () => { 342 | [...$list.querySelectorAll('.list-item.selected')].map($n => $n.classList.remove('selected')); 343 | if ($name.value.trim() != "") $select.disabled = false; 344 | }); 345 | $name.addEventListener('change', () => { 346 | [...$list.querySelectorAll('.list-item.selected')].map($n => $n.classList.remove('selected')); 347 | renderSelectedItem(); 348 | }); 349 | $container.querySelector(`.select-items .clear`).addEventListener('click', () => { 350 | [...$list.querySelectorAll('.list-item.selected')].map($n => $n.classList.remove('selected')); 351 | $name.value = ""; 352 | renderSelectedItem(); 353 | }); 354 | $container.querySelector(`.file-list .list-header`).addEventListener('click', (event) => { 355 | let $n = event.target; 356 | if (!($n instanceof HTMLElement)) return; 357 | let $column = $n.closest('.list-header > *'); 358 | if (!$column) return; 359 | let orderBy = [...$column.parentElement.children].indexOf($column); 360 | let orderBy0 = $table.getAttribute('data-order-by'); 361 | let order = 'asc'; 362 | if (orderBy0 !== null && orderBy == orderBy0) { 363 | order = $table.getAttribute('data-order'); 364 | order = { 365 | '': 'asc', 366 | asc: 'desc', 367 | desc: '', 368 | }[order]; 369 | } 370 | $table.setAttribute('data-order-by', orderBy); 371 | $table.setAttribute('data-order', order); 372 | sortFileList(); 373 | }); 374 | $list.addEventListener('click', async (event) => { 375 | let $n = event.target; 376 | if (!($n instanceof HTMLElement)) return; 377 | let $item = $n.closest('.list-item'); 378 | if (!$item || $item.classList.contains('disabled')) return; 379 | let name = $item.querySelector('.name').title; 380 | if ($item.classList.contains('directory')) { 381 | if ($container.classList.contains('multiple') && $list.classList.contains('selected')) return; 382 | let dir = $location.value; 383 | $location.value = dir ? await __FILE_SYSTEM_TOOLS__.joinName(dir, name) : name; 384 | renderFileList(); 385 | } else if ($item.classList.contains('file')) { 386 | if ($item.classList.contains('selected')) { 387 | $item.classList.remove('selected'); 388 | } else { 389 | if (!options.multiple) [...$list.querySelectorAll('.list-item.selected')].map($n => $n.classList.remove('selected')); 390 | $item.classList.add('selected'); 391 | } 392 | renderSelectedItem(); 393 | } 394 | }); 395 | $location.addEventListener('change', renderFileList); 396 | $container.querySelector('.location .goto').addEventListener('click', renderFileList); 397 | }; 398 | -------------------------------------------------------------------------------- /src/lib/code-editor/editor.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Code Editor Extension 3 | * @version: 1.2 4 | */ 5 | 6 | /** 7 | * @typedef {string|number} Keybinding 8 | * @typedef {Record} FunctionRecord 9 | * @typedef {Record} ActionRecord 10 | * @typedef {({keybinding?:Keybinding}&monaco.editor.IKeybindingRule)} KeybindingRule 11 | * @typedef {({func:function|string,args?:any[],world?:'MAIN',injectImmediately?:boolean})} ScriptDetail 12 | * @typedef {({id?:string,options?:monaco.editor.IStandaloneEditorConstructionOptions&monaco.editor.IDiffEditorConstructionOptions&{originalValue?:string},events?:FunctionRecord,commands?:FunctionRecord,actions?:ActionRecord,keybindingRules?:KeybindingRule[],init?:ScriptDetail|ScriptDetail[],type?:'CodeEditor'|'DiffEditor'})} Context 13 | * 14 | * @typedef {string|string[]} ProxyChain 15 | * @typedef {({args?:any[],optional?:boolean,ext?:ProxyChain|ProxyOptions,clone?:string,chain?:ProxyChain})} ProxyOptions 16 | * 17 | * @typedef {({addExtraLib:(source:string,uri:string,createModel:boolean)=>void,addExtraLibs:(name:string|string[],createModel:boolean)=>void,setCompilerOptions:(options:monaco.languages.typescript.CompilerOptions)=>void,setDiagnosticsOptions:(options:monaco.languages.typescript.DiagnosticsOptions)=>void})} JSUtil 18 | * @typedef {({setDiagnosticsOptions:(options:monaco.languages.json.DiagnosticsOptions)=>void})} JSONUtil 19 | * @typedef {({pattern?:string|RegExp,excludePattern?:string|RegExp,kind?:number|string,insertTextRules?:number|string}&monaco.languages.CompletionItem)} CompletionItem 20 | * @typedef {({registerCompletionItems:(languageSelector:monaco.languages.LanguageSelector,items:CompletionItem[])=>void,javascript:JSUtil,typescript:JSUtil,json:JSONUtil})} LanguageUtil 21 | * @typedef {({ 22 | * editor:monaco.editor.IStandaloneCodeEditor|monaco.editor.IStandaloneDiffEditor, 23 | * primaryEditor:monaco.editor.IStandaloneCodeEditor, 24 | * addActions:(actions:ActionRecord)=>Promise, 25 | * addCommands:(commands:FunctionRecord)=>Promise, 26 | * addKeybindingRules:(rules:KeybindingRule[],init?:boolean)=>Promise, 27 | * updateEvents:(events:FunctionRecord)=>void, 28 | * updateOptions:(options:monaco.editor.IEditorOptions&monaco.editor.IGlobalEditorOptions&monaco.editor.IDiffEditorOptions&{value?:string,originalValue?:string,language?:string})=>void, 29 | * setEditorType:(type:'CodeEditor'|'DiffEditor')=>Promise, 30 | * getEditorType:()=>'CodeEditor'|'DiffEditor', 31 | * executeScript:(details:ScriptDetail)=>any, 32 | * sendMessage:(action:string,data:any)=>any, 33 | * sendEvent:(type:string,event:any,wait:boolean)=>any, 34 | * languages:LanguageUtil, 35 | * })} EditorUtil 36 | * @typedef {EditorUtil} AsyncEditorUtil 37 | * @typedef {monaco} AsyncMonaco 38 | */ 39 | 40 | /** 41 | * Available only in the editor context 42 | * @type {EditorUtil} 43 | */ 44 | var editorUtil; 45 | 46 | const codeEditor = { 47 | extensionId: "code-editor@example.com", 48 | /** 49 | * Create a new editor under $container 50 | * @param {HTMLTextAreaElement|HTMLElement} $container 51 | * @param {Context} context 52 | * @returns 53 | */ 54 | create($container, context = {}) { 55 | let classBlock = context.classBlock || 'ext-code-editor'; 56 | let $source; 57 | let restore = () => { }; 58 | if (!context.options) context.options = {}; 59 | switch ($container.nodeName) { 60 | case 'TEXTAREA': { 61 | $source = $container; 62 | if ($source.value !== "" && 'undefined' === typeof context.options.value) context.options.value = $source.value; 63 | break; 64 | } 65 | case 'SCRIPT': 66 | case 'TEMPLATE': { 67 | $source = $container; 68 | if ($source.value !== "" && 'undefined' === typeof context.options.value) context.options.value = $source.innerHTML; 69 | break; 70 | } 71 | } 72 | if ($source) { 73 | $container = document.createElement('div'); 74 | $source.style.display = 'none'; 75 | $source.insertAdjacentElement('afterend', $container); 76 | restore = () => { 77 | $source.style.display = ""; 78 | if ($container) $container.remove(); 79 | }; 80 | } 81 | $container.classList.add(`${classBlock}`, `${classBlock}--loading`); 82 | if (!context) context = {} 83 | if (!context.events) context.events = {}; 84 | if (!context.events.command) { 85 | context.events.command = function (event) { 86 | if (event.kbId) { 87 | if ("function" === typeof context.kbCommands[event.kbId]) { 88 | context.kbCommands[event.kbId].call(this, ...event.args); 89 | } 90 | } else if (event.scriptId) { 91 | if ("function" === typeof context.scripts[event.scriptId]) { 92 | let run = context.scripts[event.scriptId]; 93 | delete context.scripts[event.scriptId]; 94 | return run.call(this); 95 | } 96 | } else if (event.id) { 97 | if ("function" === typeof context.commands[event.id]) { 98 | context.commands[event.id].call(this, ...event.args); 99 | } 100 | } 101 | }; 102 | } 103 | if (!context.events.action) { 104 | context.events.action = function (event) { 105 | if (event.id && context.actions[event.id] && "function" === typeof context.actions[event.id].run) { 106 | context.actions[event.id].run.call(this, ...event.args); 107 | } 108 | }; 109 | } 110 | if (!context.commands) context.commands = {}; 111 | if (!context.kbCommands) context.kbCommands = {}; 112 | if (!context.keybindingRules) context.keybindingRules = []; 113 | if (!context.actions) context.actions = {}; 114 | if (!context.scripts) context.scripts = {}; 115 | 116 | const createId = () => { 117 | return `${Date.now()}-${Math.round(Math.random() * 1E4)}`; 118 | }; 119 | 120 | let id = context.id || createId(); 121 | const resolves = {}; 122 | const editor = { 123 | readyState: 'connecting', 124 | }; 125 | const promises = {}; 126 | { 127 | let readyStateComplete; 128 | let readyStateInteractive; 129 | promises.complete = new Promise(resolve => { readyStateComplete = resolve }); 130 | promises.interactive = new Promise(resolve => { readyStateInteractive = resolve }); 131 | let onreadystatechange = context.events.readystatechange; 132 | context.events.readystatechange = function (event) { 133 | editor.readyState = event.readyState; 134 | switch (event.readyState) { 135 | case 'loading': { 136 | break; 137 | } 138 | case 'interactive': { 139 | readyStateInteractive(); 140 | break; 141 | } 142 | case 'complete': { 143 | // await new Promise(r => setTimeout(r, 10000)); 144 | $container.classList.remove(`${classBlock}--loading`, `${classBlock}--disconnected`); 145 | readyStateComplete() 146 | break; 147 | } 148 | } 149 | if (onreadystatechange) onreadystatechange.call(editor, event); 150 | }; 151 | } 152 | const port = browser.runtime.connect(this.extensionId, { 153 | name: id, 154 | }); 155 | /** 156 | * Trigger event 157 | * @param {string} type 158 | * @param {*} event 159 | * @returns 160 | */ 161 | const emit = (type, event) => { 162 | if (context.events && "function" === typeof context.events[type]) { 163 | try { 164 | return context.events[type].call(editor, event); 165 | } catch (e) { 166 | console.error(e); 167 | } 168 | } 169 | }; 170 | port.onDisconnect.addListener((p) => { 171 | if (editor.readyState === "connecting") restore(); 172 | if (editor.readyState !== 'dispose') { 173 | editor.readyState = 'disconnected'; 174 | $container.classList.add(`${classBlock}--disconnected`); 175 | } 176 | if (emit('disconnect', p.error) !== false) console.info('editor_disconnect:', p.error) 177 | }); 178 | port.onMessage.addListener(async (message) => { 179 | // console.debug(message); 180 | if (!message) return; 181 | if (message.code) { 182 | if (message.id && resolves[message.id]) { 183 | resolves[message.id](message); 184 | delete resolves[message.id]; 185 | } 186 | } else { 187 | let result = { 188 | id: message.id, 189 | code: 200, 190 | data: null, 191 | }; 192 | let data = message.data || {}; 193 | try { 194 | switch (message.action) { 195 | case 'event': { 196 | // XXX throw error 197 | result.data = await emit(data.type, data.event); 198 | break; 199 | } 200 | default: { 201 | result.code = 404; 202 | } 203 | } 204 | if (result.id) port.postMessage(result); 205 | } catch (e) { 206 | if (e.code && 'data' in e) { 207 | result.code = e.code; 208 | result.data = e.data || e; 209 | } else { 210 | result.code = 500; 211 | result.data = e; 212 | } 213 | if (result.data) result.data = "" + result.data; 214 | if (result.id) port.postMessage(result); 215 | } 216 | } 217 | }); 218 | /** 219 | * Sends action to editor context 220 | * @param {string} action 221 | * @param {*} data 222 | * @returns 223 | */ 224 | const sendMessage = async (action, data) => { 225 | let id = `${Date.now()}-${Math.round(Math.random() * 1E4)}`; 226 | let message = { 227 | action, 228 | data, 229 | id, 230 | }; 231 | let promise = new Promise((resolve, reject) => { 232 | resolves[id] = (message) => { 233 | if (message && message.code === 200) { 234 | resolve(message.data) 235 | } else { 236 | reject(message); 237 | } 238 | } 239 | }); 240 | port.postMessage(message); 241 | return await promise; 242 | }; 243 | /** 244 | * Proxy iframe object 245 | * @param {ProxyChain} chain 246 | * @param {ProxyOptions} option 247 | * @returns {Promise} 248 | */ 249 | const proxy = async (chain, option = {}) => { 250 | await promises.interactive; 251 | let data = Object.assign({ chain }, option); 252 | return await sendMessage('proxy', data); 253 | }; 254 | const convertActions = (actions) => { 255 | let r = {}; 256 | if (!actions) return r; 257 | for (let id in actions) { 258 | r[id] = JSON.parse(JSON.stringify(actions[id])); 259 | } 260 | return r; 261 | }; 262 | const convertFunctions = (funcs) => { 263 | return Object.entries(funcs || {}).reduce((p, [k, v]) => (p[k] = "string" === typeof v ? v : !!v, p), {}); 264 | }; 265 | const convertKeybindingRules = (rules) => { 266 | let r = []; 267 | if (!rules || !Array.isArray(rules)) return r; 268 | for (let rule of rules) { 269 | let kb = rule.keybinding.trim(); 270 | rule.keybinding = kb; 271 | if (typeof rule.command === 'function') { 272 | let kbId = JSON.stringify({ 273 | keybinding: kb, 274 | when: rule.when || '', 275 | }); 276 | context.kbCommands[kbId] = rule.command; 277 | rule.kbId = kbId; 278 | delete rule.command; 279 | } 280 | r.push(rule); 281 | } 282 | return r; 283 | }; 284 | const normalScript = (details) => { 285 | if (Array.isArray(details)) { 286 | return details.map(d => normalScript(d)); 287 | } 288 | if ('MAIN' === details.world && details.func) { 289 | const id = createId(); 290 | const func = details.func; 291 | const args = details.args; 292 | context.scripts[id] = function () { 293 | return func.call(editor, ...(args || [])); 294 | }; 295 | details.scriptId = id; 296 | delete details.func; 297 | delete details.args; 298 | return details; 299 | } 300 | if ("function" === typeof details.func) { 301 | let func = "" + details.func; 302 | // XXX: unexpected token: identifier 303 | if (/^[^(]*func\s*\(/.test(func) && !/^[^(]*\bfunction\b[^(]*\(/.test(func)) { 304 | func = func.replace(/^([^(]*)(func\s*\()/, '$1 function $2'); 305 | } 306 | details.func = func; 307 | } 308 | return details; 309 | }; 310 | 311 | let init = context.init; 312 | if (init) { 313 | if (!Array.isArray(init)) init = [init]; 314 | normalScript(init); 315 | } 316 | 317 | let $el; 318 | const dispose = async () => { 319 | try { 320 | await proxy('editorUtil.editor.dispose', { args: [] }); 321 | } finally { 322 | editor.readyState = 'dispose'; 323 | if ($el) $el.remove(); 324 | restore(); 325 | } 326 | }; 327 | (async () => { 328 | let r = await sendMessage('create', { 329 | options: context.options || {}, 330 | events: convertFunctions(context.events), 331 | actions: convertActions(context.actions), 332 | commands: convertFunctions(context.commands), 333 | keybindingRules: convertKeybindingRules(context.keybindingRules), 334 | init, 335 | type: context.type, 336 | }); 337 | 338 | let n = document.createElement('iframe'); 339 | n.src = r.url; 340 | editor.url = r.url; 341 | $container.appendChild(n); 342 | $el = n; 343 | })(); 344 | 345 | return Object.assign(editor, { 346 | id, 347 | $container, 348 | promises, 349 | port, 350 | dispose, 351 | sendMessage, 352 | proxy, 353 | /** 354 | * @returns {AsyncEditorUtil} 355 | */ 356 | get util() { 357 | let that = this; 358 | function createProxy(chain = [], args = []) { 359 | return new Proxy(() => { }, { 360 | get(target, prop, receiver) { 361 | return createProxy([...chain, prop], args); 362 | }, 363 | apply(target, thisArg, args) { 364 | return that.proxy(chain, { args }); 365 | } 366 | }); 367 | } 368 | return createProxy(['editorUtil']); 369 | }, 370 | emit, 371 | /** 372 | * Update the editor's options. 373 | * @param {(Context['options']|FunctionRecord|ActionRecord|KeybindingRule[]|string)} value 374 | * @param {'options'|'actions'|'commands'|'events'|'keybindingRules'|'type'} type 375 | * @returns 376 | */ 377 | async updateOptions(value, type = 'options') { 378 | switch (type) { 379 | case 'actions': { 380 | Object.assign(context[type], value); 381 | value = convertActions(value); 382 | break; 383 | } 384 | case 'commands': 385 | case 'events': { 386 | Object.assign(context[type], value); 387 | value = convertFunctions(value); 388 | break; 389 | } 390 | case 'keybindingRules': { 391 | context[type].push(...value); 392 | value = convertKeybindingRules(value); 393 | break; 394 | } 395 | } 396 | return await sendMessage('updateContext', { 397 | [type]: value, 398 | }); 399 | }, 400 | /** 401 | * Get value of the current model attached to this editor. 402 | * @param {string} [name] 403 | * @returns {Promise} 404 | */ 405 | async getValue(name = null) { 406 | return await sendMessage('getValue', { 407 | name, 408 | }); 409 | }, 410 | /** 411 | * Injects a script into a target context. 412 | * @param {ScriptDetail} details 413 | * @returns 414 | */ 415 | async executeScript(details) { 416 | await promises.interactive; 417 | normalScript(details); 418 | return await sendMessage('executeScript', details); 419 | }, 420 | }); 421 | }, 422 | /** 423 | * Sends action to code-editor extension. 424 | * @param {string} action 425 | * @param {*} data 426 | * @returns 427 | */ 428 | async sendMessage(action, data) { 429 | let message = { 430 | action, 431 | data, 432 | }; 433 | let r = await browser.runtime.sendMessage(this.extensionId, message, {}); 434 | if (r && r.code === 200) { 435 | return r.data; 436 | } else { 437 | throw r; 438 | } 439 | }, 440 | async getEnv() { 441 | return await this.sendMessage('getEnv'); 442 | }, 443 | }; 444 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 2023 ichaoX 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 2023 ichaoX 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------