예제 #1
0
    def show_inspector(self):
        """
        Show web inspector bound to QmxGraph page.
        """
        if not self._inspector_dialog:
            from PyQt5.QtWebKit import QWebSettings
            QWebSettings.globalSettings().setAttribute(
                QWebSettings.DeveloperExtrasEnabled, True)

            dialog = self._inspector_dialog = QDialog(self)
            dialog.setWindowTitle("Web Inspector")
            dialog.setWindowFlags(dialog.windowFlags()
                                  | Qt.WindowMaximizeButtonHint)
            dialog.resize(800, 600)
            layout = QGridLayout(dialog)
            layout.setContentsMargins(0, 0, 0, 0)  # no margin to web view

            from PyQt5.QtWebKitWidgets import QWebInspector
            inspector = QWebInspector(dialog)
            inspector.setSizePolicy(QSizePolicy.Expanding,
                                    QSizePolicy.Expanding)
            inspector.setPage(self.inner_web_view().page())
            inspector.setVisible(True)
            layout.addWidget(inspector)

        self._inspector_dialog.show()
예제 #2
0
def init():
    """Initialize the global QWebSettings."""
    cache_path = standarddir.cache()
    data_path = standarddir.data()
    if config.get('general', 'private-browsing') or cache_path is None:
        QWebSettings.setIconDatabasePath('')
    else:
        QWebSettings.setIconDatabasePath(cache_path)
    if cache_path is not None:
        QWebSettings.setOfflineWebApplicationCachePath(
            os.path.join(cache_path, 'application-cache'))
    if data_path is not None:
        QWebSettings.globalSettings().setLocalStoragePath(
            os.path.join(data_path, 'local-storage'))
        QWebSettings.setOfflineStoragePath(
            os.path.join(data_path, 'offline-storage'))

    for sectname, section in MAPPINGS.items():
        for optname, mapping in section.items():
            default = mapping.save_default()
            log.config.vdebug("Saved default for {} -> {}: {!r}".format(
                sectname, optname, default))
            value = config.get(sectname, optname)
            log.config.vdebug("Setting {} -> {} to {!r}".format(
                sectname, optname, value))
            mapping.set(value)
    objreg.get('config').changed.connect(update_settings)
예제 #3
0
def init():
    """Initialize the global QWebSettings."""
    cache_path = standarddir.cache()
    data_path = standarddir.data()
    if config.get('general', 'private-browsing') or cache_path is None:
        QWebSettings.setIconDatabasePath('')
    else:
        QWebSettings.setIconDatabasePath(cache_path)
    if cache_path is not None:
        QWebSettings.setOfflineWebApplicationCachePath(
            os.path.join(cache_path, 'application-cache'))
    if data_path is not None:
        QWebSettings.globalSettings().setLocalStoragePath(
            os.path.join(data_path, 'local-storage'))
        QWebSettings.setOfflineStoragePath(
            os.path.join(data_path, 'offline-storage'))

    for sectname, section in MAPPINGS.items():
        for optname, mapping in section.items():
            default = mapping.save_default()
            log.config.vdebug("Saved default for {} -> {}: {!r}".format(
                sectname, optname, default))
            value = config.get(sectname, optname)
            log.config.vdebug("Setting {} -> {} to {!r}".format(
                sectname, optname, value))
            mapping.set(value)
    objreg.get('config').changed.connect(update_settings)
예제 #4
0
def init():
    """Initialize the global QWebSettings."""
    cache_path = standarddir.cache()
    data_path = standarddir.data()

    QWebSettings.setIconDatabasePath(standarddir.cache())
    QWebSettings.setOfflineWebApplicationCachePath(
        os.path.join(cache_path, 'application-cache'))
    QWebSettings.globalSettings().setLocalStoragePath(
        os.path.join(data_path, 'local-storage'))
    QWebSettings.setOfflineStoragePath(
        os.path.join(data_path, 'offline-storage'))

    settings = QWebSettings.globalSettings()
    _set_user_stylesheet(settings)
    _set_cookie_accept_policy(settings)
    _set_cache_maximum_pages(settings)

    _init_user_agent()

    config.instance.changed.connect(_update_settings)

    global global_settings
    global_settings = WebKitSettings(QWebSettings.globalSettings())
    global_settings.init_settings()
예제 #5
0
파일: app.py 프로젝트: julianuu/qutebrowser
 def _shutdown(self, status, restart):
     """Second stage of shutdown."""
     log.destroy.debug("Stage 2 of shutting down...")
     if qApp is None:
         # No QApplication exists yet, so quit hard.
         sys.exit(status)
     # Remove eventfilter
     try:
         log.destroy.debug("Removing eventfilter...")
         qApp.removeEventFilter(objreg.get('event-filter'))
     except AttributeError:
         pass
     # Close all windows
     QApplication.closeAllWindows()
     # Shut down IPC
     try:
         objreg.get('ipc-server').shutdown()
     except KeyError:
         pass
     # Save everything
     try:
         save_manager = objreg.get('save-manager')
     except KeyError:
         log.destroy.debug("Save manager not initialized yet, so not "
                           "saving anything.")
     else:
         for key in save_manager.saveables:
             try:
                 save_manager.save(key, is_exit=True)
             except OSError as e:
                 error.handle_fatal_exc(
                     e,
                     self._args,
                     "Error while saving!",
                     pre_text="Error while saving {}".format(key))
     # Disable storage so removing tempdir will work
     QWebSettings.setIconDatabasePath('')
     QWebSettings.setOfflineWebApplicationCachePath('')
     QWebSettings.globalSettings().setLocalStoragePath('')
     # Re-enable faulthandler to stdout, then remove crash log
     log.destroy.debug("Deactivating crash log...")
     objreg.get('crash-handler').destroy_crashlogfile()
     # Delete temp basedir
     if ((self._args.temp_basedir or self._args.temp_basedir_restarted)
             and not restart):
         atexit.register(shutil.rmtree,
                         self._args.basedir,
                         ignore_errors=True)
     # Delete temp download dir
     objreg.get('temporary-downloads').cleanup()
     # If we don't kill our custom handler here we might get segfaults
     log.destroy.debug("Deactivating message handler...")
     qInstallMessageHandler(None)
     # Now we can hopefully quit without segfaults
     log.destroy.debug("Deferring QApplication::exit...")
     objreg.get('signal-handler').deactivate()
     # We use a singleshot timer to exit here to minimize the likelihood of
     # segfaults.
     QTimer.singleShot(0, functools.partial(qApp.exit, status))
예제 #6
0
    def __init__(self):
        super(WebRender, self).__init__()

        vbox = QVBoxLayout(self)
        #Web Frame
        self.webFrame = QWebView()
        QWebSettings.globalSettings().setAttribute(
            QWebSettings.DeveloperExtrasEnabled, True)
        vbox.addWidget(self.webFrame)
