🚧 WIP: almost finish shortKey system

This commit is contained in:
Molunerfinn 2019-12-22 17:22:32 +08:00
parent b8ec879e23
commit fec4360043
17 changed files with 384 additions and 341 deletions

View File

@ -33,10 +33,7 @@ import bus from '~/main/utils/eventBus'
import { import {
updateShortKeyFromVersion212 updateShortKeyFromVersion212
} from '~/main/migrate/shortKeyUpdateHelper' } from '~/main/migrate/shortKeyUpdateHelper'
import { import shortKeyHandler from '~/main/utils/shortKeyHandler'
shortKeyUpdater,
initShortKeyRegister
} from '~/main/utils/shortKeyHandler'
import logger from '~/main/utils/logger' import logger from '~/main/utils/logger'
const isDevelopment = process.env.NODE_ENV !== 'production' const isDevelopment = process.env.NODE_ENV !== 'production'
@ -462,13 +459,39 @@ ipcMain.on('uploadChoosedFiles', async (evt: IpcMainEvent, files: IFileWithPath[
return uploadChoosedFiles(evt.sender, files) return uploadChoosedFiles(evt.sender, files)
}) })
ipcMain.on('updateShortKey', (evt: IpcMainEvent, item: IShortKeyConfig, oldKey: string) => { ipcMain.on('updateShortKey', (evt: IpcMainEvent, item: IShortKeyConfig, oldKey: string, from: string) => {
shortKeyUpdater(globalShortcut, item, oldKey) const result = shortKeyHandler.updateShortKey(item, oldKey, from)
const notification = new Notification({ evt.sender.send('updateShortKeyResponse', result)
title: '操作成功', if (result) {
body: '你的快捷键已经修改成功' const notification = new Notification({
}) title: '操作成功',
notification.show() body: '你的快捷键已经修改成功'
})
notification.show()
} else {
const notification = new Notification({
title: '操作失败',
body: '快捷键冲突,请重新设置'
})
notification.show()
}
})
ipcMain.on('bindOrUnbindShortKey', (evt: IpcMainEvent, item: IShortKeyConfig, from: string) => {
const result = shortKeyHandler.bindOrUnbindShortKey(item, from)
if (result) {
const notification = new Notification({
title: '操作成功',
body: '你的快捷键已经修改成功'
})
notification.show()
} else {
const notification = new Notification({
title: '操作失败',
body: '快捷键冲突,请重新设置'
})
notification.show()
}
}) })
ipcMain.on('updateCustomLink', () => { ipcMain.on('updateCustomLink', () => {
@ -585,7 +608,7 @@ app.on('ready', async () => {
// 不需要阻塞 // 不需要阻塞
process.nextTick(() => { process.nextTick(() => {
updateShortKeyFromVersion212(db, db.get('settings.shortKey')) updateShortKeyFromVersion212(db, db.get('settings.shortKey'))
initShortKeyRegister(globalShortcut, db.get('settings.shortKey')) shortKeyHandler.init()
}) })
if (process.env.NODE_ENV !== 'development') { if (process.env.NODE_ENV !== 'development') {
@ -638,13 +661,26 @@ app.setLoginItemSettings({
function initEventCenter () { function initEventCenter () {
const eventList: any = { const eventList: any = {
'picgo:upload': uploadClipboardFiles 'picgo:upload': uploadClipboardFiles,
'createSettingWindow': shortKeyRequestSettingWindow,
hideMiniWindow
} }
for (let i in eventList) { for (let i in eventList) {
bus.on(i, eventList[i]) bus.on(i, eventList[i])
} }
} }
function shortKeyRequestSettingWindow (command: string) {
if (!settingWindow) createSettingWindow()
bus.emit('createSettingWindowDone', command, settingWindow!.id)
}
function hideMiniWindow () {
if (miniWindow && miniWindow.isVisible()) {
miniWindow.hide()
}
}
// Exit cleanly on request from parent process in development mode. // Exit cleanly on request from parent process in development mode.
if (isDevelopment) { if (isDevelopment) {
if (process.platform === 'win32') { if (process.platform === 'win32') {

View File

@ -8,7 +8,7 @@ const updateShortKeyFromVersion212 = (db: typeof DB, shortKeyConfig: IShortKeyCo
shortKeyConfig['picgo:upload'] = { shortKeyConfig['picgo:upload'] = {
enable: true, enable: true,
key: shortKeyConfig.upload, key: shortKeyConfig.upload,
name: 'picgo:upload', name: 'upload',
label: '快捷上传' label: '快捷上传'
} }
delete shortKeyConfig.upload delete shortKeyConfig.upload

View File

@ -3,68 +3,56 @@ import {
BrowserWindow, BrowserWindow,
clipboard, clipboard,
Notification, Notification,
IpcMain, WebContents,
WebContents ipcMain
} from 'electron' } from 'electron'
import db from '#/datastore' import db from '#/datastore'
import Uploader from './uploader' import Uploader from './uploader'
import pasteTemplate from '#/utils/pasteTemplate' import pasteTemplate from '#/utils/pasteTemplate'
import PicGoCore from '~/universal/types/picgo'
const WEBCONTENTS = Symbol('WEBCONTENTS') const WEBCONTENTS = Symbol('WEBCONTENTS')
const IPCMAIN = Symbol('IPCMAIN')
const PICGO = Symbol('PICGO')
class GuiApi { class GuiApi implements IGuiApi {
private [WEBCONTENTS]: WebContents private [WEBCONTENTS]: WebContents
private [IPCMAIN]: IpcMain constructor (webcontents: WebContents) {
private [PICGO]: PicGoCore
constructor (ipcMain: IpcMain, webcontents: WebContents, picgo: PicGoCore) {
this[WEBCONTENTS] = webcontents this[WEBCONTENTS] = webcontents
this[IPCMAIN] = ipcMain
this[PICGO] = picgo
} }
/** private async showSettingWindow () {
* for plugin showInputBox const settingWindow = BrowserWindow.fromWebContents(this[WEBCONTENTS])
* @param {object} options if (settingWindow.isVisible()) {
* return type is string or '' return true
*/
showInputBox (options: IShowInputBoxOption) {
if (options === undefined) {
options = {
title: '',
placeholder: ''
}
} }
this[WEBCONTENTS].send('showInputBox', options) settingWindow.show()
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this[IPCMAIN].once('showInputBox', (event: Event, value: string) => { setTimeout(() => {
resolve()
}, 1000) // TODO: a better way to wait page loaded.
})
}
async showInputBox (options: IShowInputBoxOption = {
title: '',
placeholder: ''
}) {
await this.showSettingWindow()
this[WEBCONTENTS].send('showInputBox', options)
return new Promise<string>((resolve, reject) => {
ipcMain.once('showInputBox', (event: Event, value: string) => {
resolve(value) resolve(value)
}) })
}) })
} }
/** showFileExplorer (options: IShowFileExplorerOption = {}) {
* for plugin show file explorer return new Promise<string>((resolve, reject) => {
* @param {object} options
*/
showFileExplorer (options: {}) {
if (options === undefined) {
options = {}
}
return new Promise((resolve, reject) => {
dialog.showOpenDialog(BrowserWindow.fromWebContents(this[WEBCONTENTS]), options, (filename: string) => { dialog.showOpenDialog(BrowserWindow.fromWebContents(this[WEBCONTENTS]), options, (filename: string) => {
resolve(filename) resolve(filename)
}) })
}) })
} }
/** async upload (input: IUploadOption) {
* for plugin to upload file const imgs = await new Uploader(input, this[WEBCONTENTS]).upload()
* @param {array} input
*/
async upload (input: []) {
const imgs = await new Uploader(input, this[WEBCONTENTS], this[PICGO]).upload()
if (imgs !== false) { if (imgs !== false) {
const pasteStyle = db.get('settings.pasteStyle') || 'markdown' const pasteStyle = db.get('settings.pasteStyle') || 'markdown'
let pasteText = '' let pasteText = ''
@ -88,11 +76,7 @@ class GuiApi {
return [] return []
} }
/** showNotification (options: IShowNotificationOption = {
* For notification
* @param {Object} options
*/
showNotification (options = {
title: '', title: '',
body: '' body: ''
}) { }) {
@ -103,17 +87,13 @@ class GuiApi {
notification.show() notification.show()
} }
/** showMessageBox (options: IShowMessageBoxOption = {
*
* @param {Object} options
*/
showMessageBox (options = {
title: '', title: '',
message: '', message: '',
type: 'info', type: 'info',
buttons: ['Yes', 'No'] buttons: ['Yes', 'No']
}) { }) {
return new Promise((resolve, reject) => { return new Promise<IShowMessageBoxResult>((resolve, reject) => {
dialog.showMessageBox( dialog.showMessageBox(
BrowserWindow.fromWebContents(this[WEBCONTENTS]), BrowserWindow.fromWebContents(this[WEBCONTENTS]),
options options

View File

@ -15,7 +15,7 @@ class Logger {
warn: IChalkType.warn, warn: IChalkType.warn,
error: IChalkType.error error: IChalkType.error
} }
protected handleLog (type: ILogType, msg: string | Error): string | Error | undefined { protected handleLog (type: ILogType, msg: ILoggerType): ILoggerType {
// if configPath is invalid then this.ctx.config === undefined // if configPath is invalid then this.ctx.config === undefined
// if not then check config.silent // if not then check config.silent
const log = chalk[this.level[type]](`[PicGo ${type.toUpperCase()}]:`) const log = chalk[this.level[type]](`[PicGo ${type.toUpperCase()}]:`)
@ -26,7 +26,7 @@ class Logger {
return msg return msg
} }
protected handleWriteLog (type: string, msg: string | Error): void { protected handleWriteLog (type: string, msg: ILoggerType): void {
try { try {
const logLevel = db.get('settings.logLevel') const logLevel = db.get('settings.logLevel')
const logPath = db.get('settings.logPath') || path.join(baseDir, './picgo.log') const logPath = db.get('settings.logPath') || path.join(baseDir, './picgo.log')
@ -56,19 +56,19 @@ class Logger {
} }
} }
success (msg: string | Error): string | Error | undefined { success (msg: ILoggerType): ILoggerType {
return this.handleLog('success', msg) return this.handleLog('success', msg)
} }
info (msg: string | Error): string | Error | undefined { info (msg: ILoggerType): ILoggerType {
return this.handleLog('info', msg) return this.handleLog('info', msg)
} }
error (msg: string | Error): string | Error | undefined { error (msg: ILoggerType): ILoggerType {
return this.handleLog('error', msg) return this.handleLog('error', msg)
} }
warn (msg: string | Error): string | Error | undefined { warn (msg: ILoggerType): ILoggerType {
return this.handleLog('warn', msg) return this.handleLog('warn', msg)
} }
} }

View File

@ -178,7 +178,7 @@ const handlePluginActions = (ipcMain: IpcMain, CONFIG_PATH: string) => {
ipcMain.on('pluginActions', (event: IpcMainEvent, name: string, label: string) => { ipcMain.on('pluginActions', (event: IpcMainEvent, name: string, label: string) => {
const picgo = new PicGo(CONFIG_PATH) const picgo = new PicGo(CONFIG_PATH)
const plugin = picgo.pluginLoader.getPlugin(`picgo-plugin-${name}`) const plugin = picgo.pluginLoader.getPlugin(`picgo-plugin-${name}`)
const guiApi = new GuiApi(ipcMain, event.sender, picgo) const guiApi = new GuiApi(event.sender)
if (plugin.guiMenu && plugin.guiMenu(picgo).length > 0) { if (plugin.guiMenu && plugin.guiMenu(picgo).length > 0) {
const menu: GuiMenuItem[] = plugin.guiMenu(picgo) const menu: GuiMenuItem[] = plugin.guiMenu(picgo)
menu.forEach(item => { menu.forEach(item => {
@ -193,7 +193,7 @@ const handlePluginActions = (ipcMain: IpcMain, CONFIG_PATH: string) => {
const handleRemoveFiles = (ipcMain: IpcMain, CONFIG_PATH: string) => { const handleRemoveFiles = (ipcMain: IpcMain, CONFIG_PATH: string) => {
ipcMain.on('removeFiles', (event: IpcMainEvent, files: ImgInfo[]) => { ipcMain.on('removeFiles', (event: IpcMainEvent, files: ImgInfo[]) => {
const picgo = new PicGo(CONFIG_PATH) const picgo = new PicGo(CONFIG_PATH)
const guiApi = new GuiApi(ipcMain, event.sender, picgo) const guiApi = new GuiApi(event.sender)
setTimeout(() => { setTimeout(() => {
picgo.emit('remove', files, guiApi) picgo.emit('remove', files, guiApi)
}, 500) }, 500)

View File

@ -1,60 +1,178 @@
import bus from './eventBus' import bus from './eventBus'
import PicGoCore from '~/universal/types/picgo'
import path from 'path'
import { import {
GlobalShortcut app,
globalShortcut,
BrowserWindow
} from 'electron' } from 'electron'
let isInModifiedMode = false // 修改快捷键模式 import logger from './logger'
bus.on('toggleShortKeyModifiedMode', flag => { import GuiApi from './guiApi'
isInModifiedMode = flag import db from '#/datastore'
}) import shortKeyService from './shortKeyService'
/** // eslint-disable-next-line
* const requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require
* @param {string} name
*/
const shortKeyHandler = (name: string) => {
if (isInModifiedMode) {
return
}
if (name.includes('picgo:')) {
bus.emit(name)
} else if (name.includes('picgo-plugin-')) {
// TODO: 处理插件快捷键
}
}
/** const PicGo = requireFunc('picgo') as typeof PicGoCore
* const STORE_PATH = app.getPath('userData')
*/ const CONFIG_PATH = path.join(STORE_PATH, '/data.json')
const shortKeyUpdater = (globalShortcut: GlobalShortcut, item: IShortKeyConfig, oldKey: string) => {
// 如果提供了旧key则解绑 class ShortKeyHandler {
if (oldKey) { private isInModifiedMode: boolean = false
globalShortcut.unregister(oldKey) constructor () {
bus.on('toggleShortKeyModifiedMode', flag => {
this.isInModifiedMode = flag
})
} }
if (item.enable === false) { init () {
globalShortcut.unregister(item.key) this.initBuiltInShortKey()
} else { this.initPluginsShortKey()
}
private initBuiltInShortKey () {
const commands = db.get('settings.shortKey') as IShortKeyConfigs
Object.keys(commands)
.filter(item => item.includes('picgo:'))
.map(command => {
const config = commands[command]
globalShortcut.register(config.key, () => {
this.handler(command)
})
})
}
private initPluginsShortKey () {
const picgo = new PicGo(CONFIG_PATH)
const pluginList = picgo.pluginLoader.getList()
for (let item of pluginList) {
const plugin = picgo.pluginLoader.getPlugin(item)
// if a plugin has commands
if (plugin && plugin.commands) {
if (typeof plugin.commands !== 'function') {
logger.warn(`${item}'s commands is not a function`)
continue
}
const commands = plugin.commands(picgo) as IPluginShortKeyConfig[]
for (let cmd of commands) {
const command = `${item}:${cmd.name}`
if (db.has(`settings.shortKey[${command}]`)) {
const commandConfig = db.get(`settings.shortKey.${command}`) as IShortKeyConfig
this.registerShortKey(commandConfig, command, cmd.handle, false)
} else {
this.registerShortKey(cmd, command, cmd.handle, true)
}
}
} else {
continue
}
}
}
private registerShortKey (config: IShortKeyConfig | IPluginShortKeyConfig, command: string, handler: IShortKeyHandler, writeFlag: boolean) {
shortKeyService.registerCommand(command, handler)
if (config.key) {
globalShortcut.register(config.key, () => {
this.handler(command)
})
} else {
logger.warn(`${command} do not provide a key to bind`)
}
if (writeFlag) {
db.set(`settings.shortKey.${command}`, {
enable: true,
name: config.name,
label: config.label,
key: config.key
} as IShortKeyConfig)
}
}
// enable or disable shortKey
bindOrUnbindShortKey (item: IShortKeyConfig, from: string): boolean {
const command = `${from}:${item.name}`
if (item.enable === false) {
globalShortcut.unregister(item.key)
db.set(`settings.shortKey.${command}.enable`, false)
return true
} else {
if (globalShortcut.isRegistered(item.key)) {
return false
} else {
db.set(`settings.shortKey.${command}.enable`, true)
globalShortcut.register(item.key, () => {
this.handler(command)
})
return true
}
}
}
// update shortKey bindings
updateShortKey (item: IShortKeyConfig, oldKey: string, from: string): boolean {
const command = `${from}:${item.name}`
if (globalShortcut.isRegistered(item.key)) return false
globalShortcut.unregister(oldKey)
db.set(`settings.shortKey.${command}.key`, item.key)
globalShortcut.register(item.key, () => { globalShortcut.register(item.key, () => {
shortKeyHandler(item.name) this.handler(`${from}:${item.name}`)
})
return true
}
private async handler (command: string) {
if (this.isInModifiedMode) {
return
}
if (command.includes('picgo:')) {
bus.emit(command)
} else if (command.includes('picgo-plugin-')) {
const handler = shortKeyService.getShortKeyHandler(command)
if (handler) {
const picgo = new PicGo(CONFIG_PATH)
// make sure settingWindow is created
bus.once('createSettingWindowDone', (cmd: string, settingWindowId: number) => {
if (cmd === command) {
const webContents = BrowserWindow.fromId(settingWindowId).webContents
const guiApi = new GuiApi(webContents)
return handler(picgo, guiApi)
}
})
bus.emit('createSettingWindow', command)
}
} else {
logger.warn(`can not find command: ${command}`)
}
}
registerPluginShortKey (pluginName: string) {
const picgo = new PicGo(CONFIG_PATH)
const plugin = picgo.pluginLoader.getPlugin(pluginName)
if (plugin && plugin.commands) {
if (typeof plugin.commands !== 'function') {
logger.warn(`${pluginName}'s commands is not a function`)
return
}
const commands = plugin.commands(picgo) as IPluginShortKeyConfig[]
for (let cmd of commands) {
const command = `${pluginName}:${cmd.name}`
if (db.has(`settings.shortKey[${command}]`)) {
const commandConfig = db.get(`settings.shortKey[${command}]`) as IShortKeyConfig
this.registerShortKey(commandConfig, command, cmd.handle, false)
} else {
this.registerShortKey(cmd, command, cmd.handle, true)
}
}
}
}
unregisterPluginShortKey (pluginName: string) {
const commands = db.get('settings.shortKey') as IShortKeyConfigs
const keyList = Object.keys(commands)
.filter(command => command.includes(pluginName))
.map(command => {
return {
command,
key: commands[command].key
}
}) as IKeyCommandType[]
keyList.forEach(item => {
globalShortcut.unregister(item.key)
shortKeyService.unregisterCommand(item.command)
db.unset('settings.shortKey', item.command)
}) })
} }
} }
// 初始化阶段的注册 export default new ShortKeyHandler()
const initShortKeyRegister = (globalShortcut: GlobalShortcut, shortKeys: IShortKeyConfig[]) => {
let errorList = []
for (let i in shortKeys) {
try {
if (shortKeys[i].enable) {
globalShortcut.register(shortKeys[i].key, () => {
shortKeyHandler(shortKeys[i].name)
})
}
} catch (e) {
errorList.push(shortKeys[i])
}
}
}
export {
shortKeyUpdater,
initShortKeyRegister
}

View File

@ -0,0 +1,21 @@
import logger from './logger'
class ShortKeyService {
private commandList: Map<string, IShortKeyHandler> = new Map()
registerCommand (command: string, handler: IShortKeyHandler) {
this.commandList.set(command, handler)
}
unregisterCommand (command: string) {
this.commandList.delete(command)
}
getShortKeyHandler (command: string): IShortKeyHandler | null {
const handler = this.commandList.get(command)
if (handler) return handler
logger.warn(`cannot find command: ${command}`)
return null
}
getCommandList () {
return [...this.commandList.keys()]
}
}
export default new ShortKeyService()

View File

@ -88,7 +88,7 @@ const waitForRename = (window: BrowserWindow, id: number): Promise<string|null>
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
ipcMain.once(`rename${id}`, (evt: Event, newName: string) => { ipcMain.once(`rename${id}`, (evt: Event, newName: string) => {
resolve(newName) resolve(newName)
window.hide() window.close()
}) })
window.on('close', () => { window.on('close', () => {
resolve(null) resolve(null)
@ -101,7 +101,7 @@ class Uploader {
private picgo: PicGoCore private picgo: PicGoCore
private webContents: WebContents private webContents: WebContents
private img: undefined | string[] private img: undefined | string[]
constructor (img: undefined | string[], webContents: WebContents, picgo: PicGoCore | undefined = undefined) { constructor (img: IUploadOption, webContents: WebContents, picgo: PicGoCore | undefined = undefined) {
this.img = img this.img = img
this.webContents = webContents this.webContents = webContents
this.picgo = picgo || new PicGo(CONFIG_PATH) this.picgo = picgo || new PicGo(CONFIG_PATH)

View File

@ -171,7 +171,7 @@ export default class extends Vue {
] ]
} }
os = '' os = ''
shortKey: ShortKeyMap = { shortKey: IShortKeyMap = {
upload: db.get('shortKey.upload') upload: db.get('shortKey.upload')
} }
picBed: IPicBedType[] = [] picBed: IPicBedType[] = []

View File

@ -131,7 +131,7 @@ export default class extends Vue {
id: null, id: null,
imgUrl: '' imgUrl: ''
} }
choosedList: ObjT<boolean> = {} choosedList: IObjT<boolean> = {}
choosedPicBed: string[] = [] choosedPicBed: string[] = []
searchText = '' searchText = ''
handleBarActive = false handleBarActive = false
@ -173,7 +173,7 @@ export default class extends Vue {
if (this.choosedPicBed.length > 0) { if (this.choosedPicBed.length > 0) {
let arr: ImgInfo[] = [] let arr: ImgInfo[] = []
this.choosedPicBed.forEach(item => { this.choosedPicBed.forEach(item => {
let obj: Obj = { let obj: IObj = {
type: item type: item
} }
if (this.searchText) { if (this.searchText) {
@ -288,7 +288,7 @@ export default class extends Vue {
cleanSearch () { cleanSearch () {
this.searchText = '' this.searchText = ''
} }
isMultiple (obj: Obj) { isMultiple (obj: IObj) {
return Object.values(obj).some(item => item) return Object.values(obj).some(item => item)
} }
multiRemove () { multiRemove () {

View File

@ -292,7 +292,7 @@ export default class extends Vue {
customLink = { customLink = {
value: db.get('settings.customLink') || '$url' value: db.get('settings.customLink') || '$url'
} }
shortKey: ShortKeyMap = { shortKey: IShortKeyMap = {
upload: db.get('settings.shortKey.upload') upload: db.get('settings.shortKey.upload')
} }
proxy = db.get('picBed.proxy') || '' proxy = db.get('picBed.proxy') || ''
@ -492,7 +492,7 @@ export default class extends Vue {
remote.shell.openExternal('https://picgo.github.io/PicGo-Doc/zh/guide/config.html#picgo设置') remote.shell.openExternal('https://picgo.github.io/PicGo-Doc/zh/guide/config.html#picgo设置')
} }
goShortCutPage () { goShortCutPage () {
this.$router.push('shortcut') this.$router.push('shortKey')
} }
beforeDestroy () { beforeDestroy () {
ipcRenderer.removeListener('getPicBeds', this.getPicBeds) ipcRenderer.removeListener('getPicBeds', this.getPicBeds)

View File

@ -1,183 +0,0 @@
<template>
<div id="shortcut-page">
<div class="view-title">
快捷键设置
</div>
<el-row>
<el-col :span="20" :offset="2">
<el-table
:data="list"
size="mini"
>
<el-table-column
label="快捷键名称"
>
<template slot-scope="scope">
{{ scope.row.label ? scope.row.label : scope.row.name }}
</template>
</el-table-column>
<el-table-column
width="180px"
label="快捷键绑定"
prop="key"
>
</el-table-column>
<el-table-column
label="状态"
>
<template slot-scope="scope">
<el-tag
size="mini"
:type="scope.row.enable ? 'success' : 'danger'"
>
{{ scope.row.enable ? '已启用' : '已禁用' }}
</el-tag>
</template>
</el-table-column>
<el-table-column
label="来源"
>
<template slot-scope="scope">
{{ calcOrigin(scope.row.name) }}
</template>
</el-table-column>
<el-table-column
label="操作"
>
<template slot-scope="scope">
<el-button
@click="toggleEnable(scope.row)"
size="mini"
:class="{
disabled: scope.row.enable
}"
type="text">
{{ scope.row.enable ? '禁用' : '启用' }}
</el-button>
<el-button
class="edit"
size="mini"
@click="openKeyBindingDialog(scope.row.name, scope.$index)"
type="text">
编辑
</el-button>
</template>
</el-table-column>
</el-table>
</el-col>
</el-row>
<el-dialog
title="修改上传快捷键"
:visible.sync="keyBindingVisible"
:modal-append-to-body="false"
>
<el-form
label-position="top"
label-width="80px"
>
<el-form-item
label="快捷上传"
>
<el-input
class="align-center"
@keydown.native.prevent="keyDetect($event)"
v-model="shortKey"
:autofocus="true"
></el-input>
</el-form-item>
</el-form>
<span slot="footer">
<el-button @click="cancelKeyBinding" round>取消</el-button>
<el-button type="primary" @click="confirmKeyBinding" round>确定</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
import keyDetect from 'utils/key-binding'
export default {
name: 'shortcut-page',
data () {
return {
list: [],
keyBindingVisible: false,
shortKeyName: '',
shortKey: '',
currentIndex: 0
}
},
created () {
const shortKeyConfig = this.$db.get('settings.shortKey')
this.list = Object.keys(shortKeyConfig).map(item => shortKeyConfig[item])
},
watch: {
keyBindingVisible (val) {
this.$electron.ipcRenderer.send('toggleShortKeyModifiedMode', val)
}
},
methods: {
calcOrigin (item) {
const [origin] = item.split(':')
return origin
},
toggleEnable (item) {
const status = !item.enable
item.enable = status
this.$db.set(`settings.shortKey.${item.name}.enable`, status)
this.$electron.ipcRenderer.send('updateShortKey', item)
},
keyDetect (event) {
this.shortKey = keyDetect(event).join('+')
},
openKeyBindingDialog (name, index) {
this.shortKeyName = name
this.shortKey = this.$db.get(`settings.shortKey.${name}.key`)
this.currentIndex = index
this.keyBindingVisible = true
},
cancelKeyBinding () {
this.keyBindingVisible = false
this.shortKey = this.$db.get(`settings.shortKey.${this.shortKeyName}.key`)
},
confirmKeyBinding () {
const oldKey = this.$db.get(`settings.shortKey.${this.shortKeyName}.key`)
this.$db.set(`settings.shortKey.${this.shortKeyName}.key`, this.shortKey)
const newKey = this.$db.get(`settings.shortKey.${this.shortKeyName}`)
this.$electron.ipcRenderer.send('updateShortKey', newKey, oldKey)
this.list[this.currentIndex].key = this.shortKey
this.keyBindingVisible = false
}
},
beforeDestroy () {
this.$electron.ipcRenderer.send('toggleShortKeyModifiedMode', false)
}
}
</script>
<style lang='stylus'>
#shortcut-page
.el-dialog__body
padding 10px 20px
.el-form-item
margin-bottom 0
.el-button
&.disabled
color: #F56C6C
&.edit
color: #67C23A
.el-table
background-color: transparent
color #ddd
thead
color #bbb
th,tr
background-color: transparent
&__body
tr.el-table__row--striped
td
background transparent
&--enable-row-hover
.el-table__body
tr:hover
&>td
background #333
</style>

View File

@ -38,7 +38,7 @@
label="来源" label="来源"
> >
<template slot-scope="scope"> <template slot-scope="scope">
{{ calcOrigin(scope.row.name) }} {{ calcOriginShowName(scope.row.from) }}
</template> </template>
</el-table-column> </el-table-column>
<el-table-column <el-table-column
@ -57,7 +57,7 @@
<el-button <el-button
class="edit" class="edit"
size="mini" size="mini"
@click="openKeyBindingDialog(scope.row.name, scope.$index)" @click="openKeyBindingDialog(scope.row, scope.$index)"
type="text"> type="text">
编辑 编辑
</el-button> </el-button>
@ -96,20 +96,25 @@
<script lang="ts"> <script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator' import { Component, Vue, Watch } from 'vue-property-decorator'
import keyDetect from '@/utils/key-binding' import keyDetect from '@/utils/key-binding'
import { ipcRenderer } from 'electron' import { ipcRenderer, IpcRendererEvent } from 'electron'
@Component({ @Component({
name: 'shortcut-page' name: 'shortkey-page'
}) })
export default class extends Vue { export default class extends Vue {
list: IShortKeyConfig[] = [] list: IShortKeyConfig[] = []
keyBindingVisible = false keyBindingVisible = false
shortKeyName = '' command = ''
shortKey = '' shortKey = ''
currentIndex = 0 currentIndex = 0
created () { created () {
const shortKeyConfig = this.$db.get('settings.shortKey') as IShortKeyConfigs const shortKeyConfig = this.$db.get('settings.shortKey') as IShortKeyConfigs
this.list = Object.keys(shortKeyConfig).map(item => shortKeyConfig[item]) this.list = Object.keys(shortKeyConfig).map(item => {
return {
...shortKeyConfig[item],
from: this.calcOrigin(item)
}
})
} }
@Watch('keyBindingVisible') @Watch('keyBindingVisible')
onKeyBindingVisibleChange (val: boolean) { onKeyBindingVisibleChange (val: boolean) {
@ -119,32 +124,41 @@ export default class extends Vue {
const [origin] = item.split(':') const [origin] = item.split(':')
return origin return origin
} }
calcOriginShowName (item: string) {
return item.replace('picgo-plugin-', '')
}
toggleEnable (item: IShortKeyConfig) { toggleEnable (item: IShortKeyConfig) {
const status = !item.enable const status = !item.enable
item.enable = status item.enable = status
this.$db.set(`settings.shortKey.${item.name}.enable`, status) // this.$db.set(`settings.shortKey.${item.name}.enable`, status)
ipcRenderer.send('updateShortKey', item) ipcRenderer.send('bindOrUnbindShortKey', item, item.from)
} }
keyDetect (event: KeyboardEvent) { keyDetect (event: KeyboardEvent) {
this.shortKey = keyDetect(event).join('+') this.shortKey = keyDetect(event).join('+')
} }
openKeyBindingDialog (name: string, index: number) { openKeyBindingDialog (config: IShortKeyConfig, index: number) {
this.shortKeyName = name this.command = `${config.from}:${config.name}`
this.shortKey = this.$db.get(`settings.shortKey.${name}.key`) this.shortKey = this.$db.get(`settings.shortKey.${this.command}.key`)
this.currentIndex = index this.currentIndex = index
this.keyBindingVisible = true this.keyBindingVisible = true
} }
cancelKeyBinding () { cancelKeyBinding () {
this.keyBindingVisible = false this.keyBindingVisible = false
this.shortKey = this.$db.get(`settings.shortKey.${this.shortKeyName}.key`) this.shortKey = this.$db.get(`settings.shortKey.${this.command}.key`)
} }
confirmKeyBinding () { confirmKeyBinding () {
const oldKey = this.$db.get(`settings.shortKey.${this.shortKeyName}.key`) const oldKey = this.$db.get(`settings.shortKey.${this.command}.key`)
this.$db.set(`settings.shortKey.${this.shortKeyName}.key`, this.shortKey) // this.$db.set(`settings.shortKey.${this.command}.key`, this.shortKey)
const newKey = this.$db.get(`settings.shortKey.${this.shortKeyName}`) // const newKey = this.$db.get(`settings.shortKey.${this.command}`)
ipcRenderer.send('updateShortKey', newKey, oldKey) const config = Object.assign({}, this.list[this.currentIndex])
this.list[this.currentIndex].key = this.shortKey config.key = this.shortKey
this.keyBindingVisible = false ipcRenderer.send('updateShortKey', config, oldKey, config.from)
ipcRenderer.once('updateShortKeyResponse', (evt: IpcRendererEvent, result) => {
if (result) {
this.keyBindingVisible = false
this.list[this.currentIndex].key = this.shortKey
}
})
} }
beforeDestroy () { beforeDestroy () {
ipcRenderer.send('toggleShortKeyModifiedMode', false) ipcRenderer.send('toggleShortKeyModifiedMode', false)

View File

@ -95,9 +95,9 @@ export default new Router({
name: 'plugin' name: 'plugin'
}, },
{ {
path: 'shortcut', path: 'shortKey',
component: () => import(/* webpackChunkName: "ShortkeyPage" */ '@/pages/ShortCut.vue'), component: () => import(/* webpackChunkName: "ShortkeyPage" */ '@/pages/ShortKey.vue'),
name: 'shortcut' name: 'shortKey'
} }
] ]
}, },

View File

@ -37,7 +37,7 @@ class DB {
this.db.set('settings.shortKey[picgo:upload]', { this.db.set('settings.shortKey[picgo:upload]', {
enable: true, enable: true,
key: 'CommandOrControl+Shift+P', key: 'CommandOrControl+Shift+P',
name: 'picgo:upload', name: 'upload',
label: '快捷上传' label: '快捷上传'
}).write() }).write()
} }
@ -58,6 +58,9 @@ class DB {
// @ts-ignore // @ts-ignore
return this.read().get(key).insert(value).write() return this.read().get(key).insert(value).write()
} }
unset (key: string, value: any): boolean {
return this.read().get(key).unset(value).write()
}
} }
export default new DB() export default new DB()

View File

@ -1,9 +1,9 @@
// global // global
interface Obj { interface IObj {
[propName: string]: any [propName: string]: any
} }
interface ObjT<T> { interface IObjT<T> {
[propName: string]: T [propName: string]: T
} }
@ -31,6 +31,14 @@ interface IShortKeyConfig {
key: string // 按键 key: string // 按键
name: string name: string
label: string label: string
from?: string
}
interface IPluginShortKeyConfig {
key: string
name: string
label: string
handle: IShortKeyHandler
} }
interface IShortKeyConfigs { interface IShortKeyConfigs {
@ -41,6 +49,11 @@ interface IOldShortKeyConfigs {
upload: string upload: string
} }
interface IKeyCommandType {
key: string,
command: string
}
// Main process // Main process
interface IBrowserWindowOptions { interface IBrowserWindowOptions {
height: number, height: number,
@ -83,7 +96,7 @@ declare type ILogType = 'success' | 'info' | 'warn' | 'error'
declare var __static: string declare var __static: string
// PicGo Types // PicGo Types
type ICtx = import('picgo')
interface IPicGoPlugin { interface IPicGoPlugin {
name: string name: string
author: string author: string
@ -135,14 +148,53 @@ interface INPMSearchResultObject {
} }
// GuiApi // GuiApi
interface IGuiApi {
showInputBox: (options: IShowInputBoxOption) => Promise<string>
showFileExplorer: (options: IShowFileExplorerOption) => Promise<string>
upload: (input: IUploadOption) => Promise<ImgInfo[]>
showNotification: (options?: IShowNotificationOption) => void
showMessageBox: (options?: IShowMessageBoxOption) => Promise<IShowMessageBoxResult>
}
interface IShowInputBoxOption { interface IShowInputBoxOption {
title: string title: string
placeholder: string placeholder: string
} }
// PicBeds type IShowFileExplorerOption = IObj
type IUploadOption = undefined | string[]
interface IShowNotificationOption {
title: string
body: string
}
interface IShowMessageBoxOption {
title: string
message: string
type: string
buttons: string[]
}
interface IShowMessageBoxResult {
result: number
checkboxChecked: boolean
}
interface IShortKeyHandlerObj {
handle: IShortKeyHandler
key: string
label: string
}
type IShortKeyHandler = (ctx: ICtx, guiApi?: IGuiApi) => Promise<void | ICtx>
interface shortKeyHandlerMap {
from: string
handle: IShortKeyHandler
}
// PicBeds
interface IAliYunConfig { interface IAliYunConfig {
accessKeyId: string accessKeyId: string
accessKeySecret: string, accessKeySecret: string,
@ -193,3 +245,5 @@ interface IUpYunConfig {
options: string, options: string,
path: string path: string
} }
type ILoggerType = string | Error | boolean | number | undefined

View File

@ -9,6 +9,6 @@ interface ISettingForm {
logLevel: string[] logLevel: string[]
} }
interface ShortKeyMap { interface IShortKeyMap {
[propName: string]: string [propName: string]: string
} }