完善代码补全功能

This commit is contained in:
fofolee
2022-03-31 17:25:05 +08:00
parent 17cf743e1f
commit f6b8bb2a8d
21 changed files with 1273 additions and 18 deletions

View File

@@ -0,0 +1,8 @@
var Text = ["AppleScript", "false", "linefeed", "return", "pi", "quote", "result", "space", "tab", "true", ];
var Keyword = ["about", "above", "after", "against", "and", "around", "as", "at", "back", "before", "beginning", "behind", "below", "beneath", "beside", "between", "but", "by", "considering", "contain", "contains", "continue", "copy", "div", "does", "eighth", "else", "end", "equal", "equals", "error", "every", "exit", "fifth", "first", "for", "fourth", "from", "front", "get", "given", "global", "if", "ignoring", "in", "into", "is", "it", "its", "last", "local", "me", "middle", "mod", "my", "ninth", "not", "of", "on", "onto", "or", "over", "prop", "property", "put", "ref", "reference", "repeat", "returning", "script", "second", "set", "seventh", "since", "sixth", "some", "tell", "tenth", "that", "the", "then", "third", "through", "thru", "timeout", "times", "to", "transaction", "try", "until", "where", "while", "whose", "with", "without", "alias", "application", "boolean", "class", "constant", "date", "file", "integer", "list", "number", "real", "record", "string", "text", "character", "characters", "contents", "day", "frontmost", "id", "item", "length", "month", "name", "paragraph", "paragraphs", "rest", "reverse", "running", "time", "version", "weekday", "word", "words", "year"];
var Function = ["activate", "beep", "count", "delay", "launch", "log", "offset", "read", "round", "run", "say", "summarize", "write", "clipboard info", "the clipboard", "info for", "list disks", "list folder", "mount volume", "path to", "close for access", "open for access", "get eof", "set eof", "current date", "do shell script", "get volume settings", "random number", "set volume", "system attribute", "system info", "time to GMT", "load script", "run script", "store script", "scripting components", "ASCII character", "ASCII number", "localized string", "folder", "from list", "remote application", "URL", "display alert", "display dialog", ];
export default {
Keyword,
Function,
Text,
};

View File

@@ -0,0 +1,8 @@
var Text = ["true", "false"];
var Keyword = "goto|call|exit|break|exist|defined|errorlevel|cmdextversion|if|else|for|EQU|NEQ|LSS|LEQ|GTR|GEQ".split("|");
var Function = "assoc|bcdedit|cd|chcp|chdir|cls|color|copy|date|del|dir|echo|endlocal|erase|format|ftype|graftabl|md|mkdir|mklink|mode|more|move|path|pause|popd|prompt|pushd|rd|rem|ren|rename|rmdir|robocopy|set|setlocal|shift|start|time|title|tree|type|ver|verify|vol|wmic".split("|");
export default {
Text,
Keyword,
Function,
};

View File

@@ -0,0 +1,6 @@
var Keywords = "auto if break case register continue return default do sizeof static else struct switch extern typedef union for goto while enum const volatile inline restrict asm fortran".split(" ")
var Struct = "int long char short double float unsigned signed void bool".split(" ")
export default {
Keywords,
Struct
}

View File

@@ -0,0 +1,11 @@
var Keyword = "abstract as async await base break case catch checked class const continue" + " default delegate do else enum event explicit extern finally fixed for" + " foreach goto if implicit in interface internal is lock namespace new" + " operator out override params private protected public readonly ref return sealed" + " sizeof stackalloc static struct switch this throw try typeof unchecked" + " unsafe using virtual void volatile while add alias ascending descending dynamic from get" + " global group into join let orderby partial remove select set value var yield" + "catch class do else finally for foreach if struct switch try while" + "class interface namespace struct var"
var Struct = "Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func" + " Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32" + " UInt64 bool byte char decimal double short int long object" + " sbyte float string ushort uint ulong"
var Text = "true false null"
Keyword = Keyword.split(" ")
Struct = Struct.split(" ")
Text = Text.split(" ")
export default {
Keyword,
Struct,
Text
}

View File

@@ -0,0 +1,6 @@
var Function = ["_G", "_VERSION", "assert", "collectgarbage", "dofile", "error", "getfenv", "getmetatable", "ipairs", "load", "loadfile", "loadstring", "module", "next", "pairs", "pcall", "print", "rawequal", "rawget", "rawset", "require", "select", "setfenv", "setmetatable", "tonumber", "tostring", "type", "unpack", "xpcall", "coroutine.create", "coroutine.resume", "coroutine.running", "coroutine.status", "coroutine.wrap", "coroutine.yield", "debug.debug", "debug.getfenv", "debug.gethook", "debug.getinfo", "debug.getlocal", "debug.getmetatable", "debug.getregistry", "debug.getupvalue", "debug.setfenv", "debug.sethook", "debug.setlocal", "debug.setmetatable", "debug.setupvalue", "debug.traceback", "close", "flush", "lines", "read", "seek", "setvbuf", "write", "io.close", "io.flush", "io.input", "io.lines", "io.open", "io.output", "io.popen", "io.read", "io.stderr", "io.stdin", "io.stdout", "io.tmpfile", "io.type", "io.write", "math.abs", "math.acos", "math.asin", "math.atan", "math.atan2", "math.ceil", "math.cos", "math.cosh", "math.deg", "math.exp", "math.floor", "math.fmod", "math.frexp", "math.huge", "math.ldexp", "math.log", "math.log10", "math.max", "math.min", "math.modf", "math.pi", "math.pow", "math.rad", "math.random", "math.randomseed", "math.sin", "math.sinh", "math.sqrt", "math.tan", "math.tanh", "os.clock", "os.date", "os.difftime", "os.execute", "os.exit", "os.getenv", "os.remove", "os.rename", "os.setlocale", "os.time", "os.tmpname", "package.cpath", "package.loaded", "package.loaders", "package.loadlib", "package.path", "package.preload", "package.seeall", "string.byte", "string.char", "string.dump", "string.find", "string.format", "string.gmatch", "string.gsub", "string.len", "string.lower", "string.match", "string.rep", "string.reverse", "string.sub", "string.upper", "table.concat", "table.insert", "table.maxn", "table.remove", "table.sort"];
var Keyword = ["and", "break", "elseif", "false", "nil", "not", "or", "return", "true", "function", "end", "if", "then", "else", "do", "while", "repeat", "until", "for", "in", "local"];
export default {
Function,
Keyword
}

View File