예제 #7
0
 def _shutdown(self, status, restart):
     """Second stage of shutdown."""
     log.destroy.debug("Stage 2 of shutting down...")
     if qApp is None:
         # No QApplication exists yet, so quit hard.
         sys.exit(status)
     # Remove eventfilter
     try:
         log.destroy.debug("Removing eventfilter...")
         qApp.removeEventFilter(objreg.get('event-filter'))
     except AttributeError:
         pass
     # Close all windows
     QApplication.closeAllWindows()
     # Shut down IPC
     try:
         objreg.get('ipc-server').shutdown()
     except KeyError:
         pass
     # Save everything
     try:
         save_manager = objreg.get('save-manager')
     except KeyError:
         log.destroy.debug("Save manager not initialized yet, so not "
                           "saving anything.")
     else:
         for key in save_manager.saveables:
             try:
                 save_manager.save(key, is_exit=True)
             except OSError as e:
                 error.handle_fatal_exc(
                     e, self._args, "Error while saving!",
                     pre_text="Error while saving {}".format(key))
     # Disable storage so removing tempdir will work
     QWebSettings.setIconDatabasePath('')
     QWebSettings.setOfflineWebApplicationCachePath('')
     QWebSettings.globalSettings().setLocalStoragePath('')
     # Re-enable faulthandler to stdout, then remove crash log
     log.destroy.debug("Deactivating crash log...")
     objreg.get('crash-handler').destroy_crashlogfile()
     # Delete temp basedir
     if ((self._args.temp_basedir or self._args.temp_basedir_restarted) and
             not restart):
         atexit.register(shutil.rmtree, self._args.basedir,
                         ignore_errors=True)
     # Delete temp download dir
     objreg.get('temporary-downloads').cleanup()
     # If we don't kill our custom handler here we might get segfaults
     log.destroy.debug("Deactivating message handler...")
     qInstallMessageHandler(None)
     # Now we can hopefully quit without segfaults
     log.destroy.debug("Deferring QApplication::exit...")
     objreg.get('signal-handler').deactivate()
     # We use a singleshot timer to exit here to minimize the likelihood of
     # segfaults.
     QTimer.singleShot(0, functools.partial(qApp.exit, status))
예제 #8
0
파일: common.py 프로젝트: nixman97/Pendulum
    def __init__(self, parent, debug=True):
        super(QGoogleMap, self).__init__(parent)
        if debug:
            QWebSettings.globalSettings().setAttribute(
                QWebSettings.DeveloperExtrasEnabled, True)
            self.setPage(_LoggedPage())

        self.initialized = False
        self.loadFinished.connect(self.onLoadFinished)
        self.page().mainFrame().addToJavaScriptWindowObject("qtWidget", self)

        basePath = os.path.abspath(os.path.dirname(__file__))
        url = 'file://' + basePath + '/qgmap.html'
        self.load(QUrl(url))
예제 #9
0
    def __init__(self, *args, **kwargs):
        super(Window, self).__init__(*args, **kwargs)
        self.resize(600, 400)
        layout = QHBoxLayout(self)

        # 左侧
        widgetLeft = QWidget(self)
        layoutLeft = QVBoxLayout(widgetLeft)
        # 右侧
        self.widgetRight = QListWidget(self,
                                       minimumWidth=200,
                                       iconSize=QSize(150, 150))
        self.widgetRight.setViewMode(QListWidget.IconMode)
        layout.addWidget(widgetLeft)
        layout.addWidget(self.widgetRight)

        self.webView = QWebView()
        layoutLeft.addWidget(self.webView)

        # 截图方式一
        groupBox1 = QGroupBox('截图方式一', self)
        layout1 = QVBoxLayout(groupBox1)
        layout1.addWidget(QPushButton('截图1', self, clicked=self.onScreenShot1))
        layoutLeft.addWidget(groupBox1)

        # 截图方式二(采用js)
        groupBox2 = QGroupBox('截图方式二', self)
        layout2 = QVBoxLayout(groupBox2)
        self.codeEdit = QLineEdit(
            'body',
            groupBox2,
            placeholderText='请输入需要截图的元素、ID或者class:如body、#id .class')
        layout2.addWidget(self.codeEdit)
        self.btnMethod2 = QPushButton('',
                                      self,
                                      clicked=self.onScreenShot2,
                                      enabled=False)
        layout2.addWidget(self.btnMethod2)
        layoutLeft.addWidget(groupBox2)

        # 开启开发人员工具
        QWebSettings.globalSettings().setAttribute(
            QWebSettings.DeveloperExtrasEnabled, True)
        self.webView.loadStarted.connect(self.onLoadStarted)
        self.webView.loadFinished.connect(self.onLoadFinished)
        self.webView.load(QUrl("https://pyqt5.com"))

        # 暴露接口和加载完成后执行jquery等一些库文件
        self.webView.page().mainFrame().javaScriptWindowObjectCleared.connect(
            self.populateJavaScriptWindowObject)
예제 #10
0
def enable_caret_browsing(qapp):
    """Fixture to enable caret browsing globally."""
    settings = QWebSettings.globalSettings()
    old_value = settings.testAttribute(QWebSettings.CaretBrowsingEnabled)
    settings.setAttribute(QWebSettings.CaretBrowsingEnabled, True)
    yield
    settings.setAttribute(QWebSettings.CaretBrowsingEnabled, old_value)
예제 #11
0
def init(_args):
    """Initialize the global QWebSettings."""
    cache_path = standarddir.cache()
    data_path = standarddir.data()

    QWebSettings.setIconDatabasePath(standarddir.cache())
    QWebSettings.setOfflineWebApplicationCachePath(
        os.path.join(cache_path, 'application-cache'))
    QWebSettings.globalSettings().setLocalStoragePath(
        os.path.join(data_path, 'local-storage'))
    QWebSettings.setOfflineStoragePath(
        os.path.join(data_path, 'offline-storage'))

    websettings.init_mappings(MAPPINGS)
    _set_user_stylesheet()
    config.instance.changed.connect(_update_settings)
def enable_caret_browsing(qapp):
    """Fixture to enable caret browsing globally."""
    settings = QWebSettings.globalSettings()
    old_value = settings.testAttribute(QWebSettings.CaretBrowsingEnabled)
    settings.setAttribute(QWebSettings.CaretBrowsingEnabled, True)
    yield
    settings.setAttribute(QWebSettings.CaretBrowsingEnabled, old_value)
예제 #13
0
def _set_global_render_settings(js_disable_cross_domain_access, private_mode,
                                disable_browser_caches):
    from PyQt5.QtWebKit import QWebSecurityOrigin, QWebSettings
    from twisted.python import log

    log.msg("memory cache: %s, private mode: %s, js cross-domain access: %s" %
            (ONOFF[not disable_browser_caches], ONOFF[private_mode],
             ONOFF[not js_disable_cross_domain_access]))

    if js_disable_cross_domain_access is False:
        # In order to enable cross domain requests it is necessary to add
        # the http and https to the local scheme, this way all the urls are
        # seen as inside the same security origin.
        for scheme in ['http', 'https']:
            QWebSecurityOrigin.addLocalScheme(scheme)

    settings = QWebSettings.globalSettings()
    settings.setAttribute(QWebSettings.PrivateBrowsingEnabled, private_mode)
    settings.setAttribute(QWebSettings.LocalStorageEnabled, not private_mode)

    if disable_browser_caches is True:
        # disables the page cache (also known as the in-memory webkit cache)
        # see https://webkit.org/blog/427/webkit-page-cache-i-the-basics/
        settings.setObjectCacheCapacities(0, 0, 0)
        settings.setMaximumPagesInCache(0)
