This repository was archived by the owner on Dec 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcommandpalette.py
246 lines (199 loc) · 8.47 KB
/
commandpalette.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
#
# Copyright 2020 Thomas Engel <[email protected]>
# License: same as zim (gpl)
#
# DESCRIPTION:
#
# Zim plugin to search and execute menu entries via dialog.
#
# CHANGELOG:
#
# 2020-11-22 1st working version
# 2020-11-23 Improved usability
# 2020-12-13 Improved code and usability
# 2020-12-29 Added history support
# 2021-01-01 Improved usability
# 2021-01-03 Improved usability
# 2021-01-23 Limited history feature to only contain last entry
# 2021-01-23 Added ability to show keybindings in dialog
# 2021-02-18 Fixed display of keybindings
# 2021-03-13 Improved search ability
# 2021-04-16 Renamed project from "Zim Dash" to "Zim Command Palette" and changed keybinding from alt-x to ctrl-shift-p
# 2021-04-29 Enhanced documentation
import logging
import gi
gi.require_version('Gdk', '3.0')
gi.require_version('Gtk', '3.0')
from gi.repository import Gdk, Gtk
from zim.actions import action
from zim.config import String
from zim.gui.mainwindow import MainWindowExtension
from zim.gui.widgets import Dialog
from zim.plugins import PluginClass
logger = logging.getLogger('zim.plugins.commandpalette')
class CommandPalettePlugin(PluginClass):
plugin_info = {
'name': _('Command Palette'), # T: plugin name
'description': _('This plugin opens a search dialog to allow quickly '
'executing menu entries. The search dialog can be opened by '
'pressing the keyboard shortcut Ctrl+Shift+P which can be '
'customized via Zim\'s key bindings '
'preferences.'), # T: plugin description
'author': 'Thomas Engel <[email protected]>',
'help': 'Plugins:Command Palette',
}
class CommandPaletteMainWindowExtension(MainWindowExtension):
""" Listener for the show command palette dialog shortcut. """
def __init__(self, plugin, window):
MainWindowExtension.__init__(self, plugin, window)
self.window = window
def _init_store(self):
""" Construct the store containing all menu-items and associated actions. """
store = Gtk.ListStore(str, object, str)
for label, item in ZimMenuBarCrawler().run(self.window.menubar).items():
action = item[0]
shortcut = item[1]
store.append((label, action, shortcut))
return store
@action('', accelerator='<ctrl><shift>p', menuhints='accelonly')
def do_show_command_palette_dialog(self):
store = self._init_store()
dialog = ZimCommandPaletteDialog(self.window, store, self.plugin.preferences)
# BUG: Text selection in page view may get lost when opening the command palette dialog.
# FIX: Cache text selection and restore after dialog is closed.
text_buffer_selection_cache = TextBufferSelectionCache(self.window.pageview.textview.get_buffer())
dialog_response = dialog.run()
text_buffer_selection_cache.restore()
if dialog_response == Gtk.ResponseType.OK:
dialog.action()
# The return value is only relevant for the on_key_press_event function and makes sure that the
# pressed key is not processed any further.
return True
class TextBufferSelectionCache:
""" Cache and restore a selection within a text buffer. """
def __init__(self, buffer):
self._buffer = buffer
self.save()
def has_selection(self):
return self._sel_start is not None and self._sel_end is not None
def save(self):
if self._buffer.get_has_selection():
self._sel_start, self._sel_end = self._buffer.get_selection_bounds()
else:
self._sel_start, self._sel_end = None, None
def restore(self):
if self.has_selection():
self._buffer.select_range(self._sel_start, self._sel_end)
class ZimMenuBarCrawler:
""" Crawler for Gtk.MenuBar to return all item labels and associated actions in a dictionary. """
# Separator ">>" used between menu item names e.g. "File >> New Page..."
SEPARATOR = u'\u0020\u0020\u00BB\u0020\u0020'
def run(self, menu_bar: Gtk.MenuBar):
result = {}
def crawl(container: Gtk.MenuItem, path: str):
if container.get_submenu():
for child in container.get_submenu():
if hasattr(child, "get_label") and child.get_label():
child_path = path + ZimMenuBarCrawler.SEPARATOR + child.get_label().replace("_", "")
crawl(child, child_path)
else:
accel_name = None
if container.get_accel_path():
accel = Gtk.AccelMap.lookup_entry(container.get_accel_path())[1]
accel_name = Gtk.accelerator_get_label(accel.accel_key, accel.accel_mods)
result[path] = [container.activate, accel_name]
for child in menu_bar:
if hasattr(child, "get_label") and child.get_label():
crawl(child, child.get_label().replace("_", ""))
return result
class ZimCommandPaletteDialog(Dialog):
""" A search dialog with auto-complete feature. """
def __init__(self, parent, store, preferences):
title = _('Command Palette')
Dialog.__init__(self, parent, title)
self.uistate.define(last_entry=String(None))
self.action = None
self.store = store
self.entries = {item[0]: item[1] for item in self.store} # { label: action }
# Configure completion for search field.
completion = Gtk.EntryCompletion()
completion.set_model(store)
cell_shortcut = Gtk.CellRendererText()
completion.pack_end(cell_shortcut, False)
completion.add_attribute(cell_shortcut, 'text', 2)
completion.set_text_column(0)
completion.set_minimum_key_length(0)
completion.connect("match-selected", self.on_match_selected)
def match_anywhere(_completion, _entrystr, _iter, _data):
""" Match any part. """
_modelstr = _completion.get_model()[_iter][0].lower()
for part in _entrystr.split():
if part not in _modelstr:
return False
return True
completion.set_match_func(match_anywhere, None)
self.hbox = Gtk.HBox()
# Add search field.
self.txt_search = Gtk.SearchEntry(hexpand=True, margin=2)
self.txt_search.set_activates_default(True) # Make ENTER key press trigger the OK button.
self.txt_search.set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, Gtk.STOCK_FIND)
self.txt_search.set_placeholder_text("Search commands")
self.txt_search.set_completion(completion)
last_entry = self.init_last_entry()
if last_entry:
self.txt_search.set_text(last_entry)
self.txt_search.connect('search-changed', self.do_validate, parent)
self.txt_search.connect("key-press-event", self.on_key_pressed, parent)
# Add ok button.
self.btn_ok = self.get_widget_for_response(response_id=Gtk.ResponseType.OK)
self.btn_ok.set_can_default(True)
self.btn_ok.grab_default()
self.btn_ok.set_sensitive(last_entry is not None)
# Configure dialog.
self.set_modal(True)
self.set_default_size(380, 100)
self.hbox.pack_start(self.txt_search, True, True, 0)
self.vbox.pack_start(self.hbox, True, True, 0)
# Set focus to search field
self.txt_search.grab_focus()
def init_last_entry(self):
"""
Returns either the entry which was selected by the user in the last dialog call or None, when there never was
any selection at all or when the selected entry does not exist anymore (e.g. disabled plugin).
"""
if self.uistate['last_entry'] in self.entries:
return self.uistate['last_entry']
return None
def on_key_pressed(self, widget, event, data=None):
""" Listener for gtk.Entry key press events. """
if event.keyval == Gdk.KEY_Up or event.keyval == Gdk.KEY_Down:
# Open popup-menu with suggestions when pressing arrow-up/arrow-down key.
#
# Note: The popup-menu is only shown when the text field contains at least one character. This bypasses
# a bug which appears when the text field is empty in which case the entries shown in the popup menu
# can't be selected by pressing the ENTER key.
if len(self.txt_search.get_text()) > 0:
self.txt_search.emit('changed')
return True
elif event.keyval == Gdk.KEY_Escape:
self.close()
return True
return False
def on_match_selected(self, completion, model, iter):
""" Directly close dialog when selecting an entry in the completion list. """
logger.debug("ZimCommandPalettePlugin: Match selected from popup menu: {}".format(model[iter][0]))
self.txt_search.set_text(model[iter][0])
if self.do_response_ok():
self.close()
def do_validate(self, entry, data):
""" Validating selected text entry and enable/disable ok button. """
self.btn_ok.set_sensitive(entry.get_text() in self.entries)
def do_response_ok(self):
""" Finishing up when activating the ok button. """
if self.txt_search.get_text() in self.entries:
self.action = self.entries[self.txt_search.get_text()]
self.uistate['last_entry'] = self.txt_search.get_text()
self.result = Gtk.ResponseType.OK
return True
else:
logger.error("ZimCommandPalettePlugin: Aborting, invalid entry selected: {}".format(self.txt_search.get_text()))