def valider(self): parameters = self.parent.parent.db.executewithreturn("""SELECT * FROM parameters""") self.parent.parent.db.executewithoutreturn( """UPDATE parameters SET home = ? WHERE id = ?""", (self.urlAccueil.text(), parameters[0][0])) self.parent.parent.db.executewithoutreturn( """UPDATE parameters SET moteur = ? WHERE id = ?""", (self.listeMoteur[self.moteurBox.currentIndex()], parameters[0][0])) self.parent.parent.dbConnection.executewithoutreturn( """UPDATE parameters SET js = ? WHERE id = ?""", (self.listejs[self.jsbox.currentIndex()], parameters[0][0])) if self.listejs[self.jsbox.currentIndex()] == "Activé": QWebEngineSettings.globalSettings().setAttribute(QWebEngineSettings.JavascriptEnabled, True) else: QWebEngineSettings.globalSettings().setAttribute(QWebEngineSettings.JavascriptEnabled, False) self.parent.parent.db.executewithoutreturn( """UPDATE parameters SET private = ? WHERE id = ?""", (self.listeprivate[self.privatebox.currentIndex()], parameters[0][0])) if self.listeprivate[self.privatebox.currentIndex()] == "Activé": QWebEngineProfile.defaultProfile().setHttpCacheType(QWebEngineProfile.MemoryHttpCache) self.parent.parent.privateBrowsing = True else: QWebEngineProfile.defaultProfile().setHttpCacheType(QWebEngineProfile.DiskHttpCache) self.parent.parent.privateBrowsing = False QMessageBox().about(self, "Enregistrement fait", "L'enregistrement des paramètres a été fait sans problème")
def __init__(self): super().__init__() proxy = QNetworkProxy() proxy.setType(QNetworkProxy.HttpProxy) proxy.setHostName("109.173.124.250") proxy.setPort(7793) QNetworkProxy.setApplicationProxy(proxy) try: print("1") ua = UserAgent() ua.update() useragent = ua.random except FakeUserAgentError: print("2") useragent = "Mozilla / 5.0 (Windows NT 10.0; Win64; x64) AppleWebKit / 537.36 (KHTML, как Gecko) Chrome / " \ "72.0.3626.121 Safari / 537.36" profile = QWebEngineProfile() profile.setHttpUserAgent(useragent) page = QWebEnginePage(profile) page.setUrl(QUrl("https://www.instagram.com/")) self.setPage(page) self.page().proxyAuthenticationRequired.connect( self.handle_proxy_auth_req) self.imit_peop = threading.Thread(target=self.imitation_people, args=()) self._timer = QTimer() self.loadFinished.connect(self.startTimer) self._timer.timeout.connect(self.start_thread_imitation)
def __init__(self, settings=None): super(Py2WebBrowser, self).__init__() self.pwb = QWebEngineView() self.pwb.setAttribute(Qt.WA_DeleteOnClose, True) if settings is not None: self.bconf = settings else: self.bconf = BaseConfig() self.raw_cookies = [] self.cookie_list = [] self.req_obj = QWebEngineHttpRequest() profile = QWebEngineProfile("pyweb", self.pwb) profile.setHttpUserAgent(random.choice(self.bconf.USER_AGENT_LIST)) cookie_store = profile.cookieStore() cookie_store.cookieAdded.connect(self._on_cookie) wp = QWebEnginePage(profile, self.pwb) self.pwb.setPage(wp) self._settings() self.pwb.show()
def __init__(self, parent=None): QDialog.__init__(self, parent=parent) self.setupUi(self) self.web_session = requests.Session() self.web_profile = QWebEngineProfile() self.web_interceptor = RequestInterceptor() self.web_interceptor.response_intercepted.connect(self.response_esia) self.web_profile.setRequestInterceptor(self.web_interceptor) self.ESIAWebView.setPage(QWebEnginePage(self.web_profile, self)) self.LoginMethodTabs.currentChanged.connect(self.on_tab_changed) self.FNSLoginBtn.clicked.connect(self.login_fns)
def __init__(self): super().__init__() self.label = QLabel('reCAPTCHA를 해결하고 확인 버튼을 누르세요.\n' '404 페이지가 로드되면 정상입니다. 완료 버튼을 눌러 종료하세요.') self.label.setStyleSheet('font: 10pt \'맑은 고딕\'') self.label.setAlignment(Qt.AlignCenter) self.label.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) QWebEngineProfile.defaultProfile().setHttpAcceptLanguage('ko') self.browser = QWebEngineView() self.browser.setStyleSheet('border: 1px solid gray;') # self.browser.loadStarted.connect(self.test) # self.browser.loadFinished.connect(self.test2) self.btn_zoom_in = NPButton('+', 9, self) self.btn_zoom_in.setMinimumWidth(30) self.btn_zoom_in.setMaximumWidth(50) self.btn_zoom_in.clicked.connect(self.zoom_in) self.btn_zoom_out = NPButton('-', 9, self) self.btn_zoom_out.setMinimumWidth(30) self.btn_zoom_out.setMaximumWidth(50) self.btn_zoom_out.clicked.connect(self.zoom_out) self.btn = NPButton('완료', 10, self) self.btn.setMaximumWidth(200) self.btn.clicked.connect(self.accept) # self.btn.clicked.connect(self.test2) self.abc = False box_h = QHBoxLayout() box_h.addWidget(self.btn_zoom_in) box_h.addWidget(self.btn_zoom_out) box_h.addStretch(4) box_h.addWidget(self.btn) box_h.setStretchFactor(self.btn_zoom_in, 1) box_h.setStretchFactor(self.btn_zoom_out, 1) box_h.setStretchFactor(self.btn, 4) box_v = QVBoxLayout() box_v.addWidget(self.label) box_v.addWidget(self.browser) box_v.addLayout(box_h) box_v.setContentsMargins(8, 10, 8, 8) self.setLayout(box_v) # self.setWindowModality(Qt.ApplicationModal) self.setWindowTitle('reCAPTCHA') self.setWindowIcon(QIcon('icon.png')) self.setWindowFlag(Qt.WindowContextHelpButtonHint, False) self.browser.setFocus() self.resize(480, 700)
def test_SchemeHandlerRedirect(self): app = QApplication([]) handler = TestSchemeHandler() profile = QWebEngineProfile.defaultProfile() profile.installUrlSchemeHandler("testpy", handler) view = QWebEngineView() view.loadFinished.connect(app.quit) QTimer.singleShot(5000, app.quit) view.show() view.load("testpy:hello") app.exec_() self.assertEqual(view.url(), "testpy:goodbye")
def main(): import sys QCoreApplication.setOrganizationName("QtExamples") QApplication.setAttribute(Qt.AA_EnableHighDpiScaling) WebUiHandler.registerUrlScheme() app = QApplication(sys.argv) profile = QWebEngineProfile() handler = WebUiHandler() profile.installUrlSchemeHandler(WebUiHandler.schemeName, handler) page = QWebEnginePage(profile) page.load(WebUiHandler.aboutUrl) view = QWebEngineView() view.setPage(page) view.setContextMenuPolicy(Qt.NoContextMenu) view.resize(500, 600) view.show() sys.exit(app.exec_())
def reinit_code(self): reqdata = {'client_id': self.__client_id, 'scope': 'gist'} req = urllib2.Request('https://github.com/login/device/code', data=json.dumps(reqdata), headers=self.__headers) req.get_method = lambda: 'POST' code, ret = urlopen_nt(req) if code != 200: raise RuntimeError('code %d when trying to register device' % code) init_data = json.loads(ret.read()) print(init_data) self.__device_code = init_data['device_code'] self.__interval = init_data.get('interval', 5) url = init_data['verification_uri'] self.__await_login_redirect = True self.__webprofile = QWebEngineProfile(parent=self.__webview) self.__webpage = QWebEnginePage(self.__webprofile, parent=self.__webview) # just to be sure they are deleted in proper order self.__webview.setPage(self.__webpage) self.__webview.load(QUrl(url)) self.__devidlabel.setText('code: %s' % (init_data['user_code'],))
class LoginFNS(QDialog, Ui_LoginFNSDialog): def __init__(self, db, parent=None): QDialog.__init__(self, parent=parent) self.setupUi(self) self.db = db self.web_session = requests.Session() self.web_profile = QWebEngineProfile() self.web_interceptor = RequestInterceptor() self.web_interceptor.response_intercepted.connect(self.response_esia) self.web_profile.setRequestInterceptor(self.web_interceptor) self.ESIAWebView.setPage(QWebEnginePage(self.web_profile, self)) self.LoginMethodTabs.currentChanged.connect(self.on_tab_changed) self.FNSLoginBtn.clicked.connect(self.login_fns) def on_tab_changed(self, index): if index == 1: # ESIA login selected self.login_esia() def login_fns(self): client_secret = readSQL( self.db, "SELECT value FROM settings WHERE name='RuTaxClientSecret'") inn = self.InnEdit.text() password = self.PasswordEdit.text() s = requests.Session() s.headers['ClientVersion'] = '2.9.0' s.headers['Device-Id'] = str(uuid.uuid1()) s.headers['Device-OS'] = 'Android' s.headers['Content-Type'] = 'application/json; charset=UTF-8' s.headers['Accept-Encoding'] = 'gzip' s.headers['User-Agent'] = 'okhttp/4.2.2' payload = '{' + f'"client_secret":"{client_secret}","inn":"{inn}","password":"******"' + '}' response = s.post( 'https://irkkt-mobile.nalog.ru:8888/v2/mobile/users/lkfl/auth', data=payload) if response.status_code != 200: logging.error( g_tr('SlipsTaxAPI', "FNS login failed: ") + f"{response}/{response.text}") return logging.info( g_tr('SlipsTaxAPI', "FNS login successful: ") + f"{response.text}") json_content = json.loads(response.text) new_session_id = json_content['sessionId'] new_refresh_token = json_content['refresh_token'] _ = executeSQL( self.db, "UPDATE settings SET value=:new_session WHERE name='RuTaxSessionId'", [(":new_session", new_session_id)]) _ = executeSQL( self.db, "UPDATE settings SET value=:new_refresh_token WHERE name='RuTaxRefreshToken'", [(":new_refresh_token", new_refresh_token)]) self.db.commit() self.accept() def login_esia(self): self.web_session.headers['ClientVersion'] = '2.9.0' self.web_session.headers['Device-Id'] = str(uuid.uuid1()) self.web_session.headers['Device-OS'] = 'Android' self.web_session.headers[ 'Content-Type'] = 'application/json; charset=UTF-8' self.web_session.headers['Accept-Encoding'] = 'gzip' self.web_session.headers['User-Agent'] = 'okhttp/4.2.2' response = self.web_session.get( 'https://irkkt-mobile.nalog.ru:8888/v2/mobile/users/esia/auth/url') if response.status_code != 200: logging.error( g_tr('SlipsTaxAPI', "Get ESIA URL failed: ") + f"{response}/{response.text}") return json_content = json.loads(response.text) auth_url = json_content['url'] self.ESIAWebView.load(QUrl(auth_url)) @Slot() def response_esia(self, auth_code, state): client_secret = readSQL( self.db, "SELECT value FROM settings WHERE name='RuTaxClientSecret'") payload = '{' + f'"authorization_code": "{auth_code}", "client_secret": "{client_secret}", "state": "{state}"' \ + '}' response = self.web_session.post( 'https://irkkt-mobile.nalog.ru:8888/v2/mobile/users/esia/auth', data=payload) if response.status_code != 200: logging.error( g_tr('SlipsTaxAPI', "ESIA login failed: ") + f"{response}/{response.text}") return logging.info( g_tr('SlipsTaxAPI', "ESIA login successful: ") + f"{response.text}") json_content = json.loads(response.text) new_session_id = json_content['sessionId'] new_refresh_token = json_content['refresh_token'] _ = executeSQL( self.db, "UPDATE settings SET value=:new_session WHERE name='RuTaxSessionId'", [(":new_session", new_session_id)]) _ = executeSQL( self.db, "UPDATE settings SET value=:new_refresh_token WHERE name='RuTaxRefreshToken'", [(":new_refresh_token", new_refresh_token)]) self.db.commit() self.accept()
def __init__(self, title="", icon="", web_contents="", debug=False, transparent=False, online=False, url_rules="", cookies_path="", user_agent="", custom_css="", custom_js=""): """ * :param title:str * :param icon:str * :param web_contents:str * :param debug:bool * :param transparent:bool * :param online:bool * :param disable_gpu:bool * :param url_rules:dict * :param cookies_path:str * :param user_agent:str * :param custom_css:str * :param custom_js:str * :param toolbar:dict """ super(JWebView, self).__init__() self.setAttribute(Qt.WA_DeleteOnClose, True) self.debug = debug self.online = online self.home = web_contents self.profile = QWebEngineProfile().defaultProfile() self.webpage = JWebPage(icon, debug, online, cookies_path, url_rules) self.setPage(self.webpage) self.page().loadFinished.connect(self._page_load_finish) if custom_css: # Check for custom CSS self.custom_css = custom_css print("Custom CSS detected") if custom_js: # Check for custom JavaScript self.custom_js = custom_js print("Custom JavaScript detected") if url_rules: # Check for URL rules try: self.block_rules = url_rules["block"] except KeyError: self.block_rules = "" finally: self.interceptor = Interceptor(debug, self.block_rules) else: self.interceptor = Interceptor(debug) if user_agent: # Set user agent self.user_agent = user_agent self.profile.setHttpUserAgent(user_agent) if self.debug: # TODO implement webinspector self.settings().setAttribute(QWebEngineSettings.XSSAuditingEnabled, True) else: self.setContextMenuPolicy(Qt.PreventContextMenu) if transparent: # Activates background transparency self.setAttribute(Qt.WA_TranslucentBackground) self.page().setBackgroundColor(Qt.transparent) self.setStyleSheet("background:transparent;") print( "Transparency detected, make sure you set [ body {background:transparent;} ]" ) settings = self.settings() # * Set Engine options # * TODO: allow to set settings per application by passing a list settings.setAttribute(QWebEngineSettings.JavascriptCanPaste, True) settings.setAttribute(QWebEngineSettings.PlaybackRequiresUserGesture, False) settings.setAttribute(QWebEngineSettings.FullScreenSupportEnabled, True) settings.setAttribute( QWebEngineSettings.AllowWindowActivationFromJavaScript, True) settings.setAttribute( QWebEngineSettings.LocalContentCanAccessRemoteUrls, True) settings.setAttribute(QWebEngineSettings.JavascriptCanAccessClipboard, True) settings.setAttribute(QWebEngineSettings.SpatialNavigationEnabled, True) settings.setAttribute(QWebEngineSettings.TouchIconsEnabled, True) settings.setAttribute(QWebEngineSettings.FocusOnNavigationEnabled, True) if online: settings.setAttribute(QWebEngineSettings.DnsPrefetchEnabled, True) print("Engine online (IPC) Disabled") self.page().profile().downloadRequested.connect( self._download_requested) # Set persistent cookies self.profile.setPersistentCookiesPolicy( QWebEngineProfile.ForcePersistentCookies) # set cookies on user folder if cookies_path: # allow specific path per application. _cookies_path = f"{os.getenv('HOME')}/.jak/{cookies_path}" else: # use separate cookies database per application title = title.lower().replace(" ", "-") _cookies_path = f"{os.getenv('HOME')}/.jak/{title}" self.profile.setPersistentStoragePath(_cookies_path) print(f"Cookies PATH:{_cookies_path}") else: print("Engine interprocess communication (IPC) up and running:") #self.profile.setHttpCacheType(self.profile.MemoryHttpCache) self.profile.setRequestInterceptor(self.interceptor) print(self.profile.httpUserAgent()) validate_url(self, web_contents)
class JWebView(QWebEngineView): """ #### Imports: from JAK.WebEngine import JWebView """ def __init__(self, title="", icon="", web_contents="", debug=False, transparent=False, online=False, url_rules="", cookies_path="", user_agent="", custom_css="", custom_js=""): """ * :param title:str * :param icon:str * :param web_contents:str * :param debug:bool * :param transparent:bool * :param online:bool * :param disable_gpu:bool * :param url_rules:dict * :param cookies_path:str * :param user_agent:str * :param custom_css:str * :param custom_js:str * :param toolbar:dict """ super(JWebView, self).__init__() self.setAttribute(Qt.WA_DeleteOnClose, True) self.debug = debug self.online = online self.home = web_contents self.profile = QWebEngineProfile().defaultProfile() self.webpage = JWebPage(icon, debug, online, cookies_path, url_rules) self.setPage(self.webpage) self.page().loadFinished.connect(self._page_load_finish) if custom_css: # Check for custom CSS self.custom_css = custom_css print("Custom CSS detected") if custom_js: # Check for custom JavaScript self.custom_js = custom_js print("Custom JavaScript detected") if url_rules: # Check for URL rules try: self.block_rules = url_rules["block"] except KeyError: self.block_rules = "" finally: self.interceptor = Interceptor(debug, self.block_rules) else: self.interceptor = Interceptor(debug) if user_agent: # Set user agent self.user_agent = user_agent self.profile.setHttpUserAgent(user_agent) if self.debug: # TODO implement webinspector self.settings().setAttribute(QWebEngineSettings.XSSAuditingEnabled, True) else: self.setContextMenuPolicy(Qt.PreventContextMenu) if transparent: # Activates background transparency self.setAttribute(Qt.WA_TranslucentBackground) self.page().setBackgroundColor(Qt.transparent) self.setStyleSheet("background:transparent;") print( "Transparency detected, make sure you set [ body {background:transparent;} ]" ) settings = self.settings() # * Set Engine options # * TODO: allow to set settings per application by passing a list settings.setAttribute(QWebEngineSettings.JavascriptCanPaste, True) settings.setAttribute(QWebEngineSettings.PlaybackRequiresUserGesture, False) settings.setAttribute(QWebEngineSettings.FullScreenSupportEnabled, True) settings.setAttribute( QWebEngineSettings.AllowWindowActivationFromJavaScript, True) settings.setAttribute( QWebEngineSettings.LocalContentCanAccessRemoteUrls, True) settings.setAttribute(QWebEngineSettings.JavascriptCanAccessClipboard, True) settings.setAttribute(QWebEngineSettings.SpatialNavigationEnabled, True) settings.setAttribute(QWebEngineSettings.TouchIconsEnabled, True) settings.setAttribute(QWebEngineSettings.FocusOnNavigationEnabled, True) if online: settings.setAttribute(QWebEngineSettings.DnsPrefetchEnabled, True) print("Engine online (IPC) Disabled") self.page().profile().downloadRequested.connect( self._download_requested) # Set persistent cookies self.profile.setPersistentCookiesPolicy( QWebEngineProfile.ForcePersistentCookies) # set cookies on user folder if cookies_path: # allow specific path per application. _cookies_path = f"{os.getenv('HOME')}/.jak/{cookies_path}" else: # use separate cookies database per application title = title.lower().replace(" ", "-") _cookies_path = f"{os.getenv('HOME')}/.jak/{title}" self.profile.setPersistentStoragePath(_cookies_path) print(f"Cookies PATH:{_cookies_path}") else: print("Engine interprocess communication (IPC) up and running:") #self.profile.setHttpCacheType(self.profile.MemoryHttpCache) self.profile.setRequestInterceptor(self.interceptor) print(self.profile.httpUserAgent()) validate_url(self, web_contents) def _page_load_finish(self) -> None: result = time.localtime(time.time()) print(f"Document Ready in: {result.tm_sec} seconds") try: if self.custom_css: print("Custom CSS loaded") JavaScript.css(self, self.custom_css) except AttributeError: pass try: if self.custom_js: print("Custom JavaScript loaded") JavaScript.send(self, self.custom_js) except AttributeError: pass def _download_requested(self, download_item) -> None: """ * If a download is requested call a save file dialog * :param download_item: file to be downloaded """ from PySide2.QtWidgets import QFileDialog self.download_item = download_item dialog = QFileDialog(self) path = dialog.getSaveFileName(dialog, "Save File", download_item.path()) if path[0]: print(path) download_item.setPath(path[0]) print(f"downloading file to:( {download_item.path()} )") download_item.accept() download_item.finished.connect(self._download_finished) else: print("Download canceled") def _download_finished(self) -> None: """ Goes to previous page and pops an alert informing the user that the download is finish and were to find it """ file_path = self.download_item.path() msg = f"File Downloaded to: {file_path}" try: from Widgets import InfoDialog except ImportError: from JAK.Widgets import InfoDialog InfoDialog(self, "Download Complete", msg) if self.online: self.back() def navigate_home(self) -> None: """ Goes back to original application url """ self.load(self.home)
print("2") userAgent = "Mozilla / 5.0 (Windows NT 10.0; Win64; x64) AppleWebKit / 537.36 (KHTML, как Gecko) Chrome / " \ "72.0.3626.121 Safari / 537.36" app = QApplication(sys.argv) proxy = QNetworkProxy() proxy.setType(QNetworkProxy.HttpProxy) proxy.setHostName("109.173.124.250") proxy.setPort(7793) QNetworkProxy.setApplicationProxy(proxy) grid = QGridLayout() # browser = QWebEngineView() browser = Browser() # url_input = UrlInput(browser) list_view = QListView() list_view.setFixedWidth(300) # interceptor = WebEngineUrlRequestInterceptor() profile = QWebEngineProfile() profile.setHttpUserAgent(userAgent) page = MyWebEnginePage(profile, browser) page.setUrl(QUrl("https://www.instagram.com/")) # page.setUrl(QUrl("https://2ip.ru")) browser.setPage(page) page_proxy = browser.page() page_proxy.proxyAuthenticationRequired.connect(handleProxyAuthReq) grid.addWidget(list_view, 0, 1) grid.addWidget(browser, 0, 2) main_frame = QWidget() main_frame.setMinimumSize(800, 600) main_frame.setLayout(grid) main_frame.show() sys.exit(app.exec_())
def __init__(self): super(Browser, self).__init__() self.db = Database(os.path.join(os.path.dirname(__file__), "data.db")) self.db.createdb() self.centralWidget = QWidget(self) self.grid = QGridLayout(self.centralWidget) self.theme = "" self.version = "1.0.0" self.versionCompaDB = 1 self.versionAccDB = self.db.executewithreturn( """SELECT version FROM informations""")[0][0] if self.versionAccDB != self.versionCompaDB: QMessageBox.information( self, "Base de donnée non à jour", "La Base de donnée n'est pas compatible avec " "cette version de Browthon.\n" "Elle va être mise à jour.") self.dbConnection.disconnect() self.versionAccDB = majdb( os.path.join(os.path.dirname(__file__), "data.db"), self.versionAccDB, self.versionCompaDB) self.dbConnection.reconnect( os.path.join(os.path.dirname(__file__), "data.db")) self.dbConnection.createdb() QWebEngineSettings.globalSettings().setAttribute( QWebEngineSettings.FullScreenSupportEnabled, True) if self.db.executewithreturn( """SELECT js FROM parameters""")[0][0] == "Activé": QWebEngineSettings.globalSettings().setAttribute( QWebEngineSettings.JavascriptEnabled, True) else: QWebEngineSettings.globalSettings().setAttribute( QWebEngineSettings.JavascriptEnabled, False) if self.db.executewithreturn( """SELECT private FROM parameters""")[0][0] == "Activé": self.privateBrowsing = True QWebEngineProfile.defaultProfile().setHttpCacheType( QWebEngineProfile.MemoryHttpCache) else: self.privateBrowsing = False QWebEngineProfile.defaultProfile().setHttpCacheType( QWebEngineProfile.DiskHttpCache) self.urlInput = UrlInput(self) self.urlInput.setObjectName("addressBar") self.back = PushButton( "", QIcon(geticonpath(self, "../Icons/NavigationBar/back.png")), "backButton") self.forward = PushButton( "", QIcon(geticonpath(self, "../Icons/NavigationBar/forward.png")), "forwardButton") self.reload = PushButton( "", QIcon(geticonpath(self, "../Icons/NavigationBar/reload.png")), "reloadButton") self.bookmark = PushButton( "", QIcon(geticonpath(self, "../Icons/NavigationBar/noFav.png")), "favButton") self.home = PushButton( "", QIcon(geticonpath(self, "../Icons/NavigationBar/home.png")), "homeButton") self.parameter = PushButton( "", QIcon(geticonpath(self, "../Icons/NavigationBar/param.png")), "paramButton") self.tabWidget = TabWidget(self) self.tabWidget.tabBar().setObjectName("tabBar") self.tabWidget.requestsaddtab() self.back.setFlat(True) self.forward.setFlat(True) self.reload.setFlat(True) self.bookmark.setFlat(True) self.home.setFlat(True) self.parameter.setFlat(True) self.reload.clicked.connect(self.browserWidget.reload) self.back.clicked.connect(self.browserWidget.back) self.forward.clicked.connect(self.browserWidget.forward) self.bookmark.clicked.connect(self.fav) self.home.clicked.connect(lambda: self.urlInput.enterurlgiven( self.db.executewithreturn("""SELECT home FROM parameters""")[0][0]) ) self.parameter.clicked.connect(self.openparameter) self.grid.addWidget(self.back, 0, 0) self.grid.addWidget(self.reload, 0, 1) self.grid.addWidget(self.forward, 0, 2) self.grid.addWidget(self.urlInput, 0, 3) self.grid.addWidget(self.bookmark, 0, 4) self.grid.addWidget(self.home, 0, 5) self.grid.addWidget(self.parameter, 0, 6) self.grid.addWidget(self.tabWidget, 1, 0, 1, 7) self.grid.setContentsMargins(0, 0, 0, 0) self.grid.setSpacing(0) self.setCentralWidget(self.centralWidget) self.showMaximized() self.setWindowTitle('Browthon') self.parameterWindow = ParameterWindow(self) QWebEngineProfile.defaultProfile().\ downloadRequested.connect(self.parameterWindow.downloadPage.downloadrequested) theme = self.db.executewithreturn( """SELECT theme FROM parameters""")[0][0] if theme == "": self.theme = "" self.applytheme() else: if os.path.exists( os.path.join(os.path.dirname(__file__), "..", "Themes", theme, "theme.json")): self.theme = os.path.join(os.path.dirname(__file__), "..", "Themes", theme) self.applytheme() else: print("Le theme " + theme + " n'existe pas/plus.") self.theme = "" self.applytheme() self.parameterWindow.addonsPage.launchaddons("load") self.show() if self.db.executewithreturn( """SELECT first FROM parameters""")[0][0] == "O": parameters = self.dbConnection.executewithreturn( """SELECT * FROM parameters""") self.db.executewithoutreturn( """UPDATE parameters SET first = ? WHERE id = ?""", ("N", parameters[0][0]))
def __init__(self, title="", icon="", web_contents="", debug=False, transparent=False, online=False, url_rules="", cookies_path="", user_agent="", custom_css="", custom_js=""): super(JWebView, self).__init__() self.setAttribute(Qt.WA_DeleteOnClose, True) self.debug = debug self.online = online self.home = web_contents self.profile = QWebEngineProfile().defaultProfile() self.webpage = JWebPage(icon, debug, online, url_rules) self.setPage(self.webpage) self.page().fullScreenRequested.connect(self._full_screen_requested) self.page().loadFinished.connect(self._page_load_finish) if custom_css: self.custom_css = custom_css print("Custom CSS detected") if custom_js: self.custom_js = custom_js print("Custom JavaScript detected") if url_rules: self.block_rules = url_rules["block"] self.interceptor = Interceptor(debug, self.block_rules) else: self.interceptor = Interceptor(debug) self.profile.setRequestInterceptor(self.interceptor) if user_agent: self.user_agent = user_agent self.profile.setHttpUserAgent(user_agent) print(self.profile.httpUserAgent()) if online: print("Engine online (IPC) Disabled") self.page().profile().downloadRequested.connect( self._download_requested) # Set persistent cookies self.profile.setPersistentCookiesPolicy( QWebEngineProfile.ForcePersistentCookies) # set cookies on user folder if cookies_path: # allow specific path per application. _cookies_path = f"{os.getenv('HOME')}/.jak/{cookies_path}" else: # use separate cookies database per application title = title.lower().replace(" ", "-") _cookies_path = f"{os.getenv('HOME')}/.jak/{title}" self.profile.setCachePath(_cookies_path) self.profile.setPersistentStoragePath(_cookies_path) print(f"Cookies PATH:{_cookies_path}") else: print("Engine interprocess communication (IPC) up and running:") #self.profile.setHttpCacheType(self.profile.MemoryHttpCache) if self.debug: # TODO implement webinspector self.settings().setAttribute(QWebEngineSettings.XSSAuditingEnabled, True) else: self.setContextMenuPolicy(Qt.PreventContextMenu) if transparent: # Activates webview background transparency # FIXME background transparency not working # https://bugreports.qt.io/browse/QTBUG-41960 self.setAttribute(Qt.WA_TranslucentBackground) self.page().setBackgroundColor(Qt.transparent) #self.setWindowFlags(Qt.FramelessWindowHint) self.setStyleSheet("background:transparent;") settings = self.settings() # TODO allow settings per application settings.setAttribute(QWebEngineSettings.JavascriptCanPaste, True) settings.setAttribute(QWebEngineSettings.PlaybackRequiresUserGesture, False) settings.setAttribute(QWebEngineSettings.FullScreenSupportEnabled, False) # Disabled BUG settings.setAttribute( QWebEngineSettings.AllowWindowActivationFromJavaScript, True) settings.setAttribute( QWebEngineSettings.LocalContentCanAccessRemoteUrls, True) settings.setAttribute(QWebEngineSettings.JavascriptCanAccessClipboard, True) settings.setAttribute(QWebEngineSettings.SpatialNavigationEnabled, True) settings.setAttribute(QWebEngineSettings.TouchIconsEnabled, True) settings.setAttribute(QWebEngineSettings.FocusOnNavigationEnabled, True) if online: settings.setAttribute(QWebEngineSettings.DnsPrefetchEnabled, True) validate_url(self, web_contents)
def __init__(self, context, parent=None): super(SVDBrowser, self).__init__(parent) QWebEngineProfile.defaultProfile().downloadRequested.connect( self.on_downloadRequested) # Create widgets #self.setWindowModality(Qt.ApplicationModal) self.title = QLabel(self.tr("SVD Browser")) self.closeButton = QPushButton(self.tr("Close")) self.setWindowTitle(self.title.text()) self.browseButton = QPushButton("Browse SVD Folder") self.deleteSvdButton = QPushButton("Delete") self.applySvdButton = QPushButton("Apply SVD") self.view = QWebEngineView() url = "https://developer.arm.com/tools-and-software/embedded/cmsis/cmsis-search" self.view.load(QUrl(url)) self.columns = 3 self.context = context self.currentFileLabel = QLabel() self.currentFile = "" #Files self.files = QFileSystemModel() self.files.setRootPath(svdPath) self.files.setNameFilters(["*.svd", "*.patched"]) #Tree self.tree = QTreeView() self.tree.setModel(self.files) self.tree.setSortingEnabled(True) self.tree.hideColumn(2) self.tree.sortByColumn(0, Qt.AscendingOrder) self.tree.setRootIndex(self.files.index(svdPath)) for x in range(self.columns): #self.tree.resizeColumnToContents(x) self.tree.header().setSectionResizeMode( x, QHeaderView.ResizeToContents) treeLayout = QVBoxLayout() treeLayout.addWidget(self.tree) treeButtons = QHBoxLayout() #treeButtons.addWidget(self.newFolderButton) treeButtons.addWidget(self.browseButton) treeButtons.addWidget(self.applySvdButton) treeButtons.addWidget(self.deleteSvdButton) treeLayout.addLayout(treeButtons) treeWidget = QWidget() treeWidget.setLayout(treeLayout) # Create layout and add widgets buttons = QHBoxLayout() buttons.addWidget(self.closeButton) vlayoutWidget = QWidget() vlayout = QVBoxLayout() vlayout.addWidget(self.view) vlayout.addLayout(buttons) vlayoutWidget.setLayout(vlayout) hsplitter = QSplitter() hsplitter.addWidget(treeWidget) hsplitter.addWidget(vlayoutWidget) hlayout = QHBoxLayout() hlayout.addWidget(hsplitter) self.showMaximized() #Fixes bug that maximized windows are "stuck" #Because you can't trust QT to do the right thing here # Set dialog layout self.setLayout(hlayout) # Add signals self.closeButton.clicked.connect(self.close) self.tree.selectionModel().selectionChanged.connect(self.selectFile) self.applySvdButton.clicked.connect(self.applySvd) self.deleteSvdButton.clicked.connect(self.deleteSvd) self.browseButton.clicked.connect(self.browseSvd)