예제 #14
0
    def _check_prerequisites(self, win_id):
        """Check if the command is permitted to run currently.

        Args:
            win_id: The window ID the command is run in.
        """
        mode_manager = objreg.get('mode-manager', scope='window',
                                  window=win_id)
        curmode = mode_manager.mode
        if self._modes is not None and curmode not in self._modes:
            mode_names = '/'.join(mode.name for mode in self._modes)
            raise cmdexc.PrerequisitesError(
                "{}: This command is only allowed in {} mode.".format(
                    self.name, mode_names))
        elif self._not_modes is not None and curmode in self._not_modes:
            mode_names = '/'.join(mode.name for mode in self._not_modes)
            raise cmdexc.PrerequisitesError(
                "{}: This command is not allowed in {} mode.".format(
                    self.name, mode_names))
        if self._needs_js and not QWebSettings.globalSettings().testAttribute(
                QWebSettings.JavascriptEnabled):
            raise cmdexc.PrerequisitesError(
                "{}: This command needs javascript enabled.".format(self.name))
        if self.deprecated:
            message.warning(win_id, '{} is deprecated - {}'.format(
                self.name, self.deprecated))
예제 #15
0
 def setup_global_settings():
     if not WebPageCustom.global_settings_set:
         settings = QWebSettings.globalSettings()
         settings.enablePersistentStorage('{base}/{cache}'.format(
             base=BASE_PROJECT_DIR,
             cache=WebPageCustom.cache_directory_name))
         settings.setMaximumPagesInCache(0)
         settings.setAttribute(QWebSettings.DnsPrefetchEnabled, False)
         settings.setAttribute(QWebSettings.JavascriptEnabled, True)
         settings.setAttribute(QWebSettings.JavaEnabled, False)
         settings.setAttribute(QWebSettings.PluginsEnabled, False)
         settings.setAttribute(QWebSettings.JavascriptCanOpenWindows, False)
         settings.setAttribute(QWebSettings.JavascriptCanCloseWindows,
                               False)
         settings.setAttribute(QWebSettings.JavascriptCanAccessClipboard,
                               False)
         settings.setAttribute(QWebSettings.DeveloperExtrasEnabled, False)
         settings.setAttribute(QWebSettings.SpatialNavigationEnabled, False)
         settings.setAttribute(QWebSettings.OfflineStorageDatabaseEnabled,
                               True)
         settings.setAttribute(
             QWebSettings.OfflineWebApplicationCacheEnabled, True)
         settings.setAttribute(QWebSettings.LocalStorageEnabled, True)
         settings.setAttribute(QWebSettings.AcceleratedCompositingEnabled,
                               False)
         settings.setAttribute(QWebSettings.NotificationsEnabled, False)
         WebPageCustom.global_settings_set = True
예제 #16
0
 def _click_js(self, click_target):
     settings = QWebSettings.globalSettings()
     attribute = QWebSettings.JavascriptCanOpenWindows
     could_open_windows = settings.testAttribute(attribute)
     settings.setAttribute(attribute, True)
     self._elem.evaluateJavaScript('this.click();')
     settings.setAttribute(attribute, could_open_windows)
예제 #17
0
    def follow_selected(self, *, tab=False):
        if not self.has_selection():
            return
        if QWebSettings.globalSettings().testAttribute(
                QWebSettings.JavascriptEnabled):
            if tab:
                self._tab.data.override_target = usertypes.ClickTarget.tab
            self._tab.run_js_async(
                'window.getSelection().anchorNode.parentNode.click()')
        else:
            selection = self.selection(html=True)
            try:
                selected_element = xml.etree.ElementTree.fromstring(
                    '<html>{}</html>'.format(selection)).find('a')
            except xml.etree.ElementTree.ParseError:
                raise browsertab.WebTabError('Could not parse selected '
                                             'element!')

            if selected_element is not None:
                try:
                    url = selected_element.attrib['href']
                except KeyError:
                    raise browsertab.WebTabError('Anchor element without '
                                                 'href!')
                url = self._tab.url().resolved(QUrl(url))
                if tab:
                    self._tab.new_tab_requested.emit(url)
                else:
                    self._tab.openurl(url)
예제 #18
0
    def _check_prerequisites(self, win_id):
        """Check if the command is permitted to run currently.

        Args:
            win_id: The window ID the command is run in.
        """
        mode_manager = objreg.get('mode-manager',
                                  scope='window',
                                  window=win_id)
        curmode = mode_manager.mode
        if self._modes is not None and curmode not in self._modes:
            mode_names = '/'.join(mode.name for mode in self._modes)
            raise cmdexc.PrerequisitesError(
                "{}: This command is only allowed in {} mode.".format(
                    self.name, mode_names))
        elif self._not_modes is not None and curmode in self._not_modes:
            mode_names = '/'.join(mode.name for mode in self._not_modes)
            raise cmdexc.PrerequisitesError(
                "{}: This command is not allowed in {} mode.".format(
                    self.name, mode_names))
        if self._needs_js and not QWebSettings.globalSettings().testAttribute(
                QWebSettings.JavascriptEnabled):
            raise cmdexc.PrerequisitesError(
                "{}: This command needs javascript enabled.".format(self.name))
        if self.deprecated:
            message.warning(
                win_id, '{} is deprecated - {}'.format(self.name,
                                                       self.deprecated))
예제 #19
0
    def __init__(self, url):
        QMainWindow.__init__(self)
        self.setupUi(self)

        # Enable plugins
        QWebSettings.globalSettings().setAttribute(QWebSettings.PluginsEnabled, True)

        # UI: connect signals to slots
        self.pushButton_Back.clicked.connect(self.on_pushButton_Back_clicked)
        self.pushButton_Forward.clicked.connect(self.on_pushButton_Forward_clicked)
        self.pushButton_Go.clicked.connect(self.on_pushButton_Go_clicked)
        self.lineEdit_AddressBar.returnPressed.connect(self.on_pushButton_Go_clicked)

        self.webView.titleChanged.connect(self.onTitleChanged)
        self.webView.loadFinished.connect(self.onLoadingNewPage)

        self.webView.load(url)
예제 #20
0
def init(_args):
    """Initialize the global QWebSettings."""
    cache_path = standarddir.cache()
    data_path = standarddir.data()

    _init_private_browsing()

    QWebSettings.setOfflineWebApplicationCachePath(
        os.path.join(cache_path, 'application-cache'))
    QWebSettings.globalSettings().setLocalStoragePath(
        os.path.join(data_path, 'local-storage'))
    QWebSettings.setOfflineStoragePath(
        os.path.join(data_path, 'offline-storage'))

    websettings.init_mappings(MAPPINGS)
    _set_user_stylesheet()
    objreg.get('config').changed.connect(update_settings)
예제 #21
0
 def __init__(self):
     QMainWindow.__init__(self)
     self.setupUi(self)
     self.predLabel.setText("Ola")
     self.status_ready("Connect Leap and Press Spacebar to start")
     [self.model_path, self.scaler_path] = self.update_models()
     self.thread = PredictionThread(self, os.path.abspath(self.model_path),
                                    os.path.abspath(self.scaler_path))
     self.thread.predict_service.user_ges.msg_ready_signal.connect(
         self.status_ready)
     self.thread.predict_service.user_ges.calibration.msg_ready_signal.connect(
         self.cal_train_msg_slot)
     self.pred_serv_launch = False
     QWebSettings.globalSettings().setAttribute(
         QWebSettings.AcceleratedCompositingEnabled, True)
     QWebSettings.globalSettings().setAttribute(QWebSettings.WebGLEnabled,
                                                True)
     self.applyBtn.clicked.connect(self.applyBtn_clicked)
