hotkeys.service.ts 7.9 KB
Newer Older
E
.  
Eugene Pankov 已提交
1
import { Injectable, Inject, NgZone, EventEmitter } from '@angular/core'
E
wip  
Eugene Pankov 已提交
2
import { IHotkeyDescription, HotkeyProvider } from '../api/hotkeyProvider'
E
.  
Eugene Pankov 已提交
3 4 5
import { NativeKeyEvent, stringifyKeySequence } from './hotkeys.util'
import { ConfigService } from '../services/config.service'
import { ElectronService } from '../services/electron.service'
E
.  
Eugene Pankov 已提交
6

E
.  
Eugene Pankov 已提交
7 8 9 10 11 12
export interface PartialHotkeyMatch {
    id: string,
    strokes: string[],
    matchedLength: number,
}

E
.  
Eugene Pankov 已提交
13
const KEY_TIMEOUT = 2000
E
.  
Eugene Pankov 已提交
14

E
.  
Eugene Pankov 已提交
15 16 17
interface EventBufferEntry {
    event: NativeKeyEvent,
    time: number,
E
.  
Eugene Pankov 已提交
18 19 20 21
}

@Injectable()
export class HotkeysService {
E
.  
Eugene Pankov 已提交
22
    key = new EventEmitter<NativeKeyEvent>()
E
.  
Eugene Pankov 已提交
23
    matchedHotkey = new EventEmitter<string>()
E
.  
Eugene Pankov 已提交
24
    globalHotkey = new EventEmitter()
E
.  
Eugene Pankov 已提交
25
    private currentKeystrokes: EventBufferEntry[] = []
E
.  
Eugene Pankov 已提交
26
    private disabledLevel = 0
E
Eugene Pankov 已提交
27
    private hotkeyDescriptions: IHotkeyDescription[] = []
E
.  
Eugene Pankov 已提交
28

E
lint  
Eugene Pankov 已提交
29
    constructor (
E
.  
Eugene Pankov 已提交
30 31
        private zone: NgZone,
        private electron: ElectronService,
E
.  
Eugene Pankov 已提交
32
        private config: ConfigService,
E
Eugene Pankov 已提交
33
        @Inject(HotkeyProvider) private hotkeyProviders: HotkeyProvider[],
E
.  
Eugene Pankov 已提交
34
    ) {
E
.  
Eugene Pankov 已提交
35
        let events = ['keydown', 'keyup']
E
.  
Eugene Pankov 已提交
36
        events.forEach((event) => {
E
.  
Eugene Pankov 已提交
37
            document.addEventListener(event, (nativeEvent) => {
E
lint  
Eugene Pankov 已提交
38
                if (document.querySelectorAll('input:focus').length === 0) {
E
.  
Eugene Pankov 已提交
39 40 41
                    this.pushKeystroke(event, nativeEvent)
                    this.processKeystrokes()
                    this.emitKeyEvent(nativeEvent)
E
.  
Eugene Pankov 已提交
42
                }
E
.  
Eugene Pankov 已提交
43 44
            })
        })
E
wip  
Eugene Pankov 已提交
45
        this.config.changed$.subscribe(() => {
E
.  
Eugene Pankov 已提交
46 47 48
            this.registerGlobalHotkey()
        })
        this.registerGlobalHotkey()
E
Eugene Pankov 已提交
49 50 51
        this.getHotkeyDescriptions().then(hotkeys => {
            this.hotkeyDescriptions = hotkeys
        })
E
.  
Eugene Pankov 已提交
52 53
    }

E
.  
Eugene Pankov 已提交
54
    pushKeystroke (name, nativeEvent) {
E
.  
Eugene Pankov 已提交
55 56
        nativeEvent.event = name
        this.currentKeystrokes.push({ event: nativeEvent, time: performance.now() })
E
.  
Eugene Pankov 已提交
57
    }
E
.  
Eugene Pankov 已提交
58

E
.  
Eugene Pankov 已提交
59
    processKeystrokes () {
E
.  
Eugene Pankov 已提交
60 61
        if (this.isEnabled()) {
            this.zone.run(() => {
E
.  
Eugene Pankov 已提交
62 63 64 65 66 67
                let matched = this.getCurrentFullyMatchedHotkey()
                if (matched) {
                    console.log('Matched hotkey', matched)
                    this.matchedHotkey.emit(matched)
                    this.clearCurrentKeystrokes()
                }
E
.  
Eugene Pankov 已提交
68 69
            })
        }
E
.  
Eugene Pankov 已提交
70 71 72 73
    }

