-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
KeyboardShortcutsSimple.py
353 lines (298 loc) · 12.5 KB
/
KeyboardShortcutsSimple.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
#Author-Thomas Axelsson
#Description-Lists all keyboard shortcuts
# This file is part of KeyboardShortcutsSimple, a Fusion 360 add-in for naming
# features directly after creation.
#
# Copyright (C) 2020 Thomas Axelsson
#
# KeyboardShortcutsSimple is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# KeyboardShortcutsSimple is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with KeyboardShortcutsSimple. If not, see <https://www.gnu.org/licenses/>.
import adsk.core, adsk.fusion, adsk.cam, traceback
from collections import defaultdict
import json
import operator
import os
import sys
from tkinter import Tk
import xml.etree.ElementTree as ET
NAME = 'Keyboard Shortcuts Simple'
FILE_DIR = os.path.dirname(os.path.realpath(__file__))
# Import relative path to avoid namespace pollution
from .thomasa88lib import utils
from .thomasa88lib import events
from .thomasa88lib import error
from .version import VERSION
if os.name == 'nt':
from . import windows as platform
else:
from . import mac as platform
# Force modules to be fresh during development
import importlib
importlib.reload(thomasa88lib.utils)
importlib.reload(thomasa88lib.events)
importlib.reload(thomasa88lib.error)
importlib.reload(platform)
LIST_CMD_ID = 'thomasa88_keyboardShortcutsSimpleList'
UNKNOWN_WORKSPACE = 'UNKNOWN'
app_ = None
ui_ = None
error_catcher_ = thomasa88lib.error.ErrorCatcher(msgbox_in_debug=False)
events_manager_ = thomasa88lib.events.EventsManager(error_catcher_)
list_cmd_def_ = None
cmd_def_workspaces_map_ = None
used_workspaces_ids_ = None
sorted_workspaces_ = None
ws_filter_map_ = None
ns_hotkeys_ = None
class Hotkey:
pass
def list_command_created_handler(args):
eventArgs = adsk.core.CommandCreatedEventArgs.cast(args)
get_data()
# The nifty thing with cast is that code completion then knows the object type
cmd = adsk.core.Command.cast(args.command)
cmd.isRepeatable = False
cmd.isExecutedWhenPreEmpted = False
cmd.isOKButtonVisible = False
cmd.setDialogMinimumSize(350, 200)
cmd.setDialogInitialSize(400, 500)
events_manager_.add_handler(cmd.inputChanged,
adsk.core.InputChangedEventHandler,
input_changed_handler)
events_manager_.add_handler(cmd.destroy,
adsk.core.CommandEventHandler,
destroy_handler)
inputs = cmd.commandInputs
workspace_input = inputs.addDropDownCommandInput('workspace',
'Workspace',
adsk.core.DropDownStyles.LabeledIconDropDownStyle)
global ws_filter_map_
ws_filter_map_ = []
workspace_input.listItems.add('All', True, '', -1)
ws_filter_map_.append(None)
#workspace_input.listItems.addSeparator(-1)
workspace_input.listItems.add('----------------------------------', False, '', -1)
ws_filter_map_.append('SEPARATOR')
workspace_input.listItems.add('General', False, '', -1)
ws_filter_map_.append(UNKNOWN_WORKSPACE)
for workspace in sorted_workspaces_:
workspace_input.listItems.add(workspace.name, False, '', -1)
ws_filter_map_.append(workspace.id)
only_user_input = inputs.addBoolValueInput('only_user', 'Only user-defined ', True, '', True)
shortcut_sort_input = inputs.addBoolValueInput('shortcut_sort', 'Sort by shortcut keys', True, '', False)
inputs.addTextBoxCommandInput('list', '', get_hotkeys_str(only_user=only_user_input.value), 30, False)
inputs.addTextBoxCommandInput('list_info', '', '* = User-defined', 1, True)
copy_input = inputs.addBoolValueInput('copy', 'Copy', False,
thomasa88lib.utils.get_fusion_deploy_folder() + '/Electron/UI/Resources/Icons/Copy')
def get_data():
# Build on every invocation, in case keys have changed
# (Does not really matter for a Script)
build_cmd_def_workspaces_map()
global sorted_workspaces_
sorted_workspaces_ = sorted([ui_.workspaces.itemById(w_id) for w_id in used_workspaces_ids_],
key=lambda w: w.name)
global ns_hotkeys_
options_file = platform.find_options_file(app_)
hotkeys = parse_hotkeys(options_file)
hotkeys = map_command_names(hotkeys)
ns_hotkeys_ = namespace_group_hotkeys(hotkeys)
def input_changed_handler(args):
eventArgs = adsk.core.InputChangedEventArgs.cast(args)
inputs = eventArgs.inputs
if eventArgs.input.id == 'list':
return
list_input = inputs.itemById('list')
only_user_input = inputs.itemById('only_user')
shortcut_sort_input = inputs.itemById('shortcut_sort')
workspace_input = inputs.itemById('workspace')
workspace_filter = ws_filter_map_[workspace_input.selectedItem.index]
if eventArgs.input.id == 'copy':
copy_input = eventArgs.input
copy_input.value = False
copy_to_clipboard(get_hotkeys_str(only_user_input.value, workspace_filter,
sort_by_key=shortcut_sort_input.value,
html=False))
else:
# Update list
list_input.formattedText = get_hotkeys_str(only_user_input.value, workspace_filter,
sort_by_key=shortcut_sort_input.value)
def destroy_handler(args):
# Force the termination of the command.
adsk.terminate()
events_manager_.clean_up()
def get_hotkeys_str(only_user=False, workspace_filter=None, sort_by_key=False, html=True):
# HTML table is hard to copy-paste. Use fixed-width font instead.
# Supported HTML in QT: https://doc.qt.io/archives/qt-4.8/richtext-html-subset.html
def header(text, text_underline='-'):
if html:
return f'<b>{text}</b><br>'
else:
return f'{text}\n{text_underline * len(text)}\n'
def newline():
return '<br>' if html else '\n'
def sort_key(hotkey):
if sort_by_key:
return (hotkey.keyboard_base_key, hotkey.keyboard_key_sequence)
else:
return hotkey.command_name
string = ''
if html:
string += '<pre>'
else:
string += header('Fusion 360 Keyboard Shortcuts', '=') + '\n'
for workspace_id, hotkeys in ns_hotkeys_.items():
if workspace_filter and workspace_id != workspace_filter:
continue
# Make sure to filter before any de-dup operation
if only_user:
hotkeys = [hotkey for hotkey in hotkeys if not hotkey.is_default]
if not hotkeys:
continue
hotkeys = deduplicate_hotkeys(hotkeys)
if workspace_id != UNKNOWN_WORKSPACE:
workspace_name = ui_.workspaces.itemById(workspace_id).name
else:
workspace_name = 'General'
if html:
string += f'<b>{workspace_name}</b><br>'
else:
string += f'{workspace_name}\n{"=" * len(workspace_name)}\n'
for hotkey in sorted(hotkeys, key=sort_key):
name = hotkey.command_name
if not hotkey.is_default:
name += '*'
string += f'{name:30} {hotkey.keyboard_key_sequence}'
string += newline()
string += newline()
if html:
string += '</pre>'
else:
string += '* = User-defined'
return string
def map_command_names(hotkeys):
for hotkey in hotkeys:
command = ui_.commandDefinitions.itemById(hotkey.command_id)
if command:
command_name = command.name
else:
command_name = hotkey.command_id
if hotkey.command_argument:
command_name += '->' + hotkey.command_argument
hotkey.command_name = command_name
return hotkeys
def namespace_group_hotkeys(hotkeys):
ns_hotkeys = defaultdict(list)
for hotkey in hotkeys:
workspaces = find_cmd_workspaces(hotkey.command_id)
for workspace in workspaces:
ns_hotkeys[workspace].append(hotkey)
if not workspaces:
ns_hotkeys[UNKNOWN_WORKSPACE].append(hotkey)
return ns_hotkeys
def build_cmd_def_workspaces_map():
global cmd_def_workspaces_map_
global used_workspaces_ids_
cmd_def_workspaces_map_ = defaultdict(set)
used_workspaces_ids_ = set()
for workspace in ui_.workspaces:
try:
if workspace.productType == '':
continue
except Exception:
continue
for panel in workspace.toolbarPanels:
explore_controls(panel.controls, workspace)
def explore_controls(controls, workspace):
global used_workspaces_ids_
for control in controls:
if control.objectType == adsk.core.CommandControl.classType():
try:
cmd_id = control.commandDefinition.id
except RuntimeError as e:
#print(f"Could not read commandDefintion for {control.id}", control)
continue
cmd_def_workspaces_map_[cmd_id].add(workspace.id)
used_workspaces_ids_.add(workspace.id)
#print("READ", cmd_id)
elif control.objectType == adsk.core.DropDownControl.classType():
explore_controls(control.controls, workspace)
def find_cmd_workspaces(cmd_id):
return cmd_def_workspaces_map_.get(cmd_id, [ UNKNOWN_WORKSPACE ])
def deduplicate_hotkeys(hotkeys):
ids = set()
filtered = []
for hotkey in hotkeys:
# Using command_name instead of command_id, as the names duplicate
hid = (hotkey.command_name, hotkey.command_argument)
if hid in ids:
#print("DUP: ", hotkey.command_id, hotkey.command_argument, hotkey.fusion_key_sequence)
continue
ids.add(hid)
filtered.append(hotkey)
return filtered
def parse_hotkeys(options_file):
hotkeys = []
xml = ET.parse(options_file)
root = xml.getroot()
json_element = root.find('./HotKeyGroup/HotKeyJSONString')
value = json.loads(json_element.attrib['Value'])
for h in value['hotkeys']:
if 'hotkey_sequence' not in h:
continue
fusion_key_sequence = h['hotkey_sequence']
# Move data extraction to separate function?
# E.g. ! is used for shift+1, so we need to pull out the virtual keycode,
# to get the actual key that the user needs to press. (E.g. '=' is placed
# on different keys on different keyboards and some use shift.)
keyboard_key_sequence, keyboard_base_key = platform.fusion_key_to_keyboard_key(fusion_key_sequence)
for hotkey_command in h['commands']:
hotkey = Hotkey()
hotkey.command_id = hotkey_command['command_id']
hotkey.command_argument = hotkey_command['command_argument']
hotkey.is_default = hotkey_command['isDefault']
hotkey.fusion_key_sequence = fusion_key_sequence
hotkey.keyboard_key_sequence = keyboard_key_sequence
hotkey.keyboard_base_key = keyboard_base_key
hotkeys.append(hotkey)
return hotkeys
def copy_to_clipboard(string):
# From https://stackoverflow.com/a/25476462/106019
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append(string)
r.update() # now it stays on the clipboard after the window is closed
r.destroy()
def delete_command_def():
cmd_def = ui_.commandDefinitions.itemById(LIST_CMD_ID)
if cmd_def:
cmd_def.deleteMe()
def run(context):
global app_
global ui_
global list_cmd_def_
with error_catcher_:
app_ = adsk.core.Application.get()
ui_ = app_.userInterface
if ui_.activeCommand == LIST_CMD_ID:
ui_.terminateActiveCommand()
delete_command_def()
list_cmd_def_ = ui_.commandDefinitions.addButtonDefinition(LIST_CMD_ID,
f'{NAME} {VERSION}',
'',)
events_manager_.add_handler(list_cmd_def_.commandCreated,
adsk.core.CommandCreatedEventHandler,
list_command_created_handler)
list_cmd_def_.execute()
# Keep the script running.
adsk.autoTerminate(False)