This commit is contained in:
zuowei1216
2025-12-22 21:06:29 +08:00
parent 8ea58fe480
commit 1b19ff1b92
179 changed files with 21895 additions and 3774 deletions

View File

@@ -0,0 +1 @@
## 提供工具

View File

@@ -0,0 +1 @@
*.js linguist-detectable=false

View File

@@ -0,0 +1,99 @@
export declare interface cep_node {
global: any;
process: any;
buffer: any;
require: any;
}
export declare interface cep {
encoding: {
Base64: "Base64" | string;
UTF8: "UTF-8" | string;
convertion: {
utf8_to_b64: (...params: any) => {};
b64_to_utf8: (...params: any) => {};
binary_to_b64: (...params: any) => {};
b64_to_binary: (...params: any) => {};
ascii_to_b64: (...params: any) => {};
};
};
fs: {
ERR_CANT_READ: number;
ERR_CANT_WRITE: number;
ERR_FILE_EXISTS: number;
ERR_INVALID_PARAMS: number;
ERR_NOT_DIRECTORY: number;
ERR_NOT_FILE: number;
ERR_NOT_FOUND: number;
ERR_OUT_OF_SPACE: number;
ERR_UNKNOWN: number;
ERR_UNSUPPORTED_ENCODING: number;
NO_ERROR: number;
chmod: (...params: any) => {};
deleteFile: (...params: any) => {};
makedir: (...params: any) => {};
readFile: (...params: any) => {};
readdir: (...params: any) => {};
rename: (...params: any) => {};
showOpenDialog: (...params: any) => {};
showOpenDialogEx: (...params: any) => {};
showSaveDialogEx: (...params: any) => {};
stat: (...params: any) => {};
writeFile: (...params: any) => {};
};
process: {
ERR_EXCEED_MAX_NUM_PROCESS: number;
createProcess: (...params: any) => {};
getWorkingDirectory: (...params: any) => {};
isRunning: (...params: any) => {};
onquit: (...params: any) => {};
stderr: (...params: any) => {};
stdin: (...params: any) => {};
stdout: (...params: any) => {};
terminate: (...params: any) => {};
waitfor: (...params: any) => {};
};
util: {
DEPRECATED_API: number;
ERR_INVALID_URL: number;
openURLInDefaultBrowser: (...params: any) => {};
registerExtensionUnloadCallback: (...params: any) => {};
storeProxyCredentials: (...params: any) => {};
};
}
export interface __adobe_cep__ {
addEventListener: (...params: any) => {};
analyticsLogging: (...params: any) => {};
autoThemeColorChange: (...params: any) => {};
closeExtension: (...params: any) => {};
dispatchEvent: (...params: any) => {};
dumpInstallationInfo: (...params: any) => {};
evalScript: (...params: any) => {};
getCurrentApiVersion: (...params: any) => {};
getCurrentImsUserId: (...params: any) => {};
getExtensionId: (...params: any) => {};
getExtensions: (...params: any) => {};
getHostCapabilities: (...params: any) => {};
getHostEnvironment: (...params: any) => {};
getMonitorScaleFactor: (...params: any) => {};
getNetworkPreferences: (...params: any) => {};
getScaleFactor: (...params: any) => {};
getSystemPath: (...params: any) => {};
imsConnect: (...params: any) => {};
imsDisconnect: (...params: any) => {};
imsFetchAccessToken: (...params: any) => {};
imsFetchAccounts: (...params: any) => {};
imsSetProxyCredentials: (...params: any) => {};
initResourceBundle: (...params: any) => {};
invokeAsync: (...params: any) => {};
invokeSync: (...params: any) => {};
nglImsFetchAccessToken: (...params: any) => {};
nglImsFetchProfile: (...params: any) => {};
registerInvalidCertificateCallback: (...params: any) => {};
registerKeyEventsInterest: (...params: any) => {};
removeEventListener: (...params: any) => {};
requestOpenExtension: (...params: any) => {};
resizeContent: (...params: any) => {};
setScaleFactorChangedHandler: (...params: any) => {};
showAAM: (...params: any) => {};
}

View File

@@ -0,0 +1,36 @@
import CSInterface, { SystemPath } from "./csinterface"
export class CEPPath {
constructor() {
}
static getUserData(): string {
const cs = new CSInterface()
return cs.getSystemPath(SystemPath.USER_DATA)
}
static getCommonFiles() {
const cs = new CSInterface()
return cs.getSystemPath(SystemPath.COMMON_FILES)
}
static getMyDocuments(): string {
const cs = new CSInterface()
return cs.getSystemPath(SystemPath.MY_DOCUMENTS)
}
static getApplication(): string {
const cs = new CSInterface()
return cs.getSystemPath(SystemPath.APPLICATION)
}
static getExtension(): string {
const cs = new CSInterface()
return cs.getSystemPath(SystemPath.EXTENSION)
}
static getHostApplication(): string {
const cs = new CSInterface()
return cs.getSystemPath(SystemPath.HOST_APPLICATION)
}
}

View File

@@ -0,0 +1,701 @@
// FOR REFERENCE ONLY -- THIS FILE IS NOT BUNDLED
/**************************************************************************************************
*
* ADOBE SYSTEMS INCORPORATED
* Copyright 2020 Adobe Systems Incorporated
* All Rights Reserved.
*
* NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the
* terms of the Adobe license agreement accompanying it. If you have received this file from a
* source other than Adobe, then your use, modification, or distribution of it requires the prior
* written permission of Adobe.
*
**************************************************************************************************/
// This is the JavaScript code for bridging to native functionality
// See CEPEngine_extensions.cpp for implementation of native methods.
//
// Note: So far all native file i/o functions are synchronous, and aynchronous file i/o is TBD.
/** Version v11.0.0 */
/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, forin: true, maxerr: 50, regexp: true */
/*global define, native */
var cep;
if (!cep) {
cep = {};
}
if (!cep.fs) {
cep.fs = {};
}
if (!cep.process) {
cep.process = {};
}
if (!cep.encoding) {
cep.encoding = {};
}
if (!cep.util) {
cep.util = {};
}
(function () {
// Internal function to get the last error code.
native function GetLastError();
function getLastError() {
return GetLastError();
}
function getErrorResult(){
var result = {err: getLastError()};
return result;
}
// Error values. These MUST be in sync with the error values
// at the top of CEPEngine_extensions.cpp
/**
* @constant No error.
*/
cep.fs.NO_ERROR = 0;
/**
* @constant Unknown error occurred.
*/
cep.fs.ERR_UNKNOWN = 1;
/**
* @constant Invalid parameters passed to function.
*/
cep.fs.ERR_INVALID_PARAMS = 2;
/**
* @constant File or directory was not found.
*/
cep.fs.ERR_NOT_FOUND = 3;
/**
* @constant File or directory could not be read.
*/
cep.fs.ERR_CANT_READ = 4;
/**
* @constant An unsupported encoding value was specified.
*/
cep.fs.ERR_UNSUPPORTED_ENCODING = 5;
/**
* @constant File could not be written.
*/
cep.fs.ERR_CANT_WRITE = 6;
/**
* @constant Target directory is out of space. File could not be written.
*/
cep.fs.ERR_OUT_OF_SPACE = 7;
/**
* @constant Specified path does not point to a file.
*/
cep.fs.ERR_NOT_FILE = 8;
/**
* @constant Specified path does not point to a directory.
*/
cep.fs.ERR_NOT_DIRECTORY = 9;
/**
* @constant Specified file already exists.
*/
cep.fs.ERR_FILE_EXISTS = 10;
/**
* @constant The maximum number of processes has been exceeded.
*/
cep.process.ERR_EXCEED_MAX_NUM_PROCESS = 101;
/**
* @constant Invalid URL.
*/
cep.util.ERR_INVALID_URL = 201;
/**
* @constant deprecated API.
*/
cep.util.DEPRECATED_API = 202;
/**
* @constant UTF8 encoding type.
*/
cep.encoding.UTF8 = "UTF-8";
/**
* @constant Base64 encoding type.
*/
cep.encoding.Base64 = "Base64";
/**
* Displays the OS File Open dialog, allowing the user to select files or directories.
*
* @param allowMultipleSelection {boolean} When true, multiple files/folders can be selected.
* @param chooseDirectory {boolean} When true, only folders can be selected. When false, only
* files can be selected.
* @param title {string} Title of the open dialog.
* @param initialPath {string} Initial path to display in the dialog. Pass NULL or "" to
* display the last path chosen.
* @param fileTypes {Array.<string>} The file extensions (without the dot) for the types
* of files that can be selected. Ignored when chooseDirectory=true.
*
* @return An object with these properties:
* <ul><li>"data": An array of the full names of the selected files.</li>
* <li>"err": The status of the operation, one of
* <br>NO_ERROR
* <br>ERR_INVALID_PARAMS </li>
* </ul>
**/
native function ShowOpenDialog();
cep.fs.showOpenDialog = function (allowMultipleSelection, chooseDirectory, title, initialPath, fileTypes) {
var resultString = ShowOpenDialog(allowMultipleSelection, chooseDirectory,
title || 'Open', initialPath || '',
fileTypes ? fileTypes.join(' ') : '');
var result = {data: JSON.parse(resultString || '[]'), err: getLastError() };
return result;
};
/**
* Displays the OS File Open dialog, allowing the user to select files or directories.
*
* @param allowMultipleSelection {boolean} When true, multiple files/folders can be selected.
* @param chooseDirectory {boolean} When true, only folders can be selected. When false, only
* files can be selected.
* @param title {string} Title of the open dialog.
* @param initialPath {string} Initial path to display in the dialog. Pass NULL or "" to
* display the last path chosen.
* @param fileTypes {Array.<string>} The file extensions (without the dot) for the types
* of files that can be selected. Ignored when chooseDirectory=true.
* @param friendlyFilePrefix {string} String to put in front of the extensions
* of files that can be selected. Ignored when chooseDirectory=true. (win only)
* For example:
* fileTypes = ["gif", "jpg", "jpeg", "png", "bmp", "webp", "svg"];
* friendlyFilePrefix = "Images (*.gif;*.jpg;*.jpeg;*.png;*.bmp;*.webp;*.svg)";
* @param prompt {string} String for OK button (mac only, default is "Open" on mac, "Open" or "Select Folder" on win).
*
* @return An object with these properties:
* <ul><li>"data": An array of the full names of the selected files.</li>
* <li>"err": The status of the operation, one of
* <br>NO_ERROR
* <br>ERR_INVALID_PARAMS </li>
* </ul>
**/
native function ShowOpenDialogEx();
cep.fs.showOpenDialogEx = function (allowMultipleSelection, chooseDirectory, title, initialPath, fileTypes,
friendlyFilePrefix, prompt) {
var resultString = ShowOpenDialogEx(allowMultipleSelection, chooseDirectory,
title || 'Open', initialPath || '',
fileTypes ? fileTypes.join(' ') : '', friendlyFilePrefix || '',
prompt || '');
var result = {data: JSON.parse(resultString || '[]'), err: getLastError() };
return result;
};
/**
* Displays the OS File Save dialog, allowing the user to type in a file name.
*
* @param title {string} Title of the save dialog.
* @param initialPath {string} Initial path to display in the dialog. Pass NULL or "" to
* display the last path chosen.
* @param fileTypes {Array.<string>} The file extensions (without the dot) for the types
* of files that can be selected.
* @param defaultName {string} String to start with for the file name.
* @param friendlyFilePrefix {string} String to put in front of the extensions of files that can be selected. (win only)
* For example:
* fileTypes = ["gif", "jpg", "jpeg", "png", "bmp", "webp", "svg"];
* friendlyFilePrefix = "Images (*.gif;*.jpg;*.jpeg;*.png;*.bmp;*.webp;*.svg)";
* @param prompt {string} String for Save button (mac only, default is "Save" on mac and win).
* @param nameFieldLabel {string} String displayed in front of the file name text field (mac only, "File name:" on win).
*
* @return An object with these properties:
* <ul><li>"data": The file path selected to save at or "" if canceled</li>
* <li>"err": The status of the operation, one of
* <br>NO_ERROR
* <br>ERR_INVALID_PARAMS </li>
* </ul>
**/
native function ShowSaveDialogEx();
cep.fs.showSaveDialogEx = function (title, initialPath, fileTypes, defaultName, friendlyFilePrefix, prompt, nameFieldLabel) {
var resultString = ShowSaveDialogEx(title || '', initialPath || '',
fileTypes ? fileTypes.join(' ') : '', defaultName || '',
friendlyFilePrefix || '', prompt || '', nameFieldLabel || '');
var result = {data: resultString || '', err: getLastError() };
return result;
};
/**
* Reads the contents of a folder.
*
* @param path {string} The path of the folder to read.
*
* @return An object with these properties:
* <ul><li>"data": An array of the names of the contained files (excluding '.' and '..'.</li>
* <li>"err": The status of the operation, one of:
* <br>NO_ERROR
* <br>ERR_UNKNOWN
* <br>ERR_INVALID_PARAMS
* <br>ERR_NOT_FOUND
* <br>ERR_CANT_READ </li></ul>
**/
native function ReadDir();
cep.fs.readdir = function (path) {
var resultString = ReadDir(path);
var result = {data: JSON.parse(resultString || '[]'), err: getLastError() };
return result;
};
/**
* Creates a new folder.
*
* @param path {string} The path of the folder to create.
*
* @return An object with this property:
* <ul><li>"err": The status of the operation, one of:
* <br>NO_ERROR
* <br>ERR_UNKNOWN
* <br>ERR_INVALID_PARAMS</li></ul>
**/
native function MakeDir();
cep.fs.makedir = function (path) {
MakeDir(path);
return getErrorResult();
};
/**
* Renames a file or folder.
*
* @param oldPath {string} The old name of the file or folder.
* @param newPath {string} The new name of the file or folder.
*
* @return An object with this property:
* <ul><li>"err": The status of the operation, one of:
* <br>NO_ERROR
* <br>ERR_UNKNOWN
* <br>ERR_INVALID_PARAMS
* <br>ERR_NOT_FOUND
* <br>ERR_FILE_EXISTS </li></ul>
**/
native function Rename();
cep.fs.rename = function(oldPath, newPath) {
Rename(oldPath, newPath);
return getErrorResult();
};
/**
* Reports whether an item is a file or folder.
*
* @param path {string} The path of the file or folder.
*
* @return An object with these properties:
* <ul><li>"data": An object with properties
* <br>isFile (boolean)
* <br>isDirectory (boolean)
* <br>mtime (modification DateTime) </li>
* <li>"err": The status of the operation, one of
* <br>NO_ERROR
* <br>ERR_UNKNOWN
* <br>ERR_INVALID_PARAMS
* <br>ERR_NOT_FOUND </li>
* </ul>
**/
native function IsDirectory();
native function GetFileModificationTime();
cep.fs.stat = function (path) {
var isDir = IsDirectory(path);
var modtime = GetFileModificationTime(path);
var result = {
data: {
isFile: function () {
return !isDir;
},
isDirectory: function () {
return isDir;
},
mtime: modtime
},
err: getLastError()
};
return result;
};
/**
* Reads the entire contents of a file.
*
* @param path {string} The path of the file to read.
* @param encoding {string} The encoding of the contents of file, one of
* UTF8 (the default) or Base64.
*
* @return An object with these properties:
* <ul><li>"data": The file contents. </li>
* <li>"err": The status of the operation, one of
* <br>NO_ERROR
* <br>ERR_UNKNOWN
* <br>ERR_INVALID_PARAMS
* <br>ERR_NOT_FOUND
* <br>ERR_CANT_READ
* <br>ERR_UNSUPPORTED_ENCODING </li>
* </ul>
**/
native function ReadFile();
cep.fs.readFile = function (path, encoding) {
encoding = encoding ? encoding : cep.encoding.UTF8;
var contents = ReadFile(path, encoding);
var result = {data: contents, err: getLastError() };
return result;
};
/**
* Writes data to a file, replacing the file if it already exists.
*
* @param path {string} The path of the file to write.
* @param data {string} The data to write to the file.
* @param encoding {string} The encoding of the contents of file, one of
* UTF8 (the default) or Base64.
*
* @return An object with this property:
* <ul><li>"err": The status of the operation, one of:
* <br>NO_ERROR
* <br>ERR_UNKNOWN
* <br>ERR_INVALID_PARAMS
* <br>ERR_UNSUPPORTED_ENCODING
* <br>ERR_CANT_WRITE
* <br>ERR_OUT_OF_SPACE </li></ul>
**/
native function WriteFile();
cep.fs.writeFile = function (path, data, encoding) {
encoding = encoding ? encoding : cep.encoding.UTF8;
WriteFile(path, data, encoding);
return getErrorResult();
};
/**
* Sets permissions for a file or folder.
*
* @param path {string} The path of the file or folder.
* @param mode {number} The permissions in numeric format (for example, 0777).
*
* @return An object with this property:
* <ul><li>"err": The status of the operation, one of:
* <br>NO_ERROR
* <br>ERR_UNKNOWN
* <br>ERR_INVALID_PARAMS
* <br>ERR_CANT_WRITE </li></ul>
**/
native function SetPosixPermissions();
cep.fs.chmod = function (path, mode) {
SetPosixPermissions(path, mode);
return getErrorResult();
};
/**
* Deletes a file.
*
* @param path {string} The path of the file to delete.
*
* @return An object with this property:
* <ul><li>"err": The status of the operation, one of:
* <br>NO_ERROR
* <br>ERR_UNKNOWN
* <br>ERR_INVALID_PARAMS
* <br>ERR_NOT_FOUND
* <br>ERR_NOT_FILE </li></ul>
**/
native function DeleteFileOrDirectory();
native function IsDirectory();
cep.fs.deleteFile = function (path) {
if (IsDirectory(path)) {
var result = {err: cep.fs.ERR_NOT_FILE};
return result;
}
DeleteFileOrDirectory(path);
return getErrorResult();
};
/**
* Creates a process.
*
* @param arguments {list} The arguments to create process. The first one is the full path of the executable,
* followed by the arguments of the executable.
*
* @return An object with these properties:
* <ul><li>"data": The pid of the process, or -1 on error. </li>
* <li>"err": The status of the operation, one of
* <br>NO_ERROR
* <br>ERR_UNKNOWN
* <br>ERR_INVALID_PARAMS
* <br>ERR_EXCEED_MAX_NUM_PROCESS
* <br>ERR_NOT_FOUND
* <br>ERR_NOT_FILE</li>
* </ul>
**/
native function CreateProcess();
cep.process.createProcess = function () {
var args = Array.prototype.slice.call(arguments);
var pid = CreateProcess(args);
var result = {data: pid, err: getLastError()};
return result;
};
/**
* Registers a standard-output handler for a process.
*
* @param pid {int} The pid of the process.
* @param callback {function} The handler function for the standard output callback.
*
* @return An object with this property:
* <ul><li>"err": The status of the operation, one of:
* <br>NO_ERROR
* <br>ERR_UNKNOWN
* <br>ERR_INVALID_PARAMS
* <br>ERR_INVALID_PROCESS_ID </li></ul>
**/
native function SetupStdOutHandler();
cep.process.stdout = function (pid, callback) {
SetupStdOutHandler(pid, callback);
return getErrorResult();
};
/**
* Registers up a standard-error handler for a process.
*
* @param pid {int} The pid of the process.
* @param callback {function} The handler function for the standard error callback.
*
* @return An object with this property:
* <ul><li>"err": The status of the operation, one of:
* <br>NO_ERROR
* <br>ERR_UNKNOWN
* <br>ERR_INVALID_PARAMS
* <br>ERR_INVALID_PROCESS_ID </li></ul>
**/
native function SetupStdErrHandler();
cep.process.stderr = function (pid, callback) {
SetupStdErrHandler(pid, callback);
return getErrorResult();
};
/**
* Writes data to the standard input of a process.
*
* @param pid {int} The pid of the process
* @param data {string} The data to write.
*
* @return An object with this property:
* <ul><li>"err": The status of the operation, one of:
* <br>NO_ERROR
* <br>ERR_UNKNOWN
* <br>ERR_INVALID_PARAMS
* <br>ERR_INVALID_PROCESS_ID </li></ul>
**/
native function WriteStdIn();
cep.process.stdin = function (pid, data) {
WriteStdIn(pid, data);
return getErrorResult();
};
/**
* Retrieves the working directory of a process.
*
* @param pid {int} The pid of the process.
*
* @return An object with these properties:
* <ul><li>"data": The path of the working directory. </li>
* <li>"err": The status of the operation, one of
* <br>NO_ERROR
* <br>ERR_UNKNOWN
* <br>ERR_INVALID_PARAMS
* <br>ERR_INVALID_PROCESS_ID </li></ul>
**/
native function GetWorkingDirectory();
cep.process.getWorkingDirectory = function (pid) {
var wd = GetWorkingDirectory(pid);
var result = {data: wd, err: getLastError()};
return result;
};
/**
* Waits for a process to quit.
*
* @param pid {int} The pid of the process.
*
* @return An object with this property:
* <ul><li>"err": The status of the operation, one of:
* <br>NO_ERROR
* <br>ERR_UNKNOWN
* <br>ERR_INVALID_PARAMS
* <br>ERR_INVALID_PROCESS_ID </li></ul>
**/
native function WaitFor();
cep.process.waitfor = function (pid) {
WaitFor(pid);
return getErrorResult();
};
/**
* Registers a handler for the onquit callback of a process.
*
* @param pid {int} The pid of the process.
* @param callback {function} The handler function.
*
* @return An object with this property:
* <ul><li>"err": The status of the operation, one of:
* <br>NO_ERROR
* <br>ERR_UNKNOWN
* <br>ERR_INVALID_PARAMS
* <br>ERR_INVALID_PROCESS_ID </li></ul>
**/
native function OnQuit();
cep.process.onquit = function (pid, callback) {
OnQuit(pid, callback);
return getErrorResult();
};
/**
* Reports whether a process is currently running.
*
* @param pid {int} The pid of the process.
*
* @return An object with these properties:
* <ul><li>"data": True if the process is running, false otherwise. </li>
* <li>"err": The status of the operation, one of
* <br>NO_ERROR
* <br>ERR_UNKNOWN
* <br>ERR_INVALID_PARAMS
* <br>ERR_INVALID_PROCESS_ID </li></ul>
**/
native function IsRunning();
cep.process.isRunning = function (pid) {
var isRunning = IsRunning(pid);
var result = {data: isRunning, err: getLastError()};
return result;
};
/**
* Terminates a process.
*
* @param pid {int} The pid of the process
*
* @return An object with this property:
* <ul><li>"err": The status of the operation, one of:
* <br>NO_ERROR
* <br>ERR_UNKNOWN
* <br>ERR_INVALID_PARAMS
* <br>ERR_INVALID_PROCESS_ID </li></ul>
**/
native function Terminate();
cep.process.terminate = function (pid) {
Terminate(pid);
return getErrorResult();
};
/**
* Encoding conversions.
*
*/
cep.encoding.convertion =
{
utf8_to_b64: function(str) {
return window.btoa(unescape(encodeURIComponent(str)));
},
b64_to_utf8: function(base64str) {
// If a base64 string contains any whitespace character, DOM Exception 5 occurs during window.atob, please see
// http://stackoverflow.com/questions/14695988/dom-exception-5-invalid-character-error-on-valid-base64-image-string-in-javascri
base64str = base64str.replace(/\s/g, '');
return decodeURIComponent(escape(window.atob(base64str)));
},
binary_to_b64: function(binary) {
return window.btoa(binary);
},
b64_to_binary: function(base64str) {
return window.atob(base64str);
},
ascii_to_b64: function(ascii) {
return window.btoa(binary);
},
b64_to_ascii: function(base64str) {
return window.atob(base64str);
}
};
/**
* Opens a page in the default system browser.
*
* @param url {string} The URL of the page/file to open, or the email address.
* Must use HTTP/HTTPS/file/mailto. For example:
* "http://www.adobe.com"
* "https://github.com"
* "file:///C:/log.txt"
* "mailto:test@adobe.com"
*
* @return An object with this property:
* <ul><li>"err": The status of the operation, one of:
* <br>NO_ERROR
* <br>ERR_UNKNOWN
* <br>ERR_INVALID_PARAMS</li></ul>
**/
native function OpenURLInDefaultBrowser();
cep.util.openURLInDefaultBrowser = function (url) {
if (url && (url.indexOf("http://") === 0 ||
url.indexOf("https://") === 0 ||
url.indexOf("file://") === 0 ||
url.indexOf("mailto:") === 0)) {
OpenURLInDefaultBrowser(url);
return getErrorResult();
} else {
return { err : cep.util.ERR_INVALID_URL };
}
};
/**
* Registers a callback function for extension unload. If called more than once,
* the last callback that is successfully registered is used.
*
* @deprecated since version 6.0.0
*
* @param callback {function} The handler function.
*
* @return An object with this property:
* <ul><li>"err": The status of the operation, one of:
* <br>NO_ERROR
* <br>ERR_INVALID_PARAMS</li></ul>
**/
native function RegisterExtensionUnloadCallback();
cep.util.registerExtensionUnloadCallback = function (callback) {
return { err : cep.util.DEPRECATED_API };
};
/**
* Stores the user's proxy credentials
*
* @param username {string} proxy username
* @param password {string} proxy password
*
* @return An object with this property:
* <ul><li>"err": The status of the operation, one of
* <br>NO_ERROR
* <br>ERR_INVALID_PARAMS </li>
* </ul>
**/
native function StoreProxyCredentials();
cep.util.storeProxyCredentials = function (username, password) {
StoreProxyCredentials(username, password);
return getErrorResult();
};
})();