    emitKeyEvent (nativeEvent) {
        this.zone.run(() => {
E
.  
Eugene Pankov 已提交
74
            this.key.emit(nativeEvent)
E
.  
Eugene Pankov 已提交
75 76
        })
    }
E
.  
Eugene Pankov 已提交
77

E
.  
Eugene Pankov 已提交
78 79 80 81
    clearCurrentKeystrokes () {
        this.currentKeystrokes = []
    }

E
lint  
Eugene Pankov 已提交
82
    getCurrentKeystrokes (): string[] {
E
.  
Eugene Pankov 已提交
83 84 85 86
        this.currentKeystrokes = this.currentKeystrokes.filter((x) => performance.now() - x.time < KEY_TIMEOUT )
        return stringifyKeySequence(this.currentKeystrokes.map((x) => x.event))
    }

E
.  
Eugene Pankov 已提交
87
    registerGlobalHotkey () {
E
.  
Eugene Pankov 已提交
88
        this.electron.globalShortcut.unregisterAll()
89
        let value = this.config.store.hotkeys['toggle-window'] || []
E
lint  
Eugene Pankov 已提交
90
        if (typeof value === 'string') {
E
.  
Eugene Pankov 已提交
91 92 93
            value = [value]
        }
        value.forEach(item => {
E
lint  
Eugene Pankov 已提交
94
            item = (typeof item === 'string') ? [item] : item
E
.  
Eugene Pankov 已提交
95

E
wip  
Eugene Pankov 已提交
96 97 98 99 100 101 102
            try {
                this.electron.globalShortcut.register(item[0].replace(/-/g, '+'), () => {
                    this.globalHotkey.emit()
                })
            } catch (err) {
                console.error('Could not register the global hotkey:', err)
            }
E
.  
Eugene Pankov 已提交
103 104
        })
    }
E
.  
Eugene Pankov 已提交
105 106

    getHotkeysConfig () {
E
Eugene Pankov 已提交
107 108 109 110
        return this.getHotkeysConfigRecursive(this.config.store.hotkeys)
    }

    getHotkeysConfigRecursive (branch) {
E
.  
Eugene Pankov 已提交
111
        let keys = {}
E
Eugene Pankov 已提交
112 113 114 115 116 117 118 119 120 121 122
        for (let key in branch) {
            let value = branch[key]
            if (value instanceof Object && !(value instanceof Array)) {
                let subkeys = this.getHotkeysConfigRecursive(value)
                for (let subkey in subkeys) {
                    keys[key + '.' + subkey] = subkeys[subkey]
                }
            } else {
                if (typeof value === 'string') {
                    value = [value]
                }
E
Eugene Pankov 已提交
123 124 125 126
                if (value) {
                    value = value.map((item) => (typeof item === 'string') ? [item] : item)
                    keys[key] = value
                }
E
.  
Eugene Pankov 已提交
127
            }
E
.  
Eugene Pankov 已提交
128 129 130 131
        }
        return keys
    }

E
lint  
Eugene Pankov 已提交
132
    getCurrentFullyMatchedHotkey (): string {
E
Eugene Pankov 已提交
133 134 135 136
        let currentStrokes = this.getCurrentKeystrokes()
        let config = this.getHotkeysConfig()
        for (let id in config) {
            for (let sequence of config[id]) {
E
.  
Eugene Pankov 已提交
137
                if (currentStrokes.length < sequence.length) {
E
.  
Eugene Pankov 已提交
138
                    continue
E
.  
Eugene Pankov 已提交
139
                }
E
Eugene Pankov 已提交
140 141 142 143 144
                if (sequence.every(
                    (x, index) =>
                        x.toLowerCase() ===
                            currentStrokes[currentStrokes.length - sequence.length + index].toLowerCase()
                )) {
E
.  
Eugene Pankov 已提交
145 146 147 148 149 150 151
                    return id
                }
            }
        }
        return null
    }

E
lint  
Eugene Pankov 已提交
152
    getCurrentPartiallyMatchedHotkeys (): PartialHotkeyMatch[] {
E
Eugene Pankov 已提交
153 154
        let currentStrokes = this.getCurrentKeystrokes()
        let config = this.getHotkeysConfig()
E
.  
Eugene Pankov 已提交
155
        let result = []
E
Eugene Pankov 已提交
156 157
        for (let id in config) {
            for (let sequence of config[id]) {
E
.  
Eugene Pankov 已提交
158
                for (let matchLength = Math.min(currentStrokes.length, sequence.length); matchLength > 0; matchLength--) {
E
Eugene Pankov 已提交
159 160 161 162 163
                    if (sequence.slice(0, matchLength).every(
                        (x, index) =>
                            x.toLowerCase() ===
                                currentStrokes[currentStrokes.length - matchLength + index].toLowerCase()
                    )) {
E
.  
Eugene Pankov 已提交
164 165 166 167 168 169 170 171 172 173 174 175 176
                        result.push({
                            matchedLength: matchLength,
                            id,
                            strokes: sequence
                        })
                        break
                    }
                }
            }
        }
        return result
    }

E
lint  
Eugene Pankov 已提交
177 178
    getHotkeyDescription (id: string): IHotkeyDescription {
        return this.hotkeyDescriptions.filter((x) => x.id === id)[0]
E
.  
Eugene Pankov 已提交
179
    }
E
.  
Eugene Pankov 已提交
180 181 182 183 184 185 186 187 188 189