예제 #22
0
 def _click_js(self, click_target: usertypes.ClickTarget) -> None:
     settings = QWebSettings.globalSettings()
     attribute = QWebSettings.JavascriptCanOpenWindows
     could_open_windows = settings.testAttribute(attribute)
     settings.setAttribute(attribute, True)
     ok = self._elem.evaluateJavaScript('this.click(); true;')
     settings.setAttribute(attribute, could_open_windows)
     if not ok:
         log.webelem.debug("Failed to click via JS, falling back to event")
         self._click_fake_event(click_target)
예제 #23
0
 def _click_js(self, click_target):
     settings = QWebSettings.globalSettings()
     attribute = QWebSettings.JavascriptCanOpenWindows
     could_open_windows = settings.testAttribute(attribute)
     settings.setAttribute(attribute, True)
     ok = self._elem.evaluateJavaScript('this.click(); true;')
     settings.setAttribute(attribute, could_open_windows)
     if not ok:
         log.webelem.debug("Failed to click via JS, falling back to event")
         self._click_fake_event(click_target)
예제 #24
0
def init():
    """Initialize the global QWebSettings."""
    cachedir = standarddir.get(QStandardPaths.CacheLocation)
    QWebSettings.setIconDatabasePath(cachedir)
    QWebSettings.setOfflineWebApplicationCachePath(
        os.path.join(cachedir, 'application-cache'))
    datadir = standarddir.get(QStandardPaths.DataLocation)
    QWebSettings.globalSettings().setLocalStoragePath(
        os.path.join(datadir, 'local-storage'))
    QWebSettings.setOfflineStoragePath(
        os.path.join(datadir, 'offline-storage'))

    global settings
    settings = QWebSettings.globalSettings()
    for sectname, section in MAPPINGS.items():
        for optname, (typ, arg) in section.items():
            value = config.get(sectname, optname)
            _set_setting(typ, arg, value)
    objreg.get('config').changed.connect(update_settings)
예제 #25
0
def init():
    """Initialize the global QWebSettings."""
    cache_path = standarddir.cache()
    data_path = standarddir.data()
    if config.get('general', 'private-browsing') or cache_path is None:
        QWebSettings.setIconDatabasePath('')
    else:
        QWebSettings.setIconDatabasePath(cache_path)
    if cache_path is not None:
        QWebSettings.setOfflineWebApplicationCachePath(
            os.path.join(cache_path, 'application-cache'))
    if data_path is not None:
        QWebSettings.globalSettings().setLocalStoragePath(
            os.path.join(data_path, 'local-storage'))
        QWebSettings.setOfflineStoragePath(
            os.path.join(data_path, 'offline-storage'))

    websettings.init_mappings(MAPPINGS)
    objreg.get('config').changed.connect(update_settings)
예제 #26
0
def init():
    """Initialize the global QWebSettings."""
    cachedir = standarddir.get(QStandardPaths.CacheLocation)
    QWebSettings.setIconDatabasePath(cachedir)
    QWebSettings.setOfflineWebApplicationCachePath(
        os.path.join(cachedir, 'application-cache'))
    datadir = standarddir.get(QStandardPaths.DataLocation)
    QWebSettings.globalSettings().setLocalStoragePath(
        os.path.join(datadir, 'local-storage'))
    QWebSettings.setOfflineStoragePath(os.path.join(datadir,
                                                    'offline-storage'))

    global settings
    settings = QWebSettings.globalSettings()
    for sectname, section in MAPPINGS.items():
        for optname, (typ, arg) in section.items():
            value = config.get(sectname, optname)
            _set_setting(typ, arg, value)
    objreg.get('config').changed.connect(update_settings)
예제 #27
0
def init():
    """Initialize the global QWebSettings."""
    cache_path = standarddir.cache()
    data_path = standarddir.data()
    if config.get('general', 'private-browsing') or cache_path is None:
        QWebSettings.setIconDatabasePath('')
    else:
        QWebSettings.setIconDatabasePath(cache_path)
    if cache_path is not None:
        QWebSettings.setOfflineWebApplicationCachePath(
            os.path.join(cache_path, 'application-cache'))
    if data_path is not None:
        QWebSettings.globalSettings().setLocalStoragePath(
            os.path.join(data_path, 'local-storage'))
        QWebSettings.setOfflineStoragePath(
            os.path.join(data_path, 'offline-storage'))

    websettings.init_mappings(MAPPINGS)
    objreg.get('config').changed.connect(update_settings)
예제 #28
0
    def _get_qws(self, qws):
        """Get the QWebSettings object to use.

        Args:
            qws: The QWebSettings instance to use, or None to use the global
                 instance.
        """
        if qws is None:
            return QWebSettings.globalSettings()
        else:
            return qws
예제 #29
0
def _update_settings(option):
    """Update global settings when qwebsettings changed."""
    global_settings.update_setting(option)

    settings = QWebSettings.globalSettings()
    if option in ['scrollbar.hide', 'content.user_stylesheets']:
        _set_user_stylesheet(settings)
    elif option == 'content.cookies.accept':
        _set_cookie_accept_policy(settings)
    elif option == 'content.cache.maximum_pages':
        _set_cache_maximum_pages(settings)
예제 #30
0
def _update_settings(option):
    """Update global settings when qwebsettings changed."""
    global_settings.update_setting(option)

    settings = QWebSettings.globalSettings()
    if option in ['scrollbar.hide', 'content.user_stylesheets']:
        _set_user_stylesheet(settings)
    elif option == 'content.cookies.accept':
        _set_cookie_accept_policy(settings)
    elif option == 'content.cache.maximum_pages':
        _set_cache_maximum_pages(settings)
예제 #31
0
 def __init__(self):
     global downloads_list_file
     QMainWindow.__init__(self)
     self.setWindowIcon(QIcon(":/quartz.png"))
     self.setWindowTitle("Quartz Browser - " + __version__)
     # Window Properties
     self.history = []
     self.downloads = []
     self.confirm_before_quit = True
     # Create required directories
     for folder in [configdir, icon_dir, thumbnails_dir]:
         if not os.path.exists(folder):
             os.mkdir(folder)
     # Import and Apply Settings
     self.setAttribute(Qt.WA_DeleteOnClose)
     self.settings = QSettings(1, 0, "quartz-browser", "Quartz", self)
     self.opensettings()
     self.websettings = QWebSettings.globalSettings()
     self.websettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True)
     self.websettings.setMaximumPagesInCache(10)
     self.websettings.setIconDatabasePath(icon_dir)
     self.websettings.setAttribute(QWebSettings.JavascriptCanOpenWindows,
                                   True)
     self.websettings.setAttribute(QWebSettings.JavascriptCanCloseWindows,
                                   True)
     if webkit.enable_adblock:
         self.websettings.setUserStyleSheetUrl(
             QUrl.fromLocalFile(program_dir + 'userContent.css'))
     # Import Downloads and Bookmarks
     self.dwnldsmodel = DownloadsModel(self.downloads,
                                       QApplication.instance())
     self.dwnldsmodel.deleteDownloadsRequested.connect(self.deleteDownloads)
     imported_downloads = importDownloads(downloads_list_file)
     for [filepath, url, totalsize, timestamp] in imported_downloads:
         try:  # Check if downloads.txt is valid
             tymstamp = float(timestamp)
         except:
             self.downloads = []
             exportDownloads(downloads_list_file, [])
             print("Error in importing Downloads.")
             break
         old_download = Download(networkmanager)
         old_download.loadDownload(filepath, url, totalsize, timestamp)
         old_download.datachanged.connect(self.dwnldsmodel.datachanged)
         self.downloads.append(old_download)
     self.bookmarks = importBookmarks(configdir + "bookmarks.txt")
     self.favourites = importFavourites(configdir + 'favourites.txt')
     # Find and set icon theme name
     for theme_name in ['Adwaita', 'Gnome', 'Tango']:
         if os.path.exists('/usr/share/icons/' + theme_name):
             QIcon.setThemeName(theme_name)
             break
     self.initUI()
     self.resize(1024, 714)