View File

@@ -0,0 +1,788 @@
/**
* Stores constants for the window types supported by the CSXS infrastructure.
*/
declare function CSXSWindowType(): void;
/**
* EvalScript error message
*/
declare var EvalScript_ErrMessage: any;
/**
* Version
Defines a version number with major, minor, micro, and special
components. The major, minor and micro values are numeric; the special
value can be any string.
* @param major - The major version component, a positive integer up to nine digits long.
* @param minor - The minor version component, a positive integer up to nine digits long.
* @param micro - The micro version component, a positive integer up to nine digits long.
* @param special - The special version component, an arbitrary string.
*/
declare class Version {
constructor(major: any, minor: any, micro: any, special: any);
/**
* The maximum value allowed for a numeric version component.
This reflects the maximum value allowed in PlugPlug and the manifest schema.
*/
static MAX_NUM: any;
}
/**
* VersionBound
Defines a boundary for a version range, which associates a \c Version object
with a flag for whether it is an inclusive or exclusive boundary.
* @param version - The \c #Version object.
* @param inclusive - True if this boundary is inclusive, false if it is exclusive.
*/
declare class VersionBound {
constructor(version: any, inclusive: any);
}
/**
* VersionRange
Defines a range of versions using a lower boundary and optional upper boundary.
* @param lowerBound - The \c #VersionBound object.
* @param upperBound - The \c #VersionBound object, or null for a range with no upper boundary.
*/
declare class VersionRange {
constructor(lowerBound: any, upperBound: any);
}
/**
* Runtime
Represents a runtime related to the CEP infrastructure.
Extensions can declare dependencies on particular
CEP runtime versions in the extension manifest.
* @param name - The runtime name.
* @param version - A \c #VersionRange object that defines a range of valid versions.
*/
declare class Runtime {
constructor(name: any, version: any);
}
/**
* Extension
Encapsulates a CEP-based extension to an Adobe application.
* @param id - The unique identifier of this extension.
* @param name - The localizable display name of this extension.
* @param mainPath - The path of the "index.html" file.
* @param basePath - The base path of this extension.
* @param windowType - The window type of the main window of this extension.
* Valid values are defined by \c #CSXSWindowType.
* @param width - The default width in pixels of the main window of this extension.
* @param height - The default height in pixels of the main window of this extension.
* @param minWidth - The minimum width in pixels of the main window of this extension.
* @param minHeight - The minimum height in pixels of the main window of this extension.
* @param maxWidth - The maximum width in pixels of the main window of this extension.
* @param maxHeight - The maximum height in pixels of the main window of this extension.
* @param defaultExtensionDataXml - The extension data contained in the default \c ExtensionDispatchInfo section of the extension manifest.
* @param specialExtensionDataXml - The extension data contained in the application-specific \c ExtensionDispatchInfo section of the extension manifest.
* @param requiredRuntimeList - An array of \c Runtime objects for runtimes required by this extension.
* @param isAutoVisible - True if this extension is visible on loading.
* @param isPluginExtension - True if this extension has been deployed in the Plugins folder of the host application.
*/
declare class Extension {
constructor(
id: any,
name: any,
mainPath: any,
basePath: any,
windowType: any,
width: any,
height: any,
minWidth: any,
minHeight: any,
maxWidth: any,
maxHeight: any,
defaultExtensionDataXml: any,
specialExtensionDataXml: any,
requiredRuntimeList: any,
isAutoVisible: any,
isPluginExtension: any
);
}
/**
* CSEvent
A standard JavaScript event, the base class for CEP events.
* @param type - The name of the event type.
* @param scope - The scope of event, can be "GLOBAL" or "APPLICATION".
* @param appId - The unique identifier of the application that generated the event.
* @param extensionId - The unique identifier of the extension that generated the event.
*/
declare class CSEvent {
public type: any
public scope: any
public appId: any
public extensionId: any
constructor(type?: any, scope?: any, appId?: any, extensionId?: any);
/**
* Event-specific data.
*/
data: any;
}
/**
* SystemPath
Stores operating-system-specific location constants for use in the
\c #CSInterface.getSystemPath() method.
*/
declare class SystemPath {
constructor();
/**
* The path to user data.
*/
static USER_DATA: any;
/**
* The path to common files for Adobe applications.
*/
static COMMON_FILES: any;
/**
* The path to the user's default document folder.
*/
static MY_DOCUMENTS: any;
static APPLICATION: any;
/**
* The path to current extension.
*/
static EXTENSION: any;
/**
* The path to hosting application's executable.
*/
static HOST_APPLICATION: any;
}
/**
* ColorType
Stores color-type constants.
*/
declare class ColorType {
constructor();
/**
* RGB color type.
*/
static RGB: any;
/**
* Gradient color type.
*/
static GRADIENT: any;
/**
* Null color type.
*/
static NONE: any;
}
/**
* RGBColor
Stores an RGB color with red, green, blue, and alpha values.
All values are in the range [0.0 to 255.0]. Invalid numeric values are
converted to numbers within this range.
* @param red - The red value, in the range [0.0 to 255.0].
* @param green - The green value, in the range [0.0 to 255.0].
* @param blue - The blue value, in the range [0.0 to 255.0].
* @param alpha - The alpha (transparency) value, in the range [0.0 to 255.0].
The default, 255.0, means that the color is fully opaque.
*/
declare class RGBColor {
constructor(red: any, green: any, blue: any, alpha: any);
}
/**
* Direction
A point value in which the y component is 0 and the x component
is positive or negative for a right or left direction,
or the x component is 0 and the y component is positive or negative for
an up or down direction.
* @param x - The horizontal component of the point.
* @param y - The vertical component of the point.
*/
declare class Direction {
constructor(x: any, y: any);
}
/**
* GradientStop
Stores gradient stop information.
* @param offset - The offset of the gradient stop, in the range [0.0 to 1.0].
* @param rgbColor - The color of the gradient at this point, an \c #RGBColor object.
*/
declare class GradientStop {
constructor(offset: any, rgbColor: any);
}
/**
* GradientColor
Stores gradient color information.
* @param type - The gradient type, must be "linear".
* @param direction - A \c #Direction object for the direction of the gradient
* (up, down, right, or left).
* @param numStops - The number of stops in the gradient.
* @param gradientStopList - An array of \c #GradientStop objects.
*/
declare class GradientColor {
constructor(type: any, direction: any, numStops: any, gradientStopList: any);
}
/**
* UIColor
Stores color information, including the type, anti-alias level, and specific color
values in a color object of an appropriate type.
* @param type - The color type, 1 for "rgb" and 2 for "gradient".
* The supplied color object must correspond to this type.
* @param antialiasLevel - The anti-alias level constant.
* @param color - A \c #RGBColor or \c #GradientColor object containing specific color information.
*/
declare class UIColor {
constructor(type: any, antialiasLevel: any, color: any);
}
/**
* AppSkinInfo
Stores window-skin properties, such as color and font. All color parameter values are \c #UIColor objects except that systemHighlightColor is \c #RGBColor object.
* @param baseFontFamily - The base font family of the application.
* @param baseFontSize - The base font size of the application.
* @param appBarBackgroundColor - The application bar background color.
* @param panelBackgroundColor - The background color of the extension panel.
* @param appBarBackgroundColorSRGB - The application bar background color, as sRGB.
* @param panelBackgroundColorSRGB - The background color of the extension panel, as sRGB.
* @param systemHighlightColor - The highlight color of the extension panel, if provided by the host application. Otherwise, the operating-system highlight color.
*/
declare class AppSkinInfo {
constructor(
baseFontFamily: any,
baseFontSize: any,
appBarBackgroundColor: any,
panelBackgroundColor: any,
appBarBackgroundColorSRGB: any,
panelBackgroundColorSRGB: any,
systemHighlightColor: any
);
}
/**
* HostEnvironment
Stores information about the environment in which the extension is loaded.
* @param appName - The application's name.
* @param appVersion - The application's version.
* @param appLocale - The application's current license locale.
* @param appUILocale - The application's current UI locale.
* @param appId - The application's unique identifier.
* @param isAppOnline - True if the application is currently online.
* @param appSkinInfo - An \c #AppSkinInfo object containing the application's default color and font styles.
*/
declare class HostEnvironment {
constructor(
appName: any,
appVersion: any,
appLocale: any,
appUILocale: any,
appId: any,
isAppOnline: any,
appSkinInfo: any
);
}
/**
* HostCapabilities
Stores information about the host capabilities.
* @param EXTENDED_PANEL_MENU - True if the application supports panel menu.
* @param EXTENDED_PANEL_ICONS - True if the application supports panel icon.
* @param DELEGATE_APE_ENGINE - True if the application supports delegated APE engine.
* @param SUPPORT_HTML_EXTENSIONS - True if the application supports HTML extensions.
* @param DISABLE_FLASH_EXTENSIONS - True if the application disables FLASH extensions.
*/
declare class HostCapabilities {
constructor(
EXTENDED_PANEL_MENU: any,
EXTENDED_PANEL_ICONS: any,
DELEGATE_APE_ENGINE: any,
SUPPORT_HTML_EXTENSIONS: any,
DISABLE_FLASH_EXTENSIONS: any
);
}
/**
* ApiVersion
Stores current api version.
Since 4.2.0
* @param major - The major version
* @param minor - The minor version.
* @param micro - The micro version.
*/
declare class ApiVersion {
constructor(major: any, minor: any, micro: any);
}
/**
* MenuItemStatus
Stores flyout menu item status
Since 5.2.0
* @param menuItemLabel - The menu item label.
* @param enabled - True if user wants to enable the menu item.
* @param checked - True if user wants to check the menu item.
*/
declare class MenuItemStatus {
constructor(menuItemLabel: any, enabled: any, checked: any);
}
/**
* ContextMenuItemStatus
Stores the status of the context menu item.
Since 5.2.0
* @param menuItemID - The menu item id.
* @param enabled - True if user wants to enable the menu item.
* @param checked - True if user wants to check the menu item.
*/
declare class ContextMenuItemStatus {
constructor(menuItemID: any, enabled: any, checked: any);
}
/**
* CSInterface
This is the entry point to the CEP extensibility infrastructure.
Instantiate this object and use it to:
<ul>
<li>Access information about the host application in which an extension is running</li>
<li>Launch an extension</li>
<li>Register interest in event notifications, and dispatch events</li>
</ul>
*/
type RBGAColor = {
alpha: number;
green: number;
blue: number;
red: number;
};
export default class CSInterface {
constructor();
/**
* User can add this event listener to handle native application theme color changes.
Callback function gives extensions ability to fine-tune their theme color after the
global theme color has been changed.
The callback function should be like below:
* @example
* // event is a CSEvent object, but user can ignore it.
function OnAppThemeColorChanged(event)
{
// Should get a latest HostEnvironment object from application.
var skinInfo = JSON.parse(window.__adobe_cep__.getHostEnvironment()).appSkinInfo;
// Gets the style information such as color info from the skinInfo,
// and redraw all UI controls of your extension according to the style info.
}
*/
static THEME_COLOR_CHANGED_EVENT: any;
/**
* The host environment data object.
*/
hostEnvironment: {
appName: string;
appVersion: string;
appLocale: string;
appUILocale: string;
appId: string;
isAppOnline: boolean;
appSkinInfo: {
baseFontFamily: string;
baseFontSize: number;
appBarBackgroundColor: {
antialiasLevel: number;
type: number;
color: RBGAColor;
};
panelBackgroundColor: {
antialiasLevel: number;
type: number;
color: RBGAColor;
};
appBarBackgroundColorSRGB: {
antialiasLevel: number;
type: number;
color: RBGAColor;
};
panelBackgroundColorSRGB: {
antialiasLevel: number;
type: number;
color: RBGAColor;
};
systemHighlightColor: RBGAColor;
};
};
/**
* Retrieves information about the host environment in which the
extension is currently running.
* @returns A \c #HostEnvironment object.
*/
getHostEnvironment(): any;
/**
* Loads binary file created which is located at url asynchronously
* @example
* To create JS binary use command ./cep_compiler test.js test.bin
To load JS binary asyncronously
var CSLib = new CSInterface();
CSLib.loadBinAsync(url, function () { });
* @param urlName - url at which binary file is located. Local files should start with 'file://'
* @param callback - Optional. A callback function that returns after binary is loaded
*/
loadBinAsync(urlName: any, callback: any): void;
/**
* Loads binary file created synchronously
* @example
* To create JS binary use command ./cep_compiler test.js test.bin
To load JS binary syncronously
var CSLib = new CSInterface();
CSLib.loadBinSync(path);
* @param pathName - the local path at which binary file is located
*/
loadBinSync(pathName: any): void;
/**
* Closes this extension.
*/
closeExtension(): void;
/**
* Retrieves a path for which a constant is defined in the system.
* @param pathType - The path-type constant defined in \c #SystemPath ,
* @returns The platform-specific system path string.
*/
getSystemPath(pathType: any): any;
/**
* Evaluates a JavaScript script, which can use the JavaScript DOM
of the host application.
* @param script - The JavaScript script.
* @param callback - Optional. A callback function that receives the result of execution.
If execution fails, the callback function receives the error message \c EvalScript_ErrMessage.
*/
evalScript(script: any, callback: any): void;
/**
* Retrieves the unique identifier of the application.
in which the extension is currently running.
* @returns The unique ID string.
*/
getApplicationID(): any;
/**
* Retrieves host capability information for the application
in which the extension is currently running.
* @returns A \c #HostCapabilities object.
*/
getHostCapabilities(): any;
/**
* Triggers a CEP event programmatically. Yoy can use it to dispatch
an event of a predefined type, or of a type you have defined.
* @param event - A \c CSEvent object.
*/
dispatchEvent(event: any): void;
/**
* Registers an interest in a CEP event of a particular type, and
assigns an event handler.
The event infrastructure notifies your extension when events of this type occur,
passing the event object to the registered handler function.
* @param type - The name of the event type of interest.
* @param listener - The JavaScript handler function or method.
* @param obj - Optional, the object containing the handler method, if any.
Default is null.
*/
addEventListener(type: any, listener: Function, obj?: any): void;
/**
* Removes a registered event listener.
* @param type - The name of the event type of interest.
* @param listener - The JavaScript handler function or method that was registered.
* @param obj - Optional, the object containing the handler method, if any.
Default is null.
*/
removeEventListener(type: any, listener: any, obj: any): void;
/**
* Loads and launches another extension, or activates the extension if it is already loaded.
* @example
* To launch the extension "help" with ID "HLP" from this extension, call:
<code>requestOpenExtension("HLP", ""); </code>
* @param extensionId - The extension's unique identifier.
* @param startupParams - Not currently used, pass "".
*/
requestOpenExtension(extensionId: any, startupParams: any): void;
/**
* Retrieves the list of extensions currently loaded in the current host application.
The extension list is initialized once, and remains the same during the lifetime
of the CEP session.
* @param extensionIds - Optional, an array of unique identifiers for extensions of interest.
If omitted, retrieves data for all extensions.
* @returns Zero or more \c #Extension objects.
*/
getExtensions(extensionIds: any): any;
/**
* Retrieves network-related preferences.
* @returns A JavaScript object containing network preferences.
*/
getNetworkPreferences(): any;
/**
* Initializes the resource bundle for this extension with property values
for the current application and locale.
To support multiple locales, you must define a property file for each locale,
containing keyed display-string values for that locale.
See localization documentation for Extension Builder and related products.
Keys can be in the
form <code>key.value="localized string"</code>, for use in HTML text elements.
For example, in this input element, the localized \c key.value string is displayed
instead of the empty \c value string:
<code><input type="submit" value="" data-locale="key"/></code>
* @returns An object containing the resource bundle information.
*/
initResourceBundle(): any;
/**
* Writes installation information to a file.
* @returns The file path.
*/
dumpInstallationInfo(): any;
/**
* Retrieves version information for the current Operating System,
See http://www.useragentstring.com/pages/Chrome/ for Chrome \c navigator.userAgent values.
* @returns A string containing the OS version, or "unknown Operation System".
If user customizes the User Agent by setting CEF command parameter "--user-agent", only
"Mac OS X" or "Windows" will be returned.
*/
getOSInformation(): any;
/**
* Opens a page in the default system browser.
Since 4.2.0
* @param url - The URL of the page/file to open, or the email address.
Must use HTTP/HTTPS/file/mailto protocol. For example:
"http://www.adobe.com"
"https://github.com"
"file:///C:/log.txt"
"mailto:test@adobe.com"
* @returns One of these error codes:\n
<ul>\n
<li>NO_ERROR - 0</li>\n
<li>ERR_UNKNOWN - 1</li>\n
<li>ERR_INVALID_PARAMS - 2</li>\n
<li>ERR_INVALID_URL - 201</li>\n
</ul>\n
*/
openURLInDefaultBrowser(url: any): any;
/**
* Retrieves extension ID.
Since 4.2.0
* @returns extension ID.
*/
getExtensionID(): any;
/**
* Retrieves the scale factor of screen.
On Windows platform, the value of scale factor might be different from operating system's scale factor,
since host application may use its self-defined scale factor.
Since 4.2.0
* @returns One of the following float number.
<ul>\n
<li> -1.0 when error occurs </li>\n
<li> 1.0 means normal screen </li>\n
<li> >1.0 means HiDPI screen </li>\n
</ul>\n
*/
getScaleFactor(): any;
/**
* Set a handler to detect any changes of scale factor. This only works on Mac.
Since 4.2.0
* @param handler - The function to be called when scale factor is changed.
*/
setScaleFactorChangedHandler(handler: any): void;
/**
* Retrieves current API version.
Since 4.2.0
* @returns ApiVersion object.
*/
getCurrentApiVersion(): {
minor: string;
micro: string;
major: string;
};
/**
* Set panel flyout menu by an XML.
Since 5.2.0
Register a callback function for "com.adobe.csxs.events.flyoutMenuClicked" to get notified when a
menu item is clicked.
The "data" attribute of event is an object which contains "menuId" and "menuName" attributes.
Register callback functions for "com.adobe.csxs.events.flyoutMenuOpened" and "com.adobe.csxs.events.flyoutMenuClosed"
respectively to get notified when flyout menu is opened or closed.
* @param menu - A XML string which describes menu structure.
An example menu XML:
<Menu>
<MenuItem Id="menuItemId1" Label="TestExample1" Enabled="true" Checked="false"/>
<MenuItem Label="TestExample2">
<MenuItem Label="TestExample2-1" >
<MenuItem Label="TestExample2-1-1" Enabled="false" Checked="true"/>
</MenuItem>
<MenuItem Label="TestExample2-2" Enabled="true" Checked="true"/>
</MenuItem>
<MenuItem Label="---" />
<MenuItem Label="TestExample3" Enabled="false" Checked="false"/>
</Menu>
*/
setPanelFlyoutMenu(menu: any): void;
/**
* Updates a menu item in the extension window's flyout menu, by setting the enabled
and selection status.
Since 5.2.0
* @param menuItemLabel - The menu item label.
* @param enabled - True to enable the item, false to disable it (gray it out).
* @param checked - True to select the item, false to deselect it.
* @returns false when the host application does not support this functionality (HostCapabilities.EXTENDED_PANEL_MENU is false).
Fails silently if menu label is invalid.
*/
updatePanelMenuItem(menuItemLabel: any, enabled: any, checked: any): any;
/**
* An example menu XML:
<Menu>
<MenuItem Id="menuItemId1" Label="TestExample1" Enabled="true" Checkable="true" Checked="false" Icon="./image/small_16X16.png"/>
<MenuItem Id="menuItemId2" Label="TestExample2">
<MenuItem Id="menuItemId2-1" Label="TestExample2-1" >
<MenuItem Id="menuItemId2-1-1" Label="TestExample2-1-1" Enabled="false" Checkable="true" Checked="true"/>
</MenuItem>
<MenuItem Id="menuItemId2-2" Label="TestExample2-2" Enabled="true" Checkable="true" Checked="true"/>
</MenuItem>
<MenuItem Label="---" />
<MenuItem Id="menuItemId3" Label="TestExample3" Enabled="false" Checkable="true" Checked="false"/>
</Menu>
* @param menu - A XML string which describes menu structure.
* @param callback - The callback function which is called when a menu item is clicked. The only parameter is the returned ID of clicked menu item.
*/
setContextMenu(menu: any, callback: any): void;
/**
* An example menu JSON:
{
"menu": [
{
"id": "menuItemId1",
"label": "testExample1",
"enabled": true,
"checkable": true,
"checked": false,
"icon": "./image/small_16X16.png"
},
{
"id": "menuItemId2",
"label": "testExample2",
"menu": [
{
"id": "menuItemId2-1",
"label": "testExample2-1",
"menu": [
{
"id": "menuItemId2-1-1",
"label": "testExample2-1-1",
"enabled": false,
"checkable": true,
"checked": true
}
]
},
{
"id": "menuItemId2-2",
"label": "testExample2-2",
"enabled": true,
"checkable": true,
"checked": true
}
]
},
{
"label": "---"
},
{
"id": "menuItemId3",
"label": "testExample3",
"enabled": false,
"checkable": true,
"checked": false
}
]
}
* @param menu - A JSON string which describes menu structure.
* @param callback - The callback function which is called when a menu item is clicked. The only parameter is the returned ID of clicked menu item.
*/
setContextMenuByJSON(menu: any, callback: any): void;
/**
* Updates a context menu item by setting the enabled and selection status.
Since 5.2.0
* @param menuItemID - The menu item ID.
* @param enabled - True to enable the item, false to disable it (gray it out).
* @param checked - True to select the item, false to deselect it.
*/
updateContextMenuItem(menuItemID: any, enabled: any, checked: any): void;
/**
* Get the visibility status of an extension window.
Since 6.0.0
* @returns true if the extension window is visible; false if the extension window is hidden.
*/
isWindowVisible(): any;
/**
* Resize extension's content to the specified dimensions.
1. Works with modal and modeless extensions in all Adobe products.
2. Extension's manifest min/max size constraints apply and take precedence.
3. For panel extensions
3.1 This works in all Adobe products except:
* Premiere Pro
* Prelude
* After Effects
3.2 When the panel is in certain states (especially when being docked),
it will not change to the desired dimensions even when the
specified size satisfies min/max constraints.
Since 6.0.0
* @param width - The new width
* @param height - The new height
*/
resizeContent(width: any, height: any): void;
/**
* Register the invalid certificate callback for an extension.
This callback will be triggered when the extension tries to access the web site that contains the invalid certificate on the main frame.
But if the extension does not call this function and tries to access the web site containing the invalid certificate, a default error page will be shown.
Since 6.1.0
* @param callback - the callback function
*/
registerInvalidCertificateCallback(callback: any): void;
/**
* Register an interest in some key events to prevent them from being sent to the host application.
This function works with modeless extensions and panel extensions.
Generally all the key events will be sent to the host application for these two extensions if the current focused element
is not text input or dropdown,
If you want to intercept some key events and want them to be handled in the extension, please call this function
in advance to prevent them being sent to the host application.
Since 6.1.0
*/
registerKeyEventsInterest(keyEventsInterest: any): void;
/**
* Set the title of the extension window.
This function works with modal and modeless extensions in all Adobe products, and panel extensions in Photoshop, InDesign, InCopy, Illustrator, Flash Pro and Dreamweaver.
Since 6.1.0
* @param title - The window title.
*/
setWindowTitle(title: any): void;
/**
* Get the title of the extension window.
This function works with modal and modeless extensions in all Adobe products, and panel extensions in Photoshop, InDesign, InCopy, Illustrator, Flash Pro and Dreamweaver.
Since 6.1.0
* @returns The window title.
*/
getWindowTitle(): any;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,30 @@
import CSInterface, { CSEvent } from "./csinterface";
/**
* 扩展PS的CSInterface类
*/
export class CSInterfaceEx {
constructor() {
}
/**持久化运行 */
public persistent() {
var cs = new CSInterface();
var event1 = new CSEvent();
event1.type = "com.adobe.PhotoshopPersistent";
event1.scope = "APPLICATION";
event1.extensionId = cs.getExtensionID();
cs.dispatchEvent(event1);
}
/**取消持久化运行 */
public unPersisten() {
var cs = new CSInterface();
var event1 = new CSEvent();
event1.type = "com.adobe.PhotoshopUnPersistent";
event1.scope = "APPLICATION";
event1.extensionId = cs.getExtensionID();
cs.dispatchEvent(event1);
}
}

View File

@@ -0,0 +1,3 @@
export type Scripts = {
[key: string]: (a: any, ...ags: any) => any;
};

View File

@@ -0,0 +1,64 @@
import CSInterface from "./csinterface"
export function initJsx(path: string) {
console.log('[cep] init jsx', path);
const cs = new CSInterface()
cs.evalScript(`$.evalFile("${path}")`, (e) => {
if (e === 'undefined') return console.log('init json success');
console.warn('load jsx', e);
})
}
type JsxTypeof = typeof import('../../../src/jsx/index')
type MethodName = keyof JsxTypeof
export function evalJSX<T extends MethodName>(functionName: T, ...args: Parameters<JsxTypeof[T]>) {
return new Promise<ReturnType<JsxTypeof[T]>>((resolve, reject) => {
const formattedArgs = args
.map((arg) => {
console.log(JSON.stringify(arg));
return `${JSON.stringify(arg)}`;
})
.join(",");
const cs = new CSInterface()
cs.evalScript(
`try{
var res = ${functionName}(${formattedArgs});
JSON.stringify(res)
}catch(e){
alert(e);
e.fileName =new File(e.fileName).fsName;
JSON.stringify(e)
}`, (e) => {
console.log('evalJSX', e);
if (e === 'undefined') return resolve(null)
try {
let parsed = JSON.parse(e);
if (parsed.name === "ReferenceError") {
console.error("REFERENCE ERROR");
reject(parsed);
} else {
resolve(parsed);
}
} catch (error) {
reject(error)
}
})
})
}
export function evalFile(path: string) {
return new Promise((resolve, reject) => {
const cs = new CSInterface()
cs.evalScript(`$.evalFile("${path}")`, (e) => {
if (e === 'undefined') return resolve(null)
// alert(e)
console.warn('evalFileError: ' + path, e);
reject(e)
})
})
}
export { CSInterface }
export { CSInterfaceEx } from "./csinterfaceEx"

View File

@@ -0,0 +1,87 @@
// Abstracted built-in Node.js Modules
//@ts-ignore
export const crypto = (
typeof window.cep !== "undefined" ? require("crypto") : {}
) as typeof import("crypto");
export const assert = (
typeof window.cep !== "undefined" ? require("assert") : {}
) as typeof import("assert");
export const buffer = (
typeof window.cep !== "undefined" ? require("buffer") : {}
) as typeof import("buffer");
export const child_process = (
typeof window.cep !== "undefined" ? require("child_process") : {}
) as typeof import("child_process");
export const cluster = (
typeof window.cep !== "undefined" ? require("cluster") : {}
) as typeof import("cluster");
export const dgram = (
typeof window.cep !== "undefined" ? require("dgram") : {}
) as typeof import("dgram");
export const dns = (
typeof window.cep !== "undefined" ? require("dns") : {}
) as typeof import("dns");
export const domain = (
typeof window.cep !== "undefined" ? require("domain") : {}
) as typeof import("domain");
export const events = (
typeof window.cep !== "undefined" ? require("events") : {}
) as typeof import("events");
export const fs = (
typeof window.cep !== "undefined" ? require("fs") : {}
) as typeof import("fs");
export const http = (
typeof window.cep !== "undefined" ? require("http") : {}
) as typeof import("http");
export const https = (
typeof window.cep !== "undefined" ? require("https") : {}
) as typeof import("https");
export const net = (
typeof window.cep !== "undefined" ? require("net") : {}
) as typeof import("net");
export const os = (
typeof window.cep !== "undefined" ? require("os") : {}
) as typeof import("os");
export const path = (
typeof window.cep !== "undefined" ? require("path") : {}
) as typeof import("path");
export const punycode = (
typeof window.cep !== "undefined" ? require("punycode") : {}
) as typeof import("punycode");
export const querystring = (
typeof window.cep !== "undefined" ? require("querystring") : {}
) as typeof import("querystring");
export const readline = (
typeof window.cep !== "undefined" ? require("readline") : {}
) as typeof import("readline");
export const stream = (
typeof window.cep !== "undefined" ? require("stream") : {}
) as typeof import("stream");
export const string_decoder = (
typeof window.cep !== "undefined" ? require("string_decoder") : {}
) as typeof import("string_decoder");
export const timers = (
typeof window.cep !== "undefined" ? require("timers") : {}
) as typeof import("timers");
export const tls = (
typeof window.cep !== "undefined" ? require("tls") : {}
) as typeof import("tls");
export const tty = (
typeof window.cep !== "undefined" ? require("tty") : {}
) as typeof import("tty");
export const url = (
typeof window.cep !== "undefined" ? require("url") : {}
) as typeof import("url");
export const util = (
typeof window.cep !== "undefined" ? require("util") : {}
) as typeof import("util");
export const v8 = (
typeof window.cep !== "undefined" ? require("v8") : {}
) as typeof import("v8");
export const vm = (
typeof window.cep !== "undefined" ? require("vm") : {}
) as typeof import("vm");
export const zlib = (
typeof window.cep !== "undefined" ? require("zlib") : {}
) as typeof import("zlib");

265
AdminPanel/plugins/utils/cep/vulcan.d.ts vendored Normal file
View File

@@ -0,0 +1,265 @@
/**
* Vulcan
The singleton instance, <tt>VulcanInterface</tt>, provides an interface
to the Vulcan. Allows you to launch CC applications
and discover information about them.
*/
export default class Vulcan {
constructor();
/**
* Gets all available application SAPCode-Specifiers on the local machine.
*
* Vulcan Control New 6.x APIs, and Deprecating older Vulcan Control APIs.
* Changes : New getTargetSpecifiersEx returns productSAPCodeSpecifiers
*
* @return The array of all available application SAPCode-Specifiers.
*/
getTargetSpecifiersEx(): any;
/**
* Launches a CC application on the local machine, if it is not already running.
*
* Vulcan Control New 6.x APIs, and Deprecating older Vulcan Control APIs.
* Changes : New launchAppEx uses productSAPCodeSpecifiers
*
* @param productSAPCodeSpecifier The application specifier; for example "ILST-25.2.3", "ILST-25", "ILST-25.2.3-en_US" and "ILST. Refer to `Documentation/CEP 11.1 HTML Extension Cookbook.md#applications-integrated-with-cep` for product SAPCode.
* @param focus True to launch in foreground, or false to launch in the background.
* @param cmdLine Optional, command-line parameters to supply to the launch command.
* @return True if the app can be launched, false otherwise.
*/
launchAppEx(
productSAPCodeSpecifier: string,
focus: boolean,
cmdLine?: string,
): boolean;
/**
* Checks whether a CC application is running on the local machine.
*
* Vulcan Control New 6.x APIs, and Deprecating older Vulcan Control APIs.
* Changes : New isAppRunningEx uses productSAPCodeSpecifiers
*
* @param productSAPCodeSpecifier The application specifier; for example "ILST-25.2.3", "ILST-25", "ILST-25.2.3-en_US" and "ILST. Refer to `Documentation/CEP 11.1 HTML Extension Cookbook.md#applications-integrated-with-cep` for product SAPCode.
* @return True if the app is running, false otherwise.
*/
isAppRunningEx(productSAPCodeSpecifier: string): boolean;
/**
* Checks whether a CC application is installed on the local machine.
*
* Vulcan Control New 6.x APIs, and Deprecating older Vulcan Control APIs.
* Changes : New isAppInstalledEx uses productSAPCodeSpecifiers
*
* @param productSAPCodeSpecifier The application specifier; for example "ILST-25.2.3", "ILST-25", "ILST-25.2.3-en_US" and "ILST. Refer to `Documentation/CEP 11.1 HTML Extension Cookbook.md#applications-integrated-with-cep` for product SAPCode.
* @return True if the app is installed, false otherwise.
*/
isAppInstalledEx(productSAPCodeSpecifier: string): any;
/**s
* Retrieves the local install path of a CC application.
*
* Vulcan Control New 6.x APIs, and Deprecating older Vulcan Control APIs.
* Changes : New getAppPathEx uses productSAPCodeSpecifiers
*
* @param productSAPCodeSpecifier The application specifier; for example "ILST-25.2.3", "ILST-25", "ILST-25.2.3-en_US" and "ILST. Refer to `Documentation/CEP 11.1 HTML Extension Cookbook.md#applications-integrated-with-cep` for product SAPCode.
* @return The path string if the application is found, "" otherwise.
*/
getAppPathEx(): any;
// OLD FUNCTIONS
// OLD FUNCTIONS
// OLD FUNCTIONS
// OLD FUNCTIONS
/**
* Gets all available application specifiers on the local machine.
* @returns The array of all available application specifiers.
*/
getTargetSpecifiers(): any;
/**
* Launches a CC application on the local machine, if it is not already running.
* @param targetSpecifier - The application specifier; for example "indesign".
Note: In Windows 7 64-bit or Windows 8 64-bit system, some target applications (like Photoshop and Illustrator) have both 32-bit version
and 64-bit version. Therefore, we need to specify the version by this parameter with "photoshop-70.032" or "photoshop-70.064". If you
installed Photoshop 32-bit and 64-bit on one Windows 64-bit system and invoke this interface with parameter "photoshop-70.032", you may
receive wrong result.
The specifiers for Illustrator is "illustrator-17.032", "illustrator-17.064", "illustrator-17" and "illustrator".
In other platforms there is no such issue, so we can use "photoshop" or "photoshop-70" as specifier.
* @param focus - True to launch in foreground, or false to launch in the background.
* @param cmdLine - Optional, command-line parameters to supply to the launch command.
* @returns True if the app can be launched, false otherwise.
*/
launchApp(targetSpecifier: any, focus: any, cmdLine: any): any;
/**
* Checks whether a CC application is running on the local machine.
* @param targetSpecifier - The application specifier; for example "indesign".
Note: In Windows 7 64-bit or Windows 8 64-bit system, some target applications (like Photoshop and Illustrator) have both 32-bit version
and 64-bit version. Therefore, we need to specify the version by this parameter with "photoshop-70.032" or "photoshop-70.064". If you
installed Photoshop 32-bit and 64-bit on one Windows 64-bit system and invoke this interface with parameter "photoshop-70.032", you may
receive wrong result.
The specifiers for Illustrator is "illustrator-17.032", "illustrator-17.064", "illustrator-17" and "illustrator".
In other platforms there is no such issue, so we can use "photoshop" or "photoshop-70" as specifier.
* @returns True if the app is running, false otherwise.
*/
isAppRunning(targetSpecifier: any): any;
/**
* Checks whether a CC application is installed on the local machine.
* @param targetSpecifier - The application specifier; for example "indesign".
Note: In Windows 7 64-bit or Windows 8 64-bit system, some target applications (like Photoshop and Illustrator) have both 32-bit version
and 64-bit version. Therefore, we need to specify the version by this parameter with "photoshop-70.032" or "photoshop-70.064". If you
installed Photoshop 32-bit and 64-bit on one Windows 64-bit system and invoke this interface with parameter "photoshop-70.032", you may
receive wrong result.
The specifiers for Illustrator is "illustrator-17.032", "illustrator-17.064", "illustrator-17" and "illustrator".
In other platforms there is no such issue, so we can use "photoshop" or "photoshop-70" as specifier.
* @returns True if the app is installed, false otherwise.
*/
isAppInstalled(targetSpecifier: any): any;
/**
* Retrieves the local install path of a CC application.
* @param targetSpecifier - The application specifier; for example "indesign".
Note: In Windows 7 64-bit or Windows 8 64-bit system, some target applications (like Photoshop and Illustrator) have both 32-bit version
and 64-bit version. Therefore, we need to specify the version by this parameter with "photoshop-70.032" or "photoshop-70.064". If you
installed Photoshop 32-bit and 64-bit on one Windows 64-bit system and invoke this interface with parameter "photoshop-70.032", you may
receive wrong result.
The specifiers for Illustrator is "illustrator-17.032", "illustrator-17.064", "illustrator-17" and "illustrator".
In other platforms there is no such issue, so we can use "photoshop" or "photoshop-70" as specifier.
* @returns The path string if the application is found, "" otherwise.
*/
getAppPath(targetSpecifier: any): any;
/**
* Registers a message listener callback function for a Vulcan message.
* @param type - The message type.
* @param callback - The callback function that handles the message.
Takes one argument, the message object.
* @param obj - Optional, the object containing the callback method, if any.
Default is null.
*/
addMessageListener(type: any, callback: any, obj: any): void;
/**
* Removes a registered message listener callback function for a Vulcan message.
* @param type - The message type.
* @param callback - The callback function that was registered.
Takes one argument, the message object.
* @param obj - Optional, the object containing the callback method, if any.
Default is null.
*/
removeMessageListener(type: any, callback: any, obj: any): void;
/**
* Dispatches a Vulcan message.
* @param vulcanMessage - The message object.
*/
dispatchMessage(vulcanMessage: any): void;
/**
* Retrieves the message payload of a Vulcan message for the registered message listener callback function.
* @param vulcanMessage - The message object.
* @returns A string containing the message payload.
*/
getPayload(vulcanMessage: any): any;
/**
* Gets all available endpoints of the running Vulcan-enabled applications.
Since 7.0.0
* @returns The array of all available endpoints.
An example endpoint string:
<endPoint>
<appId>PHXS</appId>
<appVersion>16.1.0</appVersion>
</endPoint>
*/
getEndPoints(): any;
/**
* Gets the endpoint for itself.
Since 7.0.0
* @returns The endpoint string for itself.
*/
getSelfEndPoint(): any;
}
/**
* Singleton instance of Vulcan
*/
declare var VulcanInterface: any;
/**
* VulcanMessage
Message type for sending messages between host applications.
A message of this type can be sent to the designated destination
when appId and appVersion are provided and valid. Otherwise,
the message is broadcast to all running Vulcan-enabled applications.
To send a message between extensions running within one
application, use the <code>CSEvent</code> type in CSInterface.js.
* @param type - The message type.
* @param appId - The peer appId.
* @param appVersion - The peer appVersion.
*/
export declare class VulcanMessage {
static TYPE_PREFIX: string;
static SCOPE_SUITE: string;
static DEFAULT_APP_ID: string;
static DEFAULT_APP_VERSION: string;
static DEFAULT_DATA: string;
static dataTemplate: string;
static payloadTemplate: string;
constructor(type: any, appId: any, appVersion: any);
/**
* Initializes this message instance.
* @param message - A \c message instance to use for initialization.
*/
initialize(message: any): void;
/**
* Retrieves the message data.
* @returns A data string in XML format.
*/
xmlData(): any;
/**
* Sets the message payload of this message.
* @param payload - A string containing the message payload.
*/
setPayload(payload: any): void;
/**
* Retrieves the message payload of this message.
* @returns A string containing the message payload.
*/
getPayload(): any;
/**
* Converts the properties of this instance to a string.
* @returns The string version of this instance.
*/
toString(): any;
}
/**
* Retrieves the content of an XML element.
* @param xmlStr - The XML string.
* @param key - The name of the tag.
* @returns The content of the tag, or the empty string
if such tag is not found or the tag has no content.
*/
declare function GetValueByKey(xmlStr: any, key: any): any;
/**
* Reports whether required parameters are valid.
* @returns True if all required parameters are valid,
false if any of the required parameters are invalid.
*/
declare function requiredParamsValid(): any;
/**
* Reports whether a string has a given prefix.
* @param str - The target string.
* @param prefix - The specific prefix string.
* @returns True if the string has the prefix, false if not.
*/
declare function strStartsWith(str: any, prefix: any): any;

View File

@@ -0,0 +1,620 @@
/**************************************************************************************************
*
* ADOBE SYSTEMS INCORPORATED
* Copyright 2020 Adobe Systems Incorporated
* All Rights Reserved.
*
* NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the
* terms of the Adobe license agreement accompanying it. If you have received this file from a
* source other than Adobe, then your use, modification, or distribution of it requires the prior
* written permission of Adobe.
*
**************************************************************************************************/
/** Vulcan - v11.2.0 */
/**
* @class Vulcan
*
* The singleton instance, <tt>VulcanInterface</tt>, provides an interface
* to the Vulcan. Allows you to launch CC applications
* and discover information about them.
*/
function Vulcan() {}
/**
* Gets all available application SAPCode-Specifiers on the local machine.
*
* Vulcan Control New 6.x APIs, and Deprecating older Vulcan Control APIs.
* Changes : New getTargetSpecifiersEx returns productSAPCodeSpecifiers
*
* @return The array of all available application SAPCode-Specifiers.
*/
Vulcan.prototype.getTargetSpecifiersEx = function () {
var params = {};
return JSON.parse(
window.__adobe_cep__.invokeSync(
"vulcanGetTargetSpecifiersEx",
JSON.stringify(params)
)
);
};
/**
* Launches a CC application on the local machine, if it is not already running.
*
* Vulcan Control New 6.x APIs, and Deprecating older Vulcan Control APIs.
* Changes : New launchAppEx uses productSAPCodeSpecifiers
*
* @param productSAPCodeSpecifier The application specifier; for example "ILST-25.2.3", "ILST-25", "ILST-25.2.3-en_US" and "ILST. Refer to `Documentation/CEP 11.1 HTML Extension Cookbook.md#applications-integrated-with-cep` for product SAPCode.
* @param focus True to launch in foreground, or false to launch in the background.
* @param cmdLine Optional, command-line parameters to supply to the launch command.
* @return True if the app can be launched, false otherwise.
*/
Vulcan.prototype.launchAppEx = function (
productSAPCodeSpecifier,
focus,
cmdLine
) {
if (!requiredParamsValid(productSAPCodeSpecifier)) {
return false;
}
var params = {};
params.productSAPCodeSpecifier = productSAPCodeSpecifier;
params.focus = focus ? "true" : "false";
params.cmdLine = requiredParamsValid(cmdLine) ? cmdLine : "";
return JSON.parse(
window.__adobe_cep__.invokeSync("vulcanLaunchAppEx", JSON.stringify(params))
).result;
};
/**
* Checks whether a CC application is running on the local machine.
*
* Vulcan Control New 6.x APIs, and Deprecating older Vulcan Control APIs.
* Changes : New isAppRunningEx uses productSAPCodeSpecifiers
*
* @param productSAPCodeSpecifier The application specifier; for example "ILST-25.2.3", "ILST-25", "ILST-25.2.3-en_US" and "ILST. Refer to `Documentation/CEP 11.1 HTML Extension Cookbook.md#applications-integrated-with-cep` for product SAPCode.
* @return True if the app is running, false otherwise.
*/
Vulcan.prototype.isAppRunningEx = function (productSAPCodeSpecifier) {
if (!requiredParamsValid(productSAPCodeSpecifier)) {
return false;
}
var params = {};
params.productSAPCodeSpecifier = productSAPCodeSpecifier;
return JSON.parse(
window.__adobe_cep__.invokeSync(
"vulcanIsAppRunningEx",
JSON.stringify(params)
)
).result;
};
/**
* Checks whether a CC application is installed on the local machine.
*
* Vulcan Control New 6.x APIs, and Deprecating older Vulcan Control APIs.
* Changes : New isAppInstalledEx uses productSAPCodeSpecifiers
*
* @param productSAPCodeSpecifier The application specifier; for example "ILST-25.2.3", "ILST-25", "ILST-25.2.3-en_US" and "ILST. Refer to `Documentation/CEP 11.1 HTML Extension Cookbook.md#applications-integrated-with-cep` for product SAPCode.
* @return True if the app is installed, false otherwise.
*/
Vulcan.prototype.isAppInstalledEx = function (productSAPCodeSpecifier) {
if (!requiredParamsValid(productSAPCodeSpecifier)) {
return false;
}
var params = {};
params.productSAPCodeSpecifier = productSAPCodeSpecifier;
return JSON.parse(
window.__adobe_cep__.invokeSync(
"vulcanIsAppInstalledEx",
JSON.stringify(params)
)
).result;
};
/**s
* Retrieves the local install path of a CC application.
*
* Vulcan Control New 6.x APIs, and Deprecating older Vulcan Control APIs.
* Changes : New getAppPathEx uses productSAPCodeSpecifiers
*
* @param productSAPCodeSpecifier The application specifier; for example "ILST-25.2.3", "ILST-25", "ILST-25.2.3-en_US" and "ILST. Refer to `Documentation/CEP 11.1 HTML Extension Cookbook.md#applications-integrated-with-cep` for product SAPCode.
* @return The path string if the application is found, "" otherwise.
*/
Vulcan.prototype.getAppPathEx = function (productSAPCodeSpecifier) {
if (!requiredParamsValid(productSAPCodeSpecifier)) {
return "";
}
var params = {};
params.productSAPCodeSpecifier = productSAPCodeSpecifier;
return JSON.parse(
window.__adobe_cep__.invokeSync(
"vulcanGetAppPathEx",
JSON.stringify(params)
)
).result;
};
/**
* DEPRECATED API:: use getTargetSpecifiersEx
* Gets all available application specifiers on the local machine.
*
* @return The array of all available application specifiers.
*/
Vulcan.prototype.getTargetSpecifiers = function () {
console.warn(
"WARNING! Function 'getTargetSpecifiers' has been deprecated, please use the new 'getTargetSpecifiersEx' function instead!"
);
var params = {};
return JSON.parse(
window.__adobe_cep__.invokeSync(
"vulcanGetTargetSpecifiers",
JSON.stringify(params)
)
);
};
/**
* DEPRECATED API:: use launchAppEx
* Launches a CC application on the local machine, if it is not already running.
*
* @param targetSpecifier The application specifier; for example "indesign".
*
* Note: In Windows 7 64-bit or Windows 8 64-bit system, some target applications (like Photoshop and Illustrator) have both 32-bit version
* and 64-bit version. Therefore, we need to specify the version by this parameter with "photoshop-70.032" or "photoshop-70.064". If you
* installed Photoshop 32-bit and 64-bit on one Windows 64-bit system and invoke this interface with parameter "photoshop-70.032", you may
* receive wrong result.
* The specifiers for Illustrator is "illustrator-17.032", "illustrator-17.064", "illustrator-17" and "illustrator".
*
* In other platforms there is no such issue, so we can use "photoshop" or "photoshop-70" as specifier.
* @param focus True to launch in foreground, or false to launch in the background.
* @param cmdLine Optional, command-line parameters to supply to the launch command.
* @return True if the app can be launched, false otherwise.
*/
Vulcan.prototype.launchApp = function (targetSpecifier, focus, cmdLine) {
console.warn(
"WARNING! Function 'launchApp' has been deprecated, please use the new 'launchAppEx' function instead!"
);
if (!requiredParamsValid(targetSpecifier)) {
return false;
}
var params = {};
params.targetSpecifier = targetSpecifier;
params.focus = focus ? "true" : "false";
params.cmdLine = requiredParamsValid(cmdLine) ? cmdLine : "";
return JSON.parse(
window.__adobe_cep__.invokeSync("vulcanLaunchApp", JSON.stringify(params))
).result;
};
/**
* DEPRECATED API:: use isAppRunningEx
* Checks whether a CC application is running on the local machine.
*
* @param targetSpecifier The application specifier; for example "indesign".
*
* Note: In Windows 7 64-bit or Windows 8 64-bit system, some target applications (like Photoshop and Illustrator) have both 32-bit version
* and 64-bit version. Therefore, we need to specify the version by this parameter with "photoshop-70.032" or "photoshop-70.064". If you
* installed Photoshop 32-bit and 64-bit on one Windows 64-bit system and invoke this interface with parameter "photoshop-70.032", you may
* receive wrong result.
* The specifiers for Illustrator is "illustrator-17.032", "illustrator-17.064", "illustrator-17" and "illustrator".
*
* In other platforms there is no such issue, so we can use "photoshop" or "photoshop-70" as specifier.
* @return True if the app is running, false otherwise.
*/
Vulcan.prototype.isAppRunning = function (targetSpecifier) {
console.warn(
"WARNING! Function 'isAppRunning' has been deprecated, please use the new 'isAppRunningEx' function instead!"
);
if (!requiredParamsValid(targetSpecifier)) {
return false;
}
var params = {};
params.targetSpecifier = targetSpecifier;
return JSON.parse(
window.__adobe_cep__.invokeSync(
"vulcanIsAppRunning",
JSON.stringify(params)
)
).result;
};
/**
* DEPRECATED API:: use isAppInstalledEx
* Checks whether a CC application is installed on the local machine.
*
* @param targetSpecifier The application specifier; for example "indesign".
*
* Note: In Windows 7 64-bit or Windows 8 64-bit system, some target applications (like Photoshop and Illustrator) have both 32-bit version
* and 64-bit version. Therefore, we need to specify the version by this parameter with "photoshop-70.032" or "photoshop-70.064". If you
* installed Photoshop 32-bit and 64-bit on one Windows 64-bit system and invoke this interface with parameter "photoshop-70.032", you may
* receive wrong result.
* The specifiers for Illustrator is "illustrator-17.032", "illustrator-17.064", "illustrator-17" and "illustrator".
*
* In other platforms there is no such issue, so we can use "photoshop" or "photoshop-70" as specifier.
* @return True if the app is installed, false otherwise.
*/
Vulcan.prototype.isAppInstalled = function (targetSpecifier) {
console.warn(
"WARNING! Function 'isAppInstalled' has been deprecated, please use the new 'isAppInstalledEx' function instead!"
);
if (!requiredParamsValid(targetSpecifier)) {
return false;
}
var params = {};
params.targetSpecifier = targetSpecifier;
return JSON.parse(
window.__adobe_cep__.invokeSync(
"vulcanIsAppInstalled",
JSON.stringify(params)
)
).result;
};
/**
* DEPRECATED API:: use getAppPathEx
* Retrieves the local install path of a CC application.
*
* @param targetSpecifier The application specifier; for example "indesign".
*
* Note: In Windows 7 64-bit or Windows 8 64-bit system, some target applications (like Photoshop and Illustrator) have both 32-bit version
* and 64-bit version. Therefore, we need to specify the version by this parameter with "photoshop-70.032" or "photoshop-70.064". If you
* installed Photoshop 32-bit and 64-bit on one Windows 64-bit system and invoke this interface with parameter "photoshop-70.032", you may
* receive wrong result.
* The specifiers for Illustrator is "illustrator-17.032", "illustrator-17.064", "illustrator-17" and "illustrator".
*
* In other platforms there is no such issue, so we can use "photoshop" or "photoshop-70" as specifier.
* @return The path string if the application is found, "" otherwise.
*/
Vulcan.prototype.getAppPath = function (targetSpecifier) {
console.warn(
"WARNING! Function 'getAppPath' has been deprecated, please use the new 'getAppPathEx' function instead!"
);
if (!requiredParamsValid(targetSpecifier)) {
return "";
}
var params = {};
params.targetSpecifier = targetSpecifier;
return JSON.parse(
window.__adobe_cep__.invokeSync("vulcanGetAppPath", JSON.stringify(params))
).result;
};
/**
* Registers a message listener callback function for a Vulcan message.
*
* @param type The message type.
* @param callback The callback function that handles the message.
* Takes one argument, the message object.
* @param obj Optional, the object containing the callback method, if any.
* Default is null.
*/
Vulcan.prototype.addMessageListener = function (type, callback, obj) {
if (
!requiredParamsValid(type, callback) ||
!strStartsWith(type, VulcanMessage.TYPE_PREFIX)
) {
return;
}
var params = {};
params.type = type;
window.__adobe_cep__.invokeAsync(
"vulcanAddMessageListener",
JSON.stringify(params),
callback,
obj
);
};
/**
* Removes a registered message listener callback function for a Vulcan message.
*
* @param type The message type.
* @param callback The callback function that was registered.
* Takes one argument, the message object.
* @param obj Optional, the object containing the callback method, if any.
* Default is null.
*/
Vulcan.prototype.removeMessageListener = function (type, callback, obj) {
if (
!requiredParamsValid(type, callback) ||
!strStartsWith(type, VulcanMessage.TYPE_PREFIX)
) {
return;
}
var params = {};
params.type = type;
window.__adobe_cep__.invokeAsync(
"vulcanRemoveMessageListener",
JSON.stringify(params),
callback,
obj
);
};
/**
* Dispatches a Vulcan message.
*
* @param vulcanMessage The message object.
*/
Vulcan.prototype.dispatchMessage = function (vulcanMessage) {
if (
!requiredParamsValid(vulcanMessage) ||
!strStartsWith(vulcanMessage.type, VulcanMessage.TYPE_PREFIX)
) {
return;
}
var params = {};
var message = new VulcanMessage(vulcanMessage.type);
message.initialize(vulcanMessage);
params.vulcanMessage = message;
window.__adobe_cep__.invokeSync(
"vulcanDispatchMessage",
JSON.stringify(params)
);
};
/**
* Retrieves the message payload of a Vulcan message for the registered message listener callback function.
*
* @param vulcanMessage The message object.
* @return A string containing the message payload.
*/
Vulcan.prototype.getPayload = function (vulcanMessage) {
if (
!requiredParamsValid(vulcanMessage) ||
!strStartsWith(vulcanMessage.type, VulcanMessage.TYPE_PREFIX)
) {
return null;
}
var message = new VulcanMessage(vulcanMessage.type);
message.initialize(vulcanMessage);
return message.getPayload();
};
/**
* Gets all available endpoints of the running Vulcan-enabled applications.
*
* Since 7.0.0
*
* @return The array of all available endpoints.
* An example endpoint string:
* <endPoint>
* <appId>PHXS</appId>
* <appVersion>16.1.0</appVersion>
* </endPoint>
*/
Vulcan.prototype.getEndPoints = function () {
var params = {};
return JSON.parse(
window.__adobe_cep__.invokeSync(
"vulcanGetEndPoints",
JSON.stringify(params)
)
);
};
/**
* Gets the endpoint for itself.
*
* Since 7.0.0
*
* @return The endpoint string for itself.
*/
Vulcan.prototype.getSelfEndPoint = function () {
var params = {};
return window.__adobe_cep__.invokeSync(
"vulcanGetSelfEndPoint",
JSON.stringify(params)
);
};
/** Singleton instance of Vulcan **/
var VulcanInterface = new Vulcan();
//--------------------------------- Vulcan Message ------------------------------
/**
* @class VulcanMessage
* Message type for sending messages between host applications.
* A message of this type can be sent to the designated destination
* when appId and appVersion are provided and valid. Otherwise,
* the message is broadcast to all running Vulcan-enabled applications.
*
* To send a message between extensions running within one
* application, use the <code>CSEvent</code> type in CSInterface.js.
*
* @param type The message type.
* @param appId The peer appId.
* @param appVersion The peer appVersion.
*
*/
function VulcanMessage(type, appId, appVersion) {
this.type = type;
this.scope = VulcanMessage.SCOPE_SUITE;
this.appId = requiredParamsValid(appId)
? appId
: VulcanMessage.DEFAULT_APP_ID;
this.appVersion = requiredParamsValid(appVersion)
? appVersion
: VulcanMessage.DEFAULT_APP_VERSION;
this.data = VulcanMessage.DEFAULT_DATA;
}
VulcanMessage.TYPE_PREFIX = "vulcan.SuiteMessage.";
VulcanMessage.SCOPE_SUITE = "GLOBAL";
VulcanMessage.DEFAULT_APP_ID = "UNKNOWN";
VulcanMessage.DEFAULT_APP_VERSION = "UNKNOWN";
VulcanMessage.DEFAULT_DATA = "<data><payload></payload></data>";
VulcanMessage.dataTemplate = "<data>{0}</data>";
VulcanMessage.payloadTemplate = "<payload>{0}</payload>";
/**
* Initializes this message instance.
*
* @param message A \c message instance to use for initialization.
*/
VulcanMessage.prototype.initialize = function (message) {
this.type = message.type;
this.scope = message.scope;
this.appId = message.appId;
this.appVersion = message.appVersion;
this.data = message.data;
};
/**
* Retrieves the message data.
*
* @return A data string in XML format.
*/
VulcanMessage.prototype.xmlData = function () {
if (this.data === undefined) {
var str = "";
str = String.format(VulcanMessage.payloadTemplate, str);
this.data = String.format(VulcanMessage.dataTemplate, str);
}
return this.data;
};
/**
* Sets the message payload of this message.
*
* @param payload A string containing the message payload.
*/
VulcanMessage.prototype.setPayload = function (payload) {
var str = cep.encoding.convertion.utf8_to_b64(payload);
str = String.format(VulcanMessage.payloadTemplate, str);
this.data = String.format(VulcanMessage.dataTemplate, str);
};
/**
* Retrieves the message payload of this message.
*
* @return A string containing the message payload.
*/
VulcanMessage.prototype.getPayload = function () {
var str = GetValueByKey(this.data, "payload");
if (str !== null) {
return cep.encoding.convertion.b64_to_utf8(str);
}
return null;
};
/**
* Converts the properties of this instance to a string.
*
* @return The string version of this instance.
*/
VulcanMessage.prototype.toString = function () {
var str = "type=" + this.type;
str += ", scope=" + this.scope;
str += ", appId=" + this.appId;
str += ", appVersion=" + this.appVersion;
str += ", data=" + this.xmlData();
return str;
};
//--------------------------------------- Util --------------------------------
/**
* Formats a string based on a template.
*
* @param src The format template.
*
* @return The formatted string
*/
String.format = function (src) {
if (arguments.length === 0) {
return null;
}
var args = Array.prototype.slice.call(arguments, 1);
return src.replace(/\{(\d+)\}/g, function (m, i) {
return args[i];
});
};
/**
* Retrieves the content of an XML element.
*
* @param xmlStr The XML string.
* @param key The name of the tag.
*
* @return The content of the tag, or the empty string
* if such tag is not found or the tag has no content.
*/
function GetValueByKey(xmlStr, key) {
if (window.DOMParser) {
var parser = new window.DOMParser();
try {
var xmlDoc = parser.parseFromString(xmlStr, "text/xml");
var node = xmlDoc.getElementsByTagName(key)[0];
if (node && node.childNodes[0]) {
return node.childNodes[0].nodeValue;
}
} catch (e) {
//log the error
}
}
return "";
}
/**
* Reports whether required parameters are valid.
*
* @return True if all required parameters are valid,
* false if any of the required parameters are invalid.
*/
function requiredParamsValid() {
for (var i = 0; i < arguments.length; i++) {
var argument = arguments[i];
if (argument === undefined || argument === null) {
return false;
}
}
return true;
}
/**
* Reports whether a string has a given prefix.
*
* @param str The target string.
* @param prefix The specific prefix string.
*
* @return True if the string has the prefix, false if not.
*/
function strStartsWith(str, prefix) {
if (typeof str != "string") {
return false;
}
return str.indexOf(prefix) === 0;
}
// Boilerplate Added Export
export { VulcanMessage };
export default Vulcan;

View File

@@ -0,0 +1,65 @@
/**
* 获取当前光标位置 返回表示位置的索引number以0开头
* @param ctrl
* @returns {number}
*/
export function getCursorPosition(element) {
var CaretPos = 0;
if (document.selection) {//支持IE
element.focus();
var Sel = document.selection.createRange();
Sel.moveStart('character', -element.value.length);
CaretPos = Sel.text.length;
}
else if (element.selectionStart || element.selectionStart == '0')//支持firefox
CaretPos = element.selectionStart;
return (CaretPos);
}
export function insertAtCursor(myField, myValue) {
//IE 浏览器
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
sel.select();
}
//FireFox、Chrome等
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
// 保存滚动条
var restoreTop = myField.scrollTop;
myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
if (restoreTop > 0) {
myField.scrollTop = restoreTop;
}
myField.focus();
myField.selectionStart = startPos + myValue.length;
myField.selectionEnd = startPos + myValue.length;
} else {
myField.value += myValue;
myField.focus();
}
}

