Compare commits

..

31 Commits

Author SHA1 Message Date
muwoo
651e202ab1 bugfix: windows 搜索图标有问题 2021-09-06 20:37:38 +08:00
muwoo
614d5ae369 bugfix: #42; ref: 支持windows拼音搜索系统应用 2021-09-06 14:58:18 +08:00
muwoo
f287d10ca9 bugfix: 修复 windows 搜索系统应用报错问题 2021-09-06 11:32:02 +08:00
muwoo
a04efd0d4f feat: 支持 windows 搜索系统应用:#39 2021-09-03 18:09:55 +08:00
muwoo
153d9dc5d7 feat: 支持 windows 搜索系统应用:#39 2021-09-03 18:09:08 +08:00
muwoo
de138955b5 feat: 支持win系统软件搜索 2021-09-03 18:07:42 +08:00
muwoo
8d340cb76c bugfix:#40 2021-09-03 14:22:41 +08:00
muwoo
579b283a55 docs: update 文档 2021-09-01 09:17:25 +08:00
muwoo
3858f35559 version: update 2021-08-31 21:25:12 +08:00
muwoo
57504ab1eb bugfix: #32,#31 2021-08-31 20:53:20 +08:00
muwoo
0991d0ad64 feat: 支持linux 2021-08-26 17:43:56 +08:00
muwoo
e71eed00ad feat: workflow 2021-08-26 17:33:44 +08:00
muwoo
be5bce68dc feat: workflow 2021-08-26 17:20:22 +08:00
muwoo
871beba4bf workflow 2021-08-26 17:19:54 +08:00
muwoo
f0b757c01f feat: linux workflow 2021-08-26 17:05:04 +08:00
muwoo
f480508200 feat: linux workflow 2021-08-26 16:36:25 +08:00
muwoo
247c2b7ab9 feat: linux workflow 2021-08-26 16:18:44 +08:00
木偶
a489a8f130 Merge pull request #34 from SOVLOOKUP/cross-platform
Cross platform Linux 跨平台适配
2021-08-26 16:06:10 +08:00
sovlookup
d38dcab9cc feat: linux version 2021-08-26 12:57:04 +08:00
sovlookup
64541ad651 chore: run at latest version 2021-08-26 12:23:29 +08:00
sovlookup
5b1cef93c8 merge 2021-08-26 11:06:50 +08:00
sovlookup
8dd59720e0 merge 2021-08-26 11:03:52 +08:00
木偶
ee2a23a421 Merge pull request #28 from clouDr-f2e/dev
Dev
2021-08-23 11:16:34 +08:00
muwoo
7dd5407bbe bugfix: 修复超级面板浅拷贝问题 2021-08-23 11:13:25 +08:00
muwoo
b58c37842a feat: 触摸板支持系统监控 2021-08-19 15:53:05 +08:00
muwoo
2d2743cbb1 ref: 优化取色功能 2021-08-19 14:03:50 +08:00
muwoo
efccc2b091 Merge remote-tracking branch 'github/master' 2021-08-18 20:37:28 +08:00
muwoo
c6c57b1e01 bugfix: 修复帮助功能 2021-08-18 20:37:15 +08:00
木偶
a8c1db6ed3 Update README.md 2021-08-18 20:00:59 +08:00
muwoo
4e55f14a69 style: touchbar 颜色调整 2021-08-18 19:48:23 +08:00
sovlookup
bf6e95e370 feat: electron12 2021-08-04 00:52:14 +08:00
29 changed files with 12546 additions and 219 deletions

View File

@@ -23,7 +23,7 @@ jobs:
strategy:
fail-fast: false
matrix:
os: [macos-latest, windows-2019]
os: [ubuntu-latest, macos-latest, windows-2019]
# create steps
steps:
@@ -40,6 +40,7 @@ jobs:
- name: Install system deps
if: matrix.os == 'ubuntu-latest'
run: |
sudo apt-get install libxtst-dev libpng++-dev
sudo apt-get install --no-install-recommends -y icnsutils graphicsmagick xz-utils
# step3: yarn
- name: macos Yarn install
@@ -56,6 +57,13 @@ jobs:
yarn global add xvfb-maybe
npm run rebuild_win
- name: linux Yarn install
if: ${{runner.os == 'Linux'}}
run: |
yarn
yarn global add xvfb-maybe
npm run rebuild_linux
- name: Build & release app
run: |
npm run release

5
.pnpm-debug.log Normal file
View File

@@ -0,0 +1,5 @@
{
"0 debug pnpm:scope": {
"selected": 1
}
}

View File