예제 #32
0
    def _get_qws(self, qws):
        """Get the QWebSettings object to use.

        Args:
            qws: The QWebSettings instance to use, or None to use the global
                 instance.
        """
        if qws is None:
            return QWebSettings.globalSettings()
        else:
            return qws
예제 #33
0
def _set_global_render_settings(js_disable_cross_domain_access, private_mode):
    from PyQt5.QtWebKit import QWebSecurityOrigin, QWebSettings

    if js_disable_cross_domain_access is False:
        # In order to enable cross domain requests it is necessary to add
        # the http and https to the local scheme, this way all the urls are
        # seen as inside the same security origin.
        for scheme in ['http', 'https']:
            QWebSecurityOrigin.addLocalScheme(scheme)

    settings = QWebSettings.globalSettings()
    settings.setAttribute(QWebSettings.PrivateBrowsingEnabled, private_mode)
예제 #34
0
    def prepare(self, metaData):
        """
        Public method to prepare the disk cache file.
        
        @param metaData meta data for a URL (QNetworkCacheMetaData)
        @return reference to the IO device (QIODevice)
        """
        if QWebSettings.globalSettings().testAttribute(
                QWebSettings.PrivateBrowsingEnabled):
            return None

        return QNetworkDiskCache.prepare(self, metaData)
예제 #35
0
 def prepare(self, metaData):
     """
     Public method to prepare the disk cache file.
     
     @param metaData meta data for a URL (QNetworkCacheMetaData)
     @return reference to the IO device (QIODevice)
     """
     if QWebSettings.globalSettings().testAttribute(
             QWebSettings.PrivateBrowsingEnabled):
         return None
     
     return QNetworkDiskCache.prepare(self, metaData)
예제 #36
0
파일: main.py 프로젝트: vinhut/nooto
    def __init__(self):
        # Explaining super is out of the scope of this article
        # So please google it if you're not familar with it
        # Simple reason why we use it here is that it allows us to
        # access variables, methods etc in the design.py file
        super(self.__class__, self).__init__()
        self.setupUi(self)  # This is defined in ui file automatically
        self.fillPassword()

        self.conn = sqlite3.connect("nooto.db")
        self.conn.row_factory = sqlite3.Row
        self.curs = self.conn.cursor()
        self.curs.execute("SELECT id,title,parent FROM Note")
        titles = self.curs.fetchall()

        self.id2objmap = {}
        # sort by parent value
        titles = sorted(titles, key=lambda parent: parent["parent"])

        for row in titles:
            if row["parent"] == None:
                title = self.decrypt(row["title"])
                item = QTreeWidgetItem(self.treeWidget)
                item.setText(0, title)
                item.setText(1, str(row["id"]))
                self.id2objmap[row["id"]] = {"title": title, "parent": None, "object": item}
            else:
                title = self.decrypt(row["title"])
                parent = row["parent"]
                item = QTreeWidgetItem(self.id2objmap[parent]["object"])
                item.setText(0, title)
                item.setText(1, str(row["id"]))
                item.setText(2, str(parent))
                self.id2objmap[row["id"]] = {"title": title, "parent": parent, "object": item}

        self.treeWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.treeWidget.customContextMenuRequested.connect(self.openContextMenu)
        self.treeWidget.setHeaderLabel("Note Title")
        self.treeWidget.setColumnCount(1)
        self.treeWidget.expandAll()

        settings = QWebSettings.globalSettings()
        settings.setAttribute(QWebSettings.JavascriptCanAccessClipboard, True)
        settings.setAttribute(QWebSettings.PluginsEnabled, True)

        url = QUrl("file://" + os.getcwd() + "/index.html")
        # url = QUrl('http://www.tinymce.com/tryit/full.php')
        self.webView.setUrl(url)
        # self.webView.page().setContentEditable(True)
        self.webView.page().mainFrame().addToJavaScriptWindowObject("pyObj", self)

        self.treeWidget.itemClicked.connect(self.getTreeItemText)
예제 #37
0
파일: server.py 프로젝트: Bzisch/splash
def _set_global_render_settings(js_disable_cross_domain_access, private_mode):
    from PyQt5.QtWebKit import QWebSecurityOrigin, QWebSettings

    if js_disable_cross_domain_access is False:
        # In order to enable cross domain requests it is necessary to add
        # the http and https to the local scheme, this way all the urls are
        # seen as inside the same security origin.
        for scheme in ['http', 'https']:
            QWebSecurityOrigin.addLocalScheme(scheme)

    settings = QWebSettings.globalSettings()
    settings.setAttribute(QWebSettings.PrivateBrowsingEnabled, private_mode)
    settings.setAttribute(QWebSettings.LocalStorageEnabled, not private_mode)
예제 #38
0
def init(_args):
    """Initialize the global QWebSettings."""
    cache_path = standarddir.cache()
    data_path = standarddir.data()

    QWebSettings.setIconDatabasePath(standarddir.cache())
    QWebSettings.setOfflineWebApplicationCachePath(
        os.path.join(cache_path, 'application-cache'))
    QWebSettings.globalSettings().setLocalStoragePath(
        os.path.join(data_path, 'local-storage'))
    QWebSettings.setOfflineStoragePath(
        os.path.join(data_path, 'offline-storage'))

    settings = QWebSettings.globalSettings()
    _set_user_stylesheet(settings)
    _set_cookie_accept_policy(settings)
    _set_cache_maximum_pages(settings)

    config.instance.changed.connect(_update_settings)

    global global_settings
    global_settings = WebKitSettings(QWebSettings.globalSettings())
    global_settings.init_settings()
예제 #39
0
def init(_args):
    """Initialize the global QWebSettings."""
    cache_path = standarddir.cache()
    data_path = standarddir.data()

    QWebSettings.setIconDatabasePath(standarddir.cache())
    QWebSettings.setOfflineWebApplicationCachePath(
        os.path.join(cache_path, 'application-cache'))
    QWebSettings.globalSettings().setLocalStoragePath(
        os.path.join(data_path, 'local-storage'))
    QWebSettings.setOfflineStoragePath(
        os.path.join(data_path, 'offline-storage'))

    if (config.get('general', 'private-browsing') and
            not qtutils.version_check('5.4.2')):
        # WORKAROUND for https://codereview.qt-project.org/#/c/108936/
        # Won't work when private browsing is not enabled globally, but that's
        # the best we can do...
        QWebSettings.setIconDatabasePath('')

    websettings.init_mappings(MAPPINGS)
    _set_user_stylesheet()
    objreg.get('config').changed.connect(update_settings)