@@ -0,0 +1,10 @@
var Function = ["abs", "accept", "alarm", "atan2", "bind", "binmode", "bless", "bootstrap", "break", "caller", "chdir", "chmod", "chomp", "chop", "chown", "chr", "chroot", "close", "closedir", "connect", "cos", "crypt", "dbmclose", "dbmopen", "default", "defined", "delete", "die", "do", "dump", "each", "endgrent", "endhostent", "endnetent", "endprotoent", "endpwent", "endservent", "eof", "eval", "exec", "exists", "exit", "exp", "fcntl", "fileno", "flock", "fork", "format", "formline", "getc", "getgrent", "getgrgid", "getgrnam", "gethostbyaddr", "gethostbyname", "gethostent", "getlogin", "getnetbyaddr", "getnetbyname", "getnetent", "getpeername", "getpgrp", "getppid", "getpriority", "getprotobyname", "getprotobynumber", "getprotoent", "getpwent", "getpwnam", "getpwuid", "getservbyname", "getservbyport", "getservent", "getsockname", "getsockopt", "given", "glob", "gmtime", "goto", "grep", "hex", "import", "index", "int", "ioctl", "join", "keys", "kill", "last", "lc", "lcfirst", "length", "link", "listen", "localtime", "lock", "log", "lstat", "map", "mkdir", "msgctl", "msgget", "msgrcv", "msgsnd", "new", "next", "no", "oct", "open", "opendir", "ord", "pack", "package", "pipe", "pop", "pos", "print", "printf", "prototype", "push", "rand", "read", "readdir", "readline", "readlink", "readpipe", "recv", "redo", "ref", "rename", "require", "reset", "return", "reverse", "rewinddir", "rindex", "rmdir", "say", "scalar", "seek", "seekdir", "select", "semctl", "semget", "semop", "send", "setgrent", "sethostent", "setnetent", "setpgrp", "setpriority", "setprotoent", "setpwent", "setservent", "setsockopt", "shift", "shmctl", "shmget", "shmread", "shmwrite", "shutdown", "sin", "sleep", "socket", "socketpair", "sort", "splice", "split", "sprintf", "sqrt", "srand", "stat", "state", "study", "sub", "substr", "symlink", "syscall", "sysopen", "sysread", "sysseek", "system", "syswrite", "tell", "telldir", "tie", "tied", "time", "times", "truncate", "uc", "ucfirst", "umask", "undef", "unlink", "unpack", "unshift", "untie", "use", "utime", "values", "vec", "wait", "waitpid", "wantarray", "warn", "when", "write"]
var Keyword = ["local", "my", "our"]
var Operator = ["lt", "gt", "le", "ge", "eq", "ne", "cmp", "not", "and", "or", "xor"]
var Variable = ["STDIN", "STDIN_TOP", "STDOUT", "STDOUT_TOP", "STDERR", "STDERR_TOP", "$ARG", "$_", "@ARG", "@_", "$LIST_SEPARATOR", "$\"", "$PROCESS_ID", "$PID", "$$", "$REAL_GROUP_ID", "$GID", "$(", "$EFFECTIVE_GROUP_ID", "$EGID", "$)", "$PROGRAM_NAME", "$0", "$SUBSCRIPT_SEPARATOR", "$SUBSEP", "$;", "$REAL_USER_ID", "$UID", "$<", "$EFFECTIVE_USER_ID", "$EUID", "$>", "$a", "$b", "$COMPILING", "$^C", "$DEBUGGING", "$^D", "${^ENCODING}", "$ENV", "%ENV", "$SYSTEM_FD_MAX", "$^F", "@F", "${^GLOBAL_PHASE}", "$^H", "%^H", "@INC", "%INC", "$INPLACE_EDIT", "$^I", "$^M", "$OSNAME", "$^O", "${^OPEN}", "$PERLDB", "$^P", "$SIG", "%SIG", "$BASETIME", "$^T", "${^TAINT}", "${^UNICODE}", "${^UTF8CACHE}", "${^UTF8LOCALE}", "$PERL_VERSION", "$^V", "${^WIN32_SLOPPY_STAT}", "$EXECUTABLE_NAME", "$^X", "$1", "$MATCH", "$&", "${^MATCH}", "$PREMATCH", "$`", "${^PREMATCH}", "$POSTMATCH", "$'", "${^POSTMATCH}", "$LAST_PAREN_MATCH", "$+", "$LAST_SUBMATCH_RESULT", "$^N", "@LAST_MATCH_END", "@+", "%LAST_PAREN_MATCH", "%+", "@LAST_MATCH_START", "@-", "%LAST_MATCH_START", "%-", "$LAST_REGEXP_CODE_RESULT", "$^R", "${^RE_DEBUG_FLAGS}", "${^RE_TRIE_MAXBUF}", "$ARGV", "@ARGV", "ARGV", "ARGVOUT", "$OUTPUT_FIELD_SEPARATOR", "$OFS", "$,", "$INPUT_LINE_NUMBER", "$NR", "$.", "$INPUT_RECORD_SEPARATOR", "$RS", "$/", "$OUTPUT_RECORD_SEPARATOR", "$ORS", "$\\", "$OUTPUT_AUTOFLUSH", "$|", "$ACCUMULATOR", "$^A", "$FORMAT_FORMFEED", "$^L", "$FORMAT_PAGE_NUMBER", "$%", "$FORMAT_LINES_LEFT", "$-", "$FORMAT_LINE_BREAK_CHARACTERS", "$:", "$FORMAT_LINES_PER_PAGE", "$=", "$FORMAT_TOP_NAME", "$^", "$FORMAT_NAME", "$~", "${^CHILD_ERROR_NATIVE}", "$EXTENDED_OS_ERROR", "$^E", "$EXCEPTIONS_BEING_CAUGHT", "$^S", "$WARNING", "$^W", "${^WARNING_BITS}", "$OS_ERROR", "$ERRNO", "$!", "%OS_ERROR", "%ERRNO", "%!", "$CHILD_ERROR", "$?", "$EVAL_ERROR", "$@", "$OFMT", "$#", "$*", "$ARRAY_BASE", "$[", "$OLD_PERL_VERSION", "$]"]
export default {
Function,
Keyword,
Operator,
Variable
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,11 @@
var Keyword = ["as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "lambda", "pass", "raise", "return", "try", "while", "with", "yield", "in", "nonlocal", "False", "True", "None", "async", "await", ];
var Function = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr", "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod", "enumerate", "eval", "filter", "float", "format", "frozenset", "getattr", "globals", "hasattr", "hash", "help", "hex", "id", "input", "int", "isinstance", "issubclass", "iter", "len", "list", "locals", "map", "max", "memoryview", "min", "next", "object", "oct", "open", "ord", "pow", "property", "range", "repr", "reversed", "round", "set", "setattr", "slice", "sorted", "staticmethod", "str", "sum", "super", "tuple", "type", "vars", "zip", "__import__", "NotImplemented", "Ellipsis", "__debug__", "ascii", "bytes", "exec", "print", ];
var Operator = ["and", "or", "not", "is"];
var Text = ["True", "False"]
export default {
Keyword,
Function,
Operator,
Text
};

View File

@@ -0,0 +1,4 @@
var Keyword = ["alias", "and", "BEGIN", "begin", "break", "case", "class", "def", "defined?", "do", "else", "elsif", "END", "end", "ensure", "false", "for", "if", "in", "module", "next", "not", "or", "redo", "rescue", "retry", "return", "self", "super", "then", "true", "undef", "unless", "until", "when", "while", "yield", "nil", "raise", "throw", "catch", "fail", "loop", "callcc", "caller", "lambda", "proc", "public", "protected", "private", "require", "load", "require_relative", "extend", "autoload", "__END__", "__FILE__", "__LINE__", "__dir__", "def", "class", "case", "for", "while", "until", "module", "then", "catch", "loop", "proc", "begin", "end", "until", ];
export default {
Keyword
};

View File

@@ -0,0 +1,8 @@
var Keyword = ["if", "then", "do", "else", "elif", "while", "until", "for", "in", "esac", "fi", "fin", "fil", "done", "exit", "set", "unset", "export", "function", ];
var Function = "ab|awk|bash|beep|cat|cc|cd|chown|chmod|chroot|clear|cp|curl|cut|diff|echo|find|gawk|gcc|get|git|grep|hg|kill|killall|ln|ls|make|mkdir|openssl|mv|nc|nl|node|npm|ping|ps|restart|rm|rmdir|sed|service|sh|shopt|shred|source|sort|sleep|ssh|start|stop|su|sudo|svn|tee|telnet|top|touch|vi|vim|wall|wc|wget|who|write|yes|zsh".split("|");
var Text = ["true", "false"];
export default {
Keyword,
Function,
Text,
};

103
src/plugins/monaco/types/common.d.ts vendored Normal file
View File

@@ -0,0 +1,103 @@
// Axios
interface AxiosRequestConfig<D = any> {
url?: string;
method?: Method;
baseURL?: string;
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
headers?: AxiosRequestHeaders;
params?: any;
paramsSerializer?: (params: any) => string;
data?: D;
timeout?: number;
timeoutErrorMessage?: string;
withCredentials?: boolean;
adapter?: AxiosAdapter;
auth?: AxiosBasicCredentials;
responseType?: ResponseType;
xsrfCookieName?: string;
xsrfHeaderName?: string;
onUploadProgress?: (progressEvent: any) => void;
onDownloadProgress?: (progressEvent: any) => void;
maxContentLength?: number;
validateStatus?: ((status: number) => boolean) | null;
maxBodyLength?: number;
maxRedirects?: number;
socketPath?: string | null;
httpAgent?: any;
httpsAgent?: any;
proxy?: AxiosProxyConfig | false;
cancelToken?: CancelToken;
decompress?: boolean;
transitional?: TransitionalOptions;
signal?: AbortSignal;
insecureHTTPParser?: boolean;
}
interface Axios {
constructor(config?: AxiosRequestConfig);
defaults: AxiosDefaults;
interceptors: {
request: AxiosInterceptorManager<AxiosRequestConfig>;
response: AxiosInterceptorManager<AxiosResponse>;
};
getUri(config?: AxiosRequestConfig): string;
request<T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig<D>): Promise<R>;
get<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
delete<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
head<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
options<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
post<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
put<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
patch<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
}
declare var axios: Axios;
// Audio
declare var Audio: {
new(src?: string): HTMLAudioElement;
};
// fetch
interface RequestInit {
// whatwg/fetch standard options
body?: BodyInit | undefined;
headers?: HeadersInit | undefined;
method?: string | undefined;
redirect?: RequestRedirect | undefined;
signal?: AbortSignal | null | undefined;
// node-fetch extensions
agent?: RequestOptions['agent'] | ((parsedUrl: URL) => RequestOptions['agent']); // =null http.Agent instance, allows custom proxy, certificate etc.
compress?: boolean | undefined; // =true support gzip/deflate content encoding. false to disable
follow?: number | undefined; // =20 maximum redirect count. 0 to not follow redirect
size?: number | undefined; // =0 maximum response body size in bytes. 0 to disable
timeout?: number | undefined; // =0 req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies)
// node-fetch does not support mode, cache or credentials options
}
declare function fetch(
url: RequestInfo,
init?: RequestInit
): Promise<Response>;
// console
declare var console: {
log(message?: any): void,
error(message?: any): void
}
// process
declare var process: {
argv: any[];
title: string;
version: string;
versions: object;
arch: string;
platform: string;
env: object;
pid: number;
features: object
}

762
src/plugins/monaco/types/electron.d.ts vendored Normal file
View File

@@ -0,0 +1,762 @@
interface Clipboard {
// Docs: https://electronjs.org/docs/api/clipboard
/**
* An array of supported formats for the clipboard `type`.
*/
availableFormats(type?: 'selection' | 'clipboard'): string[];
/**
* Clears the clipboard content.
*/
clear(type?: 'selection' | 'clipboard'): void;
/**
* Whether the clipboard supports the specified `format`.
*
* @experimental
*/
has(format: string, type?: 'selection' | 'clipboard'): boolean;
/**
* Reads `format` type from the clipboard.
*
* `format` should contain valid ASCII characters and have `/` separator. `a/c`,
* `a/bc` are valid formats while `/abc`, `abc/`, `a/`, `/a`, `a` are not valid.
*
* @experimental
*/
read(format: string): string;
/**
* * `title` string
* * `url` string
*
* Returns an Object containing `title` and `url` keys representing the bookmark in
* the clipboard. The `title` and `url` values will be empty strings when the
* bookmark is unavailable. The `title` value will always be empty on Windows.
*
* @platform darwin,win32
*/
readBookmark(): ReadBookmark;
/**
* Reads `format` type from the clipboard.
*
* @experimental
*/
readBuffer(format: string): Buffer;
/**
* The text on the find pasteboard, which is the pasteboard that holds information
* about the current state of the active applications find panel.
*
* This method uses synchronous IPC when called from the renderer process. The
* cached value is reread from the find pasteboard whenever the application is
* activated.
*
* @platform darwin
*/
readFindText(): string;
/**
* The content in the clipboard as markup.
*/
readHTML(type?: 'selection' | 'clipboard'): string;
/**
* The image content in the clipboard.
*/
readImage(type?: 'selection' | 'clipboard'): NativeImage;
/**
* The content in the clipboard as RTF.
*/
readRTF(type?: 'selection' | 'clipboard'): string;
/**
* The content in the clipboard as plain text.
*/
readText(type?: 'selection' | 'clipboard'): string;
/**
* Writes `data` to the clipboard.
*/
write(data: Data, type?: 'selection' | 'clipboard'): void;
/**
* Writes the `title` (macOS only) and `url` into the clipboard as a bookmark.
*
* **Note:** Most apps on Windows don't support pasting bookmarks into them so you
* can use `clipboard.write` to write both a bookmark and fallback text to the
* clipboard.
*
* @platform darwin,win32
*/
writeBookmark(title: string, url: string, type?: 'selection' | 'clipboard'): void;
/**
* Writes the `buffer` into the clipboard as `format`.
*
* @experimental
*/
writeBuffer(format: string, buffer: Buffer, type?: 'selection' | 'clipboard'): void;
/**
* Writes the `text` into the find pasteboard (the pasteboard that holds
* information about the current state of the active applications find panel) as
* plain text. This method uses synchronous IPC when called from the renderer
* process.
*
* @platform darwin
*/
writeFindText(text: string): void;
/**
* Writes `markup` to the clipboard.
*/
writeHTML(markup: string, type?: 'selection' | 'clipboard'): void;
/**
* Writes `image` to the clipboard.
*/
writeImage(image: NativeImage, type?: 'selection' | 'clipboard'): void;
/**
* Writes the `text` into the clipboard in RTF.
*/
writeRTF(text: string, type?: 'selection' | 'clipboard'): void;
/**
* Writes the `text` into the clipboard as plain text.
*/
writeText(text: string, type?: 'selection' | 'clipboard'): void;
}
interface ContextBridge {
// Docs: https://electronjs.org/docs/api/context-bridge
exposeInMainWorld(apiKey: string, api: any): void;
}
interface CrashReporter {
// Docs: https://electronjs.org/docs/api/crash-reporter
/**
* Set an extra parameter to be sent with the crash report. The values specified
* here will be sent in addition to any values set via the `extra` option when
* `start` was called.
*
* Parameters added in this fashion (or via the `extra` parameter to
* `crashReporter.start`) are specific to the calling process. Adding extra
* parameters in the main process will not cause those parameters to be sent along
* with crashes from renderer or other child processes. Similarly, adding extra
* parameters in a renderer process will not result in those parameters being sent
* with crashes that occur in other renderer processes or in the main process.
*
* **Note:** Parameters have limits on the length of the keys and values. Key names
* must be no longer than 39 bytes, and values must be no longer than 20320 bytes.
* Keys with names longer than the maximum will be silently ignored. Key values
* longer than the maximum length will be truncated.
*/
addExtraParameter(key: string, value: string): void;
/**
* The date and ID of the last crash report. Only crash reports that have been
* uploaded will be returned; even if a crash report is present on disk it will not
* be returned until it is uploaded. In the case that there are no uploaded
* reports, `null` is returned.
*
* **Note:** This method is only available in the main process.
*/
getLastCrashReport(): CrashReport;
/**
* The current 'extra' parameters of the crash reporter.
*/
getParameters(): Record<string, string>;
/**
* Returns all uploaded crash reports. Each report contains the date and uploaded
* ID.
*
* **Note:** This method is only available in the main process.
*/
getUploadedReports(): CrashReport[];
/**
* Whether reports should be submitted to the server. Set through the `start`
* method or `setUploadToServer`.
*
* **Note:** This method is only available in the main process.
*/
getUploadToServer(): boolean;
/**
* Remove an extra parameter from the current set of parameters. Future crashes
* will not include this parameter.
*/
removeExtraParameter(key: string): void;
/**
* This would normally be controlled by user preferences. This has no effect if
* called before `start` is called.
*
* **Note:** This method is only available in the main process.
*/
setUploadToServer(uploadToServer: boolean): void;
/**
* This method must be called before using any other `crashReporter` APIs. Once
* initialized this way, the crashpad handler collects crashes from all
* subsequently created processes. The crash reporter cannot be disabled once
* started.
*
* This method should be called as early as possible in app startup, preferably
* before `app.on('ready')`. If the crash reporter is not initialized at the time a
* renderer process is created, then that renderer process will not be monitored by
* the crash reporter.
*
* **Note:** You can test out the crash reporter by generating a crash using
* `process.crash()`.
*
* **Note:** If you need to send additional/updated `extra` parameters after your
* first call `start` you can call `addExtraParameter`.
*
* **Note:** Parameters passed in `extra`, `globalExtra` or set with
* `addExtraParameter` have limits on the length of the keys and values. Key names
* must be at most 39 bytes long, and values must be no longer than 127 bytes. Keys
* with names longer than the maximum will be silently ignored. Key values longer
* than the maximum length will be truncated.
*
* **Note:** This method is only available in the main process.
*/
start(options: CrashReporterStartOptions): void;
}
interface IpcRenderer extends NodeJS.EventEmitter {
// Docs: https://electronjs.org/docs/api/ipc-renderer
/**
* Resolves with the response from the main process.
*
* Send a message to the main process via `channel` and expect a result
* asynchronously. Arguments will be serialized with the Structured Clone
* Algorithm, just like `window.postMessage`, so prototype chains will not be
* included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw
* an exception.
*
* > **NOTE:** Sending non-standard JavaScript types such as DOM objects or special
* Electron objects will throw an exception.
*
* Since the main process does not have support for DOM objects such as
* `ImageBitmap`, `File`, `DOMMatrix` and so on, such objects cannot be sent over
* Electron's IPC to the main process, as the main process would have no way to
* decode them. Attempting to send such objects over IPC will result in an error.
*
* The main process should listen for `channel` with `ipcMain.handle()`.
*
* For example:
*
* If you need to transfer a `MessagePort` to the main process, use
* `ipcRenderer.postMessage`.
*
* If you do not need a response to the message, consider using `ipcRenderer.send`.
*/
invoke(channel: string, ...args: any[]): Promise<any>;
/**
* Listens to `channel`, when a new message arrives `listener` would be called with
* `listener(event, args...)`.
*/
on(channel: string, listener: (event: IpcRendererEvent, ...args: any[]) => void): this;
/**
* Adds a one time `listener` function for the event. This `listener` is invoked
* only the next time a message is sent to `channel`, after which it is removed.
*/
once(channel: string, listener: (event: IpcRendererEvent, ...args: any[]) => void): this;
/**
* Send a message to the main process, optionally transferring ownership of zero or
* more `MessagePort` objects.
*
* The transferred `MessagePort` objects will be available in the main process as
* `MessagePortMain` objects by accessing the `ports` property of the emitted
* event.
*
* For example:
*
* For more information on using `MessagePort` and `MessageChannel`, see the MDN
* documentation.
*/
postMessage(channel: string, message: any, transfer?: MessagePort[]): void;
/**
* Removes all listeners, or those of the specified `channel`.
*/
removeAllListeners(channel: string): this;
/**
* Removes the specified `listener` from the listener array for the specified
* `channel`.
*/
removeListener(channel: string, listener: (...args: any[]) => void): this;
/**
* Send an asynchronous message to the main process via `channel`, along with
* arguments. Arguments will be serialized with the Structured Clone Algorithm,
* just like `window.postMessage`, so prototype chains will not be included.
* Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an
* exception.
*
* > **NOTE:** Sending non-standard JavaScript types such as DOM objects or special
* Electron objects will throw an exception.
*
* Since the main process does not have support for DOM objects such as
* `ImageBitmap`, `File`, `DOMMatrix` and so on, such objects cannot be sent over
* Electron's IPC to the main process, as the main process would have no way to
* decode them. Attempting to send such objects over IPC will result in an error.
*
* The main process handles it by listening for `channel` with the `ipcMain`
* module.
*
* If you need to transfer a `MessagePort` to the main process, use
* `ipcRenderer.postMessage`.
*
* If you want to receive a single response from the main process, like the result
* of a method call, consider using `ipcRenderer.invoke`.
*/
send(channel: string, ...args: any[]): void;
/**
* The value sent back by the `ipcMain` handler.
*
* Send a message to the main process via `channel` and expect a result
* synchronously. Arguments will be serialized with the Structured Clone Algorithm,
* just like `window.postMessage`, so prototype chains will not be included.
* Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an
* exception.
*
* > **NOTE:** Sending non-standard JavaScript types such as DOM objects or special
* Electron objects will throw an exception.
*
* Since the main process does not have support for DOM objects such as
* `ImageBitmap`, `File`, `DOMMatrix` and so on, such objects cannot be sent over
* Electron's IPC to the main process, as the main process would have no way to
* decode them. Attempting to send such objects over IPC will result in an error.
*
* The main process handles it by listening for `channel` with `ipcMain` module,
* and replies by setting `event.returnValue`.
*
* > :warning: **WARNING**: Sending a synchronous message will block the whole
* renderer process until the reply is received, so use this method only as a last
* resort. It's much better to use the asynchronous version, `invoke()`.
*/
sendSync(channel: string, ...args: any[]): any;
/**
* Sends a message to a window with `webContentsId` via `channel`.
*/
sendTo(webContentsId: number, channel: string, ...args: any[]): void;
/**
* Like `ipcRenderer.send` but the event will be sent to the `<webview>` element in
* the host page instead of the main process.
*/
sendToHost(channel: string, ...args: any[]): void;
}
interface IpcRendererEvent extends Event {
// Docs: https://electronjs.org/docs/api/structures/ipc-renderer-event
/**
* A list of MessagePorts that were transferred with this message
*/
ports: MessagePort[];
/**
* The `IpcRenderer` instance that emitted the event originally
*/
sender: IpcRenderer;
/**
* The `webContents.id` that sent the message, you can call
* `event.sender.sendTo(event.senderId, ...)` to reply to the message, see
* ipcRenderer.sendTo for more information. This only applies to messages sent from
* a different renderer. Messages sent directly from the main process set
* `event.senderId` to `0`.
*/
senderId: number;
}
class NativeImage {
// Docs: https://electronjs.org/docs/api/native-image
/**
* Creates an empty `NativeImage` instance.
*/
static createEmpty(): NativeImage;
/**
* Creates a new `NativeImage` instance from `buffer` that contains the raw bitmap
* pixel data returned by `toBitmap()`. The specific format is platform-dependent.
*/
static createFromBitmap(buffer: Buffer, options: CreateFromBitmapOptions): NativeImage;
/**
* Creates a new `NativeImage` instance from `buffer`. Tries to decode as PNG or
* JPEG first.
*/
static createFromBuffer(buffer: Buffer, options?: CreateFromBufferOptions): NativeImage;
/**
* Creates a new `NativeImage` instance from `dataURL`.
*/
static createFromDataURL(dataURL: string): NativeImage;
/**
* Creates a new `NativeImage` instance from the NSImage that maps to the given
* image name. See `System Icons` for a list of possible values.
*
* The `hslShift` is applied to the image with the following rules:
*
* * `hsl_shift[0]` (hue): The absolute hue value for the image - 0 and 1 map to 0
* and 360 on the hue color wheel (red).
* * `hsl_shift[1]` (saturation): A saturation shift for the image, with the
* following key values: 0 = remove all color. 0.5 = leave unchanged. 1 = fully
* saturate the image.
* * `hsl_shift[2]` (lightness): A lightness shift for the image, with the
* following key values: 0 = remove all lightness (make all pixels black). 0.5 =
* leave unchanged. 1 = full lightness (make all pixels white).
*
* This means that `[-1, 0, 1]` will make the image completely white and `[-1, 1,
* 0]` will make the image completely black.
*
* In some cases, the `NSImageName` doesn't match its string representation; one
* example of this is `NSFolderImageName`, whose string representation would
* actually be `NSFolder`. Therefore, you'll need to determine the correct string
* representation for your image before passing it in. This can be done with the
* following:
*
* `echo -e '#import <Cocoa/Cocoa.h>\nint main() { NSLog(@"%@", SYSTEM_IMAGE_NAME);
* }' | clang -otest -x objective-c -framework Cocoa - && ./test`
*
* where `SYSTEM_IMAGE_NAME` should be replaced with any value from this list.
*
* @platform darwin
*/
static createFromNamedImage(imageName: string, hslShift?: number[]): NativeImage;
/**
* Creates a new `NativeImage` instance from a file located at `path`. This method
* returns an empty image if the `path` does not exist, cannot be read, or is not a
* valid image.
*/
static createFromPath(path: string): NativeImage;
/**
* fulfilled with the file's thumbnail preview image, which is a NativeImage.
*
* @platform darwin,win32
*/
static createThumbnailFromPath(path: string, maxSize: Size): Promise<Electron.NativeImage>;
/**
* Add an image representation for a specific scale factor. This can be used to
* explicitly add different scale factor representations to an image. This can be
* called on empty images.
*/
addRepresentation(options: AddRepresentationOptions): void;
/**
* The cropped image.
*/
crop(rect: Rectangle): NativeImage;
/**
* The image's aspect ratio.
*
* If `scaleFactor` is passed, this will return the aspect ratio corresponding to
* the image representation most closely matching the passed value.
*/
getAspectRatio(scaleFactor?: number): number;
/**
* A Buffer that contains the image's raw bitmap pixel data.
*
* The difference between `getBitmap()` and `toBitmap()` is that `getBitmap()` does
* not copy the bitmap data, so you have to use the returned Buffer immediately in
* current event loop tick; otherwise the data might be changed or destroyed.
*/
getBitmap(options?: BitmapOptions): Buffer;
/**
* A Buffer that stores C pointer to underlying native handle of the image. On
* macOS, a pointer to `NSImage` instance would be returned.
*
* Notice that the returned pointer is a weak pointer to the underlying native
* image instead of a copy, so you _must_ ensure that the associated `nativeImage`
* instance is kept around.
*
* @platform darwin
*/
getNativeHandle(): Buffer;
/**
* An array of all scale factors corresponding to representations for a given
* nativeImage.
*/
getScaleFactors(): number[];
/**
* If `scaleFactor` is passed, this will return the size corresponding to the image
* representation most closely matching the passed value.
*/
getSize(scaleFactor?: number): Size;
/**
* Whether the image is empty.
*/
isEmpty(): boolean;
/**
* Whether the image is a template image.
*/
isTemplateImage(): boolean;
/**
* The resized image.
*
* If only the `height` or the `width` are specified then the current aspect ratio
* will be preserved in the resized image.
*/
resize(options: ResizeOptions): NativeImage;
/**
* Marks the image as a template image.
*/
setTemplateImage(option: boolean): void;
/**
* A Buffer that contains a copy of the image's raw bitmap pixel data.
*/
toBitmap(options?: ToBitmapOptions): Buffer;
/**
* The data URL of the image.
*/
toDataURL(options?: ToDataURLOptions): string;
/**
* A Buffer that contains the image's `JPEG` encoded data.
*/
toJPEG(quality: number): Buffer;
/**
* A Buffer that contains the image's `PNG` encoded data.
*/
toPNG(options?: ToPNGOptions): Buffer;
/**
* A `boolean` property that determines whether the image is considered a template
* image.
*
* Please note that this property only has an effect on macOS.
*
* @platform darwin
*/
isMacTemplateImage: boolean;
}
interface Shell {
// Docs: https://electronjs.org/docs/api/shell
/**
* Play the beep sound.
*/
beep(): void;
/**
* Open the given external protocol URL in the desktop's default manner. (For
* example, mailto: URLs in the user's default mail agent).
*/
openExternal(url: string, options?: OpenExternalOptions): Promise<void>;
/**
* Resolves with a string containing the error message corresponding to the failure
* if a failure occurred, otherwise "".
*
* Open the given file in the desktop's default manner.
*/
openPath(path: string): Promise<string>;
/**
* Resolves the shortcut link at `shortcutPath`.
*
* An exception will be thrown when any error happens.
*
* @platform win32
*/
readShortcutLink(shortcutPath: string): ShortcutDetails;
/**
* Show the given file in a file manager. If possible, select the file.
*/
showItemInFolder(fullPath: string): void;
/**
* Resolves when the operation has been completed. Rejects if there was an error
* while deleting the requested item.
*
* This moves a path to the OS-specific trash location (Trash on macOS, Recycle Bin
* on Windows, and a desktop-environment-specific location on Linux).
*/
trashItem(path: string): Promise<void>;
/**
* Whether the shortcut was created successfully.
*
* Creates or updates a shortcut link at `shortcutPath`.
*
* @platform win32
*/
writeShortcutLink(shortcutPath: string, operation: 'create' | 'update' | 'replace', options: ShortcutDetails): boolean;
/**
* Whether the shortcut was created successfully.
*
* Creates or updates a shortcut link at `shortcutPath`.
*
* @platform win32
*/
writeShortcutLink(shortcutPath: string, options: ShortcutDetails): boolean;
}
interface WebFrame extends NodeJS.EventEmitter {
// Docs: https://electronjs.org/docs/api/web-frame
/**
* Attempts to free memory that is no longer being used (like images from a
* previous navigation).
*
* Note that blindly calling this method probably makes Electron slower since it
* will have to refill these emptied caches, you should only call it if an event in
* your app has occurred that makes you think your page is actually using less
* memory (i.e. you have navigated from a super heavy page to a mostly empty one,
* and intend to stay there).
*/
clearCache(): void;
/**
* A promise that resolves with the result of the executed code or is rejected if
* execution throws or results in a rejected promise.
*
* Evaluates `code` in page.
*
* In the browser window some HTML APIs like `requestFullScreen` can only be
* invoked by a gesture from the user. Setting `userGesture` to `true` will remove
* this limitation.
*/
executeJavaScript(code: string, userGesture?: boolean, callback?: (result: any, error: Error) => void): Promise<any>;
/**
* A promise that resolves with the result of the executed code or is rejected if
* execution could not start.
*
* Works like `executeJavaScript` but evaluates `scripts` in an isolated context.
*
* Note that when the execution of script fails, the returned promise will not
* reject and the `result` would be `undefined`. This is because Chromium does not
* dispatch errors of isolated worlds to foreign worlds.
*/
executeJavaScriptInIsolatedWorld(worldId: number, scripts: WebSource[], userGesture?: boolean, callback?: (result: any, error: Error) => void): Promise<any>;
/**
* A child of `webFrame` with the supplied `name`, `null` would be returned if
* there's no such frame or if the frame is not in the current renderer process.
*/
findFrameByName(name: string): WebFrame;
/**
* that has the supplied `routingId`, `null` if not found.
*/
findFrameByRoutingId(routingId: number): WebFrame;
/**
* The frame element in `webFrame's` document selected by `selector`, `null` would
* be returned if `selector` does not select a frame or if the frame is not in the
* current renderer process.
*/
getFrameForSelector(selector: string): WebFrame;
/**
* * `images` MemoryUsageDetails
* * `scripts` MemoryUsageDetails
* * `cssStyleSheets` MemoryUsageDetails
* * `xslStyleSheets` MemoryUsageDetails
* * `fonts` MemoryUsageDetails
* * `other` MemoryUsageDetails
*
* Returns an object describing usage information of Blink's internal memory
* caches.
*
* This will generate:
*/
getResourceUsage(): ResourceUsage;
/**
* A list of suggested words for a given word. If the word is spelled correctly,
* the result will be empty.
*/
getWordSuggestions(word: string): string[];
/**
* The current zoom factor.
*/
getZoomFactor(): number;
/**
* The current zoom level.
*/
getZoomLevel(): number;
/**
* A key for the inserted CSS that can later be used to remove the CSS via
* `webFrame.removeInsertedCSS(key)`.
*
* Injects CSS into the current web page and returns a unique key for the inserted
* stylesheet.
*/
insertCSS(css: string, options?: InsertCSSOptions): string;
/**
* Inserts `text` to the focused element.
*/
insertText(text: string): void;
/**
* True if the word is misspelled according to the built in spellchecker, false
* otherwise. If no dictionary is loaded, always return false.
*/
isWordMisspelled(word: string): boolean;
/**
* Removes the inserted CSS from the current web page. The stylesheet is identified
* by its key, which is returned from `webFrame.insertCSS(css)`.
*/
removeInsertedCSS(key: string): void;
/**
* Set the security origin, content security policy and name of the isolated world.
* Note: If the `csp` is specified, then the `securityOrigin` also has to be
* specified.
*/
setIsolatedWorldInfo(worldId: number, info: Info): void;
setSpellCheckProvider(language: string, provider: Provider): void;
/**
* Sets the maximum and minimum pinch-to-zoom level.
*
* > **NOTE**: Visual zoom is disabled by default in Electron. To re-enable it,
* call:
*
* > **NOTE**: Visual zoom only applies to pinch-to-zoom behavior. Cmd+/-/0 zoom
* shortcuts are controlled by the 'zoomIn', 'zoomOut', and 'resetZoom' MenuItem
* roles in the application Menu. To disable shortcuts, manually define the Menu
* and omit zoom roles from the definition.
*/
setVisualZoomLevelLimits(minimumLevel: number, maximumLevel: number): void;
/**
* Changes the zoom factor to the specified factor. Zoom factor is zoom percent
* divided by 100, so 300% = 3.0.
*
* The factor must be greater than 0.0.
*/
setZoomFactor(factor: number): void;
/**
* Changes the zoom level to the specified level. The original size is 0 and each
* increment above or below represents zooming 20% larger or smaller to default
* limits of 300% and 50% of original size, respectively.
*
* > **NOTE**: The zoom policy at the Chromium level is same-origin, meaning that
* the zoom level for a specific domain propagates across all instances of windows
* with the same domain. Differentiating the window URLs will make zoom work
* per-window.
*/
setZoomLevel(level: number): void;
/**
* A `WebFrame | null` representing the first child frame of `webFrame`, the
* property would be `null` if `webFrame` has no children or if first child is not
* in the current renderer process.
*
*/
readonly firstChild: (WebFrame) | (null);
/**
* A `WebFrame | null` representing next sibling frame, the property would be
* `null` if `webFrame` is the last frame in its parent or if the next sibling is
* not in the current renderer process.
*
*/
readonly nextSibling: (WebFrame) | (null);
/**
* A `WebFrame | null` representing the frame which opened `webFrame`, the property
* would be `null` if there's no opener or opener is not in the current renderer
* process.
*
*/
readonly opener: (WebFrame) | (null);
/**
* A `WebFrame | null` representing parent frame of `webFrame`, the property would
* be `null` if `webFrame` is top or parent is not in the current renderer process.
*
*/
readonly parent: (WebFrame) | (null);
/**
* An `Integer` representing the unique frame id in the current renderer process.
* Distinct WebFrame instances that refer to the same underlying frame will have
* the same `routingId`.
*
*/
readonly routingId: number;
/**
* A `WebFrame | null` representing top frame in frame hierarchy to which
* `webFrame` belongs, the property would be `null` if top frame is not in the
* current renderer process.
*
*/
readonly top: (WebFrame) | (null);
}
declare var electron: {
clipboard: Clipboard
contextBridge: ContextBridge
crashReporter: CrashReporter
ipcRenderer: IpcRenderer
nativeImage: NativeImage
shell: Shell
webFrame: WebFrame
}

1069
src/plugins/monaco/types/lib.es5.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff

8420
src/plugins/monaco/types/node.api.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,274 @@
interface quickcommandApi {
/**
* 显示一个按钮组对话框,并返回用户点击的按钮的索引及名称
*
* ```js
* quickcommand.showButtonBox(["按钮1", "按钮2", "按钮3"]).then(({ id, text }) => {
* console.log(`选择了第${id+1}个按钮`)
* console.log(`按钮的文本为${text}`)
* })
* ```
*
* @param buttons 每一个按钮的名称
* @param title 窗口标题,默认为空
*/
showButtonBox(buttons: array, title?: string): Promise<{ id: number, text: string }>;
/**
* 显示一个输入框组对话框,并返回用户输入的所有值
*
* ```js
* quickcommand.showInputBox(["输入框1", "输入框2", "输入框3"]).then(values => {
* console.log(`输入的内容分别为${values}`)
* })
* ```
*
* @param labels 每一个输入框的标签名
* @param title 窗口标题,默认为空
*/
showInputBox(labels: array, title?: string): Promise<array>;
/**
* 显示一个支持搜索的且可以动态更新的选项列表,并返回用户点击选项的索引及名称
*
* ```js
* // plaintext
* var opt = []
* for (var i = 0; i < 15; i++) {
* // 每一个选项为文本格式
* opt.push(`选项` + i)
* }
* quickcommand.showSelectList(opt).then(choise => {
* console.log(`选择的选项为${choise.text}`)
* })
*
* // json
* var opt = []
* for (var i = 0; i < 15; i++) {
* // 每一个选项为 json 格式
* opt.push({title: `选项${i}`, description: `选项${i}的描述`, abcd: `选项${i}的自定义属性`})
* }
* quickcommand.showSelectList(opt, {optionType: 'json'}).then(choise => {
* console.log(`选择的选项为${choise.title}`)
* })
*
* // html
* var opt = []
* for (var i = 0; i < 15; i++) {
* // 每一个选项为 html 格式
* opt.push(`<div style="color: red">选项${i}</div>`)
* }
* quickcommand.showSelectList(opt, {optionType: 'html'}).then(choise => {
* console.log(`选择的选项为${quickcommand.htmlParse(choise.text).body.innerText}`)
* })
* ```
*
* @param selects 每一个列表选项
* @param options 列表的选项。placeholder: 搜索框占位符,optionType: 选项的格式默认为plaintext
*/
showSelectList(selects: array, options?: { placeholder: string, optionType: 'plaintext' | 'html' | 'json' }): Promise<{ id: number, text: string }>;
/**
* 动态更新当前的选项列表的选项
*
* ```js
* // 初始状态只有 1、2、3 三个选项
* quickcommand.showSelectList(['1','2','3']).then(x=>{
* console.log(x)
* })
*
* // 1s 后追加一个选项
* quickcommand.setTimeout(()=>{
* quickcommand.updateSelectList('4')
* }, 1000)
*
* // 2s 后更新第二个选项的值
* quickcommand.setTimeout(()=>{
* quickcommand.updateSelectList('updated', 1)
* }, 2000)
* ```
*
* @param opt 要更新的选项
* @param id 要更新的选项的序号,不赋值时则追加到最后一个选项后面
*/
updateSelectList(opt: string, id?: number): void;
/**
* 显示一个文本框,并返回用户输入的值
*
* ```js
* quickcommand.showTextAera("请输入文本").then(text=>{
* console.log(`输入的文本为${text}`)
* })
* ```
*
* @param placeholder 文本框占位符
* @param value 默认的文本值
*/
showTextAera(placeholder?: string, value?: string): Promise<string>;
/**
* 显示一个自动消失的提示框
*
* ```js
* quickcommand.showMessageBox("这是一段3s后自动消失的成功提示")
* ```
* @param message 显示的消息内容
* @param icon 图标,默认为 success
* @param time 多少毫秒后消失,默认为 3000
*/
showMessageBox(message: string, icon?: 'success' | 'error' | 'warning' | 'info' | 'question', time?: number): void;
/**
* 显示一个确认框,返回是否点击了确认
*
* ```js
* quickcommand.showConfirmBox().then(confirmed => {
* confirmed && console.log('点击了确定')
* })
* ```
* @param title 提示的标题
*/
showConfirmBox(title?: string): Promise<boolean>;
/**
* 同步等待,会阻塞进程
* @param ms 等待的毫秒数
*/
sleep(ms: number): void;
/**
* 异步等待
*
* ```js
* quickcommand.setTimeout(()=>{
* console.log('2000毫秒后执行')
* }, 2000)
* ```
*
* @param ms 等待的毫秒数
*/
setTimeout(callback: () => void, ms)
/**
* 将给定的html字符串解析为 DOM 对象,用于快速编写爬虫脚本
*
* ```js
* var html = `<a href="https://u.tools/">uTools</a>`
* var href = quickcommand.htmlParse(html).querySelector('a').href
* console.log(`解析出来的a标签地址为${href}`)
* ```
*
* @param html 需要解析的 html 文本
*/
htmlParse(html: string): object
/**
* 下载文件,并返回文件的 Buffer可选直接下载到指定路径或者弹出对话框选择下载路径
*
* ```js
* // 下载文件到D:/
* quickcommand.downloadFile('https://res.u-tools.cn/currentversion/uTools-1.1.3.exe', 'D:/')
*
* // 下载文件,并弹出对话框询问保存路径
* quickcommand.downloadFile('https://res.u-tools.cn/currentversion/uTools-1.1.3.exe')
* ```
*
* @param url 地址
* @param file 当赋值为文件路径时,则表示下载文件的绝对路径;
* 不赋值时,则会弹出对话框要求选择下载到的路径;
* 赋值为 Object时表示弹出对话框的 options格式和 utools.showSaveDialog 中的 options一致
*/
downloadFile(url, file?: string | object): Promise<Buffer>
/**
* 上传文件,可以直接上传指定文件,或者弹出对话框选择要上传的文件,可以自定义表单数据
*
* ```js
* // 上传图片到图床
* quickcommand.uploadFile("https://imgkr.com/api/v2/files/upload", "C:\\test.jpg").then(res=>{
* console.log('上传成功,图片地址为:' + res.data.data)
* })
*
* // 包含额外表单数据
* quickcommand.uploadFile("https://catbox.moe/user/api.php", "C:\\test.jpg", 'fileToUpload', {
* "reqtype": "fileupload"
* }).then(res=>{
* console.log('上传成功,图片地址为:' + res.data)
* })
* ```
*
* @param url 地址
* @param file 当赋值为文件路径时,则表示要上传的文件的绝对路径;
* 不赋值时,则会弹出对话框要求选择要上传的文件的路径;
* 赋值为 Object时表示弹出对话框的 options格式和 utools.showOpenDialog 中的 options一致
*
* @param name 文件名,默认为 file
* @param formData 其他需要提交的表单数据
*/
uploadFile(url: string, file?: string | object, name?: string, formData?: object): Promise<object>
/**
* 加载一个远程脚本文件,并返回脚本 export 的对象
*
* ```js
* let remote = 'https://cdn.jsdelivr.net/npm/sweetalert2@9'
* quickcommand.loadRemoteScript(remote).then(swal => {
* swal.fire('已加载 sweetalert2 并成功弹窗')
* })
* ```
*
* @param url 脚本地址
*/
loadRemoteScript(url: string): Promise<object>
/**
* 将 signal 发送给 pid 标识的进程 , 默认为关闭进程同process.kill
* @param pid 进程 ID
* @param signal 进程信号默认为SIGTERM
*/
kill(pid: number, signal?: number | string): void
/**
* windows 下运行 VBS 脚本并返回运行结果
*
* ```js
* quickcommand.runVbs(`CreateObject("SAPI.SpVoice").Speak"Hello"`)
* ```
*
* @param script VBS 代码
*/
runVbs(script: string): Promise<string>
/**
* 对应 utools.onPluginEnter 的 code type 和 payload
*
* code: 唯一标识
*
* type: 匹配模式,可以为 text | img | files | regex | over | window
*
* payload: 当匹配模式为关键字时,返回进入插件的关键字;为正则时,返回匹配的文本;为窗口时,返回匹配的窗口信息;为文件时,返回匹配的文件信息
*
* ```js
* if (quickcommand.enterData.type == 'regex'){
* var text = quickcommand.enterData.payload
* console.log(`主输入框匹配的文本为${text}`)
* }
* ```
*
*/
enterData: { code: string, type: string, payload: any }
/**
* 模拟复制操作
*/
simulateCopy()
/**
* 模拟粘贴操作
*/
simulatePaste()
}
declare var quickcommand: quickcommandApi;

649
src/plugins/monaco/types/utools.api.d.ts vendored Normal file
View File

@@ -0,0 +1,649 @@
interface UBrowser {
/**
* 设置 User-Agent
*/
useragent(userAgent: string): this;
/**
* 前往
* @param url 链接地址,支持 http 或 file 协议
* @param headers 请求头参数
* @param timeout 加载超时,默认 60000 ms(60秒)
*/
goto(url: string, headers?: { Referer: string, userAgent: string }, timeout?: number): this;
/**
* 页面大小
*/
viewport(width: number, height: number): this;
/**
* 隐藏 ubrowser 窗口
*/
hide(): this;
/**
* 显示 ubrowser 窗口
*/
show(): this;
/**
* 注入样式
*/
css(css: string): this;
/**
* 键盘按键
*/
press(key: string, ...modifier: ('control' | 'ctrl' | 'shift' | 'meta' | 'alt' | 'command' | 'cmd')[]): this;
/**
* 粘贴
* @param text 如果是图片的base64编码字符串粘贴图片为空只执行粘贴动作
*/
paste(text?: string): this;
/**
* 页面截图
* @param arg 1.字符串 - 要截取的DOM元素 2.对象 - 截图位置和大小, 3.空 - 为截取整个窗口
* @param savePath 截图保存路径,可以是文件夹 或 .png文件完全路径, 默认保存临时目录
*/
screenshot(arg: string | { x: number, y: number, width: number, height: number }, savePath?: string): this;
/**
* 保存为PDF
* @param options 选项
* @param savePath PDF保存路径可以是文件夹 或 .pdf文件完全路径, 默认保存临时目录
*/
pdf(options?: { marginsType: 0 | 1 | 2, pageSize: ('A3' | 'A4' | 'A5' | 'Legal' | 'Letter' | 'Tabloid') | ({ width: number, height: number }) }, savePath?: string): this;
/**
* 模拟设备
*/
device(arg: ('iPhone 11' | 'iPhone X' | 'iPad' | 'iPhone 6/7/8 Plus' | 'iPhone 6/7/8' | 'iPhone 5/SE' | 'HUAWEI Mate10' | 'HUAWEI Mate20' | 'HUAWEI Mate30' | 'HUAWEI Mate30 Pro') | { size: { width: number, height: number }, useragent: string }): this;
/**
* 获取 cookie
* @param name 为空获取全部cookie
*/
cookies(name?: string): this;
/**
* 设置Cookie
*/
setCookies(name: string, value: string): this;
/**
* 设置Cookie
*/
setCookies(cookies: { name: string, value: string }[]): this;
/**
* 删除 cookie
*/
removeCookies(name: string): this;
/**
* 清空cookie
* @param url 在执行"goto"前执行 url参数必需
*/
clearCookies(url?: string): this;
/**
* 打开开发者工具
*/
devTools(mode?: 'right' | 'bottom' | 'undocked' | 'detach'): this;
/**
* 执行JS计算 并获得结果
* @param func 在目标网页中执行
* @param params 传到 func 中的参数
*/
evaluate(func: (...params: any[]) => any, ...params: any[]): this;
/**
* 等待时间
* @param ms 毫秒
*/
wait(ms: number): this;
/**
* 等待元素出现
* @param selector DOM元素
* @param timeout 超时 默认60000 ms(60秒)
*/
wait(selector: string, timeout?: number): this;
/**
* 等待 JS函数 执行返回 true
* @param func 执行的JS函数
* @param timeout 超时 默认60000 ms(60秒)
* @param params 传到 func 中的参数
*/
wait(func: (...params: any[]) => boolean, timeout?: number, ...params: any[]): this;
/**
* 当元素存在时执行直到碰到 end
* @param selector DOM元素
*/
when(selector: string): this;
/**
* 当 JS函数执行返回 true 时执行直到碰到 end
* @param func 执行的JS函数
* @param params 传到 func 中的参数
*/
when(func: (...params: any[]) => boolean, ...params: any[]): this;
/**
* 配合 when 使用
*/
end(): this;
/**
* 单击元素
*/
click(selector: string): this;
/**
* 元素触发按下鼠标左键
*/
mousedown(selector: string): this;
/**
* 元素触发释放鼠标左键
*/
mouseup(selector: string): this;
/**
* 赋值 file input
* @param selector <input type='file' /> 元素
* @param payload 1. string - 文件路径 或 图片的base64编码2. string[] - 文件路径集合3. Uint8Array[]
*/
file(selector: string, payload: string | string[] | Uint8Array): this;
/**
* input textarea select 等元素赋值并触发 input 或 change事件
*/
value(selector: string, value: string): this;
/**
* checkbox radio 元素选中或取消选中
*/
check(selector: string, checked: boolean): this;
/**
* 元素获得焦点
*/
focus(selector: string): this;
/**
* 滚动到元素位置
*/
scroll(selector: string): this;
/**
* Y轴滚动
*/
scroll(y: number): this;
/**
* X轴和Y轴滚动
*/
scroll(x: number, y: number): this;
/**
* 运行在闲置的 ubrowser 上
* @param ubrowserId utools.getIdleUBrowsers() 中获得
*/
run(ubrowserId: number): Promise<any[]>;
/**
* 启动一个 ubrowser 运行
* 当运行结束后,窗口如果为隐藏状态将自动销毁窗口
* @param options
*/
run(options: {
show?: boolean,
width?: number,
height?: number,
x?: number,
y?: number,
center?: boolean,
minWidth?: number,
minHeight?: number,
maxWidth?: number,
maxHeight?: number,
resizable?: boolean,
movable?: boolean,
minimizable?: boolean,
maximizable?: boolean,
alwaysOnTop?: boolean,
fullscreen?: boolean,
fullscreenable?: boolean,
enableLargerThanScreen?: boolean,
opacity?: number
}): Promise<any[]>;
}
interface Display {
accelerometerSupport: ('available' | 'unavailable' | 'unknown');
bounds: { x: number, y: number, width: number, height: number };
colorDepth: number;
colorSpace: string;
depthPerComponent: number;
id: number;
internal: boolean;
monochrome: boolean;
rotation: number;
scaleFactor: number;
size: { width: number, height: number };
touchSupport: ('available' | 'unavailable' | 'unknown');
workArea: { x: number, y: number, width: number, height: number };
workAreaSize: { width: number, height: number };
}
interface DbDoc {
_id: string,
_rev?: string,
[key: string]: any
}
interface DbReturn {
id: string,
rev?: string,
ok?: boolean,
error?: boolean,
name?: string,
message?: string
}
interface UToolsApi {
/**
* 插件进入时触发
*/
onPluginEnter(callback: (action: {code: string, type: string, payload: any }) => void): void;
/**
* 插件隐藏时触发
*/
onPluginOut(callback: () => void): void;
/**
* 插件分离时触发
*/
onPluginDetach(callback: () => void): void;
/**
* 插件从云端拉取到数据时触发
*/
onDbPull(callback: (docs: { _id: string, _rev: string }[]) => void): void;
/**
* 隐藏主窗口
* @param isRestorePreWindow 是否焦点回归到前面的活动窗口,默认 true
*/
hideMainWindow(isRestorePreWindow?: boolean): boolean;
/**
* 显示主窗口
*/
showMainWindow(): boolean;
/**
* 设置插件自身高度
*/
setExpendHeight(height: number): boolean;
/**
* 设置子输入框
* @param onChange 修改时触发
* @param placeholder 占位符, 默认为空
* @param isFocus 是否获得焦点,默认为 true
*/
setSubInput(onChange: (text: string) => void, placeholder?: string, isFocus?: boolean): boolean;
/**
* 移除子输入框
*/
removeSubInput(): boolean;
/**
* 赋值子输入框
*/
setSubInputValue(value: string): boolean;
/**
* 子输入框获得焦点
*/
subInputFocus(): boolean;
/**
* 子输入框获得焦点并选中
*/
subInputSelect(): boolean;
/**
* 子输入框失去焦点,插件获得焦点
*/
subInputBlur(): boolean;
/**
* 创建独立窗口
* @param url 相对路径 html 文件
* @param options 参考 https://www.electronjs.org/docs/api/browser-window#new-browserwindowoptions
* @param callback url 加载完成时的回调
*/
createBrowserWindow(url: string, options: { width?: number, height?: number }, callback?: () => void): { id: number, [key: string]: any, webContents: { id: number, [key: string]: any } };
/**
* 隐藏插件到后台
*/
outPlugin(): boolean;
/**
* 是否深色模式
*/
isDarkColors(): boolean;
/**
* 获取用户
*/
getUser(): { avatar: string, nickname: string, type: string } | null;
/**
* 获取用户服务端临时令牌
*/
fetchUserServerTemporaryToken(): Promise<{ token: string, expiredAt: number }>;
/**
* 打开支付
* @param callback 支付成功触发
*/
openPayment(options: {
/**
* 商品ID在 “uTools 开发者工具” 插件中创建
*/
goodsId: string,
/**
* 第三方服务生成的订单号(可选)
*/
outOrderId?: string,
/**
* 第三方服务附加数据在查询API和支付通知中原样返回可作为自定义参数使用(可选)
*/
attach?: string
}, callback?: () => void): void;
/**
* 获取用户支付记录
*/
fetchUserPayments(): Promise<{ order_id: string, total_fee: number, body: string, attach: string, goods_id: string, out_order_id: string, paid_at: string }[]>;
/**
* 设置插件动态功能
*/
setFeature(feature: {
code: string,
explain: string,
platform: ('darwin' | 'win32' | 'linux') | (Array<'darwin' | 'win32' | 'linux'>),
icon?: string,
cmds: string | {
type: 'img' | 'files' | 'regex' | 'over' | 'window',
label: string
}[]
}): boolean;
/**
* 移除插件动态功能
*/
removeFeature(code: string): boolean;
/**
* 获取插件所有动态功能
*/
getFeatures(): {
code: string,
explain: string,
platform: ('darwin' | 'win32' | 'linux') | (Array<'darwin' | 'win32' | 'linux'>),
icon?: string,
cmds: string | {
type: 'img' | 'files' | 'regex' | 'over' | 'window',
label: string
}[]
}[];
/**
* 插件间跳转
*/
redirect(label: string, payload: string | { type: 'text' | 'img' | 'files', data: any }): void;
/**
* 获取闲置的 ubrowser
*/
getIdleUBrowsers(): { id: number, title: string, url: string}[];
/**
* 设置 ubrowser 代理 https://www.electronjs.org/docs/api/session#sessetproxyconfig
*/
setUBrowserProxy(config: {pacScript?: string, proxyRules?: string, proxyBypassRules?: string}): boolean;
/**
* 清空 ubrowser 缓存
*/
clearUBrowserCache(): boolean;
/**
* 显示系统通知
*/
showNotification(body: string): void;
/**
* 弹出文件选择框
*/
showOpenDialog(options: {
title?: string,
defaultPath?: string,
buttonLabel?: string,
filters?: { name: string, extensions: string[] }[],
properties?: Array<'openFile' | 'openDirectory' | 'multiSelections' | 'showHiddenFiles' | 'createDirectory' | 'promptToCreate' | 'noResolveAliases' | 'treatPackageAsDirectory' | 'dontAddToRecent'>,
message?: string,
securityScopedBookmarks?: boolean
}): (string[]) | (undefined);
/**
* 弹出文件保存框
*/
showSaveDialog(options: {
title?: string,
defaultPath?: string,
buttonLabel?: string,
filters?: { name: string, extensions: string[] }[],
message?: string,
nameFieldLabel?: string,
showsTagField?: string,
properties?: Array<'showHiddenFiles' | 'createDirectory' | 'treatPackageAsDirectory' | 'showOverwriteConfirmation' | 'dontAddToRecent'>,
securityScopedBookmarks?: boolean
}): (string) | (undefined);
/**
* 插件页面中查找
*/
findInPage(text: string, options?: {
forward?: boolean,
findNext?: boolean,
matchCase?: boolean,
wordStart?: boolean,
medialCapitalAsWordStart?: boolean
}): void;
/**
* 停止插件页面中查找
*/
stopFindInPage (action: 'clearSelection' | 'keepSelection' | 'activateSelection'): void;
/**
* 拖拽文件
*/
startDrag(file: string | string[]): void;
/**
* 屏幕取色
*/
screenColorPick(callback: (color: { hex: string, rgb: string }) => void): void;
/**
* 屏幕截图
*/
screenCapture(callback: (imgBase64: string) => void): void;
/**
* 获取本地 ID
*/
getNativeId(): string;
/**
* 获取软件版本
*/
getAppVersion(): string;
/**
* 获取路径
*/
getPath(name: 'home' | 'appData' | 'userData' | 'cache' | 'temp' | 'exe' | 'module' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'logs' | 'pepperFlashSystemPlugin'): string;
/**
* 获取文件图标
*/
getFileIcon(filePath: string): string;
/**
* 复制文件到剪贴板
*/
copyFile(file: string | string[]): boolean;
/**
* 复制图片到剪贴板
* @param img base64、buffer、图片路径
*/
copyImage(img: string | Uint8Array): boolean;
/**
* 复制文本到剪贴板
*/
copyText(text: string): boolean;
/**
* 获取复制的文件或文件夹
*/
getCopyedFiles(): { isFile: boolean, isDirectory: boolean, name: string, path: string }[];
/**
* 读取当前文件管理器路径(linux 不支持)
*/
readCurrentFolderPath(): Promise<string>;
/**
* 读取当前浏览器窗口的URL(linux 不支持)
* MacOs 支持浏览器 Safari、Chrome、Opera、Vivaldi、Brave
* Windows 支持浏览器 Chrome、Firefox、Edge、IE、Opera、Brave
* Linux 不支持
*/
readCurrentBrowserUrl(): Promise<string>;
/**
* 默认方式打开给定的文件
*/
shellOpenPath(fullPath: string): void;
/**
* 在文件管理器中显示给定的文件
*/
shellShowItemInFolder(fullPath: string): void;
/**
* 系统默认的协议打开URL
*/
shellOpenExternal(url: string): void;
/**
* 播放哔哔声
*/
shellBeep(): void;
/**
* 模拟键盘按键
*/
simulateKeyboardTap(key: string, ...modifier: ('control' | 'ctrl' | 'shift' | 'option' | 'alt' | 'command' | 'super')[]): void;
/**
* 模拟鼠标单击
*/
simulateMouseClick(x?: number, y?: number): void;
/**
* 模拟鼠标右击
*/
simulateMouseRightClick(x?: number, y?: number): void;
/**
* 模拟鼠标双击
*/
simulateMouseDoubleClick(x?: number, y?: number): void;
/**
* 模拟鼠标移动
*/
simulateMouseMove(x: number, y: number): void;
/**
* 获取鼠标绝对位置
*/
getCursorScreenPoint(): { x: number, y: number };
/**
* 获取主显示器
*/
getPrimaryDisplay(): Display;
/**
* 获取所有显示器
*/
getAllDisplays(): Display[];
/**
* 获取位置所在的显示器
*/
getDisplayNearestPoint(point: { x: number, y: number }): Display;
/**
* 获取矩形所在的显示器
*/
getDisplayMatching(rect: { x: number, y: number, width: number, height: number }): Display;
/**
* 是否开发中
*/
isDev(): boolean;
/**
* 是否 MacOs 操作系统
*/
isMacOs(): boolean;
/**
* 是否 Windows 操作系统
*/
isWindows(): boolean;
/**
* 是否 Linux 操作系统
*/
isLinux(): boolean;
db: {
/**
* 创建/更新文档
*/
put(doc: DbDoc): DbReturn;
/**
* 获取文档
*/
get(id: string): DbDoc | null;
/**
* 删除文档
*/
remove(doc: string | DbDoc): DbReturn;
/**
* 批量操作文档(新增、修改、删除)
*/
bulkDocs(docs: DbDoc[]): DbReturn[];
/**
* 获取所有文档 可根据文档id前缀查找
*/
allDocs(key?: string): DbDoc[];
/**
* 存储附件到新文档
* @param docId 文档ID
* @param attachment 附件 buffer
* @param type 附件类型示例image/png, text/plain
*/
postAttachment(docId: string, attachment: Uint8Array, type: string): DbReturn;
/**
* 获取附件
* @param docId 文档ID
*/
getAttachment(docId: string): Uint8Array | null;
/**
* 获取附件类型
* @param docId 文档ID
*/
getAttachmentType(docId: string): string | null;
/**
* 异步
*/
promises: {
/**
* 创建/更新文档
*/
put(doc: DbDoc): Promise<DbReturn>;
/**
* 获取文档
*/
get(id: string): Promise<DbDoc | null>;
/**
* 删除文档
*/
remove(doc: string | DbDoc): Promise<DbReturn>;
/**
* 批量操作文档(新增、修改、删除)
*/
bulkDocs(docs: DbDoc[]): Promise<DbReturn[]>;
/**
* 获取所有文档 可根据文档id前缀查找
*/
allDocs(key?: string): Promise<DbDoc[]>;
/**
* 存储附件到新文档
* @param docId 文档ID
* @param attachment 附件 buffer
* @param type 附件类型示例image/png, text/plain
*/
postAttachment(docId: string, attachment: Uint8Array, type: string): Promise<DbReturn>;
/**
* 获取附件
* @param docId 文档ID
*/
getAttachment(docId: string): Promise<Uint8Array | null>;
/**
* 获取附件类型
* @param docId 文档ID
*/
getAttachmentType(docId: string): Promise<string | null>;
}
};
dbStorage: {
/**
* 键值对存储,如果键名存在,则更新其对应的值
* @param key 键名(同时为文档ID)
* @param value 键值
*/
setItem (key: string, value: any): void;
/**
* 获取键名对应的值
*/
getItem (key: string): any;
/**
* 删除键值对(删除文档)
*/
removeItem (key: string): void;
};
ubrowser: UBrowser;
}
declare var utools: UToolsApi;