def getData(self): """ Public method to get the data entered into the dialog. @return tuple giving the default and default push URLs (tuple of two strings) """ defaultUrl = QUrl.fromUserInput(self.defaultUrlEdit.text()) username = self.defaultUserEdit.text() password = self.defaultPasswordEdit.text() if username: defaultUrl.setUserName(username) if password: defaultUrl.setPassword(password) if not defaultUrl.isValid(): defaultUrl = "" else: defaultUrl = defaultUrl.toString() defaultPushUrl = QUrl.fromUserInput(self.defaultPushUrlEdit.text()) username = self.defaultPushUserEdit.text() password = self.defaultPushPasswordEdit.text() if username: defaultPushUrl.setUserName(username) if password: defaultPushUrl.setPassword(password) if not defaultPushUrl.isValid(): defaultPushUrl = "" else: defaultPushUrl = defaultPushUrl.toString() return defaultUrl, defaultPushUrl
def _get_search_url(txt: str) -> QUrl: """Get a search engine URL for a text. Args: txt: Text to search for. Return: The search URL as a QUrl. """ log.url.debug("Finding search engine for {!r}".format(txt)) engine, term = _parse_search_term(txt) if not engine: engine = 'DEFAULT' if term: template = config.val.url.searchengines[engine] semiquoted_term = urllib.parse.quote(term) quoted_term = urllib.parse.quote(term, safe='') evaluated = template.format(semiquoted_term, unquoted=term, quoted=quoted_term, semiquoted=semiquoted_term) url = QUrl.fromUserInput(evaluated) else: url = QUrl.fromUserInput(config.val.url.searchengines[engine]) url.setPath(None) # type: ignore[arg-type] url.setFragment(None) # type: ignore[arg-type] url.setQuery(None) # type: ignore[call-overload] qtutils.ensure_valid(url) return url
def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.webView = QWebView(self) self.webView.settings().setAttribute(self.webView.settings().globalSettings().DeveloperExtrasEnabled, True) self.webView.settings().setUserStyleSheetUrl(QUrl.fromUserInput(os.path.join(app_folder, "style.css"))) self.webView.loadFinished.connect(self.jsHack) self.setCentralWidget(self.webView) # Main toolbar self.toolBar = QToolBar(self) self.toolBar.setContextMenuPolicy(Qt.CustomContextMenu) self.addToolBar(Qt.LeftToolBarArea, self.toolBar) page = self.webView.page() backAction = page.action(page.Back) backAction.setShortcut("Alt+Left") self.toolBar.addAction(backAction) nextAction = page.action(page.Forward) nextAction.setShortcut("Alt+Right") self.toolBar.addAction(nextAction) reloadAction = page.action(page.Reload) reloadAction.setShortcuts(["Ctrl+R", "F5"]) self.toolBar.addAction(reloadAction) stopAction = page.action(page.Stop) stopAction.setShortcut("Esc") self.toolBar.addAction(stopAction) self.toolBar.addSeparator() style = QApplication.style() self.uploadAction = QAction(self, text="Upload", icon=style.standardIcon(style.SP_ArrowUp)) self.uploadAction.setShortcut("Alt+Up") self.uploadAction.triggered.connect(self.upload) self.toolBar.addAction(self.uploadAction) self.setGitHubSiteAction = QAction(self, text="Set Page", icon=style.standardIcon(style.SP_FileIcon)) self.setGitHubSiteAction.setShortcut("Ctrl+L") self.setGitHubSiteAction.triggered.connect(self.setGitHubSite) self.toolBar.addAction(self.setGitHubSiteAction) self.setGitDirectoryAction = QAction(self, text="Set Directory", icon=style.standardIcon(style.SP_DirIcon)) self.setGitDirectoryAction.setShortcut("Ctrl+O") self.setGitDirectoryAction.triggered.connect(self.setGitDirectory) self.toolBar.addAction(self.setGitDirectoryAction) self.webView.load(QUrl.fromUserInput(settings.value("settings/GitUrl")))
def commandLineUrlArgument() -> QUrl: args = QCoreApplication.arguments() for arg in args[1:]: if not arg.startswith("_"): return QUrl.fromUserInput(arg) return QUrl("https://www.qt.io")
def handleVideoButton(self, url): if validYoutubeUrl(url): self.videoDownloadButton.show() return self.video_URL = False frames = [self.tabWidget.currentWidget().page().mainFrame()] frames += self.tabWidget.currentWidget().page().mainFrame( ).childFrames() for frame in frames: videos = frame.findAllElements('video').toList() for video in videos: dl_link = video.attribute('src') child = video.findFirst('source[src]') if dl_link == '' and not child.isNull(): dl_link = child.attribute('src') dl_url = QUrl(dl_link) if not dl_url.isValid(): continue if dl_url.isRelative(): dl_url = frame.url().resolved(dl_url) self.video_URL = QUrl.fromUserInput(dl_url.toString()) self.video_page_url = frame.url().toString() break break if self.video_URL: self.videoDownloadButton.show() else: self.videoDownloadButton.hide()
def add_tab(self): index = self.tab_count self.tabs.append(QWidget()) self.tabs[index].layout = QVBoxLayout() self.tabs[index].layout.setContentsMargins(0, 0, 0, 0) self.tabs[index].setObjectName("tab" + str(index)) self.tabs[index].content = QWebEngineView() # Create default URL url = QUrl() url = url.fromUserInput("https://www.google.de") self.tabs[index].content.load(url) # register events self.tabs[index].content.titleChanged.connect(lambda: self.update_tab(index, "title")) self.tabs[index].content.iconChanged.connect(lambda: self.update_tab(index, "icon")) self.tabs[index].content.urlChanged.connect(lambda: self.update_tab(index, "url")) # create split view self.tabs[index].splitview = QSplitter() self.tabs[index].splitview.setOrientation(Qt.Vertical) self.tabs[index].layout.addWidget(self.tabs[index].splitview) self.tabs[index].splitview.addWidget(self.tabs[index].content) self.tabs[index].setLayout(self.tabs[index].layout) self.container.layout.addWidget(self.tabs[index]) self.container.layout.setCurrentWidget(self.tabs[index]) self.tab_bar.addTab("New tab") self.tab_bar.setTabData(index, {"object": "tab" + str(index), "initial": index}) self.tab_bar.setCurrentIndex(index) self.tab_count += 1
def addTab(self, url="about:blank"): if url == "--app": win = MainWindow(appMode=True) win.addTab(url="about:blank") win.show() return url else: for window in browser.windows[::-1]: if window.isVisible(): window.addTab(url=url) if not (window.tabWidget().widget(0).history( ).canGoBack() or window.tabWidget().widget(0).history( ).canGoForward()) and window.tabWidget().widget( 0).url().toString() in ( "about:blank", "", QUrl.fromUserInput( settings.new_tab_page).toString(), ): window.removeTab(0) browser.windows[-1].activateWindow() return url self.addWindow(url) browser.windows[-1].activateWindow() return url
def qurl_from_user_input(urlstr): """Get a QUrl based on a user input. Additionally handles IPv6 addresses. QUrl.fromUserInput handles something like '::1' as a file URL instead of an IPv6, so we first try to handle it as a valid IPv6, and if that fails we use QUrl.fromUserInput. WORKAROUND - https://bugreports.qt.io/browse/QTBUG-41089 FIXME - Maybe https://codereview.qt-project.org/#/c/93851/ has a better way to solve this? https://github.com/qutebrowser/qutebrowser/issues/109 Args: urlstr: The URL as string. Return: The converted QUrl. """ # First we try very liberally to separate something like an IPv6 from the # rest (e.g. path info or parameters) match = re.match(r'\[?([0-9a-fA-F:.]+)\]?(.*)', urlstr.strip()) if match: ipstr, rest = match.groups() else: ipstr = urlstr.strip() rest = '' # Then we try to parse it as an IPv6, and if we fail use # QUrl.fromUserInput. try: ipaddress.IPv6Address(ipstr) except ipaddress.AddressValueError: return QUrl.fromUserInput(urlstr) else: return QUrl('http://[{}]{}'.format(ipstr, rest))
def qurl_from_user_input(urlstr): """Get a QUrl based on a user input. Additionally handles IPv6 addresses. QUrl.fromUserInput handles something like '::1' as a file URL instead of an IPv6, so we first try to handle it as a valid IPv6, and if that fails we use QUrl.fromUserInput. WORKAROUND - https://bugreports.qt.io/browse/QTBUG-41089 FIXME - Maybe https://codereview.qt-project.org/#/c/93851/ has a better way to solve this? https://github.com/The-Compiler/qutebrowser/issues/109 Args: urlstr: The URL as string. Return: The converted QUrl. """ # First we try very liberally to separate something like an IPv6 from the # rest (e.g. path info or parameters) match = re.match(r'\[?([0-9a-fA-F:.]+)\]?(.*)', urlstr.strip()) if match: ipstr, rest = match.groups() else: ipstr = urlstr.strip() rest = '' # Then we try to parse it as an IPv6, and if we fail use # QUrl.fromUserInput. try: ipaddress.IPv6Address(ipstr) except ipaddress.AddressValueError: return QUrl.fromUserInput(urlstr) else: return QUrl('http://[{}]{}'.format(ipstr, rest))
def transform(self, value): if not value: return None else: return [ QUrl.fromUserInput(v) if v else None for v in value.split(',') ]
def onYtVideoParse(self, videos): dialog = youtube.YoutubeDialog(videos, self) if dialog.exec_() == 1 : index = abs(dialog.buttonGroup.checkedId())-2 vid = videos[index] reply = networkmanager.get( QNetworkRequest(QUrl.fromUserInput(vid.url)) ) self.handleUnsupportedContent(reply, vid.filename + '.' + vid.extension)
def is_url(urlstr: str) -> bool: """Check if url seems to be a valid URL. Args: urlstr: The URL as string. Return: True if it is a valid URL, False otherwise. """ autosearch = config.val.url.auto_search log.url.debug("Checking if {!r} is a URL (autosearch={}).".format( urlstr, autosearch)) urlstr = urlstr.strip() qurl = QUrl(urlstr) qurl_userinput = QUrl.fromUserInput(urlstr) if autosearch == 'never': # no autosearch, so everything is a URL unless it has an explicit # search engine. try: engine, _term = _parse_search_term(urlstr) except ValueError: return False else: return engine is None if not qurl_userinput.isValid(): # This will also catch non-URLs containing spaces. return False if _has_explicit_scheme(qurl) and ' ' not in urlstr: # URLs with explicit schemes are always URLs log.url.debug("Contains explicit scheme") url = True elif (autosearch == 'schemeless' and (not _has_explicit_scheme(qurl) or ' ' in urlstr)): # When autosearch=schemeless, URLs must contain schemes to be valid log.url.debug("No explicit scheme in given URL, treating as non-URL") url = False elif qurl_userinput.host() in ['localhost', '127.0.0.1', '::1']: log.url.debug("Is localhost.") url = True elif is_special_url(qurl): # Special URLs are always URLs, even with autosearch=never log.url.debug("Is a special URL.") url = True elif autosearch == 'dns': log.url.debug("Checking via DNS check") # We want to use QUrl.fromUserInput here, as the user might enter # "foo.de" and that should be treated as URL here. url = ' ' not in qurl_userinput.userName() and _is_url_dns(urlstr) elif autosearch == 'naive': log.url.debug("Checking via naive check") url = ' ' not in qurl_userinput.userName() and _is_url_naive(urlstr) else: # pragma: no cover raise ValueError("Invalid autosearch value") log.url.debug("url = {}".format(url)) return url
def _is_url_dns(urlstr: str) -> bool: """Check if a URL is really a URL via DNS. Args: url: The URL to check for as a string. Return: True if the URL really is a URL, False otherwise. """ url = QUrl.fromUserInput(urlstr) assert url.isValid() if (utils.raises(ValueError, ipaddress.ip_address, urlstr) and not QHostAddress(urlstr).isNull()): log.url.debug("Bogus IP URL -> False") # Qt treats things like "23.42" or "1337" or "0xDEAD" as valid URLs # which we don't want to. return False host = url.host() if not host: log.url.debug("URL has no host -> False") return False log.url.debug("Doing DNS request for {}".format(host)) info = QHostInfo.fromName(host) return not info.error()
def AddTab(self): i = self.tabCount self.tabs.append(QWidget()) self.tabs[i].layout = QVBoxLayout() self.tabs[i].setObjectName("tab" + str(i)) # open WebView self.tabs[i].content = QWebEngineView() self.tabs[i].content.load(QUrl.fromUserInput("http://google.com")) # Add webview to tabs layout self.tabs[i].layout.addWidget(self.tabs[i].content) # Add tab to top level widget self.container.layout.addWidget(self.tabs[i]) self.container.layout.setCurrentWidget(self.tabs[i]) # set the tab at top of the screen self.TabBar.addTab("New Tab" + str(i)) self.TabBar.setTabData(i, "Tab " + str(i)) self.TabBar.setCurrentIndex(i) # set top level tab from list to layout self.tabs[i].setLayout(self.tabs[i].layout) self.tabCount += 1
def __guessUrlFromPath(self, path): """ Private method to guess an URL given a path string. @param path path string to guess an URL for (string) @return guessed URL (QUrl) """ manager = self.__mainWindow.openSearchManager() path = Utilities.fromNativeSeparators(path) url = manager.convertKeywordSearchToUrl(path) if url.isValid(): return url try: url = QUrl.fromUserInput(path) except AttributeError: url = QUrl(path) if url.scheme() == "about" and \ url.path() == "home": url = QUrl("eric:home") if url.scheme() in ["s", "search"]: url = manager.currentEngine().searchUrl(url.path().strip()) if url.scheme() != "" and \ (url.host() != "" or url.path() != ""): return url urlString = Preferences.getHelp("DefaultScheme") + path.strip() url = QUrl.fromEncoded(urlString.encode("utf-8"), QUrl.TolerantMode) return url
def fix_url(url): """ Converts an url string to a QUrl object; checks if turning to search query is necessary No-op if already a QUrl """ if isinstance(url, QUrl): return url # clean entry; standard case if url.strip()[:4] in ['http', 'file']: return QUrl(url.strip()) # empty case if not url.strip(): return QUrl() # 'maybe url, maybe not' case url = url.rstrip() # search if a non-alphanum (including space, that will be stripped) leads; # also search if the text has no url structure search = (not url[0].isalnum() or not ('.' in url) or tldextract.extract(url).suffix == '') url = url.lstrip() if search: return QUrl( "http://duckduckgo.com/html/?q={}".format(url.replace(" ", "+"))) else: return QUrl.fromUserInput(url)
def proxy_from_url(url): """ Create a QNetworkProxy from an url. """ if not isinstance(url, QUrl): url = QUrl.fromUserInput(url) if not url.isValid(): raise RuntimeError("Invalid url %s" % url.toString()) scheme = url.scheme() types = { 'http': QNetworkProxy.HttpProxy, 'socks': QNetworkProxy.Socks5Proxy, 'socks5': QNetworkProxy.Socks5Proxy, 'direct': QNetworkProxy.NoProxy, } if scheme not in types: raise RuntimeError("scheme %s for url is invalid" % scheme) proxy = QNetworkProxy(types[scheme], url.host()) if url.port() != -1: proxy.setPort(url.port()) if url.userName(): proxy.setUser(url.userName()) if url.password(): proxy.setPassword(url.password()) return proxy
def fix_url(url): """ Converts an url string to a QUrl object; checks if turning to search query is necessary No-op if already a QUrl """ if isinstance(url, QUrl): return url # clean entry; standard case if url.strip()[:4] in ['http', 'file']: return QUrl(url.strip()) # empty case if not url.strip(): return QUrl() # 'maybe url, maybe not' case url = url.rstrip() # search if a non-alphanum (including space, that will be stripped) leads; # also search if the text has no url structure search = (not url[0].isalnum() or not ('.' in url) or tldextract.extract(url).suffix == '') url = url.lstrip() if search: return QUrl("http://duckduckgo.com/html/?q={}".format( url.replace(" ", "+"))) else: return QUrl.fromUserInput(url)
def value(self): value = super().value() if value is None: return # split webjumps and protocols between command and argument if re.match(r"^\S+://.*", value): args = value.split("://", 1) else: args = value.split(" ", 1) command = args[0] # Look for webjumps webjump = None if command in WEBJUMPS: webjump = WEBJUMPS[command] else: # Look for a incomplete webjump, accepting a candidate # if there is a single option candidates = [wj for wj in WEBJUMPS if wj.startswith(command)] if len(candidates) == 1: webjump = WEBJUMPS[candidates[0]] if webjump: if not webjump.allow_args: # send the url as is return webjump.url elif len(args) < 2: # send the url without a search string return webjump.url.replace("%s", "") else: # format the url as entered if webjump.protocol: return value else: return webjump.url.replace( "%s", str(QUrl.toPercentEncoding(args[1]), "utf-8")) # Look for a bookmark bookmarks = {name: url for url, name in self.bookmarks} if value in bookmarks: return bookmarks[value] # Look for a incomplete bookmarks, accepting a candidate # if there is a single option candidates = [bm for bm in bookmarks if bm.startswith(command)] if len(candidates) == 1: return bookmarks[candidates[0]] # No webjump, no bookmark, look for a url if "://" not in value: url = QUrl.fromUserInput(value) if url.isValid(): # default scheme is https for us if url.scheme() == "http": url.setScheme("https") return url return value
def getCommandLineUrlArgument() -> str: args = QApplication.arguments() if len(args) > 1: lastArg = args[-1] isValidUrl = QUrl.fromUserInput(lastArg).isValid() if isValidUrl: return lastArg return ''
def handle_show_app_help(self): """Show RepTate current application (if any) manual, or all applications""" try: help_file = self.ApplicationtabWidget.currentWidget().help_file except AttributeError as e: print('in "handle_show_help":', e) help_file = 'http://reptate.readthedocs.io/manual/Applications/applications.html' QDesktopServices.openUrl(QUrl.fromUserInput((help_file)))
def urlFromUserInput(self, url): """ Public slot to get the URL from user input. @param url URL entered by the user (string) @return sanitized URL (string) """ return QUrl.fromUserInput(url).toString()
def __init__(self): super(PDFView, self).__init__() pdf_js_path = "file:///" + os.path.join(os.getcwd(), "pdfjs-2.2.228-dist", "web", "viewer.html") pdf_path = "" pdf_path = "file:///" + os.path.join(os.getcwd(), "sample.pdf") pdf_js_path = pdf_js_path.replace('\\', '/') pdf_path = pdf_path.replace('\\', '/') self.load(QUrl.fromUserInput('%s?file=%s' % (pdf_js_path, pdf_path)))
def handle_show_reptate_help(self): """Show RepTate documentation""" try: help_file = self.help_file except AttributeError as e: print('in "handle_show_help":', e) return QDesktopServices.openUrl(QUrl.fromUserInput((help_file)))
def __init__(self): super(PDFView, self).__init__() self.setAcceptDrops(True) pdf_js_path = "file:///" + os.path.join(os.getcwd(), "code", "web", "viewer.html") pdf_path = "file:///" + os.path.join(os.getcwd(), "sample", "sample.pdf") if sys.platform == "win32": pdf_js_path = pdf_js_path.replace('\\', '/') pdf_path = pdf_path.replace('\\', '/') self.load(QUrl.fromUserInput('%s?file=%s' % (pdf_js_path, pdf_path)))
def to_py(self, value): self._basic_py_validation(value, str) if not value: return None qurl = QUrl.fromUserInput(value) if not qurl.isValid(): raise configexc.ValidationError(value, "invalid URL - " "{}".format(qurl.errorString())) return qurl
def main(): import sys app = QApplication(sys.argv) QQuickWindow.setDefaultAlphaBuffer(True) QCoreApplication.setApplicationName("Photosurface") QCoreApplication.setOrganizationName("QtProject") QCoreApplication.setApplicationVersion(QT_VERSION_STR) parser = QCommandLineParser() parser.setApplicationDescription("Qt Quick Demo - Photo Surface") parser.addHelpOption() parser.addVersionOption() parser.addPositionalArgument("directory", "The image directory or URL to show.") parser.process(app) initialUrl = QUrl() if parser.positionalArguments(): initialUrl = QUrl.fromUserInput(parser.positionalArguments()[0], QDir.currentPath(), QUrl.AssumeLocalFile) if not initialUrl.isValid(): print( 'Invalid argument: "', parser.positionalArguments()[0], '": ', initialUrl.errorString(), ) sys.exit(1) nameFilters = imageNameFilters() engine = QQmlApplicationEngine() context: QQmlContext = engine.rootContext() picturesLocationUrl = QUrl.fromLocalFile(QDir.homePath()) picturesLocations = QStandardPaths.standardLocations( QStandardPaths.PicturesLocation) if picturesLocations: picturesLocationUrl = QUrl.fromLocalFile(picturesLocations[0]) if not initialUrl and QDir(picturesLocations[0]).entryInfoList( nameFilters, QDir.Files): initialUrl = picturesLocationUrl context.setContextProperty("contextPicturesLocation", picturesLocationUrl) context.setContextProperty("contextInitialUrl", initialUrl) context.setContextProperty("contextImageNameFilters", nameFilters) engine.load(QUrl("qrc:///photosurface.qml")) if not engine.rootObjects(): sys.exit(-1) sys.exit(app.exec_())
def runShortcut(self, index): if not index.isValid(): return False shortcut = self.shortcuts[index.row()] if shortcut["path"].startswith("special://"): if shortcut["path"] == COMPUTER_PATH: if os.name == "nt": explorer = os.path.join(os.environ["SystemRoot"], "explorer.exe") return QProcess.startDetached( explorer, ["::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"]) else: path = "/" elif shortcut["path"] == DOCUMENTS_PATH: path = QStandardPaths.writableLocation( QStandardPaths.DocumentsLocation) elif shortcut["path"] == MUSIC_PATH: path = QStandardPaths.writableLocation( QStandardPaths.MusicLocation) elif shortcut["path"] == PICTURES_PATH: path = QStandardPaths.writableLocation( QStandardPaths.PicturesLocation) else: return False if os.name == "nt": #针对windows进行优化 explorer = os.path.join(os.environ["SystemRoot"], "explorer.exe") return QProcess.startDetached(explorer, [path]) else: return QDesktopServices.openUrl(QUrl.fromLocalFile(path)) else: currentDirectory = os.getcwd() try: if shortcut["dir"] is not None and shortcut["dir"] != "": os.chdir(shortcut["dir"]) if shortcut[ "openwith"] is not None and shortcut["openwith"] != "": if not os.path.exists(shortcut["openwith"]): return False return QProcess.startDetached(shortcut["openwith"], [shortcut["path"]]) else: url = QUrl.fromUserInput(shortcut["path"]) if not url.isValid(): return False if url.scheme() == "file" and not os.path.exists( url.toLocalFile()): return False return QDesktopServices.openUrl(url) except OSError: #raised by chdir() pass finally: os.chdir(currentDirectory) return False
def changePDF(self, pdf_path): self.load( QUrl.fromUserInput('%s?file=%s' % (self.pdf_js_path, pdf_path))) if sys.platform == 'win32' and 'sample' not in pdf_path: if '/' in pdf_path: config.set('history_pdf', pdf_path.split('/')[-1].split('.')[0], pdf_path) else: config.set('history_pdf', pdf_path.split('\\')[-1].split('.')[0], pdf_path) config.write(open('CONFIG.ini', 'w'))
def handle_show_th_help(self): """Show RepTate current theory (if any) manual, or all theories""" try: app = self.ApplicationtabWidget.currentWidget() ds = app.DataSettabWidget.currentWidget() th = ds.theories[ds.current_theory] help_file = th.help_file except Exception as e: print('in "handle_show_help":', e) help_file = 'http://reptate.readthedocs.io/manual/All_Theories/All_Theories.html' QDesktopServices.openUrl(QUrl.fromUserInput((help_file)))
def getData(self): """ Public method to get the entered data. @return tuple with name and new URL of the remote repository @rtype tuple of (str, str) """ url = QUrl.fromUserInput(self.newUrlEdit.text()) if self.__userInfo: url.setUserInfo(self.__userInfo) return self.nameEdit.text(), url.toString()
def on_vcsUrlPicker_textChanged(self, txt): """ Private slot to handle changes of the URL. @param txt current text of the line edit (string) """ url = QUrl.fromUserInput(txt) enable = url.isValid() and url.scheme() in ConfigHgSchemes self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(enable) self.vcsUrlPicker.setPickerEnabled(url.scheme() == "file" or len(txt) == 0)
def on_vcsUrlCombo_editTextChanged(self, txt): """ Private slot to handle changes of the URL. @param txt current text of the combo box @type str """ url = QUrl.fromUserInput(txt) enable = url.isValid() and url.scheme() in ConfigGitSchemes self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(enable) self.vcsUrlButton.setEnabled(url.scheme() == "file" or len(txt) == 0)
def changeStyle(self, index): """ Object method Params: int index -> the index of the active tab Return: None Changes the style applied to the HTML files, using the index of the active tab. This method is called each time the active tab is changed. This applies a soft StyleSheet change (the HTML files are not modified). """ new_name = "'" + QUrl.fromUserInput(os.path.realpath(self._styles[index]._path)).url() + "'" StyleHandler.setStyle(self._chosen_file.toLocalFile(), new_name) self.tab_bar.widget(index).load(self._chosen_file) old_name = new_name
def get_help_url(self, app, help_path): """ Parses a help path and returns the url for this path. :param str help_path: the path for the help, split by spaces :param BasicApp app: the app which is currently opened :return: """ file_name, path = self.split_path(help_path) help_fragment = self.get_help_fragment(app, help_path) app_local_path = os.path.join(app.module_path(), "db", "help", file_name)+".html" app_local_url = QUrl.fromUserInput(app_local_path) if os.path.exists(app_local_path): app_local_url.setFragment(help_fragment) return app_local_url global_help_path = os.path.join(self.dice.application_dir, "db", "help", file_name)+".html" global_help_url = QUrl.fromUserInput(global_help_path) if os.path.exists(global_help_path): global_help_url.setFragment(help_fragment) return global_help_url return ""
def accept(self): if self.txtName.text().strip() == "": QMessageBox.information(self, self.windowTitle(), self.tr("请填写网络链接的名称。")) self.txtName.setFocus(Qt.OtherFocusReason) return if self.txtLink.text().strip() == "": QMessageBox.information(self, self.windowTitle(), self.tr("请填写网络链接的地址。")) self.txtLink.setFocus(Qt.OtherFocusReason) return url = QUrl.fromUserInput(self.txtLink.text().strip()) if not url.isValid(): QMessageBox.information(self, self.windowTitle(), self.tr("您填写的似乎不是正确的网络链接地址。")) self.txtLink.setFocus(Qt.OtherFocusReason) self.txtLink.selectAll() return QDialog.accept(self)
def runShortcut(self, index): if not index.isValid(): return False shortcut = self.shortcuts[index.row()] if shortcut["path"].startswith("special://"): if shortcut["path"] == COMPUTER_PATH: if os.name == "nt": explorer = os.path.join(os.environ["SystemRoot"], "explorer.exe") return QProcess.startDetached(explorer, ["::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"]) else: path = "/" elif shortcut["path"] == DOCUMENTS_PATH: path = QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation) elif shortcut["path"] == MUSIC_PATH: path = QStandardPaths.writableLocation(QStandardPaths.MusicLocation) elif shortcut["path"] == PICTURES_PATH: path = QStandardPaths.writableLocation(QStandardPaths.PicturesLocation) else: return False if os.name == "nt": #针对windows进行优化 explorer = os.path.join(os.environ["SystemRoot"], "explorer.exe") return QProcess.startDetached(explorer, [path]) else: return QDesktopServices.openUrl(QUrl.fromLocalFile(path)) else: currentDirectory = os.getcwd() try: if shortcut["dir"] is not None and shortcut["dir"] != "": os.chdir(shortcut["dir"]) if shortcut["openwith"] is not None and shortcut["openwith"] != "": if not os.path.exists(shortcut["openwith"]): return False return QProcess.startDetached(shortcut["openwith"], [shortcut["path"]]) else: url = QUrl.fromUserInput(shortcut["path"]) if not url.isValid(): return False if url.scheme() == "file" and not os.path.exists(url.toLocalFile()): return False return QDesktopServices.openUrl(url) except OSError: #raised by chdir() pass finally: os.chdir(currentDirectory) return False
def editShortcut(self): index = self.listView.currentIndex() if not index.isValid(): return shortcut = self.quickDesktopModel.shortcutAt(index) url = QUrl.fromUserInput(shortcut["path"]) if not url.isValid(): return if url.scheme() == "special": QMessageBox.information(self, self.tr("编辑快捷方式"), self.tr("不能编辑特殊图标。")) return elif url.scheme() == "file": d = ShortcutDialog(self) else: d = BookmarkDialog(self) if self.window().runDialog(d.edit, shortcut) == QDialog.Accepted: shortcut.update(d.getResult()) self.quickDesktopModel.updateShortcut(shortcut, index) d.deleteLater()
def getShortcutIcon(shortcut): if shortcut["icon"]: icon = QIcon(shortcut["icon"]) if not icon.isNull(): return icon iconProvider = QFileIconProvider() if shortcut["path"] == COMPUTER_PATH: return QIcon(":/images/user-home.png") elif shortcut["path"] == DOCUMENTS_PATH: documentsIcon = iconProvider.icon(QFileInfo(QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation))) if documentsIcon.isNull(): return QIcon(":/images/folder-documents.png") else: return documentsIcon elif shortcut["path"] == MUSIC_PATH: musicIcon = iconProvider.icon(QFileInfo(QStandardPaths.writableLocation(QStandardPaths.MusicLocation))) if musicIcon.isNull(): return QIcon(":/images/folder-sound.png") else: return musicIcon elif shortcut["path"] == PICTURES_PATH: picturesIcon = iconProvider.icon(QFileInfo(QStandardPaths.writableLocation(QStandardPaths.PicturesLocation))) if picturesIcon.isNull(): return QIcon(":/images/folder-image.png") else: return picturesIcon else: url = QUrl.fromUserInput(shortcut["path"]) if url.scheme() == "file": if os.path.exists(shortcut["path"]): icon = iconProvider.icon(QFileInfo(url.toLocalFile())) if not icon.isNull(): return icon return QIcon(":/images/unknown.png") else: return QIcon(":/images/httpurl.png") return QIcon(":/images/unknown.png")
def initUI(self): """ Object method Params: None Return: None This method initializes the layout of the StyleScreen. The tab bar is created, a new tab is created for each stylesheet registered by the application. The tab bar has closable and renamable tabs (see editable_tabs module). A push button is created below the tab bar. """ vbox = QVBoxLayout() self.tab_bar = EditableTabWidget(self) self.tab_bar.setTabsClosable(True) self.tab_bar.tabCloseRequested[int].connect(self._styles.pop) self.tab_bar.currentChanged[int].connect(self.changeStyle) template = list() path = random.choice(self.parent()._files._htmlFiles) self._chosen_file = QUrl.fromUserInput(path) for i in range(len(self._styles)): # QWebview creation template.append(WebView(self)) template[i].load(self._chosen_file) # Tab creation self.tab_bar.addTab(template[i], self._styles[i]._name); if self._styles[i]._user_style == False: self.tab_bar.tabBar().tabButton(i, QTabBar.RightSide).resize(0,0) button = QPushButton(CONFIRM_BUTTON_NAME, self) button.clicked.connect(self.confirm) vbox.addWidget(self.tab_bar) vbox.addWidget(button) self.setLayout(vbox)
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_())
fileName = "%s_frame%s%s" % (fileName[:index], self._frameCounter, fileName[index:]) image = QImage(frame.contentsSize(), QImage.Format_ARGB32_Premultiplied) image.fill(Qt.transparent) painter = QPainter(image) painter.setRenderHint(QPainter.Antialiasing, True) painter.setRenderHint(QPainter.TextAntialiasing, True) painter.setRenderHint(QPainter.SmoothPixmapTransform, True) frame.documentElement().render(painter) painter.end() image.save(fileName) self._frameCounter += 1 for childFrame in frame.childFrames(): self.saveFrame(childFrame) if __name__ == '__main__': if len(sys.argv) != 3: cerr(__doc__) sys.exit(1) url = QUrl.fromUserInput(sys.argv[1]) fileName = sys.argv[2] app = QApplication(sys.argv) capture = FrameCapture() capture.finished.connect(app.quit) capture.load(url, fileName) app.exec_()
parser = argparse.ArgumentParser() parser.add_argument('url', help='The URL to open') parser.add_argument('--plugins', '-p', help='Enable plugins', default=False, action='store_true') if WEBENGINE: parser.add_argument('--webengine', help='Use QtWebEngine', default=False, action='store_true') return parser.parse_args() if __name__ == '__main__': args = parse_args() app = QApplication(sys.argv) if WEBENGINE and args.webengine: wv = QWebEngineView() else: wv = QWebView() wv.loadStarted.connect(lambda: print("Loading started")) wv.loadProgress.connect(lambda p: print("Loading progress: {}%".format(p))) wv.loadFinished.connect(lambda: print("Loading finished")) if args.plugins and not WEBENGINE: wv.settings().setAttribute(QWebSettings.PluginsEnabled, True) wv.load(QUrl.fromUserInput(args.url)) wv.show() app.exec_()
def addTab(self, url="about:blank"): if url == "--app": win = MainWindow(appMode=True) win.addTab(url="about:blank") win.show() return url else: for window in browser.windows[::-1]: if window.isVisible(): window.addTab(url=url) if not (window.tabWidget().widget(0).history().canGoBack() or window.tabWidget().widget(0).history().canGoForward()) and window.tabWidget().widget(0).url().toString() in ("about:blank", "", QUrl.fromUserInput(settings.new_tab_page).toString(),): window.removeTab(0) browser.windows[-1].activateWindow() return url self.addWindow(url) browser.windows[-1].activateWindow() return url
def setGitHubSite(self): url = QInputDialog.getText(self, "Githost", "Enter the URL of your project page here:") if url[1]: settings.setValue("settings/GitUrl", url[0]) self.webView.load(QUrl.fromUserInput(settings.value("settings/GitUrl"))) settings.sync()
def createRequest(self, op, request, device=None): url = request.url() ctype = str(request.header(QNetworkRequest.ContentTypeHeader)) urlString = url.toString() lurlString = urlString.lower() x = filtering.adblock_filter.match(urlString) y = url.authority() in filtering.host_rules if settings.setting_to_bool("content/HostFilterEnabled") and url.authority() != "" else False z = (lurlString.endswith(".swf") or "flash" in ctype) and not settings.setting_to_bool("content/FlashEnabled") aa = (lurlString.endswith(".gif") or "image/gif" in ctype) and not settings.setting_to_bool("content/GIFsEnabled") if x != None or y or z or aa: return QNetworkAccessManager.createRequest(self, self.GetOperation, QNetworkRequest(QUrl(random.choice(("http://www.randomkittengenerator.com/images/cats/rotator.php", "http://thecatapi.com/api/images/get?format=src&type=png&size=small")) if settings.setting_to_bool("content/KittensEnabled") else "data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw=="))) if urlString in tuple(replacement_table.keys()): return QNetworkAccessManager.createRequest(self, op, QNetworkRequest(QUrl(replacement_table[urlString])), device) if url.scheme() == "file" and os.path.isdir(os.path.abspath(url.path())): try: html = directoryView % {"title": urlString, "heading": url.path(), "links": "".join(["<a href=\"%s\">%s</a><br/>" % (QUrl.fromUserInput(os.path.join(urlString, path)).toString(), path,) for path in [".."] + sorted(os.listdir(os.path.abspath(url.path())))])} except: html = directoryView % {"title": urlString, "heading": url.path(), "links": tr("The contents of this directory could not be loaded.")} return NetworkReply(self, url, self.GetOperation, html) if url.scheme() == "nimbus-extension": request.setUrl(QUrl("http://127.0.0.1:8133/" + stringfunctions.chop(url.toString(QUrl.RemoveScheme), "//"))) return QNetworkAccessManager.createRequest(self, op, request, device) if url.scheme() == "nimbus": request.setUrl(QUrl("file://%s/" % (paths.app_folder,) + stringfunctions.chop(url.toString(QUrl.RemoveScheme), "//"))) return self.createRequest(op, request, device) if url.scheme() == "nimbus-settings": request.setUrl(QUrl("file://%s/" % (settings.settings_folder,) + stringfunctions.chop(url.toString(QUrl.RemoveScheme), "//"))) return self.createRequest(op, request, device) if url.scheme() == "apt": os.system("xterm -e \"sudo apt-get install %s\" &" % (stringfunctions.chop(url.toString(QUrl.RemoveScheme), "//").split("&")[0],)) return QNetworkAccessManager.createRequest(self, self.GetOperation, QNetworkRequest(QUrl(""))) if url.scheme() == "mailto": QDesktopServices.openUrl(url) return QNetworkAccessManager.createRequest(self, self.GetOperation, QNetworkRequest(QUrl(""))) else: return QNetworkAccessManager.createRequest(self, op, request, device)
def transform(self, value): if not value: return None else: return QUrl.fromUserInput(value)
def load(self, url): self._percent = 0 self._url = QUrl.fromUserInput(url) self._page.mainFrame().load(self._url) self._page.setViewportSize(QSize(1920, 10000)) print("Loading... %s" % url)
def changeLocation(self): url = QUrl.fromUserInput(self.locationEdit.text()) self.view.load(url) self.view.setFocus()
def transform(self, value): if not value: return None else: return [QUrl.fromUserInput(v) if v else None for v in value.split(',')]
def on_pushButton_Go_clicked(self): url = QUrl.fromUserInput(self.lineEdit_AddressBar.text()) self.webView.load(url)