def showDateNoWaitDetails(self, data): QWebSettings.clearMemoryCaches() QWebSettings.clearIconDatabase() ViewGenerator.generate_css(data, self.app) ViewGenerator.generate_html(data) self.reload()
def init(): """Initialize the global QWebSettings.""" cache_path = standarddir.cache() data_path = standarddir.data() if config.get('general', 'private-browsing') or cache_path is None: QWebSettings.setIconDatabasePath('') else: QWebSettings.setIconDatabasePath(cache_path) if cache_path is not None: QWebSettings.setOfflineWebApplicationCachePath( os.path.join(cache_path, 'application-cache')) if data_path is not None: QWebSettings.globalSettings().setLocalStoragePath( os.path.join(data_path, 'local-storage')) QWebSettings.setOfflineStoragePath( os.path.join(data_path, 'offline-storage')) for sectname, section in MAPPINGS.items(): for optname, mapping in section.items(): default = mapping.save_default() log.config.vdebug("Saved default for {} -> {}: {!r}".format( sectname, optname, default)) value = config.get(sectname, optname) log.config.vdebug("Setting {} -> {} to {!r}".format( sectname, optname, value)) mapping.set(value) objreg.get('config').changed.connect(update_settings)
def __init__(self): self.debug = 1 self.app = QApplication([]) self.desktop = QApplication.desktop() self.web = QWebView() self.icon = QIcon(ICON) QWebSettings.setIconDatabasePath(DATA_DIR)
def __init__(self): super(WebRender, self).__init__() vbox = QVBoxLayout(self) #Web Frame self.webFrame = QWebView() QWebSettings.globalSettings().setAttribute( QWebSettings.DeveloperExtrasEnabled, True) vbox.addWidget(self.webFrame)
def showData(self, data): QWebSettings.clearMemoryCaches() QWebSettings.clearIconDatabase() ViewGenerator.generate_document_view(data, self.app) time.sleep(2) self.load(QtCore.QUrl('file:///'+os.getcwd()+"/generated_html/document_view.html"))
def update_settings(section, option): """Update global settings when qwebsettings changed.""" cache_path = standarddir.cache() if (section, option) == ('general', 'private-browsing'): if config.get('general', 'private-browsing') or cache_path is None: QWebSettings.setIconDatabasePath('') else: QWebSettings.setIconDatabasePath(cache_path) websettings.update_mappings(MAPPINGS, section, option)
def showDataNoGeneration(self, data): QWebSettings.clearMemoryCaches() QWebSettings.clearIconDatabase() ViewGenerator.generate_css(data, self.app) ViewGenerator.generate_html(data) time.sleep(2) self.load(QtCore.QUrl('file:///'+os.getcwd()+"/generated_html/index.html"))
def initUI(self): self.setMinimumSize(300, 300) # self.TextEdit = QtWidgets.QTextEdit(self) # self.TextEdit.setMinimumSize(300, 300) # self.TextEdit.setReadOnly(True) # self.load(QtCore.QUrl('file:///'+os.getcwd()+"/generated_html/index.html")) QWebSettings.setMaximumPagesInCache(0) QWebSettings.setObjectCacheCapacities(0, 0, 0)
def __init__(self): self.debug=1 self.app = QApplication(sys.argv) self.desktop= QApplication.desktop() self.web = QWebView() self.icon = QIcon(ICON) QWebSettings.setIconDatabasePath(DATA_DIR) self.web.setWindowIcon(self.icon) self.web.titleChanged.connect(self.title_changed) self.web.iconChanged.connect(self.icon_changed) self.web.page().windowCloseRequested.connect(self.close_window) self.web.page().geometryChangeRequested.connect(self.set_geometry)
def update_settings(section, option): """Update global settings when qwebsettings changed.""" if (section, option) == ('general', 'private-browsing'): cache_path = standarddir.cache() if config.get('general', 'private-browsing') or cache_path is None: QWebSettings.setIconDatabasePath('') else: QWebSettings.setIconDatabasePath(cache_path) elif section == 'ui' and option in ['hide-scrollbar', 'user-stylesheet']: _set_user_stylesheet() websettings.update_mappings(MAPPINGS, section, option)
def _shutdown(self, status): """Second stage of shutdown.""" log.destroy.debug("Stage 2 of shutting down...") if qApp is None: # No QApplication exists yet, so quit hard. sys.exit(status) # Remove eventfilter try: log.destroy.debug("Removing eventfilter...") qApp.removeEventFilter(objreg.get('event-filter')) except AttributeError: pass # Close all windows QApplication.closeAllWindows() # Shut down IPC try: objreg.get('ipc-server').shutdown() except KeyError: pass # Save everything try: save_manager = objreg.get('save-manager') except KeyError: log.destroy.debug("Save manager not initialized yet, so not " "saving anything.") else: for key in save_manager.saveables: try: save_manager.save(key, is_exit=True) except OSError as e: error.handle_fatal_exc( e, self._args, "Error while saving!", pre_text="Error while saving {}".format(key)) # Disable favicons so removing tempdir will work QWebSettings.setIconDatabasePath("") # Re-enable faulthandler to stdout, then remove crash log log.destroy.debug("Deactivating crash log...") objreg.get('crash-handler').destroy_crashlogfile() # Delete temp basedir if self._args.temp_basedir: atexit.register(shutil.rmtree, self._args.basedir) # If we don't kill our custom handler here we might get segfaults log.destroy.debug("Deactivating message handler...") qInstallMessageHandler(None) # Now we can hopefully quit without segfaults log.destroy.debug("Deferring QApplication::exit...") objreg.get('signal-handler').deactivate() # We use a singleshot timer to exit here to minimize the likelihood of # segfaults. QTimer.singleShot(0, functools.partial(qApp.exit, status))
def update_settings(section, option): """Update global settings when qwebsettings changed.""" if (section, option) == ('general', 'private-browsing'): if config.get('general', 'private-browsing'): QWebSettings.setIconDatabasePath('') else: QWebSettings.setIconDatabasePath(standarddir.cache()) else: try: mapping = MAPPINGS[section][option] except KeyError: return value = config.get(section, option) mapping.set(value)
def enable_caret_browsing(qapp): """Fixture to enable caret browsing globally.""" settings = QWebSettings.globalSettings() old_value = settings.testAttribute(QWebSettings.CaretBrowsingEnabled) settings.setAttribute(QWebSettings.CaretBrowsingEnabled, True) yield settings.setAttribute(QWebSettings.CaretBrowsingEnabled, old_value)
def _check_prerequisites(self, win_id): """Check if the command is permitted to run currently. Args: win_id: The window ID the command is run in. """ mode_manager = objreg.get('mode-manager', scope='window', window=win_id) curmode = mode_manager.mode if self._modes is not None and curmode not in self._modes: mode_names = '/'.join(mode.name for mode in self._modes) raise cmdexc.PrerequisitesError( "{}: This command is only allowed in {} mode.".format( self.name, mode_names)) elif self._not_modes is not None and curmode in self._not_modes: mode_names = '/'.join(mode.name for mode in self._not_modes) raise cmdexc.PrerequisitesError( "{}: This command is not allowed in {} mode.".format( self.name, mode_names)) if self._needs_js and not QWebSettings.globalSettings().testAttribute( QWebSettings.JavascriptEnabled): raise cmdexc.PrerequisitesError( "{}: This command needs javascript enabled.".format(self.name)) if self.deprecated: message.warning(win_id, '{} is deprecated - {}'.format( self.name, self.deprecated))
def follow_selected(self, *, tab=False): if not self.has_selection(): return if QWebSettings.globalSettings().testAttribute( QWebSettings.JavascriptEnabled): if tab: self._tab.data.override_target = usertypes.ClickTarget.tab self._tab.run_js_async( 'window.getSelection().anchorNode.parentNode.click()') else: selection = self.selection(html=True) try: selected_element = xml.etree.ElementTree.fromstring( '<html>{}</html>'.format(selection)).find('a') except xml.etree.ElementTree.ParseError: raise browsertab.WebTabError('Could not parse selected ' 'element!') if selected_element is not None: try: url = selected_element.attrib['href'] except KeyError: raise browsertab.WebTabError('Anchor element without ' 'href!') url = self._tab.url().resolved(QUrl(url)) if tab: self._tab.new_tab_requested.emit(url) else: self._tab.openurl(url)
def addFeed(self, urlString, title, icon): """ Public method to add a feed. @param urlString URL of the feed (string) @param title title of the feed (string) @param icon icon for the feed (QIcon) @return flag indicating a successful addition of the feed (boolean) """ if urlString == "": return False if not self.__loaded: self.__load() # step 1: check, if feed was already added for feed in self.__feeds: if feed[0] == urlString: return False # step 2: add the feed if icon.isNull() or \ icon == QIcon(QWebSettings.webGraphic( QWebSettings.DefaultFrameIconGraphic)): icon = UI.PixmapCache.getIcon("rss16.png") feed = (urlString, title, icon) self.__feeds.append(feed) self.__addFeedItem(feed) self.__save() return True
def __init__(self, url): QMainWindow.__init__(self) self.setupUi(self) # Enable plugins QWebSettings.globalSettings().setAttribute(QWebSettings.PluginsEnabled, True) # UI: connect signals to slots self.pushButton_Back.clicked.connect(self.on_pushButton_Back_clicked) self.pushButton_Forward.clicked.connect(self.on_pushButton_Forward_clicked) self.pushButton_Go.clicked.connect(self.on_pushButton_Go_clicked) self.lineEdit_AddressBar.returnPressed.connect(self.on_pushButton_Go_clicked) self.webView.titleChanged.connect(self.onTitleChanged) self.webView.loadFinished.connect(self.onLoadingNewPage) self.webView.load(url)
def _click_js(self, click_target): settings = QWebSettings.globalSettings() attribute = QWebSettings.JavascriptCanOpenWindows could_open_windows = settings.testAttribute(attribute) settings.setAttribute(attribute, True) ok = self._elem.evaluateJavaScript('this.click(); true;') settings.setAttribute(attribute, could_open_windows) if not ok: log.webelem.debug("Failed to click via JS, falling back to event") self._click_fake_event(click_target)
def init(): """Initialize the global QWebSettings.""" cache_path = standarddir.cache() data_path = standarddir.data() if config.get('general', 'private-browsing') or cache_path is None: QWebSettings.setIconDatabasePath('') else: QWebSettings.setIconDatabasePath(cache_path) if cache_path is not None: QWebSettings.setOfflineWebApplicationCachePath( os.path.join(cache_path, 'application-cache')) if data_path is not None: QWebSettings.globalSettings().setLocalStoragePath( os.path.join(data_path, 'local-storage')) QWebSettings.setOfflineStoragePath( os.path.join(data_path, 'offline-storage')) websettings.init_mappings(MAPPINGS) objreg.get('config').changed.connect(update_settings)
def _update_settings(option): """Update global settings when qwebsettings changed.""" global_settings.update_setting(option) settings = QWebSettings.globalSettings() if option in ['scrollbar.hide', 'content.user_stylesheets']: _set_user_stylesheet(settings) elif option == 'content.cookies.accept': _set_cookie_accept_policy(settings) elif option == 'content.cache.maximum_pages': _set_cache_maximum_pages(settings)
def _get_qws(self, qws): """Get the QWebSettings object to use. Args: qws: The QWebSettings instance to use, or None to use the global instance. """ if qws is None: return QWebSettings.globalSettings() else: return qws
def prepare(self, metaData): """ Public method to prepare the disk cache file. @param metaData meta data for a URL (QNetworkCacheMetaData) @return reference to the IO device (QIODevice) """ if QWebSettings.globalSettings().testAttribute( QWebSettings.PrivateBrowsingEnabled): return None return QNetworkDiskCache.prepare(self, metaData)
def __init__(self): # Explaining super is out of the scope of this article # So please google it if you're not familar with it # Simple reason why we use it here is that it allows us to # access variables, methods etc in the design.py file super(self.__class__, self).__init__() self.setupUi(self) # This is defined in ui file automatically self.fillPassword() self.conn = sqlite3.connect("nooto.db") self.conn.row_factory = sqlite3.Row self.curs = self.conn.cursor() self.curs.execute("SELECT id,title,parent FROM Note") titles = self.curs.fetchall() self.id2objmap = {} # sort by parent value titles = sorted(titles, key=lambda parent: parent["parent"]) for row in titles: if row["parent"] == None: title = self.decrypt(row["title"]) item = QTreeWidgetItem(self.treeWidget) item.setText(0, title) item.setText(1, str(row["id"])) self.id2objmap[row["id"]] = {"title": title, "parent": None, "object": item} else: title = self.decrypt(row["title"]) parent = row["parent"] item = QTreeWidgetItem(self.id2objmap[parent]["object"]) item.setText(0, title) item.setText(1, str(row["id"])) item.setText(2, str(parent)) self.id2objmap[row["id"]] = {"title": title, "parent": parent, "object": item} self.treeWidget.setContextMenuPolicy(Qt.CustomContextMenu) self.treeWidget.customContextMenuRequested.connect(self.openContextMenu) self.treeWidget.setHeaderLabel("Note Title") self.treeWidget.setColumnCount(1) self.treeWidget.expandAll() settings = QWebSettings.globalSettings() settings.setAttribute(QWebSettings.JavascriptCanAccessClipboard, True) settings.setAttribute(QWebSettings.PluginsEnabled, True) url = QUrl("file://" + os.getcwd() + "/index.html") # url = QUrl('http://www.tinymce.com/tryit/full.php') self.webView.setUrl(url) # self.webView.page().setContentEditable(True) self.webView.page().mainFrame().addToJavaScriptWindowObject("pyObj", self) self.treeWidget.itemClicked.connect(self.getTreeItemText)
def _set_global_render_settings(js_disable_cross_domain_access, private_mode): from PyQt5.QtWebKit import QWebSecurityOrigin, QWebSettings if js_disable_cross_domain_access is False: # In order to enable cross domain requests it is necessary to add # the http and https to the local scheme, this way all the urls are # seen as inside the same security origin. for scheme in ['http', 'https']: QWebSecurityOrigin.addLocalScheme(scheme) settings = QWebSettings.globalSettings() settings.setAttribute(QWebSettings.PrivateBrowsingEnabled, private_mode) settings.setAttribute(QWebSettings.LocalStorageEnabled, not private_mode)
def init(): """Initialize the global QWebSettings.""" cachedir = standarddir.get(QStandardPaths.CacheLocation) QWebSettings.setIconDatabasePath(cachedir) QWebSettings.setOfflineWebApplicationCachePath( os.path.join(cachedir, 'application-cache')) datadir = standarddir.get(QStandardPaths.DataLocation) QWebSettings.globalSettings().setLocalStoragePath( os.path.join(datadir, 'local-storage')) QWebSettings.setOfflineStoragePath( os.path.join(datadir, 'offline-storage')) global settings settings = QWebSettings.globalSettings() for sectname, section in MAPPINGS.items(): for optname, (typ, arg) in section.items(): value = config.get(sectname, optname) _set_setting(typ, arg, value) objreg.get('config').changed.connect(update_settings)
def init(_args): """Initialize the global QWebSettings.""" cache_path = standarddir.cache() data_path = standarddir.data() QWebSettings.setIconDatabasePath(standarddir.cache()) QWebSettings.setOfflineWebApplicationCachePath( os.path.join(cache_path, 'application-cache')) QWebSettings.globalSettings().setLocalStoragePath( os.path.join(data_path, 'local-storage')) QWebSettings.setOfflineStoragePath( os.path.join(data_path, 'offline-storage')) settings = QWebSettings.globalSettings() _set_user_stylesheet(settings) _set_cookie_accept_policy(settings) _set_cache_maximum_pages(settings) config.instance.changed.connect(_update_settings) global global_settings global_settings = WebKitSettings(QWebSettings.globalSettings()) global_settings.init_settings()
def _shutdown(self, status, restart): """Second stage of shutdown.""" log.destroy.debug("Stage 2 of shutting down...") if qApp is None: # No QApplication exists yet, so quit hard. sys.exit(status) # Remove eventfilter try: log.destroy.debug("Removing eventfilter...") qApp.removeEventFilter(objreg.get('event-filter')) except AttributeError: pass # Close all windows QApplication.closeAllWindows() # Shut down IPC try: objreg.get('ipc-server').shutdown() except KeyError: pass # Save everything try: save_manager = objreg.get('save-manager') except KeyError: log.destroy.debug("Save manager not initialized yet, so not " "saving anything.") else: for key in save_manager.saveables: try: save_manager.save(key, is_exit=True) except OSError as e: error.handle_fatal_exc( e, self._args, "Error while saving!", pre_text="Error while saving {}".format(key)) # Disable storage so removing tempdir will work QWebSettings.setIconDatabasePath('') QWebSettings.setOfflineWebApplicationCachePath('') QWebSettings.globalSettings().setLocalStoragePath('') # Re-enable faulthandler to stdout, then remove crash log log.destroy.debug("Deactivating crash log...") objreg.get('crash-handler').destroy_crashlogfile() # Delete temp basedir if ((self._args.temp_basedir or self._args.temp_basedir_restarted) and not restart): atexit.register(shutil.rmtree, self._args.basedir, ignore_errors=True) # If we don't kill our custom handler here we might get segfaults log.destroy.debug("Deactivating message handler...") qInstallMessageHandler(None) # Now we can hopefully quit without segfaults log.destroy.debug("Deferring QApplication::exit...") objreg.get('signal-handler').deactivate() # We use a singleshot timer to exit here to minimize the likelihood of # segfaults. QTimer.singleShot(0, functools.partial(qApp.exit, status))
def recordBrowser(self, browser, position): """ Public method to record the data of a browser about to be closed. @param browser reference to the browser to be closed (HelpBrowser) @param position index of the tab to be closed (integer) """ globalSettings = QWebSettings.globalSettings() if globalSettings.testAttribute(QWebSettings.PrivateBrowsingEnabled): return if browser.url().isEmpty(): return tab = ClosedTab(browser.url(), browser.title(), position) self.__closedTabs.insert(0, tab) self.closedTabAvailable.emit(True)
def __updateRow(self, itm=None): """ Private slot to update a download item. @param itm reference to the download item (DownloadItem) """ if itm is None: itm = self.sender() if itm not in self.__downloads: return row = self.__downloads.index(itm) if self.__iconProvider is None: self.__iconProvider = QFileIconProvider() icon = self.__iconProvider.icon(QFileInfo(itm.fileName())) if icon.isNull(): icon = self.style().standardIcon(QStyle.SP_FileIcon) itm.setIcon(icon) oldHeight = self.downloadsView.rowHeight(row) self.downloadsView.setRowHeight( row, max(oldHeight, itm.minimumSizeHint().height() * 1.5)) remove = False globalSettings = QWebSettings.globalSettings() if not itm.downloading() and \ globalSettings.testAttribute(QWebSettings.PrivateBrowsingEnabled): remove = True if itm.downloadedSuccessfully() and \ self.removePolicy() == DownloadManager.RemoveSuccessFullDownload: remove = True if remove: self.__model.removeRow(row) self.cleanupButton.setEnabled( (len(self.__downloads) - self.activeDownloads()) > 0) # record the change self.changeOccurred()
def _set_global_render_settings(js_disable_cross_domain_access, private_mode, disable_browser_caches): from PyQt5.QtWebKit import QWebSecurityOrigin, QWebSettings if js_disable_cross_domain_access is False: # In order to enable cross domain requests it is necessary to add # the http and https to the local scheme, this way all the urls are # seen as inside the same security origin. for scheme in ['http', 'https']: QWebSecurityOrigin.addLocalScheme(scheme) settings = QWebSettings.globalSettings() settings.setAttribute(QWebSettings.PrivateBrowsingEnabled, private_mode) settings.setAttribute(QWebSettings.LocalStorageEnabled, not private_mode) if disable_browser_caches is True: # disables the page cache (also known as the in-memory webkit cache) # see https://webkit.org/blog/427/webkit-page-cache-i-the-basics/ settings.setObjectCacheCapacities(0, 0, 0) settings.setMaximumPagesInCache(0)
def initSetting(self): # 获取当前设置 webSettings = QWebSettings.globalSettings() # 设置默认编码为utf-8 webSettings.setDefaultTextEncoding("utf-8") # 自动加载图片 webSettings.setAttribute(QWebSettings.AutoLoadImages, True) # 开发人员工具 webSettings.setAttribute(QWebSettings.DeveloperExtrasEnabled, False) # 开启java支持 webSettings.setAttribute(QWebSettings.JavaEnabled, True) # js 打开窗口 webSettings.setAttribute(QWebSettings.JavascriptCanOpenWindows, True) # js 关闭窗口 webSettings.setAttribute(QWebSettings.JavascriptCanCloseWindows, True) # js 访问剪贴板 webSettings.setAttribute(QWebSettings.JavascriptCanAccessClipboard, True) # html5离线储存 webSettings.setAttribute(QWebSettings.OfflineStorageDatabaseEnabled, True) webSettings.setAttribute( QWebSettings.OfflineWebApplicationCacheEnabled, True) # 开启插件 webSettings.setAttribute(QWebSettings.PluginsEnabled, True) # 私密浏览 webSettings.setAttribute(QWebSettings.PrivateBrowsingEnabled, True) # html5本地储存 webSettings.setAttribute(QWebSettings.LocalStorageEnabled, True) webSettings.setAttribute(QWebSettings.LocalStorageDatabaseEnabled, True) webSettings.setAttribute(QWebSettings.LocalContentCanAccessFileUrls, True) webSettings.setAttribute(QWebSettings.LocalContentCanAccessRemoteUrls, True) # css3网格布局 webSettings.setAttribute(QWebSettings.CSSGridLayoutEnabled, True) # 允许桌面通知 webSettings.setAttribute(QWebSettings.NotificationsEnabled, True) # 跨站点 webSettings.setAttribute(QWebSettings.XSSAuditingEnabled, True)
def __searchNow(self): """ Private slot to perform the web search. """ searchText = self.text() if not searchText: return globalSettings = QWebSettings.globalSettings() if not globalSettings.testAttribute( QWebSettings.PrivateBrowsingEnabled): if searchText in self.__recentSearches: self.__recentSearches.remove(searchText) self.__recentSearches.insert(0, searchText) if len(self.__recentSearches) > self.__maxSavedSearches: self.__recentSearches = \ self.__recentSearches[:self.__maxSavedSearches] self.__setupCompleterMenu() url = self.__openSearchManager.currentEngine().searchUrl(searchText) self.search.emit(url)
def follow_selected(self, *, tab=False): if QWebSettings.globalSettings().testAttribute( QWebSettings.JavascriptEnabled): if tab: self._tab.data.override_target = usertypes.ClickTarget.tab self._tab.run_js_async(""" const aElm = document.activeElement; if (window.getSelection().anchorNode) { window.getSelection().anchorNode.parentNode.click(); } else if (aElm && aElm !== document.body) { aElm.click(); } """) else: selection = self._widget.selectedHtml() if not selection: # Getting here may mean we crashed, but we can't do anything # about that until this commit is released: # https://github.com/annulen/webkit/commit/0e75f3272d149bc64899c161f150eb341a2417af # TODO find a way to check if something is focused self._follow_enter(tab) return try: selected_element = xml.etree.ElementTree.fromstring( '<html>{}</html>'.format(selection)).find('a') except xml.etree.ElementTree.ParseError: raise browsertab.WebTabError('Could not parse selected ' 'element!') if selected_element is not None: try: url = selected_element.attrib['href'] except KeyError: raise browsertab.WebTabError('Anchor element without ' 'href!') url = self._tab.url().resolved(QUrl(url)) if tab: self._tab.new_tab_requested.emit(url) else: self._tab.openurl(url)
def init(_args): """Initialize the global QWebSettings.""" cache_path = standarddir.cache() data_path = standarddir.data() _init_private_browsing() QWebSettings.setOfflineWebApplicationCachePath( os.path.join(cache_path, 'application-cache')) QWebSettings.globalSettings().setLocalStoragePath( os.path.join(data_path, 'local-storage')) QWebSettings.setOfflineStoragePath( os.path.join(data_path, 'offline-storage')) websettings.init_mappings(MAPPINGS) _set_user_stylesheet() objreg.get('config').changed.connect(update_settings)
def _check_prerequisites(self, win_id): """Check if the command is permitted to run currently. Args: win_id: The window ID the command is run in. """ mode_manager = objreg.get('mode-manager', scope='window', window=win_id) curmode = mode_manager.mode if self._modes is not None and curmode not in self._modes: mode_names = '/'.join(mode.name for mode in self._modes) raise cmdexc.PrerequisitesError( "{}: This command is only allowed in {} mode.".format( self.name, mode_names)) elif self._not_modes is not None and curmode in self._not_modes: mode_names = '/'.join(mode.name for mode in self._not_modes) raise cmdexc.PrerequisitesError( "{}: This command is not allowed in {} mode.".format( self.name, mode_names)) if self._needs_js and not QWebSettings.globalSettings().testAttribute( QWebSettings.JavascriptEnabled): raise cmdexc.PrerequisitesError( "{}: This command needs javascript enabled.".format(self.name))
def __init__(self): super(MainWindow, self).__init__() #self.setViewport(QGLWidget(QGLFormat(QGL.SampleBuffers | QGL.DirectRendering))) settings = QWebSettings.globalSettings() settings.setAttribute(QWebSettings.AcceleratedCompositingEnabled, True) settings.setAttribute(QWebSettings.WebGLEnabled, True) scene = QGraphicsScene(self) w = QGraphicsWebView() w.page().settings().setAttribute( QWebSettings.AcceleratedCompositingEnabled, True) w.page().settings().setAttribute(QWebSettings.WebGLEnabled, True) w.resize(900, 700) plot_content = plots.plot3d() w.setHtml(html % {'plot_content': plot_content}) scene.addItem(w) scene.setSceneRect(0, 0, 900, 700) self.setScene(scene) #self.setCacheMode(QGraphicsView.CacheBackground) self.setWindowTitle("Plot 3D")
def clearMemory(self): QWebSettings.globalSettings().clearMemoryCaches() QWebSettings.globalSettings().clearIconDatabase()
def clear_caches(): QWebSettings.clearMemoryCaches()
def webSettings(self): self.cookiesjar = PersistentCookieJar(self) self.zoom = self.readZoom() # We don't want Flash (it causes a lot of trouble in some distros) QWebSettings.globalSettings().setAttribute(QWebSettings.PluginsEnabled, False) # We don't need Java QWebSettings.globalSettings().setAttribute(QWebSettings.JavaEnabled, False) # Enabling Local Storage (now required by Slack) QWebSettings.globalSettings().setAttribute( QWebSettings.LocalStorageEnabled, True) # We need browsing history (required to not limit LocalStorage) QWebSettings.globalSettings().setAttribute( QWebSettings.PrivateBrowsingEnabled, False) # Enabling Cache self.diskCache = QNetworkDiskCache(self) self.diskCache.setCacheDirectory(self.cache_path) # Required for copy and paste clipboard integration QWebSettings.globalSettings().setAttribute( QWebSettings.JavascriptCanAccessClipboard, True) # Enabling Inspeclet only when --debug=True (requires more CPU usage) QWebSettings.globalSettings().setAttribute( QWebSettings.DeveloperExtrasEnabled, self.debug) # Sharing the same networkAccessManager self.networkAccessManager = QNetworkAccessManager(self) self.networkAccessManager.setCookieJar(self.cookiesjar) self.networkAccessManager.setCache(self.diskCache)
def has_js(self): settings = QWebSettings.globalSettings() return settings.testAttribute(QWebSettings.JavascriptEnabled)
'css-media-type': (MapType.setter, lambda qws, v: qws.setCSSMediaType(v)), #'accelerated-compositing': # (MapType.attribute, QWebSettings.AcceleratedCompositingEnabled), #'tiled-backing-store': # (MapType.attribute, QWebSettings.TiledBackingStoreEnabled), }, 'storage': { 'offline-storage-database': (MapType.attribute, QWebSettings.OfflineStorageDatabaseEnabled), 'offline-web-application-storage': (MapType.attribute, QWebSettings.OfflineWebApplicationCacheEnabled), 'local-storage': (MapType.attribute, QWebSettings.LocalStorageEnabled), 'maximum-pages-in-cache': (MapType.static_setter, lambda v: QWebSettings.setMaximumPagesInCache(v)), 'object-cache-capacities': (MapType.static_setter, lambda v: QWebSettings.setObjectCacheCapacities(*v)), 'offline-storage-default-quota': (MapType.static_setter, lambda v: QWebSettings.setOfflineStorageDefaultQuota(v)), 'offline-web-application-cache-quota': (MapType.static_setter, lambda v: QWebSettings.setOfflineWebApplicationCacheQuota(v)), }, 'general': { 'private-browsing': (MapType.attribute, QWebSettings.PrivateBrowsingEnabled), 'developer-extras': (MapType.attribute, QWebSettings.DeveloperExtrasEnabled),
def __init__(self, fullscreen=False, sizes=None): """ This constructor function initializes a layout of the Arius output module but doesn`t displays it on the screen. Firstly, it creates a new app and detects screens configuration. Then, QGridLayout is created and its appearance is configured: margins and spaces between elements is set to 0. After that, we create three QWebViews: one for our main content view and two others for header and footer views. Immideately after creating these instances we assign them their heights according to percentages given by user and dimensions of the screen. Next, we remove scroll bars from top and bottom views and load predefined pages into them. Then we allow QWebKit to run all extensions it needs to render the page. After that, wee set the layout design as a grid of three rows. Finally, we create an updater object which will run in another stream and a timer instance which checks that stream for new commands from the server, and in case if there`s some update handles it. """ if not fullscreen and not sizes: print 'You must initialize windows size' raise Exception self._fullscreen = fullscreen if sizes: self._screen_width = sizes[0] self._screen_height = sizes[1] self._app = QtWidgets.QApplication(sys.argv) self._app.setStyle("Fusion") if self._fullscreen: self._get_screen_height() self._layout = QGridLayout() # create a main view of an app self._layout.setSpacing(0) # and do some design settings self._layout.setContentsMargins(0, 0, 0, 0) self._main_browser = QWebView() # create a main content view # and initialize zoom factor variable which will be used to control # zoom main_page = FakeBrowser(self) self._main_browser.setPage(main_page) self._zoom_factor = 1 self._top_browser = QWebView() # and create top and bottom views self._bottom_browser = QWebView() self._top_browser_height = config[ 'output_header_height'] * self._screen_height # calculate views sizes self._bottom_browser_height = config[ 'output_footer_height'] * self._screen_height self._top_browser.setMaximumHeight( self._top_browser_height) # and assign them to the views self._top_browser.setMinimumHeight(self._top_browser_height) self._bottom_browser.setMaximumHeight(self._bottom_browser_height) self._bottom_browser.setMinimumHeight(self._bottom_browser_height) self._top_browser.page().mainFrame().setScrollBarPolicy( QtCore.Qt.Vertical, QtCore.Qt.ScrollBarAlwaysOff) # remove the scroll bars self._main_browser.page().mainFrame().setScrollBarPolicy( QtCore.Qt.Vertical, QtCore.Qt.ScrollBarAlwaysOff) self._main_browser.page().mainFrame().setScrollBarPolicy( QtCore.Qt.Horizontal, QtCore.Qt.ScrollBarAlwaysOff) self._bottom_browser.page().mainFrame().setScrollBarPolicy( QtCore.Qt.Vertical, QtCore.Qt.ScrollBarAlwaysOff) self._top_browser_load_url( config['flask_server_home'] + config['output_browser_top_page']) # load default design self._bottom_browser_load_url(config['flask_server_home'] + config['output_browser_bottom_page']) self._main_browser.settings().setAttribute( QWebSettings.DeveloperExtrasEnabled, True) # enable console self._main_browser.settings().setAttribute(QWebSettings.PluginsEnabled, True) # enable plugins QWebSettings.setObjectCacheCapacities(0, 0, 0) # disable caching self._main_browser.settings().setAttribute( QWebSettings.AcceleratedCompositingEnabled, True) self._main_browser.settings().setAttribute(QWebSettings.WebGLEnabled, True) self._layout.addWidget(self._top_browser, 1, 0) # set views positions self._layout.addWidget(self._main_browser, 2, 0) self._layout.addWidget(self._bottom_browser, 3, 0) # create a RLock object to syncronyze threads. self._lock = threading.RLock() # and create an updater object self._updater = OutputUpdater(self._lock) self._updater.start() # which is ran in another non-blocking stream self.timeoutTimer = QTimer() # create a timer to check for commands tCallback = functools.partial( self._handle_command) # set a timer`s function self.timeoutTimer.timeout.connect(tCallback) self.timeoutTimer.start( config['output_update_frequency']) # and start it # as no data is displayed on the main view - curent content type is # None self._cur_filetype = None # text to speech speaker self._speaker = None # audioplayer self._player = Player()
def clearHistory(self): clear_everything = (self.dataType.currentIndex() == self.dataType.count()-1) if self.dataType.currentIndex() == 0 or clear_everything: data.clearHistory() if self.dataType.currentIndex() == 1 or clear_everything: data.clearCookies() if self.dataType.currentIndex() == 2 or clear_everything: QWebSettings.globalSettings().clearMemoryCaches() if self.dataType.currentIndex() == 3 or clear_everything: QWebSettings.globalSettings().setIconDatabasePath("") QWebSettings.globalSettings().setLocalStoragePath("") QWebSettings.globalSettings().setOfflineStoragePath("") QWebSettings.globalSettings().setOfflineWebApplicationCachePath("") for subpath in ("WebpageIcons.db", "LocalStorage", "Databases",): path = os.path.abspath(os.path.join(settings.settings_folder, subpath)) if os.path.isfile(path): try: os.remove(path) except: pass elif os.path.isdir(path): if sys.platform.startswith("win"): args = ["rmdir", "/s", "/q", "\"" + path + "\""] try: os.system(" ".join(args)) except: pass else: try: subprocess.Popen(["rm", "-rf", path]) except: pass QWebSettings.globalSettings().enablePersistentStorage(settings.settings_folder)
def main(reactorString, ampChildPath): #def main(): from twisted.internet import reactor, stdio from twisted.python import reflect, runtime #ampChild = reflect.namedAny(ampChildPath) #protInstance = ampChild(*sys.argv[1:-2]) # This is how you reach the prot from here. protInstance = '' from twisted.internet import reactor # this is actually used, ignore the warning. hermes = Hermes.Hermes(protInstance) charon = Charon(hermes) view = AetherMainWindow(charon, reactor, baseurl, protInstance) trayIcon = SystemTrayIcon(basedir, app, view) trayIcon.protInstance = protInstance #protInstance.trayIcon = trayIcon ef = ModifierEventFilter() app.view = view ef.view = view app.trayIcon = trayIcon view.trayIcon = trayIcon ef.trayIcon = trayIcon charon.trayIcon = trayIcon trayIcon.webView = view app.installEventFilter(ef) trayIcon.show() #FIXME before package enableWebkitInspector = False if enableWebkitInspector is True: from PyQt5.QtWebKit import QWebSettings QWebSettings.globalSettings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True) inspect = QWebInspector() inspect.resize(1450, 300) inspect.move(0,0) inspect.setPage(view.webView.page()) view.setContextMenuPolicy(Qt.DefaultContextMenu) inspect.show() splash.finish(view) if not globals.appStartedAtBoot: view.show() trayIcon.toggleVisibilityMenuItem.setText('Hide Aether') if runtime.platform.isWindows(): stdio.StandardIO(protInstance) else: stdio.StandardIO(protInstance, 3, 4) #enter = getattr(ampChild, '__enter__', None) # if enter is not None: # enter() # try: # reactor.run() # except: # if enter is not None: # info = sys.exc_info() # if not ampChild.__exit__(*info): # raise # else: # raise # else: # if enter is not None: # ampChild.__exit__(None, None, None) reactor.run()
def __init__(self, parent=None): QWebView.__init__(self, parent) self.settings = QWebSettings.globalSettings() self.settings.setAttribute(QWebSettings.LocalContentCanAccessFileUrls, True)
def main(argv): global server_thread print("Starting %s %s..." % (common.app_name, common.app_version)) print(""" __ / \_ __( )_ _( \_ _( )_ (__________________) """) app = QApplication(argv) network.setup() filtering.setup() # Create extension server. server_thread = extension_server.ExtensionServerThread( QCoreApplication.instance()) # Start DBus loop if has_dbus: print("DBus available. Creating main loop...", end=" ") mainloop = DBusQtMainLoop(set_as_default=True) dbus.set_default_main_loop(mainloop) print("done.") else: print("DBus unavailable.") # Create app. app.setApplicationName(common.app_name) app.setApplicationVersion(common.app_version) app.installTranslator(translate.translator) # We want Nimbus to stay open when the last window is closed, # so we set this. app.setQuitOnLastWindowClosed(False) # If D-Bus is present... if has_dbus: print("Creating DBus session bus...", end=" ") try: bus = dbus.SessionBus() except: print("failed.") else: print("done.") try: print("Checking for running instances of %s..." % (common.app_name, ), end=" ") proxy = bus.get_object( "org.nimbus.%s" % (common.app_name, ), "/%s" % common.app_name, ) except: dbus_present = False else: dbus_present = True print("done.") # If Nimbus detects the existence of another Nimbus process, it # will send all the requested URLs to the existing process and # exit. if dbus_present: print( "An instance of Nimbus is already running. Passing arguments via DBus." ) for arg in argv[1:]: proxy.addTab(arg) if len(argv) < 2: proxy.addWindow() return elif has_dbus: print("No prior instances found. Continuing on our merry way.") # Hack together the browser's icon. This needs to be improved. common.app_icon = common.complete_icon("nimbus") app.setWindowIcon(common.app_icon) common.searchEditor = search_manager.SearchEditor() common.downloadManager = DownloadManager(windowTitle=tr("Downloads")) common.downloadManager.resize(QSize(480, 320)) common.downloadManager.loadSession() # Create tray icon. common.trayIcon = SystemTrayIcon() common.trayIcon.newWindowRequested.connect(addWindow) #common.trayIcon.windowReopenRequested.connect(reopenWindow) common.trayIcon.show() # Creates a licensing information dialog. common.licenseDialog = custom_widgets.LicenseDialog() # Create instance of clear history dialog. common.chistorydialog = clear_history_dialog.ClearHistoryDialog() uc = QUrl.fromUserInput(settings.user_css) websettings = QWebSettings.globalSettings() websettings.setUserStyleSheetUrl(uc) websettings.enablePersistentStorage(settings.settings_folder) websettings.setAttribute(websettings.LocalContentCanAccessRemoteUrls, True) websettings.setAttribute(websettings.LocalContentCanAccessFileUrls, True) websettings.setAttribute(websettings.DeveloperExtrasEnabled, True) try: websettings.setAttribute(websettings.ScrollAnimatorEnabled, True) except: pass common.applyWebSettings() # Set up settings dialog. settings.settingsDialog = settings_dialog.SettingsDialog() settings.settingsDialog.setWindowFlags(Qt.Dialog) closeSettingsDialogAction = QAction(settings.settingsDialog) closeSettingsDialogAction.setShortcuts(["Esc", "Ctrl+W"]) closeSettingsDialogAction.triggered.connect(settings.settingsDialog.hide) settings.settingsDialog.addAction(closeSettingsDialogAction) # Set up clippings manager. settings.clippingsManager = settings_dialog.ClippingsPanel() settings.clippingsManager.setWindowFlags(Qt.Dialog) closeClippingsManagerAction = QAction(settings.clippingsManager) closeClippingsManagerAction.setShortcuts(["Esc", "Ctrl+W"]) closeClippingsManagerAction.triggered.connect( settings.clippingsManager.hide) settings.clippingsManager.addAction(closeClippingsManagerAction) # Create DBus server if has_dbus: print("Creating DBus server...", end=" ") server = DBusServer(bus) print("done.") # Load adblock rules. filtering.adblock_filter_loader.start() if not os.path.isdir(settings.extensions_folder): try: print("Copying extensions...", end=" ") shutil.copytree(common.extensions_folder,\ settings.extensions_folder) except: print("failed.") else: print("done.") if not os.path.isfile(settings.startpage): try: print("Copying start page...", end=" ") shutil.copy2(common.startpage, settings.startpage) except: print("failed.") else: print("done.") settings.reload_extensions() settings.reload_userscripts() server_thread.setDirectory(settings.extensions_folder) # Start extension server. server_thread.start() # On quit, save settings. app.aboutToQuit.connect(prepareQuit) # Load settings. data.loadData() # View source dialog. common.viewSourceDialog = ViewSourceDialogTabber() #common.viewSourceDialog.show() # This is a baaad name. common.sessionSaver = QTimer(QCoreApplication.instance()) common.sessionSaver.timeout.connect(saveSession) common.sessionSaver.timeout.connect(data.saveData) if common.portable: common.sessionSaver.start(50000) else: common.sessionSaver.start(30000) common.desktop = QDesktopWidget() changeSettings = False if os.path.isfile(settings.crash_file): print("Crash file detected.", end="") if not has_dbus: print( " With no DBus, %s may already be running." % common.app_name, ) multInstances = QMessageBox.question( None, tr("Hm."), tr("It's not good to run multiple instances of %(app_name)s. Is an instance of %(app_name)s already running?" ) % {"app_name": common.app_name}, QMessageBox.Yes | QMessageBox.No) if multInstances == QMessageBox.Yes: print("%s will now halt." % common.app_name, ) return else: print() clearCache = QMessageBox() clearCache.setWindowTitle(tr("Ow.")) clearCache.setText( tr("%(app_name)s seems to have crashed during your last session. Fortunately, your tabs were saved up to 30 seconds beforehand. Would you like to restore them?" ) % {"app_name": common.app_name}) clearCache.addButton(QPushButton(tr("Yes and change &settings")), QMessageBox.YesRole) clearCache.addButton(QMessageBox.Yes) clearCache.addButton(QMessageBox.No) returnValue = clearCache.exec_() if returnValue == QMessageBox.No: try: os.remove(settings.session_file) except: pass if returnValue == 0: changeSettings = True else: f = open(settings.crash_file, "w") f.write("") f.close() if not "--daemon" in argv and os.path.exists(settings.session_file): print("Loading previous session...", end=" ") if changeSettings: settings.settingsDialog.exec_() loadSession() print("done.") if not "--daemon" in argv and len(argv[1:]) > 0: # Create instance of MainWindow. print("Loading the URLs you requested...", end=" ") if len(browser.windows) > 0: win = browser.windows[-1] else: win = MainWindow(appMode=("--app" in argv)) # Open URLs from command line. if len(argv[1:]) > 0: for arg in argv[1:]: if "." in arg or ":" in arg: win.addTab(url=arg) if win.tabWidget().count() < 1: win.addTab(url=settings.settings.value("general/Homepage")) # Show window. win.show() print("done.") elif not "--daemon" in argv and len(argv[1:]) == 0 and len( browser.windows) == 0: win = MainWindow(appMode=("--app" in argv)) win.addTab(url=settings.settings.value("general/Homepage")) win.show() # Load filtering stuff. if not os.path.isdir(filtering.hosts_folder): common.trayIcon.showMessage(tr("Downloading content filters"), ( "Ad blocking and host filtering will not work until this completes." )) filtering.update_filters() else: filtering.load_host_rules() # Start app. print("Kon~!") sys.exit(app.exec_())
def inspect(self, page): settings = QWebSettings.globalSettings() settings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True) self._widget.setPage(page)
def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.show() self.setWindowTitle("Prakhar") #window tiltle self.setWindowIcon(QIcon('download.jpg')) #Window Icon self.height = 1000 self.width = 1000 self.top = 50 self.left = 50 self.statusMessage = "Quote of the day : Love is not to be Purchased, And Affection has No Price" self.setGeometry(self.top,self.left,self.width,self.height) self.statusBar().showMessage(self.statusMessage) self.browser = QWebView() """Tabs Coding Is From Here""" self.tabs = QTabWidget() self.tabs.setDocumentMode(True) self.tabs.tabBarDoubleClicked.connect(self.tab_open_double_click) self.tabs.currentChanged.connect(self.current_tabChanged) self.add_new_tab(QUrl("https://www.google.com"),'Hometab') #home page google self.tabs.setTabsClosable(True) self.tabs.tabCloseRequested.connect(self.close_current_tab) self.setCentralWidget(self.tabs) """Till Here""" QWebSettings.globalSettings().setAttribute(QWebSettings.PluginsEnabled, True); #Plugins Enabled nav = QToolBar("Navigation") #Navigation Tab nav.setIconSize(QSize(16,16)) self.addToolBar(nav) back_btn = QAction(QIcon("left.ico"),"back",self) #Back Button back_btn.setStatusTip("Previous Page") back_btn.triggered.connect(lambda :self.tabs.currentWidget().back()) nav.addAction(back_btn) for_btn = QAction(QIcon("right.ico"),"front",self) #Forward Button for_btn.setStatusTip("Next Page") for_btn.triggered.connect(lambda :self.tabs.currentWidget().forward()) nav.addAction(for_btn) reload_btn = QAction(QIcon("restart.ico"),"Restart",self) #Reload Button reload_btn.setStatusTip("Restart Loading") reload_btn.triggered.connect(lambda :self.tabs.currentWidget().reload()) nav.addAction(reload_btn) home_btn = QAction(QIcon("home.ico"), "Home", self) #Home Button home_btn.setStatusTip("Take Me to the Home Page") home_btn.triggered.connect(self.navigate_home) nav.addAction(home_btn) nav.addSeparator() self.httpsicon = QLabel() #Security Lock self.httpsicon.setPixmap(QPixmap('unlock.png')) nav.addWidget(self.httpsicon) self.urlbar = QLineEdit() #editing of Url in navigation Tab self.urlbar.returnPressed.connect(self.navigate_to_url) nav.addWidget(self.urlbar) stop_btn = QAction(QIcon("stop.ico"),"Stop",self) #Stop Loading Button stop_btn.setStatusTip("Stop Loading") stop_btn.triggered.connect(lambda :self.tabs.currentWidget().stop()) nav.addAction(stop_btn) self.menuBar().setNativeMenuBar(False) bar_menu = self.menuBar() file_menu = self.menuBar().addMenu(QIcon('filemenu.ico'),"&File") #graph = self.menuBar().addMenu("&Graphs") new_tab_action = QAction("New Tab",self) #Print /menu new_tab_action.setStatusTip("Opens a New Page") new_tab_action.triggered.connect(lambda x : self.add_new_tab()) file_menu.addAction(new_tab_action) self.menuBar().setNativeMenuBar(False) bar_menu = self.menuBar() file_menu = self.menuBar().addMenu(QIcon('game.ico'), "&Games") #threeD = QAction("3-Dimentional",self) #threeD.setStatusTip("Makes A 3-D Graph of the File you provide") #threeD.triggered.connect(self.graph) #graph.addAction(threeD) print_action = QAction("Print_Page",self) #Print /menu print_action.setStatusTip("Print This Page") print_action.triggered.connect(self.print_page) bar_menu.addAction(print_action) open_action = QAction("Open_File", self) #OPEN MENU open_action.setStatusTip("Open A File") open_action.triggered.connect(self.open_file) bar_menu.addAction(open_action) save_action = QAction("Save_As", self) #Save MEnu save_action.setStatusTip("Save This Page") save_action.triggered.connect(self.save_file) bar_menu.addAction(save_action) about_action = QAction("About_Prakhar_Browser", self) #About About Us about_action.setStatusTip("Know More About Prakhar") about_action.triggered.connect(self.about) bar_menu.addAction(about_action) navigate_pasha_action = QAction("Prakhar's_Home_Page", self) #About Prakhar home page navigate_pasha_action.setStatusTip("Go To Prakhar's Home Page") navigate_pasha_action.triggered.connect(self.navigatePasha) bar_menu.addAction(navigate_pasha_action) game_action = QAction("Snake Game", self) #Game game_action.setStatusTip("snakess all Around") game_action.triggered.connect(self.game) file_menu.addAction(game_action) air_action = QAction("Air Hockey", self) #Game air_action.setStatusTip("It's Hockey") air_action.triggered.connect(self.air) file_menu.addAction(air_action) calc_action = QAction("Prakhar Calculator", self) #Game calc_action.setStatusTip("Calculating") calc_action.triggered.connect(self.calculate) bar_menu.addAction(calc_action)
def shutdown(): """Disable storage so removing tmpdir will work.""" QWebSettings.setIconDatabasePath('') QWebSettings.setOfflineWebApplicationCachePath('') QWebSettings.globalSettings().setLocalStoragePath('')
def _set(self, value, settings=None): QWebSettings.globalSettings().setThirdPartyCookiePolicy( self.MAPPING[value])
def disableJS(self): settings = QWebSettings.globalSettings() settings.setAttribute(QWebSettings.JavascriptEnabled, False)
def _set_user_stylesheet(): """Set the generated user-stylesheet.""" stylesheet = shared.get_user_stylesheet().encode('utf-8') url = urlutils.data_url('text/css;charset=utf-8', stylesheet) QWebSettings.globalSettings().setUserStyleSheetUrl(url)
def post(self, request, data): """ Public method to check, if the data to be sent contains login data. @param request reference to the network request (QNetworkRequest) @param data data to be sent (QByteArray) """ # shall passwords be saved? if not Preferences.getUser("SavePasswords"): return # observe privacy if QWebSettings.globalSettings().testAttribute( QWebSettings.PrivateBrowsingEnabled): return if not self.__loaded: self.__load() # determine the url refererHeader = request.rawHeader(b"Referer") if refererHeader.isEmpty(): return url = QUrl.fromEncoded(refererHeader) url = self.__stripUrl(url) # check that url isn't in __never if url.toString() in self.__never: return # check the request type navType = request.attribute(QNetworkRequest.User + 101) if navType is None: return if navType != QWebPage.NavigationTypeFormSubmitted: return # determine the QWebPage webPage = request.attribute(QNetworkRequest.User + 100) if webPage is None: return # determine the requests content type contentTypeHeader = request.rawHeader(b"Content-Type") if contentTypeHeader.isEmpty(): return multipart = contentTypeHeader.startsWith(b"multipart/form-data") if multipart: boundary = contentTypeHeader.split(" ")[1].split("=")[1] else: boundary = None # find the matching form on the web page form = self.__findForm(webPage, data, boundary=boundary) if not form.isValid(): return form.url = QUrl(url) # check, if the form has a password if not form.hasAPassword: return # prompt, if the form has never be seen key = self.__createKey(url, "") if key not in self.__loginForms: mb = E5MessageBox.E5MessageBox( E5MessageBox.Question, self.tr("Save password"), self.tr( """<b>Would you like to save this password?</b><br/>""" """To review passwords you have saved and remove them, """ """use the password management dialog of the Settings""" """ menu."""), modal=True) neverButton = mb.addButton( self.tr("Never for this site"), E5MessageBox.DestructiveRole) noButton = mb.addButton( self.tr("Not now"), E5MessageBox.RejectRole) mb.addButton(E5MessageBox.Yes) mb.exec_() if mb.clickedButton() == neverButton: self.__never.append(url.toString()) return elif mb.clickedButton() == noButton: return # extract user name and password user = "" password = "" for index in range(len(form.elements)): element = form.elements[index] type_ = form.elementTypes[element[0]] if user == "" and \ type_ == "text": user = element[1] elif password == "" and \ type_ == "password": password = element[1] form.elements[index] = (element[0], "--PASSWORD--") if user and password: self.__logins[key] = \ (user, Utilities.crypto.pwConvert(password, encode=True)) self.__loginForms[key] = form self.changed.emit()
def __setListContent(self): """ Private method to prepare the content for the reader. """ u = self.url() if not u.path().endswith("/"): u.setPath(u.path() + "/") baseUrl = self.url().toString() basePath = u.path() linkClasses = {} iconSize = QWebSettings.globalSettings().fontSize( QWebSettings.DefaultFontSize) parent = u.resolved(QUrl("..")) if parent.isParentOf(u): icon = UI.PixmapCache.getIcon("up.png") linkClasses["link_parent"] = \ self.__cssLinkClass(icon, iconSize).format("link_parent") parentStr = self.tr( """ <p><a class="link_parent" href="{0}">""" """Change to parent directory</a></p>""").format( parent.toString()) else: parentStr = "" row = \ """ <tr class="{0}">"""\ """<td class="name"><a class="{1}" href="{2}">{3}</a></td>"""\ """<td class="size">{4}</td>"""\ """<td class="modified">{5}</td>"""\ """</tr>\n""" table = self.tr(""" <tr>""" """<th align="left">Name</th>""" """<th>Size</th>""" """<th align="left">Last modified</th>""" """</tr>\n""") i = 0 for item in self.__items: name = item.name() if item.isDir() and not name.endswith("/"): name += "/" child = u.resolved(QUrl(name.replace(":", "%3A"))) if item.isFile(): size = item.size() unit = 0 while size: newSize = size // 1024 if newSize and unit < len(self.__units): size = newSize unit += 1 else: break sizeStr = self.tr("{0} {1}", "size unit")\ .format(size, self.__units[unit]) linkClass = "link_file" if linkClass not in linkClasses: icon = UI.PixmapCache.getIcon("fileMisc.png") linkClasses[linkClass] = \ self.__cssLinkClass(icon, iconSize).format(linkClass) else: sizeStr = "" linkClass = "link_dir" if linkClass not in linkClasses: icon = UI.PixmapCache.getIcon("dirClosed.png") linkClasses[linkClass] = \ self.__cssLinkClass(icon, iconSize).format(linkClass) table += row.format( i == 0 and "odd" or "even", linkClass, child.toString(), Utilities.html_encode(item.name()), sizeStr, item.lastModified().toString("yyyy-MM-dd hh:mm"), ) i = 1 - i content = ftpListPage_html.format( Utilities.html_encode(baseUrl), "".join(linkClasses.values()), self.tr("Listing of {0}").format(basePath), parentStr, table) self.__content = QByteArray(content.encode("utf8")) self.__content.append(512 * b' ') self.open(QIODevice.ReadOnly | QIODevice.Unbuffered) self.setHeader(QNetworkRequest.ContentTypeHeader, "text/html; charset=UTF-8") self.setHeader(QNetworkRequest.ContentLengthHeader, self.__content.size()) self.setAttribute(QNetworkRequest.HttpStatusCodeAttribute, 200) self.setAttribute(QNetworkRequest.HttpReasonPhraseAttribute, "Ok") self.metaDataChanged.emit() self.downloadProgress.emit(self.__content.size(), self.__content.size()) self.readyRead.emit()
def __init__(self, browser, parent=None): """ Constructor @param browser reference to the browser window (HelpBrowser) @param parent reference to the parent widget (QWidget) """ super(SiteInfoDialog, self).__init__(parent) self.setupUi(self) self.setWindowFlags(Qt.Window) # put icons self.tabWidget.setTabIcon( 0, UI.PixmapCache.getIcon("siteinfo-general.png")) self.tabWidget.setTabIcon(1, UI.PixmapCache.getIcon("siteinfo-media.png")) self.tabWidget.setTabIcon( 2, UI.PixmapCache.getIcon("siteinfo-databases.png")) if SSL: self.tabWidget.setTabIcon( 3, UI.PixmapCache.getIcon("siteinfo-security.png")) self.__mainFrame = browser.page().mainFrame() title = browser.title() sslInfo = browser.page().getSslCertificateChain() # populate General tab self.heading.setText("<b>{0}</b>".format(title)) self.siteAddressLabel.setText(self.__mainFrame.baseUrl().toString()) self.sizeLabel.setText(dataString(browser.page().totalBytes())) encoding = "" # populate Meta tags meta = self.__mainFrame.findAllElements("meta") for element in meta: content = element.attribute("content") name = element.attribute("name") if not name: name = element.attribute("http-equiv") if element.attribute("charset"): encoding = element.attribute("charset") if "charset=" in content: encoding = content[content.index("charset=") + 8:] if not content or not name: continue QTreeWidgetItem(self.tagsTree, [name, content]) for col in range(self.tagsTree.columnCount()): self.tagsTree.resizeColumnToContents(col) if not encoding: encoding = QWebSettings.globalSettings().defaultTextEncoding() self.encodingLabel.setText(encoding) # populate the Security info and the Security tab if sslInfo and \ ((qVersion() >= "5.0.0" and not sslInfo[0].isBlacklisted()) or (qVersion() < "5.0.0" and sslInfo[0].isValid())): self.securityLabel.setStyleSheet(SiteInfoDialog.okStyle) self.securityLabel.setText('<b>Connection is encrypted.</b>') if SSL: self.sslWidget.showCertificateChain(sslInfo) self.securityDetailsButton.setEnabled(True) else: self.securityDetailsButton.setEnabled(False) else: self.securityLabel.setStyleSheet(SiteInfoDialog.nokStyle) self.securityLabel.setText('<b>Connection is not encrypted.</b>') self.securityDetailsButton.setEnabled(False) self.tabWidget.setTabEnabled( self.tabWidget.indexOf(self.securityTab), False) # populate Media tab images = self.__mainFrame.findAllElements("img") for element in images: src = element.attribute("src") alt = element.attribute("alt") if src and src.startswith("data:"): continue if not alt: if src.find("/") == -1: alt = src else: pos = src.find("/") alt = src[pos + 1:] if not src or not alt: continue QTreeWidgetItem(self.imagesTree, [alt, src]) for col in range(self.imagesTree.columnCount()): self.imagesTree.resizeColumnToContents(col) if self.imagesTree.columnWidth(0) > 300: self.imagesTree.setColumnWidth(0, 300) self.imagesTree.setCurrentItem(self.imagesTree.topLevelItem(0)) self.imagesTree.setContextMenuPolicy(Qt.CustomContextMenu) self.imagesTree.customContextMenuRequested.connect( self.__imagesTreeContextMenuRequested) # populate the Databases tab databases = self.__mainFrame.securityOrigin().databases() counter = 0 for database in databases: itm = QListWidgetItem(self.databasesList) itm.setText(database.displayName()) itm.setData(Qt.UserRole, counter) counter += 1 if counter == 0: itm = QListWidgetItem(self.databasesList) itm.setText(self.tr("No databases are used by this page.")) itm.setFlags(itm.flags() & Qt.ItemIsSelectable)
def inspect(self, page: QWebPage) -> None: # type: ignore[override] settings = QWebSettings.globalSettings() settings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True) self._widget.setPage(page)