예제 #40
0
    def _addHistoryEntry(self, itm):
        """
        Protected method to add a history item.
        
        @param itm reference to the history item to add (HistoryEntry)
        """
        globalSettings = QWebSettings.globalSettings()
        if globalSettings.testAttribute(QWebSettings.PrivateBrowsingEnabled):
            return

        self.__history.insert(0, itm)
        self.entryAdded.emit(itm)
        if len(self.__history) == 1:
            self.__checkForExpired()
예제 #41
0
    def _addHistoryEntry(self, itm):
        """
        Protected method to add a history item.
        
        @param itm reference to the history item to add (HistoryEntry)
        """
        globalSettings = QWebSettings.globalSettings()
        if globalSettings.testAttribute(QWebSettings.PrivateBrowsingEnabled):
            return

        self.__history.insert(0, itm)
        self.entryAdded.emit(itm)
        if len(self.__history) == 1:
            self.__checkForExpired()
예제 #42
0
def applyWebSettings():
    websettings = QWebSettings.globalSettings()
    websettings.setAttribute(
        websettings.XSSAuditingEnabled,
        settings.setting_to_bool("network/XSSAuditingEnabled"))
    websettings.setAttribute(
        websettings.DnsPrefetchEnabled,
        settings.setting_to_bool("network/DnsPrefetchEnabled"))
    websettings.setAttribute(
        websettings.AutoLoadImages,
        settings.setting_to_bool("content/AutoLoadImages"))
    websettings.setAttribute(
        websettings.JavascriptCanOpenWindows,
        settings.setting_to_bool("content/JavascriptCanOpenWindows"))
    websettings.setAttribute(
        websettings.JavascriptCanCloseWindows,
        settings.setting_to_bool("content/JavascriptCanCloseWindows"))
    websettings.setAttribute(
        websettings.JavascriptCanAccessClipboard,
        settings.setting_to_bool("content/JavascriptCanAccessClipboard"))
    websettings.setAttribute(websettings.JavaEnabled,
                             settings.setting_to_bool("content/JavaEnabled"))
    websettings.setAttribute(
        websettings.PrintElementBackgrounds,
        settings.setting_to_bool("content/PrintElementBackgrounds"))
    websettings.setAttribute(
        websettings.FrameFlatteningEnabled,
        settings.setting_to_bool("content/FrameFlatteningEnabled"))
    websettings.setAttribute(
        websettings.PluginsEnabled,
        settings.setting_to_bool("content/PluginsEnabled"))
    websettings.setAttribute(
        websettings.TiledBackingStoreEnabled,
        settings.setting_to_bool("content/TiledBackingStoreEnabled"))
    websettings.setAttribute(
        websettings.SiteSpecificQuirksEnabled,
        settings.setting_to_bool("content/SiteSpecificQuirksEnabled"))
    try:
        websettings.setAttribute(
            websettings.SpatialNavigationEnabled,
            settings.setting_to_bool("navigation/SpatialNavigationEnabled"))
    except:
        pass
    try:
        websettings.setAttribute(
            websettings.CaretBrowsingEnabled,
            settings.setting_to_bool("navigation/CaretBrowsingEnabled"))
    except:
        pass
예제 #43
0
    def cookiesForUrl(self, url):
        """
        Public method to get the cookies for a URL.
        
        @param url URL to get cookies for (QUrl)
        @return list of cookies (list of QNetworkCookie)
        """
        if not self.__loaded:
            self.load()

        globalSettings = QWebSettings.globalSettings()
        if globalSettings.testAttribute(QWebSettings.PrivateBrowsingEnabled):
            return []

        return QNetworkCookieJar.cookiesForUrl(self, url)
예제 #44
0
    def __init__(self, parent=None, debug=True):
        QWebView.__init__(self, parent=parent)

        cache = QNetworkDiskCache()
        cache.setCacheDirectory("cache")
        self.page().networkAccessManager().setCache(cache)
        self.page().networkAccessManager()

        if debug:
            QWebSettings.globalSettings().setAttribute(
                QWebSettings.DeveloperExtrasEnabled, True)

        self.initialized = False

        self.page().mainFrame().addToJavaScriptWindowObject("qtWidget", self)

        basePath = os.path.abspath(os.path.dirname(__file__))
        url = 'file://' + basePath + '/qOSM.html'
        self.load(QUrl(url))

        self.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)

        self.loadFinished.connect(self.onLoadFinished)
        self.linkClicked.connect(QDesktopServices.openUrl)
예제 #45
0
 def __init__(self, *args, **kwargs):
     super(Window, self).__init__(*args, **kwargs)
     self.resize(800, 600)
     # 浏览器设置
     setting = QWebSettings.globalSettings()
     setting.setAttribute(QWebSettings.PluginsEnabled, True)
     # 解决xp下ssl问题
     self.page().networkAccessManager().sslErrors.connect(self.handleSslErrors)
     sslconf = QSslConfiguration.defaultConfiguration()
     clist = sslconf.caCertificates()
     cnew = QSslCertificate.fromData(b"CaCertificates")
     clist.extend(cnew)
     sslconf.setCaCertificates(clist)
     sslconf.setProtocol(QSsl.AnyProtocol)
     QSslConfiguration.setDefaultConfiguration(sslconf)
예제 #46
0
파일: CookieJar.py 프로젝트: testmana2/test
 def cookiesForUrl(self, url):
     """
     Public method to get the cookies for a URL.
     
     @param url URL to get cookies for (QUrl)
     @return list of cookies (list of QNetworkCookie)
     """
     if not self.__loaded:
         self.load()
     
     globalSettings = QWebSettings.globalSettings()
     if globalSettings.testAttribute(QWebSettings.PrivateBrowsingEnabled):
         return []
     
     return QNetworkCookieJar.cookiesForUrl(self, url)
예제 #47
0
    def recordBrowser(self, browser, position):
        """
        Public method to record the data of a browser about to be closed.
        
        @param browser reference to the browser to be closed (HelpBrowser)
        @param position index of the tab to be closed (integer)
        """
        globalSettings = QWebSettings.globalSettings()
        if globalSettings.testAttribute(QWebSettings.PrivateBrowsingEnabled):
            return

        if browser.url().isEmpty():
            return

        tab = ClosedTab(browser.url(), browser.title(), position)
        self.__closedTabs.insert(0, tab)
        self.closedTabAvailable.emit(True)
예제 #48
0
 def recordBrowser(self, browser, position):
     """
     Public method to record the data of a browser about to be closed.
     
     @param browser reference to the browser to be closed (HelpBrowser)
     @param position index of the tab to be closed (integer)
     """
     globalSettings = QWebSettings.globalSettings()
     if globalSettings.testAttribute(QWebSettings.PrivateBrowsingEnabled):
         return
     
     if browser.url().isEmpty():
         return
     
     tab = ClosedTab(browser.url(), browser.title(), position)
     self.__closedTabs.insert(0, tab)
     self.closedTabAvailable.emit(True)
