def __init__(self, parent=None): """Initialize QWebView.""" super(WebView, self).__init__(parent) self.setStyleSheet("background-color: transparent") QNetworkProxyFactory.setUseSystemConfiguration(True) settings, temporary_directory = self.settings(), mkdtemp() settings.setDefaultTextEncoding("utf-8") settings.setIconDatabasePath(temporary_directory) settings.setLocalStoragePath(temporary_directory) settings.setOfflineStoragePath(temporary_directory) settings.setMaximumPagesInCache(settings.maximumPagesInCache() * 2) settings.setOfflineWebApplicationCachePath(temporary_directory) settings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True) settings.setAttribute(QWebSettings.LocalStorageEnabled, True) settings.setAttribute(QWebSettings.OfflineStorageDatabaseEnabled, True) settings.setAttribute(QWebSettings.PluginsEnabled, True) settings.setAttribute(QWebSettings.DnsPrefetchEnabled, True) settings.setAttribute(QWebSettings.JavascriptCanOpenWindows, True) settings.setAttribute(QWebSettings.JavascriptCanCloseWindows, True) settings.setAttribute(QWebSettings.JavascriptCanAccessClipboard, True) settings.setAttribute(QWebSettings.SpatialNavigationEnabled, True) settings.setAttribute(QWebSettings.PrivateBrowsingEnabled, True) settings.setAttribute(QWebSettings.LocalContentCanAccessFileUrls, True) settings.setAttribute(QWebSettings.CSSGridLayoutEnabled, True) settings.setAttribute(QWebSettings.ScrollAnimatorEnabled, True) settings.setAttribute(QWebSettings.LocalContentCanAccessRemoteUrls, True) settings.setAttribute(QWebSettings.OfflineWebApplicationCacheEnabled, True) self.setHtml(HTML_PLACEHOLDER.strip(), QUrl("http://127.0.0.1:8000/")) settings.setUserStyleSheetUrl( QUrl( # HTML Transparent Background. "data:text/css;charset=utf-8;base64," "Ym9keXtiYWNrZ3JvdW5kOnRyYW5zcGFyZW50fQ==")) self.page().setForwardUnsupportedContent(True)
def __init__(self, url, parent=None): super(WebBrowser, self).__init__(parent) self.progress = 0 fd = QFile(":/jquery.min.js") if fd.open(QIODevice.ReadOnly | QFile.Text): self.jQuery = QTextStream(fd).readAll() fd.close() else: self.jQuery = '' QNetworkProxyFactory.setUseSystemConfiguration(True) self.view = QWebEngineView(self) self.view.load(QUrl(url)) self.view.loadFinished.connect(self.adjustLocation) self.view.titleChanged.connect(self.adjustTitle) self.view.loadProgress.connect(self.setProgress) self.view.loadFinished.connect(self.finishLoading) self.locationEdit = QLineEdit(self) self.locationEdit.setSizePolicy( QSizePolicy.Expanding, self.locationEdit.sizePolicy().verticalPolicy()) self.locationEdit.returnPressed.connect(self.changeLocation) toolBar = self.addToolBar("Navigation") toolBar.addAction(self.view.pageAction(QWebEnginePage.Back)) toolBar.addAction(self.view.pageAction(QWebEnginePage.Forward)) toolBar.addAction(self.view.pageAction(QWebEnginePage.Reload)) toolBar.addAction(self.view.pageAction(QWebEnginePage.Stop)) toolBar.addWidget(self.locationEdit) viewMenu = self.menuBar().addMenu("&View") viewSourceAction = QAction("Page Source", self) viewSourceAction.triggered.connect(self.viewSource) viewMenu.addAction(viewSourceAction) effectMenu = self.menuBar().addMenu("&Effect") effectMenu.addAction("Highlight all links", self.highlightAllLinks) self.rotateAction = QAction(self.style().standardIcon( QStyle.SP_FileDialogDetailedView), "Turn images upside down", self, checkable=True, toggled=self.rotateImages) effectMenu.addAction(self.rotateAction) toolsMenu = self.menuBar().addMenu("&Tools") toolsMenu.addAction("Remove GIF images", self.removeGifImages) toolsMenu.addAction("Remove all inline frames", self.removeInlineFrames) toolsMenu.addAction("Remove all object elements", self.removeObjectElements) toolsMenu.addAction("Remove all embedded elements", self.removeEmbeddedElements) self.setCentralWidget(self.view)
def __init__(self, parent=None): """Initialize QWebView.""" super(WebView, self).__init__(parent) self.setStyleSheet("background-color: transparent") QNetworkProxyFactory.setUseSystemConfiguration(True) settings, temporary_directory = self.settings(), mkdtemp() settings.setDefaultTextEncoding("utf-8") settings.setIconDatabasePath(temporary_directory) settings.setLocalStoragePath(temporary_directory) settings.setOfflineStoragePath(temporary_directory) settings.setMaximumPagesInCache(settings.maximumPagesInCache() * 2) settings.setOfflineWebApplicationCachePath(temporary_directory) settings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True) settings.setAttribute(QWebSettings.LocalStorageEnabled, True) settings.setAttribute(QWebSettings.OfflineStorageDatabaseEnabled, True) settings.setAttribute(QWebSettings.PluginsEnabled, True) settings.setAttribute(QWebSettings.DnsPrefetchEnabled, True) settings.setAttribute(QWebSettings.JavascriptCanOpenWindows, True) settings.setAttribute(QWebSettings.JavascriptCanCloseWindows, True) settings.setAttribute(QWebSettings.JavascriptCanAccessClipboard, True) settings.setAttribute(QWebSettings.SpatialNavigationEnabled, True) settings.setAttribute(QWebSettings.PrivateBrowsingEnabled, True) settings.setAttribute(QWebSettings.LocalContentCanAccessFileUrls, True) settings.setAttribute(QWebSettings.CSSGridLayoutEnabled, True) settings.setAttribute(QWebSettings.ScrollAnimatorEnabled, True) settings.setAttribute( QWebSettings.LocalContentCanAccessRemoteUrls, True) settings.setAttribute( QWebSettings.OfflineWebApplicationCacheEnabled, True) self.setHtml(HTML_PLACEHOLDER.strip(), QUrl("http://127.0.0.1:8000/")) settings.setUserStyleSheetUrl(QUrl( # HTML Transparent Background. "data:text/css;charset=utf-8;base64," "Ym9keXtiYWNrZ3JvdW5kOnRyYW5zcGFyZW50fQ==")) self.page().setForwardUnsupportedContent(True)
def init(): """Set the application wide proxy factory.""" proxy_factory = ProxyFactory() objreg.register('proxy-factory', proxy_factory) QNetworkProxyFactory.setApplicationProxyFactory(proxy_factory) config.instance.changed.connect(_warn_for_pac) _warn_for_pac()
def init(): """Set the application wide proxy factory.""" global application_factory application_factory = ProxyFactory() QNetworkProxyFactory.setApplicationProxyFactory(application_factory) config.instance.changed.connect(_warn_for_pac) _warn_for_pac()
def main(): if markups.__version_tuple__ < (2, ): sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.') # If we're running on Windows without a console, then discard stdout # and save stderr to a file to facilitate debugging in case of crashes. if sys.executable.endswith('pythonw.exe'): sys.stdout = open(devnull, 'w') sys.stderr = open('stderr.log', 'w') app = QApplication(sys.argv) app.setOrganizationName("ReText project") app.setApplicationName("ReText") app.setApplicationDisplayName("ReText") app.setApplicationVersion(app_version) app.setOrganizationDomain('mitya57.me') if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7 app.setDesktopFileName('me.mitya57.ReText.desktop') QNetworkProxyFactory.setUseSystemConfiguration(True) RtTranslator = QTranslator() for path in datadirs: if RtTranslator.load('retext_' + globalSettings.uiLanguage, join(path, 'locale')): break QtTranslator = QTranslator() QtTranslator.load("qtbase_" + globalSettings.uiLanguage, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(RtTranslator) app.installTranslator(QtTranslator) print('Using configuration file:', settings.fileName()) if globalSettings.appStyleSheet: sheetfile = QFile(globalSettings.appStyleSheet) sheetfile.open(QIODevice.ReadOnly) app.setStyleSheet(QTextStream(sheetfile).readAll()) sheetfile.close() window = ReTextWindow() window.show() # ReText can change directory when loading files, so we # need to have a list of canonical names before loading fileNames = list(map(canonicalize, sys.argv[1:])) previewMode = False for fileName in fileNames: if QFile.exists(fileName): window.openFileWrapper(fileName) if previewMode: window.actionPreview.setChecked(True) window.preview(True) elif fileName == '--preview': previewMode = True if globalSettings.openLastFilesOnStartup: window.restoreLastOpenedFiles() inputData = '' if (sys.stdin is None or sys.stdin.isatty()) else sys.stdin.read() if inputData or not window.tabWidget.count(): window.createNew(inputData) signal.signal(signal.SIGINT, lambda sig, frame: window.close()) sys.exit(app.exec())
def __init__(self, url): super(MainWindow, self).__init__() self.progress = 0 fd = QFile(":/jquery.min.js") if fd.open(QIODevice.ReadOnly | QFile.Text): self.jQuery = QTextStream(fd).readAll() fd.close() else: self.jQuery = '' QNetworkProxyFactory.setUseSystemConfiguration(True) self.view = QWebView(self) self.view.load(url) self.view.loadFinished.connect(self.adjustLocation) self.view.titleChanged.connect(self.adjustTitle) self.view.loadProgress.connect(self.setProgress) self.view.loadFinished.connect(self.finishLoading) self.locationEdit = QLineEdit(self) self.locationEdit.setSizePolicy(QSizePolicy.Expanding, self.locationEdit.sizePolicy().verticalPolicy()) self.locationEdit.returnPressed.connect(self.changeLocation) toolBar = self.addToolBar("Navigation") toolBar.addAction(self.view.pageAction(QWebPage.Back)) toolBar.addAction(self.view.pageAction(QWebPage.Forward)) toolBar.addAction(self.view.pageAction(QWebPage.Reload)) toolBar.addAction(self.view.pageAction(QWebPage.Stop)) toolBar.addWidget(self.locationEdit) viewMenu = self.menuBar().addMenu("&View") viewSourceAction = QAction("Page Source", self) viewSourceAction.triggered.connect(self.viewSource) viewMenu.addAction(viewSourceAction) effectMenu = self.menuBar().addMenu("&Effect") effectMenu.addAction("Highlight all links", self.highlightAllLinks) self.rotateAction = QAction( self.style().standardIcon(QStyle.SP_FileDialogDetailedView), "Turn images upside down", self, checkable=True, toggled=self.rotateImages) effectMenu.addAction(self.rotateAction) toolsMenu = self.menuBar().addMenu("&Tools") toolsMenu.addAction("Remove GIF images", self.removeGifImages) toolsMenu.addAction("Remove all inline frames", self.removeInlineFrames) toolsMenu.addAction("Remove all object elements", self.removeObjectElements) toolsMenu.addAction("Remove all embedded elements", self.removeEmbeddedElements) self.setCentralWidget(self.view)
def shutdown(self): """ Public method to shut down the network manager. """ self.__saveTimer.saveIfNeccessary() self.__loaded = False self.__temporarilyIgnoredSslErrors = {} self.__permanentlyIgnoredSslErrors = {} # set proxy factory to None to avoid crashes QNetworkProxyFactory.setApplicationProxyFactory(None)
def main(): if markups.__version_tuple__ < (2, ): sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.') # If we're running on Windows without a console, then discard stdout # and save stderr to a file to facilitate debugging in case of crashes. if sys.executable.endswith('pythonw.exe'): sys.stdout = open(devnull, 'w') sys.stderr = open('stderr.log', 'w') app = QApplication(sys.argv) app.setOrganizationName("ReText project") app.setApplicationName("ReText") app.setApplicationDisplayName("ReText") app.setApplicationVersion(app_version) app.setOrganizationDomain('mitya57.me') if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7 app.setDesktopFileName('me.mitya57.ReText.desktop') QNetworkProxyFactory.setUseSystemConfiguration(True) RtTranslator = QTranslator() for path in datadirs: if RtTranslator.load('retext_' + globalSettings.uiLanguage, join(path, 'locale')): break QtTranslator = QTranslator() QtTranslator.load("qt_" + globalSettings.uiLanguage, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(RtTranslator) app.installTranslator(QtTranslator) print('Using configuration file:', settings.fileName()) if globalSettings.appStyleSheet: sheetfile = QFile(globalSettings.appStyleSheet) sheetfile.open(QIODevice.ReadOnly) app.setStyleSheet(QTextStream(sheetfile).readAll()) sheetfile.close() window = ReTextWindow() window.show() # ReText can change directory when loading files, so we # need to have a list of canonical names before loading fileNames = list(map(canonicalize, sys.argv[1:])) previewMode = False for fileName in fileNames: if QFile.exists(fileName): window.openFileWrapper(fileName) if previewMode: window.actionPreview.setChecked(True) window.preview(True) elif fileName == '--preview': previewMode = True inputData = '' if (sys.stdin is None or sys.stdin.isatty()) else sys.stdin.read() if inputData or not window.tabWidget.count(): window.createNew(inputData) signal.signal(signal.SIGINT, lambda sig, frame: window.close()) sys.exit(app.exec())
def __init__(self, *args): """Initialize QPDF.""" super(QPDF, self).__init__(*args) self.web, self.pdf_name = QWebView(), uuid4().hex + ".pdf" self.to_pdf, self.url_or_path = self.convert_to_pdf, None self.setPageSize(QPrinter.A4) self.setFontEmbeddingEnabled(True) self.setOutputFormat(QPrinter.PdfFormat) self.web.settings().setDefaultTextEncoding("utf-8") QNetworkProxyFactory.setUseSystemConfiguration(True) self.setPageMargins(10, 10, 10, 10, QPrinter.Millimeter) self.web.loadFinished.connect(lambda: self.web.print_(self))
def __init__(self, url): super(QMainWindow, self).__init__() self.progress = 0 QNetworkProxyFactory.setUseSystemConfiguration(True) self.generateView(url) self.editLocation() self.generateToolBar() self.generateViewMenu() self.generateEffectMenu() self.generateToolsMenu() self.setCentralWidget(self.view)
def queryProxy(self, query): """Get the QNetworkProxies for a query. Args: query: The QNetworkProxyQuery to get a proxy for. Return: A list of QNetworkProxy objects in order of preference. """ proxy = config.val.content.proxy if proxy is configtypes.SYSTEM_PROXY: # On Linux, use "export http_proxy=socks5://host:port" to manually # set system proxy. # ref. http://doc.qt.io/qt-5/qnetworkproxyfactory.html#systemProxyForQuery proxies = QNetworkProxyFactory.systemProxyForQuery(query) elif isinstance(proxy, pac.PACFetcher): if objects.backend == usertypes.Backend.QtWebEngine: # Looks like query.url() is always invalid on QtWebEngine... proxies = [urlutils.proxy_from_url(QUrl('direct://'))] else: proxies = proxy.resolve(query) else: proxies = [proxy] for p in proxies: if p.type() != QNetworkProxy.NoProxy: capabilities = p.capabilities() if config.val.content.proxy_dns_requests: capabilities |= QNetworkProxy.HostNameLookupCapability else: capabilities &= ~QNetworkProxy.HostNameLookupCapability p.setCapabilities(capabilities) return proxies
def queryProxy(self, query): """Get the QNetworkProxies for a query. Args: query: The QNetworkProxyQuery to get a proxy for. Return: A list of QNetworkProxy objects in order of preference. """ proxy = config.val.content.proxy if proxy is configtypes.SYSTEM_PROXY: # On Linux, use "export http_proxy=socks5://host:port" to manually # set system proxy. # ref. https://doc.qt.io/qt-5/qnetworkproxyfactory.html#systemProxyForQuery proxies = QNetworkProxyFactory.systemProxyForQuery(query) elif isinstance(proxy, pac.PACFetcher): if objects.backend == usertypes.Backend.QtWebEngine: # Looks like query.url() is always invalid on QtWebEngine... proxy = urlutils.proxy_from_url(QUrl('direct://')) assert not isinstance(proxy, pac.PACFetcher) proxies = [proxy] elif objects.backend == usertypes.Backend.QtWebKit: proxies = proxy.resolve(query) else: raise utils.Unreachable(objects.backend) else: proxies = [proxy] for proxy in proxies: self._set_capabilities(proxy) return proxies
def queryProxy(self, query): """Get the QNetworkProxies for a query. Args: query: The QNetworkProxyQuery to get a proxy for. Return: A list of QNetworkProxy objects in order of preference. """ proxy = config.get('network', 'proxy') if proxy is configtypes.SYSTEM_PROXY: proxies = QNetworkProxyFactory.systemProxyForQuery(query) elif isinstance(proxy, pac.PACFetcher): proxies = proxy.resolve(query) else: proxies = [proxy] for p in proxies: if p.type() != QNetworkProxy.NoProxy: capabilities = p.capabilities() if config.get('network', 'proxy-dns-requests'): capabilities |= QNetworkProxy.HostNameLookupCapability else: capabilities &= ~QNetworkProxy.HostNameLookupCapability p.setCapabilities(capabilities) return proxies
def queryProxy(self, query): """Get the QNetworkProxies for a query. Args: query: The QNetworkProxyQuery to get a proxy for. Return: A list of QNetworkProxy objects in order of preference. """ proxy = config.val.content.proxy if proxy is configtypes.SYSTEM_PROXY: proxies = QNetworkProxyFactory.systemProxyForQuery(query) elif isinstance(proxy, pac.PACFetcher): proxies = proxy.resolve(query) else: proxies = [proxy] for p in proxies: if p.type() != QNetworkProxy.NoProxy: capabilities = p.capabilities() if config.val.content.proxy_dns_requests: capabilities |= QNetworkProxy.HostNameLookupCapability else: capabilities &= ~QNetworkProxy.HostNameLookupCapability p.setCapabilities(capabilities) return proxies
def queryProxy(self, query): """Get the QNetworkProxies for a query. Args: query: The QNetworkProxyQuery to get a proxy for. Return: A list of QNetworkProxy objects in order of preference. """ proxy = config.val.content.proxy if proxy is configtypes.SYSTEM_PROXY: # On Linux, use "export http_proxy=socks5://host:port" to manually # set system proxy. # ref. http://doc.qt.io/qt-5/qnetworkproxyfactory.html#systemProxyForQuery proxies = QNetworkProxyFactory.systemProxyForQuery(query) elif isinstance(proxy, pac.PACFetcher): proxies = proxy.resolve(query) else: proxies = [proxy] for p in proxies: if p.type() != QNetworkProxy.NoProxy: capabilities = p.capabilities() if config.val.content.proxy_dns_requests: capabilities |= QNetworkProxy.HostNameLookupCapability else: capabilities &= ~QNetworkProxy.HostNameLookupCapability p.setCapabilities(capabilities) return proxies
def queryProxy(self, query): """Get the QNetworkProxies for a query. Args: query: The QNetworkProxyQuery to get a proxy for. Return: A list of QNetworkProxy objects in order of preference. """ proxy = config.val.content.proxy if proxy is configtypes.SYSTEM_PROXY: # On Linux, use "export http_proxy=socks5://host:port" to manually set system proxy # ref. http://doc.qt.io/qt-5/qnetworkproxyfactory.html#systemProxyForQuery proxies = QNetworkProxyFactory.systemProxyForQuery(query) elif isinstance(proxy, pac.PACFetcher): proxies = proxy.resolve(query) else: proxies = [proxy] for p in proxies: if p.type() != QNetworkProxy.NoProxy: capabilities = p.capabilities() if config.val.content.proxy_dns_requests: capabilities |= QNetworkProxy.HostNameLookupCapability else: capabilities &= ~QNetworkProxy.HostNameLookupCapability p.setCapabilities(capabilities) return proxies
def main(): app = QApplication(sys.argv) app.setOrganizationName("ReText project") app.setApplicationName("ReText") app.setApplicationDisplayName("ReText") app.setApplicationVersion(app_version) app.setOrganizationDomain('mitya57.me') if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7 app.setDesktopFileName('me.mitya57.ReText.desktop') QNetworkProxyFactory.setUseSystemConfiguration(True) RtTranslator = QTranslator() for path in datadirs: if RtTranslator.load('retext_' + globalSettings.uiLanguage, join(path, 'locale')): break QtTranslator = QTranslator() QtTranslator.load("qt_" + globalSettings.uiLanguage, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(RtTranslator) app.installTranslator(QtTranslator) if globalSettings.appStyleSheet: sheetfile = QFile(globalSettings.appStyleSheet) sheetfile.open(QIODevice.ReadOnly) app.setStyleSheet(QTextStream(sheetfile).readAll()) sheetfile.close() window = ReTextWindow() window.show() # ReText can change directory when loading files, so we # need to have a list of canonical names before loading fileNames = list(map(canonicalize, sys.argv[1:])) previewMode = False for fileName in fileNames: if QFile.exists(fileName): window.openFileWrapper(fileName) if previewMode: window.actionPreview.setChecked(True) window.preview(True) elif fileName == '--preview': previewMode = True inputData = '' if sys.stdin.isatty() else sys.stdin.read() if inputData or not window.tabWidget.count(): window.createNew(inputData) signal.signal(signal.SIGINT, lambda sig, frame: window.close()) sys.exit(app.exec())
def main(): app = QApplication(sys.argv) app.setOrganizationName("ReText project") app.setApplicationName("ReText") app.setApplicationDisplayName("ReText") app.setApplicationVersion(app_version) app.setOrganizationDomain('mitya57.me') if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7 app.setDesktopFileName('me.mitya57.ReText.desktop') QNetworkProxyFactory.setUseSystemConfiguration(True) RtTranslator = QTranslator() for path in datadirs: if RtTranslator.load('retext_' + globalSettings.uiLanguage, join(path, 'locale')): break QtTranslator = QTranslator() QtTranslator.load("qt_" + globalSettings.uiLanguage, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(RtTranslator) app.installTranslator(QtTranslator) if globalSettings.appStyleSheet: sheetfile = QFile(globalSettings.appStyleSheet) sheetfile.open(QIODevice.ReadOnly) app.setStyleSheet(QTextStream(sheetfile).readAll()) sheetfile.close() window = ReTextWindow() window.show() # ReText can change directory when loading files, so we # need to have a list of canonical names before loading fileNames = list(map(canonicalize, sys.argv[1:])) previewMode = False for fileName in fileNames: if QFile.exists(fileName): window.openFileWrapper(fileName) if previewMode: window.actionPreview.trigger() elif fileName == '--preview': previewMode = True if sys.stdin: inputData = '' if sys.stdin.isatty() else sys.stdin.read() if inputData or not window.tabWidget.count(): window.createNew(inputData) signal.signal(signal.SIGINT, lambda sig, frame: window.close()) sys.exit(app.exec())
def __init__(self, engine, parent=None): """ Constructor @param engine reference to the help engine (QHelpEngine) @param parent reference to the parent object (QObject) """ super(NetworkManager, self).__init__(parent) from E5Network.E5NetworkProxyFactory import E5NetworkProxyFactory self.__proxyFactory = E5NetworkProxyFactory() if Preferences.getUI("UseSystemProxy"): QNetworkProxyFactory.setUseSystemConfiguration(True) else: QNetworkProxyFactory.setApplicationProxyFactory( self.__proxyFactory) QNetworkProxyFactory.setUseSystemConfiguration(False) self.languagesChanged() if SSL_AVAILABLE: self.__sslErrorHandler = E5SslErrorHandler(self) self.sslErrors.connect(self.__sslErrorHandler.sslErrorsReplySlot) self.__temporarilyIgnoredSslErrors = {} self.__permanentlyIgnoredSslErrors = {} # dictionaries of permanently and temporarily ignored SSL errors self.__loaded = False self.__saveTimer = AutoSaver(self, self.__save) self.changed.connect(self.__saveTimer.changeOccurred) self.proxyAuthenticationRequired.connect(proxyAuthenticationRequired) self.authenticationRequired.connect( lambda reply, auth: self.authentication(reply.url(), auth)) from .EricSchemeHandler import EricSchemeHandler self.__ericSchemeHandler = EricSchemeHandler() WebBrowserWindow.webProfile().installUrlSchemeHandler( QByteArray(b"eric"), self.__ericSchemeHandler) if engine: from .QtHelpSchemeHandler import QtHelpSchemeHandler self.__qtHelpSchemeHandler = QtHelpSchemeHandler(engine) WebBrowserWindow.webProfile().installUrlSchemeHandler( QByteArray(b"qthelp"), self.__qtHelpSchemeHandler) self.__interceptor = NetworkUrlInterceptor(self) try: WebBrowserWindow.webProfile().setUrlRequestInterceptor( self.__interceptor) except AttributeError: # Qt < 5.13 WebBrowserWindow.webProfile().setRequestInterceptor( self.__interceptor) WebBrowserWindow.cookieJar()
def queryProxy(self, query): """Get the QNetworkProxies for a query. Args: query: The QNetworkProxyQuery to get a proxy for. Return: A list of QNetworkProxy objects in order of preference. """ proxy = config.get('network', 'proxy') if proxy is configtypes.SYSTEM_PROXY: return QNetworkProxyFactory.systemProxyForQuery(query) else: return [proxy]
def queryProxy(self, query): if self.CUSTOM_PROXY is None: proxies = QNetworkProxyFactory.systemProxyForQuery(query) else: proxies = [self.CUSTOM_PROXY] for p in proxies: if p.type() != QNetworkProxy.NoProxy: capabilities = p.capabilities() if proxy_dns_requests.value: capabilities |= QNetworkProxy.HostNameLookupCapability else: capabilities &= ~QNetworkProxy.HostNameLookupCapability p.setCapabilities(capabilities) return proxies
def preferencesChanged(self): """ Public slot to handle a change of preferences. """ self.__interceptor.preferencesChanged() if Preferences.getUI("UseSystemProxy"): QNetworkProxyFactory.setUseSystemConfiguration(True) else: QNetworkProxyFactory.setApplicationProxyFactory( self.__proxyFactory) QNetworkProxyFactory.setUseSystemConfiguration(False)
def queryProxy(self, query): """Get the QNetworkProxies for a query. Args: query: The QNetworkProxyQuery to get a proxy for. Return: A list of QNetworkProxy objects in order of preference. """ proxy = config.get('network', 'proxy') if proxy is configtypes.SYSTEM_PROXY: proxies = QNetworkProxyFactory.systemProxyForQuery(query) else: proxies = [proxy] for p in proxies: if p.type() != QNetworkProxy.NoProxy: capabilities = p.capabilities() if config.get('network', 'proxy-dns-requests'): capabilities |= QNetworkProxy.HostNameLookupCapability else: capabilities &= ~QNetworkProxy.HostNameLookupCapability p.setCapabilities(capabilities) return proxies
def main(): multiprocessing.set_start_method('spawn') if markups.__version_tuple__ < (2, ): sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.') # If we're running on Windows without a console, then discard stdout # and save stderr to a file to facilitate debugging in case of crashes. if sys.executable.endswith('pythonw.exe'): sys.stdout = open(devnull, 'w') sys.stderr = open('stderr.log', 'w') try: # See https://github.com/retext-project/retext/issues/399 # and https://launchpad.net/bugs/941826 ctypes.CDLL('libGL.so.1', ctypes.RTLD_GLOBAL) except OSError: pass # Needed for Qt WebEngine on Windows QApplication.setAttribute(Qt.AA_ShareOpenGLContexts) app = QApplication(sys.argv) app.setOrganizationName("ReText project") app.setApplicationName("ReText") app.setApplicationDisplayName("ReText") app.setApplicationVersion(app_version) app.setOrganizationDomain('mitya57.me') if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7 app.setDesktopFileName('me.mitya57.ReText.desktop') QNetworkProxyFactory.setUseSystemConfiguration(True) initializeDataDirs() RtTranslator = QTranslator() for path in datadirs: if RtTranslator.load('retext_' + globalSettings.uiLanguage, join(path, 'locale')): break QtTranslator = QTranslator() QtTranslator.load("qtbase_" + globalSettings.uiLanguage, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(RtTranslator) app.installTranslator(QtTranslator) print('Using configuration file:', settings.fileName()) if globalSettings.appStyleSheet: sheetfile = QFile(globalSettings.appStyleSheet) sheetfile.open(QIODevice.ReadOnly) app.setStyleSheet(QTextStream(sheetfile).readAll()) sheetfile.close() window = ReTextWindow() window.show() # ReText can change directory when loading files, so we # need to have a list of canonical names before loading fileNames = list(map(canonicalize, sys.argv[1:])) previewMode = False readStdIn = False if globalSettings.openLastFilesOnStartup: window.restoreLastOpenedFiles() for fileName in fileNames: if QFile.exists(fileName): window.openFileWrapper(fileName) if previewMode: window.actionPreview.setChecked(True) window.preview(True) elif fileName == '--preview': previewMode = True elif fileName == '-': readStdIn = True inputData = '' if readStdIn and sys.stdin is not None: if sys.stdin.isatty(): print('Reading stdin, press ^D to end...') inputData = sys.stdin.read() if inputData or not window.tabWidget.count(): window.createNew(inputData) signal.signal(signal.SIGINT, lambda sig, frame: window.close()) sys.exit(app.exec())
def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") self.progress = 0 ## fd = QFile(":/jquery.min.js") ## ## if fd.open(QIODevice.ReadOnly | QFile.Text): ## self.jQuery = QTextStream(fd).readAll() ## fd.close() ## else: ## self.jQuery = '' MainWindow.resize(551, 467) ############################################################ QNetworkProxyFactory.setUseSystemConfiguration(True) # QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.HttpProxy, '192.168.1.107', 3128)) ############################################################ icon11 = QIcon() icon11.addPixmap(QPixmap("icons/option.png"), QIcon.Normal, QIcon.Off) MainWindow.setWindowIcon(icon11) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.horizontalLayout_4 = QHBoxLayout(self.centralwidget) self.horizontalLayout_4.setObjectName("horizontalLayout_4") self.verticalLayout_2 = QVBoxLayout() self.verticalLayout_2.setObjectName("verticalLayout_2") self.horizontalLayout_3 = QHBoxLayout() self.horizontalLayout_3.setObjectName("horizontalLayout_3") ###################################################################### self.tb_back = QToolButton(self.centralwidget) icon = QIcon() icon.addPixmap(QPixmap("icons/back.png"), QIcon.Active, QIcon.Off) self.tb_back.setIcon(icon) self.tb_back.setObjectName("tb_back") self.horizontalLayout_3.addWidget(self.tb_back) ############################## Enter ####################################### self.tb_back.clicked.connect(self.back) ############################################################################ self.tb_reload = QToolButton(self.centralwidget) icon1 = QIcon() icon1.addPixmap(QPixmap("icons/reload.png"), QIcon.Active, QIcon.Off) self.tb_reload.setIcon(icon1) self.tb_reload.setObjectName("tb_reload") self.horizontalLayout_3.addWidget(self.tb_reload) ############################## Enter ####################################### self.tb_reload.clicked.connect(self.reload) ############################################################################ self.tb_forword = QToolButton(self.centralwidget) icon2 = QIcon() icon2.addPixmap(QPixmap("icons/forword.png"), QIcon.Active, QIcon.Off) self.tb_forword.setIcon(icon2) self.tb_forword.setObjectName("tb_forword") self.horizontalLayout_3.addWidget(self.tb_forword) ############################## Enter ####################################### self.tb_forword.clicked.connect(self.forword) ############################################################################ self.tb_home = QToolButton(self.centralwidget) icon3 = QIcon() icon3.addPixmap(QPixmap("icons/home.png"), QIcon.Active, QIcon.Off) self.tb_home.setIcon(icon3) self.tb_home.setObjectName("tb_home") self.horizontalLayout_3.addWidget(self.tb_home) ############################## Enter ####################################### self.tb_home.clicked.connect(self.home) ############################################################################ self.line_edit = QLineEdit(self.centralwidget) self.line_edit.setObjectName("line_edit") self.horizontalLayout_3.addWidget(self.line_edit) ############################################################################ self.tb_search = QToolButton(self.centralwidget) icon4 = QIcon() icon4.addPixmap(QPixmap("icons/search.png"), QIcon.Active, QIcon.Off) self.tb_search.setIcon(icon4) self.tb_search.setObjectName("tb_search") self.horizontalLayout_3.addWidget(self.tb_search) ############################## Enter ####################################### self.tb_search.clicked.connect(self.search) ############################################################################ self.tb_newtab = QToolButton(self.centralwidget) icon5 = QIcon() icon5.addPixmap(QPixmap("icons/star.png"), QIcon.Active, QIcon.Off) self.tb_newtab.setIcon(icon5) self.tb_newtab.setObjectName("tb_newtab") self.horizontalLayout_3.addWidget(self.tb_newtab) self.verticalLayout_2.addLayout(self.horizontalLayout_3) self.webView = QWebView(self.centralwidget) self.webView.setUrl(QtCore.QUrl("about:blank")) self.webView.setObjectName("webView") self.verticalLayout_2.addWidget(self.webView) self.horizontalLayout_4.addLayout(self.verticalLayout_2) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow)
def __init__(self, parent=None): super(MainWindow, self).__init__() QNetworkProxyFactory.setUseSystemConfiguration(True) self.statusBar().showMessage(__doc__ + get_nuitka_version()) self.setWindowTitle(__doc__.strip().capitalize()) self.setMinimumSize(480, 400) self.setMaximumSize(1024, 800) self.resize(self.minimumSize()) self.setWindowIcon(QIcon.fromTheme("python")) self.center() QShortcut("Ctrl+q", self, activated=lambda: self.close()) self.menuBar().addMenu("&File").addAction("Exit", lambda: self.close()) windowMenu = self.menuBar().addMenu("&Window") windowMenu.addAction("Minimize", lambda: self.showMinimized()) windowMenu.addAction("Maximize", lambda: self.showMaximized()) windowMenu.addAction("Restore", lambda: self.showNormal()) windowMenu.addAction("FullScreen", lambda: self.showFullScreen()) windowMenu.addAction("Center", lambda: self.center()) windowMenu.addAction("Top-Left", lambda: self.move(0, 0)) windowMenu.addAction("To Mouse", lambda: self.move_to_mouse_position()) windowMenu.addSeparator() windowMenu.addAction( "Increase size", lambda: self.resize(self.size().width() * 1.4, self.size().height() * 1.4)) windowMenu.addAction("Decrease size", lambda: self.resize( self.size().width() // 1.4, self.size().height() // 1.4)) windowMenu.addAction("Minimum size", lambda: self.resize(self.minimumSize())) windowMenu.addAction("Maximum size", lambda: self.resize(self.maximumSize())) windowMenu.addAction("Horizontal Wide", lambda: self.resize( self.maximumSize().width(), self.minimumSize().height())) windowMenu.addAction("Vertical Tall", lambda: self.resize( self.minimumSize().width(), self.maximumSize().height())) windowMenu.addSeparator() windowMenu.addAction("Disable Resize", lambda: self.setFixedSize(self.size())) windowMenu.addAction("Set Interface Font...", lambda: self.setFont(QFontDialog.getFont()[0])) windowMenu.addAction( "Load .qss Skin", lambda: self.setStyleSheet(self.skin())) helpMenu = self.menuBar().addMenu("&Help") helpMenu.addAction("About Qt 5", lambda: QMessageBox.aboutQt(self)) helpMenu.addAction("About Python 3", lambda: open_new_tab('https://www.python.org')) helpMenu.addAction("About " + __doc__, lambda: QMessageBox.about(self, __doc__, HELP)) helpMenu.addSeparator() helpMenu.addAction( "Keyboard Shortcut", lambda: QMessageBox.information(self, __doc__, "<b>Quit = CTRL+Q")) if sys.platform.startswith('linux'): helpMenu.addAction("View Source Code", lambda: call('xdg-open ' + __file__, shell=True)) helpMenu.addAction("View GitHub Repo", lambda: open_new_tab(__url__)) helpMenu.addAction("Check Updates", lambda: Downloader(self)) # process self.process = QProcess() self.process.readyReadStandardOutput.connect(self._read_output) self.process.readyReadStandardError.connect(self._read_errors) self.process.finished.connect(self._process_finished) self.process.error.connect(self._process_failed) # widgets self.group0, self.group1 = QGroupBox("Options"), QGroupBox("Paths") self.group4, self.group5 = QGroupBox("Details"), QGroupBox("Miscs") g0grid, g1vlay = QGridLayout(self.group0), QGridLayout(self.group1) g5vlay, g4vlay = QVBoxLayout(self.group5), QVBoxLayout(self.group4) # group 0 the options self.module = QCheckBox("Create compiled extension module") self.standalone = QCheckBox("Standalone executable binary output") self.nofreeze = QCheckBox("No freeze all modules of standard library") self.python_debug = QCheckBox("Use Python Debug") self.warning = QCheckBox("Warnings for implicit exceptions at compile") self.recurse_std = QCheckBox("Recursive compile the standard library") self.recurse_not = QCheckBox("Force No recursive compiling") self.execute = QCheckBox("Execute the created binary after compiling") self.pythonpath = QCheckBox("Keep pythonpath when executing") self.enhaced = QCheckBox("Enhaced compile, Not CPython compatible") self.nolineno = QCheckBox("No Statements line numbers on compile") self.rmbuilddir = QCheckBox("Remove build directory after compile.") self.nuitka_debug = QCheckBox("Use Nuitka Debug") self.keep_debug = QCheckBox("Keep debug info on compile for GDB") self.traced = QCheckBox("Traced execution output") self.plusplus = QCheckBox("Compile C++ Only on generated source files") self.experimental = QCheckBox("Experimental features") self.force_clang = QCheckBox("Force use of CLang") self.force_mingw = QCheckBox("Force use of MinGW on MS Windows") self.force_lto = QCheckBox("Use link time optimizations LTO") self.show_scons = QCheckBox("Show Scons executed commands") self.show_progress = QCheckBox("Show progress info and statistics") self.show_summary = QCheckBox("Show final summary of included modules") self.disable_console = QCheckBox("Disable the Console on MS Windows") for i, widget in enumerate(( self.module, self.standalone, self.nofreeze, self.python_debug, self.warning, self.recurse_std, self.recurse_not, self.execute, self.pythonpath, self.enhaced, self.nolineno, self.rmbuilddir, self.nuitka_debug, self.keep_debug, self.traced, self.plusplus, self.experimental, self.force_clang, self.force_mingw, self.force_lto, self.show_scons, self.show_progress, self.show_summary, self.disable_console)): widget.setToolTip(widget.text()) g0grid.addWidget(widget, i if i < i + 1 else i - (i - 1), i % 2) # group 1 paths self.target = QLineEdit() self.outdir = QLineEdit(os.path.expanduser("~")) self.t_icon = QLineEdit() self.target.setToolTip("Python App file you want to Compile to Binary") self.outdir.setToolTip("Folder to write Compiled Output Binary files") self.t_icon.setToolTip("Icon image file to embed for your Python App") self.target.setPlaceholderText("/full/path/to/target/python_app.py") self.outdir.setPlaceholderText("/full/path/to/output/folder/") self.t_icon.setPlaceholderText("/full/path/to/python_app/icon.png") self.completer, self.dirs = QCompleter(self), QDirModel(self) self.completer.setModel(self.dirs) self.completer.setCaseSensitivity(Qt.CaseInsensitive) self.completer.setCompletionMode(QCompleter.PopupCompletion) self.completer.popup().setStyleSheet("border: 1px solid gray") self.completer.popup().setVerticalScrollBarPolicy( Qt.ScrollBarAlwaysOff) self.outdir.setCompleter(self.completer) self.t_icon.setCompleter(self.completer) self.target.setCompleter(self.completer) self.clear_1 = QPushButton(QIcon.fromTheme("edit-clear"), "", self, clicked=lambda: self.target.clear()) self.clear_2 = QPushButton(QIcon.fromTheme("edit-clear"), "", self, clicked=lambda: self.t_icon.clear()) self.clear_3 = QPushButton(QIcon.fromTheme("edit-clear"), "", self, clicked=lambda: self.outdir.clear()) self.open_1 = QPushButton( QIcon.fromTheme("folder-open"), "", self, clicked=lambda: self.target.setText(str(QFileDialog.getOpenFileName( self, __doc__, os.path.expanduser("~"), """Python (*.py);; Python for Windows (*.pyw);;All (*.*)""")[0]))) self.open_2 = QPushButton( QIcon.fromTheme("folder-open"), "", self, clicked=lambda: self.t_icon.setText(str(QFileDialog.getOpenFileName( self, __doc__, os.path.expanduser("~"), "PNG (*.png);;JPG (*.jpg);;ICO (*.ico);;All (*.*)")[0]))) self.open_3 = QPushButton( QIcon.fromTheme("folder-open"), "", self, clicked=lambda: self.outdir.setText(str(QFileDialog.getExistingDirectory( self, __doc__, os.path.expanduser("~"))))) self.l_icon = QLabel("Target Icon") g1vlay.addWidget(QLabel("<b>Target Python"), 0, 0) g1vlay.addWidget(self.target, 0, 1) g1vlay.addWidget(self.clear_1, 0, 2) g1vlay.addWidget(self.open_1, 0, 3) g1vlay.addWidget(self.l_icon, 1, 0) g1vlay.addWidget(self.t_icon, 1, 1) g1vlay.addWidget(self.clear_2, 1, 2) g1vlay.addWidget(self.open_2, 1, 3) g1vlay.addWidget(QLabel("<b>Output Folder"), 2, 0) g1vlay.addWidget(self.outdir, 2, 1) g1vlay.addWidget(self.clear_3, 2, 2) g1vlay.addWidget(self.open_3, 2, 3) # group 4 the dome view mode self.jobs = QSpinBox() self.jobs.setRange(1, cpu_count()) self.jobs.setValue(cpu_count()) self.jobs.setToolTip("Backend Worker Jobs Processes") self.python_version = QComboBox() self.python_version.addItems(["2.7", "3.2", "3.3", "3.4"]) self.python_version.setToolTip("Python version to use with Nuitka") self.display_tree = QPushButton("Display Tree") self.display_tree.clicked.connect( lambda: call(NUITKA + " --display-tree {}".format( self.target.text()), shell=True)) self.dump_tree = QPushButton( "View Docs", clicked=lambda: open_new_tab("http://nuitka.net/doc/user-manual.html")) self.open_log = QPushButton("View Logs") _log = os.path.join(gettempdir(), "nuitka-gui.log") _open = "xdg-open " if sys.platform.startswith("lin") else "open " self.open_log.clicked.connect(lambda: call(_open + _log, shell=True)) self.open_folder = QPushButton("Open Build Folder") self.open_folder.clicked.connect(lambda: call( _open + str(self.outdir.text()).strip(), shell=True)) # self.display_tree.clicked.connect(self._display_tree) g4vlay.addWidget(QLabel("<b>Worker Jobs")) g4vlay.addWidget(self.jobs) g4vlay.addWidget(QLabel("<b>Python Version")) g4vlay.addWidget(self.python_version) g4vlay.addWidget(QLabel("<b>Actions")) g4vlay.addWidget(self.display_tree) g4vlay.addWidget(self.dump_tree) g4vlay.addWidget(self.open_log) g4vlay.addWidget(self.open_folder) self.debug, self.scr = QCheckBox("Use Debug"), QCheckBox("Make Script") self.chrt, self.ionice = QCheckBox("Slow CPU"), QCheckBox("Slow HDD") self.minimi = QCheckBox("Auto Minimize") self.chrt.setToolTip("Use Low CPU speed priority (Linux only)") self.ionice.setToolTip("Use Low HDD speed priority (Linux only)") self.scr.setToolTip("Generate a Bash Script to Compile with Nuitka") self.debug.setToolTip("Use Debug Verbose mode") self.minimi.setToolTip("Automatically Minimize when compiling starts") self.scr.setChecked(True) self.chrt.setChecked(True) self.ionice.setChecked(True) self.minimi.setChecked(True) g5vlay.addWidget(self.debug) g5vlay.addWidget(self.scr) g5vlay.addWidget(self.chrt) g5vlay.addWidget(self.ionice) g5vlay.addWidget(self.minimi) self.guimode = QComboBox() self.guimode.addItems(('Full UX / UI', 'Simple UX / UI')) self.guimode.setCurrentIndex(1) self._set_guimode() self.guimode.setStyleSheet("""QComboBox{background:transparent; margin-left:25px;color:gray;text-decoration:underline;border:0}""") self.guimode.currentIndexChanged.connect(self._set_guimode) self.bt = QDialogButtonBox(self) self.bt.setStandardButtons( QDialogButtonBox.Ok | QDialogButtonBox.Close) self.bt.rejected.connect(self.close) self.bt.accepted.connect(self.run) if not sys.platform.startswith('lin'): self.scr.setChecked(False) self.chrt.setChecked(False) self.ionice.setChecked(False) self.scr.hide() self.chrt.hide() self.ionice.hide() if not sys.platform.startswith('win'): self.l_icon.hide() self.t_icon.hide() self.clear_2.hide() self.open_2.hide() if sys.platform.startswith('win'): self.display_tree.hide() container = QWidget() container_layout = QGridLayout(container) # Y, X container_layout.addWidget(self.guimode, 0, 1) container_layout.addWidget(self.group0, 1, 1) container_layout.addWidget(self.group1, 2, 1) container_layout.addWidget(self.group4, 1, 2) container_layout.addWidget(self.group5, 2, 2) container_layout.addWidget(self.bt, 3, 1) self.setCentralWidget(container)
def queryProxy(self, query): """ Public method to determine a proxy for a given query. @param query reference to the query object (QNetworkProxyQuery) @return list of proxies in order of preference (list of QNetworkProxy) """ if query.queryType() == QNetworkProxyQuery.UrlRequest and \ query.protocolTag() in ["http", "https", "ftp"]: # use proxy at all ? if not Preferences.getUI("UseProxy"): return [QNetworkProxy(QNetworkProxy.NoProxy)] # test for exceptions exceptions = Preferences.getUI("ProxyExceptions") if exceptions != self.__exceptions: self.__setExceptions(exceptions) urlHost = query.url().host() for matcher in self.__hostnameMatchers: if matcher.match(urlHost): return [QNetworkProxy(QNetworkProxy.NoProxy)] # determine proxy if Preferences.getUI("UseSystemProxy"): proxyList = QNetworkProxyFactory.systemProxyForQuery(query) if not Globals.isWindowsPlatform() and \ len(proxyList) == 1 and \ proxyList[0].type() == QNetworkProxy.NoProxy: # try it the Python way # scan the environment for variables named <scheme>_proxy # scan over whole environment to make this case insensitive for name, value in os.environ.items(): name = name.lower() if value and name[-6:] == '_proxy' and \ name[:-6] == query.protocolTag().lower(): url = QUrl(value) if url.scheme() == "http": proxyType = QNetworkProxy.HttpProxy elif url.scheme() == "https": proxyType = QNetworkProxy.HttpCachingProxy elif url.scheme() == "ftp": proxyType = QNetworkProxy.FtpCachingProxy else: proxyType = QNetworkProxy.HttpProxy proxy = QNetworkProxy(proxyType, url.host(), url.port(), url.userName(), url.password()) proxyList = [proxy] break if proxyList: scheme = schemeFromProxyType(proxyList[0].type()) if scheme == "": scheme = "Http" if scheme != "NoProxy": proxyList[0].setUser( Preferences.getUI("ProxyUser/{0}".format(scheme))) proxyList[0].setPassword( Preferences.getUI( "ProxyPassword/{0}".format(scheme))) return proxyList else: return [QNetworkProxy(QNetworkProxy.NoProxy)] else: if Preferences.getUI("UseHttpProxyForAll"): protocolKey = "Http" else: protocolKey = query.protocolTag().capitalize() host = Preferences.getUI("ProxyHost/{0}".format(protocolKey)) if not host: E5MessageBox.critical( None, QCoreApplication.translate( "E5NetworkProxyFactory", "Proxy Configuration Error"), QCoreApplication.translate( "E5NetworkProxyFactory", """Proxy usage was activated""" """ but no proxy host for protocol""" """ '{0}' configured.""").format(protocolKey)) return [QNetworkProxy(QNetworkProxy.DefaultProxy)] else: if protocolKey in ["Http", "Https", "Ftp"]: if query.protocolTag() == "ftp": proxyType = QNetworkProxy.FtpCachingProxy elif query.protocolTag() == "https": proxyType = QNetworkProxy.HttpCachingProxy else: proxyType = QNetworkProxy.HttpProxy proxy = QNetworkProxy( proxyType, host, Preferences.getUI("ProxyPort/" + protocolKey), Preferences.getUI("ProxyUser/" + protocolKey), Preferences.getUI("ProxyPassword/" + protocolKey)) else: proxy = QNetworkProxy(QNetworkProxy.DefaultProxy) return [proxy, QNetworkProxy(QNetworkProxy.DefaultProxy)] else: return [QNetworkProxy(QNetworkProxy.NoProxy)]
def queryProxy(self, query): """ Public method to determine a proxy for a given query. @param query reference to the query object (QNetworkProxyQuery) @return list of proxies in order of preference (list of QNetworkProxy) """ if query.queryType() == QNetworkProxyQuery.UrlRequest and query.protocolTag() in ["http", "https", "ftp"]: # use proxy at all ? if not Preferences.getUI("UseProxy"): return [QNetworkProxy(QNetworkProxy.NoProxy)] # test for exceptions exceptions = Preferences.getUI("ProxyExceptions") if exceptions != self.__exceptions: self.__setExceptions(exceptions) urlHost = query.url().host() for matcher in self.__hostnameMatchers: if matcher.match(urlHost): return [QNetworkProxy(QNetworkProxy.NoProxy)] # determine proxy if Preferences.getUI("UseSystemProxy"): proxyList = QNetworkProxyFactory.systemProxyForQuery(query) if ( not Globals.isWindowsPlatform() and len(proxyList) == 1 and proxyList[0].type() == QNetworkProxy.NoProxy ): # try it the Python way # scan the environment for variables named <scheme>_proxy # scan over whole environment to make this case insensitive for name, value in os.environ.items(): name = name.lower() if value and name[-6:] == "_proxy" and name[:-6] == query.protocolTag().lower(): url = QUrl(value) if url.scheme() == "http": proxyType = QNetworkProxy.HttpProxy elif url.scheme() == "https": proxyType = QNetworkProxy.HttpCachingProxy elif url.scheme() == "ftp": proxyType = QNetworkProxy.FtpCachingProxy else: proxyType = QNetworkProxy.HttpProxy proxy = QNetworkProxy(proxyType, url.host(), url.port(), url.userName(), url.password()) proxyList = [proxy] break if proxyList: scheme = schemeFromProxyType(proxyList[0].type()) if scheme == "": scheme = "Http" if scheme != "NoProxy": proxyList[0].setUser(Preferences.getUI("ProxyUser/{0}".format(scheme))) proxyList[0].setPassword(Preferences.getUI("ProxyPassword/{0}".format(scheme))) return proxyList else: return [QNetworkProxy(QNetworkProxy.NoProxy)] else: if Preferences.getUI("UseHttpProxyForAll"): protocolKey = "Http" else: protocolKey = query.protocolTag().capitalize() host = Preferences.getUI("ProxyHost/{0}".format(protocolKey)) if not host: E5MessageBox.critical( None, QCoreApplication.translate("E5NetworkProxyFactory", "Proxy Configuration Error"), QCoreApplication.translate( "E5NetworkProxyFactory", """Proxy usage was activated""" """ but no proxy host for protocol""" """ '{0}' configured.""", ).format(protocolKey), ) return [QNetworkProxy(QNetworkProxy.DefaultProxy)] else: if protocolKey in ["Http", "Https", "Ftp"]: if query.protocolTag() == "ftp": proxyType = QNetworkProxy.FtpCachingProxy elif query.protocolTag() == "https": proxyType = QNetworkProxy.HttpCachingProxy else: proxyType = QNetworkProxy.HttpProxy proxy = QNetworkProxy( proxyType, host, Preferences.getUI("ProxyPort/" + protocolKey), Preferences.getUI("ProxyUser/" + protocolKey), Preferences.getUI("ProxyPassword/" + protocolKey), ) else: proxy = QNetworkProxy(QNetworkProxy.DefaultProxy) return [proxy, QNetworkProxy(QNetworkProxy.DefaultProxy)] else: return [QNetworkProxy(QNetworkProxy.NoProxy)]
def init(): """Set the application wide proxy factory.""" proxy_factory = ProxyFactory() objreg.register('proxy-factory', proxy_factory) QNetworkProxyFactory.setApplicationProxyFactory(proxy_factory)
def __init__(self, args): global emacs_width, emacs_height, proxy_string # Parse init arguments. (emacs_width, emacs_height, emacs_server_port) = args emacs_width = int(emacs_width) emacs_height = int(emacs_height) # Init variables. self.module_dict = {} self.buffer_dict = {} self.view_dict = {} for name in [ "scroll_other_buffer", "eval_js_function", "eval_js_code", "action_quit", "send_key", "send_key_sequence", "handle_search_forward", "handle_search_backward", "set_focus_text" ]: self.build_buffer_function(name) for name in [ "execute_js_function", "execute_js_code", "execute_function", "execute_function_with_args" ]: self.build_buffer_return_function(name) # Init EPC client port. init_epc_client(int(emacs_server_port)) # Build EPC server. self.server = ThreadingEPCServer(('localhost', 0), log_traceback=True) self.server.allow_reuse_address = True # import logging # self.server = ThreadingEPCServer(('localhost', 0) # self.server.logger.setLevel(logging.DEBUG) eaf_config_dir = get_emacs_config_dir() self.session_file = os.path.join(eaf_config_dir, "session.json") if not os.path.exists(eaf_config_dir): os.makedirs(eaf_config_dir) # ch = logging.FileHandler(filename=os.path.join(eaf_config_dir, 'epc_log.txt'), mode='w') # formatter = logging.Formatter('%(asctime)s | %(levelname)-8s | %(lineno)04d | %(message)s') # ch.setFormatter(formatter) # ch.setLevel(logging.DEBUG) # self.server.logger.addHandler(ch) self.server.register_instance( self) # register instance functions let elisp side call # Start EPC server with sub-thread, avoid block Qt main loop. self.server_thread = threading.Thread(target=self.server.serve_forever) self.server_thread.start() # Pass epc port and webengine codec information to Emacs when first start EAF. eval_in_emacs('eaf--first-start', [self.server.server_address[1]]) # Disable use system proxy, avoid page slow when no network connected. QNetworkProxyFactory.setUseSystemConfiguration(False) # Set Network proxy. (proxy_host, proxy_port, proxy_type) = get_emacs_vars( ["eaf-proxy-host", "eaf-proxy-port", "eaf-proxy-type"]) self.proxy = (proxy_type, proxy_host, proxy_port) self.is_proxy = False if proxy_type != "" and proxy_host != "" and proxy_port != "": self.enable_proxy()
def shutdown(): QNetworkProxyFactory.setApplicationProxyFactory(None)
def __init__(self, parent=None): """Init class.""" super(MainWindow, self).__init__() QNetworkProxyFactory.setUseSystemConfiguration(True) self.statusBar().showMessage(get_blender_version()) self.setWindowTitle(__doc__.strip().capitalize()) self.setMinimumSize(400, 200) self.setMaximumSize(1024, 800) self.resize(self.minimumSize()) self.setWindowIcon(QIcon.fromTheme("blender")) self.center() QShortcut("Ctrl+q", self, activated=lambda: self.close()) self.menuBar().addMenu("&File").addAction("Exit", exit) windowMenu = self.menuBar().addMenu("&Window") windowMenu.addAction("Minimize", lambda: self.showMinimized()) windowMenu.addAction("Maximize", lambda: self.showMaximized()) windowMenu.addAction("Restore", lambda: self.showNormal()) windowMenu.addAction("FullScreen", lambda: self.showFullScreen()) windowMenu.addAction("Center", lambda: self.center()) windowMenu.addAction("Top-Left", lambda: self.move(0, 0)) windowMenu.addAction("To Mouse", lambda: self.move_to_mouse_position()) windowMenu.addSeparator() windowMenu.addAction( "Increase size", lambda: self.resize(self.size().width() * 1.4, self.size().height() * 1.4)) windowMenu.addAction("Decrease size", lambda: self.resize( self.size().width() // 1.4, self.size().height() // 1.4)) windowMenu.addAction("Minimum size", lambda: self.resize(self.minimumSize())) windowMenu.addAction("Maximum size", lambda: self.resize(self.maximumSize())) windowMenu.addAction("Horizontal Wide", lambda: self.resize( self.maximumSize().width(), self.minimumSize().height())) windowMenu.addAction("Vertical Tall", lambda: self.resize( self.minimumSize().width(), self.maximumSize().height())) windowMenu.addSeparator() windowMenu.addAction("Disable Resize", lambda: self.setFixedSize(self.size())) windowMenu.addAction("Set Interface Font...", lambda: self.setFont(QFontDialog.getFont()[0])) windowMenu.addAction( "Load .qss Skin", lambda: self.setStyleSheet(self.skin())) helpMenu = self.menuBar().addMenu("&Help") helpMenu.addAction("About Qt 5", lambda: QMessageBox.aboutQt(self)) helpMenu.addAction("About Python 3", lambda: open_new_tab('https://www.python.org')) helpMenu.addAction("About" + __doc__, lambda: QMessageBox.about(self, __doc__, HELP)) helpMenu.addSeparator() helpMenu.addAction( "Keyboard Shortcut", lambda: QMessageBox.information(self, __doc__, "<b>Quit = CTRL+Q")) if sys.platform.startswith('linux'): helpMenu.addAction( "View Source Code", lambda: call('xdg-open ' + __file__, shell=True)) helpMenu.addAction("View GitHub Repo", lambda: open_new_tab(__url__)) helpMenu.addAction("Report Bugs", lambda: open_new_tab( 'https://github.com/juancarlospaco/bgelauncher/issues?state=open')) helpMenu.addAction("Check Updates", lambda: Downloader(self)) # process self.process = QProcess() self.process.readyReadStandardOutput.connect(self._read_output) self.process.readyReadStandardError.connect(self._read_errors) self.process.finished.connect(self._process_finished) self.process.error.connect(self._process_failed) # widgets self.group0, self.group1 = QGroupBox("BGE"), QGroupBox("Resolutions") self.group2, self.group3 = QGroupBox("AntiAlias"), QGroupBox("3DViews") self.group4, self.group5 = QGroupBox("Dome mode"), QGroupBox("Misc") g0grid, g1vlay = QGridLayout(self.group0), QVBoxLayout(self.group1) g5vlay, g4vlay = QVBoxLayout(self.group5), QVBoxLayout(self.group4) g2vlay, g3vlay = QVBoxLayout(self.group2), QVBoxLayout(self.group3) # group 0 the game engine options self.fixedti = QCheckBox("Force frames") self.mipmaps = QCheckBox("No MipMaps") self.showfps = QCheckBox("Show F.P.S.") self.propert = QCheckBox("Debug properties") self.profile = QCheckBox("Debug profilings") self.materia = QCheckBox("OpenGL Materials") self.depreca = QCheckBox("Debug Deprecations") self.nosound = QCheckBox("No Audio") g0grid.addWidget(self.showfps, 0, 0) g0grid.addWidget(self.fixedti, 0, 1) g0grid.addWidget(self.propert, 0, 2) g0grid.addWidget(self.mipmaps, 0, 3) g0grid.addWidget(self.profile, 1, 0) g0grid.addWidget(self.materia, 1, 1) g0grid.addWidget(self.depreca, 1, 2) g0grid.addWidget(self.nosound, 1, 3) # group 1 screen resolutions self.fullscreen = QCheckBox("FullScreen") self.autodetect = QCheckBox("AutoDetect") self.width, self.heigt = QComboBox(), QComboBox() self.bpp = QComboBox() resols = [ "240", "600", "640", "400", "480", "600", "640", "768", "800", "840", "1024", "1080", "1150", "1280", "1680", "1920", "2048"] self.width.addItems([str(self.get_half_of_resolution()[0])] + resols) self.heigt.addItems([str(self.get_half_of_resolution()[1])] + resols) self.bpp.addItems(["32", "16", "8"]) _container1, _container2 = QWidget(), QWidget() _res_lay, _mis_lay = QHBoxLayout(_container1), QHBoxLayout(_container2) _res_lay.addWidget(self.width) _res_lay.addWidget(QLabel("Pixels Width")) _res_lay.addWidget(self.heigt) _res_lay.addWidget(QLabel("Pixels Heigth")) _mis_lay.addWidget(self.fullscreen) _mis_lay.addWidget(self.autodetect) _mis_lay.addWidget(self.bpp) _mis_lay.addWidget(QLabel("Bits per Pixel")) g1vlay.addWidget(_container1) g1vlay.addWidget(_container2) # group 2 antialiasing self.aaa, self.aas = QCheckBox("AntiAliasing"), QSpinBox() self.aas.setToolTip("Maximum anti-aliasing samples") self.aaa.setChecked(True) self.aas.setRange(2, 16) self.aas.setValue(16) self.aas.setSingleStep(2) g2vlay.addWidget(self.aaa) g2vlay.addWidget(QLabel("Maximum Samples")) g2vlay.addWidget(self.aas) # group 3 the 3d stereo view mode self.stereos, self.smode = QCheckBox("3D View"), QComboBox() self.smode.addItems([ "NoStereo", "Anaglyph", "SideBySide", "SyncDoubling", "3DTVTopBottom", "Interlace", "VInterlace", "HWPageFlip"]) g3vlay.addWidget(self.stereos) g3vlay.addWidget(QLabel("Stereoscopy")) g3vlay.addWidget(self.smode) g3vlay.addWidget(QLabel("<small><i>Requires 3D<br>capable hardware!")) # group 4 the dome view mode self.dome, self.dmode = QCheckBox("Dome View"), QComboBox() self.dmode.addItems(["Fisheye", "TruncatedFront", "TruncatedRear", "CubeMap", "SphericalPanoramic"]) self.dangle, self.dtilt = QSpinBox(), QSpinBox() self.dangle.setToolTip("Field of view in degrees") self.dtilt.setToolTip("Tilt angle in degrees") self.dangle.setRange(10, 360) self.dangle.setValue(10) self.dtilt.setRange(10, 360) self.dtilt.setValue(10) g4vlay.addWidget(self.dome) g4vlay.addWidget(QLabel("Field of view")) g4vlay.addWidget(self.dangle) g4vlay.addWidget(QLabel("Tilt angle")) g4vlay.addWidget(self.dtilt) # group 5 miscelaneous stuff self.debug, self.log = QCheckBox("Use Debug"), QCheckBox("Save Logs") self.chrt, self.ionice = QCheckBox("Slow CPU"), QCheckBox("Slow HDD") self.minimi = QCheckBox("Auto Minimize") self.embeds = QCheckBox("Wallpaper mode") self.chrt.setToolTip("Use Low CPU speed priority (Linux only)") self.ionice.setToolTip("Use Low HDD speed priority (Linux only)") self.debug.setToolTip("Use BGE Verbose logs,ideal for Troubleshooting") self.minimi.setToolTip("Automatically Minimize Launcher after launch") self.embeds.setToolTip("Embed Game as interactive Desktop Wallpaper") self.minimi.setChecked(True) if not sys.platform.startswith('linux'): self.chrt.setDisabled(True) self.ionice.setDisabled(True) g5vlay.addWidget(self.debug) g5vlay.addWidget(self.log) g5vlay.addWidget(self.chrt) g5vlay.addWidget(self.ionice) g5vlay.addWidget(self.embeds) g5vlay.addWidget(self.minimi) # option to show or hide some widgets on the gui self.guimode = QComboBox() self.guimode.addItems(('Full UX / UI', 'Simple UX / UI')) self.guimode.setCurrentIndex(1) self._set_guimode() self.guimode.setStyleSheet( """QComboBox{background:transparent;border:0; margin-left:25px;color:gray;text-decoration:underline}""") self.guimode.currentIndexChanged.connect(self._set_guimode) # buttons from bottom to close or proceed self.bt = QDialogButtonBox(self) self.bt.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Close) self.bt.rejected.connect(self.close) self.bt.accepted.connect(self.run) # container for all groups of widgets container = QWidget() container_layout = QGridLayout(container) # Y, X container_layout.addWidget(self.guimode, 0, 1) container_layout.addWidget(self.group2, 1, 0) container_layout.addWidget(self.group3, 2, 0) container_layout.addWidget(self.group0, 1, 1) container_layout.addWidget(self.group1, 2, 1) container_layout.addWidget(self.group4, 1, 2) container_layout.addWidget(self.group5, 2, 2) container_layout.addWidget(self.bt, 3, 1) self.setCentralWidget(container)
def init(): """Set the application wide proxy factory.""" QNetworkProxyFactory.setApplicationProxyFactory(ProxyFactory())
def __init__(self, url, app): super(Window, self).__init__() self.progress = 0 self.app = app self.UI_FILE_PATH = 'ui/room_design.ui' self.CALLBACK = 'python_callback' self.MODELS_INFO = 'assets/models_info.json' self.TEXTURES_INFO = 'assets/textures_info.json' self.WIIMOTE_FREQUENCY = 50 self.DEFAULT_SCALE = 1.0 self.DEFAULT_ROTATION = 0.0 self.PLANE_XZ = 'xz' self.PLANE_XY = 'xy' self.PLANE_YZ = 'yz' self.WIN_X = 30 self.WIN_Y = 60 self.WIN_WIDTH = 1000 self.WIN_HEIGHT = 650 self.WIIMOTE_DEFAULT_ACCEL_SENSOR_VALUE = 512 self.WIIMOTE_MIN_ACCEL_SENSOR_VALUE = 407 self.WIIMOTE_MAX_ACCEL_SENSOR_VALUE = 610 self.WIIMOTE_SENSITIVITY = 10000 self.MESH_SELECT_TABLE_X_LEFT = 250 self.TEXTURE_SELECT_TABLE_X_LEFT = 50 self.SELECT_TABLES_Y = 665 screen_dimens = self.app.desktop().screenGeometry() self.url = url self.monitor_width = screen_dimens.width() self.monitor_height = screen_dimens.height() QNetworkProxyFactory.setUseSystemConfiguration(True) self.win = uic.loadUi(self.UI_FILE_PATH) self.wv = QWebView(self.win) js.SetupScene.init(self.wv) js.SetupScene.apply_callback(self.CALLBACK, self) self.wv.load(self.url) self.list_widget = self.win.list_widget self.mesh_select_table = None self.model_table = None self.texture_select_table = None self.setup_ui() self.meshes = [] self.selected_mesh = None self.mesh_translation = [] self.mesh_rotation = [] self.mesh_scale = [] self.is_first_b_button_callback = True self.wm_current_a_button_state = False self.address_line_edit = self.win.line_edit_address self.connect_btn = self.win.btn_connect self.connect_btn.clicked.connect(self.connect_wiimote) self.initial_accelerometer_data = None self.wiimote = wii.Wiimote(self.WIIMOTE_FREQUENCY, self.monitor_width, self.monitor_height) self.dpad_button_states = {} self.setup_wiimote() self.last_angle_y_rotation = self.DEFAULT_ROTATION self.last_scale_factor = self.DEFAULT_SCALE self.win.show() self.undo_utility = undo.UndoUtility() self.selected_plane = self.PLANE_XZ self.select_plane(self.selected_plane)
def __init__(self, parent=None): """Init class.""" super(MainWindow, self).__init__() QNetworkProxyFactory.setUseSystemConfiguration(True) self.statusBar().showMessage(__doc__ + get_nuitka_version()) self.setWindowTitle(__doc__.strip().capitalize()) self.setMinimumSize(480, 400) self.setMaximumSize(1024, 800) self.resize(self.minimumSize()) self.setWindowIcon(QIcon.fromTheme("python")) self.center() QShortcut("Ctrl+q", self, activated=lambda: self.close()) self.menuBar().addMenu("&File").addAction("Exit", lambda: self.close()) windowMenu = self.menuBar().addMenu("&Window") windowMenu.addAction("Minimize", lambda: self.showMinimized()) windowMenu.addAction("Maximize", lambda: self.showMaximized()) windowMenu.addAction("Restore", lambda: self.showNormal()) windowMenu.addAction("FullScreen", lambda: self.showFullScreen()) windowMenu.addAction("Center", lambda: self.center()) windowMenu.addAction("Top-Left", lambda: self.move(0, 0)) windowMenu.addAction("To Mouse", lambda: self.move_to_mouse_position()) windowMenu.addSeparator() windowMenu.addAction( "Increase size", lambda: self.resize(self.size().width() * 1.4, self.size().height() * 1.4)) windowMenu.addAction("Decrease size", lambda: self.resize( self.size().width() // 1.4, self.size().height() // 1.4)) windowMenu.addAction("Minimum size", lambda: self.resize(self.minimumSize())) windowMenu.addAction("Maximum size", lambda: self.resize(self.maximumSize())) windowMenu.addAction("Horizontal Wide", lambda: self.resize( self.maximumSize().width(), self.minimumSize().height())) windowMenu.addAction("Vertical Tall", lambda: self.resize( self.minimumSize().width(), self.maximumSize().height())) windowMenu.addSeparator() windowMenu.addAction("Disable Resize", lambda: self.setFixedSize(self.size())) windowMenu.addAction("Set Interface Font...", lambda: self.setFont(QFontDialog.getFont()[0])) windowMenu.addAction( "Load .qss Skin", lambda: self.setStyleSheet(self.skin())) helpMenu = self.menuBar().addMenu("&Help") helpMenu.addAction("About Qt 5", lambda: QMessageBox.aboutQt(self)) helpMenu.addAction("About Python 3", lambda: open_new_tab('https://www.python.org')) helpMenu.addAction("About " + __doc__, lambda: QMessageBox.about(self, __doc__, HELP)) helpMenu.addSeparator() helpMenu.addAction( "Keyboard Shortcut", lambda: QMessageBox.information(self, __doc__, "<b>Quit = CTRL+Q")) if sys.platform.startswith('linux'): helpMenu.addAction("View Source Code", lambda: call('xdg-open ' + __file__, shell=True)) helpMenu.addAction("View GitHub Repo", lambda: open_new_tab(__url__)) helpMenu.addAction("Check Updates", lambda: Downloader(self)) # process self.process = QProcess() self.process.readyReadStandardOutput.connect(self._read_output) self.process.readyReadStandardError.connect(self._read_errors) self.process.finished.connect(self._process_finished) self.process.error.connect(self._process_failed) # widgets self.group0, self.group1 = QGroupBox("Options"), QGroupBox("Paths") self.group4, self.group5 = QGroupBox("Details"), QGroupBox("Miscs") g0grid, g1vlay = QGridLayout(self.group0), QGridLayout(self.group1) g5vlay, g4vlay = QVBoxLayout(self.group5), QVBoxLayout(self.group4) # group 0 the options self.module = QCheckBox("Create compiled extension module") self.standalone = QCheckBox("Standalone executable binary output") self.nofreeze = QCheckBox("No freeze all modules of standard library") self.python_debug = QCheckBox("Use Python Debug") self.warning = QCheckBox("Warnings for implicit exceptions at compile") self.recurse_std = QCheckBox("Recursive compile the standard library") self.recurse_not = QCheckBox("Force No recursive compiling") self.execute = QCheckBox("Execute the created binary after compiling") self.pythonpath = QCheckBox("Keep pythonpath when executing") self.enhaced = QCheckBox("Enhaced compile, Not CPython compatible") self.nolineno = QCheckBox("No Statements line numbers on compile") self.rmbuilddir = QCheckBox("Remove build directory after compile.") self.nuitka_debug = QCheckBox("Use Nuitka Debug") self.keep_debug = QCheckBox("Keep debug info on compile for GDB") self.traced = QCheckBox("Traced execution output") self.plusplus = QCheckBox("Compile C++ Only on generated source files") self.experimental = QCheckBox("Experimental features") self.force_clang = QCheckBox("Force use of CLang") self.force_mingw = QCheckBox("Force use of MinGW on MS Windows") self.force_lto = QCheckBox("Use link time optimizations LTO") self.show_scons = QCheckBox("Show Scons executed commands") self.show_progress = QCheckBox("Show progress info and statistics") self.show_summary = QCheckBox("Show final summary of included modules") self.disable_console = QCheckBox("Disable the Console on MS Windows") for i, widget in enumerate(( self.module, self.standalone, self.nofreeze, self.python_debug, self.warning, self.recurse_std, self.recurse_not, self.execute, self.pythonpath, self.enhaced, self.nolineno, self.rmbuilddir, self.nuitka_debug, self.keep_debug, self.traced, self.plusplus, self.experimental, self.force_clang, self.force_mingw, self.force_lto, self.show_scons, self.show_progress, self.show_summary, self.disable_console)): widget.setToolTip(widget.text()) g0grid.addWidget(widget, i if i < i + 1 else i - (i - 1), i % 2) # group 1 paths self.target = QLineEdit() self.outdir = QLineEdit(os.path.expanduser("~")) self.t_icon = QLineEdit() self.target.setToolTip("Python App file you want to Compile to Binary") self.outdir.setToolTip("Folder to write Compiled Output Binary files") self.t_icon.setToolTip("Icon image file to embed for your Python App") self.target.setPlaceholderText("/full/path/to/target/python_app.py") self.outdir.setPlaceholderText("/full/path/to/output/folder/") self.t_icon.setPlaceholderText("/full/path/to/python_app/icon.png") self.completer, self.dirs = QCompleter(self), QDirModel(self) self.completer.setModel(self.dirs) self.completer.setCaseSensitivity(Qt.CaseInsensitive) self.completer.setCompletionMode(QCompleter.PopupCompletion) self.completer.popup().setStyleSheet("border: 1px solid gray") self.completer.popup().setVerticalScrollBarPolicy( Qt.ScrollBarAlwaysOff) self.outdir.setCompleter(self.completer) self.t_icon.setCompleter(self.completer) self.target.setCompleter(self.completer) self.clear_1 = QPushButton(QIcon.fromTheme("edit-clear"), "", self, clicked=lambda: self.target.clear()) self.clear_2 = QPushButton(QIcon.fromTheme("edit-clear"), "", self, clicked=lambda: self.t_icon.clear()) self.clear_3 = QPushButton(QIcon.fromTheme("edit-clear"), "", self, clicked=lambda: self.outdir.clear()) self.open_1 = QPushButton( QIcon.fromTheme("folder-open"), "", self, clicked=lambda: self.target.setText(str(QFileDialog.getOpenFileName( self, __doc__, os.path.expanduser("~"), """Python (*.py);; Python for Windows (*.pyw);;All (*.*)""")[0]))) self.open_2 = QPushButton( QIcon.fromTheme("folder-open"), "", self, clicked=lambda: self.t_icon.setText(str(QFileDialog.getOpenFileName( self, __doc__, os.path.expanduser("~"), "PNG (*.png);;JPG (*.jpg);;ICO (*.ico);;All (*.*)")[0]))) self.open_3 = QPushButton( QIcon.fromTheme("folder-open"), "", self, clicked=lambda: self.outdir.setText(str(QFileDialog.getExistingDirectory( self, __doc__, os.path.expanduser("~"))))) self.l_icon = QLabel("Target Icon") g1vlay.addWidget(QLabel("<b>Target Python"), 0, 0) g1vlay.addWidget(self.target, 0, 1) g1vlay.addWidget(self.clear_1, 0, 2) g1vlay.addWidget(self.open_1, 0, 3) g1vlay.addWidget(self.l_icon, 1, 0) g1vlay.addWidget(self.t_icon, 1, 1) g1vlay.addWidget(self.clear_2, 1, 2) g1vlay.addWidget(self.open_2, 1, 3) g1vlay.addWidget(QLabel("<b>Output Folder"), 2, 0) g1vlay.addWidget(self.outdir, 2, 1) g1vlay.addWidget(self.clear_3, 2, 2) g1vlay.addWidget(self.open_3, 2, 3) # group 4 the dome view mode self.jobs = QSpinBox() self.jobs.setRange(1, cpu_count()) self.jobs.setValue(cpu_count()) self.jobs.setToolTip("Backend Worker Jobs Processes") self.python_version = QComboBox() self.python_version.addItems(["2.7", "3.2", "3.3", "3.4"]) self.python_version.setToolTip("Python version to use with Nuitka") self.display_tree = QPushButton("Display Tree") self.display_tree.clicked.connect( lambda: call(NUITKA + " --display-tree {}".format( self.target.text()), shell=True)) self.dump_tree = QPushButton( "View Docs", clicked=lambda: open_new_tab("http://nuitka.net/doc/user-manual.html")) self.open_log = QPushButton("View Logs") _log = os.path.join(gettempdir(), "nuitka-gui.log") _open = "xdg-open " if sys.platform.startswith("lin") else "open " self.open_log.clicked.connect(lambda: call(_open + _log, shell=True)) self.open_folder = QPushButton("Open Build Folder") self.open_folder.clicked.connect(lambda: call( _open + str(self.outdir.text()).strip(), shell=True)) # self.display_tree.clicked.connect(self._display_tree) g4vlay.addWidget(QLabel("<b>Worker Jobs")) g4vlay.addWidget(self.jobs) g4vlay.addWidget(QLabel("<b>Python Version")) g4vlay.addWidget(self.python_version) g4vlay.addWidget(QLabel("<b>Actions")) g4vlay.addWidget(self.display_tree) g4vlay.addWidget(self.dump_tree) g4vlay.addWidget(self.open_log) g4vlay.addWidget(self.open_folder) # group 5 miscelaneous stuff self.debug, self.scr = QCheckBox("Use Debug"), QCheckBox("Make Script") self.chrt, self.ionice = QCheckBox("Slow CPU"), QCheckBox("Slow HDD") self.minimi = QCheckBox("Auto Minimize") self.chrt.setToolTip("Use Low CPU speed priority (Linux only)") self.ionice.setToolTip("Use Low HDD speed priority (Linux only)") self.scr.setToolTip("Generate a Bash Script to Compile with Nuitka") self.debug.setToolTip("Use Debug Verbose mode") self.minimi.setToolTip("Automatically Minimize when compiling starts") self.scr.setChecked(True) self.chrt.setChecked(True) self.ionice.setChecked(True) self.minimi.setChecked(True) g5vlay.addWidget(self.debug) g5vlay.addWidget(self.scr) g5vlay.addWidget(self.chrt) g5vlay.addWidget(self.ionice) g5vlay.addWidget(self.minimi) # option to show or hide some widgets on the gui self.guimode = QComboBox() self.guimode.addItems(('Full UX / UI', 'Simple UX / UI')) self.guimode.setCurrentIndex(1) self._set_guimode() self.guimode.setStyleSheet("""QComboBox{background:transparent; margin-left:25px;color:gray;text-decoration:underline;border:0}""") self.guimode.currentIndexChanged.connect(self._set_guimode) # buttons from bottom to close or proceed self.bt = QDialogButtonBox(self) self.bt.setStandardButtons( QDialogButtonBox.Ok | QDialogButtonBox.Close) self.bt.rejected.connect(self.close) self.bt.accepted.connect(self.run) if not sys.platform.startswith('lin'): self.scr.setChecked(False) self.chrt.setChecked(False) self.ionice.setChecked(False) self.scr.hide() self.chrt.hide() self.ionice.hide() if not sys.platform.startswith('win'): self.l_icon.hide() self.t_icon.hide() self.clear_2.hide() self.open_2.hide() if sys.platform.startswith('win'): self.display_tree.hide() # container for all groups of widgets container = QWidget() container_layout = QGridLayout(container) # Y, X container_layout.addWidget(self.guimode, 0, 1) container_layout.addWidget(self.group0, 1, 1) container_layout.addWidget(self.group1, 2, 1) container_layout.addWidget(self.group4, 1, 2) container_layout.addWidget(self.group5, 2, 2) container_layout.addWidget(self.bt, 3, 1) self.setCentralWidget(container)
def shutdown(): QNetworkProxyFactory.setApplicationProxyFactory( None) # type: ignore[arg-type]
def main(): multiprocessing.set_start_method('spawn') if markups.__version_tuple__ < (2, ): sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.') # If we're running on Windows without a console, then discard stdout # and save stderr to a file to facilitate debugging in case of crashes. if sys.executable.endswith('pythonw.exe'): sys.stdout = open(devnull, 'w') sys.stderr = open('stderr.log', 'w') try: # See https://github.com/retext-project/retext/issues/399 # and https://launchpad.net/bugs/941826 ctypes.CDLL('libGL.so.1', ctypes.RTLD_GLOBAL) except OSError: pass # Needed for Qt WebEngine on Windows QApplication.setAttribute(Qt.ApplicationAttribute.AA_ShareOpenGLContexts) QApplication.setAttribute(Qt.ApplicationAttribute.AA_UseHighDpiPixmaps) app = QApplication(sys.argv) app.setOrganizationName("ReText project") app.setApplicationName("ReText") app.setApplicationDisplayName("ReText") app.setApplicationVersion(app_version) app.setOrganizationDomain('mitya57.me') app.setDesktopFileName('me.mitya57.ReText.desktop') QNetworkProxyFactory.setUseSystemConfiguration(True) initializeDataDirs() RtTranslator = QTranslator() for path in datadirs: if RtTranslator.load('retext_' + globalSettings.uiLanguage, join(path, 'locale')): break QtTranslator = QTranslator() QtTranslator.load("qtbase_" + globalSettings.uiLanguage, QLibraryInfo.location(QLibraryInfo.LibraryLocation.TranslationsPath)) app.installTranslator(RtTranslator) app.installTranslator(QtTranslator) parser = QCommandLineParser() parser.addHelpOption() parser.addVersionOption() previewOption = QCommandLineOption('preview', QApplication.translate('main', 'Open the files in preview mode')) newWindowOption = QCommandLineOption('new-window', QApplication.translate('main', 'Create a new window even if there is an existing one')) parser.addOption(previewOption) parser.addOption(newWindowOption) parser.addPositionalArgument('files', QApplication.translate('main', 'List of files to open'), '[files...]') parser.process(app) filesToOpen = parser.positionalArguments() print('Using configuration file:', settings.fileName()) if globalSettings.appStyleSheet: sheetfile = QFile(globalSettings.appStyleSheet) sheetfile.open(QIODevice.OpenModeFlag.ReadOnly) app.setStyleSheet(QTextStream(sheetfile).readAll()) sheetfile.close() window = ReTextWindow() openInExistingWindow = (globalSettings.openFilesInExistingWindow and not parser.isSet(newWindowOption)) connection = QDBusConnection.sessionBus() if connection.isConnected() and openInExistingWindow: connection.registerObject('/', window, QDBusConnection.RegisterOption.ExportAllSlots) serviceName = 'me.mitya57.ReText' if not connection.registerService(serviceName) and filesToOpen: print('Opening the file(s) in the existing window of ReText.') iface = QDBusInterface(serviceName, '/', '', connection) for fileName in filesToOpen: iface.call('openFileWrapper', fileName) qWidgetIface = QDBusInterface(serviceName, '/', 'org.qtproject.Qt.QWidget', connection) qWidgetIface.call('raise') sys.exit(0) window.show() # ReText can change directory when loading files, so we # need to have a list of canonical names before loading fileNames = list(map(canonicalize, filesToOpen)) readStdIn = False if globalSettings.openLastFilesOnStartup: window.restoreLastOpenedFiles() for fileName in fileNames: if QFile.exists(fileName): window.openFileWrapper(fileName) if parser.isSet(previewOption): window.actionPreview.setChecked(True) window.preview(True) elif fileName == '-': readStdIn = True inputData = '' if readStdIn and sys.stdin is not None: if sys.stdin.isatty(): print('Reading stdin, press ^D to end...') inputData = sys.stdin.read() if inputData or not window.tabWidget.count(): window.createNew(inputData) signal.signal(signal.SIGINT, lambda sig, frame: window.close()) sys.exit(app.exec())