summaryrefslogtreecommitdiff
path: root/qutebrowser/browser/webkit/webkitsettings.py
blob: bd65be65b503ff1b6bec4efb005696b1451808c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# Copyright 2016-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser.  If not, see <https://www.gnu.org/licenses/>.

# FIXME:qt6 (lint)
# pylint: disable=no-name-in-module

"""Bridge from QWebSettings to our own settings.

Module attributes:
    ATTRIBUTES: A mapping from internal setting names to QWebSetting enum
                constants.
"""

from typing import cast
import os.path

from qutebrowser.qt.core import QUrl
from qutebrowser.qt.gui import QFont
from qutebrowser.qt.webkit import QWebSettings
from qutebrowser.qt.webkitwidgets import QWebPage

from qutebrowser.config import config, websettings
from qutebrowser.config.websettings import AttributeInfo as Attr
from qutebrowser.utils import standarddir, urlutils
from qutebrowser.browser import shared


# The global WebKitSettings object
global_settings = cast('WebKitSettings', None)

parsed_user_agent = None


class WebKitSettings(websettings.AbstractSettings):

    """A wrapper for the config for QWebSettings."""

    _ATTRIBUTES = {
        'content.images':
            Attr(QWebSettings.WebAttribute.AutoLoadImages),
        'content.javascript.enabled':
            Attr(QWebSettings.WebAttribute.JavascriptEnabled),
        'content.javascript.can_open_tabs_automatically':
            Attr(QWebSettings.WebAttribute.JavascriptCanOpenWindows),
        'content.javascript.can_close_tabs':
            Attr(QWebSettings.WebAttribute.JavascriptCanCloseWindows),
        'content.javascript.clipboard':
            Attr(QWebSettings.WebAttribute.JavascriptCanAccessClipboard,
                 converter=lambda val: val != "none"),
        'content.plugins':
            Attr(QWebSettings.WebAttribute.PluginsEnabled),
        'content.webgl':
            Attr(QWebSettings.WebAttribute.WebGLEnabled),
        'content.hyperlink_auditing':
            Attr(QWebSettings.WebAttribute.HyperlinkAuditingEnabled),
        'content.local_content_can_access_remote_urls':
            Attr(QWebSettings.WebAttribute.LocalContentCanAccessRemoteUrls),
        'content.local_content_can_access_file_urls':
            Attr(QWebSettings.WebAttribute.LocalContentCanAccessFileUrls),
        'content.dns_prefetch':
            Attr(QWebSettings.WebAttribute.DnsPrefetchEnabled),
        'content.frame_flattening':
            Attr(QWebSettings.WebAttribute.FrameFlatteningEnabled),
        'content.cache.appcache':
            Attr(QWebSettings.WebAttribute.OfflineWebApplicationCacheEnabled),
        'content.local_storage':
            Attr(QWebSettings.WebAttribute.LocalStorageEnabled,
                 QWebSettings.WebAttribute.OfflineStorageDatabaseEnabled),
        'content.print_element_backgrounds':
            Attr(QWebSettings.WebAttribute.PrintElementBackgrounds),
        'content.xss_auditing':
            Attr(QWebSettings.WebAttribute.XSSAuditingEnabled),
        'content.site_specific_quirks.enabled':
            Attr(QWebSettings.WebAttribute.SiteSpecificQuirksEnabled),

        'input.spatial_navigation':
            Attr(QWebSettings.WebAttribute.SpatialNavigationEnabled),
        'input.links_included_in_focus_chain':
            Attr(QWebSettings.WebAttribute.LinksIncludedInFocusChain),

        'zoom.text_only':
            Attr(QWebSettings.WebAttribute.ZoomTextOnly),
        'scrolling.smooth':
            Attr(QWebSettings.WebAttribute.ScrollAnimatorEnabled),
    }

    _FONT_SIZES = {
        'fonts.web.size.minimum':
            QWebSettings.FontSize.MinimumFontSize,
        'fonts.web.size.minimum_logical':
            QWebSettings.FontSize.MinimumLogicalFontSize,
        'fonts.web.size.default':
            QWebSettings.FontSize.DefaultFontSize,
        'fonts.web.size.default_fixed':
            QWebSettings.FontSize.DefaultFixedFontSize,
    }

    _FONT_FAMILIES = {
        'fonts.web.family.standard': QWebSettings.FontFamily.StandardFont,
        'fonts.web.family.fixed': QWebSettings.FontFamily.FixedFont,
        'fonts.web.family.serif': QWebSettings.FontFamily.SerifFont,
        'fonts.web.family.sans_serif': QWebSettings.FontFamily.SansSerifFont,
        'fonts.web.family.cursive': QWebSettings.FontFamily.CursiveFont,
        'fonts.web.family.fantasy': QWebSettings.FontFamily.FantasyFont,
    }

    # Mapping from QWebSettings::QWebSettings() in
    # qtwebkit/Source/WebKit/qt/Api/qwebsettings.cpp
    _FONT_TO_QFONT = {
        QWebSettings.FontFamily.StandardFont: QFont.StyleHint.Serif,
        QWebSettings.FontFamily.FixedFont: QFont.StyleHint.Monospace,
        QWebSettings.FontFamily.SerifFont: QFont.StyleHint.Serif,
        QWebSettings.FontFamily.SansSerifFont: QFont.StyleHint.SansSerif,
        QWebSettings.FontFamily.CursiveFont: QFont.StyleHint.Cursive,
        QWebSettings.FontFamily.FantasyFont: QFont.StyleHint.Fantasy,
    }


def _set_user_stylesheet(settings):
    """Set the generated user-stylesheet."""
    stylesheet = shared.get_user_stylesheet().encode('utf-8')
    url = urlutils.data_url('text/css;charset=utf-8', stylesheet)
    settings.setUserStyleSheetUrl(url)


def _set_cookie_accept_policy(settings):
    """Update the content.cookies.accept setting."""
    mapping = {
        'all': QWebSettings.ThirdPartyCookiePolicy.AlwaysAllowThirdPartyCookies,
        'no-3rdparty': QWebSettings.ThirdPartyCookiePolicy.AlwaysBlockThirdPartyCookies,
        'never': QWebSettings.ThirdPartyCookiePolicy.AlwaysBlockThirdPartyCookies,
        'no-unknown-3rdparty': QWebSettings.ThirdPartyCookiePolicy.AllowThirdPartyWithExistingCookies,
    }
    value = config.val.content.cookies.accept
    settings.setThirdPartyCookiePolicy(mapping[value])


def _set_cache_maximum_pages(settings):
    """Update the content.cache.maximum_pages setting."""
    value = config.val.content.cache.maximum_pages
    settings.setMaximumPagesInCache(value)


def _update_settings(option):
    """Update global settings when qwebsettings changed."""
    global_settings.update_setting(option)

    settings = QWebSettings.globalSettings()
    if option in ['scrollbar.hide', 'content.user_stylesheets']:
        _set_user_stylesheet(settings)
    elif option == 'content.cookies.accept':
        _set_cookie_accept_policy(settings)
    elif option == 'content.cache.maximum_pages':
        _set_cache_maximum_pages(settings)


def _init_user_agent():
    global parsed_user_agent
    ua = QWebPage().userAgentForUrl(QUrl())
    parsed_user_agent = websettings.UserAgent.parse(ua)


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()


def shutdown():
    """Disable storage so removing tmpdir will work."""
    QWebSettings.setIconDatabasePath('')
    QWebSettings.setOfflineWebApplicationCachePath('')
    QWebSettings.globalSettings().setLocalStoragePath('')