예제 #49
0
 def __updateRow(self, itm=None):
     """
     Private slot to update a download item.
     
     @param itm reference to the download item (DownloadItem)
     """
     if itm is None:
         itm = self.sender()
     
     if itm not in self.__downloads:
         return
     
     row = self.__downloads.index(itm)
     
     if self.__iconProvider is None:
         self.__iconProvider = QFileIconProvider()
     
     icon = self.__iconProvider.icon(QFileInfo(itm.fileName()))
     if icon.isNull():
         icon = self.style().standardIcon(QStyle.SP_FileIcon)
     itm.setIcon(icon)
     
     oldHeight = self.downloadsView.rowHeight(row)
     self.downloadsView.setRowHeight(
         row,
         max(oldHeight, itm.minimumSizeHint().height() * 1.5))
     
     remove = False
     globalSettings = QWebSettings.globalSettings()
     if not itm.downloading() and \
        globalSettings.testAttribute(QWebSettings.PrivateBrowsingEnabled):
         remove = True
     
     if itm.downloadedSuccessfully() and \
        self.removePolicy() == DownloadManager.RemoveSuccessFullDownload:
         remove = True
     
     if remove:
         self.__model.removeRow(row)
     
     self.cleanupButton.setEnabled(
         (len(self.__downloads) - self.activeDownloads()) > 0)
     
     # record the change
     self.changeOccurred()
예제 #50
0
파일: common.py 프로젝트: ismlsmile/nimbus
def applyWebSettings():
    websettings = QWebSettings.globalSettings()
    websettings.setAttribute(websettings.XSSAuditingEnabled, settings.setting_to_bool("network/XSSAuditingEnabled"))
    websettings.setAttribute(websettings.DnsPrefetchEnabled, settings.setting_to_bool("network/DnsPrefetchEnabled"))
    websettings.setAttribute(websettings.AutoLoadImages, settings.setting_to_bool("content/AutoLoadImages"))
    websettings.setAttribute(websettings.JavascriptCanOpenWindows, settings.setting_to_bool("content/JavascriptCanOpenWindows"))
    websettings.setAttribute(websettings.JavascriptCanCloseWindows, settings.setting_to_bool("content/JavascriptCanCloseWindows"))
    websettings.setAttribute(websettings.JavascriptCanAccessClipboard, settings.setting_to_bool("content/JavascriptCanAccessClipboard"))
    websettings.setAttribute(websettings.JavaEnabled, settings.setting_to_bool("content/JavaEnabled"))
    websettings.setAttribute(websettings.PrintElementBackgrounds, settings.setting_to_bool("content/PrintElementBackgrounds"))
    websettings.setAttribute(websettings.FrameFlatteningEnabled, settings.setting_to_bool("content/FrameFlatteningEnabled"))
    websettings.setAttribute(websettings.PluginsEnabled, settings.setting_to_bool("content/PluginsEnabled"))
    websettings.setAttribute(websettings.TiledBackingStoreEnabled, settings.setting_to_bool("content/TiledBackingStoreEnabled"))
    websettings.setAttribute(websettings.SiteSpecificQuirksEnabled, settings.setting_to_bool("content/SiteSpecificQuirksEnabled"))
    try: websettings.setAttribute(websettings.SpatialNavigationEnabled, settings.setting_to_bool("navigation/SpatialNavigationEnabled"))
    except: pass
    try: websettings.setAttribute(websettings.CaretBrowsingEnabled, settings.setting_to_bool("navigation/CaretBrowsingEnabled"))
    except: pass
예제 #51
0
 def __searchNow(self):
     """
     Private slot to perform the web search.
     """
     searchText = self.text()
     if not searchText:
         return
     
     globalSettings = QWebSettings.globalSettings()
     if not globalSettings.testAttribute(
             QWebSettings.PrivateBrowsingEnabled):
         if searchText in self.__recentSearches:
             self.__recentSearches.remove(searchText)
         self.__recentSearches.insert(0, searchText)
         if len(self.__recentSearches) > self.__maxSavedSearches:
             self.__recentSearches = \
                 self.__recentSearches[:self.__maxSavedSearches]
         self.__setupCompleterMenu()
     
     url = self.__openSearchManager.currentEngine().searchUrl(searchText)
     self.search.emit(url)
예제 #52
0
    def _check_prerequisites(self):
        """Check if the command is permitted to run currently.

        Raise:
            PrerequisitesError if the command can't be called currently.
        """
        curmode = objreg.get('mode-manager').mode()
        if self._modes is not None and curmode not in self._modes:
            mode_names = '/'.join(mode.name for mode in self._modes)
            raise cmdexc.PrerequisitesError(
                "{}: This command is only allowed in {} mode.".format(
                    self.name, mode_names))
        elif self._not_modes is not None and curmode in self._not_modes:
            mode_names = '/'.join(mode.name for mode in self._not_modes)
            raise cmdexc.PrerequisitesError(
                "{}: This command is not allowed in {} mode.".format(
                    self.name, mode_names))
        if self._needs_js and not QWebSettings.globalSettings().testAttribute(
                QWebSettings.JavascriptEnabled):
            raise cmdexc.PrerequisitesError(
                "{}: This command needs javascript enabled.".format(self.name))
예제 #53
0
    def _follow_selected(self, *, tab=False):
        if QWebSettings.globalSettings().testAttribute(
                QWebSettings.JavascriptEnabled):
            if tab:
                self._tab.data.override_target = usertypes.ClickTarget.tab
            self._tab.run_js_async("""
                const aElm = document.activeElement;
                if (window.getSelection().anchorNode) {
                    window.getSelection().anchorNode.parentNode.click();
                } else if (aElm && aElm !== document.body) {
                    aElm.click();
                }
            """)
        else:
            selection = self._widget.selectedHtml()
            if not selection:
                # Getting here may mean we crashed, but we can't do anything
                # about that until this commit is released:
                # https://github.com/annulen/webkit/commit/0e75f3272d149bc64899c161f150eb341a2417af
                # TODO find a way to check if something is focused
                self._follow_enter(tab)
                return
            try:
                selected_element = xml.etree.ElementTree.fromstring(
                    '<html>{}</html>'.format(selection)).find('a')
            except xml.etree.ElementTree.ParseError:
                raise browsertab.WebTabError('Could not parse selected '
                                             'element!')

            if selected_element is not None:
                try:
                    url = selected_element.attrib['href']
                except KeyError:
                    raise browsertab.WebTabError('Anchor element without '
                                                 'href!')
                url = self._tab.url().resolved(QUrl(url))
                if tab:
                    self._tab.new_tab_requested.emit(url)
                else:
                    self._tab.openurl(url)