View File

@@ -0,0 +1,313 @@
/**
* 简单版对dom的封装
* 初始化一个myDom对象
* 通过类、id、以及dom元素创建
* 可以获取所有子节点、父节点、第一个子节点、最后一个子节点、上一个兄弟节点、下一个兄弟节点
* 判断元素类型
* 获取文本
* 获取元素的坐标、宽高
* 设置元素的坐标、宽高
* 设置样式
* 复制元素
* 返回真正的dom元素
* 获取所有父亲节点
* 获取指定类型的父节点
* 获取所有子节点
* 获取自定类型的子节点
*/
/**
* 获取dom元素
* @param {*} 参数 ,可以接受dom元素或者id(id必须带#号)
*/
export function $(el) {
//id选择器
if (typeof el == 'object') {
return new Dom(el);
} else if (typeof el == 'string') {
let dom = document.getElementById(el);
return dom ? new Dom(dom) : null;
} else {
console.warn(`Dom传入的字符串不符合要求${el}`);
}
return null;
}
export class Dom {
constructor(el) {
this._el = el;
}
/**
* 获取元素内的所有文本内容
*/
getTexts() {
let result = [];
const callback = (el) => {
let arr = [...el.childNodes];
arr.filter(item => item.nodeType == 3).forEach(item => result.push(item.nodeValue))
arr.filter(item => item.nodeType == 1).forEach(item => callback(item));//遍历所有元素的子节点
}
callback(this._el);
return result;
}
/**
* 获取标签内第一个文本,没有返回空
* @returns
*/
getText() {
let texts = this.getTexts();
return texts.length > 0 ? texts[0] : ''
}
/**
* 获取元素的高
*/
getHeight() {
return this._el.offsetHeight;
}
/**
* 获取元素的宽
*/
getWidth() {
return this._el.offsetWidth;
}
get left() {
return this.getLeft();
}
get top() {
return this.getTop();
}
get width() {
return this._el.offsetWidth;
}
get height() {
return this._el.offsetHeight;
}
get bottom() {
return this.top + this.height;
}
get right() {
return this.left + this.width;
}
/**
* 获取元素的left坐标
*/
getLeft() {
const callback = (e) => {
return e.offsetParent != null ? e.offsetLeft + callback(e.offsetParent) : e.offsetLeft
}
return callback(this._el)
}
/**
* 获取元素的顶点坐标
*/
getTop() {
const callback = (e) => {
return e.offsetParent != null ? e.offsetTop + callback(e.offsetParent) : e.offsetTop
}
return callback(this._el)
}
/**
* 获取坐标包含4个点以及宽高
* @returns
*/
getPosition() {
return {
left: this.getLeft(),
top: this.getTop(),
}
}
/**
* 设置样式直接合并css的样式对象
* @param {*} option
*/
setStyle(option) {
Object.assign(this._el.style, option);
}
addUnit(val, unit = 'px') {
// return unit ? val + unit : val;
return val + unit;
}
/**
* 设置坐标
* @param {*} val 左坐标位置
* @param {*} unit 默认单位为px如果不用则需要传递null
*/
setLeft(val, unit = 'px') {
this.setStyle({ left: this.addUnit(val, unit) })
}
/**
* 设置顶坐标
* @param {*} val
* @param {*} unit
*/
setTop(val, unit = 'px') {
this.setStyle({ top: this.addUnit(val, unit) })
}
/**
* 设置宽度
* @param {*} val
* @param {*} unit
*/
setWidth(val, unit = 'px') {
this.setStyle({ width: this.addUnit(val, unit) })
}
setHeight(val, unit = 'px') {
this.setStyle({ height: this.addUnit(val, unit) })
}
setSize(width, height, unit = 'px') {
this.setStyle({
width: this.addUnit(width, unit),
height: this.addUnit(height, unit),
})
}
/**
* 设置元素位置
* @param {*} left
* @param {*} top
* @param {*} unit 单位默认为px
*/
setPosition(left, top, unit = 'px') {
this.setStyle({
left: this.addUnit(left, unit),
top: this.addUnit(top, unit)
})
}
/**
* 克隆元素
* @param {*} deep
* @returns
*/
clone(deep = true) {
let el = this._el.cloneNode(deep);//克隆元素
return new Dom(el);
}
/**
* 移除元素
*/
remove() {
this._el.remove();
}
/**
* 返回原本的dom元素
* @returns
*/
getElement() {
return this._el;
}
/**
* 获取封装一层的子元素
*/
childNodes() {
return [...this._el.childNodes].map(item => new Dom(item))
}
parentNode() {
return new Dom(this._el.parentNode)
}
firstChild() {
return new Dom(this._el.firstChild);
}
lastChild() {
return new Dom(this._el.lastChild)
}
nextSibling() {
return new Dom(this._el.nextSibling)
}
previousSibling() {
return new Dom(this._el.previousSibling)
}
/**
* 是否是标签元素
* @returns
*/
isElement() {
return this._el.nodeType == 1;
}
/**
* 获取第一个指定标签的元素
* @param {*} name 标签名字
*/
firstParentByName(name) {
name = name.toUpperCase();//转大写
const callback = (el) => {
let parent = el.parentNode;
if (parent.nodeName == 'BODY')
return null;
if (parent.nodeName == name)
return new Dom(parent)
return callback(parent);
}
return callback(this._el);
}
firstChildByName(name) {
name = name.toUpperCase();//转大写
const callback = (el) => {
let childs = el.childNodes;
if (childs.length == 0)
return null;
for (let i = 0; i < childs.length; i++) {
const item = childs[i];
if (item.nodeName == name)
return new Dom(item)
}
for (let i = 0; i < childs.length; i++) {
const item = childs[i];
if (item.childNodes.length > 0)
return callback(item)
}
return null;
}
return callback(this._el);
}
getNodeName() {
return this._el.nodeName;
}
/**
* 全选
*/
select() {
// console.log(this._el);
this._el.focus();
this._el.select();
}
}

