PluginPrintRemover.py

branch
eric7
changeset 62
81f446717433
parent 60
176c0b5b7a61
child 63
273252fd0d99
equal deleted inserted replaced
61:062648cf83d8 62:81f446717433
39 # End-Of-Header 39 # End-Of-Header
40 40
41 error = "" 41 error = ""
42 42
43 printRemoverPluginObject = None 43 printRemoverPluginObject = None
44 44
45 45
46 def createPrintRemoverPage(configDlg): 46 def createPrintRemoverPage(configDlg):
47 """ 47 """
48 Module function to create the Print Remover configuration page. 48 Module function to create the Print Remover configuration page.
49 49
50 @param configDlg reference to the configuration dialog 50 @param configDlg reference to the configuration dialog
51 @type ConfigurationWidget 51 @type ConfigurationWidget
52 @return reference to the configuration page 52 @return reference to the configuration page
53 @rtype PrintRemoverPage 53 @rtype PrintRemoverPage
54 """ 54 """
55 global printRemoverPluginObject 55 global printRemoverPluginObject
56 from PrintRemover.ConfigurationPage.PrintRemoverPage import ( 56 from PrintRemover.ConfigurationPage.PrintRemoverPage import PrintRemoverPage
57 PrintRemoverPage 57
58 )
59 return PrintRemoverPage(printRemoverPluginObject) 58 return PrintRemoverPage(printRemoverPluginObject)
60 59
61 60
62 def getConfigData(): 61 def getConfigData():
63 """ 62 """
64 Module function returning data as required by the configuration dialog. 63 Module function returning data as required by the configuration dialog.
65 64
66 @return dictionary containing the relevant data 65 @return dictionary containing the relevant data
67 @rtype dict 66 @rtype dict
68 """ 67 """
69 usesDarkPalette = ericApp().usesDarkPalette() 68 usesDarkPalette = ericApp().usesDarkPalette()
70 iconSuffix = "dark" if usesDarkPalette else "light" 69 iconSuffix = "dark" if usesDarkPalette else "light"
71 70
72 return { 71 return {
73 "printRemoverPage": [ 72 "printRemoverPage": [
74 QCoreApplication.translate("PrintRemoverPlugin", 73 QCoreApplication.translate("PrintRemoverPlugin", "Print Remover"),
75 "Print Remover"), 74 os.path.join(
76 os.path.join("PrintRemover", "icons", 75 "PrintRemover", "icons", "printRemover-{0}".format(iconSuffix)
77 "printRemover-{0}".format(iconSuffix)), 76 ),
78 createPrintRemoverPage, None, None], 77 createPrintRemoverPage,
78 None,
79 None,
80 ],
79 } 81 }
80 82
81 83
82 def prepareUninstall(): 84 def prepareUninstall():
83 """ 85 """
88 90
89 class PrintRemoverPlugin(QObject): 91 class PrintRemoverPlugin(QObject):
90 """ 92 """
91 Class implementing the Print Remover plugin. 93 Class implementing the Print Remover plugin.
92 """ 94 """
95
93 PreferencesKey = "PrintRemover" 96 PreferencesKey = "PrintRemover"
94 97
95 def __init__(self, ui): 98 def __init__(self, ui):
96 """ 99 """
97 Constructor 100 Constructor
98 101
99 @param ui reference to the user interface object 102 @param ui reference to the user interface object
100 @type UserInterface 103 @type UserInterface
101 """ 104 """
102 super().__init__(ui) 105 super().__init__(ui)
103 self.__ui = ui 106 self.__ui = ui
104 107
105 self.__defaults = { 108 self.__defaults = {
106 "StartswithStrings": [ 109 "StartswithStrings": ["print(", "print ", "console.log"],
107 "print(", "print ", "console.log"],
108 } 110 }
109 111
110 self.__translator = None 112 self.__translator = None
111 self.__loadTranslator() 113 self.__loadTranslator()
112 114
113 self.__initMenu() 115 self.__initMenu()
114 116
115 self.__editors = {} 117 self.__editors = {}
116 self.__mainActions = [] 118 self.__mainActions = []
117 119
118 def activate(self): 120 def activate(self):
119 """ 121 """
120 Public method to activate this plugin. 122 Public method to activate this plugin.
121 123
122 @return tuple of None and activation statu 124 @return tuple of None and activation statu
123 @rtype tuple of (None, bool) 125 @rtype tuple of (None, bool)
124 """ 126 """
125 global error 127 global error
126 error = "" # clear previous error 128 error = "" # clear previous error
127 129
128 global printRemoverPluginObject 130 global printRemoverPluginObject
129 printRemoverPluginObject = self 131 printRemoverPluginObject = self
130 132
131 self.__ui.showMenu.connect(self.__populateMenu) 133 self.__ui.showMenu.connect(self.__populateMenu)
132 134
133 menu = self.__ui.getMenu("plugin_tools") 135 menu = self.__ui.getMenu("plugin_tools")
134 if menu is not None: 136 if menu is not None:
135 if not menu.isEmpty(): 137 if not menu.isEmpty():
136 act = menu.addSeparator() 138 act = menu.addSeparator()
137 self.__mainActions.append(act) 139 self.__mainActions.append(act)
138 act = menu.addMenu(self.__menu) 140 act = menu.addMenu(self.__menu)
139 self.__mainActions.append(act) 141 self.__mainActions.append(act)
140 142
141 ericApp().getObject("ViewManager").editorOpenedEd.connect( 143 ericApp().getObject("ViewManager").editorOpenedEd.connect(self.__editorOpened)
142 self.__editorOpened) 144 ericApp().getObject("ViewManager").editorClosedEd.connect(self.__editorClosed)
143 ericApp().getObject("ViewManager").editorClosedEd.connect( 145
144 self.__editorClosed)
145
146 for editor in ericApp().getObject("ViewManager").getOpenEditors(): 146 for editor in ericApp().getObject("ViewManager").getOpenEditors():
147 self.__editorOpened(editor) 147 self.__editorOpened(editor)
148 148
149 return None, True 149 return None, True
150 150
151 def deactivate(self): 151 def deactivate(self):
152 """ 152 """
153 Public method to deactivate this plugin. 153 Public method to deactivate this plugin.
154 """ 154 """
155 self.__ui.showMenu.disconnect(self.__populateMenu) 155 self.__ui.showMenu.disconnect(self.__populateMenu)
156 156
157 menu = self.__ui.getMenu("plugin_tools") 157 menu = self.__ui.getMenu("plugin_tools")
158 if menu is not None: 158 if menu is not None:
159 for act in self.__mainActions: 159 for act in self.__mainActions:
160 menu.removeAction(act) 160 menu.removeAction(act)
161 self.__mainActions = [] 161 self.__mainActions = []
162 162
163 ericApp().getObject("ViewManager").editorOpenedEd.disconnect( 163 ericApp().getObject("ViewManager").editorOpenedEd.disconnect(
164 self.__editorOpened) 164 self.__editorOpened
165 )
165 ericApp().getObject("ViewManager").editorClosedEd.disconnect( 166 ericApp().getObject("ViewManager").editorClosedEd.disconnect(
166 self.__editorClosed) 167 self.__editorClosed
167 168 )
169
168 for editor, acts in self.__editors.items(): 170 for editor, acts in self.__editors.items():
169 editor.showMenu.disconnect(self.__editorShowMenu) 171 editor.showMenu.disconnect(self.__editorShowMenu)
170 menu = editor.getMenu("Tools") 172 menu = editor.getMenu("Tools")
171 if menu is not None: 173 if menu is not None:
172 for act in acts: 174 for act in acts:
173 menu.removeAction(act) 175 menu.removeAction(act)
174 self.__editors = {} 176 self.__editors = {}
175 177
176 def __loadTranslator(self): 178 def __loadTranslator(self):
177 """ 179 """
178 Private method to load the translation file. 180 Private method to load the translation file.
179 """ 181 """
180 if self.__ui is not None: 182 if self.__ui is not None:
181 loc = self.__ui.getLocale() 183 loc = self.__ui.getLocale()
182 if loc and loc != "C": 184 if loc and loc != "C":
183 locale_dir = os.path.join( 185 locale_dir = os.path.join(
184 os.path.dirname(__file__), "PrintRemover", "i18n") 186 os.path.dirname(__file__), "PrintRemover", "i18n"
187 )
185 translation = "printremover_{0}".format(loc) 188 translation = "printremover_{0}".format(loc)
186 translator = QTranslator(None) 189 translator = QTranslator(None)
187 loaded = translator.load(translation, locale_dir) 190 loaded = translator.load(translation, locale_dir)
188 if loaded: 191 if loaded:
189 self.__translator = translator 192 self.__translator = translator
190 ericApp().installTranslator(self.__translator) 193 ericApp().installTranslator(self.__translator)
191 else: 194 else:
192 print("Warning: translation file '{0}' could not be" 195 print(
193 " loaded.".format(translation)) 196 "Warning: translation file '{0}' could not be"
197 " loaded.".format(translation)
198 )
194 print("Using default.") 199 print("Using default.")
195 200
196 def getPreferences(self, key): 201 def getPreferences(self, key):
197 """ 202 """
198 Public method to retrieve the various settings. 203 Public method to retrieve the various settings.
199 204
200 @param key the key of the value to get 205 @param key the key of the value to get
201 @type str 206 @type str
202 @return value of the requested setting 207 @return value of the requested setting
203 @rtype Any 208 @rtype Any
204 """ 209 """
205 if key in ["StartswithStrings"]: 210 if key in ["StartswithStrings"]:
206 return Preferences.toList( 211 return Preferences.toList(
207 Preferences.Prefs.settings.value( 212 Preferences.Prefs.settings.value(
208 self.PreferencesKey + "/" + key, self.__defaults[key])) 213 self.PreferencesKey + "/" + key, self.__defaults[key]
214 )
215 )
209 else: 216 else:
210 return Preferences.Prefs.settings.value( 217 return Preferences.Prefs.settings.value(
211 self.PreferencesKey + "/" + key, self.__defaults[key]) 218 self.PreferencesKey + "/" + key, self.__defaults[key]
212 219 )
220
213 def setPreferences(self, key, value): 221 def setPreferences(self, key, value):
214 """ 222 """
215 Public method to store the various settings. 223 Public method to store the various settings.
216 224
217 @param key key of the setting to be set 225 @param key key of the setting to be set
218 @type str 226 @type str
219 @param value value to be set 227 @param value value to be set
220 @type Any 228 @type Any
221 """ 229 """
222 Preferences.Prefs.settings.setValue( 230 Preferences.Prefs.settings.setValue(self.PreferencesKey + "/" + key, value)
223 self.PreferencesKey + "/" + key, value) 231
224
225 def __initMenu(self): 232 def __initMenu(self):
226 """ 233 """
227 Private method to initialize the menu. 234 Private method to initialize the menu.
228 """ 235 """
229 self.__menu = QMenu("Remove Outputs") 236 self.__menu = QMenu("Remove Outputs")
230 self.__menu.setEnabled(False) 237 self.__menu.setEnabled(False)
231 self.__menu.aboutToShow.connect(self.__showMenu) 238 self.__menu.aboutToShow.connect(self.__showMenu)
232 self.__menu.triggered.connect(self.__removeLine) 239 self.__menu.triggered.connect(self.__removeLine)
233 240
234 def __populateMenu(self, name, menu): 241 def __populateMenu(self, name, menu):
235 """ 242 """
236 Private slot to populate the tools menu with our entries. 243 Private slot to populate the tools menu with our entries.
237 244
238 @param name name of the menu 245 @param name name of the menu
239 @type str 246 @type str
240 @param menu reference to the menu to be populated 247 @param menu reference to the menu to be populated
241 @type QMenu 248 @type QMenu
242 """ 249 """
243 if name not in ["Tools", "PluginTools"]: 250 if name not in ["Tools", "PluginTools"]:
244 return 251 return
245 252
246 editor = ericApp().getObject("ViewManager").activeWindow() 253 editor = ericApp().getObject("ViewManager").activeWindow()
247 254
248 if name == "Tools": 255 if name == "Tools":
249 if not menu.isEmpty(): 256 if not menu.isEmpty():
250 menu.addSeparator() 257 menu.addSeparator()
251 258
252 act = menu.addMenu(self.__menu) 259 act = menu.addMenu(self.__menu)
253 act.setEnabled(editor is not None) 260 act.setEnabled(editor is not None)
254 elif name == "PluginTools" and self.__mainActions: 261 elif name == "PluginTools" and self.__mainActions:
255 self.__mainActions[-1].setEnabled(editor is not None) 262 self.__mainActions[-1].setEnabled(editor is not None)
256 263
257 def __editorOpened(self, editor): 264 def __editorOpened(self, editor):
258 """ 265 """
259 Private slot called, when a new editor was opened. 266 Private slot called, when a new editor was opened.
260 267
261 @param editor reference to the new editor 268 @param editor reference to the new editor
262 @type Editor 269 @type Editor
263 """ 270 """
264 menu = editor.getMenu("Tools") 271 menu = editor.getMenu("Tools")
265 if menu is not None: 272 if menu is not None:
269 self.__editors[editor].append(act) 276 self.__editors[editor].append(act)
270 act = menu.addMenu(self.__menu) 277 act = menu.addMenu(self.__menu)
271 self.__menu.setEnabled(True) 278 self.__menu.setEnabled(True)
272 self.__editors[editor].append(act) 279 self.__editors[editor].append(act)
273 editor.showMenu.connect(self.__editorShowMenu) 280 editor.showMenu.connect(self.__editorShowMenu)
274 281
275 def __editorClosed(self, editor): 282 def __editorClosed(self, editor):
276 """ 283 """
277 Private slot called, when an editor was closed. 284 Private slot called, when an editor was closed.
278 285
279 @param editor reference to the editor 286 @param editor reference to the editor
280 @type Editor 287 @type Editor
281 """ 288 """
282 with contextlib.suppress(KeyError): 289 with contextlib.suppress(KeyError):
283 del self.__editors[editor] 290 del self.__editors[editor]
284 if not self.__editors: 291 if not self.__editors:
285 self.__menu.setEnabled(False) 292 self.__menu.setEnabled(False)
286 293
287 def __editorShowMenu(self, menuName, menu, editor): 294 def __editorShowMenu(self, menuName, menu, editor):
288 """ 295 """
289 Private slot called, when the the editor context menu or a submenu is 296 Private slot called, when the the editor context menu or a submenu is
290 about to be shown. 297 about to be shown.
291 298
292 @param menuName name of the menu to be shown 299 @param menuName name of the menu to be shown
293 @type str 300 @type str
294 @param menu reference to the menu 301 @param menu reference to the menu
295 @type QMenu 302 @type QMenu
296 @param editor reference to the editor 303 @param editor reference to the editor
297 @type Editor 304 @type Editor
298 """ 305 """
299 if ( 306 if menuName == "Tools" and self.__menu.menuAction() not in menu.actions():
300 menuName == "Tools" and
301 self.__menu.menuAction() not in menu.actions()
302 ):
303 # Re-add our menu 307 # Re-add our menu
304 self.__editors[editor] = [] 308 self.__editors[editor] = []
305 if not menu.isEmpty(): 309 if not menu.isEmpty():
306 act = menu.addSeparator() 310 act = menu.addSeparator()
307 self.__editors[editor].append(act) 311 self.__editors[editor].append(act)
308 act = menu.addMenu(self.__menu) 312 act = menu.addMenu(self.__menu)
309 self.__editors[editor].append(act) 313 self.__editors[editor].append(act)
310 314
311 def __showMenu(self): 315 def __showMenu(self):
312 """ 316 """
313 Private slot to build the menu hierarchy. 317 Private slot to build the menu hierarchy.
314 """ 318 """
315 self.__menu.clear() 319 self.__menu.clear()
316 for startString in self.getPreferences("StartswithStrings"): 320 for startString in self.getPreferences("StartswithStrings"):
317 if startString == '--Separator--': 321 if startString == "--Separator--":
318 self.__menu.addSeparator() 322 self.__menu.addSeparator()
319 else: 323 else:
320 act = self.__menu.addAction( 324 act = self.__menu.addAction(self.tr("Remove '{0}'").format(startString))
321 self.tr("Remove '{0}'").format(startString))
322 act.setData(startString) 325 act.setData(startString)
323 326
324 @pyqtSlot(QAction) 327 @pyqtSlot(QAction)
325 def __removeLine(self, act): 328 def __removeLine(self, act):
326 """ 329 """
327 Private slot to remove lines starting with the selected pattern. 330 Private slot to remove lines starting with the selected pattern.
328 331
329 @param act reference to the action that was triggered 332 @param act reference to the action that was triggered
330 @type QAction 333 @type QAction
331 """ 334 """
332 if act is None: 335 if act is None:
333 return 336 return
334 337
335 editor = ericApp().getObject("ViewManager").activeWindow() 338 editor = ericApp().getObject("ViewManager").activeWindow()
336 if editor is None: 339 if editor is None:
337 return 340 return
338 341
339 pattern = act.data() 342 pattern = act.data()
340 if not pattern: 343 if not pattern:
341 return 344 return
342 345
343 text = editor.text() 346 text = editor.text()
344 newText = "".join([ 347 newText = "".join(
345 line for line in text.splitlines(True) 348 [
346 if not line.lstrip().startswith(pattern) or 349 line
347 "__NO_REMOVE__" in line 350 for line in text.splitlines(True)
348 ]) 351 if not line.lstrip().startswith(pattern) or "__NO_REMOVE__" in line
352 ]
353 )
349 if newText != text: 354 if newText != text:
350 editor.beginUndoAction() 355 editor.beginUndoAction()
351 editor.selectAll() 356 editor.selectAll()
352 editor.replaceSelectedText(newText) 357 editor.replaceSelectedText(newText)
353 editor.endUndoAction() 358 editor.endUndoAction()
354 359
360
355 # 361 #
356 # eflag: noqa = M801 362 # eflag: noqa = M801

eric ide

mercurial