🚧 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 {
updateShortKeyFromVersion212
} from '~/main/migrate/shortKeyUpdateHelper'
import {
shortKeyUpdater,
initShortKeyRegister
} from '~/main/utils/shortKeyHandler'
import shortKeyHandler from '~/main/utils/shortKeyHandler'
import logger from '~/main/utils/logger'
const isDevelopment = process.env.NODE_ENV !== 'production'
@ -462,13 +459,39 @@ ipcMain.on('uploadChoosedFiles', async (evt: IpcMainEvent, files: IFileWithPath[
return uploadChoosedFiles(evt.sender, files)
})
ipcMain.on('updateShortKey', (evt: IpcMainEvent, item: IShortKeyConfig, oldKey: string) => {
shortKeyUpdater(globalShortcut, item, oldKey)
const notification = new Notification({
title: '操作成功',
body: '你的快捷键已经修改成功'
})
notification.show()
ipcMain.on('updateShortKey', (evt: IpcMainEvent, item: IShortKeyConfig, oldKey: string, from: string) => {
const result = shortKeyHandler.updateShortKey(item, oldKey, from)
evt.sender.send('updateShortKeyResponse', result)
if (result) {
const notification = new Notification({
title: '操作成功',
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', () => {
@ -585,7 +608,7 @@ app.on('ready', async () => {
// 不需要阻塞
process.nextTick(() => {
updateShortKeyFromVersion212(db, db.get('settings.shortKey'))
initShortKeyRegister(globalShortcut, db.get('settings.shortKey'))
shortKeyHandler.init()
})
if (process.env.NODE_ENV !== 'development') {
@ -638,13 +661,26 @@ app.setLoginItemSettings({
function initEventCenter () {
const eventList: any = {
'picgo:upload': uploadClipboardFiles
'picgo:upload': uploadClipboardFiles,
'createSettingWindow': shortKeyRequestSettingWindow,
hideMiniWindow
}
for (let i in eventList) {
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.
if (isDevelopment) {
if (process.platform === 'win32') {

View File

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

View File

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

View File

@ -15,7 +15,7 @@ class Logger {
warn: IChalkType.warn,
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 not then check config.silent
const log = chalk[this.level[type]](`[PicGo ${type.toUpperCase()}]:`)
@ -26,7 +26,7 @@ class Logger {
return msg
}
protected handleWriteLog (type: string, msg: string | Error): void {
protected handleWriteLog (type: string, msg: ILoggerType): void {
try {
const logLevel = db.get('settings.logLevel')
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)
}
info (msg: string | Error): string | Error | undefined {
info (msg: ILoggerType): ILoggerType {
return this.handleLog('info', msg)
}
error (msg: string | Error): string | Error | undefined {
error (msg: ILoggerType): ILoggerType {
return this.handleLog('error', msg)
}
warn (msg: string | Error): string | Error | undefined {
warn (msg: ILoggerType): ILoggerType {
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) => {
const picgo = new PicGo(CONFIG_PATH)
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) {
const menu: GuiMenuItem[] = plugin.guiMenu(picgo)
menu.forEach(item => {
@ -193,7 +193,7 @@ const handlePluginActions = (ipcMain: IpcMain, CONFIG_PATH: string) => {
const handleRemoveFiles = (ipcMain: IpcMain, CONFIG_PATH: string) => {
ipcMain.on('removeFiles', (event: IpcMainEvent, files: ImgInfo[]) => {
const picgo = new PicGo(CONFIG_PATH)
const guiApi = new GuiApi(ipcMain, event.sender, picgo)
const guiApi = new GuiApi(event.sender)
setTimeout(() => {
picgo.emit('remove', files, guiApi)
}, 500)

View File

@ -1,60 +1,178 @@
import bus from './eventBus'
import PicGoCore from '~/universal/types/picgo'
import path from 'path'
import {
GlobalShortcut
app,
globalShortcut,
BrowserWindow
} from 'electron'
let isInModifiedMode = false // 修改快捷键模式
bus.on('toggleShortKeyModifiedMode', flag => {
isInModifiedMode = flag
})
/**
*
* @param {string} name
*/
const shortKeyHandler = (name: string) => {
if (isInModifiedMode) {
return
}
if (name.includes('picgo:')) {
bus.emit(name)
} else if (name.includes('picgo-plugin-')) {
// TODO: 处理插件快捷键
}
}
import logger from './logger'
import GuiApi from './guiApi'
import db from '#/datastore'
import shortKeyService from './shortKeyService'
// eslint-disable-next-line
const requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require
/**
*
*/
const shortKeyUpdater = (globalShortcut: GlobalShortcut, item: IShortKeyConfig, oldKey: string) => {
// 如果提供了旧key则解绑
if (oldKey) {
globalShortcut.unregister(oldKey)
const PicGo = requireFunc('picgo') as typeof PicGoCore
const STORE_PATH = app.getPath('userData')
const CONFIG_PATH = path.join(STORE_PATH, '/data.json')
class ShortKeyHandler {
private isInModifiedMode: boolean = false
constructor () {
bus.on('toggleShortKeyModifiedMode', flag => {
this.isInModifiedMode = flag
})
}
if (item.enable === false) {
globalShortcut.unregister(item.key)
} else {
init () {
this.initBuiltInShortKey()
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, () => {
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)
})
}
}
// 初始化阶段的注册
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
}
export default new ShortKeyHandler()

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) => {
ipcMain.once(`rename${id}`, (evt: Event, newName: string) => {
resolve(newName)
window.hide()
window.close()
})
window.on('close', () => {
resolve(null)
@ -101,7 +101,7 @@ class Uploader {
private picgo: PicGoCore
private webContents: WebContents
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.webContents = webContents
this.picgo = picgo || new PicGo(CONFIG_PATH)

View File

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

View File

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

View File

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

View File

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

View File

@ -37,7 +37,7 @@ class DB {
this.db.set('settings.shortKey[picgo:upload]', {
enable: true,
key: 'CommandOrControl+Shift+P',
name: 'picgo:upload',
name: 'upload',
label: '快捷上传'
}).write()
}
@ -58,6 +58,9 @@ class DB {
// @ts-ignore
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()

View File

@ -1,9 +1,9 @@
// global
interface Obj {
interface IObj {
[propName: string]: any
}
interface ObjT<T> {
interface IObjT<T> {
[propName: string]: T
}
@ -31,6 +31,14 @@ interface IShortKeyConfig {
key: string // 按键
name: string
label: string
from?: string
}
interface IPluginShortKeyConfig {
key: string
name: string
label: string
handle: IShortKeyHandler
}
interface IShortKeyConfigs {
@ -41,6 +49,11 @@ interface IOldShortKeyConfigs {
upload: string
}
interface IKeyCommandType {
key: string,
command: string
}
// Main process
interface IBrowserWindowOptions {
height: number,
@ -83,7 +96,7 @@ declare type ILogType = 'success' | 'info' | 'warn' | 'error'
declare var __static: string
// PicGo Types
type ICtx = import('picgo')
interface IPicGoPlugin {
name: string
author: string
@ -135,14 +148,53 @@ interface INPMSearchResultObject {
}
// 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 {
title: 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 {
accessKeyId: string
accessKeySecret: string,
@ -193,3 +245,5 @@ interface IUpYunConfig {
options: string,
path: string
}
type ILoggerType = string | Error | boolean | number | undefined

View File

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