View File

@@ -0,0 +1,113 @@
/**
* 获取元素坐标
* @param {*} params
*/
export function getRefPosition(e) {
return { left: getLeft(e), top: getTop(e) };
}
export function getTop(e) {
var offset = e.offsetTop;
if (e.offsetParent != null) offset += getTop(e.offsetParent);
return offset;
}
export function getLeft(e) {
var offset = e.offsetLeft;
if (e.offsetParent != null) offset += getLeft(e.offsetParent);
return offset;
}
export function getHeight(id) {
let dom = document.getElementById(id);
return dom.offsetHeight;
}
export function getWidth(id) {
let dom = document.getElementById(id);
return dom.offsetWidth;
}
export function getClientHeight(id) {
let dom = document.getElementById(id);
return dom.clientHeight;
}
export function getClientWidth(id) {
let dom = document.getElementById(id);
return dom.clientWidth;
}
export function getWindowsHeight(param) {
return document.body.clientHeight
}
export function getWindowsWidth(param) {
return document.body.clientWidth
}
/**
* 教程菜单位置,保证菜单出现的位置不超出不可见区域
* @param {*} e
* @param {*} menuId
* @returns
*/
export function correctMenuPosition(e, menuId) {
let winHeight = getWindowsHeight();
let height = getHeight(menuId);
let winWidth = getWindowsWidth();
let windth = getWidth(menuId);
let top = (height + e.clientY) > winHeight ? winHeight - height : e.clientY;
let left = (windth + e.clientX) > winWidth ? winWidth - windth : e.clientX;
return { top, left: left + 5 }
}
/**
* 设置id的元素选择
* @param {*} id
*/
export function setInputSelect(id, time = 0) {
let count = 0;
const callbcak = () => {
let dom = document.getElementById(id);
if (!dom) {
count += 1;
if (count > 50) return
return setTimeout(callbcak, 50);
}
dom.select();
dom.focus()
}
time == 0 ? callbcak() : setTimeout(callbcak, 50);
}
export function setFoucs(id, time = 0) {
setTimeout(() => {
let dom = document.getElementById(id);
dom.focus()
}, time);
}
/**
* 获取dom元素位置
* @param {*} e
* @returns
*/
export function getPosition(e) {
var evt = e || event;
return { x: evt.clientX, y: evt.clientY }
}
/**
* 根据id获取元素的位置
* @param {*} elementId
* @returns
*/
export function getPostionById(elementId) {
var el = document.getElementById(elementId);
return getRefPosition(el);
}