예제 #54
0
    def _check_prerequisites(self, win_id):
        """Check if the command is permitted to run currently.

        Args:
            win_id: The window ID the command is run in.
        """
        mode_manager = objreg.get('mode-manager', scope='window',
                                  window=win_id)
        curmode = mode_manager.mode
        if self._modes is not None and curmode not in self._modes:
            mode_names = '/'.join(mode.name for mode in self._modes)
            raise cmdexc.PrerequisitesError(
                "{}: This command is only allowed in {} mode.".format(
                    self.name, mode_names))
        elif self._not_modes is not None and curmode in self._not_modes:
            mode_names = '/'.join(mode.name for mode in self._not_modes)
            raise cmdexc.PrerequisitesError(
                "{}: This command is not allowed in {} mode.".format(
                    self.name, mode_names))

        if self._needs_js and not QWebSettings.globalSettings().testAttribute(
                QWebSettings.JavascriptEnabled):
            raise cmdexc.PrerequisitesError(
                "{}: This command needs javascript enabled.".format(self.name))

        backend_mapping = {
            'webkit': usertypes.Backend.QtWebKit,
            'webengine': usertypes.Backend.QtWebEngine,
        }
        used_backend = backend_mapping[objreg.get('args').backend]
        if self.backend is not None and used_backend != self.backend:
            raise cmdexc.PrerequisitesError(
                "{}: Only available with {} "
                "backend.".format(self.name, self.backend.name))

        if self.deprecated:
            message.warning(win_id, '{} is deprecated - {}'.format(
                self.name, self.deprecated))
예제 #55
0
    def follow_selected(self, *, tab=False):
        if not self.has_selection():
            return
        if QWebSettings.globalSettings().testAttribute(QWebSettings.JavascriptEnabled):
            if tab:
                self._widget.page().open_target = usertypes.ClickTarget.tab
            self._tab.run_js_async("window.getSelection().anchorNode.parentNode.click()")
        else:
            selection = self.selection(html=True)
            try:
                selected_element = xml.etree.ElementTree.fromstring("<html>{}</html>".format(selection)).find("a")
            except xml.etree.ElementTree.ParseError:
                raise browsertab.WebTabError("Could not parse selected " "element!")

            if selected_element is not None:
                try:
                    url = selected_element.attrib["href"]
                except KeyError:
                    raise browsertab.WebTabError("Anchor element without " "href!")
                url = self._tab.url().resolved(QUrl(url))
                if tab:
                    self._tab.new_tab_requested.emit(url)
                else:
                    self._tab.openurl(url)
예제 #56
0
 def post(self, request, data):
     """
     Public method to check, if the data to be sent contains login data.
     
     @param request reference to the network request (QNetworkRequest)
     @param data data to be sent (QByteArray)
     """
     # shall passwords be saved?
     if not Preferences.getUser("SavePasswords"):
         return
     
     # observe privacy
     if QWebSettings.globalSettings().testAttribute(
             QWebSettings.PrivateBrowsingEnabled):
         return
     
     if not self.__loaded:
         self.__load()
     
     # determine the url
     refererHeader = request.rawHeader(b"Referer")
     if refererHeader.isEmpty():
         return
     url = QUrl.fromEncoded(refererHeader)
     url = self.__stripUrl(url)
     
     # check that url isn't in __never
     if url.toString() in self.__never:
         return
     
     # check the request type
     navType = request.attribute(QNetworkRequest.User + 101)
     if navType is None:
         return
     if navType != QWebPage.NavigationTypeFormSubmitted:
         return
     
     # determine the QWebPage
     webPage = request.attribute(QNetworkRequest.User + 100)
     if webPage is None:
         return
     
     # determine the requests content type
     contentTypeHeader = request.rawHeader(b"Content-Type")
     if contentTypeHeader.isEmpty():
         return
     multipart = contentTypeHeader.startsWith(b"multipart/form-data")
     if multipart:
         boundary = contentTypeHeader.split(" ")[1].split("=")[1]
     else:
         boundary = None
     
     # find the matching form on the web page
     form = self.__findForm(webPage, data, boundary=boundary)
     if not form.isValid():
         return
     form.url = QUrl(url)
     
     # check, if the form has a password
     if not form.hasAPassword:
         return
     
     # prompt, if the form has never be seen
     key = self.__createKey(url, "")
     if key not in self.__loginForms:
         mb = E5MessageBox.E5MessageBox(
             E5MessageBox.Question,
             self.tr("Save password"),
             self.tr(
                 """<b>Would you like to save this password?</b><br/>"""
                 """To review passwords you have saved and remove them, """
                 """use the password management dialog of the Settings"""
                 """ menu."""),
             modal=True)
         neverButton = mb.addButton(
             self.tr("Never for this site"),
             E5MessageBox.DestructiveRole)
         noButton = mb.addButton(
             self.tr("Not now"), E5MessageBox.RejectRole)
         mb.addButton(E5MessageBox.Yes)
         mb.exec_()
         if mb.clickedButton() == neverButton:
             self.__never.append(url.toString())
             return
         elif mb.clickedButton() == noButton:
             return
     
     # extract user name and password
     user = ""
     password = ""
     for index in range(len(form.elements)):
         element = form.elements[index]
         type_ = form.elementTypes[element[0]]
         if user == "" and \
            type_ == "text":
             user = element[1]
         elif password == "" and \
                 type_ == "password":
             password = element[1]
             form.elements[index] = (element[0], "--PASSWORD--")
     if user and password:
         self.__logins[key] = \
             (user, Utilities.crypto.pwConvert(password, encode=True))
         self.__loginForms[key] = form
         self.changed.emit()
예제 #57
0
def main(reactorString, ampChildPath):
#def main():

    from twisted.internet import reactor, stdio
    from twisted.python import reflect, runtime
    #ampChild = reflect.namedAny(ampChildPath)
    #protInstance = ampChild(*sys.argv[1:-2]) # This is how you reach the prot from here.
    protInstance = ''

    from twisted.internet import reactor # this is actually used, ignore the warning.
    hermes = Hermes.Hermes(protInstance)
    charon = Charon(hermes)
    view = AetherMainWindow(charon, reactor, baseurl, protInstance)
    trayIcon = SystemTrayIcon(basedir, app, view)
    trayIcon.protInstance = protInstance
    #protInstance.trayIcon = trayIcon
    ef = ModifierEventFilter()
    app.view = view
    ef.view = view
    app.trayIcon = trayIcon
    view.trayIcon = trayIcon
    ef.trayIcon = trayIcon
    charon.trayIcon = trayIcon
    trayIcon.webView = view
    app.installEventFilter(ef)
    trayIcon.show()

    #FIXME before package
    enableWebkitInspector = False
    if enableWebkitInspector is True:
        from PyQt5.QtWebKit import QWebSettings
        QWebSettings.globalSettings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
        inspect = QWebInspector()
        inspect.resize(1450, 300)
        inspect.move(0,0)
        inspect.setPage(view.webView.page())
        view.setContextMenuPolicy(Qt.DefaultContextMenu)
        inspect.show()

    splash.finish(view)
    if not globals.appStartedAtBoot:
        view.show()
        trayIcon.toggleVisibilityMenuItem.setText('Hide Aether')

    if runtime.platform.isWindows():
        stdio.StandardIO(protInstance)
    else:
        stdio.StandardIO(protInstance, 3, 4)
    #enter = getattr(ampChild, '__enter__', None)
    # if enter is not None:
    #     enter()
    # try:
    #     reactor.run()
    # except:
    #     if enter is not None:
    #         info = sys.exc_info()
    #         if not ampChild.__exit__(*info):
    #             raise
    #     else:
    #         raise
    # else:
    #     if enter is not None:
    #         ampChild.__exit__(None, None, None)
    reactor.run()