Initial commit

Upload local source code to github
This commit is contained in:
oxmc
2024-12-05 09:11:18 -08:00
parent a7a6efa1c8
commit 894ffb102a
11716 changed files with 767299 additions and 0 deletions

2
.gitattributes vendored Normal file
View File

@@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto

130
.gitignore vendored Normal file
View File

@@ -0,0 +1,130 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

3
README.md Normal file
View File

@@ -0,0 +1,3 @@
# Bsky Desktop
Bsky Desktop is an application for Bsky built using Electron. It allows users to manage their Bsky account and fee3ds from the app instead of the web.

116
build-app.js Normal file
View File

@@ -0,0 +1,116 @@
const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs/promises');
const process = require('process');
const packageJson = require('./package.json');
// Electron builder:
const electronBuilderPath = path.join('node_modules', 'electron-builder', 'cli.js');
// Parse command-line arguments:
const supportedPlatforms = ['win', 'mac', 'linux', 'mwl'];
const supportedArchitectures = ['x64', 'armv7l', 'arm64', 'ia32', 'universal'];
const args = process.argv.slice(2);
const carch = args.includes('--arch') ? args[args.indexOf('--arch') + 1] : null;
const cplatform = args.includes('--platform') ? args[args.indexOf('--platform') + 1] : null;
const pack = args.includes('--pack') || null;
let platform, arch, build_args;
//console.log(supportedPlatforms, supportedArchitectures, cplatform, carch);
// Platform Name:
if (cplatform == null) {
switch (process.platform) {
case "win32":
platform = "win";
break;
case "darwin":
platform = "mac";
break;
case "linux":
platform = "linux";
break;
default:
platform = "mwl"; // Build for all
break;
}
} else {
if (!supportedPlatforms.includes(cplatform)) {
console.error(`Invalid platform specified. Supported platforms: ${supportedPlatforms.join(', ')}`);
process.exit(1);
}
platform = cplatform;
}
// Platform Arch:
if (carch == null) {
arch = process.arch === "arm" ? "armv7l" : process.arch;
} else {
arch = carch;
if (!supportedArchitectures.includes(arch)) {
console.error(`Invalid arch specified. Supported architectures: ${supportedArchitectures.join(', ')}`);
process.exit(1);
}
}
// Generate artifact name:
const artifactname = `${packageJson.build.productName}-${packageJson.version}-${platform}-${arch}`;
(async () => {
try {
// Additional build arguments: (started wiht --eb-nmehere)
const additionalArgs = args.filter((arg, index) => arg.startsWith('--eb-') && index % 2 !== 0);
// CLI Args:
build_args = [
electronBuilderPath,
`--${platform}`,
`--${arch}`,
`-c.artifactName="${artifactname}.\${ext}"`,
];
// If additional args are present:
if (additionalArgs.length > 0) {
build_args.push(...additionalArgs);
}
// If pack is true:
if (pack) {
build_args.push(`--dir`);
}
// Make CLI:
const cli = `node ${build_args.join(' ')}`;
console.info(`CLI: ${cli}`);
console.info(`Building ${artifactname}`);
const process = spawn(cli, { shell: true });
// Log stdout as it comes
process.stdout.on('data', (data) => {
console.log(data.toString().trim());
});
// Log stderr as it comes
process.stderr.on('data', (data) => {
console.error(data.toString().trim());
});
// Handle process exit
process.on('close', (code) => {
if (code === 0) {
console.info(`Build completed successfully!`);
} else {
console.error(`Process exited with code ${code}`);
}
});
process.on('error', (error) => {
console.error(`Failed to start process: ${error.message}`);
});
} catch (error) {
console.error('An error occurred:', error);
process.exit(1);
}
})();

6310
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

65
package.json Normal file
View File

@@ -0,0 +1,65 @@
{
"name": "bsky-desktop",
"version": "1.0.6",
"description": "A desktop app of bsky.app",
"main": "src/app/main.js",
"scripts": {
"start": "electron .",
"pack": "electron-builder --dir",
"dist": "electron-builder",
"rebuild": "electron-rebuild",
"build": "node ./build-app.js"
},
"author": {
"name": "oxmc",
"email": "oxmc7769.mail@gmail.com"
},
"license": "AGPL-3.0-only",
"devDependencies": {
"electron": "^29.4.6",
"electron-builder": "^24.13.3"
},
"dependencies": {
"@electron/asar": "^3.2.17",
"@electron/remote": "^2.1.2",
"adm-zip": "^0.5.12",
"axios": "^1.6.8",
"electron-window-state": "^5.0.3",
"log4js": "^6.9.1",
"node-notifier": "^10.0.0",
"v8-compile-cache": "^2.3.0"
},
"build": {
"appId": "com.oxmc.bskyDesktop",
"productName": "bskyDesktop",
"asarUnpack": [
"./node_modules/node-notifier/**/*"
],
"artifactName": "bsky-desktop.${ext}",
"mac": {
"icon": "src/ui/images/logo.icns",
"category": "Network"
},
"linux": {
"target": [
"appimage"
],
"icon": "src/ui/images/logo.png",
"category": "Network"
},
"win": {
"target": [
"nsis"
],
"icon": "src/ui/images/logo.ico"
},
"protocols": [
{
"name": "bsky",
"schemes": [
"bsky"
]
}
]
}
}

View File

@@ -0,0 +1,19 @@
Copyright (c) 2015 rhysd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,27 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=yes">
<title>About This App</title>
<link rel="stylesheet" href="./styles/ui.css">
</head>
<body>
<div class="logo">
<img id="app-icon" alt="App icon" height="200">
</div>
<h2 class="title"></h2>
<h3 class="description"></h3>
<div class="copyright"></div>
<table class="versions"></table>
<div class="buttons"></div>
<footer class="footer">
<div class="link bug-report-link"></div>
</footer>
<!-- https://github.com/electron/electron/issues/2863 -->
<script>var exports = exports || {};</script>
<script src="./src/renderer.js"></script>
</body>
</html>

36
src/app/about-window/src/index.d.ts vendored Normal file
View File

@@ -0,0 +1,36 @@
export interface LicenseEntry {
type: string;
url: string;
}
export interface PackageJson {
productName?: string;
description?: string;
homepage?: string;
license?: string | LicenseEntry;
bugs?: {
url: string;
};
}
export interface AboutWindowInfo {
icon_path: string;
product_name?: string;
copyright?: string;
homepage?: string;
description?: string;
package_json_dir?: string;
about_page_dir?: string;
license?: string;
bug_report_url?: string;
css_path?: string | string[];
adjust_window_size?: boolean;
win_options?: Electron.BrowserWindowConstructorOptions;
open_devtools?: boolean;
use_inner_html?: boolean;
bug_link_text?: string;
use_version_info?: boolean | [string, string][];
show_close_button?: string;
app?: Electron.App;
BrowserWindow?: typeof Electron.BrowserWindow;
ipcMain?: Electron.IpcMain;
}
export default function openAboutWindow(info_or_img_path: AboutWindowInfo | string): Electron.BrowserWindow;

View File

@@ -0,0 +1,172 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const electron_1 = require("electron");
const fs_1 = require("fs");
const path = require("path");
function loadPackageJson(pkg_path) {
try {
return require(pkg_path);
}
catch (e) {
return null;
}
}
function detectPackageJson(specified_dir, app) {
if (specified_dir) {
const pkg = loadPackageJson(path.join(specified_dir, 'package.json'));
if (pkg !== null) {
return pkg;
}
else {
console.warn('about-window: package.json is not found in specified directory path: ' + specified_dir);
}
}
const app_name = app.name || app.getName();
for (const mod_path of module.paths) {
if (!path.isAbsolute(mod_path)) {
continue;
}
const p = path.join(mod_path, '..', 'package.json');
try {
const stats = (0, fs_1.statSync)(p);
if (stats.isFile()) {
const pkg = loadPackageJson(p);
if (pkg !== null && pkg.productName === app_name) {
return pkg;
}
}
}
catch (e) {
}
}
return null;
}
function injectInfoFromPackageJson(info, app) {
const pkg = detectPackageJson(info.package_json_dir, app);
if (pkg === null) {
return info;
}
if (!info.product_name) {
info.product_name = pkg.productName;
}
if (!info.description) {
info.description = pkg.description;
}
if (!info.license && pkg.license) {
const l = pkg.license;
info.license = typeof l === 'string' ? l : l.type;
}
if (!info.homepage) {
info.homepage = pkg.homepage;
}
if (!info.bug_report_url && typeof pkg.bugs === 'object') {
info.bug_report_url = pkg.bugs.url;
}
if (info.use_inner_html === undefined) {
info.use_inner_html = false;
}
if (info.use_version_info === undefined) {
info.use_version_info = true;
}
return info;
}
function normalizeParam(info_or_img_path) {
if (!info_or_img_path) {
throw new Error('First parameter of openAboutWindow() must not be empty. Please see the document: https://github.com/rhysd/electron-about-window/blob/master/README.md');
}
if (typeof info_or_img_path === 'string') {
return { icon_path: info_or_img_path };
}
else {
const info = info_or_img_path;
if (!info.icon_path) {
throw new Error("First parameter of openAboutWindow() must have key 'icon_path'. Please see the document: https://github.com/rhysd/electron-about-window/blob/master/README.md");
}
return Object.assign({}, info);
}
}
function openAboutWindow(info_or_img_path) {
let window = null;
let info = normalizeParam(info_or_img_path);
const ipc = electron_1.ipcMain !== null && electron_1.ipcMain !== void 0 ? electron_1.ipcMain : info.ipcMain;
const app = electron_1.app !== null && electron_1.app !== void 0 ? electron_1.app : info.app;
const BrowserWindow = electron_1.BrowserWindow !== null && electron_1.BrowserWindow !== void 0 ? electron_1.BrowserWindow : info.BrowserWindow;
if (!app || !BrowserWindow || !ipc) {
throw new Error("openAboutWindow() is called on non-main process. Set 'app', 'BrowserWindow' and 'ipcMain' properties in the 'info' argument of the function call");
}
if (window !== null) {
window.focus();
return window;
}
let base_path = info.about_page_dir;
if (base_path === undefined || base_path === null || !base_path.length) {
base_path = path.join(__dirname, '..');
}
const index_html = 'file://' + path.join(base_path, 'about.html');
const options = Object.assign({
width: 400,
height: 400,
useContentSize: true,
titleBarStyle: 'hidden-inset',
show: !info.adjust_window_size,
icon: info.icon_path,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
},
}, info.win_options || {});
window = new BrowserWindow(options);
const on_win_adjust_req = (_, width, height, show_close_button) => {
if (height > 0 && width > 0) {
if (show_close_button) {
window.setContentSize(width, height + 40);
}
else {
window.setContentSize(width, height + 52);
}
}
};
const on_win_close_req = () => {
window.close();
};
ipc.on('about-window:adjust-window-size', on_win_adjust_req);
ipc.on('about-window:close-window', on_win_close_req);
window.once('closed', () => {
window = null;
ipc.removeListener('about-window:adjust-window-size', on_win_adjust_req);
ipc.removeListener('about-window:close-window', on_win_close_req);
});
window.loadURL(index_html);
window.webContents.on('will-navigate', (e, url) => {
e.preventDefault();
electron_1.shell.openExternal(url);
});
window.webContents.on('new-window', (e, url) => {
e.preventDefault();
electron_1.shell.openExternal(url);
});
window.webContents.once('dom-ready', () => {
const win_title = info.win_options ? info.win_options.title : null;
delete info.win_options;
info.win_options = { title: win_title };
const app_name = info.product_name || app.name || app.getName();
const version = app.getVersion();
window.webContents.send('about-window:info', info, app_name, version);
if (info.open_devtools) {
if (process.versions.electron >= '1.4') {
window.webContents.openDevTools({ mode: 'detach' });
}
else {
window.webContents.openDevTools();
}
}
});
window.once('ready-to-show', () => {
window.show();
});
window.setMenu(null);
info = injectInfoFromPackageJson(info, app);
return window;
}
exports.default = openAboutWindow;
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,80 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const electron_1 = require("electron");
electron_1.ipcRenderer.on('about-window:info', (_, info, app_name, version) => {
const open_home = () => electron_1.shell.openExternal(info.homepage);
const content = info.use_inner_html ? 'innerHTML' : 'innerText';
document.title = info.win_options.title || `About ${app_name}`;
const title_elem = document.querySelector('.title');
title_elem.innerText = `${app_name} ${version}`;
if (info.homepage) {
title_elem.addEventListener('click', open_home);
title_elem.classList.add('clickable');
const logo_elem = document.querySelector('.logo');
logo_elem.addEventListener('click', open_home);
logo_elem.classList.add('clickable');
}
const copyright_elem = document.querySelector('.copyright');
if (info.copyright) {
copyright_elem[content] = info.copyright;
}
else if (info.license) {
copyright_elem[content] = `Distributed under ${info.license} license.`;
}
const icon_elem = document.getElementById('app-icon');
icon_elem.src = info.icon_path;
if (info.description) {
const desc_elem = document.querySelector('.description');
desc_elem[content] = info.description;
}
if (info.bug_report_url) {
const bug_report = document.querySelector('.bug-report-link');
bug_report.innerText = info.bug_link_text || 'Report an issue';
bug_report.addEventListener('click', e => {
e.preventDefault();
electron_1.shell.openExternal(info.bug_report_url);
});
}
if (info.css_path) {
const css_paths = !Array.isArray(info.css_path) ? [info.css_path] : info.css_path;
for (const css_path of css_paths) {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = css_path;
document.head.appendChild(link);
}
}
if (info.adjust_window_size) {
const height = document.body.scrollHeight;
const width = document.body.scrollWidth;
electron_1.ipcRenderer.send('about-window:adjust-window-size', height, width, !!info.show_close_button);
}
if (!!info.use_version_info) {
const versions = document.querySelector('.versions');
const version_info = Array.isArray(info.use_version_info)
? info.use_version_info
: ['electron', 'chrome', 'node', 'v8'].map(e => [e, process.versions[e]]);
for (const [name, value] of version_info) {
const tr = document.createElement('tr');
const name_td = document.createElement('td');
name_td.innerText = name;
tr.appendChild(name_td);
const version_td = document.createElement('td');
version_td.innerText = ' : ' + value;
tr.appendChild(version_td);
versions.appendChild(tr);
}
}
if (info.show_close_button) {
const buttons = document.querySelector('.buttons');
const close_button = document.createElement('button');
close_button.innerText = info.show_close_button;
close_button.addEventListener('click', e => {
e.preventDefault();
electron_1.ipcRenderer.send('about-window:close-window');
});
buttons.appendChild(close_button);
close_button.focus();
}
});
//# sourceMappingURL=renderer.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"renderer.js","sourceRoot":"","sources":["renderer.ts"],"names":[],"mappings":";;AAAA,uCAA8C;AAG9C,sBAAW,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,CAAM,EAAE,IAAqB,EAAE,QAAgB,EAAE,OAAe,EAAE,EAAE;IAErG,MAAM,SAAS,GAAG,GAAG,EAAE,CAAC,gBAAK,CAAC,YAAY,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAC1D,MAAM,OAAO,GAAG,IAAI,CAAC,cAAc,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC;IAChE,QAAQ,CAAC,KAAK,GAAG,IAAI,CAAC,WAAW,CAAC,KAAK,IAAI,SAAS,QAAQ,EAAE,CAAC;IAE/D,MAAM,UAAU,GAAG,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAuB,CAAC;IAC1E,UAAU,CAAC,SAAS,GAAG,GAAG,QAAQ,IAAI,OAAO,EAAE,CAAC;IAEhD,IAAI,IAAI,CAAC,QAAQ,EAAE;QACf,UAAU,CAAC,gBAAgB,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;QAChD,UAAU,CAAC,SAAS,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;QACtC,MAAM,SAAS,GAAG,QAAQ,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;QAClD,SAAS,CAAC,gBAAgB,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;QAC/C,SAAS,CAAC,SAAS,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;KACxC;IAED,MAAM,cAAc,GAAG,QAAQ,CAAC,aAAa,CAAC,YAAY,CAAQ,CAAC;IACnE,IAAI,IAAI,CAAC,SAAS,EAAE;QAChB,cAAc,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC;KAC5C;SAAM,IAAI,IAAI,CAAC,OAAO,EAAE;QACrB,cAAc,CAAC,OAAO,CAAC,GAAG,qBAAqB,IAAI,CAAC,OAAO,WAAW,CAAC;KAC1E;IAED,MAAM,SAAS,GAAG,QAAQ,CAAC,cAAc,CAAC,UAAU,CAAqB,CAAC;IAC1E,SAAS,CAAC,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC;IAE/B,IAAI,IAAI,CAAC,WAAW,EAAE;QAClB,MAAM,SAAS,GAAG,QAAQ,CAAC,aAAa,CAAC,cAAc,CAAQ,CAAC;QAChE,SAAS,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC;KACzC;IAED,IAAI,IAAI,CAAC,cAAc,EAAE;QACrB,MAAM,UAAU,GAAG,QAAQ,CAAC,aAAa,CAAC,kBAAkB,CAAmB,CAAC;QAChF,UAAU,CAAC,SAAS,GAAG,IAAI,CAAC,aAAa,IAAI,iBAAiB,CAAC;QAC/D,UAAU,CAAC,gBAAgB,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE;YACrC,CAAC,CAAC,cAAc,EAAE,CAAC;YACnB,gBAAK,CAAC,YAAY,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QAC5C,CAAC,CAAC,CAAC;KACN;IAED,IAAI,IAAI,CAAC,QAAQ,EAAE;QACf,MAAM,SAAS,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC;QAClF,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE;YAC9B,MAAM,IAAI,GAAG,QAAQ,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC;YAC5C,IAAI,CAAC,GAAG,GAAG,YAAY,CAAC;YACxB,IAAI,CAAC,IAAI,GAAG,QAAQ,CAAC;YACrB,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;SACnC;KACJ;IAED,IAAI,IAAI,CAAC,kBAAkB,EAAE;QACzB,MAAM,MAAM,GAAG,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC;QAC1C,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC;QACxC,sBAAW,CAAC,IAAI,CAAC,iCAAiC,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;KAChG;IAED,IAAI,CAAC,CAAC,IAAI,CAAC,gBAAgB,EAAE;QACzB,MAAM,QAAQ,GAAG,QAAQ,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC;QACrD,MAAM,YAAY,GAAuB,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,gBAAgB,CAAC;YACzE,CAAC,CAAC,IAAI,CAAC,gBAAgB;YACvB,CAAC,CAAC,CAAC,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAC9E,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,YAAY,EAAE;YACtC,MAAM,EAAE,GAAG,QAAQ,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;YACxC,MAAM,OAAO,GAAG,QAAQ,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;YAC7C,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC;YACzB,EAAE,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;YACxB,MAAM,UAAU,GAAG,QAAQ,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;YAChD,UAAU,CAAC,SAAS,GAAG,KAAK,GAAG,KAAK,CAAC;YACrC,EAAE,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;YAC3B,QAAQ,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;SAC5B;KACJ;IAED,IAAI,IAAI,CAAC,iBAAiB,EAAE;QACxB,MAAM,OAAO,GAAG,QAAQ,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC;QACnD,MAAM,YAAY,GAAG,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;QACtD,YAAY,CAAC,SAAS,GAAG,IAAI,CAAC,iBAAiB,CAAC;QAChD,YAAY,CAAC,gBAAgB,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE;YACvC,CAAC,CAAC,cAAc,EAAE,CAAC;YACnB,sBAAW,CAAC,IAAI,CAAC,2BAA2B,CAAC,CAAC;QAClD,CAAC,CAAC,CAAC;QACH,OAAO,CAAC,WAAW,CAAC,YAAY,CAAC,CAAC;QAClC,YAAY,CAAC,KAAK,EAAE,CAAC;KACxB;AACL,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"removeComments": true,
"preserveConstEnums": true,
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noEmitOnError": true,
"strictNullChecks": false,
"target": "es2015",
"sourceMap": true,
"declaration": true
},
"include": [
"**/*.ts"
]
}

View File

@@ -0,0 +1,79 @@
body,
html {
width: 100%;
height: 100%;
-webkit-user-select: none;
user-select: none;
-webkit-app-region: drag;
}
body {
margin: 0;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
color: #333;
background-color: #eee;
font-size: 12px;
font-family: 'Helvetica', 'Arial', 'ヒラギノ角ゴ Pro W3', 'Hiragino Kaku Gothic Pro', 'メイリオ', Meiryo, ' Pゴシック', 'MS PGothic', sans-serif;
}
.logo {
width: 200px;
-webkit-user-select: none;
user-select: none;
}
.title,
.copyright,
.description {
margin: 0.2em;
}
.clickable {
cursor: pointer;
}
.description {
margin-bottom: 1em;
text-align: center;
}
.versions {
border-collapse: collapse;
margin-top: 1em;
}
.copyright,
.versions {
color: #999;
}
.buttons {
margin-bottom: 1em;
text-align: center;
}
.buttons button {
margin-top: 1em;
width: 100px;
height: 24px;
}
.link {
cursor: pointer;
color: #80a0c2;
}
.bug-report-link {
position: absolute;
right: 0.5em;
bottom: 0.5em;
}
.clickable,
.bug-report-link,
.buttons button {
-webkit-app-region: no-drag;
}

339
src/app/badge/LICENSE Normal file
View File

@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@@ -0,0 +1,130 @@
'use strict';
module.exports = class BadgeGenerator {
constructor(win, opts = {}, systemAccentTheme) {
const defaultStyle = {
decimals: 0,
systemAccentTheme,
};
this.win = win;
this.style = Object.assign(defaultStyle, opts);
}
generate(number, updateColor) {
if (!number) return;
let opts = JSON.stringify(this.style);
if (updateColor) {
opts = JSON.stringify(this.style);
}
return this.win.webContents.executeJavaScript(`window.drawBadge = function ${this.drawBadge}; window.drawBadge(${number}, ${opts});`);
}
drawBadge(number, style) {
if (typeof style?.color !== 'string') {
throw new TypeError(`Invalid color specified\nExpected: string\nGot: ${typeof style?.color}`);
}
if (/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/gm.test(style?.fontColor)) {
style.fontColor = rgbToHex.apply(null, [...[...style.fontColor.matchAll(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/gm)].flat().slice(1, -1)]);
}
if (/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/gm.test(style?.color)) {
style.color = rgbToHex.apply(null, [...[...style.color.matchAll(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/gm)].flat().slice(1, -1)]);
}
if (!/^#[0-9A-F]{6}$/i.test(style?.fontColor)) {
style.fontColor = 'auto';
}
style.font = style?.font ?? '62px Microsoft Yahei';
style.fontColor = style?.fontColor ?? 'auto';
style.radius = style?.radius ?? 48;
style.fit = style?.fit ?? false;
style.useSystemAccentTheme = style?.useSystemAccentTheme ?? false;
style.decimals = style?.decimals === undefined || isNaN(style.decimals) ? 0 : style.decimals;
style.max = style?.max ?? 99;
const radius = style.radius;
const img = document.createElement('canvas');
img.width = Math.ceil(radius * 2);
img.height = Math.ceil(radius * 2);
img.ctx = img.getContext('2d');
img.radius = radius;
img.number = number;
const accentColor = style.systemAccentTheme;
if (style?.useSystemAccentTheme) {
style.color = accentColor;
style.fontColor = getTextColor(accentColor);
}
if (style.fontColor === 'auto') {
style.fontColor = getTextColor(accentColor);
}
img.displayStyle = style;
img.draw = function () {
let fontScale, fontWidth, fontSize, integer;
this.width = Math.ceil(this.radius * 2);
this.height = Math.ceil(this.radius * 2);
this.ctx.clearRect(0, 0, this.width, this.height);
this.ctx.fillStyle = this.displayStyle.color;
this.ctx.beginPath();
this.ctx.arc(radius, radius, radius, 0, Math.PI * 2);
this.ctx.fill();
this.ctx.font = this.displayStyle.font;
this.ctx.textAlign = 'center';
this.ctx.textBaseline = 'middle';
this.ctx.fillStyle = this.displayStyle.fontColor;
integer = this.number.toFixed(this.displayStyle.decimals);
fontSize = Number(/[0-9.]+/.exec(this.ctx.font)[0]);
if (integer > style.max) {
if (this.displayStyle.fit) {
fontSize = fontSize * 1.175;
integer = `${style.max}+`;
} else {
this.ctx.font = this.ctx.font.replace(/\d+/, Number(this.ctx.font.match(/\d+/)[0]) / 1.175);
integer = `${style.max}+`;
}
}
if (!this.displayStyle.fit || isNaN(fontSize)) {
this.ctx.fillText(integer, radius, radius);
} else {
fontWidth = this.ctx.measureText(integer).width;
fontScale = (Math.cos(Math.atan(fontSize / fontWidth)) * this.radius * 2 / fontWidth);
this.ctx.save(); // Save the canvas state
this.ctx.translate(radius, radius); // Center the text
this.ctx.scale(fontScale, fontScale); // Apply scaling for fitting
this.ctx.fillText(integer, 0, 0); // Draw scaled text
this.ctx.restore(); // Restore canvas to default stateF
}
return this;
};
function getTextColor(bgColor) {
// Convert hex color to RGB values
const red = parseInt(bgColor.substr(1, 2), 16);
const green = parseInt(bgColor.substr(3, 2), 16);
const blue = parseInt(bgColor.substr(5, 2), 16);
// Calculate perceived brightness using the luminosity algorithm
const brightness = (0.2126 * red) + (0.7152 * green) + (0.0722 * blue);
// Return white or black based on the perceived brightness
return (brightness > 128) ? '#000000' : '#FFFFFF';
}
function rgbToHex(r, g, b) {
const red = parseInt(r);
const green = parseInt(g);
const blue = parseInt(b);
const rgb = blue | (green << 8) | (red << 16);
return '#' + rgb.toString(16);
}
img.draw();
return img.toDataURL();
}
};

160
src/app/badge/index.js Normal file
View File

@@ -0,0 +1,160 @@
const { nativeImage, ipcMain, systemPreferences } = require('electron');
const BadgeGenerator = require('./badgeGenerator.js');
const { execSync } = require('child_process');
let badgeDescription = 'New notification';
let UPDATE_BADGE_EVENT;
let invokeType = 'send';
let additionalFunc = () => {
// Empty for now...
};
let currentOverlayIcon = { image: null, badgeDescription };
let currentNumber = null;
/**
* @example const badgeOptions = {
* fontColor: '#000000',
* font: '62px Microsoft Yahei',
* color: '#000000',
* radius: 48,
* updateBadgeEvent: 'notificationCount',
* badgeDescription: 'Unread Notifications',
* invokeType: 'handle',
* max: 9,
* fit: false,
* useSystemAccentTheme: true,
* additionalFunc: (count) => {
* console.log(`Received ${count} new notifications!`);
* },
* };
*
* new Badge(win, badgeOptions);
* @since 1.0.0
* @param {Electron.BrowserWindow} win
* @param {object} badgeOptions
* @returns {void}
*/
module.exports = class Badge {
constructor(win, opts = {}) {
this.win = win;
this.opts = opts;
// Get native accent color
const accentColor = getNativeAccentColor();
this.generator = new BadgeGenerator(win, opts, accentColor);
if (process.platform === 'win32' || process.platform === 'darwin') {
systemPreferences.on('accent-color-changed', () => {
const newAccentColor = getNativeAccentColor();
this.generator = new BadgeGenerator(win, opts, newAccentColor);
this.generator.generate(currentNumber, true);
this.update(currentNumber);
});
}
if (typeof opts?.updateBadgeEvent !== 'string') {
throw new TypeError(`Invalid IPC event handler name specified.\nExpected: string\nGot: ${typeof opts?.updateBadgeEvent}`);
}
UPDATE_BADGE_EVENT = opts?.updateBadgeEvent ?? 'update-badge';
badgeDescription = opts?.badgeDescription ?? UPDATE_BADGE_EVENT;
invokeType = opts?.invokeType ?? 'send';
additionalFunc = opts?.additionalFunc ?? additionalFunc;
this.initListeners();
// If win is a bowserview, change to this.win.webContents instead
this.win.on('closed', () => { this.win = null; });
if (process.platform === 'win32' || process.platform === 'darwin') {
this.win.on('show', () => { this.win.setOverlayIcon(currentOverlayIcon.image, currentOverlayIcon.badgeDescription); });
}
}
update(badgeNumber) {
if (typeof badgeNumber !== 'number' && badgeNumber != null) {
throw new TypeError(`Invalid badgeNumber specified.\nExpected: number\nGot: ${typeof badgeNumber}`);
}
if (badgeNumber) {
this.generator.generate(badgeNumber).then((base64) => {
const image = nativeImage.createFromDataURL(base64);
currentOverlayIcon = {
image,
badgeDescription,
};
if (process.platform === 'win32' || process.platform === 'darwin') {
this.win.setOverlayIcon(currentOverlayIcon.image, currentOverlayIcon.badgeDescription);
}
currentNumber = badgeNumber;
});
} else {
currentOverlayIcon = {
image: null,
badgeDescription,
};
if (process.platform === 'win32' || process.platform === 'darwin') {
this.win.setOverlayIcon(currentOverlayIcon.image, currentOverlayIcon.badgeDescription);
}
}
}
initListeners() {
if (invokeType.includes('send')) {
ipcMain.on(UPDATE_BADGE_EVENT, (event, badgeNumber) => {
if (this.win) {
this.update(badgeNumber);
additionalFunc(badgeNumber);
}
event.returnValue = 'success';
});
} else {
ipcMain.handle(UPDATE_BADGE_EVENT, (event, badgeNumber) => {
if (this.win) {
this.update(badgeNumber);
additionalFunc(badgeNumber);
}
event.returnValue = 'success';
});
}
}
};
function getNativeAccentColor() {
try {
if (process.platform === 'win32' || process.platform === 'darwin') {
return `#${systemPreferences.getAccentColor()}`;
} else if (process.platform === 'linux') {
return getLinuxAccentColor();
}
} catch (error) {
console.warn('Failed to fetch native accent color, using default:', error);
return '#4cc2ff'; // Fallback color
}
}
function getLinuxAccentColor() {
try {
// GNOME: Use gsettings to fetch theme's accent color
const color = execSync('gsettings get org.gnome.desktop.interface gtk-color-scheme')
.toString()
.match(/bg_color:\s*#([0-9a-fA-F]{6})/);
return color ? `#${color[1]}` : '#4cc2ff';
} catch {
// KDE: Use a default or parse kdeglobals
try {
const kdeColor = execSync("grep 'AccentColor=' ~/.config/kdeglobals | cut -d'=' -f2").toString().trim();
return kdeColor ? `#${kdeColor}` : '#4cc2ff';
} catch {
return '#4cc2ff';
}
}
}
function rgbToHex(r, g, b) {
const red = parseInt(r);
const green = parseInt(g);
const blue = parseInt(b);
const rgb = blue | (green << 8) | (red << 16);
return '#' + rgb.toString(16).padStart(6, '0');
}

432
src/app/context-menu/index.d.ts vendored Normal file
View File

@@ -0,0 +1,432 @@
import {
type BrowserWindow,
type BrowserView,
type ContextMenuParams,
type MenuItemConstructorOptions,
type Event as ElectronEvent,
type WebContents,
} from 'electron';
export type Labels = {
/**
@default 'Learn Spelling'
*/
readonly learnSpelling?: string;
/**
The placeholder `{selection}` will be replaced by the currently selected text.
@default 'Look Up “{selection}”'
*/
readonly lookUpSelection?: string;
/**
@default 'Search with Google'
*/
readonly searchWithGoogle?: string;
/**
@default 'Cut'
*/
readonly cut?: string;
/**
@default 'Copy'
*/
readonly copy?: string;
/**
@default 'Paste'
*/
readonly paste?: string;
/**
@default 'Select All'
*/
readonly selectAll?: string;
/**
@default 'Save Image'
*/
readonly saveImage?: string;
/**
@default 'Save Image As…'
*/
readonly saveImageAs?: string;
/**
@default 'Save Video'
*/
readonly saveVideo?: string;
/**
@default 'Save Video As…'
*/
readonly saveVideoAs?: string;
/**
@default 'Copy Link'
*/
readonly copyLink?: string;
/**
@default 'Save Link As…'
*/
readonly saveLinkAs?: string;
/**
@default 'Copy Image'
*/
readonly copyImage?: string;
/**
@default 'Copy Image Address'
*/
readonly copyImageAddress?: string;
/**
@default 'Copy Video Address'
*/
readonly copyVideoAddress?: string;
/**
@default 'Inspect Element'
*/
readonly inspect?: string;
/**
@default 'Services'
*/
readonly services?: string;
};
export type ActionOptions = {
/**
Apply a transformation to the content of the action.
If you use this on `cut`, `copy`, or `paste`, they will convert rich text to plain text.
*/
readonly transform?: (content: string) => string;
};
export type Actions = {
readonly separator: () => MenuItemConstructorOptions;
readonly learnSpelling: (options: ActionOptions) => MenuItemConstructorOptions;
readonly lookUpSelection: (options: ActionOptions) => MenuItemConstructorOptions;
readonly searchWithGoogle: (options: ActionOptions) => MenuItemConstructorOptions;
readonly cut: (options: ActionOptions) => MenuItemConstructorOptions;
readonly copy: (options: ActionOptions) => MenuItemConstructorOptions;
readonly paste: (options: ActionOptions) => MenuItemConstructorOptions;
readonly selectAll: (options: ActionOptions) => MenuItemConstructorOptions;
readonly saveImage: (options: ActionOptions) => MenuItemConstructorOptions;
readonly saveImageAs: (options: ActionOptions) => MenuItemConstructorOptions;
readonly saveVideo: (options: ActionOptions) => MenuItemConstructorOptions;
readonly saveVideoAs: (options: ActionOptions) => MenuItemConstructorOptions;
readonly copyLink: (options: ActionOptions) => MenuItemConstructorOptions;
readonly copyImage: (options: ActionOptions) => MenuItemConstructorOptions;
readonly copyImageAddress: (options: ActionOptions) => MenuItemConstructorOptions;
readonly copyVideoAddress: (options: ActionOptions) => MenuItemConstructorOptions;
readonly inspect: () => MenuItemConstructorOptions;
readonly services: () => MenuItemConstructorOptions;
};
export type Options = {
/**
Window or WebView to add the context menu to.
When not specified, the context menu will be added to all existing and new windows.
*/
readonly window?: BrowserWindow | BrowserView | Electron.WebviewTag | WebContents;
/**
Should return an array of [menu items](https://electronjs.org/docs/api/menu-item) to be prepended to the context menu.
`MenuItem` labels may contain the placeholder `{selection}` which will be replaced by the currently selected text as described in `options.labels`.
*/
readonly prepend?: (
defaultActions: Actions,
parameters: ContextMenuParams,
browserWindow: BrowserWindow | BrowserView | Electron.WebviewTag | WebContents,
event: ElectronEvent
) => MenuItemConstructorOptions[];
/**
Should return an array of [menu items](https://electronjs.org/docs/api/menu-item) to be appended to the context menu.
`MenuItem` labels may contain the placeholder `{selection}` which will be replaced by the currently selected text as described in `options.labels`.
*/
readonly append?: (
defaultActions: Actions,
parameters: ContextMenuParams,
browserWindow: BrowserWindow | BrowserView | Electron.WebviewTag | WebContents,
event: ElectronEvent
) => MenuItemConstructorOptions[];
/**
Show the `Learn Spelling {selection}` menu item when right-clicking text.
Even if `true`, the `spellcheck` preference in browser window must still be enabled. It will also only show when right-clicking misspelled words.
@default true
*/
readonly showLearnSpelling?: boolean;
/**
Show the `Look Up {selection}` menu item when right-clicking text.
@default true
*/
readonly showLookUpSelection?: boolean;
/**
Show the `Search with Google` menu item when right-clicking text.
@default true
*/
readonly showSearchWithGoogle?: boolean;
/**
Show the `Select All` menu item when right-clicking in a window.
Default: `false` on macOS, `true` on Windows and Linux
*/
readonly showSelectAll?: boolean;
/**
Show the `Copy Image` menu item when right-clicking on an image.
@default true
*/
readonly showCopyImage?: boolean;
/**
Show the `Copy Image Address` menu item when right-clicking on an image.
@default false
*/
readonly showCopyImageAddress?: boolean;
/**
Show the `Save Image` menu item when right-clicking on an image.
@default false
*/
readonly showSaveImage?: boolean;
/**
Show the `Save Image As…` menu item when right-clicking on an image.
@default false
*/
readonly showSaveImageAs?: boolean;
/**
Show the `Copy Video Address` menu item when right-clicking on a video.
@default false
*/
readonly showCopyVideoAddress?: boolean;
/**
Show the `Save Video` menu item when right-clicking on a video.
@default false
*/
readonly showSaveVideo?: boolean;
/**
Show the `Save Video As…` menu item when right-clicking on a video.
@default false
*/
readonly showSaveVideoAs?: boolean;
/**
Show the `Copy Link` menu item when right-clicking on a link.
@default true
*/
readonly showCopyLink?: boolean;
/**
Show the `Save Link As…` menu item when right-clicking on a link.
@default false
*/
readonly showSaveLinkAs?: boolean;
/**
Force enable or disable the `Inspect Element` menu item.
Default: [Only in development](https://github.com/sindresorhus/electron-is-dev)
*/
readonly showInspectElement?: boolean;
/**
Show the system `Services` submenu on macOS.
@default false
*/
readonly showServices?: boolean;
/**
Override labels for the default menu items. Useful for i18n.
The placeholder `{selection}` may be used in any label, and will be replaced by the currently selected text, trimmed to a maximum of 25 characters length. This is useful when localizing the `Look Up “{selection}”` menu item, but can also be used in custom menu items, for example, to implement a `Search Google for “{selection}”` menu item. If there is no selection, the `{selection}` placeholder will be replaced by an empty string. Normally this placeholder is only useful for menu items which will only be shown when there is text selected. This can be checked using `visible: parameters.selectionText.trim().length > 0` when implementing a custom menu item.
@default {}
@example
```
{
labels: {
copy: 'Configured Copy',
saveImageAs: 'Configured Save Image As…'
}
}
```
*/
readonly labels?: Labels;
/**
Determines whether or not to show the menu.
Can be useful if you for example have other code presenting a context menu in some contexts.
@example
```
{
// Doesn't show the menu if the element is editable
shouldShowMenu: (event, parameters) => !parameters.isEditable
}
```
*/
readonly shouldShowMenu?: (
event: ElectronEvent,
parameters: ContextMenuParams
) => boolean;
/**
This option lets you manually pick what menu items to include. It's meant for advanced needs. The default menu with the other options should be enough for most use-cases, and it ensures correct behavior, for example, correct order of menu items. So prefer the `append` and `prepend` option instead of `menu` whenever possible.
The function passed to this option is expected to return an array of [`MenuItem` constructor options](https://electronjs.org/docs/api/menu-item/).
The first argument the function receives is an array of default actions that can be used. These actions are functions that can take an object with a transform property (except for `separator` and `inspect`). The transform function will be passed the content of the action and can modify it if needed. If you use `transform` on `cut`, `copy`, or `paste`, they will convert rich text to plain text.
The second argument is [this `parameters` object](https://electronjs.org/docs/api/web-contents/#event-context-menu).
The third argument is the [BrowserWindow](https://electronjs.org/docs/api/browser-window/) the context menu was requested for.
The fourth argument is an Array of menu items for dictionary suggestions. This should be used if you wish to implement spellcheck in your custom menu.
The last argument is the event object passed to the `context-menu` event in web contents.
Even though you include an action, it will still only be shown/enabled when appropriate. For example, the `saveImage` action is only shown when right-clicking an image.
`MenuItem` labels may contain the placeholder `{selection}` which will be replaced by the currently selected text as described in `options.labels`.
The following options are ignored when `menu` is used:
- `showLearnSpelling`
- `showLookUpSelection`
- `showSearchWithGoogle`
- `showSelectAll`
- `showCopyImage`
- `showCopyImageAddress`
- `showSaveImageAs`
- `showCopyVideoAddress`
- `showSaveVideo`
- `showSaveVideoAs`
- `showCopyLink`
- `showSaveLinkAs`
- `showInspectElement`
- `showServices`
To get spellchecking, “Correct Automatically”, and “Learn Spelling” in the menu, please enable the `spellcheck` preference in browser window: `new BrowserWindow({webPreferences: {spellcheck: true}})`
@default [...dictionarySuggestions, defaultActions.separator(), defaultActions.separator(), defaultActions.learnSpelling(), defaultActions.separator(), defaultActions.lookUpSelection(), defaultActions.separator(),defaultActions.searchWithGoogle(), defaultActions.cut(), defaultActions.copy(), defaultActions.paste(), defaultActions.selectAll(), defaultActions.separator(), defaultActions.saveImage(), defaultActions.saveImageAs(), defaultActions.saveVideo(), defaultActions.saveVideoAs(), defaultActions.copyLink(), defaultActions.copyImage(), defaultActions.copyImageAddress(), defaultActions.separator(), defaultActions.copyLink(), defaultActions.saveLinkAs(), defaultActions.separator(), defaultActions.inspect()]
*/
readonly menu?: (
defaultActions: Actions,
parameters: ContextMenuParams,
browserWindow: BrowserWindow | BrowserView | Electron.WebviewTag | WebContents,
dictionarySuggestions: MenuItemConstructorOptions[],
event: ElectronEvent
) => MenuItemConstructorOptions[];
/**
Called when the context menu is shown.
*/
readonly onShow?: (event: ElectronEvent) => void;
/**
Called when the context menu is closed.
*/
readonly onClose?: (event: ElectronEvent) => void;
};
/**
This module gives you a nice extensible context menu with items like `Cut`/`Copy`/`Paste` for text, `Save Image` for images, and `Copy Link` for links. It also adds an `Inspect Element` menu item when in development to quickly view items in the inspector like in Chrome.
You can use this module directly in both the main and renderer process.
@example
```
import {app, BrowserWindow} from 'electron';
import contextMenu from 'electron-context-menu';
contextMenu({
showSaveImageAs: true
});
let mainWindow;
(async () => {
await app.whenReady();
mainWindow = new BrowserWindow({
webPreferences: {
spellcheck: true
}
});
})();
```
@example
```
import {app, BrowserWindow} from 'electron';
import contextMenu from 'electron-context-menu';
contextMenu({
prepend: (defaultActions, parameters, browserWindow) => [
{
label: 'Rainbow',
// Only show it when right-clicking images
visible: parameters.mediaType === 'image'
},
{
label: 'Search Google for “{selection}”',
// Only show it when right-clicking text
visible: parameters.selectionText.trim().length > 0,
click: () => {
shell.openExternal(`https://google.com/search?q=${encodeURIComponent(parameters.selectionText)}`);
}
}
]
});
let mainWindow;
(async () => {
await app.whenReady();
mainWindow = new BrowserWindow({
webPreferences: {
spellcheck: true
}
});
})();
```
The return value of `contextMenu()` is a function that disposes of the created event listeners:
@example
```
const dispose = contextMenu();
dispose();
```
*/
export default function contextMenu(options?: Options): () => void;

View File

@@ -0,0 +1,452 @@
const electron = require('electron');
const download = (win, url, options = {}) => {
const session = win.webContents.session;
const downloadItem = session.downloadURL(url);
};
const truncate = (input, maxLength, options = {}) => {
if (!input || maxLength <= 0) return '';
if (input.length <= maxLength) return input;
const { position = 'end' } = options;
const ellipsis = '…';
if (position === 'start') {
return ellipsis + input.slice(-(maxLength - 1));
} else if (position === 'middle') {
const halfLength = Math.floor((maxLength - 1) / 2);
return input.slice(0, halfLength) + ellipsis + input.slice(-halfLength);
} else { // Default to 'end'
return input.slice(0, maxLength - 1) + ellipsis;
}
}
const webContents = win => win.webContents ?? (win.id && win);
const decorateMenuItem = menuItem => (options = {}) => {
if (options.transform && !options.click) {
menuItem.transform = options.transform;
}
return menuItem;
};
const removeUnusedMenuItems = menuTemplate => {
let notDeletedPreviousElement;
return menuTemplate
.filter(menuItem => menuItem !== undefined && menuItem !== false && menuItem.visible !== false && menuItem.visible !== '')
.filter((menuItem, index, array) => {
const toDelete = menuItem.type === 'separator' && (!notDeletedPreviousElement || index === array.length - 1 || array[index + 1].type === 'separator');
notDeletedPreviousElement = toDelete ? notDeletedPreviousElement : menuItem;
return !toDelete;
});
};
const create = (win, options) => {
const handleContextMenu = (event, properties) => {
if (typeof options.shouldShowMenu === 'function' && options.shouldShowMenu(event, properties) === false) {
return;
}
const { editFlags } = properties;
const hasText = properties.selectionText.length > 0;
const isLink = Boolean(properties.linkURL);
const can = type => editFlags[`can${type}`] && hasText;
const defaultActions = {
separator: () => ({ type: 'separator' }),
learnSpelling: decorateMenuItem({
id: 'learnSpelling',
label: '&Learn Spelling',
visible: Boolean(properties.isEditable && hasText && properties.misspelledWord),
click() {
const target = webContents(win);
target.session.addWordToSpellCheckerDictionary(properties.misspelledWord);
},
}),
lookUpSelection: decorateMenuItem({
id: 'lookUpSelection',
label: 'Look Up “{selection}”',
visible: process.platform === 'darwin' && hasText && !isLink,
click() {
if (process.platform === 'darwin') {
webContents(win).showDefinitionForSelection();
}
},
}),
searchWithGoogle: decorateMenuItem({
id: 'searchWithGoogle',
label: '&Search with Google',
visible: hasText,
click() {
const url = new URL('https://www.google.com/search');
url.searchParams.set('q', properties.selectionText);
electron.shell.openExternal(url.toString());
},
}),
cut: decorateMenuItem({
id: 'cut',
label: 'Cu&t',
enabled: can('Cut'),
visible: properties.isEditable,
click(menuItem) {
const target = webContents(win);
if (!menuItem.transform && target) {
target.cut();
} else {
properties.selectionText = menuItem.transform ? menuItem.transform(properties.selectionText) : properties.selectionText;
electron.clipboard.writeText(properties.selectionText);
}
},
}),
copy: decorateMenuItem({
id: 'copy',
label: '&Copy',
enabled: can('Copy'),
visible: properties.isEditable || hasText,
click(menuItem) {
const target = webContents(win);
if (!menuItem.transform && target) {
target.copy();
} else {
properties.selectionText = menuItem.transform ? menuItem.transform(properties.selectionText) : properties.selectionText;
electron.clipboard.writeText(properties.selectionText);
}
},
}),
paste: decorateMenuItem({
id: 'paste',
label: '&Paste',
enabled: editFlags.canPaste,
visible: properties.isEditable,
click(menuItem) {
const target = webContents(win);
if (menuItem.transform) {
let clipboardContent = electron.clipboard.readText(properties.selectionText);
clipboardContent = menuItem.transform ? menuItem.transform(clipboardContent) : clipboardContent;
target.insertText(clipboardContent);
} else {
target.paste();
}
},
}),
selectAll: decorateMenuItem({
id: 'selectAll',
label: 'Select &All',
click() {
webContents(win).selectAll();
},
}),
saveImage: decorateMenuItem({
id: 'saveImage',
label: 'Save I&mage',
visible: properties.mediaType === 'image',
click(menuItem) {
properties.srcURL = menuItem.transform ? menuItem.transform(properties.srcURL) : properties.srcURL;
download(win, properties.srcURL);
},
}),
saveImageAs: decorateMenuItem({
id: 'saveImageAs',
label: 'Sa&ve Image As…',
visible: properties.mediaType === 'image',
click(menuItem) {
properties.srcURL = menuItem.transform ? menuItem.transform(properties.srcURL) : properties.srcURL;
download(win, properties.srcURL, { saveAs: true });
},
}),
saveVideo: decorateMenuItem({
id: 'saveVideo',
label: 'Save Vide&o',
visible: properties.mediaType === 'video',
click(menuItem) {
properties.srcURL = menuItem.transform ? menuItem.transform(properties.srcURL) : properties.srcURL;
download(win, properties.srcURL);
},
}),
saveVideoAs: decorateMenuItem({
id: 'saveVideoAs',
label: 'Save Video& As…',
visible: properties.mediaType === 'video',
click(menuItem) {
properties.srcURL = menuItem.transform ? menuItem.transform(properties.srcURL) : properties.srcURL;
download(win, properties.srcURL, { saveAs: true });
},
}),
copyLink: decorateMenuItem({
id: 'copyLink',
label: 'Copy Lin&k',
visible: properties.linkURL.length > 0 && properties.mediaType === 'none',
click(menuItem) {
properties.linkURL = menuItem.transform ? menuItem.transform(properties.linkURL) : properties.linkURL;
electron.clipboard.write({
bookmark: properties.linkText,
text: properties.linkURL,
});
},
}),
saveLinkAs: decorateMenuItem({
id: 'saveLinkAs',
label: 'Save Link As…',
visible: properties.linkURL.length > 0 && properties.mediaType === 'none',
click(menuItem) {
properties.linkURL = menuItem.transform ? menuItem.transform(properties.linkURL) : properties.linkURL;
download(win, properties.linkURL, { saveAs: true });
},
}),
copyImage: decorateMenuItem({
id: 'copyImage',
label: 'Cop&y Image',
visible: properties.mediaType === 'image',
click() {
webContents(win).copyImageAt(properties.x, properties.y);
},
}),
copyImageAddress: decorateMenuItem({
id: 'copyImageAddress',
label: 'C&opy Image Address',
visible: properties.mediaType === 'image',
click(menuItem) {
properties.srcURL = menuItem.transform ? menuItem.transform(properties.srcURL) : properties.srcURL;
electron.clipboard.write({
bookmark: properties.srcURL,
text: properties.srcURL,
});
},
}),
copyVideoAddress: decorateMenuItem({
id: 'copyVideoAddress',
label: 'Copy Video Ad&dress',
visible: properties.mediaType === 'video',
click(menuItem) {
properties.srcURL = menuItem.transform ? menuItem.transform(properties.srcURL) : properties.srcURL;
electron.clipboard.write({
bookmark: properties.srcURL,
text: properties.srcURL,
});
},
}),
inspect: () => ({
id: 'inspect',
label: 'I&nspect Element',
click() {
webContents(win).inspectElement(properties.x, properties.y);
if (webContents(win).isDevToolsOpened()) {
webContents(win).devToolsWebContents.focus();
}
},
}),
services: () => ({
id: 'services',
label: 'Services',
role: 'services',
visible: process.platform === 'darwin' && (properties.isEditable || hasText),
}),
};
const shouldShowInspectElement = typeof options.showInspectElement === 'boolean' ? options.showInspectElement : !electron.app;
const shouldShowSelectAll = options.showSelectAll || (options.showSelectAll !== false && process.platform !== 'darwin');
function word(suggestion) {
return {
id: 'dictionarySuggestions',
label: suggestion,
visible: Boolean(properties.isEditable && hasText && properties.misspelledWord),
click(menuItem) {
const target = webContents(win);
target.replaceMisspelling(menuItem.label);
},
};
}
let dictionarySuggestions = [];
if (hasText && properties.misspelledWord && properties.dictionarySuggestions.length > 0) {
dictionarySuggestions = properties.dictionarySuggestions.map(suggestion => word(suggestion));
} else {
dictionarySuggestions.push(
{
id: 'dictionarySuggestions',
label: 'No Guesses Found',
visible: Boolean(hasText && properties.misspelledWord),
enabled: false,
},
);
}
let menuTemplate = [
dictionarySuggestions.length > 0 && defaultActions.separator(),
...dictionarySuggestions,
defaultActions.separator(),
options.showLearnSpelling !== false && defaultActions.learnSpelling(),
defaultActions.separator(),
options.showLookUpSelection !== false && defaultActions.lookUpSelection(),
defaultActions.separator(),
options.showSearchWithGoogle !== false && defaultActions.searchWithGoogle(),
defaultActions.separator(),
defaultActions.cut(),
defaultActions.copy(),
defaultActions.paste(),
shouldShowSelectAll && defaultActions.selectAll(),
defaultActions.separator(),
options.showSaveImage && defaultActions.saveImage(),
options.showSaveImageAs && defaultActions.saveImageAs(),
options.showCopyImage !== false && defaultActions.copyImage(),
options.showCopyImageAddress && defaultActions.copyImageAddress(),
options.showSaveVideo && defaultActions.saveVideo(),
options.showSaveVideoAs && defaultActions.saveVideoAs(),
options.showCopyVideoAddress && defaultActions.copyVideoAddress(),
defaultActions.separator(),
options.showCopyLink !== false && defaultActions.copyLink(),
options.showSaveLinkAs && defaultActions.saveLinkAs(),
defaultActions.separator(),
shouldShowInspectElement && defaultActions.inspect(),
options.showServices && defaultActions.services(),
defaultActions.separator(),
];
if (options.menu) {
menuTemplate = options.menu(defaultActions, properties, win, dictionarySuggestions, event);
}
if (options.prepend) {
const result = options.prepend(defaultActions, properties, win, event);
if (Array.isArray(result)) {
menuTemplate.unshift(...result);
}
}
if (options.append) {
const result = options.append(defaultActions, properties, win, event);
if (Array.isArray(result)) {
menuTemplate.push(...result);
}
}
// Filter out leading/trailing separators
// TODO: https://github.com/electron/electron/issues/5869
menuTemplate = removeUnusedMenuItems(menuTemplate);
for (const menuItem of menuTemplate) {
// Apply custom labels for default menu items
if (options.labels && options.labels[menuItem.id]) {
menuItem.label = options.labels[menuItem.id];
}
// Replace placeholders in menu item labels
if (typeof menuItem.label === 'string' && menuItem.label.includes('{selection}')) {
const selectionString = typeof properties.selectionText === 'string' ? properties.selectionText.trim() : '';
menuItem.label = menuItem.label.replace('{selection}', truncate(selectionString, 25).replaceAll('&', '&&'));
}
}
if (menuTemplate.length > 0) {
const menu = electron.Menu.buildFromTemplate(menuTemplate);
if (typeof options.onShow === 'function') {
menu.on('menu-will-show', options.onShow);
}
if (typeof options.onClose === 'function') {
menu.on('menu-will-close', options.onClose);
}
menu.popup(win);
}
};
webContents(win).on('context-menu', handleContextMenu);
return () => {
try {
if (win.isDestroyed()) {
return;
}
} catch (error) {
return;
}
webContents(win).removeListener('context-menu', handleContextMenu);
};
};
module.exports = function contextMenu(options = {}) {
if (process.type === 'renderer') {
throw new Error('Cannot use electron-context-menu in the renderer process!');
}
let isDisposed = false;
const disposables = [];
const init = win => {
if (isDisposed) {
return;
}
const disposeMenu = create(win, options);
const disposable = () => {
disposeMenu();
};
webContents(win).once('destroyed', disposable);
};
const dispose = () => {
for (const dispose of disposables) {
dispose();
}
disposables.length = 0;
isDisposed = true;
};
if (options.window) {
const win = options.window;
// When window is a webview that has not yet finished loading webContents is not available
if (webContents(win) === undefined) {
const onDomReady = () => {
init(win);
};
const listenerFunction = win.addEventListener ?? win.addListener;
listenerFunction('dom-ready', onDomReady, { once: true });
disposables.push(() => {
win.removeEventListener('dom-ready', onDomReady, { once: true });
});
return dispose;
}
init(win);
return dispose;
}
for (const win of electron.BrowserWindow.getAllWindows()) {
init(win);
}
const onWindowCreated = (event, win) => {
init(win);
};
electron.app.on('browser-window-created', onWindowCreated);
disposables.push(() => {
electron.app.removeListener('browser-window-created', onWindowCreated);
});
return dispose;
}

View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

576
src/app/main.js Normal file
View File

@@ -0,0 +1,576 @@
const { app, BrowserWindow, BrowserView, globalShortcut, ipcMain, ipcRenderer, Tray, Menu, protocol, session } = require("electron");
const electronremote = require("@electron/remote/main");
//const asar = require('@electron/asar');
const windowStateKeeper = require("electron-window-state");
const { setupTitlebar, attachTitlebarToWindow } = require("./titlebar/main");
const openAboutWindow = require("./about-window/src/index").default;
const badge = require('./badge');
const contextMenu = require('./context-menu');
const asarUpdater = require('./utils/asarUpdater');
//const loadCRX = require('./utils/loadCRX');
const log4js = require("log4js");
const path = require("path");
const fs = require("fs");
const os = require("os");
require('v8-compile-cache');
const packageJson = require(path.join(__dirname, '..', '..', 'package.json'));
// isUpdaing:
global.isUpdating = false;
// App Info:
global.appInfo = {
name: app.getName(),
version: app.getVersion(),
license: packageJson.license,
deeplink: 'bsky'
}
// Paths:
global.paths = {
app_root: app.getAppPath(),
app: path.join(app.getAppPath(), 'src'),
data: os.platform() === 'win32' ? path.join(os.homedir(), 'AppData', 'Roaming', global.appInfo.name) : os.platform() === 'darwin' ? path.join(os.homedir(), 'Library', 'Application Support', global.appInfo.name) : path.join(os.homedir(), '.config', global.appInfo.name),
home: os.homedir(),
temp: path.join(os.tmpdir(), global.appInfo.name),
};
global.paths.updateDir = path.join(global.paths.data, 'update');
// URLs:
global.urls = {
main: 'https://bsky.app'
};
// Settings urls:
global.settings = {
general: `${global.urls.main}/settings`,
account: `${global.urls.main}/settings/account`,
appearance: `${global.urls.main}/settings/appearance`,
privacy: `${global.urls.main}/settings/privacy-and-security`,
};
// Badge options:
const badgeOptions = {
fontColor: '#FFFFFF', // The font color
font: '62px Microsoft Yahei', // The font and its size. You shouldn't have to change this at all
color: '#FF0000', // The background color
radius: 48, // The radius for the badge circle. You shouldn't have to change this at all
useSystemAccentTheme: true, // Use the system accent color for the badge
updateBadgeEvent: 'ui:badgeCount', // The IPC event name to listen on
badgeDescription: 'Unread Notifications', // The badge description
invokeType: 'send', // The IPC event type
max: 9, // The maximum integer allowed for the badge. Anything above this will have "+" added to the end of it.
fit: false, // Useful for multi-digit numbers. For single digits keep this set to false
additionalFunc: (count) => {
// An additional function to run whenever the IPC event fires. It has a count parameter which is the number that the badge was set to.
//console.log(`Received ${count} new notifications!`);
},
};
/* Logging */
const logFileName = 'BSKY-DESKTOP';
const logFile = path.join(global.paths.data, `${logFileName}.log`);
log4js.configure({
appenders: {
stdout: { type: "stdout" },
bskydesktop: {
type: "file",
filename: `${logFile}`,
backups: 5,
}
},
categories: {
default: {
appenders: ["stdout", "bskydesktop"],
level: "debug"
}
}
});
const logger = log4js.getLogger("bskydesktop");
logger.level = fs.existsSync(path.join(global.paths.data, '.dev')) || fs.existsSync(path.join(global.paths.data, '.debug')) ? "debug" : "info";
// if logfile already exists, rename it unles the lock file is present
if (fs.existsSync(logFile) && !fs.existsSync(path.join(global.paths.data, 'lockfile'))) {
const stats = fs.statSync(logFile);
const mtime = new Date(stats.mtime);
const today = new Date();
// If the log file is from a different day or the secconds is more than 5, rename it
if (mtime.getDate() !== today.getDate() || mtime.getSeconds() + 5 < today.getSeconds()) {
fs.renameSync(logFile, path.join(global.paths.data, `${logFileName}.${mtime.toISOString().split('T')[0]}.log`));
};
};
logger.log("Starting Bsky Desktop");
// Create data directory if it does not exist:
if (!fs.existsSync(global.paths.data)) {
logger.info("Creating Data Directory");
fs.mkdirSync(global.paths.data, { recursive: true });
};
// Create temp directory if it does not exist:
if (!fs.existsSync(global.paths.temp)) {
logger.info("Creating Temp Directory");
fs.mkdirSync(global.paths.temp, { recursive: true });
};
// Create update directory if it does not exist:
if (!fs.existsSync(global.paths.updateDir)) {
logger.info("Creating Update Directory");
fs.mkdirSync(global.paths.updateDir, { recursive: true });
};
// improve performance on linux?
if (process.platform !== "win32" && process.platform !== "darwin") {
logger.log("Disabling Hardware Acceleration and Transparent Visuals");
app.commandLine.appendSwitch("disable-transparent-visuals");
app.commandLine.appendSwitch("disable-gpu");
app.disableHardwareAcceleration();
}
// setup the titlebar main process:
setupTitlebar();
// Disable reload and F5 if not in dev mode:
if (process.env.NODE_ENV !== 'development') {
app.on('browser-window-focus', function () {
globalShortcut.register("CommandOrControl+R", () => {
//console.log("CommandOrControl+R is pressed: Shortcut Disabled");
});
globalShortcut.register("F5", () => {
//console.log("F5 is pressed: Shortcut Disabled");
});
});
app.on('browser-window-blur', function () {
globalShortcut.unregister('CommandOrControl+R');
globalShortcut.unregister('F5');
});
};
// create main window
function createWindow() {
logger.log("Creating windowStateKeeper");
const mainWindowState = windowStateKeeper({
defaultWidth: 1340,
defaultHeight: 800,
fullScreen: false,
maximize: true,
});
logger.log("Creating splash screen");
const splash = (global.splash = new BrowserWindow({
width: 400,
height: 400,
frame: false,
show: false,
icon: path.join(global.paths.app, 'ui', 'images', 'logo.png'),
alwaysOnTop: true,
skipTaskbar: true,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
}));
splash.loadFile(path.join(global.paths.app, 'ui', 'splash.html'));
logger.log("Creating Main Window");
const mainWindow = (global.mainWindow = new BrowserWindow({
x: mainWindowState.x,
y: mainWindowState.y,
width: mainWindowState.width,
height: mainWindowState.height,
minWidth: 800,
minHeight: 600,
frame: false,
show: false,
icon: path.join(global.paths.app, 'ui', 'images', 'logo.png'),
titleBarStyle: 'hidden',
titleBarOverlay: true,
webPreferences: {
nodeIntegration: true,
contextIsolation: true,
preload: path.join(global.paths.app, 'ui', 'preload-titlebar.js'),
}
}));
mainWindowState.manage(mainWindow);
mainWindow.loadFile(path.join(global.paths.app, 'ui', 'titlebar.html'));
mainWindow.hide();
const PageView = (global.PageView = new BrowserView({
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(global.paths.app, 'ui', 'preload.js'),
session: global.session,
},
}));
mainWindow.setBrowserView(PageView);
PageView.webContents.loadURL(global.urls.main);
PageView.setBounds({
x: 0,
y: 30,
width: mainWindow.getBounds().width,
height: mainWindow.getBounds().height - 30,
});
mainWindow.on("resize", () => {
PageView.setBounds({
x: 0,
y: 30,
width: mainWindow.getBounds().width,
height: mainWindow.getBounds().height - 30,
});
});
// Context Menu:
contextMenu({
labels: {
showSaveImage: 'Download Image',
showSaveVideo: 'Download Video',
showSaveAudio: 'Download Audio',
showCopyLink: 'Copy Link',
showCopyImage: 'Copy Image',
showInspectElement: 'Inspect Element'
},
showSelectAll: false,
showSaveImage: true,
showSaveVideo: true,
showSaveAudio: true,
showCopyLink: true,
showCopyImage: false,
showInspectElement: !app.isPackaged,
window: PageView
});
// Badge count: (use mainWindow as that shows the badge on the taskbar)
new badge(mainWindow, badgeOptions);
logger.log("Main Window Created, Showing splashscreen");
splash.show();
//mainWindow.show();
logger.log("Attaching Titlebar to Main Window");
attachTitlebarToWindow(mainWindow);
// DevTools:
//mainWindow.webContents.openDevTools();
//PageView.webContents.openDevTools();
//splash.webContents.openDevTools();
logger.log("Initializing @electron/remote");
electronremote.initialize();
electronremote.enable(mainWindow.webContents);
electronremote.enable(PageView.webContents);
// PageView Events:
PageView.webContents.on('did-finish-load', () => {
if (!global.isUpdating) {
// Show the main window
mainWindow.show();
// Hide the splash screen
splash.destroy();
};
});
PageView.webContents.setWindowOpenHandler(({ url }) => {
new BrowserWindow({ show: true, autoHideMenuBar: true }).loadURL(url);
return { action: 'deny' };
});
// Log PageView navigations:
/*PageView.webContents.on('will-navigate', (event, url) => {
logger.log(`Navigating to: ${url}`);
});
PageView.webContents.on('did-navigate-in-page', (event, url) => {
logger.log(`Navigated to: ${url}`);
});*/
};
function showAboutWindow() {
openAboutWindow({
icon_path: path.join(global.paths.app, 'ui', 'images', 'bsky-logo.svg'),
package_json_dir: global.paths.app_root,
product_name: global.appInfo.name,
//open_devtools: process.env.NODE_ENV !== 'production',
use_version_info: [
['Application Version', `${global.appInfo.version}`],
],
license: `MIT, GPL-2.0, GPL-3.0, ${global.appInfo.license}`,
});
};
function createTray() {
logger.log("Creating Tray");
const tray = new Tray(path.join(global.paths.app, 'ui', 'images', 'logo.png'));
tray.setToolTip('Bsky Desktop');
tray.setContextMenu(Menu.buildFromTemplate([
{ label: global.appInfo.name, enabled: false },
{ type: 'separator' },
{
label: 'About', click() {
showAboutWindow();
}
},
{ label: 'Quit', role: 'quit', click() { app.quit(); } }
]));
tray.on('click', () => {
if (mainWindow.isVisible()) {
mainWindow.hide();
} else {
mainWindow.show();
}
});
};
// Handle deeplinks:
function handleDeeplink(commandLine) {
logger.debug(commandLine);
let uri;
try {
// Extract the last element in the array
uri = commandLine.pop();
if (uri.startsWith(`${global.appInfo.deeplink}://`)) {
logger.debug(`[DEEPLINK] Found URI: ${uri}`);
uri = uri.split('/');
} else {
uri = ["none"];
}
} catch (error) {
uri = ["none"];
}
logger.debug(`[DEEPLINK] Parsing URI: ${uri.join('/')}`);
switch (uri[2]) {
case "about":
logger.log("[DEEPLINK] Show About Window");
showAboutWindow();
break;
case "settings":
switch (uri[3]) {
case "general":
logger.log("[DEEPLINK] Open General Settings");
global.PageView.webContents.send('ui:openSettings', 'general');
break;
case "account":
logger.log("[DEEPLINK] Open Account Settings");
global.PageView.webContents.send('ui:openSettings', 'account');
break;
case "appearance":
logger.log("[DEEPLINK] Open Appearance Settings");
global.PageView.webContents.send('ui:openSettings', 'appearance');
break;
case "privacy":
logger.log("[DEEPLINK] Open Privacy Settings");
global.PageView.webContents.send('ui:openSettings', 'privacy-and-security');
break;
default:
logger.warn("[DEEPLINK] Unknown settings command");
break;
};
break;
case "notiftest":
global.PageView.webContents.send('ui:notif', { title: 'Updater', message: 'Update downloaded', options: { position: 'topRight', timeout: 5000, layout: 2, color: 'blue' } });
break;
default:
if (uri[0] !== 'none') {
logger.warn("[DEEPLINK] Unknown command");
}
break;
};
};
// Hanle ui: protocol,
protocol.registerSchemesAsPrivileged([
{
scheme: 'ui',
privileges: {
secure: true,
supportFetchAPI: true,
bypassCSP: true
}
}
]);
// Main App Events:
app.whenReady().then(() => {
logger.log("App Ready, Ensuring singleInstanceLock and registering deeplink");
const gotTheLock = app.requestSingleInstanceLock();
if (gotTheLock) {
logger.log("SingleInstanceLock Acquired, Registering deeplink");
if (process.defaultApp) {
if (process.argv.length >= 2) {
app.setAsDefaultProtocolClient(global.appInfo.deeplink, process.execPath, [path.resolve(process.argv[1])])
}
} else {
app.setAsDefaultProtocolClient(global.appInfo.deeplink)
};
if (!process.defaultApp && process.argv.length >= 2) {
logger.log("Handling deeplink from commandline");
handleDeeplink(process.argv);
};
app.on('second-instance', (event, commandLine, workingDirectory) => {
logger.log("Second Instance Detected, handling");
handleDeeplink(commandLine);
/*if (global.mainWindow) {
if (global.mainWindow.isMinimized()) global.mainWindow.restore();
global.mainWindow.focus();
};*/
});
// Create persistent session for the app:
const ses = session.fromPath(path.join(global.paths.data, 'session'), {
cache: true,
partition: 'persist:bsky',
allowRunningInsecureContent: false,
contextIsolation: true,
enableRemoteModule: true,
nodeIntegration: false,
sandbox: true,
spellcheck: true,
webSecurity: true,
worldSafeExecuteJavaScript: true,
preload: path.join(global.paths.app, 'ui', 'preload.js'),
});
// Set UserAgent:
ses.setUserAgent(`Mozilla/5.0 bsky-desktop/${global.appInfo.version} (Electron:${process.versions.electron};) Chrome:${process.versions.chrome};`);
// Handle ui: protocol,
ses.protocol.handle('ui', (req) => {
// Log the incoming request URL for debugging
//console.log('Request URL:', req.url);
// Construct the correct file path
const pathToMedia = path.join(__dirname, '..', 'ui', req.url.substring(5));
//console.log('Path to media:', pathToMedia); // Log the resolved path
// Determine MIME type based on the file extension
const mimeType = req.url.endsWith('.css') ? 'text/css' :
req.url.endsWith('.js') ? 'text/javascript' :
req.url.endsWith('.png') ? 'image/png' :
req.url.endsWith('.svg') ? 'image/svg+xml' :
req.url.endsWith('.html') ? 'text/html' : 'application/octet-stream'; // Default binary mime type
try {
// Attempt to read the file synchronously
const media = fs.readFileSync(pathToMedia);
// Log success and return the response
//console.log('File found and served successfully');
return new Response(media, { // Pass the Buffer (binary data) as the body
status: 200,
headers: {
'Content-Type': mimeType,
'Access-Control-Allow-Origin': '*'
}
});
} catch (error) {
// Log the error if file is not found
console.error('Error reading file:', error);
return new Response('File not found', { // Send plain text error if file not found
status: 404,
headers: { 'Content-Type': 'text/plain' }
});
}
});
// Set session:
global.session = ses;
// Initialize the updater:
logger.log("Initializing Updater");
asarUpdater.init();
// updater events:
asarUpdater.on('available', (task) => {
//console.log('Update availible for', task)
logger.log("Update availible for", task.name);
global.PageView.webContents.send('ui:notif', JSON.stringify({ title: 'Update', message: 'An update is available' }));
if (global.splash) global.splash.webContents.send('ui:progtext', { title: 'Update Available', subtitle: 'An update is available! Downloading...' });
global.isUpdating = true;
});
asarUpdater.on('not-available', (task) => {
//console.log('not-available', task);
logger.log("No Updates Available for", task);
});
asarUpdater.on('progress', (task, p) => {
console.log(task.name, p);
if (global.splash) global.splash.webContents.send('ui:progtext', { title: 'Downloading Update', subtitle: 'Downloading update...' });
if (global.splash) global.splash.webContents.send('ui:progbar', { reason: 'update', prog: p });
});
asarUpdater.on('downloaded', (task) => {
//console.log('downloaded', task);
logger.log("Downloaded Update for,", task.name);
global.PageView.webContents.send('ui:notif', JSON.stringify({ title: 'Update Downloaded', message: 'Restarting to apply update...' }));
if (global.splash) global.splash.webContents.send('ui:progtext', { title: 'Update Downloaded', subtitle: 'Restarting to apply update...' });
});
asarUpdater.on('completed', (manifest, tasks) => {
console.log('completed', manifest, tasks);
if (tasks.length === 0) {
setTimeout(() => {
logger.log("Quitting and Installing Update");
asarUpdater.quitAndInstall();
}, 5000);
};
//app.quit()
});
asarUpdater.on('error', (err) => {
//console.error(err);
logger.error(err);
//app.quit()
});
// Set the feed URL (only works in packaged app):
if (app.isPackaged) {
logger.log("Setting Feed URL for app.asar");
asarUpdater.setFeedURL(path.join(global.paths.app_root), 'https://cdn.oxmc.me/internal/bsky-desktop/update/core');
};
//Check for updates:
logger.log("Checking for Updates");
if (app.isPackaged) {
const UPDATE_CHECK = 1000 * 60 * 60 * 4 // 4 hours
setInterval(() => {
//asarUpdater.checkForUpdates();
}, UPDATE_CHECK);
//asarUpdater.checkForUpdates();
} else {
logger.warn("Not checking for updates as app is not packaged");
};
// Handle ipc for render:
ipcMain.on('close-app', (event, arg) => {
app.quit();
});
createWindow();
createTray();
} else {
logger.log("Failed to get singleInstanceLock, Quitting");
app.quit();
};
});
app.on('open-url', (event, url) => {
event.preventDefault();
handleDeeplink([url]);
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
};
});
app.on('will-quit', () => {
globalShortcut.unregisterAll();
});
app.on('before-quit', () => {
logger.log('[Before Quit] Shutting down logger and quitting');
log4js.shutdown();
});

21
src/app/titlebar/LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Alex Torres
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,26 @@
import { Event } from '../common/event';
import { IDisposable } from '../common/lifecycle';
/** A zoom index, e.g. 1, 2, 3 */
export declare function setZoomLevel(zoomLevel: number, isTrusted: boolean): void;
export declare function getZoomLevel(): number;
/** Returns the time (in ms) since the zoom level was changed */
export declare function getTimeSinceLastZoomLevelChanged(): number;
export declare function onDidChangeZoomLevel(callback: (zoomLevel: number) => void): IDisposable;
/** The zoom scale for an index, e.g. 1, 1.2, 1.4 */
export declare function getZoomFactor(): number;
export declare function setZoomFactor(zoomFactor: number): void;
export declare function getPixelRatio(): number;
export declare function setFullscreen(fullscreen: boolean): void;
export declare function isFullscreen(): boolean;
export declare const onDidChangeFullscreen: Event<void>;
export declare const isIE: boolean;
export declare const isEdge: boolean;
export declare const isEdgeOrIE: boolean;
export declare const isOpera: boolean;
export declare const isFirefox: boolean;
export declare const isWebKit: boolean;
export declare const isChrome: boolean;
export declare const isSafari: boolean;
export declare const isWebkitWebView: boolean;
export declare const isIPad: boolean;
export declare const isEdgeWebView: boolean;

View File

@@ -0,0 +1,317 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isEdgeWebView = exports.isIPad = exports.isWebkitWebView = exports.isSafari = exports.isChrome = exports.isWebKit = exports.isFirefox = exports.isOpera = exports.isEdgeOrIE = exports.isEdge = exports.isIE = exports.onDidChangeFullscreen = exports.isFullscreen = exports.setFullscreen = exports.getPixelRatio = exports.setZoomFactor = exports.getZoomFactor = exports.onDidChangeZoomLevel = exports.getTimeSinceLastZoomLevelChanged = exports.getZoomLevel = exports.setZoomLevel = void 0;
const event_1 = require("../common/event");
class WindowManager {
constructor() {
this._zoomLevel = 0;
this._lastZoomLevelChangeTime = 0;
this._onDidChangeZoomLevel = new (_get__("event_1").Emitter)();
this.onDidChangeZoomLevel = this._onDidChangeZoomLevel.event;
// --- Zoom Factor
this._zoomFactor = 0;
// --- Fullscreen
this._fullscreen = false;
this._onDidChangeFullscreen = new (_get__("event_1").Emitter)();
this.onDidChangeFullscreen = this._onDidChangeFullscreen.event;
}
getZoomLevel() {
return this._zoomLevel;
}
getTimeSinceLastZoomLevelChanged() {
return Date.now() - this._lastZoomLevelChangeTime;
}
setZoomLevel(zoomLevel, isTrusted) {
if (this._zoomLevel === zoomLevel) {
return;
}
this._zoomLevel = zoomLevel;
// See https://github.com/Microsoft/vscode/issues/26151
this._lastZoomLevelChangeTime = isTrusted ? 0 : Date.now();
this._onDidChangeZoomLevel.fire(this._zoomLevel);
}
getZoomFactor() {
return this._zoomFactor;
}
setZoomFactor(zoomFactor) {
this._zoomFactor = zoomFactor;
}
// --- Pixel Ratio
getPixelRatio() {
const ctx = document.createElement('canvas').getContext('2d');
const dpr = window.devicePixelRatio || 1;
const bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
return dpr / bsr;
}
setFullscreen(fullscreen) {
if (this._fullscreen === fullscreen) {
return;
}
this._fullscreen = fullscreen;
this._onDidChangeFullscreen.fire();
}
isFullscreen() {
return this._fullscreen;
}
}
_get__("WindowManager").INSTANCE = new (_get__("WindowManager"))();
/** A zoom index, e.g. 1, 2, 3 */
function setZoomLevel(zoomLevel, isTrusted) {
_get__("WindowManager").INSTANCE.setZoomLevel(zoomLevel, isTrusted);
}
exports.setZoomLevel = _get__("setZoomLevel");
function getZoomLevel() {
return _get__("WindowManager").INSTANCE.getZoomLevel();
}
exports.getZoomLevel = _get__("getZoomLevel");
/** Returns the time (in ms) since the zoom level was changed */
function getTimeSinceLastZoomLevelChanged() {
return _get__("WindowManager").INSTANCE.getTimeSinceLastZoomLevelChanged();
}
exports.getTimeSinceLastZoomLevelChanged = _get__("getTimeSinceLastZoomLevelChanged");
function onDidChangeZoomLevel(callback) {
return _get__("WindowManager").INSTANCE.onDidChangeZoomLevel(callback);
}
exports.onDidChangeZoomLevel = _get__("onDidChangeZoomLevel");
/** The zoom scale for an index, e.g. 1, 1.2, 1.4 */
function getZoomFactor() {
return _get__("WindowManager").INSTANCE.getZoomFactor();
}
exports.getZoomFactor = _get__("getZoomFactor");
function setZoomFactor(zoomFactor) {
_get__("WindowManager").INSTANCE.setZoomFactor(zoomFactor);
}
exports.setZoomFactor = _get__("setZoomFactor");
function getPixelRatio() {
return _get__("WindowManager").INSTANCE.getPixelRatio();
}
exports.getPixelRatio = _get__("getPixelRatio");
function setFullscreen(fullscreen) {
_get__("WindowManager").INSTANCE.setFullscreen(fullscreen);
}
exports.setFullscreen = _get__("setFullscreen");
function isFullscreen() {
return _get__("WindowManager").INSTANCE.isFullscreen();
}
exports.isFullscreen = _get__("isFullscreen");
exports.onDidChangeFullscreen = _get__("WindowManager").INSTANCE.onDidChangeFullscreen;
const userAgent = navigator.userAgent;
exports.isIE = _get__("userAgent").indexOf('Trident') >= 0;
exports.isEdge = _get__("userAgent").indexOf('Edge/') >= 0;
exports.isEdgeOrIE = exports.isIE || exports.isEdge;
exports.isOpera = _get__("userAgent").indexOf('Opera') >= 0;
exports.isFirefox = _get__("userAgent").indexOf('Firefox') >= 0;
exports.isWebKit = _get__("userAgent").indexOf('AppleWebKit') >= 0;
exports.isChrome = _get__("userAgent").indexOf('Chrome') >= 0;
exports.isSafari = !exports.isChrome && _get__("userAgent").indexOf('Safari') >= 0;
exports.isWebkitWebView = !exports.isChrome && !exports.isSafari && exports.isWebKit;
exports.isIPad = _get__("userAgent").indexOf('iPad') >= 0;
exports.isEdgeWebView = exports.isEdge && _get__("userAgent").indexOf('WebView/') >= 0;
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "event_1":
return event_1;
case "WindowManager":
return WindowManager;
case "setZoomLevel":
return setZoomLevel;
case "getZoomLevel":
return getZoomLevel;
case "getTimeSinceLastZoomLevelChanged":
return getTimeSinceLastZoomLevelChanged;
case "onDidChangeZoomLevel":
return onDidChangeZoomLevel;
case "getZoomFactor":
return getZoomFactor;
case "setZoomFactor":
return setZoomFactor;
case "getPixelRatio":
return getPixelRatio;
case "setFullscreen":
return setFullscreen;
case "isFullscreen":
return isFullscreen;
case "userAgent":
return userAgent;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

View File

@@ -0,0 +1,12 @@
import { Event } from '../common/event';
export type EventHandler = HTMLElement | HTMLDocument | Window;
export interface IDomEvent {
<K extends keyof HTMLElementEventMap>(element: EventHandler, type: K, useCapture?: boolean): Event<HTMLElementEventMap[K]>;
(element: EventHandler, type: string, useCapture?: boolean): Event<any>;
}
export declare const domEvent: IDomEvent;
export interface CancellableEvent {
preventDefault(): any;
stopPropagation(): any;
}
export declare function stop<T extends CancellableEvent>(event: Event<T>): Event<T>;

View File

@@ -0,0 +1,215 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.stop = exports.domEvent = void 0;
const event_1 = require("../common/event");
const domEvent = (element, type, useCapture) => {
const fn = e => emitter.fire(e);
const emitter = new (_get__("event_1").Emitter)({
onFirstListenerAdd: () => {
element.addEventListener(type, fn, useCapture);
},
onLastListenerRemove: () => {
element.removeEventListener(type, fn, useCapture);
}
});
return emitter.event;
};
exports.domEvent = _get__("domEvent");
function stop(event) {
return _get__("event_1").Event.map(event, e => {
e.preventDefault();
e.stopPropagation();
return e;
});
}
exports.stop = _get__("stop");
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "event_1":
return event_1;
case "domEvent":
return domEvent;
case "stop":
return stop;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

View File

@@ -0,0 +1,38 @@
import { KeyCode, SimpleKeybinding } from '../common/keyCodes';
export declare function getCodeForKeyCode(keyCode: KeyCode): number;
export interface IKeyboardEvent {
readonly browserEvent: KeyboardEvent;
readonly target: HTMLElement;
readonly ctrlKey: boolean;
readonly shiftKey: boolean;
readonly altKey: boolean;
readonly metaKey: boolean;
readonly keyCode: KeyCode;
readonly code: string;
/**
* @internal
*/
toKeybinding(): SimpleKeybinding;
equals(keybinding: number): boolean;
preventDefault(): void;
stopPropagation(): void;
}
export declare class StandardKeyboardEvent implements IKeyboardEvent {
readonly browserEvent: KeyboardEvent;
readonly target: HTMLElement;
readonly ctrlKey: boolean;
readonly shiftKey: boolean;
readonly altKey: boolean;
readonly metaKey: boolean;
readonly keyCode: KeyCode;
readonly code: string;
private _asKeybinding;
private _asRuntimeKeybinding;
constructor(source: KeyboardEvent);
preventDefault(): void;
stopPropagation(): void;
toKeybinding(): SimpleKeybinding;
equals(other: number): boolean;
private _computeKeybinding;
private _computeRuntimeKeybinding;
}

View File

@@ -0,0 +1,462 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
var __createBinding = this && this.__createBinding || (Object.create ? function (o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = {
enumerable: true,
get: function () {
return m[k];
}
};
}
Object.defineProperty(o, k2, desc);
} : function (o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function (o, v) {
Object.defineProperty(o, "default", {
enumerable: true,
value: v
});
} : function (o, v) {
o["default"] = v;
});
var __importStar = this && this.__importStar || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) _get__("__createBinding")(result, mod, k);
_get__("__setModuleDefault")(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.StandardKeyboardEvent = exports.getCodeForKeyCode = void 0;
const keyCodes_1 = require("../common/keyCodes");
const platform = _get__("__importStar")(require("../common/platform"));
const KEY_CODE_MAP = new Array(230);
const INVERSE_KEY_CODE_MAP = new Array(112 /* KeyCode.MAX_VALUE */);
(function () {
for (let i = 0; i < _get__("INVERSE_KEY_CODE_MAP").length; i++) {
_get__("INVERSE_KEY_CODE_MAP")[i] = 0;
}
function define(code, keyCode) {
_get__("KEY_CODE_MAP")[code] = keyCode;
_get__("INVERSE_KEY_CODE_MAP")[keyCode] = code;
}
define(3, 7 /* KeyCode.PauseBreak */); // VK_CANCEL 0x03 Control-break processing
define(8, 1 /* KeyCode.Backspace */);
define(9, 2 /* KeyCode.Tab */);
define(13, 3 /* KeyCode.Enter */);
define(16, 4 /* KeyCode.Shift */);
define(17, 5 /* KeyCode.Ctrl */);
define(18, 6 /* KeyCode.Alt */);
define(19, 7 /* KeyCode.PauseBreak */);
define(20, 8 /* KeyCode.CapsLock */);
define(27, 9 /* KeyCode.Escape */);
define(32, 10 /* KeyCode.Space */);
define(33, 11 /* KeyCode.PageUp */);
define(34, 12 /* KeyCode.PageDown */);
define(35, 13 /* KeyCode.End */);
define(36, 14 /* KeyCode.Home */);
define(37, 15 /* KeyCode.LeftArrow */);
define(38, 16 /* KeyCode.UpArrow */);
define(39, 17 /* KeyCode.RightArrow */);
define(40, 18 /* KeyCode.DownArrow */);
define(45, 19 /* KeyCode.Insert */);
define(46, 20 /* KeyCode.Delete */);
define(48, 21 /* KeyCode.KEY_0 */);
define(49, 22 /* KeyCode.KEY_1 */);
define(50, 23 /* KeyCode.KEY_2 */);
define(51, 24 /* KeyCode.KEY_3 */);
define(52, 25 /* KeyCode.KEY_4 */);
define(53, 26 /* KeyCode.KEY_5 */);
define(54, 27 /* KeyCode.KEY_6 */);
define(55, 28 /* KeyCode.KEY_7 */);
define(56, 29 /* KeyCode.KEY_8 */);
define(57, 30 /* KeyCode.KEY_9 */);
define(65, 31 /* KeyCode.KEY_A */);
define(66, 32 /* KeyCode.KEY_B */);
define(67, 33 /* KeyCode.KEY_C */);
define(68, 34 /* KeyCode.KEY_D */);
define(69, 35 /* KeyCode.KEY_E */);
define(70, 36 /* KeyCode.KEY_F */);
define(71, 37 /* KeyCode.KEY_G */);
define(72, 38 /* KeyCode.KEY_H */);
define(73, 39 /* KeyCode.KEY_I */);
define(74, 40 /* KeyCode.KEY_J */);
define(75, 41 /* KeyCode.KEY_K */);
define(76, 42 /* KeyCode.KEY_L */);
define(77, 43 /* KeyCode.KEY_M */);
define(78, 44 /* KeyCode.KEY_N */);
define(79, 45 /* KeyCode.KEY_O */);
define(80, 46 /* KeyCode.KEY_P */);
define(81, 47 /* KeyCode.KEY_Q */);
define(82, 48 /* KeyCode.KEY_R */);
define(83, 49 /* KeyCode.KEY_S */);
define(84, 50 /* KeyCode.KEY_T */);
define(85, 51 /* KeyCode.KEY_U */);
define(86, 52 /* KeyCode.KEY_V */);
define(87, 53 /* KeyCode.KEY_W */);
define(88, 54 /* KeyCode.KEY_X */);
define(89, 55 /* KeyCode.KEY_Y */);
define(90, 56 /* KeyCode.KEY_Z */);
define(93, 58 /* KeyCode.ContextMenu */);
define(96, 93 /* KeyCode.NUMPAD_0 */);
define(97, 94 /* KeyCode.NUMPAD_1 */);
define(98, 95 /* KeyCode.NUMPAD_2 */);
define(99, 96 /* KeyCode.NUMPAD_3 */);
define(100, 97 /* KeyCode.NUMPAD_4 */);
define(101, 98 /* KeyCode.NUMPAD_5 */);
define(102, 99 /* KeyCode.NUMPAD_6 */);
define(103, 100 /* KeyCode.NUMPAD_7 */);
define(104, 101 /* KeyCode.NUMPAD_8 */);
define(105, 102 /* KeyCode.NUMPAD_9 */);
define(106, 103 /* KeyCode.NUMPAD_MULTIPLY */);
define(107, 104 /* KeyCode.NUMPAD_ADD */);
define(108, 105 /* KeyCode.NUMPAD_SEPARATOR */);
define(109, 106 /* KeyCode.NUMPAD_SUBTRACT */);
define(110, 107 /* KeyCode.NUMPAD_DECIMAL */);
define(111, 108 /* KeyCode.NUMPAD_DIVIDE */);
define(112, 59 /* KeyCode.F1 */);
define(113, 60 /* KeyCode.F2 */);
define(114, 61 /* KeyCode.F3 */);
define(115, 62 /* KeyCode.F4 */);
define(116, 63 /* KeyCode.F5 */);
define(117, 64 /* KeyCode.F6 */);
define(118, 65 /* KeyCode.F7 */);
define(119, 66 /* KeyCode.F8 */);
define(120, 67 /* KeyCode.F9 */);
define(121, 68 /* KeyCode.F10 */);
define(122, 69 /* KeyCode.F11 */);
define(123, 70 /* KeyCode.F12 */);
define(124, 71 /* KeyCode.F13 */);
define(125, 72 /* KeyCode.F14 */);
define(126, 73 /* KeyCode.F15 */);
define(127, 74 /* KeyCode.F16 */);
define(128, 75 /* KeyCode.F17 */);
define(129, 76 /* KeyCode.F18 */);
define(130, 77 /* KeyCode.F19 */);
define(144, 78 /* KeyCode.NumLock */);
define(145, 79 /* KeyCode.ScrollLock */);
define(186, 80 /* KeyCode.US_SEMICOLON */);
define(187, 81 /* KeyCode.US_EQUAL */);
define(188, 82 /* KeyCode.US_COMMA */);
define(189, 83 /* KeyCode.US_MINUS */);
define(190, 84 /* KeyCode.US_DOT */);
define(191, 85 /* KeyCode.US_SLASH */);
define(192, 86 /* KeyCode.US_BACKTICK */);
define(193, 110 /* KeyCode.ABNT_C1 */);
define(194, 111 /* KeyCode.ABNT_C2 */);
define(219, 87 /* KeyCode.US_OPEN_SQUARE_BRACKET */);
define(220, 88 /* KeyCode.US_BACKSLASH */);
define(221, 89 /* KeyCode.US_CLOSE_SQUARE_BRACKET */);
define(222, 90 /* KeyCode.US_QUOTE */);
define(223, 91 /* KeyCode.OEM_8 */);
define(226, 92 /* KeyCode.OEM_102 */);
/**
* https://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html
* If an Input Method Editor is processing key input and the event is keydown, return 229.
*/
define(229, 109 /* KeyCode.KEY_IN_COMPOSITION */);
define(91, 57 /* KeyCode.Meta */);
if (_get__("platform").isMacintosh) {
// the two meta keys in the Mac have different key codes (91 and 93)
define(93, 57 /* KeyCode.Meta */);
} else {
define(92, 57 /* KeyCode.Meta */);
}
})();
function extractKeyCode(e) {
if (e.charCode) {
// "keypress" events mostly
const char = String.fromCharCode(e.charCode).toUpperCase();
return _get__("keyCodes_1").KeyCodeUtils.fromString(char);
}
return _get__("KEY_CODE_MAP")[e.keyCode] || 0 /* KeyCode.Unknown */;
}
function getCodeForKeyCode(keyCode) {
return _get__("INVERSE_KEY_CODE_MAP")[keyCode];
}
exports.getCodeForKeyCode = _get__("getCodeForKeyCode");
const ctrlKeyMod = _get__("platform").isMacintosh ? 256 /* KeyMod.WinCtrl */ : 2048 /* KeyMod.CtrlCmd */;
const altKeyMod = 512 /* KeyMod.Alt */;
const shiftKeyMod = 1024 /* KeyMod.Shift */;
const metaKeyMod = _get__("platform").isMacintosh ? 2048 /* KeyMod.CtrlCmd */ : 256 /* KeyMod.WinCtrl */;
class StandardKeyboardEvent {
constructor(source) {
const e = source;
this.browserEvent = e;
this.target = e.target;
this.ctrlKey = e.ctrlKey;
this.shiftKey = e.shiftKey;
this.altKey = e.altKey;
this.metaKey = e.metaKey;
this.keyCode = _get__("extractKeyCode")(e);
this.code = e.code;
// console.info(e.type + ": keyCode: " + e.keyCode + ", which: " + e.which + ", charCode: " + e.charCode + ", detail: " + e.detail + " ====> " + this.keyCode + ' -- ' + KeyCode[this.keyCode]);
this.ctrlKey = this.ctrlKey || this.keyCode === 5 /* KeyCode.Ctrl */;
this.altKey = this.altKey || this.keyCode === 6 /* KeyCode.Alt */;
this.shiftKey = this.shiftKey || this.keyCode === 4 /* KeyCode.Shift */;
this.metaKey = this.metaKey || this.keyCode === 57 /* KeyCode.Meta */;
this._asKeybinding = this._computeKeybinding();
this._asRuntimeKeybinding = this._computeRuntimeKeybinding();
}
preventDefault() {
if (this.browserEvent && this.browserEvent.preventDefault) {
this.browserEvent.preventDefault();
}
}
stopPropagation() {
if (this.browserEvent && this.browserEvent.stopPropagation) {
this.browserEvent.stopPropagation();
}
}
toKeybinding() {
return this._asRuntimeKeybinding;
}
equals(other) {
return this._asKeybinding === other;
}
_computeKeybinding() {
let key = 0 /* KeyCode.Unknown */;
if (this.keyCode !== 5 /* KeyCode.Ctrl */ && this.keyCode !== 4 /* KeyCode.Shift */ && this.keyCode !== 6 /* KeyCode.Alt */ && this.keyCode !== 57 /* KeyCode.Meta */) {
key = this.keyCode;
}
let result = 0;
if (this.ctrlKey) {
result |= _get__("ctrlKeyMod");
}
if (this.altKey) {
result |= _get__("altKeyMod");
}
if (this.shiftKey) {
result |= _get__("shiftKeyMod");
}
if (this.metaKey) {
result |= _get__("metaKeyMod");
}
result |= key;
return result;
}
_computeRuntimeKeybinding() {
let key = 0 /* KeyCode.Unknown */;
if (this.keyCode !== 5 /* KeyCode.Ctrl */ && this.keyCode !== 4 /* KeyCode.Shift */ && this.keyCode !== 6 /* KeyCode.Alt */ && this.keyCode !== 57 /* KeyCode.Meta */) {
key = this.keyCode;
}
return new (_get__("keyCodes_1").SimpleKeybinding)(this.ctrlKey, this.shiftKey, this.altKey, this.metaKey, key);
}
}
exports.StandardKeyboardEvent = _get__("StandardKeyboardEvent");
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "__createBinding":
return __createBinding;
case "__setModuleDefault":
return __setModuleDefault;
case "__importStar":
return __importStar;
case "INVERSE_KEY_CODE_MAP":
return INVERSE_KEY_CODE_MAP;
case "KEY_CODE_MAP":
return KEY_CODE_MAP;
case "platform":
return platform;
case "keyCodes_1":
return keyCodes_1;
case "getCodeForKeyCode":
return getCodeForKeyCode;
case "extractKeyCode":
return extractKeyCode;
case "ctrlKeyMod":
return ctrlKeyMod;
case "altKeyMod":
return altKeyMod;
case "shiftKeyMod":
return shiftKeyMod;
case "metaKeyMod":
return metaKeyMod;
case "StandardKeyboardEvent":
return StandardKeyboardEvent;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

View File

@@ -0,0 +1,61 @@
export interface IMouseEvent {
readonly browserEvent: MouseEvent;
readonly leftButton: boolean;
readonly middleButton: boolean;
readonly rightButton: boolean;
readonly target: HTMLElement;
readonly detail: number;
readonly posx: number;
readonly posy: number;
readonly ctrlKey: boolean;
readonly shiftKey: boolean;
readonly altKey: boolean;
readonly metaKey: boolean;
readonly timestamp: number;
preventDefault(): void;
stopPropagation(): void;
}
export declare class StandardMouseEvent implements IMouseEvent {
readonly browserEvent: MouseEvent;
readonly leftButton: boolean;
readonly middleButton: boolean;
readonly rightButton: boolean;
readonly target: HTMLElement;
detail: number;
readonly posx: number;
readonly posy: number;
readonly ctrlKey: boolean;
readonly shiftKey: boolean;
readonly altKey: boolean;
readonly metaKey: boolean;
readonly timestamp: number;
constructor(e: MouseEvent);
preventDefault(): void;
stopPropagation(): void;
}
export interface IDataTransfer {
dropEffect: string;
effectAllowed: string;
types: any[];
files: any[];
setData(type: string, data: string): void;
setDragImage(image: any, x: number, y: number): void;
getData(type: string): string;
clearData(types?: string[]): void;
}
export declare class DragMouseEvent extends StandardMouseEvent {
readonly dataTransfer: IDataTransfer;
constructor(e: MouseEvent);
}
export interface IMouseWheelEvent extends MouseEvent {
readonly wheelDelta: number;
}
export declare class StandardWheelEvent {
readonly browserEvent: IMouseWheelEvent | null;
readonly deltaY: number;
readonly deltaX: number;
readonly target: Node;
constructor(e: IMouseWheelEvent | null, deltaX?: number, deltaY?: number);
preventDefault(): void;
stopPropagation(): void;
}

View File

@@ -0,0 +1,327 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
var __createBinding = this && this.__createBinding || (Object.create ? function (o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = {
enumerable: true,
get: function () {
return m[k];
}
};
}
Object.defineProperty(o, k2, desc);
} : function (o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function (o, v) {
Object.defineProperty(o, "default", {
enumerable: true,
value: v
});
} : function (o, v) {
o["default"] = v;
});
var __importStar = this && this.__importStar || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) _get__("__createBinding")(result, mod, k);
_get__("__setModuleDefault")(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.StandardWheelEvent = exports.DragMouseEvent = exports.StandardMouseEvent = void 0;
const browser = _get__("__importStar")(require("../browser/browser"));
const platform = _get__("__importStar")(require("../common/platform"));
class StandardMouseEvent {
constructor(e) {
this.timestamp = Date.now();
this.browserEvent = e;
this.leftButton = e.button === 0;
this.middleButton = e.button === 1;
this.rightButton = e.button === 2;
this.target = e.target;
this.detail = e.detail || 1;
if (e.type === 'dblclick') {
this.detail = 2;
}
this.ctrlKey = e.ctrlKey;
this.shiftKey = e.shiftKey;
this.altKey = e.altKey;
this.metaKey = e.metaKey;
if (typeof e.pageX === 'number') {
this.posx = e.pageX;
this.posy = e.pageY;
} else {
// Probably hit by MSGestureEvent
this.posx = e.clientX + document.body.scrollLeft + document.documentElement?.scrollLeft;
this.posy = e.clientY + document.body.scrollTop + document.documentElement?.scrollTop;
}
}
preventDefault() {
if (this.browserEvent.preventDefault) {
this.browserEvent.preventDefault();
}
}
stopPropagation() {
if (this.browserEvent.stopPropagation) {
this.browserEvent.stopPropagation();
}
}
}
exports.StandardMouseEvent = _get__("StandardMouseEvent");
class DragMouseEvent extends _get__("StandardMouseEvent") {
constructor(e) {
super(e);
this.dataTransfer = e.dataTransfer;
}
}
exports.DragMouseEvent = _get__("DragMouseEvent");
class StandardWheelEvent {
constructor(e, deltaX = 0, deltaY = 0) {
this.browserEvent = e || null;
this.target = e ? e.target || e.targetNode || e.srcElement : null;
this.deltaY = deltaY;
this.deltaX = deltaX;
if (e) {
const e1 = e;
const e2 = e;
// vertical delta scroll
if (typeof e1.wheelDeltaY !== 'undefined') {
this.deltaY = e1.wheelDeltaY / 120;
} else if (typeof e2.VERTICAL_AXIS !== 'undefined' && e2.axis === e2.VERTICAL_AXIS) {
this.deltaY = -e2.detail / 3;
}
// horizontal delta scroll
if (typeof e1.wheelDeltaX !== 'undefined') {
if (_get__("browser").isSafari && _get__("platform").isWindows) {
this.deltaX = -(e1.wheelDeltaX / 120);
} else {
this.deltaX = e1.wheelDeltaX / 120;
}
} else if (typeof e2.HORIZONTAL_AXIS !== 'undefined' && e2.axis === e2.HORIZONTAL_AXIS) {
this.deltaX = -e.detail / 3;
}
// Assume a vertical scroll if nothing else worked
if (this.deltaY === 0 && this.deltaX === 0 && e.wheelDelta) {
this.deltaY = e.wheelDelta / 120;
}
}
}
preventDefault() {
if (this.browserEvent) {
if (this.browserEvent.preventDefault) {
this.browserEvent.preventDefault();
}
}
}
stopPropagation() {
if (this.browserEvent) {
if (this.browserEvent.stopPropagation) {
this.browserEvent.stopPropagation();
}
}
}
}
exports.StandardWheelEvent = _get__("StandardWheelEvent");
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "__createBinding":
return __createBinding;
case "__setModuleDefault":
return __setModuleDefault;
case "__importStar":
return __importStar;
case "StandardMouseEvent":
return StandardMouseEvent;
case "DragMouseEvent":
return DragMouseEvent;
case "browser":
return browser;
case "platform":
return platform;
case "StandardWheelEvent":
return StandardWheelEvent;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

View File

@@ -0,0 +1,39 @@
import { Disposable, IDisposable } from '../common/lifecycle';
export declare namespace EventType {
const Tap = "-monaco-gesturetap";
const Change = "-monaco-gesturechange";
const Start = "-monaco-gesturestart";
const End = "-monaco-gesturesend";
const Contextmenu = "-monaco-gesturecontextmenu";
}
export interface GestureEvent extends MouseEvent {
initialTarget: EventTarget | undefined;
translationX: number;
translationY: number;
pageX: number;
pageY: number;
tapCount: number;
}
export declare class Gesture extends Disposable {
private static readonly SCROLL_FRICTION;
private static INSTANCE;
private static readonly HOLD_DELAY;
private dispatched;
private readonly targets;
private readonly ignoreTargets;
private handle;
private readonly activeTouches;
private _lastSetTapCountTime;
private static readonly CLEAR_TAP_COUNT_TIME;
private constructor();
static addTarget(element: HTMLElement): IDisposable;
static ignoreTarget(element: HTMLElement): IDisposable;
static isTouchDevice(): boolean;
dispose(): void;
private onTouchStart;
private onTouchEnd;
private newGestureEvent;
private dispatchEvent;
private inertia;
private onTouchMove;
}

View File

@@ -0,0 +1,454 @@
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __createBinding = this && this.__createBinding || (Object.create ? function (o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = {
enumerable: true,
get: function () {
return m[k];
}
};
}
Object.defineProperty(o, k2, desc);
} : function (o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function (o, v) {
Object.defineProperty(o, "default", {
enumerable: true,
value: v
});
} : function (o, v) {
o["default"] = v;
});
var __importStar = this && this.__importStar || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) _get__("__createBinding")(result, mod, k);
_get__("__setModuleDefault")(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Gesture = exports.EventType = void 0;
const DomUtils = _get__("__importStar")(require("../common/dom"));
const arrays = _get__("__importStar")(require("../common/arrays"));
const lifecycle_1 = require("../common/lifecycle");
const linkedList_1 = require("../common/linkedList");
var EventType;
(function (EventType) {
EventType.Tap = '-monaco-gesturetap';
EventType.Change = '-monaco-gesturechange';
EventType.Start = '-monaco-gesturestart';
EventType.End = '-monaco-gesturesend';
EventType.Contextmenu = '-monaco-gesturecontextmenu';
})(_get__("EventType") || (exports.EventType = _assign__("EventType", {})));
class Gesture extends _get__("lifecycle_1").Disposable {
constructor() {
super();
this.dispatched = false;
this.targets = new (_get__("linkedList_1").LinkedList)();
this.ignoreTargets = new (_get__("linkedList_1").LinkedList)();
this.activeTouches = {};
this.handle = null;
this._lastSetTapCountTime = 0;
this._register(_get__("DomUtils").addDisposableListener(document, 'touchstart', e => this.onTouchStart(e), {
passive: false
}));
this._register(_get__("DomUtils").addDisposableListener(document, 'touchend', e => this.onTouchEnd(e)));
this._register(_get__("DomUtils").addDisposableListener(document, 'touchmove', e => this.onTouchMove(e), {
passive: false
}));
}
static addTarget(element) {
if (!_get__("Gesture").isTouchDevice()) {
return _get__("lifecycle_1").Disposable.None;
}
if (!_get__("Gesture").INSTANCE) {
_get__("Gesture").INSTANCE = new (_get__("Gesture"))();
}
const remove = _get__("Gesture").INSTANCE.targets.push(element);
return (0, _get__("lifecycle_1").toDisposable)(remove);
}
static ignoreTarget(element) {
if (!_get__("Gesture").isTouchDevice()) {
return _get__("lifecycle_1").Disposable.None;
}
if (!_get__("Gesture").INSTANCE) {
_get__("Gesture").INSTANCE = new (_get__("Gesture"))();
}
const remove = _get__("Gesture").INSTANCE.ignoreTargets.push(element);
return (0, _get__("lifecycle_1").toDisposable)(remove);
}
static isTouchDevice() {
// `'ontouchstart' in window` always evaluates to true with typescript's modern typings. This causes `window` to be
// `never` later in `window.navigator`. That's why we need the explicit `window as Window` cast
return 'ontouchstart' in window || navigator.maxTouchPoints > 0;
}
dispose() {
if (this.handle) {
this.handle.dispose();
this.handle = null;
}
super.dispose();
}
onTouchStart(e) {
const timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.
if (this.handle) {
this.handle.dispose();
this.handle = null;
}
for (let i = 0, len = e.targetTouches.length; i < len; i++) {
const touch = e.targetTouches.item(i);
this.activeTouches[touch.identifier] = {
id: touch.identifier,
initialTarget: touch.target,
initialTimeStamp: timestamp,
initialPageX: touch.pageX,
initialPageY: touch.pageY,
rollingTimestamps: [timestamp],
rollingPageX: [touch.pageX],
rollingPageY: [touch.pageY]
};
const evt = this.newGestureEvent(_get__("EventType").Start, touch.target);
evt.pageX = touch.pageX;
evt.pageY = touch.pageY;
this.dispatchEvent(evt);
}
if (this.dispatched) {
e.preventDefault();
e.stopPropagation();
this.dispatched = false;
}
}
onTouchEnd(e) {
const timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.
const activeTouchCount = Object.keys(this.activeTouches).length;
for (let i = 0, len = e.changedTouches.length; i < len; i++) {
const touch = e.changedTouches.item(i);
if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) {
console.warn('move of an UNKNOWN touch', touch);
continue;
}
const data = this.activeTouches[touch.identifier],
holdTime = Date.now() - data.initialTimeStamp;
if (holdTime < _get__("Gesture").HOLD_DELAY && Math.abs(data.initialPageX - _get__("arrays").tail(data.rollingPageX)) < 30 && Math.abs(data.initialPageY - _get__("arrays").tail(data.rollingPageY)) < 30) {
const evt = this.newGestureEvent(_get__("EventType").Tap, data.initialTarget);
evt.pageX = _get__("arrays").tail(data.rollingPageX);
evt.pageY = _get__("arrays").tail(data.rollingPageY);
this.dispatchEvent(evt);
} else if (holdTime >= _get__("Gesture").HOLD_DELAY && Math.abs(data.initialPageX - _get__("arrays").tail(data.rollingPageX)) < 30 && Math.abs(data.initialPageY - _get__("arrays").tail(data.rollingPageY)) < 30) {
const evt = this.newGestureEvent(_get__("EventType").Contextmenu, data.initialTarget);
evt.pageX = _get__("arrays").tail(data.rollingPageX);
evt.pageY = _get__("arrays").tail(data.rollingPageY);
this.dispatchEvent(evt);
} else if (activeTouchCount === 1) {
const finalX = _get__("arrays").tail(data.rollingPageX);
const finalY = _get__("arrays").tail(data.rollingPageY);
const deltaT = _get__("arrays").tail(data.rollingTimestamps) - data.rollingTimestamps[0];
const deltaX = finalX - data.rollingPageX[0];
const deltaY = finalY - data.rollingPageY[0];
}
this.dispatchEvent(this.newGestureEvent(_get__("EventType").End, data.initialTarget));
// forget about this touch
delete this.activeTouches[touch.identifier];
}
if (this.dispatched) {
e.preventDefault();
e.stopPropagation();
this.dispatched = false;
}
}
newGestureEvent(type, initialTarget) {
const event = document.createEvent('CustomEvent');
event.initEvent(type, false, true);
event.initialTarget = initialTarget;
event.tapCount = 0;
return event;
}
dispatchEvent(event) {
if (event.type === _get__("EventType").Tap) {
const currentTime = new Date().getTime();
let setTapCount = 0;
if (currentTime - this._lastSetTapCountTime > _get__("Gesture").CLEAR_TAP_COUNT_TIME) {
setTapCount = 1;
} else {
setTapCount = 2;
}
this._lastSetTapCountTime = currentTime;
event.tapCount = setTapCount;
} else if (event.type === _get__("EventType").Change || event.type === _get__("EventType").Contextmenu) {
// tap is canceled by scrolling or context menu
this._lastSetTapCountTime = 0;
}
}
inertia(dispatchTo, t1, vX, dirX, x, vY, dirY, y) {
this.handle = _get__("DomUtils").scheduleAtNextAnimationFrame(() => {
const now = Date.now();
// velocity: old speed + accel_over_time
const deltaT = now - t1;
let delta_pos_x = 0,
delta_pos_y = 0;
let stopped = true;
vX += _get__("Gesture").SCROLL_FRICTION * deltaT;
vY += _get__("Gesture").SCROLL_FRICTION * deltaT;
if (vX > 0) {
stopped = false;
delta_pos_x = dirX * vX * deltaT;
}
if (vY > 0) {
stopped = false;
delta_pos_y = dirY * vY * deltaT;
}
// dispatch translation event
const evt = this.newGestureEvent(_get__("EventType").Change);
evt.translationX = delta_pos_x;
evt.translationY = delta_pos_y;
dispatchTo.forEach(d => d.dispatchEvent(evt));
if (!stopped) {
this.inertia(dispatchTo, now, vX, dirX, x + delta_pos_x, vY, dirY, y + delta_pos_y);
}
});
}
onTouchMove(e) {
const timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.
for (let i = 0, len = e.changedTouches.length; i < len; i++) {
const touch = e.changedTouches.item(i);
if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) {
console.warn('end of an UNKNOWN touch', touch);
continue;
}
const data = this.activeTouches[touch.identifier];
const evt = this.newGestureEvent(_get__("EventType").Change, data.initialTarget);
evt.translationX = touch.pageX - _get__("arrays").tail(data.rollingPageX);
evt.translationY = touch.pageY - _get__("arrays").tail(data.rollingPageY);
evt.pageX = touch.pageX;
evt.pageY = touch.pageY;
this.dispatchEvent(evt);
// only keep a few data points, to average the final speed
if (data.rollingPageX.length > 3) {
data.rollingPageX.shift();
data.rollingPageY.shift();
data.rollingTimestamps.shift();
}
data.rollingPageX.push(touch.pageX);
data.rollingPageY.push(touch.pageY);
data.rollingTimestamps.push(timestamp);
}
if (this.dispatched) {
e.preventDefault();
e.stopPropagation();
this.dispatched = false;
}
}
}
exports.Gesture = _get__("Gesture");
_get__("Gesture").SCROLL_FRICTION = -0.005;
_get__("Gesture").HOLD_DELAY = 700;
_get__("Gesture").CLEAR_TAP_COUNT_TIME = 400; // ms
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "__createBinding":
return __createBinding;
case "__setModuleDefault":
return __setModuleDefault;
case "__importStar":
return __importStar;
case "EventType":
return EventType;
case "linkedList_1":
return linkedList_1;
case "DomUtils":
return DomUtils;
case "Gesture":
return Gesture;
case "lifecycle_1":
return lifecycle_1;
case "arrays":
return arrays;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {
case "EventType":
return EventType = _value;
}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

View File

@@ -0,0 +1,10 @@
/**
* Returns the last element of an array.
* @param array The array.
* @param n Which element from the end (default is zero).
*/
export declare function tail<T>(array: ArrayLike<T>, n?: number): T;
/**
* @returns a new array with all falsy values removed. The original array IS NOT modified.
*/
export declare function coalesce<T>(array: Array<T | undefined | null>): T[];

View File

@@ -0,0 +1,210 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.coalesce = exports.tail = void 0;
/**
* Returns the last element of an array.
* @param array The array.
* @param n Which element from the end (default is zero).
*/
function tail(array, n = 0) {
return array[array.length - (1 + n)];
}
exports.tail = _get__("tail");
/**
* @returns a new array with all falsy values removed. The original array IS NOT modified.
*/
function coalesce(array) {
if (!array) {
return array;
}
return array.filter(e => !!e);
}
exports.coalesce = _get__("coalesce");
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "tail":
return tail;
case "coalesce":
return coalesce;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

35
src/app/titlebar/base/common/async.d.ts vendored Normal file
View File

@@ -0,0 +1,35 @@
import { Disposable } from '../common/lifecycle';
export declare class TimeoutTimer extends Disposable {
private _token;
constructor();
constructor(runner: () => void, timeout: number);
dispose(): void;
cancel(): void;
cancelAndSet(runner: () => void, timeout: number): void;
setIfNotSet(runner: () => void, timeout: number): void;
}
export declare class RunOnceScheduler {
protected runner: ((...args: any[]) => void) | null;
private timeoutToken;
private timeout;
private timeoutHandler;
constructor(runner: (...args: any[]) => void, timeout: number);
/**
* Dispose RunOnceScheduler
*/
dispose(): void;
/**
* Cancel current scheduled runner (if any).
*/
cancel(): void;
/**
* Cancel previous runner (if any) & schedule a new runner.
*/
schedule(delay?: number): void;
/**
* Returns true if scheduled.
*/
isScheduled(): boolean;
private onTimeout;
protected doRun(): void;
}

View File

@@ -0,0 +1,280 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.RunOnceScheduler = exports.TimeoutTimer = void 0;
const lifecycle_1 = require("../common/lifecycle");
class TimeoutTimer extends _get__("lifecycle_1").Disposable {
constructor(runner, timeout) {
super();
this._token = -1;
if (typeof runner === 'function' && typeof timeout === 'number') {
this.setIfNotSet(runner, timeout);
}
}
dispose() {
this.cancel();
super.dispose();
}
cancel() {
if (this._token !== -1) {
clearTimeout(this._token);
this._token = -1;
}
}
cancelAndSet(runner, timeout) {
this.cancel();
this._token = setTimeout(() => {
this._token = -1;
runner();
}, timeout);
}
setIfNotSet(runner, timeout) {
if (this._token !== -1) {
// timer is already set
return;
}
this._token = setTimeout(() => {
this._token = -1;
runner();
}, timeout);
}
}
exports.TimeoutTimer = _get__("TimeoutTimer");
class RunOnceScheduler {
constructor(runner, timeout) {
this.timeoutToken = -1;
this.runner = runner;
this.timeout = timeout;
this.timeoutHandler = this.onTimeout.bind(this);
}
/**
* Dispose RunOnceScheduler
*/
dispose() {
this.cancel();
this.runner = null;
}
/**
* Cancel current scheduled runner (if any).
*/
cancel() {
if (this.isScheduled()) {
clearTimeout(this.timeoutToken);
this.timeoutToken = -1;
}
}
/**
* Cancel previous runner (if any) & schedule a new runner.
*/
schedule(delay = this.timeout) {
this.cancel();
this.timeoutToken = setTimeout(this.timeoutHandler, delay);
}
/**
* Returns true if scheduled.
*/
isScheduled() {
return this.timeoutToken !== -1;
}
onTimeout() {
this.timeoutToken = -1;
if (this.runner) {
this.doRun();
}
}
doRun() {
if (this.runner) {
this.runner();
}
}
}
exports.RunOnceScheduler = _get__("RunOnceScheduler");
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "lifecycle_1":
return lifecycle_1;
case "TimeoutTimer":
return TimeoutTimer;
case "RunOnceScheduler":
return RunOnceScheduler;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

View File

@@ -0,0 +1,405 @@
/**
* An inlined enum containing useful character codes (to be used with String.charCodeAt).
* Please leave the const keyword such that it gets inlined when compiled to JavaScript!
*/
export declare const enum CharCode {
Null = 0,
/**
* The `\b` character.
*/
Backspace = 8,
/**
* The `\t` character.
*/
Tab = 9,
/**
* The `\n` character.
*/
LineFeed = 10,
/**
* The `\r` character.
*/
CarriageReturn = 13,
Space = 32,
/**
* The `!` character.
*/
ExclamationMark = 33,
/**
* The `"` character.
*/
DoubleQuote = 34,
/**
* The `#` character.
*/
Hash = 35,
/**
* The `$` character.
*/
DollarSign = 36,
/**
* The `%` character.
*/
PercentSign = 37,
/**
* The `&` character.
*/
Ampersand = 38,
/**
* The `'` character.
*/
SingleQuote = 39,
/**
* The `(` character.
*/
OpenParen = 40,
/**
* The `)` character.
*/
CloseParen = 41,
/**
* The `*` character.
*/
Asterisk = 42,
/**
* The `+` character.
*/
Plus = 43,
/**
* The `,` character.
*/
Comma = 44,
/**
* The `-` character.
*/
Dash = 45,
/**
* The `.` character.
*/
Period = 46,
/**
* The `/` character.
*/
Slash = 47,
Digit0 = 48,
Digit1 = 49,
Digit2 = 50,
Digit3 = 51,
Digit4 = 52,
Digit5 = 53,
Digit6 = 54,
Digit7 = 55,
Digit8 = 56,
Digit9 = 57,
/**
* The `:` character.
*/
Colon = 58,
/**
* The `;` character.
*/
Semicolon = 59,
/**
* The `<` character.
*/
LessThan = 60,
/**
* The `=` character.
*/
Equals = 61,
/**
* The `>` character.
*/
GreaterThan = 62,
/**
* The `?` character.
*/
QuestionMark = 63,
/**
* The `@` character.
*/
AtSign = 64,
A = 65,
B = 66,
C = 67,
D = 68,
E = 69,
F = 70,
G = 71,
H = 72,
I = 73,
J = 74,
K = 75,
L = 76,
M = 77,
N = 78,
O = 79,
P = 80,
Q = 81,
R = 82,
S = 83,
T = 84,
U = 85,
V = 86,
W = 87,
X = 88,
Y = 89,
Z = 90,
/**
* The `[` character.
*/
OpenSquareBracket = 91,
/**
* The `\` character.
*/
Backslash = 92,
/**
* The `]` character.
*/
CloseSquareBracket = 93,
/**
* The `^` character.
*/
Caret = 94,
/**
* The `_` character.
*/
Underline = 95,
/**
* The ``(`)`` character.
*/
BackTick = 96,
a = 97,
b = 98,
c = 99,
d = 100,
e = 101,
f = 102,
g = 103,
h = 104,
i = 105,
j = 106,
k = 107,
l = 108,
m = 109,
n = 110,
o = 111,
p = 112,
q = 113,
r = 114,
s = 115,
t = 116,
u = 117,
v = 118,
w = 119,
x = 120,
y = 121,
z = 122,
/**
* The `{` character.
*/
OpenCurlyBrace = 123,
/**
* The `|` character.
*/
Pipe = 124,
/**
* The `}` character.
*/
CloseCurlyBrace = 125,
/**
* The `~` character.
*/
Tilde = 126,
U_Combining_Grave_Accent = 768,// U+0300 Combining Grave Accent
U_Combining_Acute_Accent = 769,// U+0301 Combining Acute Accent
U_Combining_Circumflex_Accent = 770,// U+0302 Combining Circumflex Accent
U_Combining_Tilde = 771,// U+0303 Combining Tilde
U_Combining_Macron = 772,// U+0304 Combining Macron
U_Combining_Overline = 773,// U+0305 Combining Overline
U_Combining_Breve = 774,// U+0306 Combining Breve
U_Combining_Dot_Above = 775,// U+0307 Combining Dot Above
U_Combining_Diaeresis = 776,// U+0308 Combining Diaeresis
U_Combining_Hook_Above = 777,// U+0309 Combining Hook Above
U_Combining_Ring_Above = 778,// U+030A Combining Ring Above
U_Combining_Double_Acute_Accent = 779,// U+030B Combining Double Acute Accent
U_Combining_Caron = 780,// U+030C Combining Caron
U_Combining_Vertical_Line_Above = 781,// U+030D Combining Vertical Line Above
U_Combining_Double_Vertical_Line_Above = 782,// U+030E Combining Double Vertical Line Above
U_Combining_Double_Grave_Accent = 783,// U+030F Combining Double Grave Accent
U_Combining_Candrabindu = 784,// U+0310 Combining Candrabindu
U_Combining_Inverted_Breve = 785,// U+0311 Combining Inverted Breve
U_Combining_Turned_Comma_Above = 786,// U+0312 Combining Turned Comma Above
U_Combining_Comma_Above = 787,// U+0313 Combining Comma Above
U_Combining_Reversed_Comma_Above = 788,// U+0314 Combining Reversed Comma Above
U_Combining_Comma_Above_Right = 789,// U+0315 Combining Comma Above Right
U_Combining_Grave_Accent_Below = 790,// U+0316 Combining Grave Accent Below
U_Combining_Acute_Accent_Below = 791,// U+0317 Combining Acute Accent Below
U_Combining_Left_Tack_Below = 792,// U+0318 Combining Left Tack Below
U_Combining_Right_Tack_Below = 793,// U+0319 Combining Right Tack Below
U_Combining_Left_Angle_Above = 794,// U+031A Combining Left Angle Above
U_Combining_Horn = 795,// U+031B Combining Horn
U_Combining_Left_Half_Ring_Below = 796,// U+031C Combining Left Half Ring Below
U_Combining_Up_Tack_Below = 797,// U+031D Combining Up Tack Below
U_Combining_Down_Tack_Below = 798,// U+031E Combining Down Tack Below
U_Combining_Plus_Sign_Below = 799,// U+031F Combining Plus Sign Below
U_Combining_Minus_Sign_Below = 800,// U+0320 Combining Minus Sign Below
U_Combining_Palatalized_Hook_Below = 801,// U+0321 Combining Palatalized Hook Below
U_Combining_Retroflex_Hook_Below = 802,// U+0322 Combining Retroflex Hook Below
U_Combining_Dot_Below = 803,// U+0323 Combining Dot Below
U_Combining_Diaeresis_Below = 804,// U+0324 Combining Diaeresis Below
U_Combining_Ring_Below = 805,// U+0325 Combining Ring Below
U_Combining_Comma_Below = 806,// U+0326 Combining Comma Below
U_Combining_Cedilla = 807,// U+0327 Combining Cedilla
U_Combining_Ogonek = 808,// U+0328 Combining Ogonek
U_Combining_Vertical_Line_Below = 809,// U+0329 Combining Vertical Line Below
U_Combining_Bridge_Below = 810,// U+032A Combining Bridge Below
U_Combining_Inverted_Double_Arch_Below = 811,// U+032B Combining Inverted Double Arch Below
U_Combining_Caron_Below = 812,// U+032C Combining Caron Below
U_Combining_Circumflex_Accent_Below = 813,// U+032D Combining Circumflex Accent Below
U_Combining_Breve_Below = 814,// U+032E Combining Breve Below
U_Combining_Inverted_Breve_Below = 815,// U+032F Combining Inverted Breve Below
U_Combining_Tilde_Below = 816,// U+0330 Combining Tilde Below
U_Combining_Macron_Below = 817,// U+0331 Combining Macron Below
U_Combining_Low_Line = 818,// U+0332 Combining Low Line
U_Combining_Double_Low_Line = 819,// U+0333 Combining Double Low Line
U_Combining_Tilde_Overlay = 820,// U+0334 Combining Tilde Overlay
U_Combining_Short_Stroke_Overlay = 821,// U+0335 Combining Short Stroke Overlay
U_Combining_Long_Stroke_Overlay = 822,// U+0336 Combining Long Stroke Overlay
U_Combining_Short_Solidus_Overlay = 823,// U+0337 Combining Short Solidus Overlay
U_Combining_Long_Solidus_Overlay = 824,// U+0338 Combining Long Solidus Overlay
U_Combining_Right_Half_Ring_Below = 825,// U+0339 Combining Right Half Ring Below
U_Combining_Inverted_Bridge_Below = 826,// U+033A Combining Inverted Bridge Below
U_Combining_Square_Below = 827,// U+033B Combining Square Below
U_Combining_Seagull_Below = 828,// U+033C Combining Seagull Below
U_Combining_X_Above = 829,// U+033D Combining X Above
U_Combining_Vertical_Tilde = 830,// U+033E Combining Vertical Tilde
U_Combining_Double_Overline = 831,// U+033F Combining Double Overline
U_Combining_Grave_Tone_Mark = 832,// U+0340 Combining Grave Tone Mark
U_Combining_Acute_Tone_Mark = 833,// U+0341 Combining Acute Tone Mark
U_Combining_Greek_Perispomeni = 834,// U+0342 Combining Greek Perispomeni
U_Combining_Greek_Koronis = 835,// U+0343 Combining Greek Koronis
U_Combining_Greek_Dialytika_Tonos = 836,// U+0344 Combining Greek Dialytika Tonos
U_Combining_Greek_Ypogegrammeni = 837,// U+0345 Combining Greek Ypogegrammeni
U_Combining_Bridge_Above = 838,// U+0346 Combining Bridge Above
U_Combining_Equals_Sign_Below = 839,// U+0347 Combining Equals Sign Below
U_Combining_Double_Vertical_Line_Below = 840,// U+0348 Combining Double Vertical Line Below
U_Combining_Left_Angle_Below = 841,// U+0349 Combining Left Angle Below
U_Combining_Not_Tilde_Above = 842,// U+034A Combining Not Tilde Above
U_Combining_Homothetic_Above = 843,// U+034B Combining Homothetic Above
U_Combining_Almost_Equal_To_Above = 844,// U+034C Combining Almost Equal To Above
U_Combining_Left_Right_Arrow_Below = 845,// U+034D Combining Left Right Arrow Below
U_Combining_Upwards_Arrow_Below = 846,// U+034E Combining Upwards Arrow Below
U_Combining_Grapheme_Joiner = 847,// U+034F Combining Grapheme Joiner
U_Combining_Right_Arrowhead_Above = 848,// U+0350 Combining Right Arrowhead Above
U_Combining_Left_Half_Ring_Above = 849,// U+0351 Combining Left Half Ring Above
U_Combining_Fermata = 850,// U+0352 Combining Fermata
U_Combining_X_Below = 851,// U+0353 Combining X Below
U_Combining_Left_Arrowhead_Below = 852,// U+0354 Combining Left Arrowhead Below
U_Combining_Right_Arrowhead_Below = 853,// U+0355 Combining Right Arrowhead Below
U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below = 854,// U+0356 Combining Right Arrowhead And Up Arrowhead Below
U_Combining_Right_Half_Ring_Above = 855,// U+0357 Combining Right Half Ring Above
U_Combining_Dot_Above_Right = 856,// U+0358 Combining Dot Above Right
U_Combining_Asterisk_Below = 857,// U+0359 Combining Asterisk Below
U_Combining_Double_Ring_Below = 858,// U+035A Combining Double Ring Below
U_Combining_Zigzag_Above = 859,// U+035B Combining Zigzag Above
U_Combining_Double_Breve_Below = 860,// U+035C Combining Double Breve Below
U_Combining_Double_Breve = 861,// U+035D Combining Double Breve
U_Combining_Double_Macron = 862,// U+035E Combining Double Macron
U_Combining_Double_Macron_Below = 863,// U+035F Combining Double Macron Below
U_Combining_Double_Tilde = 864,// U+0360 Combining Double Tilde
U_Combining_Double_Inverted_Breve = 865,// U+0361 Combining Double Inverted Breve
U_Combining_Double_Rightwards_Arrow_Below = 866,// U+0362 Combining Double Rightwards Arrow Below
U_Combining_Latin_Small_Letter_A = 867,// U+0363 Combining Latin Small Letter A
U_Combining_Latin_Small_Letter_E = 868,// U+0364 Combining Latin Small Letter E
U_Combining_Latin_Small_Letter_I = 869,// U+0365 Combining Latin Small Letter I
U_Combining_Latin_Small_Letter_O = 870,// U+0366 Combining Latin Small Letter O
U_Combining_Latin_Small_Letter_U = 871,// U+0367 Combining Latin Small Letter U
U_Combining_Latin_Small_Letter_C = 872,// U+0368 Combining Latin Small Letter C
U_Combining_Latin_Small_Letter_D = 873,// U+0369 Combining Latin Small Letter D
U_Combining_Latin_Small_Letter_H = 874,// U+036A Combining Latin Small Letter H
U_Combining_Latin_Small_Letter_M = 875,// U+036B Combining Latin Small Letter M
U_Combining_Latin_Small_Letter_R = 876,// U+036C Combining Latin Small Letter R
U_Combining_Latin_Small_Letter_T = 877,// U+036D Combining Latin Small Letter T
U_Combining_Latin_Small_Letter_V = 878,// U+036E Combining Latin Small Letter V
U_Combining_Latin_Small_Letter_X = 879,// U+036F Combining Latin Small Letter X
/**
* Unicode Character 'LINE SEPARATOR' (U+2028)
* http://www.fileformat.info/info/unicode/char/2028/index.htm
*/
LINE_SEPARATOR_2028 = 8232,
U_CIRCUMFLEX = 94,// U+005E CIRCUMFLEX
U_GRAVE_ACCENT = 96,// U+0060 GRAVE ACCENT
U_DIAERESIS = 168,// U+00A8 DIAERESIS
U_MACRON = 175,// U+00AF MACRON
U_ACUTE_ACCENT = 180,// U+00B4 ACUTE ACCENT
U_CEDILLA = 184,// U+00B8 CEDILLA
U_MODIFIER_LETTER_LEFT_ARROWHEAD = 706,// U+02C2 MODIFIER LETTER LEFT ARROWHEAD
U_MODIFIER_LETTER_RIGHT_ARROWHEAD = 707,// U+02C3 MODIFIER LETTER RIGHT ARROWHEAD
U_MODIFIER_LETTER_UP_ARROWHEAD = 708,// U+02C4 MODIFIER LETTER UP ARROWHEAD
U_MODIFIER_LETTER_DOWN_ARROWHEAD = 709,// U+02C5 MODIFIER LETTER DOWN ARROWHEAD
U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING = 722,// U+02D2 MODIFIER LETTER CENTRED RIGHT HALF RING
U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING = 723,// U+02D3 MODIFIER LETTER CENTRED LEFT HALF RING
U_MODIFIER_LETTER_UP_TACK = 724,// U+02D4 MODIFIER LETTER UP TACK
U_MODIFIER_LETTER_DOWN_TACK = 725,// U+02D5 MODIFIER LETTER DOWN TACK
U_MODIFIER_LETTER_PLUS_SIGN = 726,// U+02D6 MODIFIER LETTER PLUS SIGN
U_MODIFIER_LETTER_MINUS_SIGN = 727,// U+02D7 MODIFIER LETTER MINUS SIGN
U_BREVE = 728,// U+02D8 BREVE
U_DOT_ABOVE = 729,// U+02D9 DOT ABOVE
U_RING_ABOVE = 730,// U+02DA RING ABOVE
U_OGONEK = 731,// U+02DB OGONEK
U_SMALL_TILDE = 732,// U+02DC SMALL TILDE
U_DOUBLE_ACUTE_ACCENT = 733,// U+02DD DOUBLE ACUTE ACCENT
U_MODIFIER_LETTER_RHOTIC_HOOK = 734,// U+02DE MODIFIER LETTER RHOTIC HOOK
U_MODIFIER_LETTER_CROSS_ACCENT = 735,// U+02DF MODIFIER LETTER CROSS ACCENT
U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR = 741,// U+02E5 MODIFIER LETTER EXTRA-HIGH TONE BAR
U_MODIFIER_LETTER_HIGH_TONE_BAR = 742,// U+02E6 MODIFIER LETTER HIGH TONE BAR
U_MODIFIER_LETTER_MID_TONE_BAR = 743,// U+02E7 MODIFIER LETTER MID TONE BAR
U_MODIFIER_LETTER_LOW_TONE_BAR = 744,// U+02E8 MODIFIER LETTER LOW TONE BAR
U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR = 745,// U+02E9 MODIFIER LETTER EXTRA-LOW TONE BAR
U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK = 746,// U+02EA MODIFIER LETTER YIN DEPARTING TONE MARK
U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK = 747,// U+02EB MODIFIER LETTER YANG DEPARTING TONE MARK
U_MODIFIER_LETTER_UNASPIRATED = 749,// U+02ED MODIFIER LETTER UNASPIRATED
U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD = 751,// U+02EF MODIFIER LETTER LOW DOWN ARROWHEAD
U_MODIFIER_LETTER_LOW_UP_ARROWHEAD = 752,// U+02F0 MODIFIER LETTER LOW UP ARROWHEAD
U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD = 753,// U+02F1 MODIFIER LETTER LOW LEFT ARROWHEAD
U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD = 754,// U+02F2 MODIFIER LETTER LOW RIGHT ARROWHEAD
U_MODIFIER_LETTER_LOW_RING = 755,// U+02F3 MODIFIER LETTER LOW RING
U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT = 756,// U+02F4 MODIFIER LETTER MIDDLE GRAVE ACCENT
U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT = 757,// U+02F5 MODIFIER LETTER MIDDLE DOUBLE GRAVE ACCENT
U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT = 758,// U+02F6 MODIFIER LETTER MIDDLE DOUBLE ACUTE ACCENT
U_MODIFIER_LETTER_LOW_TILDE = 759,// U+02F7 MODIFIER LETTER LOW TILDE
U_MODIFIER_LETTER_RAISED_COLON = 760,// U+02F8 MODIFIER LETTER RAISED COLON
U_MODIFIER_LETTER_BEGIN_HIGH_TONE = 761,// U+02F9 MODIFIER LETTER BEGIN HIGH TONE
U_MODIFIER_LETTER_END_HIGH_TONE = 762,// U+02FA MODIFIER LETTER END HIGH TONE
U_MODIFIER_LETTER_BEGIN_LOW_TONE = 763,// U+02FB MODIFIER LETTER BEGIN LOW TONE
U_MODIFIER_LETTER_END_LOW_TONE = 764,// U+02FC MODIFIER LETTER END LOW TONE
U_MODIFIER_LETTER_SHELF = 765,// U+02FD MODIFIER LETTER SHELF
U_MODIFIER_LETTER_OPEN_SHELF = 766,// U+02FE MODIFIER LETTER OPEN SHELF
U_MODIFIER_LETTER_LOW_LEFT_ARROW = 767,// U+02FF MODIFIER LETTER LOW LEFT ARROW
U_GREEK_LOWER_NUMERAL_SIGN = 885,// U+0375 GREEK LOWER NUMERAL SIGN
U_GREEK_TONOS = 900,// U+0384 GREEK TONOS
U_GREEK_DIALYTIKA_TONOS = 901,// U+0385 GREEK DIALYTIKA TONOS
U_GREEK_KORONIS = 8125,// U+1FBD GREEK KORONIS
U_GREEK_PSILI = 8127,// U+1FBF GREEK PSILI
U_GREEK_PERISPOMENI = 8128,// U+1FC0 GREEK PERISPOMENI
U_GREEK_DIALYTIKA_AND_PERISPOMENI = 8129,// U+1FC1 GREEK DIALYTIKA AND PERISPOMENI
U_GREEK_PSILI_AND_VARIA = 8141,// U+1FCD GREEK PSILI AND VARIA
U_GREEK_PSILI_AND_OXIA = 8142,// U+1FCE GREEK PSILI AND OXIA
U_GREEK_PSILI_AND_PERISPOMENI = 8143,// U+1FCF GREEK PSILI AND PERISPOMENI
U_GREEK_DASIA_AND_VARIA = 8157,// U+1FDD GREEK DASIA AND VARIA
U_GREEK_DASIA_AND_OXIA = 8158,// U+1FDE GREEK DASIA AND OXIA
U_GREEK_DASIA_AND_PERISPOMENI = 8159,// U+1FDF GREEK DASIA AND PERISPOMENI
U_GREEK_DIALYTIKA_AND_VARIA = 8173,// U+1FED GREEK DIALYTIKA AND VARIA
U_GREEK_DIALYTIKA_AND_OXIA = 8174,// U+1FEE GREEK DIALYTIKA AND OXIA
U_GREEK_VARIA = 8175,// U+1FEF GREEK VARIA
U_GREEK_OXIA = 8189,// U+1FFD GREEK OXIA
U_GREEK_DASIA = 8190,// U+1FFE GREEK DASIA
U_OVERLINE = 8254,// Unicode Character 'OVERLINE'
/**
* UTF-8 BOM
* Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF)
* http://www.fileformat.info/info/unicode/char/feff/index.htm
*/
UTF8_BOM = 65279
}

View File

@@ -0,0 +1,9 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
Object.defineProperty(exports, "__esModule", {
value: true
});

159
src/app/titlebar/base/common/color.d.ts vendored Normal file
View File

@@ -0,0 +1,159 @@
export declare class RGBA {
/**
* Red: integer in [0-255]
*/
readonly r: number;
/**
* Green: integer in [0-255]
*/
readonly g: number;
/**
* Blue: integer in [0-255]
*/
readonly b: number;
/**
* Alpha: float in [0-1]
*/
readonly a: number;
constructor(r: number, g: number, b: number, a?: number);
static equals(a: RGBA, b: RGBA): boolean;
}
export declare class HSLA {
/**
* Hue: integer in [0, 360]
*/
readonly h: number;
/**
* Saturation: float in [0, 1]
*/
readonly s: number;
/**
* Luminosity: float in [0, 1]
*/
readonly l: number;
/**
* Alpha: float in [0, 1]
*/
readonly a: number;
constructor(h: number, s: number, l: number, a: number);
static equals(a: HSLA, b: HSLA): boolean;
/**
* Converts an RGB color value to HSL. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes r, g, and b are contained in the set [0, 255] and
* returns h in the set [0, 360], s, and l in the set [0, 1].
*/
static fromRGBA(rgba: RGBA): HSLA;
private static _hue2rgb;
/**
* Converts an HSL color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes h in the set [0, 360] s, and l are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 255].
*/
static toRGBA(hsla: HSLA): RGBA;
}
export declare class HSVA {
/**
* Hue: integer in [0, 360]
*/
readonly h: number;
/**
* Saturation: float in [0, 1]
*/
readonly s: number;
/**
* Value: float in [0, 1]
*/
readonly v: number;
/**
* Alpha: float in [0, 1]
*/
readonly a: number;
constructor(h: number, s: number, v: number, a: number);
static equals(a: HSVA, b: HSVA): boolean;
static fromRGBA(rgba: RGBA): HSVA;
static toRGBA(hsva: HSVA): RGBA;
}
export declare class Color {
static fromHex(hex: string): Color;
readonly rgba: RGBA;
private _hsla?;
get hsla(): HSLA;
private _hsva?;
get hsva(): HSVA;
constructor(arg: RGBA | HSLA | HSVA);
equals(other: Color): boolean;
/**
* http://www.w3.org/TR/WCAG20/#relativeluminancedef
* Returns the number in the set [0, 1]. O => Darkest Black. 1 => Lightest white.
*/
getRelativeLuminance(): number;
private static _relativeLuminanceForComponent;
/**
* http://www.w3.org/TR/WCAG20/#contrast-ratiodef
* Returns the contrast ration number in the set [1, 21].
*/
getContrastRatio(another: Color): number;
/**
* http://24ways.org/2010/calculating-color-contrast
* Return 'true' if darker color otherwise 'false'
*/
isDarker(): boolean;
/**
* http://24ways.org/2010/calculating-color-contrast
* Return 'true' if lighter color otherwise 'false'
*/
isLighter(): boolean;
isLighterThan(another: Color): boolean;
isDarkerThan(another: Color): boolean;
lighten(factor: number): Color;
darken(factor: number): Color;
transparent(factor: number): Color;
isTransparent(): boolean;
isOpaque(): boolean;
opposite(): Color;
blend(c: Color): Color;
flatten(...backgrounds: Color[]): Color;
private static _flatten;
toString(): string;
static getLighterColor(of: Color, relative: Color, factor?: number): Color;
static getDarkerColor(of: Color, relative: Color, factor?: number): Color;
static readonly WHITE: Color;
static readonly BLACK: Color;
static readonly RED: Color;
static readonly BLUE: Color;
static readonly GREEN: Color;
static readonly CYAN: Color;
static readonly LIGHTGREY: Color;
static readonly TRANSPARENT: Color;
}
export declare namespace Color {
namespace Format {
namespace CSS {
function formatRGB(color: Color): string;
function formatRGBA(color: Color): string;
function formatHSL(color: Color): string;
function formatHSLA(color: Color): string;
/**
* Formats the color as #RRGGBB
*/
function formatHex(color: Color): string;
/**
* Formats the color as #RRGGBBAA
* If 'compact' is set, colors without transparancy will be printed as #RRGGBB
*/
function formatHexA(color: Color, compact?: boolean): string;
/**
* The default format will use HEX if opaque and RGBA otherwise.
*/
function format(color: Color): string | null;
/**
* Converts an Hex color value to a Color.
* returns r, g, and b are contained in the set [0, 255]
* @param hex string (#RGB, #RGBA, #RRGGBB or #RRGGBBAA).
*/
function parseHex(hex: string): Color | null;
}
}
}

View File

@@ -0,0 +1,708 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Color = exports.HSVA = exports.HSLA = exports.RGBA = void 0;
function roundFloat(number, decimalPoints) {
const decimal = Math.pow(10, decimalPoints);
return Math.round(number * decimal) / decimal;
}
class RGBA {
constructor(r, g, b, a = 1) {
this.r = Math.min(255, Math.max(0, r)) | 0;
this.g = Math.min(255, Math.max(0, g)) | 0;
this.b = Math.min(255, Math.max(0, b)) | 0;
this.a = _get__("roundFloat")(Math.max(Math.min(1, a), 0), 3);
}
static equals(a, b) {
return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a;
}
}
exports.RGBA = _get__("RGBA");
class HSLA {
constructor(h, s, l, a) {
this.h = Math.max(Math.min(360, h), 0) | 0;
this.s = _get__("roundFloat")(Math.max(Math.min(1, s), 0), 3);
this.l = _get__("roundFloat")(Math.max(Math.min(1, l), 0), 3);
this.a = _get__("roundFloat")(Math.max(Math.min(1, a), 0), 3);
}
static equals(a, b) {
return a.h === b.h && a.s === b.s && a.l === b.l && a.a === b.a;
}
/**
* Converts an RGB color value to HSL. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes r, g, and b are contained in the set [0, 255] and
* returns h in the set [0, 360], s, and l in the set [0, 1].
*/
static fromRGBA(rgba) {
const r = rgba.r / 255;
const g = rgba.g / 255;
const b = rgba.b / 255;
const a = rgba.a;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
let h = 0;
let s = 0;
const l = (min + max) / 2;
const chroma = max - min;
if (chroma > 0) {
s = Math.min(l <= 0.5 ? chroma / (2 * l) : chroma / (2 - 2 * l), 1);
switch (max) {
case r:
h = (g - b) / chroma + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / chroma + 2;
break;
case b:
h = (r - g) / chroma + 4;
break;
}
h *= 60;
h = Math.round(h);
}
return new (_get__("HSLA"))(h, s, l, a);
}
static _hue2rgb(p, q, t) {
if (t < 0) {
t += 1;
}
if (t > 1) {
t -= 1;
}
if (t < 1 / 6) {
return p + (q - p) * 6 * t;
}
if (t < 1 / 2) {
return q;
}
if (t < 2 / 3) {
return p + (q - p) * (2 / 3 - t) * 6;
}
return p;
}
/**
* Converts an HSL color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes h in the set [0, 360] s, and l are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 255].
*/
static toRGBA(hsla) {
const h = hsla.h / 360;
const {
s,
l,
a
} = hsla;
let r, g, b;
if (s === 0) {
r = g = b = l; // achromatic
} else {
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
r = _get__("HSLA")._hue2rgb(p, q, h + 1 / 3);
g = _get__("HSLA")._hue2rgb(p, q, h);
b = _get__("HSLA")._hue2rgb(p, q, h - 1 / 3);
}
return new (_get__("RGBA"))(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a);
}
}
exports.HSLA = _get__("HSLA");
class HSVA {
constructor(h, s, v, a) {
this.h = Math.max(Math.min(360, h), 0) | 0;
this.s = _get__("roundFloat")(Math.max(Math.min(1, s), 0), 3);
this.v = _get__("roundFloat")(Math.max(Math.min(1, v), 0), 3);
this.a = _get__("roundFloat")(Math.max(Math.min(1, a), 0), 3);
}
static equals(a, b) {
return a.h === b.h && a.s === b.s && a.v === b.v && a.a === b.a;
}
// from http://www.rapidtables.com/convert/color/rgb-to-hsv.htm
static fromRGBA(rgba) {
const r = rgba.r / 255;
const g = rgba.g / 255;
const b = rgba.b / 255;
const cmax = Math.max(r, g, b);
const cmin = Math.min(r, g, b);
const delta = cmax - cmin;
const s = cmax === 0 ? 0 : delta / cmax;
let m;
if (delta === 0) {
m = 0;
} else if (cmax === r) {
m = ((g - b) / delta % 6 + 6) % 6;
} else if (cmax === g) {
m = (b - r) / delta + 2;
} else {
m = (r - g) / delta + 4;
}
return new (_get__("HSVA"))(Math.round(m * 60), s, cmax, rgba.a);
}
// from http://www.rapidtables.com/convert/color/hsv-to-rgb.htm
static toRGBA(hsva) {
const {
h,
s,
v,
a
} = hsva;
const c = v * s;
const x = c * (1 - Math.abs(h / 60 % 2 - 1));
const m = v - c;
let [r, g, b] = [0, 0, 0];
if (h < 60) {
r = c;
g = x;
} else if (h < 120) {
r = x;
g = c;
} else if (h < 180) {
g = c;
b = x;
} else if (h < 240) {
g = x;
b = c;
} else if (h < 300) {
r = x;
b = c;
} else if (h < 360) {
r = c;
b = x;
}
r = Math.round((r + m) * 255);
g = Math.round((g + m) * 255);
b = Math.round((b + m) * 255);
return new (_get__("RGBA"))(r, g, b, a);
}
}
exports.HSVA = _get__("HSVA");
class Color {
static fromHex(hex) {
return _get__("Color").Format.CSS.parseHex(hex) || _get__("Color").RED;
}
get hsla() {
if (this._hsla) {
return this._hsla;
} else {
return _get__("HSLA").fromRGBA(this.rgba);
}
}
get hsva() {
if (this._hsva) {
return this._hsva;
}
return _get__("HSVA").fromRGBA(this.rgba);
}
constructor(arg) {
if (!arg) {
throw new Error('Color needs a value');
} else if (arg instanceof _get__("RGBA")) {
this.rgba = arg;
} else if (arg instanceof _get__("HSLA")) {
this._hsla = arg;
this.rgba = _get__("HSLA").toRGBA(arg);
} else if (arg instanceof _get__("HSVA")) {
this._hsva = arg;
this.rgba = _get__("HSVA").toRGBA(arg);
} else {
throw new Error('Invalid color ctor argument');
}
}
equals(other) {
return !!other && _get__("RGBA").equals(this.rgba, other.rgba) && _get__("HSLA").equals(this.hsla, other.hsla) && _get__("HSVA").equals(this.hsva, other.hsva);
}
/**
* http://www.w3.org/TR/WCAG20/#relativeluminancedef
* Returns the number in the set [0, 1]. O => Darkest Black. 1 => Lightest white.
*/
getRelativeLuminance() {
const R = _get__("Color")._relativeLuminanceForComponent(this.rgba.r);
const G = _get__("Color")._relativeLuminanceForComponent(this.rgba.g);
const B = _get__("Color")._relativeLuminanceForComponent(this.rgba.b);
const luminance = 0.2126 * R + 0.7152 * G + 0.0722 * B;
return _get__("roundFloat")(luminance, 4);
}
static _relativeLuminanceForComponent(color) {
const c = color / 255;
return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
}
/**
* http://www.w3.org/TR/WCAG20/#contrast-ratiodef
* Returns the contrast ration number in the set [1, 21].
*/
getContrastRatio(another) {
const lum1 = this.getRelativeLuminance();
const lum2 = another.getRelativeLuminance();
return lum1 > lum2 ? (lum1 + 0.05) / (lum2 + 0.05) : (lum2 + 0.05) / (lum1 + 0.05);
}
/**
* http://24ways.org/2010/calculating-color-contrast
* Return 'true' if darker color otherwise 'false'
*/
isDarker() {
const yiq = (this.rgba.r * 299 + this.rgba.g * 587 + this.rgba.b * 114) / 1000;
return yiq < 128;
}
/**
* http://24ways.org/2010/calculating-color-contrast
* Return 'true' if lighter color otherwise 'false'
*/
isLighter() {
const yiq = (this.rgba.r * 299 + this.rgba.g * 587 + this.rgba.b * 114) / 1000;
return yiq >= 128;
}
isLighterThan(another) {
const lum1 = this.getRelativeLuminance();
const lum2 = another.getRelativeLuminance();
return lum1 > lum2;
}
isDarkerThan(another) {
const lum1 = this.getRelativeLuminance();
const lum2 = another.getRelativeLuminance();
return lum1 < lum2;
}
lighten(factor) {
return new (_get__("Color"))(new (_get__("HSLA"))(this.hsla.h, this.hsla.s, this.hsla.l + this.hsla.l * factor, this.hsla.a));
}
darken(factor) {
return new (_get__("Color"))(new (_get__("HSLA"))(this.hsla.h, this.hsla.s, this.hsla.l - this.hsla.l * factor, this.hsla.a));
}
transparent(factor) {
const {
r,
g,
b,
a
} = this.rgba;
return new (_get__("Color"))(new (_get__("RGBA"))(r, g, b, a * factor));
}
isTransparent() {
return this.rgba.a === 0;
}
isOpaque() {
return this.rgba.a === 1;
}
opposite() {
return new (_get__("Color"))(new (_get__("RGBA"))(255 - this.rgba.r, 255 - this.rgba.g, 255 - this.rgba.b, this.rgba.a));
}
blend(c) {
const rgba = c.rgba;
// Convert to 0..1 opacity
const thisA = this.rgba.a;
const colorA = rgba.a;
const a = thisA + colorA * (1 - thisA);
if (a < 1e-6) {
return _get__("Color").TRANSPARENT;
}
const r = this.rgba.r * thisA / a + rgba.r * colorA * (1 - thisA) / a;
const g = this.rgba.g * thisA / a + rgba.g * colorA * (1 - thisA) / a;
const b = this.rgba.b * thisA / a + rgba.b * colorA * (1 - thisA) / a;
return new (_get__("Color"))(new (_get__("RGBA"))(r, g, b, a));
}
flatten(...backgrounds) {
const background = backgrounds.reduceRight((accumulator, color) => {
return _get__("Color")._flatten(color, accumulator);
});
return _get__("Color")._flatten(this, background);
}
static _flatten(foreground, background) {
const backgroundAlpha = 1 - foreground.rgba.a;
return new (_get__("Color"))(new (_get__("RGBA"))(backgroundAlpha * background.rgba.r + foreground.rgba.a * foreground.rgba.r, backgroundAlpha * background.rgba.g + foreground.rgba.a * foreground.rgba.g, backgroundAlpha * background.rgba.b + foreground.rgba.a * foreground.rgba.b));
}
toString() {
return '' + _get__("Color").Format.CSS.format(this);
}
static getLighterColor(of, relative, factor) {
if (of.isLighterThan(relative)) {
return of;
}
factor = factor || 0.5;
const lum1 = of.getRelativeLuminance();
const lum2 = relative.getRelativeLuminance();
factor = factor * (lum2 - lum1) / lum2;
return of.lighten(factor);
}
static getDarkerColor(of, relative, factor) {
if (of.isDarkerThan(relative)) {
return of;
}
factor = factor || 0.5;
const lum1 = of.getRelativeLuminance();
const lum2 = relative.getRelativeLuminance();
factor = factor * (lum1 - lum2) / lum1;
return of.darken(factor);
}
}
exports.Color = _get__("Color");
_get__("Color").WHITE = new (_get__("Color"))(new (_get__("RGBA"))(255, 255, 255, 1));
_get__("Color").BLACK = new (_get__("Color"))(new (_get__("RGBA"))(0, 0, 0, 1));
_get__("Color").RED = new (_get__("Color"))(new (_get__("RGBA"))(255, 0, 0, 1));
_get__("Color").BLUE = new (_get__("Color"))(new (_get__("RGBA"))(0, 0, 255, 1));
_get__("Color").GREEN = new (_get__("Color"))(new (_get__("RGBA"))(0, 255, 0, 1));
_get__("Color").CYAN = new (_get__("Color"))(new (_get__("RGBA"))(0, 255, 255, 1));
_get__("Color").LIGHTGREY = new (_get__("Color"))(new (_get__("RGBA"))(211, 211, 211, 1));
_get__("Color").TRANSPARENT = new (_get__("Color"))(new (_get__("RGBA"))(0, 0, 0, 0));
(function (Color) {
let Format;
(function (Format) {
let CSS;
(function (CSS) {
function formatRGB(color) {
if (color.rgba.a === 1) {
return `rgb(${color.rgba.r}, ${color.rgba.g}, ${color.rgba.b})`;
}
return Color.Format.CSS.formatRGBA(color);
}
CSS.formatRGB = formatRGB;
function formatRGBA(color) {
return `rgba(${color.rgba.r}, ${color.rgba.g}, ${color.rgba.b}, ${+color.rgba.a.toFixed(2)})`;
}
CSS.formatRGBA = formatRGBA;
function formatHSL(color) {
if (color.hsla.a === 1) {
return `hsl(${color.hsla.h}, ${(color.hsla.s * 100).toFixed(2)}%, ${(color.hsla.l * 100).toFixed(2)}%)`;
}
return Color.Format.CSS.formatHSLA(color);
}
CSS.formatHSL = formatHSL;
function formatHSLA(color) {
return `hsla(${color.hsla.h}, ${(color.hsla.s * 100).toFixed(2)}%, ${(color.hsla.l * 100).toFixed(2)}%, ${color.hsla.a.toFixed(2)})`;
}
CSS.formatHSLA = formatHSLA;
function _toTwoDigitHex(n) {
const r = n.toString(16);
return r.length !== 2 ? '0' + r : r;
}
/**
* Formats the color as #RRGGBB
*/
function formatHex(color) {
return `#${_toTwoDigitHex(color.rgba.r)}${_toTwoDigitHex(color.rgba.g)}${_toTwoDigitHex(color.rgba.b)}`;
}
CSS.formatHex = formatHex;
/**
* Formats the color as #RRGGBBAA
* If 'compact' is set, colors without transparancy will be printed as #RRGGBB
*/
function formatHexA(color, compact = false) {
if (compact && color.rgba.a === 1) {
return Color.Format.CSS.formatHex(color);
}
return `#${_toTwoDigitHex(color.rgba.r)}${_toTwoDigitHex(color.rgba.g)}${_toTwoDigitHex(color.rgba.b)}${_toTwoDigitHex(Math.round(color.rgba.a * 255))}`;
}
CSS.formatHexA = formatHexA;
/**
* The default format will use HEX if opaque and RGBA otherwise.
*/
function format(color) {
if (!color) {
return null;
}
if (color.isOpaque()) {
return Color.Format.CSS.formatHex(color);
}
return Color.Format.CSS.formatRGBA(color);
}
CSS.format = format;
/**
* Converts an Hex color value to a Color.
* returns r, g, and b are contained in the set [0, 255]
* @param hex string (#RGB, #RGBA, #RRGGBB or #RRGGBBAA).
*/
function parseHex(hex) {
if (!hex) {
// Invalid color
return null;
}
const length = hex.length;
if (length === 0) {
// Invalid color
return null;
}
if (hex.charCodeAt(0) !== 35 /* CharCode.Hash */) {
// Does not begin with a #
return null;
}
if (length === 7) {
// #RRGGBB format
const r = 16 * _parseHexDigit(hex.charCodeAt(1)) + _parseHexDigit(hex.charCodeAt(2));
const g = 16 * _parseHexDigit(hex.charCodeAt(3)) + _parseHexDigit(hex.charCodeAt(4));
const b = 16 * _parseHexDigit(hex.charCodeAt(5)) + _parseHexDigit(hex.charCodeAt(6));
return new Color(new (_get__("RGBA"))(r, g, b, 1));
}
if (length === 9) {
// #RRGGBBAA format
const r = 16 * _parseHexDigit(hex.charCodeAt(1)) + _parseHexDigit(hex.charCodeAt(2));
const g = 16 * _parseHexDigit(hex.charCodeAt(3)) + _parseHexDigit(hex.charCodeAt(4));
const b = 16 * _parseHexDigit(hex.charCodeAt(5)) + _parseHexDigit(hex.charCodeAt(6));
const a = 16 * _parseHexDigit(hex.charCodeAt(7)) + _parseHexDigit(hex.charCodeAt(8));
return new Color(new (_get__("RGBA"))(r, g, b, a / 255));
}
if (length === 4) {
// #RGB format
const r = _parseHexDigit(hex.charCodeAt(1));
const g = _parseHexDigit(hex.charCodeAt(2));
const b = _parseHexDigit(hex.charCodeAt(3));
return new Color(new (_get__("RGBA"))(16 * r + r, 16 * g + g, 16 * b + b));
}
if (length === 5) {
// #RGBA format
const r = _parseHexDigit(hex.charCodeAt(1));
const g = _parseHexDigit(hex.charCodeAt(2));
const b = _parseHexDigit(hex.charCodeAt(3));
const a = _parseHexDigit(hex.charCodeAt(4));
return new Color(new (_get__("RGBA"))(16 * r + r, 16 * g + g, 16 * b + b, (16 * a + a) / 255));
}
// Invalid color
return null;
}
CSS.parseHex = parseHex;
function _parseHexDigit(charCode) {
switch (charCode) {
case 48 /* CharCode.Digit0 */:
return 0;
case 49 /* CharCode.Digit1 */:
return 1;
case 50 /* CharCode.Digit2 */:
return 2;
case 51 /* CharCode.Digit3 */:
return 3;
case 52 /* CharCode.Digit4 */:
return 4;
case 53 /* CharCode.Digit5 */:
return 5;
case 54 /* CharCode.Digit6 */:
return 6;
case 55 /* CharCode.Digit7 */:
return 7;
case 56 /* CharCode.Digit8 */:
return 8;
case 57 /* CharCode.Digit9 */:
return 9;
case 97 /* CharCode.a */:
return 10;
case 65 /* CharCode.A */:
return 10;
case 98 /* CharCode.b */:
return 11;
case 66 /* CharCode.B */:
return 11;
case 99 /* CharCode.c */:
return 12;
case 67 /* CharCode.C */:
return 12;
case 100 /* CharCode.d */:
return 13;
case 68 /* CharCode.D */:
return 13;
case 101 /* CharCode.e */:
return 14;
case 69 /* CharCode.E */:
return 14;
case 102 /* CharCode.f */:
return 15;
case 70 /* CharCode.F */:
return 15;
}
return 0;
}
})(CSS = Format.CSS || (Format.CSS = {}));
})(Format = Color.Format || (Color.Format = {}));
})(_get__("Color") || (exports.Color = _assign__("Color", {})));
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "roundFloat":
return roundFloat;
case "RGBA":
return RGBA;
case "HSLA":
return HSLA;
case "HSVA":
return HSVA;
case "Color":
return Color;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {
case "Color":
return Color = _value;
}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

View File

@@ -0,0 +1,6 @@
export declare function memoize(_target: any, key: string, descriptor: any): void;
export interface IDebounceReducer<T> {
(previousValue: T, ...args: any[]): T;
}
export declare function debounce<T>(delay: number, reducer?: IDebounceReducer<T>, initialValueProvider?: () => T): Function;
export declare function throttle<T>(delay: number, reducer?: IDebounceReducer<T>, initialValueProvider?: () => T): Function;

View File

@@ -0,0 +1,300 @@
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.throttle = exports.debounce = exports.memoize = void 0;
function createDecorator(mapFn) {
return (target, key, descriptor) => {
let fnKey = null;
let fn = null;
if (typeof descriptor.value === 'function') {
fnKey = 'value';
fn = descriptor.value;
} else if (typeof descriptor.get === 'function') {
fnKey = 'get';
fn = descriptor.get;
}
if (!fn) {
throw new Error('not supported');
}
descriptor[fnKey] = mapFn(fn, key);
};
}
function memoize(_target, key, descriptor) {
let fnKey = null;
let fn = null;
if (typeof descriptor.value === 'function') {
fnKey = 'value';
fn = descriptor.value;
if (fn.length !== 0) {
console.warn('Memoize should only be used in functions with zero parameters');
}
} else if (typeof descriptor.get === 'function') {
fnKey = 'get';
fn = descriptor.get;
}
if (!fn) {
throw new Error('not supported');
}
const memoizeKey = `$memoize$${key}`;
descriptor[fnKey] = function (...args) {
if (!this.hasOwnProperty(memoizeKey)) {
Object.defineProperty(this, memoizeKey, {
configurable: false,
enumerable: false,
writable: false,
value: fn.apply(this, args)
});
}
return this[memoizeKey];
};
}
exports.memoize = _get__("memoize");
function debounce(delay, reducer, initialValueProvider) {
return _get__("createDecorator")((fn, key) => {
const timerKey = `$debounce$${key}`;
const resultKey = `$debounce$result$${key}`;
return function (...args) {
if (!this[resultKey]) {
this[resultKey] = initialValueProvider ? initialValueProvider() : undefined;
}
clearTimeout(this[timerKey]);
if (reducer) {
this[resultKey] = reducer(this[resultKey], ...args);
args = [this[resultKey]];
}
this[timerKey] = setTimeout(() => {
fn.apply(this, args);
this[resultKey] = initialValueProvider ? initialValueProvider() : undefined;
}, delay);
};
});
}
exports.debounce = _get__("debounce");
function throttle(delay, reducer, initialValueProvider) {
return _get__("createDecorator")((fn, key) => {
const timerKey = `$throttle$timer$${key}`;
const resultKey = `$throttle$result$${key}`;
const lastRunKey = `$throttle$lastRun$${key}`;
const pendingKey = `$throttle$pending$${key}`;
return function (...args) {
if (!this[resultKey]) {
this[resultKey] = initialValueProvider ? initialValueProvider() : undefined;
}
if (this[lastRunKey] === null || this[lastRunKey] === undefined) {
this[lastRunKey] = -Number.MAX_VALUE;
}
if (reducer) {
this[resultKey] = reducer(this[resultKey], ...args);
}
if (this[pendingKey]) {
return;
}
const nextTime = this[lastRunKey] + delay;
if (nextTime <= Date.now()) {
this[lastRunKey] = Date.now();
fn.apply(this, [this[resultKey]]);
this[resultKey] = initialValueProvider ? initialValueProvider() : undefined;
} else {
this[pendingKey] = true;
this[timerKey] = setTimeout(() => {
this[pendingKey] = false;
this[lastRunKey] = Date.now();
fn.apply(this, [this[resultKey]]);
this[resultKey] = initialValueProvider ? initialValueProvider() : undefined;
}, nextTime - Date.now());
}
};
});
}
exports.throttle = _get__("throttle");
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "memoize":
return memoize;
case "createDecorator":
return createDecorator;
case "debounce":
return debounce;
case "throttle":
return throttle;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

221
src/app/titlebar/base/common/dom.d.ts vendored Normal file
View File

@@ -0,0 +1,221 @@
import { IKeyboardEvent } from '../browser/keyboardEvent';
import { IMouseEvent } from '../browser/mouseEvent';
import { Emitter, Event } from '../common/event';
import { IDisposable } from '../common/lifecycle';
export declare function clearNode(node: HTMLElement): void;
export declare function removeNode(node: HTMLElement): void;
export declare function isInDOM(node: Node | null): boolean;
type ModifierKey = 'alt' | 'ctrl' | 'shift' | 'meta';
export interface IModifierKeyStatus {
altKey: boolean;
shiftKey: boolean;
ctrlKey: boolean;
metaKey: boolean;
lastKeyPressed?: ModifierKey;
lastKeyReleased?: ModifierKey;
event?: KeyboardEvent;
}
export declare class ModifierKeyEmitter extends Emitter<IModifierKeyStatus> {
private _keyStatus;
private static instance;
private constructor();
get keyStatus(): IModifierKeyStatus;
get isModifierPressed(): boolean;
/**
* Allows to explicitly reset the key status based on more knowledge (#109062)
*/
resetKeyStatus(): void;
private doResetKeyStatus;
static getInstance(): ModifierKeyEmitter;
dispose(): void;
}
export declare const hasClass: (node: HTMLElement, className: string) => boolean;
export declare const addClass: (node: HTMLElement, className: string) => void;
export declare const addClasses: (node: HTMLElement, ...classNames: string[]) => void;
export declare const removeClass: (node: HTMLElement, className: string) => void;
export declare const removeClasses: (node: HTMLElement, ...classNames: string[]) => void;
export declare const toggleClass: (node: HTMLElement, className: string, shouldHaveIt?: boolean) => void;
export declare function addDisposableListener<K extends keyof GlobalEventHandlersEventMap>(node: EventTarget, type: K, handler: (event: GlobalEventHandlersEventMap[K]) => void, useCapture?: boolean): IDisposable;
export declare function addDisposableListener(node: EventTarget, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable;
export declare function addDisposableListener(node: EventTarget, type: string, handler: (event: any) => void, options: AddEventListenerOptions): IDisposable;
export interface IAddStandardDisposableListenerSignature {
(node: HTMLElement, type: 'click', handler: (event: IMouseEvent) => void, useCapture?: boolean): IDisposable;
(node: HTMLElement, type: 'mousedown', handler: (event: IMouseEvent) => void, useCapture?: boolean): IDisposable;
(node: HTMLElement, type: 'keydown', handler: (event: IKeyboardEvent) => void, useCapture?: boolean): IDisposable;
(node: HTMLElement, type: 'keypress', handler: (event: IKeyboardEvent) => void, useCapture?: boolean): IDisposable;
(node: HTMLElement, type: 'keyup', handler: (event: IKeyboardEvent) => void, useCapture?: boolean): IDisposable;
(node: HTMLElement, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable;
}
export declare const addStandardDisposableListener: IAddStandardDisposableListenerSignature;
export declare function addDisposableNonBubblingMouseOutListener(node: Element, handler: (event: MouseEvent) => void): IDisposable;
/**
* Schedule a callback to be run at the next animation frame.
* This allows multiple parties to register callbacks that should run at the next animation frame.
* If currently in an animation frame, `runner` will be executed immediately.
* @return token that can be used to cancel the scheduled runner (only if `runner` was not executed immediately).
*/
export declare let runAtThisOrScheduleAtNextAnimationFrame: (runner: () => void, priority?: number) => IDisposable;
/**
* Schedule a callback to be run at the next animation frame.
* This allows multiple parties to register callbacks that should run at the next animation frame.
* If currently in an animation frame, `runner` will be executed at the next animation frame.
* @return token that can be used to cancel the scheduled runner.
*/
export declare let scheduleAtNextAnimationFrame: (runner: () => void, priority?: number) => IDisposable;
export declare function measure(callback: () => void): IDisposable;
export declare function modify(callback: () => void): IDisposable;
/**
* Add a throttled listener. `handler` is fired at most every 16ms or with the next animation frame (if browser supports it).
*/
export interface IEventMerger<R, E> {
(lastEvent: R | null, currentEvent: E): R;
}
export interface DOMEvent {
preventDefault(): void;
stopPropagation(): void;
}
export declare function addDisposableThrottledListener<R, E extends DOMEvent = DOMEvent>(node: any, type: string, handler: (event: R) => void, eventMerger?: IEventMerger<R, E>, minimumTimeMs?: number): IDisposable;
export declare function getComputedStyle(el: HTMLElement): CSSStyleDeclaration;
export declare function getClientArea(element: HTMLElement): Dimension;
/**
* Returns the effective zoom on a given element before window zoom level is applied
*/
export declare function getDomNodeZoomLevel(domNode: HTMLElement): number;
export declare class Dimension {
width: number;
height: number;
constructor(width: number, height: number);
static equals(a: Dimension | undefined, b: Dimension | undefined): boolean;
}
export declare function getTopLeftOffset(element: HTMLElement): {
left: number;
top: number;
};
export interface IDomNodePagePosition {
left: number;
top: number;
width: number;
height: number;
}
export declare function size(element: HTMLElement, width: number, height: number): void;
export declare function position(element: HTMLElement, top: number, right?: number, bottom?: number, left?: number, position?: string): void;
/**
* Returns the position of a dom node relative to the entire page.
*/
export declare function getDomNodePagePosition(domNode: HTMLElement): IDomNodePagePosition;
export interface IStandardWindow {
readonly scrollX: number;
readonly scrollY: number;
}
export declare const StandardWindow: IStandardWindow;
export declare function getTotalWidth(element: HTMLElement): number;
export declare function getContentWidth(element: HTMLElement): number;
export declare function getTotalScrollWidth(element: HTMLElement): number;
export declare function getContentHeight(element: HTMLElement): number;
export declare function getTotalHeight(element: HTMLElement): number;
export declare function getLargestChildWidth(parent: HTMLElement, children: HTMLElement[]): number;
export declare function isAncestor(testChild: Node | null, testAncestor: Node | null): boolean;
export declare function findParentWithClass(node: HTMLElement, clazz: string, stopAtClazzOrNode?: string | HTMLElement): HTMLElement | null;
export declare function createStyleSheet(container?: HTMLElement): HTMLStyleElement;
export declare function createCSSRule(selector: string, cssText: string, style?: HTMLStyleElement): void;
export declare function removeCSSRulesContainingSelector(ruleName: string, style?: HTMLStyleElement): void;
export declare function isHTMLElement(o: any): o is HTMLElement;
export declare const EventType: {
readonly CLICK: "click";
readonly AUXCLICK: "auxclick";
readonly DBLCLICK: "dblclick";
readonly MOUSE_UP: "mouseup";
readonly MOUSE_DOWN: "mousedown";
readonly MOUSE_OVER: "mouseover";
readonly MOUSE_MOVE: "mousemove";
readonly MOUSE_OUT: "mouseout";
readonly MOUSE_ENTER: "mouseenter";
readonly MOUSE_LEAVE: "mouseleave";
readonly MOUSE_WHEEL: "wheel";
readonly POINTER_UP: "pointerup";
readonly POINTER_DOWN: "pointerdown";
readonly POINTER_MOVE: "pointermove";
readonly POINTER_LEAVE: "pointerleave";
readonly CONTEXT_MENU: "contextmenu";
readonly WHEEL: "wheel";
readonly KEY_DOWN: "keydown";
readonly KEY_PRESS: "keypress";
readonly KEY_UP: "keyup";
readonly LOAD: "load";
readonly BEFORE_UNLOAD: "beforeunload";
readonly UNLOAD: "unload";
readonly PAGE_SHOW: "pageshow";
readonly PAGE_HIDE: "pagehide";
readonly ABORT: "abort";
readonly ERROR: "error";
readonly RESIZE: "resize";
readonly SCROLL: "scroll";
readonly FULLSCREEN_CHANGE: "fullscreenchange";
readonly WK_FULLSCREEN_CHANGE: "webkitfullscreenchange";
readonly SELECT: "select";
readonly CHANGE: "change";
readonly SUBMIT: "submit";
readonly RESET: "reset";
readonly FOCUS: "focus";
readonly FOCUS_IN: "focusin";
readonly FOCUS_OUT: "focusout";
readonly BLUR: "blur";
readonly INPUT: "input";
readonly STORAGE: "storage";
readonly DRAG_START: "dragstart";
readonly DRAG: "drag";
readonly DRAG_ENTER: "dragenter";
readonly DRAG_LEAVE: "dragleave";
readonly DRAG_OVER: "dragover";
readonly DROP: "drop";
readonly DRAG_END: "dragend";
readonly ANIMATION_START: "animationstart" | "webkitAnimationStart";
readonly ANIMATION_END: "animationend" | "webkitAnimationEnd";
readonly ANIMATION_ITERATION: "animationiteration" | "webkitAnimationIteration";
};
export interface EventLike {
preventDefault(): void;
stopPropagation(): void;
}
export declare const EventHelper: {
stop: (e: EventLike, cancelBubble?: boolean) => void;
};
export interface IFocusTracker {
onDidFocus: Event<void>;
onDidBlur: Event<void>;
dispose(): void;
}
export declare function saveParentsScrollTop(node: Element): number[];
export declare function restoreParentsScrollTop(node: Element, state: number[]): void;
export declare function trackFocus(element: HTMLElement | Window): IFocusTracker;
export declare function append<T extends Node>(parent: HTMLElement, ...children: T[]): T;
export declare function prepend<T extends Node>(parent: HTMLElement, child: T): T;
export declare function $<T extends HTMLElement>(description: string, attrs?: {
[key: string]: any;
}, ...children: Array<Node | string>): T;
export declare function join(nodes: Node[], separator: Node | string): Node[];
export declare function show(...elements: HTMLElement[]): void;
export declare function hide(...elements: HTMLElement[]): void;
export declare function removeTabIndexAndUpdateFocus(node: HTMLElement): void;
export declare function getElementsByTagName(tag: string): HTMLElement[];
export declare function finalHandler<T extends DOMEvent>(fn: (event: T) => any): (event: T) => any;
export declare function domContentLoaded(): Promise<any>;
/**
* Find a value usable for a dom node size such that the likelihood that it would be
* displayed with constant screen pixels size is as high as possible.
*
* e.g. We would desire for the cursors to be 2px (CSS px) wide. Under a devicePixelRatio
* of 1.25, the cursor will be 2.5 screen pixels wide. Depending on how the dom node aligns/"snaps"
* with the screen pixels, it will sometimes be rendered with 2 screen pixels, and sometimes with 3 screen pixels.
*/
export declare function computeScreenAwareSize(cssPx: number): number;
/**
* See https://github.com/Microsoft/monaco-editor/issues/601
* To protect against malicious code in the linked site, particularly phishing attempts,
* the window.opener should be set to null to prevent the linked site from having access
* to change the location of the current page.
* See https://mathiasbynens.github.io/rel-noopener/
*/
export declare function windowOpenNoOpener(url: string): void;
export declare function animate(fn: () => void): IDisposable;
export {};

File diff suppressed because it is too large Load Diff

213
src/app/titlebar/base/common/event.d.ts vendored Normal file
View File

@@ -0,0 +1,213 @@
import { IDisposable } from '../common/lifecycle';
import { LinkedList } from '../common/linkedList';
/**
* To an event a function with one or zero parameters
* can be subscribed. The event is the subscriber function itself.
*/
export interface Event<T> {
(listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[]): IDisposable;
}
export declare namespace Event {
const None: Event<any>;
/**
* Given an event, returns another event which only fires once.
*/
function once<T>(event: Event<T>): Event<T>;
/**
* Given an event and a `map` function, returns another event which maps each element
* throught the mapping function.
*/
function map<I, O>(event: Event<I>, map: (i: I) => O): Event<O>;
/**
* Given an event and an `each` function, returns another identical event and calls
* the `each` function per each element.
*/
function forEach<I>(event: Event<I>, each: (i: I) => void): Event<I>;
/**
* Given an event and a `filter` function, returns another event which emits those
* elements for which the `filter` function returns `true`.
*/
function filter<T>(event: Event<T>, filter: (e: T) => boolean): Event<T>;
function filter<T, R>(event: Event<T | R>, filter: (e: T | R) => e is R): Event<R>;
/**
* Given an event, returns the same event but typed as `Event<void>`.
*/
function signal<T>(event: Event<T>): Event<void>;
/**
* Given a collection of events, returns a single event which emits
* whenever any of the provided events emit.
*/
function any<T>(...events: Event<T>[]): Event<T>;
/**
* Given an event and a `merge` function, returns another event which maps each element
* and the cummulative result throught the `merge` function. Similar to `map`, but with memory.
*/
function reduce<I, O>(event: Event<I>, merge: (last: O | undefined, event: I) => O, initial?: O): Event<O>;
/**
* Debounces the provided event, given a `merge` function.
*
* @param event The input event.
* @param merge The reducing function.
* @param delay The debouncing delay in millis.
* @param leading Whether the event should fire in the leading phase of the timeout.
* @param leakWarningThreshold The leak warning threshold override.
*/
function debounce<T>(event: Event<T>, merge: (last: T, event: T) => T, delay?: number, leading?: boolean, leakWarningThreshold?: number): Event<T>;
function debounce<I, O>(event: Event<I>, merge: (last: O | undefined, event: I) => O, delay?: number, leading?: boolean, leakWarningThreshold?: number): Event<O>;
/**
* Given an event, it returns another event which fires only once and as soon as
* the input event emits. The event data is the number of millis it took for the
* event to fire.
*/
function stopwatch<T>(event: Event<T>): Event<number>;
/**
* Given an event, it returns another event which fires only when the event
* element changes.
*/
function latch<T>(event: Event<T>): Event<T>;
/**
* Buffers the provided event until a first listener comes
* along, at which point fire all the events at once and
* pipe the event from then on.
*
* ```typescript
* const emitter = new Emitter<number>();
* const event = emitter.event;
* const bufferedEvent = buffer(event);
*
* emitter.fire(1);
* emitter.fire(2);
* emitter.fire(3);
* // nothing...
*
* const listener = bufferedEvent(num => console.log(num));
* // 1, 2, 3
*
* emitter.fire(4);
* // 4
* ```
*/
function buffer<T>(event: Event<T>, nextTick?: boolean, _buffer?: T[]): Event<T>;
/**
* Similar to `buffer` but it buffers indefinitely and repeats
* the buffered events to every new listener.
*/
function echo<T>(event: Event<T>, nextTick?: boolean, buffer?: T[]): Event<T>;
interface IChainableEvent<T> {
event: Event<T>;
map<O>(fn: (i: T) => O): IChainableEvent<O>;
forEach(fn: (i: T) => void): IChainableEvent<T>;
filter(fn: (e: T) => boolean): IChainableEvent<T>;
reduce<R>(merge: (last: R | undefined, event: T) => R, initial?: R): IChainableEvent<R>;
latch(): IChainableEvent<T>;
on(listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[]): IDisposable;
once(listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[]): IDisposable;
}
function chain<T>(event: Event<T>): IChainableEvent<T>;
interface NodeEventEmitter {
on(event: string | symbol, listener: Function): this;
removeListener(event: string | symbol, listener: Function): this;
}
function fromNodeEventEmitter<T>(emitter: NodeEventEmitter, eventName: string, map?: (...args: any[]) => T): Event<T>;
function fromPromise<T = any>(promise: Promise<T>): Event<undefined>;
function toPromise<T>(event: Event<T>): Promise<T>;
}
type Listener<T> = [(e: T) => void, any] | ((e: T) => void);
export interface EmitterOptions {
onFirstListenerAdd?: Function;
onFirstListenerDidAdd?: Function;
onListenerDidAdd?: Function;
onLastListenerRemove?: Function;
leakWarningThreshold?: number;
}
export declare function setGlobalLeakWarningThreshold(n: number): IDisposable;
/**
* The Emitter can be used to expose an Event to the public
* to fire it from the insides.
* Sample:
class Document {
private _onDidChange = new Emitter<(value:string)=>any>();
public onDidChange = this._onDidChange.event;
// getter-style
// get onDidChange(): Event<(value:string)=>any> {
// return this._onDidChange.event;
// }
private _doIt() {
//...
this._onDidChange.fire(value);
}
}
*/
export declare class Emitter<T> {
private static readonly _noop;
private readonly _options?;
private readonly _leakageMon?;
private _disposed;
private _event?;
private _deliveryQueue?;
protected _listeners?: LinkedList<Listener<T>>;
constructor(options?: EmitterOptions);
/**
* For the public to allow to subscribe
* to events from this Emitter
*/
get event(): Event<T>;
/**
* To be kept private to fire an event to
* subscribers
*/
fire(event: T): void;
dispose(): void;
}
export interface IWaitUntil {
waitUntil(thenable: Promise<any>): void;
}
export declare class AsyncEmitter<T extends IWaitUntil> extends Emitter<T> {
private _asyncDeliveryQueue?;
fireAsync(eventFn: (thenables: Promise<any>[], listener: Function) => T): Promise<void>;
}
/**
* The EventBufferer is useful in situations in which you want
* to delay firing your events during some code.
* You can wrap that code and be sure that the event will not
* be fired during that wrap.
*
* ```
* const emitter: Emitter;
* const delayer = new EventDelayer();
* const delayedEvent = delayer.wrapEvent(emitter.event);
*
* delayedEvent(console.log);
*
* delayer.bufferEvents(() => {
* emitter.fire(); // event will not be fired yet
* });
*
* // event will only be fired at this point
* ```
*/
export declare class EventBufferer {
private buffers;
wrapEvent<T>(event: Event<T>): Event<T>;
bufferEvents<R = void>(fn: () => R): R;
}
/**
* A Relay is an event forwarder which functions as a replugabble event pipe.
* Once created, you can connect an input event to it and it will simply forward
* events from that input event through its own `event` property. The `input`
* can be changed at any point in time.
*/
export declare class Relay<T> implements IDisposable {
private listening;
private inputEvent;
private inputEventListener;
private emitter;
readonly event: Event<T>;
set input(event: Event<T>);
dispose(): void;
}
export {};

View File

@@ -0,0 +1,804 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Relay = exports.EventBufferer = exports.AsyncEmitter = exports.Emitter = exports.setGlobalLeakWarningThreshold = exports.Event = void 0;
const lifecycle_1 = require("../common/lifecycle");
const linkedList_1 = require("../common/linkedList");
var Event;
(function (Event) {
const _disposable = {
dispose() {}
};
Event.None = function () {
return _disposable;
};
/**
* Given an event, returns another event which only fires once.
*/
function once(event) {
return (listener, thisArgs = null, disposables) => {
// we need this, in case the event fires during the listener call
let didFire = false;
const result = event(e => {
if (didFire) {
return;
} else if (result) {
result.dispose();
} else {
didFire = true;
}
return listener.call(thisArgs, e);
}, null, disposables);
if (didFire) {
result.dispose();
}
return result;
};
}
Event.once = once;
/**
* Given an event and a `map` function, returns another event which maps each element
* throught the mapping function.
*/
function map(event, map) {
return (listener, thisArgs = null, disposables) => event(i => listener.call(thisArgs, map(i)), null, disposables);
}
Event.map = map;
/**
* Given an event and an `each` function, returns another identical event and calls
* the `each` function per each element.
*/
function forEach(event, each) {
return (listener, thisArgs = null, disposables) => event(i => {
each(i);
listener.call(thisArgs, i);
}, null, disposables);
}
Event.forEach = forEach;
function filter(event, filter) {
return (listener, thisArgs = null, disposables) => event(e => filter(e) && listener.call(thisArgs, e), null, disposables);
}
Event.filter = filter;
/**
* Given an event, returns the same event but typed as `Event<void>`.
*/
function signal(event) {
return event;
}
Event.signal = signal;
/**
* Given a collection of events, returns a single event which emits
* whenever any of the provided events emit.
*/
function any(...events) {
return (listener, thisArgs = null, disposables) => (0, _get__("lifecycle_1").combinedDisposable)(events.map(event => event(e => listener.call(thisArgs, e), null, disposables)));
}
Event.any = any;
/**
* Given an event and a `merge` function, returns another event which maps each element
* and the cummulative result throught the `merge` function. Similar to `map`, but with memory.
*/
function reduce(event, merge, initial) {
let output = initial;
return map(event, e => {
output = merge(output, e);
return output;
});
}
Event.reduce = reduce;
function debounce(event, merge, delay = 100, leading = false, leakWarningThreshold) {
let subscription;
let output;
let handle;
let numDebouncedCalls = 0;
const emitter = new (_get__("Emitter"))({
leakWarningThreshold,
onFirstListenerAdd() {
subscription = event(cur => {
numDebouncedCalls++;
output = merge(output, cur);
if (leading && !handle) {
emitter.fire(output);
}
clearTimeout(handle);
handle = setTimeout(() => {
const _output = output;
output = undefined;
handle = undefined;
if (!leading || numDebouncedCalls > 1) {
emitter.fire(_output);
}
numDebouncedCalls = 0;
}, delay);
});
},
onLastListenerRemove() {
subscription.dispose();
}
});
return emitter.event;
}
Event.debounce = debounce;
/**
* Given an event, it returns another event which fires only once and as soon as
* the input event emits. The event data is the number of millis it took for the
* event to fire.
*/
function stopwatch(event) {
const start = new Date().getTime();
return map(once(event), _ => new Date().getTime() - start);
}
Event.stopwatch = stopwatch;
/**
* Given an event, it returns another event which fires only when the event
* element changes.
*/
function latch(event) {
let firstCall = true;
let cache;
return filter(event, value => {
const shouldEmit = firstCall || value !== cache;
firstCall = false;
cache = value;
return shouldEmit;
});
}
Event.latch = latch;
/**
* Buffers the provided event until a first listener comes
* along, at which point fire all the events at once and
* pipe the event from then on.
*
* ```typescript
* const emitter = new Emitter<number>();
* const event = emitter.event;
* const bufferedEvent = buffer(event);
*
* emitter.fire(1);
* emitter.fire(2);
* emitter.fire(3);
* // nothing...
*
* const listener = bufferedEvent(num => console.log(num));
* // 1, 2, 3
*
* emitter.fire(4);
* // 4
* ```
*/
function buffer(event, nextTick = false, _buffer = []) {
let buffer = _buffer.slice();
let listener = event(e => {
if (buffer) {
buffer.push(e);
} else {
emitter.fire(e);
}
});
const flush = () => {
if (buffer) {
buffer.forEach(e => emitter.fire(e));
}
buffer = null;
};
const emitter = new (_get__("Emitter"))({
onFirstListenerAdd() {
if (!listener) {
listener = event(e => emitter.fire(e));
}
},
onFirstListenerDidAdd() {
if (buffer) {
if (nextTick) {
setTimeout(flush);
} else {
flush();
}
}
},
onLastListenerRemove() {
if (listener) {
listener.dispose();
}
listener = null;
}
});
return emitter.event;
}
Event.buffer = buffer;
/**
* Similar to `buffer` but it buffers indefinitely and repeats
* the buffered events to every new listener.
*/
function echo(event, nextTick = false, buffer = []) {
buffer = buffer.slice();
event(e => {
buffer.push(e);
emitter.fire(e);
});
const flush = (listener, thisArgs) => buffer.forEach(e => listener.call(thisArgs, e));
const emitter = new (_get__("Emitter"))({
onListenerDidAdd(emitter, listener, thisArgs) {
if (nextTick) {
setTimeout(() => flush(listener, thisArgs));
} else {
flush(listener, thisArgs);
}
}
});
return emitter.event;
}
Event.echo = echo;
class ChainableEvent {
get event() {
return this._event;
}
constructor(_event) {
this._event = _event;
}
map(fn) {
return new ChainableEvent(map(this._event, fn));
}
forEach(fn) {
return new ChainableEvent(forEach(this._event, fn));
}
filter(fn) {
return new ChainableEvent(filter(this._event, fn));
}
reduce(merge, initial) {
return new ChainableEvent(reduce(this._event, merge, initial));
}
latch() {
return new ChainableEvent(latch(this._event));
}
on(listener, thisArgs, disposables) {
return this._event(listener, thisArgs, disposables);
}
once(listener, thisArgs, disposables) {
return once(this._event)(listener, thisArgs, disposables);
}
}
function chain(event) {
return new ChainableEvent(event);
}
Event.chain = chain;
function fromNodeEventEmitter(emitter, eventName, map = id => id) {
const fn = (...args) => result.fire(map(...args));
const onFirstListenerAdd = () => emitter.on(eventName, fn);
const onLastListenerRemove = () => emitter.removeListener(eventName, fn);
const result = new (_get__("Emitter"))({
onFirstListenerAdd,
onLastListenerRemove
});
return result.event;
}
Event.fromNodeEventEmitter = fromNodeEventEmitter;
function fromPromise(promise) {
const emitter = new (_get__("Emitter"))();
let shouldEmit = false;
promise.then(undefined, () => null).then(() => {
if (!shouldEmit) {
setTimeout(() => emitter.fire(undefined), 0);
} else {
emitter.fire(undefined);
}
});
shouldEmit = true;
return emitter.event;
}
Event.fromPromise = fromPromise;
function toPromise(event) {
// eslint-disable-next-line promise/param-names
return new Promise(c => once(event)(c));
}
Event.toPromise = toPromise;
})(_get__("Event") || (exports.Event = _assign__("Event", {})));
let _globalLeakWarningThreshold = -1;
function setGlobalLeakWarningThreshold(n) {
const oldValue = _get__("_globalLeakWarningThreshold");
_assign__("_globalLeakWarningThreshold", n);
return {
dispose() {
_assign__("_globalLeakWarningThreshold", oldValue);
}
};
}
exports.setGlobalLeakWarningThreshold = _get__("setGlobalLeakWarningThreshold");
class LeakageMonitor {
constructor(customThreshold, name = Math.random().toString(18).slice(2, 5)) {
this.customThreshold = customThreshold;
this.name = name;
this._warnCountdown = 0;
}
dispose() {
if (this._stacks) {
this._stacks.clear();
}
}
check(listenerCount) {
let threshold = _get__("_globalLeakWarningThreshold");
if (typeof this.customThreshold === 'number') {
threshold = this.customThreshold;
}
if (threshold <= 0 || listenerCount < threshold) {
return undefined;
}
if (!this._stacks) {
this._stacks = new Map();
}
const stack = new Error().stack.split('\n').slice(3).join('\n');
const count = this._stacks.get(stack) || 0;
this._stacks.set(stack, count + 1);
this._warnCountdown -= 1;
if (this._warnCountdown <= 0) {
// only warn on first exceed and then every time the limit
// is exceeded by 50% again
this._warnCountdown = threshold * 0.5;
// find most frequent listener and print warning
let topStack;
let topCount = 0;
this._stacks.forEach((count, stack) => {
if (!topStack || topCount < count) {
topStack = stack;
topCount = count;
}
});
console.warn(`[${this.name}] potential listener LEAK detected, having ${listenerCount} listeners already. MOST frequent listener (${topCount}):`);
console.warn(topStack);
}
return () => {
const count = this._stacks.get(stack) || 0;
this._stacks.set(stack, count - 1);
};
}
}
/**
* The Emitter can be used to expose an Event to the public
* to fire it from the insides.
* Sample:
class Document {
private _onDidChange = new Emitter<(value:string)=>any>();
public onDidChange = this._onDidChange.event;
// getter-style
// get onDidChange(): Event<(value:string)=>any> {
// return this._onDidChange.event;
// }
private _doIt() {
//...
this._onDidChange.fire(value);
}
}
*/
class Emitter {
constructor(options) {
this._disposed = false;
this._options = options;
this._leakageMon = _get__("_globalLeakWarningThreshold") > 0 ? new (_get__("LeakageMonitor"))(this._options && this._options.leakWarningThreshold) : undefined;
}
/**
* For the public to allow to subscribe
* to events from this Emitter
*/
get event() {
if (!this._event) {
this._event = (listener, thisArgs, disposables) => {
if (!this._listeners) {
this._listeners = new (_get__("linkedList_1").LinkedList)();
}
const firstListener = this._listeners.isEmpty();
if (firstListener && this._options && this._options.onFirstListenerAdd) {
this._options.onFirstListenerAdd(this);
}
const remove = this._listeners.push(!thisArgs ? listener : [listener, thisArgs]);
if (firstListener && this._options && this._options.onFirstListenerDidAdd) {
this._options.onFirstListenerDidAdd(this);
}
if (this._options && this._options.onListenerDidAdd) {
this._options.onListenerDidAdd(this, listener, thisArgs);
}
// check and record this emitter for potential leakage
let removeMonitor;
if (this._leakageMon) {
removeMonitor = this._leakageMon.check(this._listeners.size);
}
const result = {
dispose: () => {
if (removeMonitor) {
removeMonitor();
}
result.dispose = _get__("Emitter")._noop;
if (!this._disposed) {
remove();
if (this._options && this._options.onLastListenerRemove) {
const hasListeners = this._listeners && !this._listeners.isEmpty();
if (!hasListeners) {
this._options.onLastListenerRemove(this);
}
}
}
}
};
if (Array.isArray(disposables)) {
disposables.push(result);
}
return result;
};
}
return this._event;
}
/**
* To be kept private to fire an event to
* subscribers
*/
fire(event) {
if (this._listeners) {
// put all [listener,event]-pairs into delivery queue
// then emit all event. an inner/nested event might be
// the driver of this
if (!this._deliveryQueue) {
this._deliveryQueue = [];
}
for (let iter = this._listeners.iterator(), e = iter.next(); !e.done; e = iter.next()) {
this._deliveryQueue.push([e.value, event]);
}
while (this._deliveryQueue.length > 0) {
const [listener, event] = this._deliveryQueue.shift();
try {
if (typeof listener === 'function') {
// eslint-disable-next-line no-useless-call
listener.call(undefined, event);
} else {
listener[0].call(listener[1], event);
}
} catch (e) {
console.error(e);
}
}
}
}
dispose() {
if (this._listeners) {
this._listeners = undefined;
}
if (this._deliveryQueue) {
this._deliveryQueue.length = 0;
}
if (this._leakageMon) {
this._leakageMon.dispose();
}
this._disposed = true;
}
}
exports.Emitter = _get__("Emitter");
_get__("Emitter")._noop = function () {};
class AsyncEmitter extends _get__("Emitter") {
async fireAsync(eventFn) {
if (!this._listeners) {
return;
}
// put all [listener,event]-pairs into delivery queue
// then emit all event. an inner/nested event might be
// the driver of this
if (!this._asyncDeliveryQueue) {
this._asyncDeliveryQueue = [];
}
for (let iter = this._listeners.iterator(), e = iter.next(); !e.done; e = iter.next()) {
const thenables = [];
this._asyncDeliveryQueue.push([e.value, eventFn(thenables, typeof e.value === 'function' ? e.value : e.value[0]), thenables]);
}
while (this._asyncDeliveryQueue.length > 0) {
const [listener, event, thenables] = this._asyncDeliveryQueue.shift();
try {
if (typeof listener === 'function') {
// eslint-disable-next-line no-useless-call
listener.call(undefined, event);
} else {
listener[0].call(listener[1], event);
}
} catch (e) {
console.error(e);
continue;
}
// freeze thenables-collection to enforce sync-calls to
// wait until and then wait for all thenables to resolve
Object.freeze(thenables);
await Promise.all(thenables);
}
}
}
exports.AsyncEmitter = _get__("AsyncEmitter");
/**
* The EventBufferer is useful in situations in which you want
* to delay firing your events during some code.
* You can wrap that code and be sure that the event will not
* be fired during that wrap.
*
* ```
* const emitter: Emitter;
* const delayer = new EventDelayer();
* const delayedEvent = delayer.wrapEvent(emitter.event);
*
* delayedEvent(console.log);
*
* delayer.bufferEvents(() => {
* emitter.fire(); // event will not be fired yet
* });
*
* // event will only be fired at this point
* ```
*/
class EventBufferer {
constructor() {
this.buffers = [];
}
wrapEvent(event) {
return (listener, thisArgs, disposables) => {
return event(i => {
const buffer = this.buffers[this.buffers.length - 1];
if (buffer) {
buffer.push(() => listener.call(thisArgs, i));
} else {
listener.call(thisArgs, i);
}
}, undefined, disposables);
};
}
bufferEvents(fn) {
const buffer = [];
this.buffers.push(buffer);
const r = fn();
this.buffers.pop();
buffer.forEach(flush => flush());
return r;
}
}
exports.EventBufferer = _get__("EventBufferer");
/**
* A Relay is an event forwarder which functions as a replugabble event pipe.
* Once created, you can connect an input event to it and it will simply forward
* events from that input event through its own `event` property. The `input`
* can be changed at any point in time.
*/
class Relay {
constructor() {
this.listening = false;
this.inputEvent = _get__("Event").None;
this.inputEventListener = _get__("lifecycle_1").Disposable.None;
this.emitter = new (_get__("Emitter"))({
onFirstListenerDidAdd: () => {
this.listening = true;
this.inputEventListener = this.inputEvent(this.emitter.fire, this.emitter);
},
onLastListenerRemove: () => {
this.listening = false;
this.inputEventListener.dispose();
}
});
this.event = this.emitter.event;
}
// eslint-disable-next-line accessor-pairs
set input(event) {
this.inputEvent = event;
if (this.listening) {
this.inputEventListener.dispose();
this.inputEventListener = event(this.emitter.fire, this.emitter);
}
}
dispose() {
this.inputEventListener.dispose();
this.emitter.dispose();
}
}
exports.Relay = _get__("Relay");
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "lifecycle_1":
return lifecycle_1;
case "Emitter":
return Emitter;
case "Event":
return Event;
case "_globalLeakWarningThreshold":
return _globalLeakWarningThreshold;
case "setGlobalLeakWarningThreshold":
return setGlobalLeakWarningThreshold;
case "LeakageMonitor":
return LeakageMonitor;
case "linkedList_1":
return linkedList_1;
case "AsyncEmitter":
return AsyncEmitter;
case "EventBufferer":
return EventBufferer;
case "Relay":
return Relay;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {
case "Event":
return Event = _value;
case "_globalLeakWarningThreshold":
return _globalLeakWarningThreshold = _value;
}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

View File

@@ -0,0 +1,69 @@
export interface IteratorDefinedResult<T> {
readonly done: false;
readonly value: T;
}
export interface IteratorUndefinedResult {
readonly done: true;
readonly value: undefined;
}
export declare const FIN: IteratorUndefinedResult;
export type IteratorResult<T> = IteratorDefinedResult<T> | IteratorUndefinedResult;
export interface Iterator<T> {
next(): IteratorResult<T>;
}
export declare namespace Iterator {
function empty<T>(): Iterator<T>;
function fromArray<T>(array: T[], index?: number, length?: number): Iterator<T>;
function from<T>(elements: Iterator<T> | T[] | undefined): Iterator<T>;
function map<T, R>(iterator: Iterator<T>, fn: (t: T) => R): Iterator<R>;
function filter<T>(iterator: Iterator<T>, fn: (t: T) => boolean): Iterator<T>;
function forEach<T>(iterator: Iterator<T>, fn: (t: T) => void): void;
function collect<T>(iterator: Iterator<T>): T[];
}
export type ISequence<T> = Iterator<T> | T[];
export declare function getSequenceIterator<T>(arg: Iterator<T> | T[]): Iterator<T>;
export interface INextIterator<T> {
next(): T | null;
}
export declare class ArrayIterator<T> implements INextIterator<T> {
private items;
protected start: number;
protected end: number;
protected index: number;
constructor(items: T[], start?: number, end?: number, index?: number);
first(): T | null;
next(): T | null;
protected current(): T | null;
}
export interface INavigator<T> extends INextIterator<T> {
current(): T | null;
previous(): T | null;
parent(): T | null;
first(): T | null;
last(): T | null;
next(): T | null;
}
export declare class ArrayNavigator<T> extends ArrayIterator<T> implements INavigator<T> {
constructor(items: T[], start?: number, end?: number, index?: number);
current(): T | null;
previous(): T | null;
first(): T | null;
last(): T | null;
parent(): T | null;
}
export declare class MappedIterator<T, R> implements INextIterator<R> {
protected iterator: INextIterator<T>;
protected fn: (item: T | null) => R;
constructor(iterator: INextIterator<T>, fn: (item: T | null) => R);
next(): R;
}
export declare class MappedNavigator<T, R> extends MappedIterator<T, R> implements INavigator<R> {
protected navigator: INavigator<T>;
constructor(navigator: INavigator<T>, fn: (item: T | null) => R);
current(): R;
previous(): R;
parent(): R;
first(): R;
last(): R;
next(): R;
}

View File

@@ -0,0 +1,380 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.MappedNavigator = exports.MappedIterator = exports.ArrayNavigator = exports.ArrayIterator = exports.getSequenceIterator = exports.Iterator = exports.FIN = void 0;
exports.FIN = {
done: true,
value: undefined
};
var Iterator;
(function (Iterator) {
const _empty = {
next() {
return exports.FIN;
}
};
function empty() {
return _empty;
}
Iterator.empty = empty;
function fromArray(array, index = 0, length = array.length) {
return {
next() {
if (index >= length) {
return exports.FIN;
}
return {
done: false,
value: array[index++]
};
}
};
}
Iterator.fromArray = fromArray;
function from(elements) {
if (!elements) {
return Iterator.empty();
} else if (Array.isArray(elements)) {
return Iterator.fromArray(elements);
} else {
return elements;
}
}
Iterator.from = from;
function map(iterator, fn) {
return {
next() {
const element = iterator.next();
if (element.done) {
return exports.FIN;
} else {
return {
done: false,
value: fn(element.value)
};
}
}
};
}
Iterator.map = map;
function filter(iterator, fn) {
return {
next() {
while (true) {
const element = iterator.next();
if (element.done) {
return exports.FIN;
}
if (fn(element.value)) {
return {
done: false,
value: element.value
};
}
}
}
};
}
Iterator.filter = filter;
function forEach(iterator, fn) {
for (let next = iterator.next(); !next.done; next = iterator.next()) {
fn(next.value);
}
}
Iterator.forEach = forEach;
function collect(iterator) {
const result = [];
forEach(iterator, value => result.push(value));
return result;
}
Iterator.collect = collect;
})(_get__("Iterator") || (exports.Iterator = _assign__("Iterator", {})));
function getSequenceIterator(arg) {
if (Array.isArray(arg)) {
return _get__("Iterator").fromArray(arg);
} else {
return arg;
}
}
exports.getSequenceIterator = _get__("getSequenceIterator");
class ArrayIterator {
constructor(items, start = 0, end = items.length, index = start - 1) {
this.items = items;
this.start = start;
this.end = end;
this.index = index;
}
first() {
this.index = this.start;
return this.current();
}
next() {
this.index = Math.min(this.index + 1, this.end);
return this.current();
}
current() {
if (this.index === this.start - 1 || this.index === this.end) {
return null;
}
return this.items[this.index];
}
}
exports.ArrayIterator = _get__("ArrayIterator");
class ArrayNavigator extends _get__("ArrayIterator") {
constructor(items, start = 0, end = items.length, index = start - 1) {
super(items, start, end, index);
}
current() {
return super.current();
}
previous() {
this.index = Math.max(this.index - 1, this.start - 1);
return this.current();
}
first() {
this.index = this.start;
return this.current();
}
last() {
this.index = this.end - 1;
return this.current();
}
parent() {
return null;
}
}
exports.ArrayNavigator = _get__("ArrayNavigator");
class MappedIterator {
constructor(iterator, fn) {
this.iterator = iterator;
this.fn = fn;
// noop
}
next() {
return this.fn(this.iterator.next());
}
}
exports.MappedIterator = _get__("MappedIterator");
class MappedNavigator extends _get__("MappedIterator") {
constructor(navigator, fn) {
super(navigator, fn);
this.navigator = navigator;
}
current() {
return this.fn(this.navigator.current());
}
previous() {
return this.fn(this.navigator.previous());
}
parent() {
return this.fn(this.navigator.parent());
}
first() {
return this.fn(this.navigator.first());
}
last() {
return this.fn(this.navigator.last());
}
next() {
return this.fn(this.navigator.next());
}
}
exports.MappedNavigator = _get__("MappedNavigator");
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "Iterator":
return Iterator;
case "getSequenceIterator":
return getSequenceIterator;
case "ArrayIterator":
return ArrayIterator;
case "ArrayNavigator":
return ArrayNavigator;
case "MappedIterator":
return MappedIterator;
case "MappedNavigator":
return MappedNavigator;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {
case "Iterator":
return Iterator = _value;
}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

View File

@@ -0,0 +1,478 @@
import { OperatingSystem } from '../common/platform';
/**
* Virtual Key Codes, the value does not hold any inherent meaning.
* Inspired somewhat from https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
* But these are "more general", as they should work across browsers & OS`s.
*/
export declare const enum KeyCode {
/**
* Placed first to cover the 0 value of the enum.
*/
Unknown = 0,
Backspace = 1,
Tab = 2,
Enter = 3,
Shift = 4,
Ctrl = 5,
Alt = 6,
PauseBreak = 7,
CapsLock = 8,
Escape = 9,
Space = 10,
PageUp = 11,
PageDown = 12,
End = 13,
Home = 14,
LeftArrow = 15,
UpArrow = 16,
RightArrow = 17,
DownArrow = 18,
Insert = 19,
Delete = 20,
KEY_0 = 21,
KEY_1 = 22,
KEY_2 = 23,
KEY_3 = 24,
KEY_4 = 25,
KEY_5 = 26,
KEY_6 = 27,
KEY_7 = 28,
KEY_8 = 29,
KEY_9 = 30,
KEY_A = 31,
KEY_B = 32,
KEY_C = 33,
KEY_D = 34,
KEY_E = 35,
KEY_F = 36,
KEY_G = 37,
KEY_H = 38,
KEY_I = 39,
KEY_J = 40,
KEY_K = 41,
KEY_L = 42,
KEY_M = 43,
KEY_N = 44,
KEY_O = 45,
KEY_P = 46,
KEY_Q = 47,
KEY_R = 48,
KEY_S = 49,
KEY_T = 50,
KEY_U = 51,
KEY_V = 52,
KEY_W = 53,
KEY_X = 54,
KEY_Y = 55,
KEY_Z = 56,
Meta = 57,
ContextMenu = 58,
F1 = 59,
F2 = 60,
F3 = 61,
F4 = 62,
F5 = 63,
F6 = 64,
F7 = 65,
F8 = 66,
F9 = 67,
F10 = 68,
F11 = 69,
F12 = 70,
F13 = 71,
F14 = 72,
F15 = 73,
F16 = 74,
F17 = 75,
F18 = 76,
F19 = 77,
NumLock = 78,
ScrollLock = 79,
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the ';:' key
*/
US_SEMICOLON = 80,
/**
* For any country/region, the '+' key
* For the US standard keyboard, the '=+' key
*/
US_EQUAL = 81,
/**
* For any country/region, the ',' key
* For the US standard keyboard, the ',<' key
*/
US_COMMA = 82,
/**
* For any country/region, the '-' key
* For the US standard keyboard, the '-_' key
*/
US_MINUS = 83,
/**
* For any country/region, the '.' key
* For the US standard keyboard, the '.>' key
*/
US_DOT = 84,
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '/?' key
*/
US_SLASH = 85,
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '`~' key
*/
US_BACKTICK = 86,
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '[{' key
*/
US_OPEN_SQUARE_BRACKET = 87,
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '\|' key
*/
US_BACKSLASH = 88,
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the ']}' key
*/
US_CLOSE_SQUARE_BRACKET = 89,
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the ''"' key
*/
US_QUOTE = 90,
/**
* Used for miscellaneous characters; it can vary by keyboard.
*/
OEM_8 = 91,
/**
* Either the angle bracket key or the backslash key on the RT 102-key keyboard.
*/
OEM_102 = 92,
NUMPAD_0 = 93,// VK_NUMPAD0, 0x60, Numeric keypad 0 key
NUMPAD_1 = 94,// VK_NUMPAD1, 0x61, Numeric keypad 1 key
NUMPAD_2 = 95,// VK_NUMPAD2, 0x62, Numeric keypad 2 key
NUMPAD_3 = 96,// VK_NUMPAD3, 0x63, Numeric keypad 3 key
NUMPAD_4 = 97,// VK_NUMPAD4, 0x64, Numeric keypad 4 key
NUMPAD_5 = 98,// VK_NUMPAD5, 0x65, Numeric keypad 5 key
NUMPAD_6 = 99,// VK_NUMPAD6, 0x66, Numeric keypad 6 key
NUMPAD_7 = 100,// VK_NUMPAD7, 0x67, Numeric keypad 7 key
NUMPAD_8 = 101,// VK_NUMPAD8, 0x68, Numeric keypad 8 key
NUMPAD_9 = 102,// VK_NUMPAD9, 0x69, Numeric keypad 9 key
NUMPAD_MULTIPLY = 103,// VK_MULTIPLY, 0x6A, Multiply key
NUMPAD_ADD = 104,// VK_ADD, 0x6B, Add key
NUMPAD_SEPARATOR = 105,// VK_SEPARATOR, 0x6C, Separator key
NUMPAD_SUBTRACT = 106,// VK_SUBTRACT, 0x6D, Subtract key
NUMPAD_DECIMAL = 107,// VK_DECIMAL, 0x6E, Decimal key
NUMPAD_DIVIDE = 108,// VK_DIVIDE, 0x6F,
/**
* Cover all key codes when IME is processing input.
*/
KEY_IN_COMPOSITION = 109,
ABNT_C1 = 110,// Brazilian (ABNT) Keyboard
ABNT_C2 = 111,// Brazilian (ABNT) Keyboard
/**
* Placed last to cover the length of the enum.
* Please do not depend on this value!
*/
MAX_VALUE = 112
}
/**
* keyboardEvent.code
*/
export declare const enum ScanCode {
DependsOnKbLayout = -1,
None = 0,
Hyper = 1,
Super = 2,
Fn = 3,
FnLock = 4,
Suspend = 5,
Resume = 6,
Turbo = 7,
Sleep = 8,
WakeUp = 9,
KeyA = 10,
KeyB = 11,
KeyC = 12,
KeyD = 13,
KeyE = 14,
KeyF = 15,
KeyG = 16,
KeyH = 17,
KeyI = 18,
KeyJ = 19,
KeyK = 20,
KeyL = 21,
KeyM = 22,
KeyN = 23,
KeyO = 24,
KeyP = 25,
KeyQ = 26,
KeyR = 27,
KeyS = 28,
KeyT = 29,
KeyU = 30,
KeyV = 31,
KeyW = 32,
KeyX = 33,
KeyY = 34,
KeyZ = 35,
Digit1 = 36,
Digit2 = 37,
Digit3 = 38,
Digit4 = 39,
Digit5 = 40,
Digit6 = 41,
Digit7 = 42,
Digit8 = 43,
Digit9 = 44,
Digit0 = 45,
Enter = 46,
Escape = 47,
Backspace = 48,
Tab = 49,
Space = 50,
Minus = 51,
Equal = 52,
BracketLeft = 53,
BracketRight = 54,
Backslash = 55,
IntlHash = 56,
Semicolon = 57,
Quote = 58,
Backquote = 59,
Comma = 60,
Period = 61,
Slash = 62,
CapsLock = 63,
F1 = 64,
F2 = 65,
F3 = 66,
F4 = 67,
F5 = 68,
F6 = 69,
F7 = 70,
F8 = 71,
F9 = 72,
F10 = 73,
F11 = 74,
F12 = 75,
PrintScreen = 76,
ScrollLock = 77,
Pause = 78,
Insert = 79,
Home = 80,
PageUp = 81,
Delete = 82,
End = 83,
PageDown = 84,
ArrowRight = 85,
ArrowLeft = 86,
ArrowDown = 87,
ArrowUp = 88,
NumLock = 89,
NumpadDivide = 90,
NumpadMultiply = 91,
NumpadSubtract = 92,
NumpadAdd = 93,
NumpadEnter = 94,
Numpad1 = 95,
Numpad2 = 96,
Numpad3 = 97,
Numpad4 = 98,
Numpad5 = 99,
Numpad6 = 100,
Numpad7 = 101,
Numpad8 = 102,
Numpad9 = 103,
Numpad0 = 104,
NumpadDecimal = 105,
IntlBackslash = 106,
ContextMenu = 107,
Power = 108,
NumpadEqual = 109,
F13 = 110,
F14 = 111,
F15 = 112,
F16 = 113,
F17 = 114,
F18 = 115,
F19 = 116,
F20 = 117,
F21 = 118,
F22 = 119,
F23 = 120,
F24 = 121,
Open = 122,
Help = 123,
Select = 124,
Again = 125,
Undo = 126,
Cut = 127,
Copy = 128,
Paste = 129,
Find = 130,
AudioVolumeMute = 131,
AudioVolumeUp = 132,
AudioVolumeDown = 133,
NumpadComma = 134,
IntlRo = 135,
KanaMode = 136,
IntlYen = 137,
Convert = 138,
NonConvert = 139,
Lang1 = 140,
Lang2 = 141,
Lang3 = 142,
Lang4 = 143,
Lang5 = 144,
Abort = 145,
Props = 146,
NumpadParenLeft = 147,
NumpadParenRight = 148,
NumpadBackspace = 149,
NumpadMemoryStore = 150,
NumpadMemoryRecall = 151,
NumpadMemoryClear = 152,
NumpadMemoryAdd = 153,
NumpadMemorySubtract = 154,
NumpadClear = 155,
NumpadClearEntry = 156,
ControlLeft = 157,
ShiftLeft = 158,
AltLeft = 159,
MetaLeft = 160,
ControlRight = 161,
ShiftRight = 162,
AltRight = 163,
MetaRight = 164,
BrightnessUp = 165,
BrightnessDown = 166,
MediaPlay = 167,
MediaRecord = 168,
MediaFastForward = 169,
MediaRewind = 170,
MediaTrackNext = 171,
MediaTrackPrevious = 172,
MediaStop = 173,
Eject = 174,
MediaPlayPause = 175,
MediaSelect = 176,
LaunchMail = 177,
LaunchApp2 = 178,
LaunchApp1 = 179,
SelectTask = 180,
LaunchScreenSaver = 181,
BrowserSearch = 182,
BrowserHome = 183,
BrowserBack = 184,
BrowserForward = 185,
BrowserStop = 186,
BrowserRefresh = 187,
BrowserFavorites = 188,
ZoomToggle = 189,
MailReply = 190,
MailForward = 191,
MailSend = 192,
MAX_VALUE = 193
}
export declare const ScanCodeUtils: {
lowerCaseToEnum: (scanCode: string) => number;
toEnum: (scanCode: string) => number;
toString: (scanCode: ScanCode) => string;
};
export declare namespace KeyCodeUtils {
function toString(keyCode: KeyCode): string;
function fromString(key: string): KeyCode;
function toUserSettingsUS(keyCode: KeyCode): string;
function toUserSettingsGeneral(keyCode: KeyCode): string;
function fromUserSettings(key: string): KeyCode;
}
export declare const enum KeyMod {
CtrlCmd = 2048,
Shift = 1024,
Alt = 512,
WinCtrl = 256
}
export declare function KeyChord(firstPart: number, secondPart: number): number;
export declare const enum KeybindingType {
Simple = 1,
Chord = 2
}
export declare class SimpleKeybinding {
readonly type = KeybindingType.Simple;
readonly ctrlKey: boolean;
readonly shiftKey: boolean;
readonly altKey: boolean;
readonly metaKey: boolean;
readonly keyCode: KeyCode;
constructor(ctrlKey: boolean, shiftKey: boolean, altKey: boolean, metaKey: boolean, keyCode: KeyCode);
equals(other: Keybinding): boolean;
getHashCode(): string;
isModifierKey(): boolean;
/**
* Does this keybinding refer to the key code of a modifier and it also has the modifier flag?
*/
isDuplicateModifierCase(): boolean;
}
export declare class ChordKeybinding {
readonly type = KeybindingType.Chord;
readonly firstPart: SimpleKeybinding;
readonly chordPart: SimpleKeybinding;
constructor(firstPart: SimpleKeybinding, chordPart: SimpleKeybinding);
getHashCode(): string;
}
export type Keybinding = SimpleKeybinding | ChordKeybinding;
export declare function createKeybinding(keybinding: number, OS: OperatingSystem): Keybinding | null;
export declare function createSimpleKeybinding(keybinding: number, OS: OperatingSystem): SimpleKeybinding;
export declare class ResolvedKeybindingPart {
readonly ctrlKey: boolean;
readonly shiftKey: boolean;
readonly altKey: boolean;
readonly metaKey: boolean;
readonly keyLabel: string | null;
readonly keyAriaLabel: string | null;
constructor(ctrlKey: boolean, shiftKey: boolean, altKey: boolean, metaKey: boolean, kbLabel: string | null, kbAriaLabel: string | null);
}
/**
* A resolved keybinding. Can be a simple keybinding or a chord keybinding.
*/
export declare abstract class ResolvedKeybinding {
/**
* This prints the binding in a format suitable for displaying in the UI.
*/
abstract getLabel(): string | null;
/**
* This prints the binding in a format suitable for ARIA.
*/
abstract getAriaLabel(): string | null;
/**
* This prints the binding in a format suitable for electron's accelerators.
* See https://github.com/electron/electron/blob/master/docs/api/accelerator.md
*/
abstract getElectronAccelerator(): string | null;
/**
* This prints the binding in a format suitable for user settings.
*/
abstract getUserSettingsLabel(): string | null;
/**
* Is the user settings label reflecting the label?
*/
abstract isWYSIWYG(): boolean;
/**
* Is the binding a chord?
*/
abstract isChord(): boolean;
/**
* Returns the firstPart, chordPart that should be used for dispatching.
*/
abstract getDispatchParts(): [string | null, string | null];
/**
* Returns the firstPart, chordPart of the keybinding.
* For simple keybindings, the second element will be null.
*/
abstract getParts(): [ResolvedKeybindingPart, ResolvedKeybindingPart | null];
}

View File

@@ -0,0 +1,477 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ResolvedKeybinding = exports.ResolvedKeybindingPart = exports.createSimpleKeybinding = exports.createKeybinding = exports.ChordKeybinding = exports.SimpleKeybinding = exports.KeyChord = exports.KeyCodeUtils = exports.ScanCodeUtils = void 0;
class KeyCodeStrMap {
constructor() {
this._keyCodeToStr = [];
this._strToKeyCode = Object.create(null);
}
define(keyCode, str) {
this._keyCodeToStr[keyCode] = str;
this._strToKeyCode[str.toLowerCase()] = keyCode;
}
keyCodeToStr(keyCode) {
return this._keyCodeToStr[keyCode];
}
strToKeyCode(str) {
return this._strToKeyCode[str.toLowerCase()] || 0 /* KeyCode.Unknown */;
}
}
const scanCodeIntToStr = [];
const scanCodeStrToInt = Object.create(null);
const scanCodeLowerCaseStrToInt = Object.create(null);
exports.ScanCodeUtils = {
lowerCaseToEnum: scanCode => _get__("scanCodeLowerCaseStrToInt")[scanCode] || 0 /* ScanCode.None */,
toEnum: scanCode => _get__("scanCodeStrToInt")[scanCode] || 0 /* ScanCode.None */,
toString: scanCode => _get__("scanCodeIntToStr")[scanCode] || 'None'
};
const uiMap = new (_get__("KeyCodeStrMap"))();
const userSettingsUSMap = new (_get__("KeyCodeStrMap"))();
const userSettingsGeneralMap = new (_get__("KeyCodeStrMap"))();
(function () {
function define(keyCode, uiLabel, usUserSettingsLabel = uiLabel, generalUserSettingsLabel = usUserSettingsLabel) {
_get__("uiMap").define(keyCode, uiLabel);
_get__("userSettingsUSMap").define(keyCode, usUserSettingsLabel);
_get__("userSettingsGeneralMap").define(keyCode, generalUserSettingsLabel);
}
define(0 /* KeyCode.Unknown */, 'unknown');
define(1 /* KeyCode.Backspace */, 'Backspace');
define(2 /* KeyCode.Tab */, 'Tab');
define(3 /* KeyCode.Enter */, 'Enter');
define(4 /* KeyCode.Shift */, 'Shift');
define(5 /* KeyCode.Ctrl */, 'Ctrl');
define(6 /* KeyCode.Alt */, 'Alt');
define(7 /* KeyCode.PauseBreak */, 'PauseBreak');
define(8 /* KeyCode.CapsLock */, 'CapsLock');
define(9 /* KeyCode.Escape */, 'Escape');
define(10 /* KeyCode.Space */, 'Space');
define(11 /* KeyCode.PageUp */, 'PageUp');
define(12 /* KeyCode.PageDown */, 'PageDown');
define(13 /* KeyCode.End */, 'End');
define(14 /* KeyCode.Home */, 'Home');
define(15 /* KeyCode.LeftArrow */, 'LeftArrow', 'Left');
define(16 /* KeyCode.UpArrow */, 'UpArrow', 'Up');
define(17 /* KeyCode.RightArrow */, 'RightArrow', 'Right');
define(18 /* KeyCode.DownArrow */, 'DownArrow', 'Down');
define(19 /* KeyCode.Insert */, 'Insert');
define(20 /* KeyCode.Delete */, 'Delete');
define(21 /* KeyCode.KEY_0 */, '0');
define(22 /* KeyCode.KEY_1 */, '1');
define(23 /* KeyCode.KEY_2 */, '2');
define(24 /* KeyCode.KEY_3 */, '3');
define(25 /* KeyCode.KEY_4 */, '4');
define(26 /* KeyCode.KEY_5 */, '5');
define(27 /* KeyCode.KEY_6 */, '6');
define(28 /* KeyCode.KEY_7 */, '7');
define(29 /* KeyCode.KEY_8 */, '8');
define(30 /* KeyCode.KEY_9 */, '9');
define(31 /* KeyCode.KEY_A */, 'A');
define(32 /* KeyCode.KEY_B */, 'B');
define(33 /* KeyCode.KEY_C */, 'C');
define(34 /* KeyCode.KEY_D */, 'D');
define(35 /* KeyCode.KEY_E */, 'E');
define(36 /* KeyCode.KEY_F */, 'F');
define(37 /* KeyCode.KEY_G */, 'G');
define(38 /* KeyCode.KEY_H */, 'H');
define(39 /* KeyCode.KEY_I */, 'I');
define(40 /* KeyCode.KEY_J */, 'J');
define(41 /* KeyCode.KEY_K */, 'K');
define(42 /* KeyCode.KEY_L */, 'L');
define(43 /* KeyCode.KEY_M */, 'M');
define(44 /* KeyCode.KEY_N */, 'N');
define(45 /* KeyCode.KEY_O */, 'O');
define(46 /* KeyCode.KEY_P */, 'P');
define(47 /* KeyCode.KEY_Q */, 'Q');
define(48 /* KeyCode.KEY_R */, 'R');
define(49 /* KeyCode.KEY_S */, 'S');
define(50 /* KeyCode.KEY_T */, 'T');
define(51 /* KeyCode.KEY_U */, 'U');
define(52 /* KeyCode.KEY_V */, 'V');
define(53 /* KeyCode.KEY_W */, 'W');
define(54 /* KeyCode.KEY_X */, 'X');
define(55 /* KeyCode.KEY_Y */, 'Y');
define(56 /* KeyCode.KEY_Z */, 'Z');
define(57 /* KeyCode.Meta */, 'Meta');
define(58 /* KeyCode.ContextMenu */, 'ContextMenu');
define(59 /* KeyCode.F1 */, 'F1');
define(60 /* KeyCode.F2 */, 'F2');
define(61 /* KeyCode.F3 */, 'F3');
define(62 /* KeyCode.F4 */, 'F4');
define(63 /* KeyCode.F5 */, 'F5');
define(64 /* KeyCode.F6 */, 'F6');
define(65 /* KeyCode.F7 */, 'F7');
define(66 /* KeyCode.F8 */, 'F8');
define(67 /* KeyCode.F9 */, 'F9');
define(68 /* KeyCode.F10 */, 'F10');
define(69 /* KeyCode.F11 */, 'F11');
define(70 /* KeyCode.F12 */, 'F12');
define(71 /* KeyCode.F13 */, 'F13');
define(72 /* KeyCode.F14 */, 'F14');
define(73 /* KeyCode.F15 */, 'F15');
define(74 /* KeyCode.F16 */, 'F16');
define(75 /* KeyCode.F17 */, 'F17');
define(76 /* KeyCode.F18 */, 'F18');
define(77 /* KeyCode.F19 */, 'F19');
define(78 /* KeyCode.NumLock */, 'NumLock');
define(79 /* KeyCode.ScrollLock */, 'ScrollLock');
define(80 /* KeyCode.US_SEMICOLON */, ';', ';', 'OEM_1');
define(81 /* KeyCode.US_EQUAL */, '=', '=', 'OEM_PLUS');
define(82 /* KeyCode.US_COMMA */, ',', ',', 'OEM_COMMA');
define(83 /* KeyCode.US_MINUS */, '-', '-', 'OEM_MINUS');
define(84 /* KeyCode.US_DOT */, '.', '.', 'OEM_PERIOD');
define(85 /* KeyCode.US_SLASH */, '/', '/', 'OEM_2');
define(86 /* KeyCode.US_BACKTICK */, '`', '`', 'OEM_3');
define(110 /* KeyCode.ABNT_C1 */, 'ABNT_C1');
define(111 /* KeyCode.ABNT_C2 */, 'ABNT_C2');
define(87 /* KeyCode.US_OPEN_SQUARE_BRACKET */, '[', '[', 'OEM_4');
define(88 /* KeyCode.US_BACKSLASH */, '\\', '\\', 'OEM_5');
define(89 /* KeyCode.US_CLOSE_SQUARE_BRACKET */, ']', ']', 'OEM_6');
define(90 /* KeyCode.US_QUOTE */, '\'', '\'', 'OEM_7');
define(91 /* KeyCode.OEM_8 */, 'OEM_8');
define(92 /* KeyCode.OEM_102 */, 'OEM_102');
define(93 /* KeyCode.NUMPAD_0 */, 'NumPad0');
define(94 /* KeyCode.NUMPAD_1 */, 'NumPad1');
define(95 /* KeyCode.NUMPAD_2 */, 'NumPad2');
define(96 /* KeyCode.NUMPAD_3 */, 'NumPad3');
define(97 /* KeyCode.NUMPAD_4 */, 'NumPad4');
define(98 /* KeyCode.NUMPAD_5 */, 'NumPad5');
define(99 /* KeyCode.NUMPAD_6 */, 'NumPad6');
define(100 /* KeyCode.NUMPAD_7 */, 'NumPad7');
define(101 /* KeyCode.NUMPAD_8 */, 'NumPad8');
define(102 /* KeyCode.NUMPAD_9 */, 'NumPad9');
define(103 /* KeyCode.NUMPAD_MULTIPLY */, 'NumPad_Multiply');
define(104 /* KeyCode.NUMPAD_ADD */, 'NumPad_Add');
define(105 /* KeyCode.NUMPAD_SEPARATOR */, 'NumPad_Separator');
define(106 /* KeyCode.NUMPAD_SUBTRACT */, 'NumPad_Subtract');
define(107 /* KeyCode.NUMPAD_DECIMAL */, 'NumPad_Decimal');
define(108 /* KeyCode.NUMPAD_DIVIDE */, 'NumPad_Divide');
})();
var KeyCodeUtils;
(function (KeyCodeUtils) {
function toString(keyCode) {
return _get__("uiMap").keyCodeToStr(keyCode);
}
KeyCodeUtils.toString = toString;
function fromString(key) {
return _get__("uiMap").strToKeyCode(key);
}
KeyCodeUtils.fromString = fromString;
function toUserSettingsUS(keyCode) {
return _get__("userSettingsUSMap").keyCodeToStr(keyCode);
}
KeyCodeUtils.toUserSettingsUS = toUserSettingsUS;
function toUserSettingsGeneral(keyCode) {
return _get__("userSettingsGeneralMap").keyCodeToStr(keyCode);
}
KeyCodeUtils.toUserSettingsGeneral = toUserSettingsGeneral;
function fromUserSettings(key) {
return _get__("userSettingsUSMap").strToKeyCode(key) || _get__("userSettingsGeneralMap").strToKeyCode(key);
}
KeyCodeUtils.fromUserSettings = fromUserSettings;
})(_get__("KeyCodeUtils") || (exports.KeyCodeUtils = _assign__("KeyCodeUtils", {})));
function KeyChord(firstPart, secondPart) {
const chordPart = (secondPart & 0x0000FFFF) << 16 >>> 0;
return (firstPart | chordPart) >>> 0;
}
exports.KeyChord = _get__("KeyChord");
class SimpleKeybinding {
constructor(ctrlKey, shiftKey, altKey, metaKey, keyCode) {
this.type = 1 /* KeybindingType.Simple */;
this.ctrlKey = ctrlKey;
this.shiftKey = shiftKey;
this.altKey = altKey;
this.metaKey = metaKey;
this.keyCode = keyCode;
}
// eslint-disable-next-line no-use-before-define
equals(other) {
if (other.type !== 1 /* KeybindingType.Simple */) {
return false;
}
return this.ctrlKey === other.ctrlKey && this.shiftKey === other.shiftKey && this.altKey === other.altKey && this.metaKey === other.metaKey && this.keyCode === other.keyCode;
}
getHashCode() {
const ctrl = this.ctrlKey ? '1' : '0';
const shift = this.shiftKey ? '1' : '0';
const alt = this.altKey ? '1' : '0';
const meta = this.metaKey ? '1' : '0';
return `${ctrl}${shift}${alt}${meta}${this.keyCode}`;
}
isModifierKey() {
return this.keyCode === 0 /* KeyCode.Unknown */ || this.keyCode === 5 /* KeyCode.Ctrl */ || this.keyCode === 57 /* KeyCode.Meta */ || this.keyCode === 6 /* KeyCode.Alt */ || this.keyCode === 4 /* KeyCode.Shift */;
}
/**
* Does this keybinding refer to the key code of a modifier and it also has the modifier flag?
*/
isDuplicateModifierCase() {
return this.ctrlKey && this.keyCode === 5 /* KeyCode.Ctrl */ || this.shiftKey && this.keyCode === 4 /* KeyCode.Shift */ || this.altKey && this.keyCode === 6 /* KeyCode.Alt */ || this.metaKey && this.keyCode === 57 /* KeyCode.Meta */;
}
}
exports.SimpleKeybinding = _get__("SimpleKeybinding");
class ChordKeybinding {
constructor(firstPart, chordPart) {
this.type = 2 /* KeybindingType.Chord */;
this.firstPart = firstPart;
this.chordPart = chordPart;
}
getHashCode() {
return `${this.firstPart.getHashCode()};${this.chordPart.getHashCode()}`;
}
}
exports.ChordKeybinding = _get__("ChordKeybinding");
function createKeybinding(keybinding, OS) {
if (keybinding === 0) {
return null;
}
const firstPart = (keybinding & 0x0000FFFF) >>> 0;
const chordPart = (keybinding & 0xFFFF0000) >>> 16;
if (chordPart !== 0) {
return new (_get__("ChordKeybinding"))(_get__("createSimpleKeybinding")(firstPart, OS), _get__("createSimpleKeybinding")(chordPart, OS));
}
return _get__("createSimpleKeybinding")(firstPart, OS);
}
exports.createKeybinding = _get__("createKeybinding");
function createSimpleKeybinding(keybinding, OS) {
const ctrlCmd = !!(keybinding & 2048 /* BinaryKeybindingsMask.CtrlCmd */);
const winCtrl = !!(keybinding & 256 /* BinaryKeybindingsMask.WinCtrl */);
const ctrlKey = OS === 2 /* OperatingSystem.Macintosh */ ? winCtrl : ctrlCmd;
const shiftKey = !!(keybinding & 1024 /* BinaryKeybindingsMask.Shift */);
const altKey = !!(keybinding & 512 /* BinaryKeybindingsMask.Alt */);
const metaKey = OS === 2 /* OperatingSystem.Macintosh */ ? ctrlCmd : winCtrl;
const keyCode = keybinding & 255 /* BinaryKeybindingsMask.KeyCode */;
return new (_get__("SimpleKeybinding"))(ctrlKey, shiftKey, altKey, metaKey, keyCode);
}
exports.createSimpleKeybinding = _get__("createSimpleKeybinding");
class ResolvedKeybindingPart {
constructor(ctrlKey, shiftKey, altKey, metaKey, kbLabel, kbAriaLabel) {
this.ctrlKey = ctrlKey;
this.shiftKey = shiftKey;
this.altKey = altKey;
this.metaKey = metaKey;
this.keyLabel = kbLabel;
this.keyAriaLabel = kbAriaLabel;
}
}
exports.ResolvedKeybindingPart = _get__("ResolvedKeybindingPart");
/**
* A resolved keybinding. Can be a simple keybinding or a chord keybinding.
*/
class ResolvedKeybinding {}
exports.ResolvedKeybinding = _get__("ResolvedKeybinding");
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "scanCodeLowerCaseStrToInt":
return scanCodeLowerCaseStrToInt;
case "scanCodeStrToInt":
return scanCodeStrToInt;
case "scanCodeIntToStr":
return scanCodeIntToStr;
case "KeyCodeStrMap":
return KeyCodeStrMap;
case "uiMap":
return uiMap;
case "userSettingsUSMap":
return userSettingsUSMap;
case "userSettingsGeneralMap":
return userSettingsGeneralMap;
case "KeyCodeUtils":
return KeyCodeUtils;
case "KeyChord":
return KeyChord;
case "SimpleKeybinding":
return SimpleKeybinding;
case "ChordKeybinding":
return ChordKeybinding;
case "createSimpleKeybinding":
return createSimpleKeybinding;
case "createKeybinding":
return createKeybinding;
case "ResolvedKeybindingPart":
return ResolvedKeybindingPart;
case "ResolvedKeybinding":
return ResolvedKeybinding;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {
case "KeyCodeUtils":
return KeyCodeUtils = _value;
}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

View File

@@ -0,0 +1,17 @@
export interface IDisposable {
dispose(): void;
}
export declare function isDisposable<E extends object>(thing: E): thing is E & IDisposable;
export declare function dispose<T extends IDisposable>(disposable: T): T;
export declare function dispose<T extends IDisposable>(...disposables: Array<T | undefined>): T[];
export declare function dispose<T extends IDisposable>(disposables: T[]): T[];
export declare function combinedDisposable(disposables: IDisposable[]): IDisposable;
export declare function toDisposable(fn: () => void): IDisposable;
export declare abstract class Disposable implements IDisposable {
static None: Readonly<IDisposable>;
protected _toDispose: IDisposable[];
protected get toDispose(): IDisposable[];
private _lifecycle_disposable_isDisposed;
dispose(): void;
protected _register<T extends IDisposable>(t: T): T;
}

View File

@@ -0,0 +1,258 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Disposable = exports.toDisposable = exports.combinedDisposable = exports.dispose = exports.isDisposable = void 0;
function isDisposable(thing) {
return typeof thing.dispose === 'function' && thing.dispose.length === 0;
}
exports.isDisposable = _get__("isDisposable");
function dispose(first, ...rest) {
if (Array.isArray(first)) {
first.forEach(d => d && d.dispose());
return [];
} else if (rest.length === 0) {
if (first) {
first.dispose();
return first;
}
return undefined;
} else {
_get__("dispose")(first);
_get__("dispose")(rest);
return [];
}
}
exports.dispose = _get__("dispose");
function combinedDisposable(disposables) {
return {
dispose: () => _get__("dispose")(disposables)
};
}
exports.combinedDisposable = _get__("combinedDisposable");
function toDisposable(fn) {
return {
dispose() {
fn();
}
};
}
exports.toDisposable = _get__("toDisposable");
class Disposable {
constructor() {
this._toDispose = [];
this._lifecycle_disposable_isDisposed = false;
}
get toDispose() {
return this._toDispose;
}
dispose() {
this._lifecycle_disposable_isDisposed = true;
this._toDispose = _get__("dispose")(this._toDispose);
}
_register(t) {
if (this._lifecycle_disposable_isDisposed) {
console.warn('Registering disposable on object that has already been disposed.');
t.dispose();
} else {
this._toDispose.push(t);
}
return t;
}
}
exports.Disposable = _get__("Disposable");
_get__("Disposable").None = Object.freeze({
dispose() {}
});
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "isDisposable":
return isDisposable;
case "dispose":
return dispose;
case "combinedDisposable":
return combinedDisposable;
case "toDisposable":
return toDisposable;
case "Disposable":
return Disposable;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

View File

@@ -0,0 +1,17 @@
import { Iterator } from '../common/iterator';
export declare class LinkedList<E> {
private _first;
private _last;
private _size;
get size(): number;
isEmpty(): boolean;
clear(): void;
unshift(element: E): () => void;
push(element: E): () => void;
private _insert;
shift(): E | undefined;
pop(): E | undefined;
private _remove;
iterator(): Iterator<E>;
toArray(): E[];
}

View File

@@ -0,0 +1,319 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.LinkedList = void 0;
const iterator_1 = require("../common/iterator");
class Node {
constructor(element) {
this.element = element;
}
}
class LinkedList {
constructor() {
this._size = 0;
}
get size() {
return this._size;
}
isEmpty() {
return !this._first;
}
clear() {
this._first = undefined;
this._last = undefined;
this._size = 0;
}
unshift(element) {
return this._insert(element, false);
}
push(element) {
return this._insert(element, true);
}
_insert(element, atTheEnd) {
const newNode = new (_get__("Node"))(element);
if (!this._first) {
this._first = newNode;
this._last = newNode;
} else if (atTheEnd) {
// push
const oldLast = this._last;
this._last = newNode;
newNode.prev = oldLast;
oldLast.next = newNode;
} else {
// unshift
const oldFirst = this._first;
this._first = newNode;
newNode.next = oldFirst;
oldFirst.prev = newNode;
}
this._size += 1;
return this._remove.bind(this, newNode);
}
shift() {
if (!this._first) {
return undefined;
} else {
const res = this._first.element;
this._remove(this._first);
return res;
}
}
pop() {
if (!this._last) {
return undefined;
} else {
const res = this._last.element;
this._remove(this._last);
return res;
}
}
_remove(node) {
let candidate = this._first;
while (candidate instanceof _get__("Node")) {
if (candidate !== node) {
candidate = candidate.next;
continue;
}
if (candidate.prev && candidate.next) {
// middle
const anchor = candidate.prev;
anchor.next = candidate.next;
candidate.next.prev = anchor;
} else if (!candidate.prev && !candidate.next) {
// only node
this._first = undefined;
this._last = undefined;
} else if (!candidate.next) {
// last
this._last = this._last.prev;
this._last.next = undefined;
} else if (!candidate.prev) {
// first
this._first = this._first.next;
this._first.prev = undefined;
}
// done
this._size -= 1;
break;
}
}
iterator() {
let element;
let node = this._first;
return {
next() {
if (!node) {
return _get__("iterator_1").FIN;
}
if (!element) {
element = {
done: false,
value: node.element
};
} else {
element.value = node.element;
}
node = node.next;
return element;
}
};
}
toArray() {
const result = [];
for (let node = this._first; node instanceof _get__("Node"); node = node.next) {
result.push(node.element);
}
return result;
}
}
exports.LinkedList = _get__("LinkedList");
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "Node":
return Node;
case "iterator_1":
return iterator_1;
case "LinkedList":
return LinkedList;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

View File

@@ -0,0 +1,36 @@
export interface IProcessEnvironment {
[key: string]: string;
}
export declare const enum Platform {
Web = 0,
Mac = 1,
Linux = 2,
FreeBSD = 3,
Windows = 4
}
export declare function PlatformToString(platform: Platform): "Windows" | "Linux" | "FreeBSD" | "Web" | "Mac";
export declare const isWindows: boolean;
export declare const isMacintosh: boolean;
export declare const isLinux: boolean;
export declare const isFreeBSD: boolean;
export declare const isNative: boolean;
export declare const isWeb: boolean;
export declare const platform: Platform;
export declare function isRootUser(): boolean;
export declare const globals: any;
export declare function setImmediate(callback: (...args: any[]) => void): number;
export declare const enum OperatingSystem {
Windows = 1,
Macintosh = 2,
Linux = 3,
FreeBSD = 4
}
export declare const OS: number;
export declare const enum AccessibilitySupport {
/**
* This should be the browser case where it is not known if a screen reader is attached or no.
*/
Unknown = 0,
Disabled = 1,
Enabled = 2
}

View File

@@ -0,0 +1,314 @@
"use strict";
/* eslint-disable indent */
/* ---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.OS = exports.setImmediate = exports.globals = exports.isRootUser = exports.platform = exports.isWeb = exports.isNative = exports.isFreeBSD = exports.isLinux = exports.isMacintosh = exports.isWindows = exports.PlatformToString = void 0;
let _isWindows = false;
let _isMacintosh = false;
let _isLinux = false;
let _isFreeBSD = false;
let _isNative = false;
let _isWeb = false;
const isElectronRenderer = typeof process !== 'undefined' && typeof process.versions !== 'undefined' && typeof process.versions.electron !== 'undefined' && process.type === 'renderer';
// OS detection
if (typeof navigator === 'object' && !_get__("isElectronRenderer")) {
const userAgent = navigator.userAgent;
_assign__("_isWindows", userAgent.indexOf('Windows') >= 0);
_assign__("_isMacintosh", userAgent.indexOf('Macintosh') >= 0);
_assign__("_isLinux", userAgent.indexOf('Linux') >= 0);
_assign__("_isFreeBSD", userAgent.indexOf('FreeBSD') >= 0);
_assign__("_isWeb", true);
} else if (typeof process === 'object') {
_assign__("_isWindows", process.platform === 'win32');
_assign__("_isMacintosh", process.platform === 'darwin');
_assign__("_isLinux", process.platform === 'linux');
_assign__("_isFreeBSD", process.platform === 'freebsd');
_assign__("_isNative", true);
}
function PlatformToString(platform) {
switch (platform) {
case 0 /* Platform.Web */:
return 'Web';
case 1 /* Platform.Mac */:
return 'Mac';
case 2 /* Platform.Linux */:
return 'Linux';
case 3 /* Platform.FreeBSD */:
return 'FreeBSD';
case 4 /* Platform.Windows */:
return 'Windows';
}
}
exports.PlatformToString = _get__("PlatformToString");
let _platform = 0 /* Platform.Web */;
if (_get__("_isNative")) {
if (_get__("_isMacintosh")) {
_assign__("_platform", 1) /* Platform.Mac */;
} else if (_get__("_isWindows")) {
_assign__("_platform", 4) /* Platform.Windows */;
} else if (_get__("_isLinux")) {
_assign__("_platform", 2) /* Platform.Linux */;
} else if (_get__("_isFreeBSD")) {
_assign__("_platform", 3) /* Platform.FreeBSD */;
}
}
exports.isWindows = _get__("_isWindows");
exports.isMacintosh = _get__("_isMacintosh");
exports.isLinux = _get__("_isLinux");
exports.isFreeBSD = _get__("_isFreeBSD");
exports.isNative = _get__("_isNative");
exports.isWeb = _get__("_isWeb");
exports.platform = _get__("_platform");
function isRootUser() {
return _get__("_isNative") && !_get__("_isWindows") && process.getuid() === 0;
}
exports.isRootUser = _get__("isRootUser");
const g = typeof global === 'object' ? global : {};
const _globals = typeof self === 'object' ? self : _get__("g");
exports.globals = _get__("_globals");
let _setImmediate = null;
function setImmediate(callback) {
if (_get__("_setImmediate") === null) {
if (exports.globals.setImmediate) {
_assign__("_setImmediate", exports.globals.setImmediate.bind(exports.globals));
} else if (typeof process !== 'undefined' && typeof process.nextTick === 'function') {
_assign__("_setImmediate", process.nextTick.bind(process));
} else {
_assign__("_setImmediate", exports.globals.setTimeout.bind(exports.globals));
}
}
return _get__("_setImmediate")(callback);
}
exports.setImmediate = _get__("setImmediate");
const _wl = _get__("_isWindows") ? 1 /* OperatingSystem.Windows */ : 3 /* OperatingSystem.Linux */ | 4 /* OperatingSystem.FreeBSD */;
exports.OS = _get__("_isMacintosh") ? 2 /* OperatingSystem.Macintosh */ : _get__("_wl");
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "isElectronRenderer":
return isElectronRenderer;
case "_isWindows":
return _isWindows;
case "_isMacintosh":
return _isMacintosh;
case "_isLinux":
return _isLinux;
case "_isFreeBSD":
return _isFreeBSD;
case "_isWeb":
return _isWeb;
case "_isNative":
return _isNative;
case "PlatformToString":
return PlatformToString;
case "_platform":
return _platform;
case "isRootUser":
return isRootUser;
case "g":
return g;
case "_globals":
return _globals;
case "_setImmediate":
return _setImmediate;
case "setImmediate":
return setImmediate;
case "_wl":
return _wl;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {
case "_isWindows":
return _isWindows = _value;
case "_isMacintosh":
return _isMacintosh = _value;
case "_isLinux":
return _isLinux = _value;
case "_isFreeBSD":
return _isFreeBSD = _value;
case "_isWeb":
return _isWeb = _value;
case "_isNative":
return _isNative = _value;
case "_platform":
return _platform = _value;
case "_setImmediate":
return _setImmediate = _value;
}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

View File

@@ -0,0 +1,23 @@
/**
* Converts HTML characters inside the string to use entities instead. Makes the string safe from
* being used e.g. in HTMLElement.innerHTML.
*/
export declare function escape(html: string): string;
/**
* Removes all occurrences of needle from the beginning and end of haystack.
* @param haystack string to trim
* @param needle the thing to trim (default is a blank)
*/
export declare function trim(haystack: string, needle?: string): string;
/**
* Removes all occurrences of needle from the beginning of haystack.
* @param haystack string to trim
* @param needle the thing to trim
*/
export declare function ltrim(haystack: string, needle: string): string;
/**
* Removes all occurrences of needle from the end of haystack.
* @param haystack string to trim
* @param needle the thing to trim
*/
export declare function rtrim(haystack: string, needle: string): string;

View File

@@ -0,0 +1,273 @@
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.rtrim = exports.ltrim = exports.trim = exports.escape = void 0;
/**
* Converts HTML characters inside the string to use entities instead. Makes the string safe from
* being used e.g. in HTMLElement.innerHTML.
*/
function escape(html) {
return html.replace(/[<>&]/g, function (match) {
switch (match) {
case '<':
return '&lt;';
case '>':
return '&gt;';
case '&':
return '&amp;';
default:
return match;
}
});
}
exports.escape = _get__("escape");
/**
* Removes all occurrences of needle from the beginning and end of haystack.
* @param haystack string to trim
* @param needle the thing to trim (default is a blank)
*/
function trim(haystack, needle = ' ') {
const trimmed = _get__("ltrim")(haystack, needle);
return _get__("rtrim")(trimmed, needle);
}
exports.trim = _get__("trim");
/**
* Removes all occurrences of needle from the beginning of haystack.
* @param haystack string to trim
* @param needle the thing to trim
*/
function ltrim(haystack, needle) {
if (!haystack || !needle) {
return haystack;
}
const needleLen = needle.length;
if (needleLen === 0 || haystack.length === 0) {
return haystack;
}
let offset = 0;
while (haystack.indexOf(needle, offset) === offset) {
offset = offset + needleLen;
}
return haystack.substring(offset);
}
exports.ltrim = _get__("ltrim");
/**
* Removes all occurrences of needle from the end of haystack.
* @param haystack string to trim
* @param needle the thing to trim
*/
function rtrim(haystack, needle) {
if (!haystack || !needle) {
return haystack;
}
const needleLen = needle.length,
haystackLen = haystack.length;
if (needleLen === 0 || haystackLen === 0) {
return haystack;
}
let offset = haystackLen,
idx = -1;
while (true) {
idx = haystack.lastIndexOf(needle, offset - 1);
if (idx === -1 || idx + needleLen !== offset) {
break;
}
if (idx === 0) {
return '';
}
offset = idx;
}
return haystack.substring(0, offset);
}
exports.rtrim = _get__("rtrim");
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "escape":
return escape;
case "ltrim":
return ltrim;
case "rtrim":
return rtrim;
case "trim":
return trim;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

58
src/app/titlebar/consts.d.ts vendored Normal file
View File

@@ -0,0 +1,58 @@
import { Color } from './base/common/color';
import { IMenuIcons } from './menubar';
export declare const INACTIVE_FOREGROUND_DARK: Color;
export declare const ACTIVE_FOREGROUND_DARK: Color;
export declare const INACTIVE_FOREGROUND: Color;
export declare const ACTIVE_FOREGROUND: Color;
export declare const DEFAULT_ITEM_SELECTOR: Color;
export declare const IS_MAC_BIGSUR_OR_LATER: boolean;
export declare const BOTTOM_TITLEBAR_HEIGHT = 60;
export declare const TOP_TITLEBAR_HEIGHT_MAC: number;
export declare const TOP_TITLEBAR_HEIGHT_WIN = 30;
export declare const WINDOW_MIN_WIDTH = 400;
export declare const WINDOW_MIN_HEIGHT = 270;
export declare const MENU_MNEMONIC_REGEX: RegExp;
export declare const MENU_ESCAPED_MNEMONIC_REGEX: RegExp;
interface ITitlebarIcons extends IMenuIcons {
linux: {
minimize: string;
maximize: string;
restore: string;
close: string;
};
freebsd: {
minimize: string;
maximize: string;
restore: string;
close: string;
};
windows: {
minimize: string;
maximize: string;
restore: string;
close: string;
};
}
export declare const menuIcons: ITitlebarIcons;
export declare function getPx(value: number): string;
/**
* Handles mnemonics for menu items. Depending on OS:
* - Windows: Supported via & character (replace && with &)
* - Linux: Supported via & character (replace && with &)
* - FreeBSD: Supported via & character (replace && with &)
* - macOS: Unsupported (replace && with empty string)
*/
export declare function mnemonicMenuLabel(label: string, forceDisableMnemonics?: boolean): string;
/**
* Handles mnemonics for buttons. Depending on OS:
* - Windows: Supported via & character (replace && with & and & with && for escaping)
* - Linux: Supported via _ character (replace && with _)
* - FreeBSD: Supported via _ character (replace && with _)
* - macOS: Unsupported (replace && with empty string)
*/
export declare function mnemonicButtonLabel(label: string, forceDisableMnemonics?: boolean): string;
export declare function cleanMnemonic(label: string): string;
export declare function parseAccelerator(accelerator: Electron.Accelerator | string): string;
export declare function applyFill(element: HTMLElement | undefined | null, svgColor: Color | undefined, fgColor: Color | undefined, color?: boolean): void;
export declare function loadWindowIcons(icons: string | undefined): any;
export {};

317
src/app/titlebar/consts.js Normal file
View File

@@ -0,0 +1,317 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) AlexTorresDev. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.loadWindowIcons = exports.applyFill = exports.parseAccelerator = exports.cleanMnemonic = exports.mnemonicButtonLabel = exports.mnemonicMenuLabel = exports.getPx = exports.menuIcons = exports.MENU_ESCAPED_MNEMONIC_REGEX = exports.MENU_MNEMONIC_REGEX = exports.WINDOW_MIN_HEIGHT = exports.WINDOW_MIN_WIDTH = exports.TOP_TITLEBAR_HEIGHT_WIN = exports.TOP_TITLEBAR_HEIGHT_MAC = exports.BOTTOM_TITLEBAR_HEIGHT = exports.IS_MAC_BIGSUR_OR_LATER = exports.DEFAULT_ITEM_SELECTOR = exports.ACTIVE_FOREGROUND = exports.INACTIVE_FOREGROUND = exports.ACTIVE_FOREGROUND_DARK = exports.INACTIVE_FOREGROUND_DARK = void 0;
const color_1 = require("./base/common/color");
const platform_1 = require("./base/common/platform");
exports.INACTIVE_FOREGROUND_DARK = _get__("color_1").Color.fromHex('#222222');
exports.ACTIVE_FOREGROUND_DARK = _get__("color_1").Color.fromHex('#333333');
exports.INACTIVE_FOREGROUND = _get__("color_1").Color.fromHex('#EEEEEE');
exports.ACTIVE_FOREGROUND = _get__("color_1").Color.fromHex('#FFFFFF');
exports.DEFAULT_ITEM_SELECTOR = _get__("color_1").Color.fromHex('#0000001F');
exports.IS_MAC_BIGSUR_OR_LATER = _get__("platform_1").isMacintosh && parseInt(process.getSystemVersion().split('.')[0]) >= 11;
exports.BOTTOM_TITLEBAR_HEIGHT = 60;
exports.TOP_TITLEBAR_HEIGHT_MAC = exports.IS_MAC_BIGSUR_OR_LATER ? 28 : 22;
exports.TOP_TITLEBAR_HEIGHT_WIN = 30;
exports.WINDOW_MIN_WIDTH = 400;
exports.WINDOW_MIN_HEIGHT = 270;
exports.MENU_MNEMONIC_REGEX = /\(&([^\s&])\)|(^|[^&])&([^\s&])/;
exports.MENU_ESCAPED_MNEMONIC_REGEX = /(&amp;)?(&amp;)([^\s&])/g;
exports.menuIcons = {
submenuIndicator: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none" /><polyline points="9 6 15 12 9 18" /></svg>',
checkbox: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M5 12l5 5l10 -10" /></svg>',
radioChecked: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path fill="currentColor" d="M10,5 C7.2,5 5,7.2 5,10 C5,12.8 7.2,15 10,15 C12.8,15 15,12.8 15,10 C15,7.2 12.8,5 10,5 L10,5 Z M10,0 C4.5,0 0,4.5 0,10 C0,15.5 4.5,20 10,20 C15.5,20 20,15.5 20,10 C20,4.5 15.5,0 10,0 L10,0 Z M10,18 C5.6,18 2,14.4 2,10 C2,5.6 5.6,2 10,2 C14.4,2 18,5.6 18,10 C18,14.4 14.4,18 10,18 L10,18 Z" /></svg>',
radioUnchecked: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path fill="currentColor" d="M10,0 C4.5,0 0,4.5 0,10 C0,15.5 4.5,20 10,20 C15.5,20 20,15.5 20,10 C20,4.5 15.5,0 10,0 L10,0 Z M10,18 C5.6,18 2,14.4 2,10 C2,5.6 5.6,2 10,2 C14.4,2 18,5.6 18,10 C18,14.4 14.4,18 10,18 L10,18 Z" /></svg>',
linux: {
minimize: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 11 11"><path d="M11,4.9v1.1H0V4.399h11z"/></svg>',
maximize: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 11 11"><path d="M0,1.7v7.6C0,10.2,0.8,11,1.7,11h7.6c0.9,0,1.7-0.8,1.7-1.7V1.7C11,0.8,10.2,0,9.3,0H1.7C0.8,0,0,0.8,0,1.7z M8.8,9.9H2.2c-0.6,0-1.1-0.5-1.1-1.1V2.2c0-0.6,0.5-1.1,1.1-1.1h6.7c0.6,0,1.1,0.5,1.1,1.1v6.7C9.9,9.4,9.4,9.9,8.8,9.9z"/></svg>',
restore: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 11 11"><path d="M7.9,2.2h-7C0.4,2.2,0,2.6,0,3.1v7C0,10.6,0.4,11,0.9,11h7c0.5,0,0.9-0.4,0.9-0.9v-7C8.8,2.6,8.4,2.2,7.9,2.2z M7.7,9.6 c0,0.2-0.1,0.3-0.3,0.3h-6c-0.2,0-0.3-0.1-0.3-0.3v-6c0-0.2,0.1-0.3,0.3-0.3h6c0.2,0,0.3,0.1,0.3,0.3V9.6z M10,0.9 c0,0.5-0.4,0.9-0.9,0.9h-2.1 c-0.5,0-0.9-0.4-0.9-0.9V0.9c0-0.5,0.4-0.9,0.9-0.9h2.1C9.6,0,10,0.4,10,0.9z"/></svg>',
close: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 11 11"><path d="M6.279 5.5L11 10.221l-.779.779L5.5 6.279.779 11 0 10.221 4.721 5.5 0 .779.779 0 5.5 4.721 10.221 0 11 .779 6.279 5.5z"/></svg>'
},
freebsd: {
minimize: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 11 11"><path d="M11,4.9v1.1H0V4.399h11z"/></svg>',
maximize: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 11 11"><path d="M0,1.7v7.6C0,10.2,0.8,11,1.7,11h7.6c0.9,0,1.7-0.8,1.7-1.7V1.7C11,0.8,10.2,0,9.3,0H1.7C0.8,0,0,0.8,0,1.7z M8.8,9.9H2.2c-0.6,0-1.1-0.5-1.1-1.1V2.2c0-0.6,0.5-1.1,1.1-1.1h6.7c0.6,0,1.1,0.5,1.1,1.1v6.7C9.9,9.4,9.4,9.9,8.8,9.9z"/></svg>',
restore: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 11 11"><path d="M7.9,2.2h-7C0.4,2.2,0,2.6,0,3.1v7C0,10.6,0.4,11,0.9,11h7c0.5,0,0.9-0.4,0.9-0.9v-7C8.8,2.6,8.4,2.2,7.9,2.2z M7.7,9.6 c0,0.2-0.1,0.3-0.3,0.3h-6c-0.2,0-0.3-0.1-0.3-0.3v-6c0-0.2,0.1-0.3,0.3-0.3h6c0.2,0,0.3,0.1,0.3,0.3V9.6z M10,0.9 c0,0.5-0.4,0.9-0.9,0.9h-2.1 c-0.5,0-0.9-0.4-0.9-0.9V0.9c0-0.5,0.4-0.9,0.9-0.9h2.1C9.6,0,10,0.4,10,0.9z"/></svg>',
close: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 11 11"><path d="M6.279 5.5L11 10.221l-.779.779L5.5 6.279.779 11 0 10.221 4.721 5.5 0 .779.779 0 5.5 4.721 10.221 0 11 .779 6.279 5.5z"/></svg>'
},
windows: {
minimize: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 11 11"><path d="M11,4.9v1.1H0V4.399h11z"/></svg>',
maximize: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 11 11"><path d="M0,1.7v7.6C0,10.2,0.8,11,1.7,11h7.6c0.9,0,1.7-0.8,1.7-1.7V1.7C11,0.8,10.2,0,9.3,0H1.7C0.8,0,0,0.8,0,1.7z M8.8,9.9H2.2c-0.6,0-1.1-0.5-1.1-1.1V2.2c0-0.6,0.5-1.1,1.1-1.1h6.7c0.6,0,1.1,0.5,1.1,1.1v6.7C9.9,9.4,9.4,9.9,8.8,9.9z"/></svg>',
restore: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 11 11"><path d="M7.9,2.2h-7C0.4,2.2,0,2.6,0,3.1v7C0,10.6,0.4,11,0.9,11h7c0.5,0,0.9-0.4,0.9-0.9v-7C8.8,2.6,8.4,2.2,7.9,2.2z M7.7,9.6 c0,0.2-0.1,0.3-0.3,0.3h-6c-0.2,0-0.3-0.1-0.3-0.3v-6c0-0.2,0.1-0.3,0.3-0.3h6c0.2,0,0.3,0.1,0.3,0.3V9.6z"/><path d="M10,0H3.5v1.1h6.1c0.2,0,0.3,0.1,0.3,0.3v6.1H11V1C11,0.4,10.6,0,10,0z"/></svg>',
close: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 11 11"><path d="M6.279 5.5L11 10.221l-.779.779L5.5 6.279.779 11 0 10.221 4.721 5.5 0 .779.779 0 5.5 4.721 10.221 0 11 .779 6.279 5.5z"/></svg>'
}
};
function getPx(value) {
return `${value}px`;
}
exports.getPx = _get__("getPx");
/**
* Handles mnemonics for menu items. Depending on OS:
* - Windows: Supported via & character (replace && with &)
* - Linux: Supported via & character (replace && with &)
* - FreeBSD: Supported via & character (replace && with &)
* - macOS: Unsupported (replace && with empty string)
*/
function mnemonicMenuLabel(label, forceDisableMnemonics) {
if (_get__("platform_1").isMacintosh || forceDisableMnemonics) {
return label.replace(/\(&&\w\)|&&/g, '').replace(/&/g, _get__("platform_1").isMacintosh ? '&' : '&&');
}
return label.replace(/&&|&/g, m => m === '&' ? '&&' : '&');
}
exports.mnemonicMenuLabel = _get__("mnemonicMenuLabel");
/**
* Handles mnemonics for buttons. Depending on OS:
* - Windows: Supported via & character (replace && with & and & with && for escaping)
* - Linux: Supported via _ character (replace && with _)
* - FreeBSD: Supported via _ character (replace && with _)
* - macOS: Unsupported (replace && with empty string)
*/
function mnemonicButtonLabel(label, forceDisableMnemonics) {
if (_get__("platform_1").isMacintosh || forceDisableMnemonics) {
return label.replace(/\(&&\w\)|&&/g, '');
}
if (_get__("platform_1").isWindows) {
return label.replace(/&&|&/g, m => m === '&' ? '&&' : '&');
}
return label.replace(/&&/g, '_');
}
exports.mnemonicButtonLabel = _get__("mnemonicButtonLabel");
function cleanMnemonic(label) {
const regex = exports.MENU_MNEMONIC_REGEX;
const matches = regex.exec(label);
if (!matches) {
return label;
}
const mnemonicInText = !matches[1];
return label.replace(regex, mnemonicInText ? '$2$3' : '').trim();
}
exports.cleanMnemonic = _get__("cleanMnemonic");
function parseAccelerator(accelerator) {
let acc = accelerator.toString();
if (!_get__("platform_1").isMacintosh) {
acc = acc.replace(/(Cmd)|(Command)/gi, '');
} else {
acc = acc.replace(/(Ctrl)|(Control)/gi, '');
}
acc = acc.replace(/(Or)/gi, '');
return acc;
}
exports.parseAccelerator = _get__("parseAccelerator");
function applyFill(element, svgColor, fgColor, color = true) {
let fillColor = '';
if (svgColor) fillColor = svgColor.toString();else if (fgColor) fillColor = fgColor.toString();
if (element && element !== null) {
if (color) element.style.color = fillColor;else element.style.backgroundColor = fillColor;
}
}
exports.applyFill = _get__("applyFill");
function loadWindowIcons(icons) {
if (!icons) return;
const jWindowsIcons = require(icons);
return {
icons: jWindowsIcons,
platformIcons: jWindowsIcons[(0, _get__("platform_1").PlatformToString)(_get__("platform_1").platform).toLocaleLowerCase()]
};
}
exports.loadWindowIcons = _get__("loadWindowIcons");
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "color_1":
return color_1;
case "platform_1":
return platform_1;
case "getPx":
return getPx;
case "mnemonicMenuLabel":
return mnemonicMenuLabel;
case "mnemonicButtonLabel":
return mnemonicButtonLabel;
case "cleanMnemonic":
return cleanMnemonic;
case "parseAccelerator":
return parseAccelerator;
case "applyFill":
return applyFill;
case "loadWindowIcons":
return loadWindowIcons;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

3
src/app/titlebar/index.d.ts vendored Normal file
View File

@@ -0,0 +1,3 @@
import { CustomTitlebar } from './titlebar';
import { Color } from './base/common/color';
export { CustomTitlebar, CustomTitlebar as Titlebar, Color as TitlebarColor };

211
src/app/titlebar/index.js Normal file
View File

@@ -0,0 +1,211 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) AlexTorresDev. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.TitlebarColor = exports.Titlebar = exports.CustomTitlebar = void 0;
const titlebar_1 = require("./titlebar");
Object.defineProperty(exports, "CustomTitlebar", {
enumerable: true,
get: function () {
return _get__("titlebar_1").CustomTitlebar;
}
});
Object.defineProperty(exports, "Titlebar", {
enumerable: true,
get: function () {
return _get__("titlebar_1").CustomTitlebar;
}
});
const color_1 = require("./base/common/color");
Object.defineProperty(exports, "TitlebarColor", {
enumerable: true,
get: function () {
return _get__("color_1").Color;
}
});
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "titlebar_1":
return titlebar_1;
case "color_1":
return color_1;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

View File

@@ -0,0 +1,3 @@
import { BrowserWindow } from 'electron';
declare const _default: (browserWindow: BrowserWindow) => void;
export default _default;

View File

@@ -0,0 +1,210 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
/* ---------------------------------------------------------------------------------------------
* Copyright (c) AlexTorresDev. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
const consts_1 = require("../consts");
exports.default = browserWindow => {
browserWindow.setMinimumSize(_get__("consts_1").WINDOW_MIN_WIDTH, _get__("consts_1").WINDOW_MIN_HEIGHT);
browserWindow.on('enter-full-screen', () => {
browserWindow.webContents.send('window-fullscreen', true);
});
browserWindow.on('leave-full-screen', () => {
browserWindow.webContents.send('window-fullscreen', false);
});
browserWindow.on('focus', () => {
browserWindow.webContents.send('window-focus', true);
});
browserWindow.on('blur', () => {
browserWindow.webContents.send('window-focus', false);
});
browserWindow.on('maximize', () => {
browserWindow.webContents.send('window-maximize', true);
});
browserWindow.on('unmaximize', () => {
browserWindow.webContents.send('window-maximize', false);
});
};
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "consts_1":
return consts_1;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

3
src/app/titlebar/main/index.d.ts vendored Normal file
View File

@@ -0,0 +1,3 @@
import attachTitlebarToWindow from './attach-titlebar-to-window';
import setupTitlebar from './setup-titlebar';
export { setupTitlebar, attachTitlebarToWindow };

View File

@@ -0,0 +1,202 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) AlexTorresDev. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
var __importDefault = this && this.__importDefault || function (mod) {
return mod && mod.__esModule ? mod : {
"default": mod
};
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.attachTitlebarToWindow = exports.setupTitlebar = void 0;
const attach_titlebar_to_window_1 = _get__("__importDefault")(require("./attach-titlebar-to-window"));
exports.attachTitlebarToWindow = _get__("attach_titlebar_to_window_1").default;
const setup_titlebar_1 = _get__("__importDefault")(require("./setup-titlebar"));
exports.setupTitlebar = _get__("setup_titlebar_1").default;
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "__importDefault":
return __importDefault;
case "attach_titlebar_to_window_1":
return attach_titlebar_to_window_1;
case "setup_titlebar_1":
return setup_titlebar_1;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

View File

@@ -0,0 +1,2 @@
declare const _default: () => void;
export default _default;

View File

@@ -0,0 +1,255 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) AlexTorresDev. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = () => {
if (process.type !== 'browser') return;
const {
BrowserWindow,
Menu,
MenuItem,
ipcMain
} = require('electron');
// Send menu to renderer title bar process
ipcMain.handle('request-application-menu', async () => JSON.parse(JSON.stringify(Menu.getApplicationMenu(), (key, value) => key !== 'commandsMap' && key !== 'menu' ? value : undefined)));
// Handle window events
ipcMain.on('window-event', (event, eventName) => {
const window = BrowserWindow.fromWebContents(event.sender);
/* eslint-disable indent */
if (window) {
switch (eventName) {
case 'window-minimize':
window?.minimize();
break;
case 'window-maximize':
window?.isMaximized() ? window.unmaximize() : window?.maximize();
break;
case 'window-close':
window?.close();
break;
case 'window-is-maximized':
event.returnValue = window?.isMaximized();
break;
default:
break;
}
}
});
// Handle menu events
ipcMain.on('menu-event', (event, commandId) => {
const item = _get__("getMenuItemByCommandId")(commandId, Menu.getApplicationMenu());
if (item) item.click(undefined, BrowserWindow.fromWebContents(event.sender), event.sender);
});
// Handle menu item icon
ipcMain.on('menu-icon', (event, commandId) => {
const item = _get__("getMenuItemByCommandId")(commandId, Menu.getApplicationMenu());
if (item && item.icon && typeof item.icon !== 'string') {
event.returnValue = item.icon.toDataURL();
} else {
event.returnValue = null;
}
});
ipcMain.on('update-window-controls', (event, args) => {
const window = BrowserWindow.fromWebContents(event.sender);
try {
if (window) window.setTitleBarOverlay(args);
event.returnValue = true;
} catch (_) {
event.returnValue = false;
}
});
};
function getMenuItemByCommandId(commandId, menu) {
if (!menu) return undefined;
for (const item of menu.items) {
if (item.submenu) {
const submenuItem = _get__("getMenuItemByCommandId")(commandId, item.submenu);
if (submenuItem) return submenuItem;
} else if (item.commandId === commandId) return item;
}
return undefined;
}
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "getMenuItemByCommandId":
return getMenuItemByCommandId;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

86
src/app/titlebar/menubar/index.d.ts vendored Normal file
View File

@@ -0,0 +1,86 @@
import { Menu } from 'electron';
import { Event } from '../base/common/event';
import { Disposable } from '../base/common/lifecycle';
import { MenuBarOptions } from './menubar-options';
import { Direction } from './menu';
import { IMenuStyle } from './menu/item';
export interface IMenuIcons {
readonly submenuIndicator: string;
readonly checkbox: string;
readonly radioChecked: string;
readonly radioUnchecked: string;
}
export interface IMenuBarOptions {
enableMnemonics?: boolean;
disableAltFocus?: boolean;
visibility?: string;
alwaysOnMnemonics?: boolean;
compactMode?: Direction;
}
export interface MenuBarMenu {
actions?: Menu;
label: string;
}
export declare class MenuBar extends Disposable {
private container;
private menuIcons;
private currentOptions;
private options;
private closeMenu;
static readonly OVERFLOW_INDEX: number;
private menus;
private overflowMenu;
private focusedMenu;
private focusToReturn;
private menuUpdater;
private _mnemonicsInUse;
private openedViaKeyboard;
private awaitingAltRelease;
private ignoreNextMouseUp;
private mnemonics;
private updatePending;
private _focusState;
private readonly _onVisibilityChange;
private readonly _onFocusStateChange;
private numMenusShown;
private overflowLayoutScheduled;
private menuStyle;
constructor(container: HTMLElement, menuIcons: IMenuIcons, currentOptions: MenuBarOptions, options: IMenuBarOptions, closeMenu?: () => void);
private registerListeners;
push(menu: Menu): void;
createOverflowMenu(): void;
setStyles(style: IMenuStyle): void;
updateMenu(menu: MenuBarMenu): void;
dispose(): void;
blur(): void;
getWidth(): number;
getHeight(): number;
toggleFocus(): void;
private updateOverflowAction;
private updateLabels;
update(options?: IMenuBarOptions): void;
private registerMnemonic;
private hideMenubar;
private showMenubar;
private get focusState();
private set focusState(value);
get isVisible(): boolean;
private get isFocused();
private get isOpen();
private get hasOverflow();
private get isCompact();
private setUnfocusedState;
private focusPrevious;
private focusNext;
private updateMnemonicVisibility;
private get mnemonicsInUse();
private set mnemonicsInUse(value);
private get shouldAltKeyFocus();
get onVisibilityChange(): Event<boolean>;
get onFocusStateChange(): Event<boolean>;
private onMenuTriggered;
private onModifierKeyToggled;
private isCurrentMenu;
private cleanupMenu;
private showMenu;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,46 @@
import { MenuItem } from 'electron';
import { Disposable } from '../../base/common/lifecycle';
import { IMenuStyle } from './item';
import { Event } from '../../base/common/event';
import { MenuBarOptions } from '../menubar-options';
import { ISubMenuData } from './submenu';
import { IMenuIcons } from '../../menubar';
export declare enum Direction {
Right = 0,
Left = 1
}
export interface IMenuOptions {
ariaLabel?: string;
enableMnemonics?: boolean;
}
export declare class CETMenu extends Disposable {
private menuContainer;
private menuIcons;
private parentOptions;
private currentOptions;
private closeSubMenu;
private focusedItem?;
private items;
private mnemonics;
private triggerKeys;
parentData: ISubMenuData;
private _onDidCancel;
constructor(menuContainer: HTMLElement, menuIcons: IMenuIcons, parentOptions: MenuBarOptions, currentOptions: IMenuOptions, closeSubMenu?: () => void);
trigger(index: number): void;
createMenu(menuItems: MenuItem[] | undefined): void;
private isTriggerKeyEvent;
private updateFocusedItem;
focus(index?: number): void;
focus(selectFirst?: boolean): void;
private focusNext;
private focusPrevious;
private updateFocus;
private doTrigger;
private cancel;
private focusItemByElement;
private setFocusedItem;
applyStyle(style: IMenuStyle): void;
get container(): HTMLElement;
get onDidCancel(): Event<void>;
dispose(): void;
}

View File

@@ -0,0 +1,565 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) AlexTorresDev. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CETMenu = exports.Direction = void 0;
const dom_1 = require("../../base/common/dom");
const lifecycle_1 = require("../../base/common/lifecycle");
const item_1 = require("./item");
const keyCodes_1 = require("../../base/common/keyCodes");
const keyboardEvent_1 = require("../../base/browser/keyboardEvent");
const event_1 = require("../../base/common/event");
const separator_1 = require("./separator");
const submenu_1 = require("./submenu");
const platform_1 = require("../../base/common/platform");
var Direction;
(function (Direction) {
Direction[Direction["Right"] = 0] = "Right";
Direction[Direction["Left"] = 1] = "Left";
})(_get__("Direction") || (exports.Direction = _assign__("Direction", {})));
class CETMenu extends _get__("lifecycle_1").Disposable {
constructor(menuContainer, menuIcons, parentOptions, currentOptions, closeSubMenu = () => {}) {
super();
this.menuContainer = menuContainer;
this.menuIcons = menuIcons;
this.parentOptions = parentOptions;
this.currentOptions = currentOptions;
this.closeSubMenu = closeSubMenu;
this.focusedItem = undefined;
this.items = [];
this.triggerKeys = {
keys: [3 /* KeyCode.Enter */, 10 /* KeyCode.Space */],
keyDown: true
};
this.parentData = {
parent: this
};
this._onDidCancel = this._register(new (_get__("event_1").Emitter)());
this.mnemonics = new Map();
this._register((0, _get__("dom_1").addDisposableListener)(this.menuContainer, _get__("dom_1").EventType.KEY_DOWN, e => {
const event = new (_get__("keyboardEvent_1").StandardKeyboardEvent)(e);
let eventHandled = true;
if (event.equals(16 /* KeyCode.UpArrow */)) {
this.focusPrevious();
} else if (event.equals(18 /* KeyCode.DownArrow */)) {
this.focusNext();
} else if (event.equals(9 /* KeyCode.Escape */)) {
this.cancel();
} else if (this.isTriggerKeyEvent(event)) {
// Staying out of the else branch even if not triggered
if (this.triggerKeys && this.triggerKeys.keyDown) {
this.doTrigger(event);
}
} else {
eventHandled = false;
}
if (eventHandled) {
event.preventDefault();
event.stopPropagation();
}
}));
this._register((0, _get__("dom_1").addDisposableListener)(this.menuContainer, _get__("dom_1").EventType.KEY_UP, e => {
const event = new (_get__("keyboardEvent_1").StandardKeyboardEvent)(e);
// Run action on Enter/Space
if (this.isTriggerKeyEvent(event)) {
if (this.triggerKeys && !this.triggerKeys.keyDown) {
this.doTrigger(event);
}
event.preventDefault();
event.stopPropagation();
// Recompute focused item
} else if (event.equals(2 /* KeyCode.Tab */) || event.equals(1024 /* KeyMod.Shift */ | 2 /* KeyCode.Tab */)) {
this.updateFocusedItem();
}
}));
if (this.currentOptions.enableMnemonics) {
this._register((0, _get__("dom_1").addDisposableListener)(this.menuContainer, _get__("dom_1").EventType.KEY_DOWN, e => {
const key = _get__("keyCodes_1").KeyCodeUtils.fromString(e.key);
if (this.mnemonics.has(key)) {
const items = this.mnemonics.get(key);
if (items.length === 1) {
if (items[0] instanceof _get__("submenu_1").CETSubMenu) {
this.focusItemByElement(items[0].element);
}
items[0].onClick(e);
}
if (items.length > 1) {
const item = items.shift();
if (item) {
this.focusItemByElement(item.element);
items.push(item);
}
this.mnemonics.set(key, items);
}
}
}));
}
if (_get__("platform_1").isLinux) {
this._register((0, _get__("dom_1").addDisposableListener)(this.menuContainer, _get__("dom_1").EventType.KEY_DOWN, e => {
const event = new (_get__("keyboardEvent_1").StandardKeyboardEvent)(e);
if (event.equals(14 /* KeyCode.Home */) || event.equals(11 /* KeyCode.PageUp */)) {
this.focusedItem = this.items.length - 1;
this.focusNext();
_get__("dom_1").EventHelper.stop(e, true);
} else if (event.equals(13 /* KeyCode.End */) || event.equals(12 /* KeyCode.PageDown */)) {
this.focusedItem = 0;
this.focusPrevious();
_get__("dom_1").EventHelper.stop(e, true);
}
}));
}
if (_get__("platform_1").isFreeBSD) {
this._register((0, _get__("dom_1").addDisposableListener)(this.menuContainer, _get__("dom_1").EventType.KEY_DOWN, e => {
const event = new (_get__("keyboardEvent_1").StandardKeyboardEvent)(e);
if (event.equals(14 /* KeyCode.Home */) || event.equals(11 /* KeyCode.PageUp */)) {
this.focusedItem = this.items.length - 1;
this.focusNext();
_get__("dom_1").EventHelper.stop(e, true);
} else if (event.equals(13 /* KeyCode.End */) || event.equals(12 /* KeyCode.PageDown */)) {
this.focusedItem = 0;
this.focusPrevious();
_get__("dom_1").EventHelper.stop(e, true);
}
}));
}
this._register((0, _get__("dom_1").addDisposableListener)(this.menuContainer, _get__("dom_1").EventType.MOUSE_OUT, e => {
const relatedTarget = e.relatedTarget;
if (!(0, _get__("dom_1").isAncestor)(relatedTarget, this.menuContainer)) {
this.focusedItem = undefined;
this.updateFocus();
e.stopPropagation();
}
}));
this._register((0, _get__("dom_1").addDisposableListener)(this.menuContainer, _get__("dom_1").EventType.MOUSE_UP, e => {
// Absorb clicks in menu dead space https://github.com/Microsoft/vscode/issues/63575
_get__("dom_1").EventHelper.stop(e, true);
}));
this._register((0, _get__("dom_1").addDisposableListener)(this.menuContainer, _get__("dom_1").EventType.MOUSE_OVER, e => {
let target = e.target;
if (!target || !(0, _get__("dom_1").isAncestor)(target, this.menuContainer) || target === this.menuContainer) {
return;
}
while (target.parentElement !== this.menuContainer && target.parentElement !== null) {
target = target.parentElement;
}
if ((0, _get__("dom_1").hasClass)(target, 'cet-action-item')) {
const lastFocusedItem = this.focusedItem;
this.setFocusedItem(target);
if (lastFocusedItem !== this.focusedItem) {
this.updateFocus();
}
}
}));
if (this.currentOptions.ariaLabel) {
this.menuContainer.setAttribute('aria-label', this.currentOptions.ariaLabel);
}
}
trigger(index) {
if (index <= this.items.length && index >= 0) {
const item = this.items[index];
if (item instanceof _get__("submenu_1").CETSubMenu) {
this.focus(index);
}
}
}
createMenu(menuItems) {
if (!menuItems) return;
menuItems.forEach(menuItem => {
if (!menuItem) return;
const itemElement = (0, _get__("dom_1").$)('li.cet-action-item', {
role: 'presentation'
});
// Prevent native context menu on actions
this._register((0, _get__("dom_1").addDisposableListener)(itemElement, _get__("dom_1").EventType.CONTEXT_MENU, e => {
e.preventDefault();
e.stopPropagation();
}));
let item;
if (menuItem.type === 'separator') {
item = new (_get__("separator_1").CETSeparator)(menuItem, this.menuIcons, this.parentOptions, this.currentOptions);
} else if (menuItem.type === 'submenu' || menuItem.submenu) {
const submenuItems = menuItem.submenu.items;
item = new (_get__("submenu_1").CETSubMenu)(menuItem, this.menuIcons, submenuItems, this.parentData, this.parentOptions, this.currentOptions, this.closeSubMenu);
if (this.currentOptions.enableMnemonics) {
const mnemonic = item.mnemonic;
if (mnemonic && item.isEnabled()) {
let actionItems = [];
if (this.mnemonics.has(mnemonic)) {
actionItems = this.mnemonics.get(mnemonic);
}
actionItems.push(item);
this.mnemonics.set(mnemonic, actionItems);
}
}
} else {
item = new (_get__("item_1").CETMenuItem)(menuItem, this.menuIcons, this.parentOptions, this.currentOptions, this.items, this.closeSubMenu);
if (this.currentOptions.enableMnemonics) {
const mnemonic = item.mnemonic;
if (mnemonic && item.isEnabled()) {
let actionItems = [];
if (this.mnemonics.has(mnemonic)) {
actionItems = this.mnemonics.get(mnemonic);
}
actionItems.push(item);
this.mnemonics.set(mnemonic, actionItems);
}
}
}
item.render(itemElement);
this.items.push(item);
(0, _get__("dom_1").append)(this.menuContainer, itemElement);
});
}
isTriggerKeyEvent(event) {
let ret = false;
if (this.triggerKeys) {
this.triggerKeys.keys.forEach(keyCode => {
ret = ret || event.equals(keyCode);
});
}
return ret;
}
updateFocusedItem() {
for (let i = 0; i < this.menuContainer.children.length; i++) {
const elem = this.menuContainer.children[i];
if ((0, _get__("dom_1").isAncestor)(document.activeElement, elem)) {
this.focusedItem = i;
break;
}
}
}
focus(arg) {
let selectFirst = false;
let index;
if (arg === undefined) {
selectFirst = true;
} else if (typeof arg === 'number') {
index = arg;
} else if (typeof arg === 'boolean') {
selectFirst = arg;
}
if (selectFirst && typeof this.focusedItem === 'undefined') {
// Focus the first enabled item
this.focusedItem = this.items.length - 1;
this.focusNext();
} else {
if (index !== undefined) {
this.focusedItem = index;
}
this.updateFocus();
}
}
focusNext() {
if (typeof this.focusedItem === 'undefined') {
this.focusedItem = this.items.length - 1;
}
const startIndex = this.focusedItem;
let item;
do {
this.focusedItem = (this.focusedItem + 1) % this.items.length;
item = this.items[this.focusedItem];
} while (this.focusedItem !== startIndex && !item.isEnabled() || item.isSeparator());
if (this.focusedItem === startIndex && !item.isEnabled() || item.isSeparator()) {
this.focusedItem = undefined;
}
this.updateFocus();
}
focusPrevious() {
if (typeof this.focusedItem === 'undefined') {
this.focusedItem = 0;
}
const startIndex = this.focusedItem;
let item;
do {
this.focusedItem = this.focusedItem - 1;
if (this.focusedItem < 0) {
this.focusedItem = this.items.length - 1;
}
item = this.items[this.focusedItem];
} while (this.focusedItem !== startIndex && !item.isEnabled() || item.isSeparator());
if (this.focusedItem === startIndex && !item.isEnabled() || item.isSeparator()) {
this.focusedItem = undefined;
}
this.updateFocus();
}
updateFocus() {
if (typeof this.focusedItem === 'undefined') {
this.menuContainer.focus();
}
for (let i = 0; i < this.items.length; i++) {
const item = this.items[i];
if (i === this.focusedItem) {
if (item.isEnabled()) {
item.focus();
} else {
this.menuContainer.focus();
}
} else {
item.blur();
}
}
}
doTrigger(event) {
if (typeof this.focusedItem === 'undefined') {
return; // nothing to focus
}
// trigger action
const item = this.items[this.focusedItem];
if (item instanceof _get__("item_1").CETMenuItem) {
item.onClick(event);
}
}
cancel() {
if (document.activeElement instanceof HTMLElement) {
document.activeElement.blur(); // remove focus from focused action
}
this._onDidCancel.fire();
}
focusItemByElement(element) {
const lastFocusedItem = this.focusedItem;
if (element) this.setFocusedItem(element);
if (lastFocusedItem !== this.focusedItem) {
this.updateFocus();
}
}
setFocusedItem(element) {
this.focusedItem = Array.prototype.findIndex.call(this.container.children, elem => elem === element);
}
applyStyle(style) {
const container = this.menuContainer;
if (style?.backgroundColor) {
let transparency = this.parentOptions?.menuTransparency;
if (transparency < 0) transparency = 0;
if (transparency > 1) transparency = 1;
const rgba = style.backgroundColor?.rgba;
container.style.backgroundColor = `rgb(${rgba.r} ${rgba.g} ${rgba.b} / ${1 - transparency})`;
}
if (this.items) {
this.items.forEach(item => {
if (item instanceof _get__("item_1").CETMenuItem || item instanceof _get__("separator_1").CETSeparator) {
item.updateStyle(style);
}
});
}
}
get container() {
return this.menuContainer;
}
get onDidCancel() {
return this._onDidCancel.event;
}
dispose() {
(0, _get__("lifecycle_1").dispose)(this.items);
this.items = [];
(0, _get__("dom_1").removeNode)(this.container);
super.dispose();
}
}
exports.CETMenu = _get__("CETMenu");
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "Direction":
return Direction;
case "event_1":
return event_1;
case "dom_1":
return dom_1;
case "keyboardEvent_1":
return keyboardEvent_1;
case "keyCodes_1":
return keyCodes_1;
case "submenu_1":
return submenu_1;
case "platform_1":
return platform_1;
case "separator_1":
return separator_1;
case "item_1":
return item_1;
case "lifecycle_1":
return lifecycle_1;
case "CETMenu":
return CETMenu;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {
case "Direction":
return Direction = _value;
}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

67
src/app/titlebar/menubar/menu/item.d.ts vendored Normal file
View File

@@ -0,0 +1,67 @@
import { MenuItem } from 'electron';
import { Color } from '../../base/common/color';
import { EventLike } from '../../base/common/dom';
import { KeyCode } from '../../base/common/keyCodes';
import { Disposable } from '../../base/common/lifecycle';
import { MenuBarOptions } from '../menubar-options';
import { IMenuOptions } from './index';
import { IMenuIcons } from '../../menubar';
export interface IMenuStyle {
foregroundColor?: Color;
backgroundColor?: Color;
selectionForegroundColor?: Color;
selectionBackgroundColor?: Color;
separatorColor?: Color;
svgColor?: Color;
}
export interface IMenuItem {
render(element: HTMLElement): void;
updateStyle(style: IMenuStyle): void;
onClick(event: EventLike): void;
dispose(): void;
isEnabled(): boolean;
isSeparator(): boolean;
focus(): void;
blur(): void;
}
export declare class CETMenuItem extends Disposable implements IMenuItem {
private _item;
private menuIcons;
private parentOptions;
private options;
private menuItems?;
private closeSubMenu;
private _mnemonic?;
private _currentElement?;
private labelElement?;
private iconElement?;
protected itemElement?: HTMLElement;
protected menuStyle?: IMenuStyle;
private radioGroup?;
constructor(_item: MenuItem, menuIcons: IMenuIcons, parentOptions: MenuBarOptions, options: IMenuOptions, menuItems?: IMenuItem[] | undefined, closeSubMenu?: () => void);
render(el: HTMLElement): void;
onClick(event: EventLike): void;
protected applyStyle(): void;
updateStyle(style: IMenuStyle): void;
focus(): void;
blur(): void;
setAccelerator(): void;
updateLabel(): void;
updateIcon(): void;
updateTooltip(): void;
updateEnabled(): void;
updateVisibility(): void;
updateChecked(): void;
updateRadioGroup(): void;
/** radioGroup index's starts with (previous separator +1 OR menuItems[0]) and ends with (next separator OR menuItems[length]) */
getRadioGroup(): {
start: number;
end: number;
};
get element(): HTMLElement | undefined;
get item(): MenuItem;
isEnabled(): boolean;
isSeparator(): boolean;
get mnemonic(): KeyCode | undefined;
dispose(): void;
}

View File

@@ -0,0 +1,575 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) AlexTorresDev. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
var __createBinding = this && this.__createBinding || (Object.create ? function (o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = {
enumerable: true,
get: function () {
return m[k];
}
};
}
Object.defineProperty(o, k2, desc);
} : function (o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function (o, v) {
Object.defineProperty(o, "default", {
enumerable: true,
value: v
});
} : function (o, v) {
o["default"] = v;
});
var __importStar = this && this.__importStar || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) _get__("__createBinding")(result, mod, k);
_get__("__setModuleDefault")(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CETMenuItem = void 0;
const electron_1 = require("electron");
const dom_1 = require("../../base/common/dom");
const keyCodes_1 = require("../../base/common/keyCodes");
const lifecycle_1 = require("../../base/common/lifecycle");
const consts_1 = require("../../consts");
const strings = _get__("__importStar")(require("../../base/common/strings"));
class CETMenuItem extends _get__("lifecycle_1").Disposable {
constructor(_item, menuIcons, parentOptions, options, menuItems, closeSubMenu = () => {}) {
super();
this._item = _item;
this.menuIcons = menuIcons;
this.parentOptions = parentOptions;
this.options = options;
this.menuItems = menuItems;
this.closeSubMenu = closeSubMenu;
// Set mnemonic
if (this._item.label && options.enableMnemonics) {
const label = this._item.label;
if (label) {
const matches = _get__("consts_1").MENU_MNEMONIC_REGEX.exec(label);
if (matches) {
this._mnemonic = _get__("keyCodes_1").KeyCodeUtils.fromString((!!matches[1] ? matches[1] : matches[2]).toLocaleUpperCase());
}
}
}
}
render(el) {
this._currentElement = el;
this._register((0, _get__("dom_1").addDisposableListener)(this.element, _get__("dom_1").EventType.MOUSE_DOWN, e => {
if (this.item.enabled && e.button === 0 && this.element) {
(0, _get__("dom_1").addClass)(this.element, 'active');
}
}));
this._register((0, _get__("dom_1").addDisposableListener)(this.element, _get__("dom_1").EventType.CLICK, e => {
if (this.item.enabled) {
this.onClick(e);
}
}));
this._register((0, _get__("dom_1").addDisposableListener)(this.element, _get__("dom_1").EventType.DBLCLICK, e => {
_get__("dom_1").EventHelper.stop(e, true);
}));
[_get__("dom_1").EventType.MOUSE_UP, _get__("dom_1").EventType.MOUSE_OUT].forEach(event => {
this._register((0, _get__("dom_1").addDisposableListener)(this.element, event, e => {
_get__("dom_1").EventHelper.stop(e);
(0, _get__("dom_1").removeClass)(this.element, 'active');
}));
});
this.itemElement = (0, _get__("dom_1").append)(this.element, (0, _get__("dom_1").$)('a.cet-action-menu-item'));
if (this.mnemonic) {
this.itemElement.setAttribute('aria-keyshortcuts', `${this.mnemonic}`);
}
this.iconElement = (0, _get__("dom_1").append)(this.itemElement, (0, _get__("dom_1").$)('span.cet-menu-item-icon'));
this.iconElement.setAttribute('role', 'none');
this.labelElement = (0, _get__("dom_1").append)(this.itemElement, (0, _get__("dom_1").$)('span.cet-action-label'));
this.updateLabel();
this.setAccelerator();
this.updateIcon();
this.updateTooltip();
this.updateEnabled();
this.updateChecked();
this.updateVisibility();
}
onClick(event) {
_get__("dom_1").EventHelper.stop(event, true);
_get__("electron_1").ipcRenderer.send('menu-event', this.item.commandId);
if (this.item.type === 'checkbox') {
this.item.checked = !this.item.checked;
this.updateChecked();
} else if (this.item.type === 'radio') {
this.updateRadioGroup();
}
this.closeSubMenu();
}
applyStyle() {
if (!this.menuStyle) {
return;
}
const isSelected = this.element && (0, _get__("dom_1").hasClass)(this.element, 'focused');
const fgColor = isSelected && this.menuStyle.selectionForegroundColor ? this.menuStyle.selectionForegroundColor : this.menuStyle.foregroundColor;
const bgColor = isSelected && this.menuStyle.selectionBackgroundColor ? this.menuStyle.selectionBackgroundColor : null;
if (this.itemElement) {
this.itemElement.style.color = fgColor ? fgColor.toString() : '';
this.itemElement.style.backgroundColor = bgColor ? bgColor.toString() : '';
if (this.iconElement) {
if (this.iconElement.firstElementChild?.className === 'icon') {
(0, _get__("consts_1").applyFill)(this.iconElement.firstElementChild, this.parentOptions?.svgColor, fgColor, false);
} else {
(0, _get__("consts_1").applyFill)(this.iconElement, this.parentOptions?.svgColor, fgColor);
}
}
}
}
updateStyle(style) {
this.menuStyle = style;
this.applyStyle();
}
focus() {
if (this.element) {
this.element.focus();
(0, _get__("dom_1").addClass)(this.element, 'focused');
}
this.applyStyle();
}
blur() {
if (this.element) {
this.element.blur();
(0, _get__("dom_1").removeClass)(this.element, 'focused');
}
this.applyStyle();
}
setAccelerator() {
let accelerator = null;
if (this.item.role) {
switch (this.item.role.toLocaleLowerCase()) {
case 'undo':
accelerator = 'CtrlOrCmd+Z';
break;
case 'redo':
accelerator = 'CtrlOrCmd+Y';
break;
case 'cut':
accelerator = 'CtrlOrCmd+X';
break;
case 'copy':
accelerator = 'CtrlOrCmd+C';
break;
case 'paste':
accelerator = 'CtrlOrCmd+V';
break;
case 'selectall':
accelerator = 'CtrlOrCmd+A';
break;
case 'minimize':
accelerator = 'CtrlOrCmd+M';
break;
case 'close':
accelerator = 'CtrlOrCmd+W';
break;
case 'reload':
accelerator = 'CtrlOrCmd+R';
break;
case 'forcereload':
accelerator = 'CtrlOrCmd+Shift+R';
break;
case 'toggledevtools':
accelerator = 'CtrlOrCmd+Shift+I';
break;
case 'togglefullscreen':
accelerator = 'F11';
break;
case 'resetzoom':
accelerator = 'CtrlOrCmd+0';
break;
case 'zoomin':
accelerator = 'CtrlOrCmd++';
break;
case 'zoomout':
accelerator = 'CtrlOrCmd+-';
break;
}
}
if (this.item.label && this.item.accelerator) {
accelerator = this.item.accelerator;
}
if (this.itemElement && accelerator !== null) {
(0, _get__("dom_1").append)(this.itemElement, (0, _get__("dom_1").$)('span.keybinding')).textContent = (0, _get__("consts_1").parseAccelerator)(accelerator);
}
}
updateLabel() {
const label = this.item.label || '';
const cleanMenuLabel = (0, _get__("consts_1").cleanMnemonic)(label);
// Update the button label to reflect mnemonics
if (this.options.enableMnemonics) {
const cleanLabel = _get__("strings").escape(label);
// This is global so reset it
_get__("consts_1").MENU_ESCAPED_MNEMONIC_REGEX.lastIndex = 0;
let escMatch = _get__("consts_1").MENU_ESCAPED_MNEMONIC_REGEX.exec(cleanLabel);
// We can't use negative lookbehind so we match our negative and skip
while (escMatch && escMatch[1]) {
escMatch = _get__("consts_1").MENU_ESCAPED_MNEMONIC_REGEX.exec(cleanLabel);
}
const replaceDoubleEscapes = str => str.replace(/&amp;&amp;/g, '&amp;');
if (escMatch) {
this.labelElement.innerText = '';
this.labelElement.append(_get__("strings").ltrim(replaceDoubleEscapes(cleanLabel.substring(0, escMatch.index)), ' '), (0, _get__("dom_1").$)('mnemonic', {
'aria-hidden': 'true'
}, escMatch[3]), _get__("strings").rtrim(replaceDoubleEscapes(cleanLabel.substring(escMatch.index + escMatch[0].length)), ' '));
} else {
this.labelElement.innerText = replaceDoubleEscapes(cleanLabel).trim();
}
} else {
this.labelElement.innerText = cleanMenuLabel.replace(/&&/g, '&');
}
const mnemonicMatches = _get__("consts_1").MENU_MNEMONIC_REGEX.exec(label);
// Register mnemonics
if (mnemonicMatches) {
const mnemonic = !!mnemonicMatches[1] ? mnemonicMatches[1] : mnemonicMatches[3];
if (this.options.enableMnemonics) {
this.itemElement?.setAttribute('aria-keyshortcuts', 'Alt+' + mnemonic.toLocaleLowerCase());
} else {
this.itemElement?.removeAttribute('aria-keyshortcuts');
}
}
}
updateIcon() {
if (this.item.icon) {
const icon = this.item.icon;
if (this.iconElement && icon) {
const iconE = (0, _get__("dom_1").append)(this.iconElement, (0, _get__("dom_1").$)('.icon'));
let iconData;
if (typeof this.item.icon !== 'string') {
iconData = _get__("electron_1").ipcRenderer.sendSync('menu-icon', this.item.commandId);
} else {
const iconPath = this.item.icon;
iconData = _get__("electron_1").nativeImage.createFromPath(iconPath).toDataURL();
}
if (iconData) iconE.style.webkitMaskBoxImage = `url(${iconData})`;
}
} else if (this.iconElement && this.item.type === 'checkbox') {
(0, _get__("dom_1").addClass)(this.iconElement, 'checkbox');
this.iconElement.innerHTML = this.menuIcons.checkbox;
} else if (this.item.type === 'radio') {
(0, _get__("dom_1").addClass)(this.iconElement, 'radio');
this.iconElement.innerHTML = this.item.checked ? this.menuIcons.radioChecked : this.menuIcons.radioUnchecked;
}
(0, _get__("consts_1").applyFill)(this.iconElement, this.parentOptions?.svgColor, this.menuStyle?.foregroundColor);
}
updateTooltip() {
let title = null;
if (this.item.sublabel) {
title = this.item.sublabel;
} else if (!this.item.label && this.item.label && this.item.icon) {
title = this.item.label;
if (this.item.accelerator) {
title = (0, _get__("consts_1").parseAccelerator)(this.item.accelerator);
}
}
if (this.itemElement && title) {
this.itemElement.title = title;
}
}
updateEnabled() {
if (this.element) {
if (this.item.enabled && this.item.type !== 'separator') {
(0, _get__("dom_1").removeClass)(this.element, 'disabled');
this.element.tabIndex = 0;
} else {
(0, _get__("dom_1").addClass)(this.element, 'disabled');
}
}
}
updateVisibility() {
if (this.item.visible === false && this.itemElement) {
this.itemElement.remove();
}
}
updateChecked() {
if (this.itemElement) {
if (this.item.checked) {
(0, _get__("dom_1").addClass)(this.itemElement, 'checked');
this.itemElement.setAttribute('aria-checked', 'true');
} else {
(0, _get__("dom_1").removeClass)(this.itemElement, 'checked');
this.itemElement.setAttribute('aria-checked', 'false');
}
}
}
updateRadioGroup() {
if (this.radioGroup === undefined) {
this.radioGroup = this.getRadioGroup();
}
if (this.menuItems) {
for (let i = this.radioGroup.start; i < this.radioGroup.end; i++) {
const menuItem = this.menuItems[i];
if (menuItem instanceof _get__("CETMenuItem") && menuItem.item.type === 'radio') {
// update item.checked for each radio button in group
menuItem.item.checked = menuItem === this;
menuItem.updateIcon();
// updateChecked() *all* radio buttons in group
menuItem.updateChecked();
// set the radioGroup property of all the other radio buttons since it was already calculated
if (menuItem !== this) {
menuItem.radioGroup = this.radioGroup;
}
}
}
}
}
/** radioGroup index's starts with (previous separator +1 OR menuItems[0]) and ends with (next separator OR menuItems[length]) */
getRadioGroup() {
let startIndex = 0;
let endIndex = this.menuItems ? this.menuItems.length : 0;
let found = false;
if (this.menuItems) {
for (const index in this.menuItems) {
const menuItem = this.menuItems[index];
if (menuItem === this) {
found = true;
} else if (menuItem instanceof _get__("CETMenuItem") && menuItem.isSeparator()) {
if (found) {
endIndex = Number.parseInt(index);
break;
} else {
startIndex = Number.parseInt(index) + 1;
}
}
}
}
return {
start: startIndex,
end: endIndex
};
}
get element() {
return this._currentElement;
}
get item() {
return this._item;
}
isEnabled() {
return this.item.enabled;
}
isSeparator() {
return this.item.type === 'separator';
}
get mnemonic() {
return this._mnemonic;
}
dispose() {
if (this.itemElement) {
(0, _get__("dom_1").removeNode)(this.itemElement);
this.itemElement = undefined;
}
super.dispose();
}
}
exports.CETMenuItem = _get__("CETMenuItem");
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "__createBinding":
return __createBinding;
case "__setModuleDefault":
return __setModuleDefault;
case "__importStar":
return __importStar;
case "consts_1":
return consts_1;
case "keyCodes_1":
return keyCodes_1;
case "dom_1":
return dom_1;
case "electron_1":
return electron_1;
case "strings":
return strings;
case "CETMenuItem":
return CETMenuItem;
case "lifecycle_1":
return lifecycle_1;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

View File

@@ -0,0 +1,11 @@
import { MenuItem } from 'electron';
import { CETMenuItem, IMenuStyle } from './item';
import { IMenuOptions } from './index';
import { MenuBarOptions } from '../../menubar/menubar-options';
import { IMenuIcons } from '../../menubar';
export declare class CETSeparator extends CETMenuItem {
private separatorElement?;
constructor(item: MenuItem, submenuIcons: IMenuIcons, submenuParentOptions: MenuBarOptions, submenuOptions: IMenuOptions);
render(container: HTMLElement): void;
updateStyle(style: IMenuStyle): void;
}

View File

@@ -0,0 +1,213 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) AlexTorresDev. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CETSeparator = void 0;
const item_1 = require("./item");
const dom_1 = require("../../base/common/dom");
class CETSeparator extends _get__("item_1").CETMenuItem {
constructor(item, submenuIcons, submenuParentOptions, submenuOptions) {
super(item, submenuIcons, submenuParentOptions, submenuOptions);
}
render(container) {
if (container) {
this.separatorElement = (0, _get__("dom_1").append)(container, (0, _get__("dom_1").$)('a.cet-action-label.separator', {
role: 'presentation'
}));
}
}
updateStyle(style) {
if (this.separatorElement && style.separatorColor) {
this.separatorElement.style.borderBottomColor = style.separatorColor.toString();
}
}
}
exports.CETSeparator = _get__("CETSeparator");
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "dom_1":
return dom_1;
case "item_1":
return item_1;
case "CETSeparator":
return CETSeparator;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

View File

@@ -0,0 +1,32 @@
import { MenuItem } from 'electron';
import { CETMenuItem } from './item';
import { EventLike } from '../../base/common/dom';
import { CETMenu, IMenuOptions } from './index';
import { MenuBarOptions } from '../../menubar/menubar-options';
import { IMenuIcons } from '../../menubar';
export interface ISubMenuData {
parent: CETMenu;
submenu?: CETMenu;
}
export declare class CETSubMenu extends CETMenuItem {
private submenuIcons;
private submenuItems;
private parentData;
private submenuParentOptions;
private submenuOptions;
private mySubmenu?;
private submenuContainer?;
private submenuIndicator?;
private submenuDisposables;
private mouseOver;
private showScheduler;
private hideScheduler;
private _closeSubMenu;
constructor(item: MenuItem, submenuIcons: IMenuIcons, submenuItems: MenuItem[], parentData: ISubMenuData, submenuParentOptions: MenuBarOptions, submenuOptions: IMenuOptions, closeSubMenu?: () => void);
render(el: HTMLElement): void;
private cleanupExistingSubmenu;
private createSubmenu;
protected applyStyle(): void;
onClick(e: EventLike): void;
dispose(): void;
}

View File

@@ -0,0 +1,372 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) AlexTorresDev. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CETSubMenu = void 0;
const consts_1 = require("../../consts");
const item_1 = require("./item");
const lifecycle_1 = require("../../base/common/lifecycle");
const dom_1 = require("../../base/common/dom");
const keyboardEvent_1 = require("../../base/browser/keyboardEvent");
const index_1 = require("./index");
const async_1 = require("../../base/common/async");
class CETSubMenu extends _get__("item_1").CETMenuItem {
constructor(item, submenuIcons, submenuItems, parentData, submenuParentOptions, submenuOptions, closeSubMenu = () => {}) {
super(item, submenuIcons, submenuParentOptions, submenuOptions);
this.submenuIcons = submenuIcons;
this.submenuItems = submenuItems;
this.parentData = parentData;
this.submenuParentOptions = submenuParentOptions;
this.submenuOptions = submenuOptions;
this.submenuDisposables = [];
this.mouseOver = false;
this._closeSubMenu = () => {};
this._closeSubMenu = closeSubMenu;
this.showScheduler = new (_get__("async_1").RunOnceScheduler)(() => {
if (this.mouseOver) {
this.cleanupExistingSubmenu(false);
this.createSubmenu(false);
}
}, 250);
this.hideScheduler = new (_get__("async_1").RunOnceScheduler)(() => {
if (this.element && !(0, _get__("dom_1").isAncestor)(document.activeElement, this.element) && this.parentData.submenu === this.mySubmenu) {
this.parentData.parent.focus(false);
this.cleanupExistingSubmenu(true);
}
}, 750);
}
render(el) {
super.render(el);
if (!this.itemElement) {
return;
}
(0, _get__("dom_1").addClass)(this.itemElement, 'cet-submenu-item');
this.itemElement.setAttribute('aria-haspopup', 'true');
this.submenuIndicator = (0, _get__("dom_1").append)(this.itemElement, (0, _get__("dom_1").$)('span.cet-submenu-indicator'));
this.submenuIndicator.innerHTML = this.submenuIcons.submenuIndicator;
this.submenuIndicator.setAttribute('aria-hidden', 'true');
(0, _get__("consts_1").applyFill)(this.submenuIndicator, this.menuStyle?.svgColor, this.menuStyle?.foregroundColor);
if (this.element) {
(0, _get__("dom_1").addDisposableListener)(this.element, _get__("dom_1").EventType.KEY_UP, e => {
const event = new (_get__("keyboardEvent_1").StandardKeyboardEvent)(e);
if (event.equals(17 /* KeyCode.RightArrow */) || event.equals(3 /* KeyCode.Enter */)) {
_get__("dom_1").EventHelper.stop(e, true);
this.createSubmenu(true);
}
});
(0, _get__("dom_1").addDisposableListener)(this.element, _get__("dom_1").EventType.KEY_DOWN, e => {
const event = new (_get__("keyboardEvent_1").StandardKeyboardEvent)(e);
if (event.equals(17 /* KeyCode.RightArrow */) || event.equals(3 /* KeyCode.Enter */)) {
_get__("dom_1").EventHelper.stop(e, true);
}
});
(0, _get__("dom_1").addDisposableListener)(this.element, _get__("dom_1").EventType.MOUSE_OVER, e => {
if (!this.mouseOver) {
this.mouseOver = true;
this.showScheduler.schedule();
}
});
(0, _get__("dom_1").addDisposableListener)(this.element, _get__("dom_1").EventType.MOUSE_LEAVE, e => {
this.mouseOver = false;
});
(0, _get__("dom_1").addDisposableListener)(this.element, _get__("dom_1").EventType.FOCUS_OUT, e => {
if (this.element && !(0, _get__("dom_1").isAncestor)(document.activeElement, this.element)) {
this.hideScheduler.schedule();
}
});
}
}
cleanupExistingSubmenu(force) {
if (this.parentData.submenu && (force || this.parentData.submenu !== this.mySubmenu)) {
this.parentData.submenu.dispose();
this.parentData.submenu = undefined;
if (this.submenuContainer) {
this.submenuContainer = undefined;
}
}
}
createSubmenu(selectFirstItem = true) {
if (!this.itemElement) {
return;
}
if (this.element) {
if (!this.parentData.submenu) {
this.submenuContainer = (0, _get__("dom_1").append)(this.element, (0, _get__("dom_1").$)('.cet-submenu'));
(0, _get__("dom_1").addClasses)(this.submenuContainer, 'cet-menubar-menu-container');
this.parentData.submenu = new (_get__("index_1").CETMenu)(this.submenuContainer, this.submenuIcons, this.submenuParentOptions, this.submenuOptions, this._closeSubMenu);
this.parentData.submenu.createMenu(this.submenuItems);
if (this.menuStyle) {
this.parentData.submenu.applyStyle(this.menuStyle);
}
const boundingRect = this.element.getBoundingClientRect();
const childBoundingRect = this.submenuContainer.getBoundingClientRect();
const computedStyles = getComputedStyle(this.parentData.parent.container);
const paddingTop = parseFloat(computedStyles.paddingTop || '0') || 0;
if (window.innerWidth <= boundingRect.right + childBoundingRect.width) {
this.submenuContainer.style.left = '10px';
this.submenuContainer.style.top = `${this.element.offsetTop + boundingRect.height}px`;
} else {
this.submenuContainer.style.left = `${this.element.offsetWidth}px`;
this.submenuContainer.style.top = `${this.element.offsetTop - paddingTop}px`;
}
this.submenuDisposables.push((0, _get__("dom_1").addDisposableListener)(this.submenuContainer, _get__("dom_1").EventType.KEY_UP, e => {
const event = new (_get__("keyboardEvent_1").StandardKeyboardEvent)(e);
if (event.equals(15 /* KeyCode.LeftArrow */)) {
_get__("dom_1").EventHelper.stop(e, true);
this.parentData.parent.focus();
if (this.parentData.submenu) {
this.parentData.submenu.dispose();
this.parentData.submenu = undefined;
}
this.submenuDisposables = (0, _get__("lifecycle_1").dispose)(this.submenuDisposables);
this.submenuContainer = undefined;
}
}));
this.submenuDisposables.push((0, _get__("dom_1").addDisposableListener)(this.submenuContainer, _get__("dom_1").EventType.KEY_DOWN, e => {
const event = new (_get__("keyboardEvent_1").StandardKeyboardEvent)(e);
if (event.equals(15 /* KeyCode.LeftArrow */)) {
_get__("dom_1").EventHelper.stop(e, true);
}
}));
this.submenuDisposables.push(this.parentData.submenu.onDidCancel(() => {
this.parentData.parent.focus();
if (this.parentData.submenu) {
this.parentData.submenu.dispose();
this.parentData.submenu = undefined;
}
this.submenuDisposables = (0, _get__("lifecycle_1").dispose)(this.submenuDisposables);
this.submenuContainer = undefined;
}));
this.parentData.submenu.focus(selectFirstItem);
this.mySubmenu = this.parentData.submenu;
} else {
this.parentData.submenu.focus(false);
}
}
}
applyStyle() {
super.applyStyle();
if (!this.menuStyle) return;
const isSelected = this.element && (0, _get__("dom_1").hasClass)(this.element, 'focused');
const fgColor = isSelected && this.menuStyle.selectionForegroundColor ? this.menuStyle.selectionForegroundColor : this.menuStyle.foregroundColor;
(0, _get__("consts_1").applyFill)(this.submenuIndicator, this.submenuParentOptions.svgColor, fgColor);
if (this.parentData.submenu) this.parentData.submenu.applyStyle(this.menuStyle);
}
onClick(e) {
// stop clicking from trying to run an action
_get__("dom_1").EventHelper.stop(e, true);
this.cleanupExistingSubmenu(false);
this.createSubmenu(false);
}
dispose() {
super.dispose();
this.hideScheduler.dispose();
if (this.mySubmenu) {
this.mySubmenu.dispose();
this.mySubmenu = null;
}
if (this.submenuContainer) {
this.submenuDisposables = (0, _get__("lifecycle_1").dispose)(this.submenuDisposables);
this.submenuContainer = undefined;
}
}
}
exports.CETSubMenu = _get__("CETSubMenu");
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "async_1":
return async_1;
case "dom_1":
return dom_1;
case "consts_1":
return consts_1;
case "keyboardEvent_1":
return keyboardEvent_1;
case "index_1":
return index_1;
case "lifecycle_1":
return lifecycle_1;
case "item_1":
return item_1;
case "CETSubMenu":
return CETSubMenu;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

View File

@@ -0,0 +1,52 @@
import { Color } from '../base/common/color';
export interface MenuBarOptions {
/**
* Enable the mnemonics on menubar and menu items
* **The default is true**
*/
enableMnemonics?: boolean;
/**
* The path of the icons of menubar.
*/
icons?: string;
/**
* The background color when the mouse is over the item.
* **The default is undefined**
*/
itemBackgroundColor?: Color;
/**
* The background color of the menu.
* **The default is automatic**
*/
menuBarBackgroundColor?: Color;
/**
* The position of menubar on titlebar.
* **The default is left**
*/
menuPosition?: 'left' | 'bottom';
/**
* The color of the menu separator.
* **The default is automatic**
*/
menuSeparatorColor?: Color;
/**
* The menu container transparency
* **The default is 0 (not apply transparency)*
*/
menuTransparency?: number;
/**
* Define if is only rendering the menubar without the titlebar.
* **The default is false**
*/
onlyShowMenuBar?: boolean;
/**
* Define if MenuBar exists on TitleBar or not.
* **The default is false**
*/
removeMenuBar?: boolean;
/**
* The color of the svg icons in the menu
* **The default is automatic**
*/
svgColor?: Color;
}

View File

@@ -0,0 +1,9 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) AlexTorresDev. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
Object.defineProperty(exports, "__esModule", {
value: true
});

105
src/app/titlebar/titlebar/index.d.ts vendored Normal file
View File

@@ -0,0 +1,105 @@
import { Color } from '../base/common/color';
import { MenuBar } from '../menubar';
import { TitleBarOptions } from './options';
import { ThemeBar } from './themebar';
export declare class CustomTitlebar extends ThemeBar {
private titlebar;
private dragRegion;
private icon;
private menuBarContainer;
private title;
private controlsContainer;
private container;
private menuBar?;
private isInactive;
private controls;
private resizer;
private currentOptions;
private platformIcons;
/**
* Create a new TitleBar instance
* @param options The options for the title bar
*/
constructor(options: TitleBarOptions);
private loadIcons;
/**
* Setup the background color of the title bar
* By default, it will use the meta theme-color or msapplication-TileColor and if it doesn't exist, it will use white
*/
private setupBackgroundColor;
/**
* Render the icon of the title bar, if is mac, it will not render
* By default, it will use the first icon found in the head of the document
*/
private createIcon;
private setIconSize;
private setupMenubar;
private setupTitle;
private createControlButton;
private setupWindowControls;
private setupContainer;
private setupTitleBar;
private loadEvents;
private closeMenu;
private onBlur;
private onFocus;
private onMenuBarVisibilityChanged;
private onMenuBarFocusChanged;
private onDidChangeMaximized;
private updateMenu;
private updateStyles;
private canCenterTitle;
/**
* Update title bar styles based on focus state.
* @param hasFocus focus state of the window
*/
onWindowFocus(focus: boolean): void;
/**
* Update the full screen state and hide or show the title bar.
* @param fullscreen Fullscreen state of the window
*/
onWindowFullScreen(fullscreen: boolean): void;
/**
* Update the title of the title bar.
* You can use this method if change the content of `<title>` tag on your html.
* @param title The title of the title bar and document.
*/
updateTitle(title: string): this;
/**
* It method set new icon to title-bar-icon of title-bar.
* @param path path to icon
*/
updateIcon(path: string): this;
/**
* Horizontal alignment of the title.
* @param side `left`, `center` or `right`.
*/
updateTitleAlignment(side: 'left' | 'center' | 'right'): this;
/**
* Update the background color of the title bar
* @param backgroundColor The color for the background
*/
updateBackground(backgroundColor: Color): this;
/**
* Update the item background color of the menubar
* @param itemBGColor The color for the item background
*/
updateItemBGColor(itemBGColor: Color): this;
/**
* Update the menu from Menu.getApplicationMenu()
*/
refreshMenu(): Promise<this>;
/**
* Update the position of menubar.
* @param menuPosition The position of the menu `left` or `bottom`.
*/
updateMenuPosition(menuPosition: 'left' | 'bottom'): this;
/**
* Remove the titlebar, menubar and all methods.
*/
dispose(): void;
get titlebarElement(): HTMLElement;
get menubarElement(): MenuBar | undefined;
get containerElement(): HTMLElement;
get titleElement(): HTMLElement;
}

View File

@@ -0,0 +1,706 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) AlexTorresDev. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CustomTitlebar = void 0;
const electron_1 = require("electron");
const color_1 = require("../base/common/color");
const dom_1 = require("../base/common/dom");
const platform_1 = require("../base/common/platform");
const menubar_1 = require("../menubar");
const themebar_1 = require("./themebar");
const consts_1 = require("../consts");
class CustomTitlebar extends _get__("themebar_1").ThemeBar {
/**
* Create a new TitleBar instance
* @param options The options for the title bar
*/
constructor(options) {
super();
this.isInactive = false;
this.currentOptions = {
closeable: true,
enableMnemonics: true,
// hideWhenClickingClose: false,
iconSize: 16,
itemBackgroundColor: undefined,
maximizable: true,
menuPosition: 'left',
menuTransparency: 0,
minimizable: true,
onlyShowMenuBar: false,
removeMenuBar: false,
shadow: false,
titleHorizontalAlignment: 'center',
tooltips: {
close: 'Close',
maximize: 'Maximize',
minimize: 'Minimize',
restoreDown: 'Restore Down'
},
unfocusEffect: true
};
// TODO: Refactor, verify if is possible use into menubar
this.closeMenu = () => {
if (this.menuBar) {
this.menuBar.blur();
}
};
this.currentOptions = {
...this.currentOptions,
...options
};
const jWindowIcons = _get__("consts_1").menuIcons[(0, _get__("platform_1").PlatformToString)(_get__("platform_1").platform)?.toLocaleLowerCase()];
this.platformIcons = jWindowIcons;
this.titlebar = (0, _get__("dom_1").$)('.cet-titlebar');
this.dragRegion = (0, _get__("dom_1").$)('.cet-drag-region');
this.icon = (0, _get__("dom_1").$)('.cet-icon');
this.menuBarContainer = (0, _get__("dom_1").$)('.cet-menubar');
this.title = (0, _get__("dom_1").$)('.cet-title');
this.controlsContainer = (0, _get__("dom_1").$)('.cet-window-controls');
this.container = (0, _get__("dom_1").$)('.cet-container');
this.controls = {
minimize: (0, _get__("dom_1").$)('.cet-control-minimize'),
maximize: (0, _get__("dom_1").$)('.cet-control-maximize'),
close: (0, _get__("dom_1").$)('.cet-control-close')
};
this.resizer = {
top: (0, _get__("dom_1").$)('.cet-resizer.top'),
left: (0, _get__("dom_1").$)('.cet-resizer.left')
};
(0, _get__("dom_1").append)(this.titlebar, this.dragRegion);
(0, _get__("dom_1").append)(this.titlebar, this.resizer.left);
(0, _get__("dom_1").append)(this.titlebar, this.resizer.top);
this.loadIcons();
this.setupBackgroundColor();
this.createIcon();
this.setupMenubar();
this.setupTitle();
this.setupWindowControls();
this.setupContainer();
this.setupTitleBar();
this.loadEvents();
// this.registerTheme(ThemeBar.win)
}
loadIcons() {
const icons = this.currentOptions.icons;
if (icons) {
const {
platformIcons
} = (0, _get__("consts_1").loadWindowIcons)(icons);
this.platformIcons = platformIcons;
}
}
/**
* Setup the background color of the title bar
* By default, it will use the meta theme-color or msapplication-TileColor and if it doesn't exist, it will use white
*/
setupBackgroundColor() {
let color = this.currentOptions.backgroundColor;
if (!color) {
const metaColor = document.querySelectorAll('meta[name="theme-color"]') || document.querySelectorAll('meta[name="msapplication-TileColor"]');
metaColor.forEach(meta => {
color = _get__("color_1").Color.fromHex(meta.getAttribute('content'));
});
if (!color) color = _get__("color_1").Color.WHITE;
this.currentOptions.backgroundColor = color;
}
this.titlebar.style.backgroundColor = color.toString();
}
/**
* Render the icon of the title bar, if is mac, it will not render
* By default, it will use the first icon found in the head of the document
*/
createIcon() {
// const onlyRendererMenuBar = this.currentOptions.onlyShowMenuBar
if (_get__("platform_1").isMacintosh) return;
let icon = this.currentOptions.icon;
if (!icon) {
const tagLink = document.querySelectorAll('link');
tagLink.forEach(link => {
if (link.getAttribute('rel') === 'icon' || link.getAttribute('rel') === 'shortcut icon') {
icon = link.getAttribute('href');
}
this.currentOptions.icon = icon;
});
}
if (icon) {
const windowIcon = (0, _get__("dom_1").append)(this.icon, (0, _get__("dom_1").$)('img'));
if (typeof icon === 'string') {
windowIcon.setAttribute('src', icon);
} else {
windowIcon.setAttribute('src', icon.toDataURL());
}
this.setIconSize(this.currentOptions.iconSize);
(0, _get__("dom_1").append)(this.titlebar, this.icon);
}
}
setIconSize(size) {
if (size < 16) size = 16;
if (size > 24) size = 24;
this.icon.firstElementChild.setAttribute('style', `height: ${size}px`);
}
setupMenubar() {
_get__("electron_1").ipcRenderer.invoke('request-application-menu')?.then(menu => this.updateMenu(menu));
const menuPosition = this.currentOptions.menuPosition;
const removeMenuBar = this.currentOptions.removeMenuBar;
if (menuPosition) {
this.updateMenuPosition(menuPosition);
}
if (removeMenuBar) return;
(0, _get__("dom_1").append)(this.titlebar, this.menuBarContainer);
}
setupTitle() {
const onlyRendererMenuBar = this.currentOptions.onlyShowMenuBar;
if (onlyRendererMenuBar) return;
this.updateTitle(document.title);
this.updateTitleAlignment(this.currentOptions.titleHorizontalAlignment);
(0, _get__("dom_1").append)(this.titlebar, this.title);
}
createControlButton(element, icon, title, active = true) {
(0, _get__("dom_1").addClass)(element, 'cet-control-icon');
element.innerHTML = icon;
element.title = title;
if (!active) {
(0, _get__("dom_1").addClass)(element, 'inactive');
}
(0, _get__("dom_1").append)(this.controlsContainer, element);
}
setupWindowControls() {
const onlyRendererMenuBar = this.currentOptions.onlyShowMenuBar;
const tooltips = this.currentOptions.tooltips;
if (_get__("platform_1").isMacintosh || onlyRendererMenuBar) return;
this.createControlButton(this.controls.minimize, this.platformIcons?.minimize, tooltips.minimize, this.currentOptions.minimizable);
this.createControlButton(this.controls.maximize, this.platformIcons?.maximize, tooltips.maximize, this.currentOptions.maximizable);
this.createControlButton(this.controls.close, this.platformIcons?.close, tooltips.close, this.currentOptions.closeable);
(0, _get__("dom_1").append)(this.titlebar, this.controlsContainer);
}
setupContainer() {
const containerOverflow = this.currentOptions.containerOverflow;
if (containerOverflow) {
this.container.style.overflow = containerOverflow;
}
while (document.body.firstChild) {
(0, _get__("dom_1").append)(this.container, document.body.firstChild);
}
(0, _get__("dom_1").append)(document.body, this.container);
}
setupTitleBar() {
const order = this.currentOptions.order;
const hasShadow = this.currentOptions.shadow;
(0, _get__("dom_1").addClass)(this.titlebar, `cet-${(0, _get__("platform_1").PlatformToString)(_get__("platform_1").platform)?.toLocaleLowerCase()}`);
if (order) {
(0, _get__("dom_1").addClass)(this.titlebar, `cet-${order}`);
}
if (hasShadow) {
(0, _get__("dom_1").addClass)(this.titlebar, 'cet-shadow');
}
if (!_get__("platform_1").isMacintosh) {
this.title.style.cursor = 'default';
}
(0, _get__("dom_1").prepend)(document.body, this.titlebar);
}
loadEvents() {
const onlyRendererMenuBar = this.currentOptions.onlyShowMenuBar;
if (onlyRendererMenuBar) return;
const minimizable = this.currentOptions.minimizable;
const maximizable = this.currentOptions.maximizable;
const closeable = this.currentOptions.closeable;
this.onDidChangeMaximized(_get__("electron_1").ipcRenderer.sendSync('window-event', 'window-is-maximized'));
_get__("electron_1").ipcRenderer.on('window-maximize', (_, isMaximized) => this.onDidChangeMaximized(isMaximized));
_get__("electron_1").ipcRenderer.on('window-fullscreen', (_, isFullScreen) => this.onWindowFullScreen(isFullScreen));
_get__("electron_1").ipcRenderer.on('window-focus', (_, isFocused) => this.onWindowFocus(isFocused));
if (minimizable) {
(0, _get__("dom_1").addDisposableListener)(this.controls.minimize, _get__("dom_1").EventType.CLICK, () => {
_get__("electron_1").ipcRenderer.send('window-event', 'window-minimize');
});
}
if (_get__("platform_1").isMacintosh) {
(0, _get__("dom_1").addDisposableListener)(this.titlebar, _get__("dom_1").EventType.DBLCLICK, () => {
_get__("electron_1").ipcRenderer.send('window-event', 'window-maximize');
});
}
if (maximizable) {
(0, _get__("dom_1").addDisposableListener)(this.controls.maximize, _get__("dom_1").EventType.CLICK, () => {
_get__("electron_1").ipcRenderer.send('window-event', 'window-maximize');
});
}
if (closeable) {
(0, _get__("dom_1").addDisposableListener)(this.controls.close, _get__("dom_1").EventType.CLICK, () => {
_get__("electron_1").ipcRenderer.send('window-event', 'window-close');
});
}
}
onBlur() {
this.isInactive = true;
this.updateStyles();
}
onFocus() {
this.isInactive = false;
this.updateStyles();
}
onMenuBarVisibilityChanged(visible) {
if (_get__("platform_1").isWindows || _get__("platform_1").isLinux || _get__("platform_1").isFreeBSD) {
if (visible) {
// Hack to fix issue #52522 with layered webkit-app-region elements appearing under cursor
(0, _get__("dom_1").hide)(this.dragRegion);
setTimeout(() => (0, _get__("dom_1").show)(this.dragRegion), 50);
}
}
}
onMenuBarFocusChanged(focused) {
if (_get__("platform_1").isWindows || _get__("platform_1").isLinux || _get__("platform_1").isFreeBSD) {
if (focused) (0, _get__("dom_1").hide)(this.dragRegion);else (0, _get__("dom_1").show)(this.dragRegion);
}
}
onDidChangeMaximized(isMaximized) {
const maximize = this.controls.maximize;
if (maximize) {
maximize.title = isMaximized ? this.currentOptions.tooltips?.restoreDown : this.currentOptions.tooltips?.maximize;
maximize.innerHTML = isMaximized ? this.platformIcons?.restore : this.platformIcons?.maximize;
}
if (this.resizer) {
if (isMaximized) (0, _get__("dom_1").hide)(this.resizer.top, this.resizer.left);else (0, _get__("dom_1").show)(this.resizer.top, this.resizer.left);
}
}
updateMenu(menu) {
if (_get__("platform_1").isMacintosh || !menu) return;
if (this.menuBar) this.menuBar.dispose();
this.menuBar = new (_get__("menubar_1").MenuBar)(this.menuBarContainer, _get__("consts_1").menuIcons, this.currentOptions, {
enableMnemonics: true
}, this.closeMenu); // TODO: Verify menubar options
this.menuBar.push(menu);
this.menuBar.update();
this.menuBar.onVisibilityChange(e => this.onMenuBarVisibilityChanged(e));
this.menuBar.onFocusStateChange(e => this.onMenuBarFocusChanged(e));
this.updateStyles();
}
updateStyles() {
if (this.isInactive) {
(0, _get__("dom_1").addClass)(this.titlebar, 'inactive');
} else {
(0, _get__("dom_1").removeClass)(this.titlebar, 'inactive');
}
const backgroundColor = this.isInactive && this.currentOptions.unfocusEffect ? this.currentOptions.backgroundColor?.lighten(0.12) : this.currentOptions.backgroundColor;
if (backgroundColor) {
this.titlebar.style.backgroundColor = backgroundColor?.toString();
}
let foregroundColor;
if (backgroundColor?.isLighter()) {
(0, _get__("dom_1").addClass)(this.titlebar, 'light');
foregroundColor = this.isInactive && this.currentOptions.unfocusEffect ? _get__("consts_1").INACTIVE_FOREGROUND_DARK : _get__("consts_1").ACTIVE_FOREGROUND_DARK;
} else {
(0, _get__("dom_1").removeClass)(this.titlebar, 'light');
foregroundColor = this.isInactive && this.currentOptions.unfocusEffect ? _get__("consts_1").INACTIVE_FOREGROUND : _get__("consts_1").ACTIVE_FOREGROUND;
}
this.titlebar.style.color = foregroundColor?.toString();
const updatedWindowControls = _get__("electron_1").ipcRenderer.sendSync('update-window-controls', {
color: backgroundColor?.toString(),
symbolColor: foregroundColor?.toString(),
height: _get__("consts_1").TOP_TITLEBAR_HEIGHT_WIN
});
if (updatedWindowControls) {
(0, _get__("dom_1").hide)(this.controlsContainer);
} else {
(0, _get__("dom_1").show)(this.controlsContainer);
}
if (this.menuBar) {
let fgColor;
const backgroundColor = this.currentOptions.menuBarBackgroundColor || this.currentOptions.backgroundColor.darken(0.12);
const foregroundColor = backgroundColor?.isLighter() ? _get__("consts_1").INACTIVE_FOREGROUND_DARK : _get__("consts_1").INACTIVE_FOREGROUND;
const bgColor = this.currentOptions.itemBackgroundColor && !this.currentOptions.itemBackgroundColor.equals(backgroundColor) ? this.currentOptions.itemBackgroundColor : _get__("consts_1").DEFAULT_ITEM_SELECTOR;
if (bgColor?.equals(_get__("consts_1").DEFAULT_ITEM_SELECTOR)) {
fgColor = backgroundColor?.isLighter() ? _get__("consts_1").ACTIVE_FOREGROUND_DARK : _get__("consts_1").ACTIVE_FOREGROUND;
} else {
fgColor = bgColor?.isLighter() ? _get__("consts_1").ACTIVE_FOREGROUND_DARK : _get__("consts_1").ACTIVE_FOREGROUND;
}
this.menuBar.setStyles({
backgroundColor,
foregroundColor,
selectionBackgroundColor: bgColor,
selectionForegroundColor: fgColor,
separatorColor: this.currentOptions.menuSeparatorColor ?? foregroundColor,
svgColor: this.currentOptions.svgColor
});
}
}
canCenterTitle() {
const menuBarContainerMargin = 20;
const menuSpaceLimit = window.innerWidth / 2 - this.menuBarContainer.getBoundingClientRect().right - menuBarContainerMargin;
return this.title.getBoundingClientRect().width / 2 <= menuSpaceLimit;
}
/// Public methods
/**
* Update title bar styles based on focus state.
* @param hasFocus focus state of the window
*/
onWindowFocus(focus) {
if (this.titlebar) {
if (focus) {
(0, _get__("dom_1").removeClass)(this.titlebar, 'inactive');
this.onFocus();
} else {
(0, _get__("dom_1").addClass)(this.titlebar, 'inactive');
this.menuBar?.blur();
this.onBlur();
}
}
}
/**
* Update the full screen state and hide or show the title bar.
* @param fullscreen Fullscreen state of the window
*/
onWindowFullScreen(fullscreen) {
const height = _get__("platform_1").isMacintosh ? _get__("consts_1").TOP_TITLEBAR_HEIGHT_MAC : _get__("consts_1").TOP_TITLEBAR_HEIGHT_WIN;
const hasShadow = this.currentOptions.shadow;
if (!_get__("platform_1").isMacintosh) {
if (fullscreen) {
(0, _get__("dom_1").hide)(this.titlebar);
this.container.style.top = '0px';
} else {
(0, _get__("dom_1").show)(this.titlebar);
if (this.currentOptions.menuPosition === 'bottom') {
this.container.style.top = (0, _get__("consts_1").getPx)(_get__("consts_1").BOTTOM_TITLEBAR_HEIGHT);
this.controlsContainer.style.height = (0, _get__("consts_1").getPx)(_get__("consts_1").TOP_TITLEBAR_HEIGHT_WIN);
} else {
this.container.style.top = (0, _get__("consts_1").getPx)(height + (hasShadow ? 1 : 0));
}
}
}
}
/**
* Update the title of the title bar.
* You can use this method if change the content of `<title>` tag on your html.
* @param title The title of the title bar and document.
*/
updateTitle(title) {
this.title.innerText = title;
document.title = title;
return this;
}
/**
* It method set new icon to title-bar-icon of title-bar.
* @param path path to icon
*/
updateIcon(path) {
if (this.icon) {
this.icon.firstElementChild.setAttribute('src', path);
}
return this;
}
/**
* Horizontal alignment of the title.
* @param side `left`, `center` or `right`.
*/
updateTitleAlignment(side) {
const order = this.currentOptions.order;
const menuPosition = this.currentOptions.menuPosition;
if (side === 'left' || side === 'right' && order === 'inverted') {
(0, _get__("dom_1").removeClass)(this.title, 'cet-title-left');
(0, _get__("dom_1").removeClass)(this.title, 'cet-title-right');
(0, _get__("dom_1").removeClass)(this.title, 'cet-title-center');
(0, _get__("dom_1").addClass)(this.title, 'cet-title-left');
}
if (side === 'right' || side === 'left' && order === 'inverted') {
if (side !== 'left' && order !== 'inverted') {
this.controlsContainer.style.marginLeft = '10px';
}
(0, _get__("dom_1").removeClass)(this.title, 'cet-title-left');
(0, _get__("dom_1").removeClass)(this.title, 'cet-title-right');
(0, _get__("dom_1").removeClass)(this.title, 'cet-title-center');
(0, _get__("dom_1").addClass)(this.title, 'cet-title-right');
}
if (side === 'center') {
(0, _get__("dom_1").removeClass)(this.title, 'cet-title-left');
(0, _get__("dom_1").removeClass)(this.title, 'cet-title-right');
(0, _get__("dom_1").removeClass)(this.title, 'cet-title-center');
if (menuPosition !== 'bottom') {
(0, _get__("dom_1").addDisposableListener)(window, 'resize', () => {
if (this.canCenterTitle()) {
(0, _get__("dom_1").addClass)(this.title, 'cet-title-center');
} else {
(0, _get__("dom_1").removeClass)(this.title, 'cet-title-center');
}
});
if (this.canCenterTitle()) {
(0, _get__("dom_1").addClass)(this.title, 'cet-title-center');
}
}
if (!_get__("platform_1").isMacintosh && order === 'first-buttons') {
this.controlsContainer.style.marginLeft = 'auto';
}
this.title.style.maxWidth = 'calc(100% - 296px)';
}
return this;
}
/**
* Update the background color of the title bar
* @param backgroundColor The color for the background
*/
updateBackground(backgroundColor) {
if (typeof backgroundColor === 'string') backgroundColor = _get__("color_1").Color.fromHex(backgroundColor);
this.currentOptions.backgroundColor = backgroundColor;
this.updateStyles();
return this;
}
/**
* Update the item background color of the menubar
* @param itemBGColor The color for the item background
*/
updateItemBGColor(itemBGColor) {
if (typeof itemBGColor === 'string') itemBGColor = _get__("color_1").Color.fromHex(itemBGColor);
this.currentOptions.itemBackgroundColor = itemBGColor;
this.updateStyles();
return this;
}
/**
* Update the menu from Menu.getApplicationMenu()
*/
async refreshMenu() {
if (!_get__("platform_1").isMacintosh) {
_get__("electron_1").ipcRenderer.invoke('request-application-menu').then(menu => this.updateMenu(menu));
}
return this;
}
/**
* Update the position of menubar.
* @param menuPosition The position of the menu `left` or `bottom`.
*/
updateMenuPosition(menuPosition) {
const height = _get__("platform_1").isMacintosh ? _get__("consts_1").TOP_TITLEBAR_HEIGHT_MAC : _get__("consts_1").TOP_TITLEBAR_HEIGHT_WIN;
const onlyRendererMenuBar = this.currentOptions.onlyShowMenuBar;
const hasShadow = this.currentOptions.shadow;
this.currentOptions.menuPosition = menuPosition;
if (menuPosition === 'left' || onlyRendererMenuBar) {
this.titlebar.style.height = (0, _get__("consts_1").getPx)(height + (hasShadow ? 1 : 0));
this.container.style.top = (0, _get__("consts_1").getPx)(height + (hasShadow ? 1 : 0));
(0, _get__("dom_1").removeClass)(this.menuBarContainer, 'bottom');
} else {
this.titlebar.style.height = (0, _get__("consts_1").getPx)(_get__("consts_1").BOTTOM_TITLEBAR_HEIGHT);
this.container.style.top = (0, _get__("consts_1").getPx)(_get__("consts_1").BOTTOM_TITLEBAR_HEIGHT);
this.controlsContainer.style.height = (0, _get__("consts_1").getPx)(height);
(0, _get__("dom_1").addClass)(this.menuBarContainer, 'bottom');
}
return this;
}
/**
* Remove the titlebar, menubar and all methods.
*/
dispose() {
// if (this.menuBar) this.menuBar.dispose()
this.titlebar.remove();
while (this.container.firstChild) (0, _get__("dom_1").append)(document.body, this.container.firstChild);
this.container.remove();
}
get titlebarElement() {
return this.titlebar;
}
get menubarElement() {
return this.menuBar;
}
get containerElement() {
return this.container;
}
get titleElement() {
return this.title;
}
}
exports.CustomTitlebar = _get__("CustomTitlebar");
function _getGlobalObject() {
try {
if (!!global) {
return global;
}
} catch (e) {
try {
if (!!window) {
return window;
}
} catch (e) {
return this;
}
}
}
;
var _RewireModuleId__ = null;
function _getRewireModuleId__() {
if (_RewireModuleId__ === null) {
let globalVariable = _getGlobalObject();
if (!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {
globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;
}
_RewireModuleId__ = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;
}
return _RewireModuleId__;
}
function _getRewireRegistry__() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
}
return theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;
}
function _getRewiredData__() {
let moduleId = _getRewireModuleId__();
let registry = _getRewireRegistry__();
let rewireData = registry[moduleId];
if (!rewireData) {
registry[moduleId] = Object.create(null);
rewireData = registry[moduleId];
}
return rewireData;
}
(function registerResetAll() {
let theGlobalVariable = _getGlobalObject();
if (!theGlobalVariable['__rewire_reset_all__']) {
theGlobalVariable['__rewire_reset_all__'] = function () {
theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);
};
}
})();
var INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';
let _RewireAPI__ = {};
(function () {
function addPropertyToAPIObject(name, value) {
Object.defineProperty(_RewireAPI__, name, {
value: value,
enumerable: false,
configurable: true
});
}
addPropertyToAPIObject('__get__', _get__);
addPropertyToAPIObject('__GetDependency__', _get__);
addPropertyToAPIObject('__Rewire__', _set__);
addPropertyToAPIObject('__set__', _set__);
addPropertyToAPIObject('__reset__', _reset__);
addPropertyToAPIObject('__ResetDependency__', _reset__);
addPropertyToAPIObject('__with__', _with__);
})();
function _get__(variableName) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _get_original__(variableName);
} else {
var value = rewireData[variableName];
if (value === INTENTIONAL_UNDEFINED) {
return undefined;
} else {
return value;
}
}
}
function _get_original__(variableName) {
switch (variableName) {
case "consts_1":
return consts_1;
case "platform_1":
return platform_1;
case "dom_1":
return dom_1;
case "color_1":
return color_1;
case "electron_1":
return electron_1;
case "menubar_1":
return menubar_1;
case "themebar_1":
return themebar_1;
case "CustomTitlebar":
return CustomTitlebar;
}
return undefined;
}
function _assign__(variableName, value) {
let rewireData = _getRewiredData__();
if (rewireData[variableName] === undefined) {
return _set_original__(variableName, value);
} else {
return rewireData[variableName] = value;
}
}
function _set_original__(variableName, _value) {
switch (variableName) {}
return undefined;
}
function _update_operation__(operation, variableName, prefix) {
var oldValue = _get__(variableName);
var newValue = operation === '++' ? oldValue + 1 : oldValue - 1;
_assign__(variableName, newValue);
return prefix ? newValue : oldValue;
}
function _set__(variableName, value) {
let rewireData = _getRewiredData__();
if (typeof variableName === 'object') {
Object.keys(variableName).forEach(function (name) {
rewireData[name] = variableName[name];
});
return function () {
Object.keys(variableName).forEach(function (name) {
_reset__(variableName);
});
};
} else {
if (value === undefined) {
rewireData[variableName] = INTENTIONAL_UNDEFINED;
} else {
rewireData[variableName] = value;
}
return function () {
_reset__(variableName);
};
}
}
function _reset__(variableName) {
let rewireData = _getRewiredData__();
delete rewireData[variableName];
if (Object.keys(rewireData).length == 0) {
delete _getRewireRegistry__()[_getRewireModuleId__];
}
;
}
function _with__(object) {
let rewireData = _getRewiredData__();
var rewiredVariableNames = Object.keys(object);
var previousValues = {};
function reset() {
rewiredVariableNames.forEach(function (variableName) {
rewireData[variableName] = previousValues[variableName];
});
}
return function (callback) {
rewiredVariableNames.forEach(function (variableName) {
previousValues[variableName] = rewireData[variableName];
rewireData[variableName] = object[variableName];
});
let result = callback();
if (!!result && typeof result.then == 'function') {
result.then(reset).catch(reset);
} else {
reset();
}
return result;
};
}
let _typeOfOriginalExport = typeof module.exports;
function addNonEnumerableProperty(name, value) {
Object.defineProperty(module.exports, name, {
value: value,
enumerable: false,
configurable: true
});
}
if ((_typeOfOriginalExport === 'object' || _typeOfOriginalExport === 'function') && Object.isExtensible(module.exports)) {
addNonEnumerableProperty('__get__', _get__);
addNonEnumerableProperty('__GetDependency__', _get__);
addNonEnumerableProperty('__Rewire__', _set__);
addNonEnumerableProperty('__set__', _set__);
addNonEnumerableProperty('__reset__', _reset__);
addNonEnumerableProperty('__ResetDependency__', _reset__);
addNonEnumerableProperty('__with__', _with__);
addNonEnumerableProperty('__RewireAPI__', _RewireAPI__);
}

89
src/app/titlebar/titlebar/options.d.ts vendored Normal file
View File

@@ -0,0 +1,89 @@
import { NativeImage } from 'electron';
import { Color } from '../base/common/color';
import { MenuBarOptions } from '../menubar/menubar-options';
export interface TitleBarOptions extends MenuBarOptions {
/**
* The background color of titlebar.
* **The default is `#ffffff`**
*/
backgroundColor?: Color;
/**
* Sets the value for the overflow of the container after title bar.
* **The default value is auto**
*/
containerOverflow?: 'auto' | 'hidden' | 'visible';
/**
* Define if the close button is enabled.
* **The default is true**
*/
closeable?: boolean;
/**
* When the close button is clicked, the window is hidden instead of closed.
* **The default is false**
*/
/**
* The icon shown on the left side of titlebar.
* **The default is the favicon of the index.html**
*/
icon?: NativeImage | string;
/**
* The icon size of titlebar. Value between 16 and 24.
* **The default is 16**
*/
iconSize?: number;
/**
* Define if the maximize and restore buttons are enabled.
* **The default is true**
*/
maximizable?: boolean;
/**
* Define if the minimize button is enabled.
* **The default is true**
*/
minimizable?: boolean;
/**
* Set the order of the elements on the title bar. You can use `inverted`, `first-buttons` or don't add for.
* **The default is undefined**
*/
order?: 'inverted' | 'first-buttons';
/**
* Show shadow of titlebar.
* **The default is false*
*/
shadow?: boolean;
/**
* Set horizontal alignment of the window title.
* **The default value is center**
*/
titleHorizontalAlignment?: 'left' | 'center' | 'right';
/**
* Set the titles of controls of the window.
*/
tooltips?: {
/**
* The tooltip of minimize button.
* **The default is "Minimize"**
*/
minimize?: string;
/**
* The tooltip of maximize button.
* **The default is "Maximize"**
*/
maximize?: string;
/**
* The tooltip of restore button.
* **The default is "Restore Down"**
*/
restoreDown?: string;
/**
* The tooltip of close button.
* **The default is "Close"**
*/
close?: string;
};
/**
* Enables or disables the blur option in titlebar.
* *The default is true*
*/
unfocusEffect?: boolean;
}

View File

@@ -0,0 +1,9 @@
"use strict";
/* ---------------------------------------------------------------------------------------------
* Copyright (c) AlexTorresDev. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------- */
Object.defineProperty(exports, "__esModule", {
value: true
});

20
src/app/titlebar/titlebar/themebar.d.ts vendored Normal file
View File

@@ -0,0 +1,20 @@
import { IDisposable, Disposable } from '../base/common/lifecycle';
export interface CssStyle {
addRule(rule: string): void;
}
export interface Theme {
(collector: CssStyle): void;
}
declare class ThemingRegistry extends Disposable {
private readonly theming;
constructor();
protected onThemeChange(theme: Theme): IDisposable;
protected getTheming(): Theme[];
}
export declare class ThemeBar extends ThemingRegistry {
constructor();
protected registerTheme(theme: Theme): void;
static get win(): Theme;
static get mac(): Theme;
}
export {};

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 汪磊
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,216 @@
const fs = require('fs');
const os = require('os');
const path = require('path');
const zlib = require('zlib');
const axios = require('axios');
const crypto = require('crypto');
const electron = require('electron');
const EventEmitter = require('events');
const dns = require('dns');
const semver = require('semver');
const app = electron.app || electron.remote.app;
const appName = app.getName();
const appPath = app.getAppPath();
class Updater extends EventEmitter {
constructor() {
super();
this.tasks = [];
}
_fetchJson(url) {
return axios.get(url, {
timeout: 1500,
headers: this.headers,
responseType: 'json',
}).then(response => response.data).catch(error => {
throw error;
});
}
_fetchFile(url, name) {
let onProgress = (p) => console.log(p);
let total = 0;
let current = 0;
let timer = null;
const tempFile = path.resolve(this.options.cacheDirectory, name);
const promise = new Promise((resolve, reject) => {
axios({
url,
method: 'GET',
responseType: 'stream',
headers: this.headers,
timeout: 3000,
})
.then((response) => {
if (response.headers['content-length']) {
total = parseInt(response.headers['content-length'], 10);
} else {
onProgress(-1);
}
timer = setTimeout(() => {
response.request.destroy(new Error('Request timed out after 2 minutes'));
}, 2 * 60 * 1000);
response.data
.on('data', (chunk) => {
current += chunk.length;
total ? onProgress(current / total) : onProgress(-1);
})
.pipe(zlib.createGunzip())
.pipe(fs.createWriteStream(tempFile))
.on('finish', () => {
clearTimeout(timer);
resolve(tempFile);
})
.on('error', (error) => {
clearTimeout(timer);
reject(error);
});
})
.catch((error) => reject(error));
});
promise.progress = (callback) => {
onProgress = callback;
return promise;
};
return promise;
}
init(options) {
const def = {
tmpdir: os.tmpdir(),
headers: {},
name: appName,
};
this.options = Object.assign({}, def, options);
this.options.cacheDirectory = path.resolve(this.options.tmpdir, this.options.name);
this.options.headers['user-agent'] = this.options.headers['user-agent'] || 'asar-updater/v0.0.2 (https://github.com/zce/asar-updater)';
fs.existsSync(this.options.cacheDirectory) || fs.mkdirSync(this.options.cacheDirectory);
}
setFeedURL(filename, url) {
if (!path.isAbsolute(filename)) {
filename = path.resolve(appPath, filename);
}
const name = path.basename(filename, '.asar');
this.tasks.push({ name, filename, url });
}
checkForUpdates() {
this._isOnline()
.then((online) => {
if (!online) {
this.emit('completed', false, 'offline');
return;
}
this.manifest = [];
this.emit('checking-for-update');
Promise.all(
this.tasks
.map((t) => this._local(t))
.map((t) => this._remote(t))
.map((p) => this._compare(p))
.map((p) => this._download(p))
)
.then((tasks) => this._allCompleted(tasks))
.catch((error) => this.emit('error', error));
})
.catch((err) => this.emit('error', err));
}
_isOnline(domain = 'google.com') {
return new Promise((resolve) => {
dns.lookup(domain, (err) => {
resolve(!err); // If there's no error, the system is online
});
});
}
_local(task) {
try {
task.local = require(path.resolve(task.filename, 'package.json'));
if (!task.local.version) throw new Error('There is no version in the package.json');
return task;
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') throw e;
throw new Error(`There is no package.json in the ${task.filename}`);
}
}
_remote(task) {
return this._fetchJson(`${task.url}?v=${Date.now()}`)
.then((remote) => {
task.remote = remote;
if (!task.remote.version) return Promise.reject(new Error('There is no version in the remote'));
return task;
});
}
_compare(promise) {
return promise.then((task) => {
task.available = semver.gt(semver.clean(task.remote.version), semver.clean(task.local.version));
this.emit(task.available ? 'available' : 'not-available', task);
return task;
});
}
_getFileStamp(filename, type) {
type = type || 'sha1';
const buffer = fs.readFileSync(filename);
const hash = crypto.createHash(type);
hash.update(buffer);
return hash.digest('hex');
}
_download(promise) {
return promise.then((task) => {
if (!task.available) return task;
return this._fetchFile(`${task.remote.url}?v=${Date.now()}`, task.name)
.progress((p) => this.emit('progress', task, p))
.then((filename) => {
if (task.remote.sha1 === this._getFileStamp(filename)) {
this.manifest.push({ from: filename, to: task.filename });
}
this.emit('downloaded', task);
return task;
});
});
}
_allCompleted(tasks) {
let updated = false;
for (let i = tasks.length - 1; i >= 0; i--) {
if (tasks[i].available) {
updated = true;
}
}
if (!updated) {
this.emit('completed', false, tasks);
return;
}
fs.writeFile(path.resolve(this.options.cacheDirectory, 'manifest.json'), JSON.stringify(this.manifest), 'utf8', (error) => {
if (error) return fs.unlink(this.options.cacheDirectory);
this.emit('completed', this.manifest, tasks);
this.manifest = [];
});
}
quitAndInstall(timeout) {
setTimeout(() => {
app.relaunch({ args: process.argv.slice(1) + ['--relaunch'] });
app.exit(0);
}, timeout || 100);
}
}
module.exports = new Updater();

39
src/app/utils/loadCRX.js Normal file
View File

@@ -0,0 +1,39 @@
const fs = require('fs');
const path = require('path');
const { session } = require('electron');
const AdmZip = require('adm-zip');
/**
* Unpacks a .crx file and loads it as an Electron extension.
* @param {string} crxPath - Path to the .crx file.
* @returns {Promise<string>} - Resolves with the extension ID after loading.
*/
async function loadCRX(crxPath) {
const outputDir = path.join(__dirname, 'extensions', path.basename(crxPath, '.crx'));
// Ensure the output directory exists
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
// Extract the .crx file
const crxData = fs.readFileSync(crxPath);
const crxHeaderSize = crxData.readUInt32LE(8); // Extract header size from CRX
const zipData = crxData.slice(crxHeaderSize);
// Save the ZIP content
const zip = new AdmZip(zipData);
zip.extractAllTo(outputDir, true);
}
// Load the unpacked extension into Electron
try {
const { id } = await session.defaultSession.loadExtension(outputDir);
console.log(`Extension loaded with ID: ${id}`);
return id;
} catch (error) {
console.error('Failed to load extension:', error);
throw error;
}
}
module.exports = loadCRX;

69
src/app/utils/sysInfo.js Normal file
View File

@@ -0,0 +1,69 @@
const os = require('os');
const childProcess = require('child_process');
class SystemInfo {
constructor() {
this.platform = os.platform(); // 'win32', 'darwin', 'linux'
this.release = os.release(); // OS version
this.versionInfo = this._getVersionInfo(); // Parsed version
}
// Check if current system is Windows
isWin() {
return this.platform === 'win32';
}
// Check if current system is macOS
isMac() {
return this.platform === 'darwin';
}
// Check if current system is Linux
isLinux() {
return this.platform === 'linux';
}
// Compare if current version is later than the given version
laterThan(compareVersion) {
const current = this.versionInfo;
const compare = this._parseVersion(compareVersion);
for (let i = 0; i < current.length; i++) {
if ((current[i] || 0) > (compare[i] || 0)) return true;
if ((current[i] || 0) < (compare[i] || 0)) return false;
}
return false;
}
// Private: Parse version strings (e.g., "10.0.19045" -> [10, 0, 19045])
_parseVersion(version) {
return version.split('.').map((num) => parseInt(num, 10) || 0);
}
// Private: Get detailed version info based on platform
_getVersionInfo() {
if (this.isWin()) {
// Windows version is already available via os.release()
return this._parseVersion(this.release);
} else if (this.isMac()) {
// Get macOS version via 'sw_vers'
const version = childProcess.execSync('sw_vers -productVersion').toString().trim();
return this._parseVersion(version);
} else if (this.isLinux()) {
// Use 'uname -r' for kernel version
const version = childProcess.execSync('uname -r').toString().trim();
return this._parseVersion(version);
} else {
return [0, 0, 0]; // Unknown system
}
}
}
// Usage Example
//const sys = new SystemInfo();
//console.log(`Is Windows: ${sys.isWin()}`);
//console.log(`Is macOS: ${sys.isMac()}`);
//console.log(`Is Linux: ${sys.isLinux()}`);
//console.log(`Current Version Info: ${sys.versionInfo.join('.')}`);
//console.log(`Later than 10.0.19044: ${sys.laterThan('10.0.19044')}`);
//console.log(`Later than 5.15.0 (Linux Kernel): ${sys.laterThan('5.15.0')}`);

View File

@@ -0,0 +1,165 @@
Fonticons, Inc. (https://fontawesome.com)
--------------------------------------------------------------------------------
Font Awesome Free License
Font Awesome Free is free, open source, and GPL friendly. You can use it for
commercial projects, open source projects, or really almost whatever you want.
Full Font Awesome Free license: https://fontawesome.com/license/free.
--------------------------------------------------------------------------------
# Icons: CC BY 4.0 License (https://creativecommons.org/licenses/by/4.0/)
The Font Awesome Free download is licensed under a Creative Commons
Attribution 4.0 International License and applies to all icons packaged
as SVG and JS file types.
--------------------------------------------------------------------------------
# Fonts: SIL OFL 1.1 License
In the Font Awesome Free download, the SIL OFL license applies to all icons
packaged as web and desktop font files.
Copyright (c) 2023 Fonticons, Inc. (https://fontawesome.com)
with Reserved Font Name: "Font Awesome".
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
SIL OPEN FONT LICENSE
Version 1.1 - 26 February 2007
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting — in part or in whole — any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
--------------------------------------------------------------------------------
# Code: MIT License (https://opensource.org/licenses/MIT)
In the Font Awesome Free download, the MIT license applies to all non-font and
non-icon files.
Copyright 2023 Fonticons, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in the
Software without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
# Attribution
Attribution is required by MIT, SIL OFL, and CC BY licenses. Downloaded Font
Awesome Free files already contain embedded comments with sufficient
attribution, so you shouldn't need to do anything additional when using these
files normally.
We've kept attribution comments terse, so we ask that you do not actively work
to remove them from files, especially code. They're a great way for folks to
learn about Font Awesome.
--------------------------------------------------------------------------------
# Brand Icons
All brand icons are trademarks of their respective owners. The use of these
trademarks does not indicate endorsement of the trademark holder by Font
Awesome, nor vice versa. **Please do not use brand logos for any purpose except
to represent the company, product, or service to which they refer.**

File diff suppressed because it is too large Load Diff

9
src/ui/css/fa/6.4.2/css/all.min.css vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

6372
src/ui/css/fa/6.4.2/css/fontawesome.css vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,19 @@
/*!
* Font Awesome Free 6.4.2 by @fontawesome - https://fontawesome.com
* License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
* Copyright 2023 Fonticons, Inc.
*/
:root, :host {
--fa-style-family-classic: 'Font Awesome 6 Free';
--fa-font-regular: normal 400 1em/1 'Font Awesome 6 Free'; }
@font-face {
font-family: 'Font Awesome 6 Free';
font-style: normal;
font-weight: 400;
font-display: block;
src: url("../webfonts/fa-regular-400.woff2") format("woff2"), url("../webfonts/fa-regular-400.ttf") format("truetype"); }
.far,
.fa-regular {
font-weight: 400; }

Some files were not shown because too many files have changed in this diff Show More