WebBrowser/GreaseMonkey/GreaseMonkeyManager.py

branch
QtWebEngine
changeset 4766
5f8d08aa2217
parent 4763
8ad353f31184
child 4767
0bace7c5ebc9
equal deleted inserted replaced
4763:8ad353f31184 4766:5f8d08aa2217
15 QUrl, QByteArray 15 QUrl, QByteArray
16 from PyQt5.QtNetwork import QNetworkAccessManager 16 from PyQt5.QtNetwork import QNetworkAccessManager
17 17
18 import Utilities 18 import Utilities
19 import Preferences 19 import Preferences
20
21 from WebBrowser.WebBrowserWindow import WebBrowserWindow
22 from .GreaseMonkeyUrlInterceptor import GreaseMonkeyUrlInterceptor
20 23
21 24
22 class GreaseMonkeyManager(QObject): 25 class GreaseMonkeyManager(QObject):
23 """ 26 """
24 Class implementing the manager for GreaseMonkey scripts. 27 Class implementing the manager for GreaseMonkey scripts.
32 @param parent reference to the parent object (QObject) 35 @param parent reference to the parent object (QObject)
33 """ 36 """
34 super(GreaseMonkeyManager, self).__init__(parent) 37 super(GreaseMonkeyManager, self).__init__(parent)
35 38
36 self.__disabledScripts = [] 39 self.__disabledScripts = []
37 self.__endScripts = [] 40 self.__scripts = []
38 self.__startScripts = []
39 self.__downloaders = [] 41 self.__downloaders = []
40 42
43 self.__interceptor = GreaseMonkeyUrlInterceptor(self)
44 WebBrowserWindow.networkManager().installUrlInterceptor(
45 self.__interceptor)
46
41 QTimer.singleShot(0, self.__load) 47 QTimer.singleShot(0, self.__load)
42 ## , m_interceptor(new GM_UrlInterceptor(this)) 48
43 ##{ 49 def __del__(self):
44 ## mApp->networkManager()->installUrlInterceptor(m_interceptor); 50 """
45 ## 51 Special method called during object destruction.
46 ## QTimer::singleShot(0, this, SLOT(load())); 52 """
47 ##} 53 WebBrowserWindow.networkManager().removeUrlInterceptor(
48 ## 54 self.__interceptor)
49 ##GM_Manager::~GM_Manager()
50 ##{
51 ## mApp->networkManager()->removeUrlInterceptor(m_interceptor);
52 ##}
53 55
54 def showConfigurationDialog(self, parent=None): 56 def showConfigurationDialog(self, parent=None):
55 """ 57 """
56 Public method to show the configuration dialog. 58 Public method to show the configuration dialog.
57 59
141 """ 143 """
142 Public method to get a list of all scripts. 144 Public method to get a list of all scripts.
143 145
144 @return list of all scripts (list of GreaseMonkeyScript) 146 @return list of all scripts (list of GreaseMonkeyScript)
145 """ 147 """
146 return self.__startScripts[:] + self.__endScripts[:] 148 return self.__scripts[:]
147 149
148 def containsScript(self, fullName): 150 def containsScript(self, fullName):
149 """ 151 """
150 Public method to check, if the given script exists. 152 Public method to check, if the given script exists.
151 153
152 @param fullName full name of the script (string) 154 @param fullName full name of the script (string)
153 @return flag indicating the existence (boolean) 155 @return flag indicating the existence (boolean)
154 """ 156 """
155 for script in self.__startScripts: 157 for script in self.__scripts:
156 if script.fullName() == fullName: 158 if script.fullName() == fullName:
157 return True 159 return True
158 for script in self.__endScripts: 160
159 if script.fullName() == fullName:
160 return True
161 return False 161 return False
162 162
163 def enableScript(self, script): 163 def enableScript(self, script):
164 """ 164 """
165 Public method to enable the given script. 165 Public method to enable the given script.
168 """ 168 """
169 script.setEnabled(True) 169 script.setEnabled(True)
170 fullName = script.fullName() 170 fullName = script.fullName()
171 if fullName in self.__disabledScripts: 171 if fullName in self.__disabledScripts:
172 self.__disabledScripts.remove(fullName) 172 self.__disabledScripts.remove(fullName)
173 ##void GM_Manager::enableScript(GM_Script* script) 173
174 ##{ 174 collection = WebBrowserWindow.webProfile().scripts()
175 ## script->setEnabled(true); 175 collection.insert(script.webScript())
176 ## m_disabledScripts.removeOne(script->fullName());
177 ##
178 ## QWebEngineScriptCollection *collection = mApp->webProfile()->scripts();
179 ## collection->insert(script->webScript());
180 ##}
181 176
182 def disableScript(self, script): 177 def disableScript(self, script):
183 """ 178 """
184 Public method to disable the given script. 179 Public method to disable the given script.
185 180
187 """ 182 """
188 script.setEnabled(False) 183 script.setEnabled(False)
189 fullName = script.fullName() 184 fullName = script.fullName()
190 if fullName not in self.__disabledScripts: 185 if fullName not in self.__disabledScripts:
191 self.__disabledScripts.append(fullName) 186 self.__disabledScripts.append(fullName)
192 ##void GM_Manager::disableScript(GM_Script* script) 187
193 ##{ 188 collection = WebBrowserWindow.webProfile().scripts()
194 ## script->setEnabled(false); 189 collection.remove(collection.findScript(fullName))
195 ## m_disabledScripts.append(script->fullName());
196 ##
197 ## QWebEngineScriptCollection *collection = mApp->webProfile()->scripts();
198 ## collection->remove(collection->findScript(script->fullName()));
199 190
200 def addScript(self, script): 191 def addScript(self, script):
201 """ 192 """
202 Public method to add a script. 193 Public method to add a script.
203 194
204 @param script script to be added (GreaseMonkeyScript) 195 @param script script to be added (GreaseMonkeyScript)
205 @return flag indicating success (boolean) 196 @return flag indicating success (boolean)
206 """ 197 """
198 if not script or not script.isValid():
199 return False
200
201 self.__scripts.append(script)
202 script.scriptChanged.connect(self.__scriptChanged)
203
204 collection = WebBrowserWindow.webProfile().scripts()
205 collection.insert(script.webScript())
206
207 self.scriptsChanged.emit()
208 return True
209
210 def removeScript(self, script, removeFile=True):
211 """
212 Public method to remove a script.
213
214 @param script script to be removed (GreaseMonkeyScript)
215 @param removeFile flag indicating to remove the script file as well
216 (bool)
217 @return flag indicating success (boolean)
218 """
207 if not script: 219 if not script:
208 return False 220 return False
209 221
210 from .GreaseMonkeyScript import GreaseMonkeyScript 222 try:
211 if script.startAt() == GreaseMonkeyScript.DocumentStart: 223 self.__scripts.remove(script)
212 self.__startScripts.append(script) 224 except ValueError:
213 else: 225 pass
214 self.__endScripts.append(script) 226
227 fullName = script.fullName()
228 collection = WebBrowserWindow.webProfile().scripts()
229 collection.remove(collection.findScript(fullName))
230
231 if fullName in self.__disabledScripts:
232 self.__disabledScripts.remove(fullName)
233
234 if removeFile:
235 QFile.remove(script.fileName())
236 del script
215 237
216 self.scriptsChanged.emit() 238 self.scriptsChanged.emit()
217 return True 239 return True
218 ##bool GM_Manager::addScript(GM_Script* script)
219 ##{
220 ## if (!script || !script->isValid()) {
221 ## return false;
222 ## }
223 ##
224 ## m_scripts.append(script);
225 ## connect(script, &GM_Script::scriptChanged, this, &GM_Manager::scriptChanged);
226 ##
227 ## QWebEngineScriptCollection *collection = mApp->webProfile()->scripts();
228 ## collection->insert(script->webScript());
229 ##
230 ## emit scriptsChanged();
231 ## return true;
232 ##}
233
234 def removeScript(self, script):
235 """
236 Public method to remove a script.
237
238 @param script script to be removed (GreaseMonkeyScript)
239 @return flag indicating success (boolean)
240 """
241 if not script:
242 return False
243
244 from .GreaseMonkeyScript import GreaseMonkeyScript
245 if script.startAt() == GreaseMonkeyScript.DocumentStart:
246 try:
247 self.__startScripts.remove(script)
248 except ValueError:
249 pass
250 else:
251 try:
252 self.__endScripts.remove(script)
253 except ValueError:
254 pass
255
256 fullName = script.fullName()
257 if fullName in self.__disabledScripts:
258 self.__disabledScripts.remove(fullName)
259 QFile.remove(script.fileName())
260
261 self.scriptsChanged.emit()
262 return True
263 ##bool GM_Manager::removeScript(GM_Script* script, bool removeFile)
264 ##{
265 ## if (!script) {
266 ## return false;
267 ## }
268 ##
269 ## m_scripts.removeOne(script);
270 ##
271 ## QWebEngineScriptCollection *collection = mApp->webProfile()->scripts();
272 ## collection->remove(collection->findScript(script->fullName()));
273 ##
274 ## m_disabledScripts.removeOne(script->fullName());
275 ##
276 ## if (removeFile) {
277 ## QFile::remove(script->fileName());
278 ## delete script;
279 ## }
280 ##
281 ## emit scriptsChanged();
282 ## return true;
283 ##}
284 240
285 def canRunOnScheme(self, scheme): 241 def canRunOnScheme(self, scheme):
286 """ 242 """
287 Public method to check, if scripts can be run on a scheme. 243 Public method to check, if scripts can be run on a scheme.
288 244
289 @param scheme scheme to check (string) 245 @param scheme scheme to check (string)
290 @return flag indicating, that scripts can be run (boolean) 246 @return flag indicating, that scripts can be run (boolean)
291 """ 247 """
292 return scheme in ["http", "https", "data", "ftp"] 248 return scheme in ["http", "https", "data", "ftp"]
293
294 ## def pageLoadStarted(self):
295 ## """
296 ## Public slot to handle the start of loading a page.
297 ## """
298 ## frame = self.sender()
299 ## if not frame:
300 ## return
301 ##
302 ## urlScheme = frame.url().scheme()
303 ## urlString = bytes(frame.url().toEncoded()).decode()
304 ##
305 ## if not self.canRunOnScheme(urlScheme):
306 ## return
307 ##
308 ## from .GreaseMonkeyJavaScript import bootstrap_js
309 ## for script in self.__startScripts:
310 ## if script.match(urlString):
311 ## frame.evaluateJavaScript(bootstrap_js + script.script())
312 ##
313 ## for script in self.__endScripts:
314 ## if script.match(urlString):
315 ## javascript = 'window.addEventListener("DOMContentLoaded",' \
316 ## 'function(e) {{ {0} }}, false);'.format(
317 ## bootstrap_js + script.script())
318 ## frame.evaluateJavaScript(javascript)
319 249
320 def __load(self): 250 def __load(self):
321 """ 251 """
322 Private slot to load the available scripts into the manager. 252 Private slot to load the available scripts into the manager.
323 """ 253 """
327 257
328 if not scriptsDir.exists("requires"): 258 if not scriptsDir.exists("requires"):
329 scriptsDir.mkdir("requires") 259 scriptsDir.mkdir("requires")
330 260
331 self.__disabledScripts = \ 261 self.__disabledScripts = \
332 Preferences.getHelp("GreaseMonkeyDisabledScripts") 262 Preferences.getWebBrowser("GreaseMonkeyDisabledScripts")
333 263
334 from .GreaseMonkeyScript import GreaseMonkeyScript 264 from .GreaseMonkeyScript import GreaseMonkeyScript
335 for fileName in scriptsDir.entryList(["*.js"], QDir.Files): 265 for fileName in scriptsDir.entryList(["*.js"], QDir.Files):
336 absolutePath = scriptsDir.absoluteFilePath(fileName) 266 absolutePath = scriptsDir.absoluteFilePath(fileName)
337 script = GreaseMonkeyScript(self, absolutePath) 267 script = GreaseMonkeyScript(self, absolutePath)
338 268
269 if not script.isValid():
270 del script
271 continue
272
273 self.__scripts.append(script)
274
339 if script.fullName() in self.__disabledScripts: 275 if script.fullName() in self.__disabledScripts:
340 script.setEnabled(False) 276 script.setEnabled(False)
341
342 if script.startAt() == GreaseMonkeyScript.DocumentStart:
343 self.__startScripts.append(script)
344 else: 277 else:
345 self.__endScripts.append(script) 278 collection = WebBrowserWindow.webProfile().scripts()
346 ##void GM_Manager::load() 279 collection.insert(script.webScript())
347 ##{
348 ## QDir gmDir(m_settingsPath + QL1S("/greasemonkey"));
349 ## if (!gmDir.exists()) {
350 ## gmDir.mkdir(m_settingsPath + QL1S("/greasemonkey"));
351 ## }
352 ##
353 ## if (!gmDir.exists("requires")) {
354 ## gmDir.mkdir("requires");
355 ## }
356 ##
357 ## m_bootstrapScript = QzTools::readAllFileContents(":gm/data/bootstrap.min.js");
358 ## m_valuesScript = QzTools::readAllFileContents(":gm/data/values.min.js");
359 ##
360 ## QSettings settings(m_settingsPath + QL1S("/extensions.ini"), QSettings::IniFormat);
361 ## settings.beginGroup("GreaseMonkey");
362 ## m_disabledScripts = settings.value("disabledScripts", QStringList()).toStringList();
363 ##
364 ## foreach (const QString &fileName, gmDir.entryList(QStringList("*.js"), QDir::Files)) {
365 ## const QString absolutePath = gmDir.absoluteFilePath(fileName);
366 ## GM_Script* script = new GM_Script(this, absolutePath);
367 ##
368 ## if (!script->isValid()) {
369 ## delete script;
370 ## continue;
371 ## }
372 ##
373 ## m_scripts.append(script);
374 ##
375 ## if (m_disabledScripts.contains(script->fullName())) {
376 ## script->setEnabled(false);
377 ## }
378 ## else {
379 ## mApp->webProfile()->scripts()->insert(script->webScript());
380 ## }
381 ## }
382 ##}
383 280
384 def __scriptChanged(self): 281 def __scriptChanged(self):
385 """ 282 """
386 Private slot handling a changed script. 283 Private slot handling a changed script.
387 """ 284 """
388 ##void GM_Manager::scriptChanged() 285 script = self.sender()
389 ##{ 286 if not script:
390 ## GM_Script *script = qobject_cast<GM_Script*>(sender()); 287 return
391 ## if (!script) 288
392 ## return; 289 fullName = script.fullName()
393 ## 290 collection = WebBrowserWindow.webProfile().scripts()
394 ## QWebEngineScriptCollection *collection = mApp->webProfile()->scripts(); 291 collection.remove(collection.findScript(fullName))
395 ## collection->remove(collection->findScript(script->fullName())); 292 collection.insert(script.webScript())
396 ## collection->insert(script->webScript());
397 ##}
398
399 ## def connectPage(self, page):
400 ## """
401 ## Public method to allow the GreaseMonkey manager to connect to the page.
402 ##
403 ## @param page reference to the web page (HelpWebPage)
404 ## """
405 ## page.mainFrame().javaScriptWindowObjectCleared.connect(
406 ## self.pageLoadStarted)
407 ##
408 ## def createRequest(self, op, request, outgoingData=None):
409 ## """
410 ## Public method to create a request.
411 ##
412 ## @param op the operation to be performed
413 ## (QNetworkAccessManager.Operation)
414 ## @param request reference to the request object (QNetworkRequest)
415 ## @param outgoingData reference to an IODevice containing data to be sent
416 ## (QIODevice)
417 ## @return reference to the created reply object (QNetworkReply)
418 ## """
419 ## if op == QNetworkAccessManager.GetOperation and \
420 ## request.rawHeader(b"X-Eric6-UserLoadAction") == QByteArray(b"1"):
421 ## urlString = request.url().toString(
422 ## QUrl.RemoveFragment | QUrl.RemoveQuery)
423 ## if urlString.endswith(".user.js"):
424 ## self.downloadScript(request)
425 ## from Helpviewer.Network.EmptyNetworkReply import \
426 ## EmptyNetworkReply
427 ## return EmptyNetworkReply(self)
428 ##
429 ## return None

eric ide

mercurial