View File

@@ -0,0 +1,64 @@
/**
* 在指定节点前插入节点
* @param {*} newElement
* @param {*} targentElement
*/
export function insertBefore(newElement, targentElement) {
targentElement.parentNode.insertBefore(newElement, targentElement)
}
/**
* 在指定节点后插入节点
* @param {*} newNode
* @param {*} referenceNode
*/
export function insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
/**
* 获取元素上坐标
* @param {*} e
* @returns
*/
export function getTop(e) {
var result = e.offsetTop;
if (e.offsetParent != null)
result += getTop(e.offsetParent);
return result;
}
/**
* 获取元素左坐标
* @param {*} e
* @returns
*/
export function getLeft(e) {
var result = e.offsetLeft;
if (e.offsetParent != null)
result += getLeft(e.offsetParent);
return result;
}
/**
* 获取dom元素位置
* @param {*} e
* @returns
*/
export function getPosition(e) {
var evt = e || event;
return { x: evt.clientX, y: evt.clientY }
}
/**
* 设置dom元素的位置 left top
* @param {*} dom
* @param {*} x
* @param {*} y
* @param {*} unit 后缀单位默认px
*/
export function setPosition(dom, left, top, unit = 'px') {
dom.style.left = left + unit;
dom.style.top = top + unit;
}