@@ -26,6 +26,7 @@
## 安装包
* [Rubick Mac OS](https://github.com/clouDr-f2e/rubick/releases)
* [Rubick Windows](https://github.com/clouDr-f2e/rubick/releases)
* [Rubick Linux](https://github.com/clouDr-f2e/rubick/releases)
## 支持能力
- [x] 支持远程下载安装插件,支持插件开发者模式
@@ -36,7 +37,7 @@
- [x] 支持搜索本地已安装 app 或 偏好设置
- [x] macos touchBar 唤起插件
- [x] 支持 Windows(目前是 mac 的 alpha 版本,功能尚不全,正在迁移中)
- [ ] 支持 Linux
- [x] 支持 Linux
@@ -50,13 +51,14 @@
## 使用问题
1. 依赖于 `robotjs` dev 环境运行请在 `install` 后执行 `npm run rebuild`
2. windows 版本目前有了一个最基础的可用版,代码在 [feat-win](https://github.com/clouDr-f2e/rubick/tree/feat-win) 分支。完整版正在开发中,敬请期待
3. linux 开发分支 cross-platform 的 iohook 开发模式下可能需要手动下载并放入node_modules, 将在未来修复
## 目前支持能力
### touchBar 唤起插件
macOS 支持 touchbar 快速唤起插件
<img src=https://user-images.githubusercontent.com/21073039/129727195-7dd50152-19f8-4064-9bcc-24393a896a6d.png width=500 />
![2oyn8-wu97m (3)](https://user-images.githubusercontent.com/21073039/129894362-1dbb8436-921c-4138-be9c-072dc2e62549.gif)
### 超级面板

View File

@@ -36,13 +36,8 @@ module.exports = {
path: '/blogs/plugin/',
},
{
title: '右击增强实现原理'
},
{
title: '系统插件实现原理'
},
{
title: '文件检索实现原理'
title: '超级面板实现原理',
path: '/blogs/superPannel/',
},
]
},

View File

@@ -0,0 +1,175 @@
## 前言
超级面板用于增强用户右击能力,实现快速呼起插件的能力,本次实现方式是通过 `robotjs` 以及 `iohook` 一起来完成
### 功能截图:
#### 文件夹下长按右建
<img src=https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/9b3d6ea7a25b4b908acc471471628979~tplv-k3u1fbpfcp-watermark.image width=300 />
#### 选择文件后长按右键
<img src=https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/8e220166cb464328b432f42d14ba9ab2~tplv-k3u1fbpfcp-watermark.image width=300 />
#### 选择文字后长按右键
<img src=https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/f9f909d08a8441e8a506831796908ef9~tplv-k3u1fbpfcp-watermark.image width=300 />
## 实现原理
### 获取选中文案
要实现改功能核心是要读取当前用户选中的文案或者文件,根据当前选择内容进行不同功能展示。但是核心有一个问题是如何来实现获取当前选中的内容。这个问题思考了很久很久,要想获取选中的文案,感觉唯一的办法是使用 `ctrl + c` 或者 `command + c` 来先复制到剪切板,再通过 `electron clipboard` 来获取当前剪切板内容。但是 `utools` 可不是通过先复制再长按这样的操作来实现的,而是直接选中文本或者文件长按后呼起超级面板。**所以一定要在右击长按前获取到当前选中的内容。**
如果要这么干,可能真的无解了,之前就因为这么想,才被无解了。正确的思路应该是先长按再获取选中的内容。别看只是掉了个个,但实现确实天壤之别:
1. 先获取选中内容:这就要求我们必须监听原生系统选中事件,但是 `electron` 并没有提供能力,我们也无法监听系统选择事件。
2. 先右击,后获取内容,这样的好处在于先右击可以通过监听鼠标右击事件,相比选择事件更加容易。
所以思路就有了,先监听长按右击事件:
```js
// macos
const mouseEvents = require("osx-mouse");
const mouseTrack = mouseEvents();
// 按下去的 time
let down_time = 0;
// 是否弹起
let isPress = false;
// 监听右击
mouseTrack.on('right-down', () => {
isPress = true;
down_time = Date.now();
// 长按 500ms 后触发
setTimeout(async () => {
if (isPress) {
// 获取选中内容
const copyResult = await getSelectedText();
}, 500);
})
mouseTrack.on('right-up', () => {
isPress = false;
});
```
接下来一步就是要去实现获取选中内容,要获取选中内容有个比较骚的操作,就是:
1. 通过 `clipboard` 先获取当前剪切板内容,并存下 A
2. 通过 `robot.js` 来调用系统 `command + c` 或者 `ctrl + c`
3. 再通过 `clipboard` 先获取当前剪切板内容,并存下 B
4. 再将 A 写到剪切板中,返回 B
先存剪切板内容的目的在于我们是偷偷帮用户执行了复制动作,当读取完用户选择内容后,需要回复用户之前的剪切板内容。接下来看一下简单的实现:
```js
const getSelected = () => {
return new Promise((resolve) => {
// 缓存之前的文案
const lastText = clipboard.readText('clipboard');
const platform = process.platform;
// 执行复制动作
if (platform === 'darwin') {
robot.keyTap('c', 'command');
} else {
robot.keyTap('c', 'control');
}
setTimeout(() => {
// 读取剪切板内容
const text = clipboard.readText('clipboard') || ''
const fileUrl = clipboard.read('public.file-url');
// 恢复剪切板内容
clipboard.writeText(lastText);
resolve({
text,
fileUrl
})
}, 300);
})
}
```
### 通知超级面板窗口当前选中内容
当获取到了选中内容后,接下来就是需要创建超级面板的 `BrowserWindow`:
```js
const { BrowserWindow, ipcMain, app } = require("electron");
module.exports = () => {
let win;
let init = (mainWindow) => {
if (win === null || win === undefined) {
createWindow();
}
};
let createWindow = () => {
win = new BrowserWindow({
frame: false,
autoHideMenuBar: true,
width: 250,
height: 50,
show: false,
alwaysOnTop: true,
webPreferences: {
webSecurity: false,
enableRemoteModule: true,
backgroundThrottling: false,
nodeIntegration: true,
devTools: false,
},
});
win.loadURL(`file://${__static}/plugins/superPanel/index.html`);
win.once('ready-to-show', () => win.show());
win.on("closed", () => {
win = undefined;
});
};
let getWindow = () => win;
return {
init: init,
getWindow: getWindow,
};
};
```
然后再通知 `superPanel` 进行内容展示:
```js
win.webContents.send('trigger-super-panel', {
...copyResult,
optionPlugin: optionPlugin.plugins,
});
```
### 超级面板点击操作
接下来要实现超级面板点击操作,这块也是比较简单的了,直接上代码好了:
#### 1. 打开 Terminal
```js
const { spawn } = require ('child_process');
spawn('open', [ '-a', 'Terminal', fileUrl ]);
```
#### 2. 新建文件
```js
remote.dialog.showSaveDialog({
title: "请选择要保存的文件名",
buttonLabel: "保存",
defaultPath: fileUrl.replace('file://', ''),
showsTagField: false,
nameFieldLabel: '',
}).then(result => {
fs.writeFileSync(result.filePath, '');
});
```
#### 3. 复制路径
```js
clipboard.writeText(fileUrl.replace('file://', ''))
```

View File

@@ -1,16 +1,17 @@
{
"name": "rubick2",
"version": "0.0.3-beta.4",
"version": "0.0.3-beta.13",
"author": "muwoo <2424880409@qq.com>",
"description": "An electron-vue project",
"license": null,
"main": "./dist/electron/main.js",
"scripts": {
"release": "node .electron-vue/build.js && electron-builder",
"release": "node .electron-vue/build.js && electron-builder --publish always",
"build": "node .electron-vue/build.js && electron-builder",
"dev": "node .electron-vue/dev-runner.js",
"rebuild": " ./node_modules/.bin/electron-rebuild",
"rebuild_win": "npm rebuild --runtime=electron --target=11.4.10 --disturl=https://atom.io/download/atom-shell --abi=85"
"rebuild_win": "npm rebuild --runtime=electron --target=11.4.10 --disturl=https://atom.io/download/atom-shell --abi=85",
"rebuild_linux": "npm rebuild --runtime=electron --target=11.4.10 --disturl=https://atom.io/download/atom-shell --abi=85"
},
"build": {
"asar": true,
@@ -54,7 +55,10 @@
"allowToChangeInstallationDirectory": true
},
"linux": {
"icon": "build/icons"
"icon": "build/icons/",
"publish": [
"github"
]
}
},
"dependencies": {
@@ -81,6 +85,7 @@
"robotjs": "git+https://github.com/Toinane/robotjs.git",
"semver": "^7.3.5",
"sudo-prompt": "^9.2.1",
"systeminformation": "^5.8.0",
"unzip": "^0.1.11",
"uuid": "^8.3.2",
"vue": "^2.5.16",
@@ -98,6 +103,7 @@
"babel-preset-env": "^1.7.0",
"babel-preset-stage-0": "^6.24.1",
"babel-register": "^6.26.0",
"babel-runtime": "^6.26.0",
"cfonts": "^2.1.2",
"chalk": "^2.4.1",
"copy-webpack-plugin": "^4.5.1",
@@ -105,7 +111,7 @@
"css-loader": "^0.28.11",
"del": "^3.0.0",
"devtron": "^1.4.0",
"electron": "^11.0.2",
"electron": "^11.4.10",
"electron-builder": "22.10.5",
"electron-debug": "^1.5.0",
"electron-devtools-installer": "^2.2.4",
@@ -140,7 +146,8 @@
],
"platforms": [
"darwin",
"win32"
"win32",
"linux"
],
"arches": [
"x64",

11829
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -3,4 +3,4 @@ module.exports = () => ({
separator: require("./separate")(),
superPanel: require("./superPanel")(),
main: require("./main")(),
});
})

View File

@@ -1,10 +1,10 @@
const { BrowserWindow, protocol } = require("electron");
const { BrowserWindow, protocol } = require("electron")
module.exports = () => {
let win;
let win
let init = (opts) => {
createWindow(opts);
};
createWindow(opts)
}
let createWindow = (opts) => {
const winURL = process.env.NODE_ENV === 'development'
@@ -14,6 +14,7 @@ module.exports = () => {
win = new BrowserWindow({
height: 60,
useContentSize: true,
resizable: true,
width: 800,
frame: false,
title: '拉比克',
@@ -23,6 +24,7 @@ module.exports = () => {
webSecurity: false,
enableRemoteModule: true,
backgroundThrottling: false,
contextIsolation: false,
webviewTag: true,
nodeIntegration: true // 在网页中集成Node
}
@@ -31,24 +33,24 @@ module.exports = () => {
win.loadURL(winURL)
protocol.interceptFileProtocol('image', (req, callback) => {
const url = req.url.substr(8);
callback(decodeURI(url));
const url = req.url.substr(8)
callback(decodeURI(url))
}, (error) => {
if (error) {
console.error('Failed to register protocol');
console.error('Failed to register protocol')
}
});
})
win.once('ready-to-show', () => win.show());
win.once('ready-to-show', () => win.show())
win.on("closed", () => {
win = undefined;
});
};
win = undefined
})
}
let getWindow = () => win;
let getWindow = () => win
return {
init: init,
getWindow: getWindow,
};
};
}
}

View File

@@ -1,13 +1,13 @@
const { BrowserWindow, nativeImage } = require("electron");
const { BrowserWindow, nativeImage } = require("electron")
module.exports = () => {
let win;
let win
let init = (x, y) => {
if (win === null || win === undefined) {
createWindow();
createWindow()
}
};
}
let createWindow = () => {
win = new BrowserWindow({
@@ -22,20 +22,21 @@ module.exports = () => {
hasShadow: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
devTools: false,
},
});
})
win.loadURL(`file://${__static}/plugins/picker/index.html`);
win.loadURL(`file://${__static}/plugins/picker/index.html`)
win.on("closed", () => {
win = undefined;
});
};
win = undefined
})
}
let getWindow = () => win;
let getWindow = () => win
return {
init: init,
getWindow: getWindow,
};
};
}
}

