PluginSelectionEncloser.py

branch
eric7
changeset 51
318d7ebbdce2
parent 48
767eb5905e08
child 52
d2119f1dd5b3
equal deleted inserted replaced
50:face142f8fa5 51:318d7ebbdce2
9 9
10 import contextlib 10 import contextlib
11 import os 11 import os
12 import json 12 import json
13 13
14 from PyQt5.QtCore import QObject, QTranslator, QCoreApplication 14 from PyQt6.QtCore import pyqtSlot, QObject, QTranslator, QCoreApplication
15 from PyQt5.QtWidgets import QAction, QMenu 15 from PyQt6.QtGui import QAction
16 16 from PyQt6.QtWidgets import QMenu
17 from E5Gui.E5Application import e5App 17
18 from EricWidgets.EricApplication import ericApp
18 19
19 import Preferences 20 import Preferences
20 21
21 # Start-Of-Header 22 # Start-Of-Header
22 name = "Selection Encloser Plug-in" 23 name = "Selection Encloser Plug-in"
23 author = "Detlev Offenbach <detlev@die-offenbachs.de>" 24 author = "Detlev Offenbach <detlev@die-offenbachs.de>"
24 autoactivate = True 25 autoactivate = True
25 deactivateable = True 26 deactivateable = True
26 version = "3.2.1" 27 version = "1.0.0"
27 className = "SelectionEncloserPlugin" 28 className = "SelectionEncloserPlugin"
28 packageName = "SelectionEncloser" 29 packageName = "SelectionEncloser"
29 shortDescription = "Enclose the selection with a string." 30 shortDescription = "Enclose the selection with a string."
30 longDescription = ( 31 longDescription = (
31 """This plug-in implements a tool to enclose the selection of""" 32 """This plug-in implements a tool to enclose the selection of"""
44 def createSelectionEncloserPage(configDlg): 45 def createSelectionEncloserPage(configDlg):
45 """ 46 """
46 Module function to create the Selection Encloser configuration page. 47 Module function to create the Selection Encloser configuration page.
47 48
48 @param configDlg reference to the configuration dialog 49 @param configDlg reference to the configuration dialog
50 @type ConfigurationWidget
49 @return reference to the configuration page 51 @return reference to the configuration page
52 @rtype SelectionEncloserPage
50 """ 53 """
51 global selectionEncloserPluginObject 54 global selectionEncloserPluginObject
52 from SelectionEncloser.ConfigurationPage.SelectionEncloserPage import ( 55 from SelectionEncloser.ConfigurationPage.SelectionEncloserPage import (
53 SelectionEncloserPage 56 SelectionEncloserPage
54 ) 57 )
58 def getConfigData(): 61 def getConfigData():
59 """ 62 """
60 Module function returning data as required by the configuration dialog. 63 Module function returning data as required by the configuration dialog.
61 64
62 @return dictionary containing the relevant data 65 @return dictionary containing the relevant data
63 """ 66 @rtype dict
64 try: 67 """
65 usesDarkPalette = e5App().usesDarkPalette() 68 usesDarkPalette = ericApp().usesDarkPalette()
66 except AttributeError:
67 # for eric6 < 20.4
68 from PyQt5.QtGui import QPalette
69 palette = e5App().palette()
70 lightness = palette.color(QPalette.Window).lightness()
71 usesDarkPalette = lightness <= 128
72 iconSuffix = "dark" if usesDarkPalette else "light" 69 iconSuffix = "dark" if usesDarkPalette else "light"
73 70
74 return { 71 return {
75 "selectionEncloserPage": [ 72 "selectionEncloserPage": [
76 QCoreApplication.translate("SelectionEncloserPlugin", 73 QCoreApplication.translate("SelectionEncloserPlugin",
96 93
97 def __init__(self, ui): 94 def __init__(self, ui):
98 """ 95 """
99 Constructor 96 Constructor
100 97
101 @param ui reference to the user interface object (UI.UserInterface) 98 @param ui reference to the user interface object
99 @type UserInterface
102 """ 100 """
103 super().__init__(ui) 101 super().__init__(ui)
104 self.__ui = ui 102 self.__ui = ui
105 103
106 # menu is a list of lists; each list consists of a string for the 104 # menu is a list of lists; each list consists of a string for the
138 136
139 def activate(self): 137 def activate(self):
140 """ 138 """
141 Public method to activate this plugin. 139 Public method to activate this plugin.
142 140
143 @return tuple of None and activation status (boolean) 141 @return tuple of None and activation status
142 @rtype (None, bool)
144 """ 143 """
145 global error 144 global error
146 error = "" # clear previous error 145 error = "" # clear previous error
147 146
148 global selectionEncloserPluginObject 147 global selectionEncloserPluginObject
156 act = menu.addSeparator() 155 act = menu.addSeparator()
157 self.__mainActions.append(act) 156 self.__mainActions.append(act)
158 act = menu.addMenu(self.__menu) 157 act = menu.addMenu(self.__menu)
159 self.__mainActions.append(act) 158 self.__mainActions.append(act)
160 159
161 e5App().getObject("ViewManager").editorOpenedEd.connect( 160 ericApp().getObject("ViewManager").editorOpenedEd.connect(
162 self.__editorOpened) 161 self.__editorOpened)
163 e5App().getObject("ViewManager").editorClosedEd.connect( 162 ericApp().getObject("ViewManager").editorClosedEd.connect(
164 self.__editorClosed) 163 self.__editorClosed)
165 164
166 for editor in e5App().getObject("ViewManager").getOpenEditors(): 165 for editor in ericApp().getObject("ViewManager").getOpenEditors():
167 self.__editorOpened(editor) 166 self.__editorOpened(editor)
168 167
169 return None, True 168 return None, True
170 169
171 def deactivate(self): 170 def deactivate(self):
178 if menu is not None: 177 if menu is not None:
179 for act in self.__mainActions: 178 for act in self.__mainActions:
180 menu.removeAction(act) 179 menu.removeAction(act)
181 self.__mainActions = [] 180 self.__mainActions = []
182 181
183 e5App().getObject("ViewManager").editorOpenedEd.disconnect( 182 ericApp().getObject("ViewManager").editorOpenedEd.disconnect(
184 self.__editorOpened) 183 self.__editorOpened)
185 e5App().getObject("ViewManager").editorClosedEd.disconnect( 184 ericApp().getObject("ViewManager").editorClosedEd.disconnect(
186 self.__editorClosed) 185 self.__editorClosed)
187 186
188 for editor, acts in self.__editors.items(): 187 for editor, acts in self.__editors.items():
189 editor.showMenu.disconnect(self.__editorShowMenu) 188 editor.showMenu.disconnect(self.__editorShowMenu)
190 menu = editor.getMenu("Tools") 189 menu = editor.getMenu("Tools")
205 translation = "selectionencloser_{0}".format(loc) 204 translation = "selectionencloser_{0}".format(loc)
206 translator = QTranslator(None) 205 translator = QTranslator(None)
207 loaded = translator.load(translation, locale_dir) 206 loaded = translator.load(translation, locale_dir)
208 if loaded: 207 if loaded:
209 self.__translator = translator 208 self.__translator = translator
210 e5App().installTranslator(self.__translator) 209 ericApp().installTranslator(self.__translator)
211 else: 210 else:
212 print("Warning: translation file '{0}' could not be" 211 print("Warning: translation file '{0}' could not be"
213 " loaded.".format(translation)) 212 " loaded.".format(translation))
214 print("Using default.") 213 print("Using default.")
215 214
216 def getPreferences(self, key): 215 def getPreferences(self, key):
217 """ 216 """
218 Public method to retrieve the various settings. 217 Public method to retrieve the various settings.
219 218
220 @param key the key of the value to get (string) 219 @param key key of the value to get
221 @return the requested setting 220 @type str
221 @return value of the requested setting
222 @rtype Any
222 """ 223 """
223 if key in ["MenuHierarchy"]: 224 if key in ["MenuHierarchy"]:
224 return json.loads( 225 return json.loads(
225 Preferences.Prefs.settings.value( 226 Preferences.Prefs.settings.value(
226 self.PreferencesKey + "/" + key, self.__defaults[key])) 227 self.PreferencesKey + "/" + key, self.__defaults[key]))
230 231
231 def setPreferences(self, key, value): 232 def setPreferences(self, key, value):
232 """ 233 """
233 Public method to store the various settings. 234 Public method to store the various settings.
234 235
235 @param key the key of the setting to be set (string) 236 @param key key of the setting to be set
236 @param value the value to be set 237 @type str
238 @param value value to be set
239 @type Any
237 """ 240 """
238 if key in ["MenuHierarchy"]: 241 if key in ["MenuHierarchy"]:
239 Preferences.Prefs.settings.setValue( 242 Preferences.Prefs.settings.setValue(
240 self.PreferencesKey + "/" + key, json.dumps(value)) 243 self.PreferencesKey + "/" + key, json.dumps(value))
241 else: 244 else:
252 255
253 def __populateMenu(self, name, menu): 256 def __populateMenu(self, name, menu):
254 """ 257 """
255 Private slot to populate the tools menu with our entry. 258 Private slot to populate the tools menu with our entry.
256 259
257 @param name name of the menu (string) 260 @param name name of the menu
258 @param menu reference to the menu to be populated (QMenu) 261 @type str
262 @param menu reference to the menu to be populated
263 @type QMenu
259 """ 264 """
260 if name not in ["Tools", "PluginTools"]: 265 if name not in ["Tools", "PluginTools"]:
261 return 266 return
262 267
263 editor = e5App().getObject("ViewManager").activeWindow() 268 editor = ericApp().getObject("ViewManager").activeWindow()
264 269
265 if name == "Tools": 270 if name == "Tools":
266 if not menu.isEmpty(): 271 if not menu.isEmpty():
267 menu.addSeparator() 272 menu.addSeparator()
268 act = menu.addMenu(self.__menu) 273 act = menu.addMenu(self.__menu)
273 278
274 def __editorOpened(self, editor): 279 def __editorOpened(self, editor):
275 """ 280 """
276 Private slot called, when a new editor was opened. 281 Private slot called, when a new editor was opened.
277 282
278 @param editor reference to the new editor (QScintilla.Editor) 283 @param editor reference to the new editor
284 @type Editor
279 """ 285 """
280 menu = editor.getMenu("Tools") 286 menu = editor.getMenu("Tools")
281 if menu is not None: 287 if menu is not None:
282 self.__editors[editor] = [] 288 self.__editors[editor] = []
283 if not menu.isEmpty(): 289 if not menu.isEmpty():
290 296
291 def __editorClosed(self, editor): 297 def __editorClosed(self, editor):
292 """ 298 """
293 Private slot called, when an editor was closed. 299 Private slot called, when an editor was closed.
294 300
295 @param editor reference to the editor (QScintilla.Editor) 301 @param editor reference to the editor
302 @type Editor
296 """ 303 """
297 with contextlib.suppress(KeyError): 304 with contextlib.suppress(KeyError):
298 del self.__editors[editor] 305 del self.__editors[editor]
299 if not self.__editors: 306 if not self.__editors:
300 self.__menu.setEnabled(False) 307 self.__menu.setEnabled(False)
302 def __editorShowMenu(self, menuName, menu, editor): 309 def __editorShowMenu(self, menuName, menu, editor):
303 """ 310 """
304 Private slot called, when the the editor context menu or a submenu is 311 Private slot called, when the the editor context menu or a submenu is
305 about to be shown. 312 about to be shown.
306 313
307 @param menuName name of the menu to be shown (string) 314 @param menuName name of the menu to be shown
308 @param menu reference to the menu (QMenu) 315 @type str
316 @param menu reference to the menu
317 @type QMenu
309 @param editor reference to the editor 318 @param editor reference to the editor
319 @type Editor
310 """ 320 """
311 if menuName == "Tools": 321 if menuName == "Tools":
312 if self.__menu.menuAction() not in menu.actions(): 322 if self.__menu.menuAction() not in menu.actions():
313 # Re-add our menu 323 # Re-add our menu
314 self.__editors[editor] = [] 324 self.__editors[editor] = []
333 submenu = QMenu(menuTitle, self.__menu) 343 submenu = QMenu(menuTitle, self.__menu)
334 for title, encString in entries: 344 for title, encString in entries:
335 if title == '--Separator--': 345 if title == '--Separator--':
336 submenu.addSeparator() 346 submenu.addSeparator()
337 else: 347 else:
338 act = submenu.addAction(title, self.__encloseSelection) 348 act = submenu.addAction(title)
339 act.setData(encString) 349 act.setData(encString)
350 submenu.triggered.connect(self.__encloseSelection)
340 self.__menu.addMenu(submenu) 351 self.__menu.addMenu(submenu)
341 352
342 def __encloseSelection(self): 353 @pyqtSlot(QAction)
354 def __encloseSelection(self, act):
343 """ 355 """
344 Private slot to enclose the selection with the selected string. 356 Private slot to enclose the selection with the selected string.
345 """ 357
346 act = self.sender() 358 @param act action that triggered
347 if act is None or not isinstance(act, QAction): 359 @type QAction
348 return 360 """
349 361 if act is None:
350 editor = e5App().getObject("ViewManager").activeWindow() 362 return
363
364 editor = ericApp().getObject("ViewManager").activeWindow()
351 if editor is None: 365 if editor is None:
352 return 366 return
353 367
354 if not editor.hasSelectedText(): 368 if not editor.hasSelectedText():
355 return 369 return
356 370
357 string = act.data() 371 encloseString = act.data()
358 if not string: 372 if not encloseString:
359 return 373 return
360 374
361 if '%s' in string: 375 if '%s' in encloseString:
362 newText = string % editor.selectedText() 376 newText = encloseString % editor.selectedText()
363 elif '{0}' in string: 377 elif '{0}' in encloseString or '{}' in encloseString:
364 newText = string.format(editor.selectedText()) 378 newText = encloseString.format(editor.selectedText())
365 else: 379 else:
366 newText = string + editor.selectedText() + string 380 newText = encloseString + editor.selectedText() + encloseString
367 editor.beginUndoAction() 381 editor.beginUndoAction()
368 editor.replaceSelectedText(newText) 382 editor.replaceSelectedText(newText)
369 editor.endUndoAction() 383 editor.endUndoAction()
370 384
371 # 385 #

eric ide

mercurial