View File

@@ -0,0 +1,174 @@
//引入操作dom元素的
import { insertBefore, insertAfter, getTop, getLeft, getPosition, setPosition } from './dom.js'
class Drap {
static status = {
downIndex: null,
upIndex: null,
node: null,
transparentNode: null,
time: null,
callback: null,
styleWidth: null,
styleHeight: null,
}
/**
* 鼠标松开
* @returns
*/
static onMouseUp() {
Drap.status.time && clearTimeout(Drap.status.time);
let obj = Object.assign({}, Drap.status); //浅复制一份
Drap.resetStatus(); //重置
if (obj.downIndex != null && obj.upIndex != null && obj.downIndex != obj.upIndex) {
Drap.status.callback && Drap.status.callback(obj);
Drap.status.callback = null;
}
document.removeEventListener('mouseup', DragFolder.onMouseUp);
document.removeEventListener('mousemove', DragFolder.onMouseMove);
return false;
}
/**
* 鼠标移动
* @param {*} e
*/
static onMouseMove(e) {
let res = getPosition(e);
setPosition(Drap.status.node, res.x, res.y);
}
/**
* 重置状态
* @returns
*/
static resetStatus() {
if (Drap.status.downIndex == null)
return;
Drap.status.downIndex = null;
Drap.status.upIndex = null;
Drap.status.upIndex = null;
Drap.status.time = null;
if (Drap.status.node != null) {
Drap.status.node.style.width = Drap.status.styleWidth;
Drap.status.node.style.height = Drap.status.styleHeight;
Drap.status.node.style.position = "static";
}
Drap.status.transparentNode && Drap.status.transparentNode.remove();
Drap.status.transparentNode = null;
}
constructor(el, option = {}) {
let config = {
direction: 'x', //默认配置 左右方向
callback: null,
}
Object.assign(config, option);
this.option = config;
this.el = el;
this.downTime = 300;
this.init();
}
/**
* 初始化
*/
init() {
// console.log(this.option);
this.el.onmousedown = (e) => {
this.onMouseDown(e)
return false
}
this.el.onmousemove = (e) => {
this.onMouseMove(e);
}
}
/**
* 鼠标按下事件
* @param {*} e
*/
onMouseDown(e) {
document.addEventListener('mouseup', Drap.onMouseUp);
Drap.status.time = setTimeout(() => {
Drap.status.downIndex = this.option.index;
Drap.status.node = this.el;
Drap.status.transparentNode = this.el.cloneNode(true); //克隆节点
Drap.status.callback = this.option.callback;
console.log(this.el.offsetWidth);
Drap.status.styleWidth = Drap.status.node.style.width;
Drap.status.styleHeight = Drap.status.node.style.height;
Drap.status.node.style.width = this.el.offsetWidth + "px";
Drap.status.node.style.height = this.el.offsetHeight + "px"
//处理节点显示
Drap.status.node.style.position = "fixed";
Drap.status.transparentNode.style.cssText += ";opacity: 0;"
insertBefore(Drap.status.transparentNode, this.el);
document.addEventListener('mousemove', Drap.onMouseMove);
}, this.downTime);
}
/**
* 鼠标移动事件
* @param {*} e
* @returns
*/
onMouseMove(e) {
if (Drap.status.downIndex == null)
return false;
let left = getLeft(this.el) + this.el.offsetWidth / 2;
let top = getTop(this.el) + this.el.offsetHeight / 2;
let obj = getPosition(e);
let min = Drap.status.downIndex < this.option.index;
//左右方向进行拖拽
Drap.status.upIndex = this.option.index;
if (this.option.direction == 'x') {
if (obj.x < left) {
// console.log('左边');
insertBefore(Drap.status.transparentNode, this.el)
} else {
// console.log('右边');
insertAfter(Drap.status.transparentNode, this.el)
Drap.status.upIndex += min ? 0 : 1; //按下大于松开的下标+1
}
return;
}
//上下方向拖拽
if (obj.y < top) {
// console.log('上边');
insertBefore(Drap.status.transparentNode, this.el);
} else {
// console.log('下边');
insertAfter(Drap.status.transparentNode, this.el);
Drap.status.upIndex += min ? 0 : 1; //按下大于松开的下标+1
}
}
}
//导出vue指令用到的对象
export const drag = {
mounted(el, binding) {
new Drap(el, binding.value || {})
}
}

View File