    enable () {
        this.disabledLevel--
    }

    disable () {
        this.disabledLevel++
    }

    isEnabled () {
E
lint  
Eugene Pankov 已提交
190
        return this.disabledLevel === 0
E
.  
Eugene Pankov 已提交
191
    }
E
Eugene Pankov 已提交
192 193 194 195 196 197 198 199 200

    async getHotkeyDescriptions (): Promise<IHotkeyDescription[]> {
        return (
            await Promise.all(
                this.config.enabledServices(this.hotkeyProviders)
                    .map(async x => x.provide ? x.provide() : x.hotkeys)
            )
        ).reduce((a, b) => a.concat(b))
    }
E
.  
Eugene Pankov 已提交
201
}
E
.  
Eugene Pankov 已提交
202 203 204 205

@Injectable()
export class AppHotkeyProvider extends HotkeyProvider {
    hotkeys: IHotkeyDescription[] = [
206 207 208 209
        {
            id: 'new-window',
            name: 'New window',
        },
E
.  
Eugene Pankov 已提交
210 211 212 213
        {
            id: 'toggle-window',
            name: 'Toggle terminal window',
        },
E
Eugene Pankov 已提交
214 215 216 217
        {
            id: 'toggle-fullscreen',
            name: 'Toggle fullscreen mode',
        },
E
.  
Eugene Pankov 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
        {
            id: 'close-tab',
            name: 'Close tab',
        },
        {
            id: 'toggle-last-tab',
            name: 'Toggle last tab',
        },
        {
            id: 'next-tab',
            name: 'Next tab',
        },
        {
            id: 'previous-tab',
            name: 'Previous tab',
        },
        {
            id: 'tab-1',
            name: 'Tab 1',
        },
        {
            id: 'tab-2',
            name: 'Tab 2',
        },
        {
            id: 'tab-3',
            name: 'Tab 3',
        },
        {
            id: 'tab-4',
            name: 'Tab 4',
        },
        {
            id: 'tab-5',
            name: 'Tab 5',
        },
        {
            id: 'tab-6',
            name: 'Tab 6',
        },
        {
            id: 'tab-7',
            name: 'Tab 7',
        },
        {
            id: 'tab-8',
            name: 'Tab 8',
        },
        {
            id: 'tab-9',
            name: 'Tab 9',
        },
        {
            id: 'tab-10',
            name: 'Tab 10',
        },
    ]
E
Eugene Pankov 已提交
275 276 277 278

    async provide (): Promise<IHotkeyDescription[]> {
        return this.hotkeys
    }
E
.  
Eugene Pankov 已提交
279
}