View File

@@ -1,11 +1,11 @@
const { BrowserWindow } = require("electron");
const { BrowserWindow } = require("electron")
module.exports = () => {
let win;
let win
let init = (opts) => {
createWindow(opts);
};
createWindow(opts)
}
let createWindow = (opts) => {
const winURL = process.env.NODE_ENV === 'development'
@@ -22,27 +22,28 @@ module.exports = () => {
webSecurity: false,
enableRemoteModule: true,
backgroundThrottling: false,
contextIsolation: false,
webviewTag: true,
nodeIntegration: true // 在网页中集成Node
}
});
})
process.env.NODE_ENV === 'development' ? win.loadURL(winURL) : win.loadFile(winURL, {
hash: `#/plugin`,
});
})
win.webContents.executeJavaScript(`window.setPluginInfo(${opts})`).then(() => {
win.show()
});
})
win.on("closed", () => {
win = undefined;
});
};
win = undefined
})
}
let getWindow = () => win;
let getWindow = () => win
return {
init: init,
getWindow: getWindow,
};
};
}
}

View File

@@ -1,13 +1,13 @@
import path from "path";
import fs from 'fs';
import {getlocalDataFile} from "./utils";
import os from 'os';
import path from "path"
import fs from 'fs'
import { getlocalDataFile } from "./utils"
import os from 'os'
const configPath = path.join(getlocalDataFile(), './rubick-config.json');
const configPath = path.join(getlocalDataFile(), './rubick-config.json')
let defaultConfig = {
Darwin: {
version: 2,
version: 3,
perf: {
shortCut: {
showAndHidden: 'Option+R',
@@ -32,7 +32,32 @@ let defaultConfig = {
global: []
},
Windows_NT: {
version: 2,
version: 3,
perf: {
shortCut: {
showAndHidden: 'Option+R',
separate: 'Ctrl+D',
quit: 'Shift+Escape'
},
common: {
start: true,
space: true,
},
local: {
search: true,
}
},
superPanel: {
baiduAPI: {
key: '',
appid: '',
},
mouseDownTime: 500
},
global: []
},
Linux: {
version: 3,
perf: {
shortCut: {
showAndHidden: 'Option+R',
@@ -63,22 +88,22 @@ global.opConfig = {
const platform = os.type();
try {
if (!opConfig.config) {
opConfig.config = JSON.parse(fs.readFileSync(configPath) || JSON.stringify(defaultConfig[platform]));
opConfig.config = JSON.parse(fs.readFileSync(configPath) || JSON.stringify(defaultConfig[platform]))
}
// 重置
if (!opConfig.version || opConfig.version < defaultConfig[platform].version) {
opConfig.config = defaultConfig[platform];
fs.writeFileSync(configPath, JSON.stringify(opConfig.config));
if (!opConfig.config.version || opConfig.config.version < defaultConfig[platform].version) {
opConfig.config = defaultConfig[platform]
fs.writeFileSync(configPath, JSON.stringify(opConfig.config))
}
return opConfig.config;
return opConfig.config
} catch (e) {
opConfig.config = defaultConfig[platform]
return opConfig.config;
return opConfig.config
}
},
set(key, value) {
opConfig.config[key] = value;
fs.writeFileSync(configPath, JSON.stringify(opConfig.config));
fs.writeFileSync(configPath, JSON.stringify(opConfig.config))
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 876 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

@@ -6,6 +6,7 @@ import ioHook from 'iohook';
import {throttle, commonConst} from './utils';
import path from 'path';
import fs from "fs";
import mito from './monitor';
const browsers = require("../browsers")();
const {picker, separator, superPanel} = browsers;
@@ -85,7 +86,13 @@ class Listener {
init(mainWindow) {
this.fn = throttle(({x, y}, picker) => {
const img = robot.screen.capture(parseInt(x) - 5, parseInt(y) - 5, 9, 9);
const { scaleFactor } = screen.getDisplayNearestPoint({x, y});
const img = robot.screen.capture(
x - parseInt(5 / scaleFactor),
y - parseInt(5 / scaleFactor),
10,
10
);
const colors = {}
@@ -187,6 +194,7 @@ class Listener {
}
initTouchBar(mainWindow) {
if (!commonConst.macOS()) return;
const { TouchBarButton, TouchBarGroup, TouchBarPopover } = TouchBar;
let items = [];
let system = [];
@@ -199,7 +207,6 @@ class Listener {
return new TouchBarButton({
icon,
backgroundColor: '#ff9fb4',
click() {
mainWindow.webContents.send('superPanel-openPlugin', {
cmd: item.features[0].cmds.filter(cmd => typeof cmd === 'string')[0],
@@ -214,7 +221,6 @@ class Listener {
if(item.type === 'system') {
return new TouchBarButton({
icon: nativeImage.createFromDataURL(item.logo).resize({width: 20, height: 20}),
backgroundColor: '#ff9fb4',
click() {
mainWindow.webContents.send('superPanel-openPlugin', {
cmd: item.features[0].cmds.filter(cmd => typeof cmd === 'string')[0],
@@ -235,10 +241,21 @@ class Listener {
showCloseButton: true
});
const monitor = new TouchBarPopover({
items: mito.touchBar,
label: '系统监控',
showCloseButton: true
});
const touchBar = new TouchBar({
items: [plugin, ...system]
items: [
plugin,
monitor,
...system
]
});
mainWindow.setTouchBar(touchBar);
mito.start(mainWindow);
});
}

124
src/main/common/monitor.js Normal file
View File

@@ -0,0 +1,124 @@
const {TouchBar} = require('electron')
const path = require('path')
const si = require('systeminformation');
const spawn = require('child_process').spawn;
const {TouchBarButton, TouchBarSpacer} = TouchBar;
const LOAD_NORMAL = "#2ecc71";
const LOAD_MEDIUM = "#f1c40f";
const LOAD_HIGH = "#d35400";
const LOAD_SEVERE = "#e74c3c";
const cpu = new TouchBarButton({
label: '',
backgroundColor: "#bdc3c7",
icon: path.join(__dirname, 'icons/chip.png'),
iconPosition: "left",
click: () => {
spawn("/System/Applications/Utilities/Activity Monitor.app/Contents/MacOS/Activity\ Monitor", []);
}
});
const memory = new TouchBarButton({
label: '',
backgroundColor: "#bdc3c7",
icon: path.join(__dirname, 'icons/ram.png'),
iconPosition: "left"
});
const network = new TouchBarButton({
label: '',
backgroundColor: '#3498db',
icon: path.join(__dirname, 'icons/internet.png'),
iconPosition: "left"
});
const battery = new TouchBarButton({
label: '',
backgroundColor: "#bdc3c7",
icon: path.join(__dirname, 'icons/power.png'),
iconPosition: "left"
});
const updateData = () => {
si.currentLoad(function(data) {
if (typeof data !== 'undefined' && data){
const load = data.currentLoad.toFixed(0)
cpu.label = load+"%"
if (load <= 20) cpu.backgroundColor = LOAD_NORMAL;
else if (load > 20 && load <= 40) cpu.backgroundColor = LOAD_MEDIUM;
else if (load > 40 && load <= 80) cpu.backgroundColor = LOAD_HIGH;
else if (load > 80 && load <= 100) cpu.backgroundColor = LOAD_SEVERE;
}
})
si.mem(function(data) {
if (typeof data !== 'undefined' && data){
const load = ((100* data.active ) / data.total).toFixed(0)
memory.label = load+"%"
if (load <= 20) memory.backgroundColor = LOAD_NORMAL;
else if (load > 20 && load <= 40) memory.backgroundColor = LOAD_MEDIUM;
else if (load > 40 && load <= 80) memory.backgroundColor = LOAD_HIGH;
else if (load > 80 && load <= 100) memory.backgroundColor = LOAD_SEVERE;
}
})
si.networkStats("", function(data) {
if (typeof data !== 'undefined' && data){
const kbtx = (data[0].tx_sec * 0.001).toFixed(0)
const kbrx = (data[0].rx_sec * 0.001).toFixed(0)
const l = (kbtx+kbrx).toString().length
network.label = "⇡"+ (kbtx*0.001).toFixed(2)
+" ⇣"+ (kbrx*0.001).toFixed(2) +" MB/s"
}
})
si.battery( function(data) {
if (typeof data !== 'undefined' && data){
if (data.ischarging){
battery.icon = path.join(__dirname, 'icons/charger.png')
}else{
battery.icon = path.join(__dirname, 'icons/power.png')
}
const load = data.percent.toFixed(0)
battery.label = load+"%"
if (load <= 20) battery.backgroundColor = LOAD_SEVERE;
else if (load > 20 && load <= 40) battery.backgroundColor = LOAD_HIGH;
else if (load > 40 && load <= 80) battery.backgroundColor = LOAD_MEDIUM;
else if (load > 80 && load <= 100) battery.backgroundColor = LOAD_NORMAL
}
})
}
const touchBar = new TouchBar({
items: [
cpu,
new TouchBarSpacer({size: 'small'}),
memory,
new TouchBarSpacer({size: 'small'}),
network,
new TouchBarSpacer({size: 'small'}),
battery,
]
})
let intervalObj;
const start = (window) => {
window.on('blur', () => {
clearInterval(intervalObj);
});
window.on('focus', () => {
intervalObj = setInterval(() => {
updateData();
}, 1000);
});
updateData();
}
export default {
start,
touchBar,
}

View File

@@ -1,18 +1,20 @@
import { app, globalShortcut } from 'electron'
import '../renderer/store'
import init from './common/common';
import {autoUpdate} from './common/autoUpdate';
import createTray from './tray';
import {commonConst} from './common/utils';
import pkg from '../../package.json';
import init from './common/common'
import { autoUpdate } from './common/autoUpdate'
import createTray from './tray'
import { commonConst } from './common/utils'
import pkg from '../../package.json'
import Store from 'electron-store';
const {main} = require("./browsers")();
Store.initRenderer()
const { main } = require("./browsers")()
if (commonConst.production()) {
global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}
// to fix https://github.com/electron/electron/issues/18397
app.allowRendererProcessReuse = false;
app.allowRendererProcessReuse = false
class initApp {
launchApp() {
@@ -28,28 +30,28 @@ class initApp {
}
createWindow() {
main.init();
init(main.getWindow());
main.init()
init(main.getWindow())
}
beforeReady() {
// 系统托盘
if (commonConst.macOS()) {
if (commonConst.production() && !app.isInApplicationsFolder()) {
app.moveToApplicationsFolder();
app.moveToApplicationsFolder()
} else {
app.dock.hide();
app.dock.hide()
}
}else {
app.disableHardwareAcceleration();
} else {
app.disableHardwareAcceleration()
}
}
onReady() {
const readyFunction = () => {
this.createWindow();
createTray(main.getWindow());
autoUpdate();
this.createWindow()
createTray(main.getWindow())
autoUpdate()
}
if (!app.isReady()) {
app.on('ready', readyFunction)
@@ -61,25 +63,25 @@ class initApp {
onRunning() {
app.on('second-instance', (event, commandLine, workingDirectory) => {
// 当运行第二个实例时,将会聚焦到myWindow这个窗口
const win = main.getWindow();
const win = main.getWindow()
if (win) {
if (win.isMinimized()) {
win.restore();
win.restore()
}
win.focus();
win.focus()
}
});
})
app.on('activate', () => {
if (!main.getWindow()) {
this.createWindow();
this.createWindow()
}
});
})
if (commonConst.windows()) {
app.setAppUserModelId(pkg.build.appId);
app.setAppUserModelId(pkg.build.appId)
}
}
onQuit () {
onQuit() {
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
@@ -106,4 +108,4 @@ class initApp {
}
}
(new initApp()).launchApp();
(new initApp()).launchApp()

View File

@@ -22,6 +22,7 @@
"
class="main-input"
@change="(e) => search({ value: e.target.value })"
@keydown.ctrl.86="shouldPaste"
:value="searchValue"
:maxLength="selected && selected.key !== 'plugin-container' ? 0 : 1000"
@keydown.down="(e) => changeCurrent(1)"
@@ -113,7 +114,7 @@
</template>
<script>
import { mapActions, mapMutations, mapState } from "vuex";
import { ipcRenderer, remote } from "electron";
import { ipcRenderer, remote, clipboard } from "electron";
import {
getWindowHeight,
debounce,
@@ -208,6 +209,18 @@ export default {
methods: {
...mapActions("main", ["onSearch", "showMainUI", "openPlugin"]),
...mapMutations("main", ["commonUpdate"]),
shouldPaste(e) {
let filePath = '';
if (process.platform === 'win32') {
const rawFilePath = clipboard.read('FileNameW');
filePath = rawFilePath.replace(new RegExp(String.fromCharCode(0), 'g'), '');
if (filePath.indexOf('plugin.json') >= 0) {
this.search({
filePath,
});
}
}
},
search(v) {
if (!this.searchFn) {
this.searchFn = debounce(this.onSearch, 200);

View File

@@ -0,0 +1,120 @@
import fs from "fs";
import path from "path";
import {nativeImage} from "electron";
import translate from "./translate";
import {APP_FINDER_PATH} from "./constans";
import iconvLite from "iconv-lite";
import bpList from "bplist-parser";
const fileLists = [];
const isZhRegex = /[\u4e00-\u9fa5]/;
const getDisplayNameRegex = /\"(?:CFBundleDisplayName)\"\s\=\s\"(.*)\"/;
async function getAppZhName(rootPath, appName) {
try {
const ERROR_RESULT = '';
const systemPath = path.join(rootPath, `${appName}/Contents/Resources/zh_CN.lproj/InfoPlist.strings`);
const customizePath = path.join(rootPath, `${appName}/Contents/Resources/zh-Hans.lproj/InfoPlist.strings`);
let appInfoPath = '';
if (fs.existsSync(systemPath)) {
appInfoPath = systemPath;
} else if (fs.existsSync(customizePath)) {
appInfoPath = customizePath;
} else {
return ERROR_RESULT;
}
let appZhName = '';
if (rootPath == '/Applications') {
const container = iconvLite.decode(fs.readFileSync(appInfoPath), 'utf-16');
if (container) {
const res = container.match(getDisplayNameRegex);
appZhName = res && res[1];
} else {
return ERROR_RESULT;
}
} else {
const [{ CFBundleDisplayName = '', CFBundleName = '' }] = await bpList.parseFile(appInfoPath);
appZhName = CFBundleDisplayName || CFBundleName;
}
return appZhName;
} catch (error) {
return ERROR_RESULT;
}
}
function getDarwinAppList () {
APP_FINDER_PATH.forEach((searchPath, index) => {
fs.readdir(searchPath, async (err, files) => {
try {
for (let i = 0; i < files.length; i++) {
const appName = files[i];
const extname = path.extname(appName);
const appSubStr = appName.split(extname)[0];
if ((extname === '.app' || extname === '.prefPane') >= 0) {
try {
const path1 = path.join(searchPath, `${appName}/Contents/Resources/App.icns`);
const path2 = path.join(searchPath, `${appName}/Contents/Resources/AppIcon.icns`);
const path3 = path.join(searchPath, `${appName}/Contents/Resources/${appSubStr}.icns`);
const path4 = path.join(searchPath, `${appName}/Contents/Resources/${appSubStr.replace(' ', '')}.icns`);
let iconPath = path1;
if (fs.existsSync(path1)) {
iconPath = path1;
} else if (fs.existsSync(path2)) {
iconPath = path2;
} else if (fs.existsSync(path3)) {
iconPath = path3;
} else if (fs.existsSync(path4)) {
iconPath = path4;
} else {
// 性能最低的方式
const resourceList = fs.readdirSync(path.join(searchPath, `${appName}/Contents/Resources`));
const iconName = resourceList.filter((file) => path.extname(file) === '.icns')[0];
iconPath = path.join(searchPath, `${appName}/Contents/Resources/${iconName}`);
}
const img = await nativeImage.createThumbnailFromPath(iconPath, { width: 64, height: 64 });
const appZhName = await getAppZhName(searchPath, appName);
const fileOptions = {
value: 'plugin',
icon: img.toDataURL(),
desc: path.join(searchPath, appName),
type: 'app',
action: `open ${path.join(searchPath, appName).replace(' ', '\\ ')}`,
keyWords: [appSubStr]
};
if (appZhName && isZhRegex.test(appZhName)) {
const py = translate(appZhName);
const pinyinArr = py.split(',');
const firstLatter = pinyinArr.map(py => py[0]);
// 拼音
fileOptions.keyWords.push(pinyinArr.join(''));
// 缩写
fileOptions.keyWords.push(firstLatter.join(''));
// 中文
fileOptions.keyWords.push(appZhName);
}
fileLists.push({
...fileOptions,
name: appSubStr,
names: JSON.parse(JSON.stringify(fileOptions.keyWords)),
});
} catch (e) {}
}
}
} catch (e) {
console.log(e);
}
});
});
}
export const getApp = {
init: getDarwinAppList,
fileLists,
}

View File

@@ -2,7 +2,7 @@ import {shell, ipcRenderer} from 'electron';
export default {
'rubick-help': {
help() {
shell.openExternal('https://u.tools/docs/guide/about-uTools.html')
shell.openExternal('https://cloudr-f2e.github.io/rubick/')
}
},
'rubick-color': {

View File

@@ -1,19 +1,19 @@
import { WINDOW_MAX_HEIGHT, WINDOW_MIN_HEIGHT, PRE_ITEM_HEIGHT, SYSTEM_PLUGINS } from './constans';
import path from 'path';
import fs from 'fs';
import process from 'child_process';
import child_process from 'child_process';
import Store from 'electron-store';
import downloadFile from 'download';
import { nativeImage, ipcRenderer } from 'electron';
import { APP_FINDER_PATH } from './constans';
import { ipcRenderer } from 'electron';
import { getlocalDataFile } from '../../../main/common/utils';
import iconvLite from 'iconv-lite';
import bpList from 'bplist-parser';
import translate from './translate'
const getApp = process.platform === 'win32' ? require('./win-app').getApp : require('./darwin-app').getApp;
const store = new Store();
getApp.init();
const fileLists = getApp.fileLists;
function getWindowHeight(searchList) {
if (!searchList) return WINDOW_MAX_HEIGHT;
if (!searchList.length) return WINDOW_MIN_HEIGHT;
@@ -50,7 +50,7 @@ async function downloadZip(downloadRepoUrl, name) {
const temp_dest = `${plugin_path}/${name}`;
// 下载模板
if (await existOrNot(temp_dest)) {
await process.execSync(`rm -rf ${temp_dest}`);
await child_process.execSync(`rm -rf ${temp_dest}`);
}
await downloadFile(downloadRepoUrl, plugin_path, { extract: true });
@@ -158,110 +158,6 @@ function find(p, target = 'plugin.json') {
console.log(e);
}
}
const fileLists = [];
// 默认搜索目录
const isZhRegex = /[\u4e00-\u9fa5]/;
const getDisplayNameRegex = /\"(?:CFBundleDisplayName)\"\s\=\s\"(.*)\"/;
async function getAppZhName(rootPath, appName) {
try {
const ERROR_RESULT = '';
const systemPath = path.join(rootPath, `${appName}/Contents/Resources/zh_CN.lproj/InfoPlist.strings`);
const customizePath = path.join(rootPath, `${appName}/Contents/Resources/zh-Hans.lproj/InfoPlist.strings`);
let appInfoPath = '';
if (fs.existsSync(systemPath)) {
appInfoPath = systemPath;
} else if (fs.existsSync(customizePath)) {
appInfoPath = customizePath;
} else {
return ERROR_RESULT;
}
let appZhName = '';
if (rootPath == '/Applications') {
const container = iconvLite.decode(fs.readFileSync(appInfoPath), 'utf-16');
if (container) {
const res = container.match(getDisplayNameRegex);
appZhName = res && res[1];
} else {
return ERROR_RESULT;
}
} else {
const [{ CFBundleDisplayName = '', CFBundleName = '' }] = await bpList.parseFile(appInfoPath);
appZhName = CFBundleDisplayName || CFBundleName;
}
return appZhName;
} catch (error) {
return ERROR_RESULT;
}
}
APP_FINDER_PATH.forEach((searchPath, index) => {
fs.readdir(searchPath, async (err, files) => {
try {
for (let i = 0; i < files.length; i++) {
const appName = files[i];
const extname = path.extname(appName);
const appSubStr = appName.split(extname)[0];
if ((extname === '.app' || extname === '.prefPane') >= 0) {
try {
const path1 = path.join(searchPath, `${appName}/Contents/Resources/App.icns`);
const path2 = path.join(searchPath, `${appName}/Contents/Resources/AppIcon.icns`);
const path3 = path.join(searchPath, `${appName}/Contents/Resources/${appSubStr}.icns`);
const path4 = path.join(searchPath, `${appName}/Contents/Resources/${appSubStr.replace(' ', '')}.icns`);
let iconPath = path1;
if (fs.existsSync(path1)) {
iconPath = path1;
} else if (fs.existsSync(path2)) {
iconPath = path2;
} else if (fs.existsSync(path3)) {
iconPath = path3;
} else if (fs.existsSync(path4)) {
iconPath = path4;
} else {
// 性能最低的方式
const resourceList = fs.readdirSync(path.join(searchPath, `${appName}/Contents/Resources`));
const iconName = resourceList.filter((file) => path.extname(file) === '.icns')[0];
iconPath = path.join(searchPath, `${appName}/Contents/Resources/${iconName}`);
}
const img = await nativeImage.createThumbnailFromPath(iconPath, { width: 64, height: 64 });
const appZhName = await getAppZhName(searchPath, appName);
const fileOptions = {
value: 'plugin',
icon: img.toDataURL(),
desc: path.join(searchPath, appName),
type: 'app',
action: `open ${path.join(searchPath, appName).replace(' ', '\\ ')}`,
keyWords: [appSubStr]
};
if (appZhName && isZhRegex.test(appZhName)) {
const py = translate(appZhName);
const pinyinArr = py.split(',');
const firstLatter = pinyinArr.map(py => py[0]);
// 拼音
fileOptions.keyWords.push(pinyinArr.join(''));
// 缩写
fileOptions.keyWords.push(firstLatter.join(''));
// 中文
fileOptions.keyWords.push(appZhName);
}
fileLists.push({
...fileOptions,
name: appSubStr,
names: JSON.parse(JSON.stringify(fileOptions.keyWords)),
});
} catch (e) {}
}
}
} catch (e) {
console.log(e);
}
});
});
function debounce(fn, delay) {
let timer;

View File

@@ -0,0 +1,80 @@
import path from "path";
import os from 'os';
import child from 'child_process';
import iconv from 'iconv-lite';
import translate from "./translate";
const fileLists = [];
const isZhRegex = /[\u4e00-\u9fa5]/;
const powershell = (cmd, callback) => {
const ps = child.spawn('powershell', ['-NoProfile', '-Command', cmd], { encoding: 'buffer' })
let chunks = [];
let err_chunks = [];
ps.stdout.on('data', chunk => {
chunks.push(iconv.decode(chunk, 'cp936'))
})
ps.stderr.on('data', err_chunk => {
err_chunks.push(iconv.decode(err_chunk, 'cp936'))
})
ps.on('close', code => {
let stdout = chunks.join("");
let stderr = err_chunks.join("");
callback(stdout, stderr)
})
}
const getWinAppList = () => {
let filterValues = "Select-Object DisplayName,DisplayIcon,UninstallString,DisplayVersion,InstallDate,Publisher,InstallLocation"
let localMatcine = `Get-ItemProperty HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* | ${filterValues}`;
let currentUser = `Get-ItemProperty HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* | ${filterValues}`;
let Wow6432Node = `Get-ItemProperty HKLM:\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* | ${filterValues}`;
let x64 = process.arch === 'x64' ? `;${Wow6432Node}` : '';
powershell(`${localMatcine};${currentUser}${x64}`, (stdout, stderr) => {
let apps = stdout.trim().replace(/\r\n[ ]{10,}/g,"").split('\r\n\r\n');
for (const app of apps) {
const dict = {}
let lines = app.split('\r\n')
for (var line of lines) {
if (line) {
const key = line.split(/\s+:\s*/)[0];
const value = line.split(/\s+:\s*/)[1];
dict[key] = value;
}
}
if (dict.DisplayName && dict.DisplayIcon && dict.DisplayIcon.indexOf('.exe') >= 0) {
dict.LegalName = dict.DisplayName.replace(/[\\\/\:\*\?\"\<\>\|]/g, "");
dict.Icon = path.join(os.tmpdir(), 'ProcessIcon', `${encodeURIComponent(dict.LegalName)}.png`);
const firstLatter = dict.DisplayName.split(' ').map(name => name[0]).join('');
const appPath = dict.DisplayIcon.split(',')[0].replace(/"/g, '');
const keyWords = [dict.DisplayName, firstLatter];
if (isZhRegex.test(dict.DisplayName)) {
const py = translate(dict.DisplayName);
const pinyinArr = py.split(',');
const zh_firstLatter = pinyinArr.map(py => py[0]);
// 拼音
keyWords.push(pinyinArr.join(''));
// 缩写
keyWords.push(zh_firstLatter.join(''));
}
fileLists.push({
...dict,
value: 'plugin',
icon: dict.Icon,
desc: appPath,
type: 'app',
action: `start "dummyclient" "${appPath}"`,
keyWords: keyWords,
name: dict.DisplayName,
names: JSON.parse(JSON.stringify(keyWords)),
});
}
}
});
}
export const getApp = {
init: getWinAppList,
fileLists,
};

View File

@@ -107,10 +107,10 @@ const actions = {
commit('commonUpdate', { searchValue: value });
return;
}
const fileUrl = clipboard.read('public.file-url').replace('file://', '');
const fileUrl = paylpad.filePath || clipboard.read('public.file-url').replace('file://', '');
commit('commonUpdate', { searchValue: value });
// 复制文件
if (fileUrl && value === 'plugin.json') {
if (paylpad.filePath || (fileUrl && value === 'plugin.json')) {
const config = JSON.parse(fs.readFileSync(fileUrl, 'utf-8'));
const pluginConfig = {
@@ -132,7 +132,6 @@ const actions = {
name: 'plugin.json'
},
searchValue: '',
devPlugins: [pluginConfig, ...state.devPlugins],
options: [
{
name: '新建rubick开发插件',
@@ -142,6 +141,7 @@ const actions = {
click: (router) => {
commit('commonUpdate', {
showMain: true,
devPlugins: [pluginConfig, ...state.devPlugins],
selected: {
key: 'plugin',
name: '新建rubick开发插件'

View File

@@ -4,6 +4,7 @@ const path = require('path');
const fs = require('fs');
const { spawn } = require ('child_process');
const mineType = require("mime-types");
const {extend} = require('../../utils');
new Vue({
el: '#app',
@@ -116,7 +117,8 @@ new Vue({
this.targetOptions = this.options.common;
} else {
// 有文件选择
this.targetOptions = JSON.parse(JSON.stringify(this.options.selected));
this.targetOptions = [];
extend(this.targetOptions, this.options.selected, true);
// 检测上传
(this.selectData.optionPlugin || []).forEach(plugin => {
plugin.features.forEach(fe => {

View File

@@ -20,8 +20,31 @@ function getData(path, defaultValue) {
}
}
const isArray = Array.isArray ||
function(object){ return object instanceof Array }
function isPlainObject(obj) {
return isObject(obj) && Object.getPrototypeOf(obj) == Object.prototype
}
function isObject(obj) { return typeof obj == "object" }
function extend(target, source, deep) {
for (let key in source)
if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {
if (isPlainObject(source[key]) && !isPlainObject(target[key]))
target[key] = {}
if (isArray(source[key]) && !isArray(target[key]))
target[key] = []
extend(target[key], source[key], deep)
}
else if (source[key] !== undefined) target[key] = source[key]
}
module.exports = {
getlocalDataFile,
saveData,
getData
getData,
extend
}