@@ -0,0 +1,203 @@
/**
* 实现拖拽文件到文件夹
*/
import { getPosition, setPosition } from './dom.js'
import { ipcSend } from "@/api/electronApi/ipc.js"
let g_time = null;
let g_div = null;
let g_foldersElement = [];//所有文件夹的dom元素
let g_selectId = 'g_selectId';
let g_moveCssTest = '';//css样式
let g_callback = null;
/**
* 开启拖拽
* @param {Array} folderIds 所有文件夹的id数组需要通过获取文件夹单个的id开启拖移入移出事件
* @param {String} imgPath 预览图片的路径地址
* @param {Int} number 拖动的数量
* @param {Function} endCallback 回调函数返回null || id
*/
export function startDragFileToFolder(e, folderIds, imgPath, number, endCallback, readyCallback) {
const downTime = 200;
// document.addEventListener('mouseup', mouseUp, true);//绑定鼠标松开事件
g_time = setTimeout(() => {
// console.log('dragFileToFolder=>绑定事件');
// readyCallback && readyCallback();//准备
// createPreviewElement(imgPath, number);
// mouseMove(e)
ipcSend('ondragstart', imgPath)
// addFolderEvent(folderIds);
// g_callback = endCallback;
// document.addEventListener('mousemove', mouseMove, true);//绑定鼠标松开事件
}, downTime);
}
// export function startDragFileToFolder(e, folderIds, imgPath, number, endCallback, readyCallback) {
// const downTime = 200;
// document.addEventListener('mouseup', mouseUp, true);//绑定鼠标松开事件
// g_time = setTimeout(() => {
// console.log('dragFileToFolder=>绑定事件');
// readyCallback && readyCallback();//准备
// createPreviewElement(imgPath, number);
// // mouseMove(e)
// ipcSend('ondragstart',imgPath)
// addFolderEvent(folderIds);
// g_callback = endCallback;
// document.addEventListener('mousemove', mouseMove, true);//绑定鼠标松开事件
// }, downTime);
// }
/**
* 鼠标拖动的处理事件
* @param {*} params
*/
function mouseMove(e) {
console.log('dragFileToFolder=>拖动');
let res = getPosition(e);
setPosition(g_div, res.x + 4, res.y + 4);
}
/**
* 松开鼠标的处理事件
*/
function mouseUp() {
if (g_time)
clearTimeout(g_time);
clearPreviewElement();//清除节点
removeFolderEvent();//清除所有文件夹元素的事件
document.removeEventListener('mouseup', mouseUp, true);
document.removeEventListener('mousemove', mouseMove, true);
console.log('dragFileToFolder=>取消绑定');
if (g_selectId) {
console.log('最终id:', g_selectId);
if (g_selectId.style)
g_selectId.style.cssText = g_moveCssTest;
const idText = '#leftFolderItem';
if (g_selectId.id)
g_callback && g_callback(g_selectId.id.replace(idText, ''))
g_selectId = null;
}
g_callback = null;
}
/**
* 创建预览元素
*/
function createPreviewElement(imgPath, number) {
if (g_div != null)
return;
g_div = document.createElement('div');
let img = document.createElement('img');
img.src = imgPath;
g_div.appendChild(img);
Object.assign(img.style, {
maxWidth: '100px',
maxHeight: '100px',
border: '2px solid #2a98ff',
borderRadius: '4px'
})
Object.assign(g_div.style, {
position: 'fixed',
zIndex: 10011,
left: '-1000px',
})
g_div.appendChild(createTextElement(number));
document.body.appendChild(g_div);
}
/**
* 创建文件数量的样式
* @param {*} number
* @returns
*/
function createTextElement(number) {
let dom = document.createElement('div');
dom.innerHTML = number;
let style = {
width: '24px',
height: '24px',
lineHeight: '24px',
borderRadius: '100%',
background: "#D84A4A",
color: '#fff',
fontSize: '12px',
position: "absolute",
top: '-12px',
right: '-12px',
boxShadow: '0px 0px 10px rgba(0, 0, 0, 0.3)',
textAlign: 'center'
}
Object.assign(dom.style, style);
return dom;
}
/**
* 清除创建的元素
*/
function clearPreviewElement() {
if (g_div) {
g_div.remove();
g_div = null;
}
}
function mouseover(e) {
console.log('移入', e);
let el = e.target;
if (el.id == '')
el = el.parentNode;
g_selectId = el;
g_moveCssTest = el.style.cssText
el.style.border = '1px solid #2a98ff';
el.style.background = 'rgba(42,152,255,0.2)';
}
function mouseout(e) {
let el = e.target;
if (el.id == '') {
el = el.parentNode;
}
console.log('移出', el);
g_selectId = null;
// let el = e.target;
el.style.cssText = g_moveCssTest;
}
/**
* 给文件夹id添加关联事件
* @param {Array} ids 所有文件夹id
*/
function addFolderEvent(ids) {
const idText = '#leftFolderItem';
g_foldersElement = ids.map(id => document.getElementById(idText + id)).filter(el => el)
g_foldersElement.forEach(el => {
el.addEventListener('mouseover', mouseover);//鼠标移入
el.addEventListener('mouseout', mouseout);//鼠标移出事件
})
}
function removeFolderEvent(params) {
if (g_foldersElement.length > 0) {
g_foldersElement.forEach(el => {
el.removeEventListener('mouseover', mouseover);//鼠标移入
el.removeEventListener('mouseout', mouseout);//鼠标移出事件
})
g_foldersElement.splice(0, g_foldersElement.length);
}
}

View File

@@ -0,0 +1,68 @@
/**
* 拖拽文件时,创建一个临时的预览图
*/
import { nodeFs, getOsPrefix } from "@/utils/nodeFs"
import g_config from "@/api/config/index";
/**
* 通过canvas将svg转成png
* @param {*} path 路径
* @returns 返回base64字符串
*/
export function dragFile2png(path, number) {
// debugger
let outPath = g_config.path.dragPreview;
console.log(path, outPath);
return new Promise((resolve, reject) => {
var img = new Image();
img.src = getOsPrefix() + path;
img.onload = () => {
var canvas = document.createElement('canvas');
var c = canvas.getContext('2d');
let width, height;
let scale = img.width / 100;
if (img.width > img.height) {
width = 100;
height = img.height / scale;
} else {
scale = img.height / 100;
height = 100;
width = img.width / scale;
}
canvas.width = width + 20;
canvas.height = height + 10;
//canvas画图片
c.drawImage(img, 10, 10, width, height);
c.strokeStyle = "#2961d9";
c.lineWidth = 2;
c.strokeRect(10, 10, width, height);
if (number > 1) {
c.beginPath();
c.arc(width + 10, 10, 10, 0, Math.PI * 2, true);
c.closePath();
c.fillStyle = "rgba(255,0,0,1)";
c.fill();
c.fillStyle = "#fff";//文字的颜色
c.textAlign = 'center';//对齐方式
// c.font = '13px "微软雅黑"';
c.fillText(number, width + 10, 13);
}
//将图片添加到body中
// console.log('转png', canvas.toDataURL('image/png'));
let base64 = canvas.toDataURL('image/png')
let temp = nodeFs.sync.writeBase64(outPath, base64.split('base64,')[1]);
temp.err == 1 ? reject(temp.msg) : resolve({ outPath });
}
img.onerror = (err) => {
reject(err);//转换失败
}
})
}

View File

@@ -0,0 +1,230 @@
//引入操作dom元素的
import { insertBefore, getTop, getPosition, setPosition } from './dom.js'
export class DragFolder {
static status = {
downIndex: null,
upIndex: null,
node: null,
transparentNode: null,
moveNode: null,
moveCssTest: null,
time: null,
callback: null,
cssText: null,
position: null,
multipleChoice: null,//多选样式节点
}
/**
* 鼠标松开
* @returns
*/
static onMouseUp() {
DragFolder.status.time && clearTimeout(DragFolder.status.time);
if (DragFolder.status.moveNode != null) {
DragFolder.status.moveNode.style.cssText = DragFolder.status.moveCssTest;
DragFolder.status.moveNode = null;
}
// let obj = Object.assign({}, DragFolder.status); //浅复制一份
let downIndex = DragFolder.status.downIndex;
let upIndex = DragFolder.status.upIndex;
let position = DragFolder.status.position;
DragFolder.resetStatus(); //重置
console.log('拖拽松开');
if (downIndex != null && upIndex != null && downIndex != upIndex) {
DragFolder.status.callback && DragFolder.status.callback({ downIndex, upIndex, position });
DragFolder.status.callback = null;
}
document.removeEventListener('mouseup', DragFolder.onMouseUp);
document.removeEventListener('mousemove', DragFolder.onMouseMove);
return false;
}
/**
* 鼠标移动
* @param {*} e
*/
static onMouseMove(e) {
console.log('移动');
let res = getPosition(e);
setPosition(DragFolder.status.node, res.x + 4, res.y + 4);
}
/**
* 重置状态
* @returns
*/
static resetStatus() {
if (DragFolder.status.downIndex == null)
return;
DragFolder.status.downIndex = null;
DragFolder.status.upIndex = null;
DragFolder.status.upIndex = null;
DragFolder.status.time = null;
if (DragFolder.status.node != null) {
DragFolder.status.node.style.cssText = DragFolder.status.cssText;
DragFolder.status.node.style.position = "static";
}
if (DragFolder.status.transparentNode != null) {
DragFolder.status.transparentNode.remove();
DragFolder.status.transparentNode = null;
}
if (DragFolder.status.multipleChoice != null) {
DragFolder.status.multipleChoice.remove();
DragFolder.status.multipleChoice = null;
}
}
constructor(el, option = {}) {
let config = {
direction: 'x', //默认配置 左右方向
callback: null,
}
Object.assign(config, option);
this.option = config;
this.el = typeof el == 'string' ? document.getElementById(el) : el;
// console.log(this.el);
this.downTime = 300;
this.init();
}
/**
* 初始化
*/
init() {
// console.log(this.option);
// debugger
this.el.onmousedown = (e) => {
// debugger
this.onMouseDown(e)
// return false
}
this.el.onmousemove = (e) => {
this.onMouseMove(e);
}
// console.log('folder初始化', this.el,this.el.onmousedown);
}
/**
* 鼠标按下事件
* @param {*} e
*/
onMouseDown(e) {
document.addEventListener('mouseup', DragFolder.onMouseUp, true);
DragFolder.status.time = setTimeout(() => {
DragFolder.status.downIndex = this.option.index;
DragFolder.status.callback = this.option.callback;
if (this.option.downCallback) {
// debugger
let temp = this.option.downCallback();
let select = temp.indexOf(this.option.index) > -1 ? temp : [this.option.index];
console.log(this.option.index,temp,select)
//创建数量的提醒
if (select.length > 1) {
DragFolder.status.multipleChoice = document.createElement('div');
DragFolder.status.multipleChoice.innerHTML = select.length;
let style = {
width: '24px',
height: '24px',
lineHeight: '24px',
borderRadius: '100%',
background: "#D84A4A",
color: '#fff',
fontSize: '12px',
position: "absolute",
top: '-12px',
right: '-12px',
boxShadow: '0px 0px 10px rgba(0, 0, 0, 0.3)',
textAlign: 'center'
}
Object.assign(DragFolder.status.multipleChoice.style, style)
}
console.error('按下回调', select);
}
DragFolder.status.node = this.el;
DragFolder.status.transparentNode = this.el.cloneNode(true); //克隆节点
// DragFolder.status.node = this.el.cloneNode(true); //克隆节点
console.log(this.el.offsetWidth);
DragFolder.status.cssText = DragFolder.status.node.style.cssText;
DragFolder.status.node.style.width = this.el.offsetWidth + 4 + "px";
DragFolder.status.node.style.height = this.el.offsetHeight + 4 + "px"
//处理节点显示
DragFolder.status.node.style.position = "fixed";
DragFolder.status.node.style.background = "#2a98ff";
DragFolder.status.node.style.zIndex = "101";
DragFolder.status.transparentNode.style.cssText += ";border: 1px solid #797979"
DragFolder.status.multipleChoice && DragFolder.status.node.appendChild(DragFolder.status.multipleChoice)
insertBefore(DragFolder.status.transparentNode, this.el);
document.addEventListener('mousemove', DragFolder.onMouseMove);
}, this.downTime);
}
/**
* 鼠标移动事件
* @param {*} e
* @returns
*/
onMouseMove(e) {
if (DragFolder.status.downIndex == null)
return false;
if (DragFolder.status.moveNode != null) {
DragFolder.status.moveNode.style.cssText = DragFolder.status.moveCssTest;
DragFolder.status.moveNode = null;
}
DragFolder.status.moveNode = this.el;
DragFolder.status.moveCssTest = this.el.style.cssText;
// let elTop = getTop(this.el)
let elTop = this.el.getBoundingClientRect().top
let top = elTop + this.el.offsetHeight / 10 * 3;
let bottom = elTop + this.el.offsetHeight / 10 * 7;
let obj = getPosition(e);
//左右方向进行拖拽
DragFolder.status.upIndex = this.option.index;
//上下方向拖拽
if (obj.y < top) {
this.el.style.borderTop = '1px solid #2a98ff';
DragFolder.status.position = 'top'
} else if (obj.y > bottom) {
this.el.style.borderBottom = '1px solid #2a98ff'
DragFolder.status.position = 'bottom'
} else {
DragFolder.status.position = 'center'
this.el.style.border = '1px solid #2a98ff';
this.el.style.background = 'rgba(42,152,255,0.2)';
}
}
}
export default DragFolder;

View File

@@ -0,0 +1,189 @@
//引入操作dom元素的
import { insertBefore, getTop, getPosition, setPosition } from './dom.js'
interface IOption {
index?:string,
callback?:Function,
downCallback?: Function,
}
export class DragTag {
public el: HTMLElement
public option: IOption
public downTime: number
static status = {
node: null,
transparentNode: null,
moveNode: null,
moveCssTest: null,
time: null,
callback: null,
cssText: null,
position: null,
multipleChoice: null,//多选样式节点
option: null
}
constructor(el, option = {}) {
let config = {
direction: 'x', //默认配置 左右方向
callback: null,
}
Object.assign(config, option);
this.option = config;
this.el = typeof el == 'string' ? document.getElementById(el) : el;
// console.log(this.el);
this.downTime = 300;
this.init();
}
/**
* 鼠标松开
* @returns
*/
static onMouseUp() {
DragTag.status.time && clearTimeout(DragTag.status.time);
if (DragTag.status.moveNode != null) {
DragTag.status.moveNode.style.cssText = DragTag.status.moveCssTest;
DragTag.status.moveNode = null;
}
DragTag.resetStatus(); //重置
console.log('拖拽松开');
DragTag.status.callback && DragTag.status.callback();
document.removeEventListener('mouseup', DragTag.onMouseUp);
document.removeEventListener('mousemove', DragTag.onMouseMove);
return false;
}
/**
* 鼠标移动
* @param {*} e
*/
static onMouseMove(e) {
console.log('移动');
let res = getPosition(e);
setPosition(DragTag.status.node, res.x + 4, res.y + 4);
}
/**
* 重置状态
* @returns
*/
static resetStatus() {
DragTag.status.time = null;
if (DragTag.status.node != null) {
DragTag.status.node.style.cssText = DragTag.status.cssText;
DragTag.status.node.style.position = "static";
}
if (DragTag.status.transparentNode != null) {
DragTag.status.transparentNode.remove();
DragTag.status.transparentNode = null;
}
if (DragTag.status.multipleChoice != null) {
DragTag.status.multipleChoice.remove();
DragTag.status.multipleChoice = null;
}
}
/**
* 初始化
*/
init() {
// console.log('初始化',this.el)
this.el.onmousedown = (e) => {
this.onMouseDown(e)
}
this.el.onmousemove = (e) => {
this.onMouseMove(e);
}
}
/**
* 鼠标按下事件
* @param {*} e
*/
onMouseDown(e) {
e.preventDefault();
e.stopPropagation();
if (e.button != 0) return
console.log('按下', e.button)
document.addEventListener('mouseup', DragTag.onMouseUp);
DragTag.status.time = setTimeout(() => {
DragTag.status.callback = this.option.callback;
if (this.option.downCallback) {
// debugger
let temp = this.option.downCallback(this.option.index);
let select = temp.indexOf(this.option.index) > -1 ? temp : [this.option.index];
console.log(this.option.index, select)
//创建数量的提醒
if (select.length > 1) {
DragTag.status.multipleChoice = document.createElement('div');
DragTag.status.multipleChoice.innerHTML = select.length;
let style = {
width: '14px',
height: '14px',
lineHeight: '14px',
borderRadius: '100%',
background: "#6450FF",
color: '#fff',
fontSize: '10px',
position: "absolute",
top: '-10px',
right: '0px',
boxShadow: '0px 0px 10px rgba(0, 0, 0, 0.3)',
textAlign: 'center'
}
Object.assign(DragTag.status.multipleChoice.style, style)
}
// console.error('按下回调',select);
}
DragTag.status.node = this.el;
DragTag.status.transparentNode = this.el.cloneNode(true); //克隆节点
// DragTag.status.node = this.el.cloneNode(true); //克隆节点
DragTag.status.cssText = DragTag.status.node.style.cssText;
DragTag.status.node.style.width = this.el.offsetWidth + 4 + "px";
DragTag.status.node.style.height = this.el.offsetHeight + 4 + "px"
//处理节点显示
DragTag.status.node.style.position = "fixed";
DragTag.status.node.style.background = "#8070FF";
DragTag.status.node.style.zIndex = "101";
let res = getPosition(e);
setPosition(DragTag.status.node, res.x + 4, res.y + 4);
DragTag.status.multipleChoice && DragTag.status.node.appendChild(DragTag.status.multipleChoice)
insertBefore(DragTag.status.transparentNode, this.el);
document.addEventListener('mousemove', DragTag.onMouseMove);
}, this.downTime);
}
/**
* 鼠标移动事件
* @param {*} e
* @returns
*/
onMouseMove(e) {
}
}
export default DragTag;

View File

@@ -0,0 +1 @@
*.js linguist-detectable=false

View File

@@ -0,0 +1 @@
"object"!=typeof JSON&&(JSON={}),function(){"use strict";var rx_one=/^[\],:{}\s]*$/,rx_two=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,rx_three=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,rx_four=/(?:^|:|,)(?:\s*\[)+/g,rx_escapable=/[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,rx_dangerous=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta,rep;function f(t){return t<10?"0"+t:t}function this_value(){return this.valueOf()}function quote(t){return rx_escapable.lastIndex=0,rx_escapable.test(t)?'"'+t.replace(rx_escapable,function(t){var e=meta[t];return"string"==typeof e?e:"\\u"+("0000"+t.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+t+'"'}function str(t,e){var r,n,o,u,f,a=gap,i=e[t];switch(i&&"object"==typeof i&&"function"==typeof i.toJSON&&(i=i.toJSON(t)),"function"==typeof rep&&(i=rep.call(e,t,i)),typeof i){case"string":return quote(i);case"number":return isFinite(i)?String(i):"null";case"boolean":case"null":return String(i);case"object":if(!i)return"null";if(gap+=indent,f=[],"[object Array]"===Object.prototype.toString.apply(i)){for(u=i.length,r=0;r<u;r+=1)f[r]=str(r,i)||"null";return o=0===f.length?"[]":gap?"[\n"+gap+f.join(",\n"+gap)+"\n"+a+"]":"["+f.join(",")+"]",gap=a,o}if(rep&&"object"==typeof rep)for(u=rep.length,r=0;r<u;r+=1)"string"==typeof rep[r]&&(o=str(n=rep[r],i))&&f.push(quote(n)+(gap?": ":":")+o);else for(n in i)Object.prototype.hasOwnProperty.call(i,n)&&(o=str(n,i))&&f.push(quote(n)+(gap?": ":":")+o);return o=0===f.length?"{}":gap?"{\n"+gap+f.join(",\n"+gap)+"\n"+a+"}":"{"+f.join(",")+"}",gap=a,o}}"function"!=typeof Date.prototype.toJSON&&(Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null},Boolean.prototype.toJSON=this_value,Number.prototype.toJSON=this_value,String.prototype.toJSON=this_value),"function"!=typeof JSON.stringify&&(meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},JSON.stringify=function(t,e,r){var n;if(gap="",indent="","number"==typeof r)for(n=0;n<r;n+=1)indent+=" ";else"string"==typeof r&&(indent=r);if(rep=e,e&&"function"!=typeof e&&("object"!=typeof e||"number"!=typeof e.length))throw new Error("JSON.stringify");return str("",{"":t})}),"function"!=typeof JSON.parse&&(JSON.parse=function(text,reviver){var j;function walk(t,e){var r,n,o=t[e];if(o&&"object"==typeof o)for(r in o)Object.prototype.hasOwnProperty.call(o,r)&&(void 0!==(n=walk(o,r))?o[r]=n:delete o[r]);return reviver.call(t,e,o)}if(text=String(text),rx_dangerous.lastIndex=0,rx_dangerous.test(text)&&(text=text.replace(rx_dangerous,function(t){return"\\u"+("0000"+t.charCodeAt(0).toString(16)).slice(-4)})),rx_one.test(text.replace(rx_two,"@").replace(rx_three,"]").replace(rx_four,"")))return j=eval("("+text+")"),"function"==typeof reviver?walk({"":j},""):j;throw new SyntaxError("JSON.parse")})}();

View File

@@ -0,0 +1,3 @@
export function join(...arr: string[]) {
return arr.join('/')
}

View File

@@ -0,0 +1,97 @@
import { fs, path } from "../cep/node";
import { csi } from "./bolt";
const getLatestFile = (dir: string, suffix: string): string | null => {
const getModified = (filePath: string) =>
fs.statSync(filePath).mtime.valueOf();
let latestFile: string | null = null;
fs.readdirSync(dir)
.filter((file) => file.includes(suffix))
.map((file) => {
if (
latestFile === null ||
getModified(path.join(dir, file)) >
getModified(path.join(dir, latestFile))
) {
latestFile = file;
}
});
return latestFile;
};
export const getPrefsDir = (): string => {
const appVersion = csi.getHostEnvironment().appVersion;
const { platform, env } = window.cep_node.process;
const mainDir =
platform == "darwin"
? `${env.HOME}/Library/Preferences`
: env.APPDATA || "";
const prefsDir = path.join(
mainDir,
"Adobe",
"After Effects",
parseFloat(appVersion).toFixed(1).toString()
);
return prefsDir;
};
export const getOutputModules = (): string[] => {
const prefsDir = getPrefsDir();
const prefsSuffix = "indep-output.txt";
const outputPref = getLatestFile(prefsDir, prefsSuffix);
if (outputPref) {
const txt = fs.readFileSync(path.join(prefsDir, outputPref), {
encoding: "utf-8",
});
const matches = txt.match(
/\"Output Module Spec Strings Name .* = \".*.\"/g
);
if (matches) {
let outputModules: string[] = [];
matches.map((line) => {
const str = line.split("=").pop()?.trim().replace(/"/g, "");
if (str && !str.includes("_HIDDEN X-Factor")) {
outputModules.push(str);
}
});
return outputModules;
}
}
return [];
};
export const getRenderSettingsList = (): string[] => {
const prefsDir = getPrefsDir();
const prefsSuffix = "indep-render.txt";
const renderPref = getLatestFile(prefsDir, prefsSuffix);
if (renderPref) {
const txt = fs.readFileSync(path.join(prefsDir, renderPref), {
encoding: "utf-8",
});
const lines = txt.match(/[^\r\n]+/g);
if (lines) {
const firstLine = lines.findIndex((line) =>
line.includes("Render Settings List")
);
const lastLine = lines.findIndex((line) =>
line.includes("Still Frame RS Index")
);
const settingBlock = lines
.slice(firstLine, lastLine)
.join("")
.trim()
.replace(/^.*\=/g, "")
.replace(/\t/g, "")
.replace(/\\/g, "")
.replace(/\"\"/g, "");
let renderSettings: string[] = [];
settingBlock.match(/\".*?\"/g)?.map((str) => {
if (str && !str.includes("_HIDDEN X-Factor")) {
renderSettings.push(str.replace(/\"/g, ""));
}
});
return renderSettings;
}
}
return [];
};

View File

@@ -0,0 +1,253 @@
import CSInterface from "../cep/csinterface";
import Vulcan, { VulcanMessage } from "../cep/vulcan";
import { ns } from "../../../shared/shared";
import { fs } from "../cep/node";
export const csi = new CSInterface();
export const vulcan = new Vulcan();
// jsx utils
/**
* @function EvalES
* Evaluates a string in ExtendScript scoped to the project's namespace
* Optionally, pass true to the isGlobal param to avoid scoping
*
* @param script The script as a string to be evaluated
* @param isGlobal Optional. Defaults to false,
*
* @return String Result.
*/
export const evalES = (script: string, isGlobal = false): Promise<string> => {
return new Promise(function (resolve, reject) {
const pre = isGlobal
? ""
: `var host = typeof $ !== 'undefined' ? $ : window; host["${ns}"].`;
const fullString = pre + script;
csi.evalScript(
"try{" + fullString + "}catch(e){alert(e);}",
(res: string) => {
resolve(res);
}
);
});
};
import type { Scripts } from "@esTypes/index";
type ArgTypes<F extends Function> = F extends (...args: infer A) => any
? A
: never;
type ReturnType<F extends Function> = F extends (...args: infer A) => infer B
? B
: never;
/**
* @description End-to-end type-safe ExtendScript evaluation with error handling
* Call ExtendScript functions from CEP with type-safe parameters and return types.
* Any ExtendScript errors are captured and logged to the CEP console for tracing
*
* @param functionName The name of the function to be evaluated.
* @param args the list of arguments taken by the function.
*
* @return Promise resolving to function native return type.
*
* @example
* // CEP
* evalTS("myFunc", 60, 'test').then((res) => {
* console.log(res.word);
* });
*
* // ExtendScript
* export const myFunc = (num: number, word: string) => {
* return { num, word };
* }
*
*/
export const evalTS = <
Key extends string & keyof Scripts,
Func extends Function & Scripts[Key]
>(
functionName: Key,
...args: ArgTypes<Func>
): Promise<ReturnType<Func>> => {
return new Promise(function (resolve, reject) {
const formattedArgs = args
.map((arg) => {
console.log(JSON.stringify(arg));
return `${JSON.stringify(arg)}`;
})
.join(",");
csi.evalScript(
`try{
var host = typeof $ !== 'undefined' ? $ : window;
var res = host["${ns}"].${functionName}(${formattedArgs});
JSON.stringify(res);
}catch(e){
e.fileName = new File(e.fileName).fsName;
JSON.stringify(e);
}`,
(res: string) => {
try {
//@ts-ignore
if (res === "undefined") return resolve();
const parsed = JSON.parse(res);
if (parsed.name === "ReferenceError") {
console.error("REFERENCE ERROR");
reject(parsed);
} else {
resolve(parsed);
}
} catch (error) {
reject(res);
}
}
);
});
};
export const evalFile = (file: string) => {
return evalES(
"typeof $ !== 'undefined' ? $.evalFile(\"" +
file +
'") : fl.runScript(FLfile.platformPathToURI("' +
file +
'"));',
true
);
};
// js utils
export const initBolt = (log = true) => {
if (window.cep) {
const extRoot = csi.getSystemPath("extension");
const jsxSrc = `${extRoot}/jsx/index.js`;
const jsxBinSrc = `${extRoot}/jsx/index.jsxbin`;
if (fs.existsSync(jsxSrc)) {
if (log) console.log(jsxSrc);
evalFile(jsxSrc);
} else if (fs.existsSync(jsxBinSrc)) {
if (log) console.log(jsxBinSrc);
evalFile(jsxBinSrc);
}
}
};
export const posix = (str: string) => str.replace(/\\/g, "/");
export const openLinkInBrowser = (url: string) => {
if (window.cep) {
csi.openURLInDefaultBrowser(url);
} else {
location.href = url;
}
};
export const getAppBackgroundColor = () => {
const { green, blue, red } = JSON.parse(
window.__adobe_cep__.getHostEnvironment() as string
).appSkinInfo.panelBackgroundColor.color;
return {
rgb: {
r: red,
g: green,
b: blue,
},
hex: `#${red.toString(16)}${green.toString(16)}${blue.toString(16)}`,
};
};
export const subscribeBackgroundColor = (callback: (color: string) => void) => {
const getColor = () => {
const newColor = getAppBackgroundColor();
console.log("BG Color Updated: ", { rgb: newColor.rgb });
const { r, g, b } = newColor.rgb;
return `rgb(${r}, ${g}, ${b})`;
};
// get current color
callback(getColor());
// listen for changes
csi.addEventListener(
"com.adobe.csxs.events.ThemeColorChanged",
() => callback(getColor()),
{}
);
};
// vulcan
declare type IVulcanMessageObject = {
event: string;
callbackID?: string;
data?: string | null;
payload?: object;
};
export const vulcanSend = (id: string, msgObj: IVulcanMessageObject) => {
const msg = new VulcanMessage(VulcanMessage.TYPE_PREFIX + id, null, null);
const msgStr = JSON.stringify(msgObj);
msg.setPayload(msgStr);
vulcan.dispatchMessage(msg);
};
export const vulcanListen = (id: string, callback: Function) => {
vulcan.addMessageListener(
VulcanMessage.TYPE_PREFIX + id,
(res: any) => {
var msgStr = vulcan.getPayload(res);
const msgObj = JSON.parse(msgStr);
callback(msgObj);
},
null
);
};
export const isAppRunning = (targetSpecifier: string) => {
const { major, minor, micro } = csi.getCurrentApiVersion();
const version = parseFloat(`${major}.${minor}`);
if (version >= 11.2) {
return vulcan.isAppRunningEx(targetSpecifier.toUpperCase());
} else {
return vulcan.isAppRunning(targetSpecifier);
}
};
interface IOpenDialogResult {
data: string[];
}
export const selectFolder = (
dir: string,
msg: string,
callback: (res: string) => void
) => {
const result = window.cep.fs.showOpenDialog(
false,
true,
msg,
dir
) as IOpenDialogResult;
if (result.data?.length > 0) {
const folder = decodeURIComponent(result.data[0].replace("file://", ""));
callback(folder);
}
};
export const selectFile = (
dir: string,
msg: string,
callback: (res: string) => void
) => {
const result = window.cep.fs.showOpenDialog(
false,
false,
msg,
dir
) as IOpenDialogResult;
if (result.data?.length > 0) {
const folder = decodeURIComponent(result.data[0].replace("file://", ""));
callback(folder);
}
};

View File

@@ -0,0 +1,28 @@
import { csi } from "./bolt";
/**
* Register all possible keyboard shortcuts on Mac and Windows for you CEP Panel
* Warning: Note that certain keys will not work per OS regardless of registration
*/
export const keyRegisterOverride = () => {
const platform = navigator.platform.substring(0, 3);
let maxKey = 0;
if (platform === "Mac") maxKey = 126; // Mac Max Key Code
else if (platform === "Win") maxKey = 222; // HTML Max Key Code
let allKeys = [];
for (let k = 0; k <= maxKey; k++) {
for (let j = 0; j <= 15; j++) {
const guide = (j >>> 0).toString(2).padStart(4, "0");
allKeys.push({
keyCode: k,
ctrlKey: guide[0] === "1",
altKey: guide[1] === "1",
shiftKey: guide[2] === "1",
metaKey: guide[3] === "1",
});
}
}
const keyRes = csi.registerKeyEventsInterest(JSON.stringify(allKeys));
console.log("Key Events Registered Completed: " + keyRes);
};

View File

@@ -0,0 +1,175 @@
import { fs, os, path } from "../cep/node";
import { csi } from "./bolt";
const readDirSafe = (dir: string) =>
fs.existsSync(dir) ? fs.readdirSync(dir) : [];
export const getAllLuts = (): { creative: string[]; technical: string[] } => {
const isWin = os.platform() === "win32";
const appPath = path.dirname(csi.getSystemPath("hostApplication"));
const appLutsDir = path.join(
isWin ? appPath : path.dirname(appPath),
"Lumetri",
"LUTs"
);
const winLocal = path.join(
os.homedir(),
"AppData",
"Roaming",
"Adobe",
"Common",
"LUTs"
);
const winGlobal = path.join("C:", "Program Files", "Adobe", "Common", "LUTs");
const macLocal = path.join(
os.homedir(),
"Library",
"Application Support",
"Adobe",
"Common",
"LUTs"
);
const macGlobal = path.join(
"Library",
"Application Support",
"Adobe",
"Common",
"LUTs"
);
const appCreative = path.join(appLutsDir, "Creative");
const appTechnical = path.join(appLutsDir, "Technical");
const localCreative = isWin
? path.join(winLocal, "Creative")
: path.join(macLocal, "Creative");
const localTechnical = isWin
? path.join(winLocal, "Technical")
: path.join(macLocal, "Technical");
const globalCreative = isWin
? path.join(winGlobal, "Creative")
: path.join(macGlobal, "Creative");
const globalTechnical = isWin
? path.join(winGlobal, "Technical")
: path.join(macGlobal, "Technical");
const appCreativeLuts = readDirSafe(appCreative);
const appTechnicalLuts = readDirSafe(appTechnical);
const localCreativeLuts = readDirSafe(localCreative);
const localTechnicalLuts = readDirSafe(localTechnical);
const globalCreativeLuts = readDirSafe(globalCreative);
const globalTechnicalLuts = readDirSafe(globalTechnical);
const creative = [
...appCreativeLuts,
...localCreativeLuts,
...globalCreativeLuts,
]
.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()))
.map((lut) => path.basename(lut, path.extname(lut)));
const technical = [
...appTechnicalLuts,
...localTechnicalLuts,
...globalTechnicalLuts,
]
.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()))
.map((lut) => path.basename(lut, path.extname(lut)));
return { creative, technical };
};
export const allowedImportFiles: string[] = [
"264",
"3g2",
"3gp",
"3gpp",
"aac",
"aaf",
"ac3",
"ai",
"aif",
"aiff",
"ari",
"asf",
"asnd",
"asx",
"avc",
"avi",
"bmp",
"bwf",
"cin",
"cine",
"crm",
"dfxp",
"dib",
"dif",
"dng",
"dpx",
"dv",
"eps",
"exr",
"f4v",
"f4v",
"fli",
"gif",
"icb",
"ico",
"jfif",
"jpe",
"jpeg",
"jpg",
"m15",
"m1a",
"m1s",
"m1v",
"m2a",
"m2p",
"m2t",
"m2ts",
"m2v",
"m4a",
"m4v",
"m75",
"mcc",
"m0d",
"mov",
"mp2",
"mp3",
"mp4",
"mpa",
"mpe",
"mpeg",
"mpg",
"mpg4",
"mpm",
"mpv",
"mts",
"mxf",
"mxv",
"mxr",
"pct",
"pict",
"png",
"prt",
"ptl",
"qt",
"r3d",
"rle",
"rmf",
"scc",
"srt",
"stl",
"sxr",
"tga",
"tif",
"tiff",
"ts",
"vda",
"vob",
"vst",
"wav",
"wma",
"wmv",
"psd",
];