summaryrefslogtreecommitdiff
path: root/qutebrowser/config/configinit.py
blob: 20f40420d369c2f67e0c2536d7185f6301c7d5f7 (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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:

# Copyright 2017-2020 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 <http://www.gnu.org/licenses/>.

"""Initialization of the configuration."""

import argparse
import os.path
import sys
import typing

from PyQt5.QtWidgets import QMessageBox

from qutebrowser.api import config as configapi
from qutebrowser.config import (config, configdata, configfiles, configtypes,
                                configexc, configcommands, stylesheet)
from qutebrowser.utils import (objreg, usertypes, log, standarddir, message,
                               qtutils)
from qutebrowser.config import configcache
from qutebrowser.misc import msgbox, objects, savemanager


# Error which happened during init, so we can show a message box.
_init_errors = None


def early_init(args: argparse.Namespace) -> None:
    """Initialize the part of the config which works without a QApplication."""
    configdata.init()

    yaml_config = configfiles.YamlConfig()

    config.instance = config.Config(yaml_config=yaml_config)
    config.val = config.ConfigContainer(config.instance)
    configapi.val = config.ConfigContainer(config.instance)
    config.key_instance = config.KeyConfig(config.instance)
    config.cache = configcache.ConfigCache()
    yaml_config.setParent(config.instance)

    for cf in config.change_filters:
        cf.validate()

    config_commands = configcommands.ConfigCommands(
        config.instance, config.key_instance)
    objreg.register('config-commands', config_commands, command_only=True)

    config_file = standarddir.config_py()
    global _init_errors

    try:
        if os.path.exists(config_file):
            configfiles.read_config_py(config_file)
        else:
            configfiles.read_autoconfig()
    except configexc.ConfigFileErrors as e:
        log.config.exception("Error while loading {}".format(e.basename))
        _init_errors = e

    try:
        configfiles.init()
    except configexc.ConfigFileErrors as e:
        _init_errors = e

    for opt, val in args.temp_settings:
        try:
            config.instance.set_str(opt, val)
        except configexc.Error as e:
            message.error("set: {} - {}".format(e.__class__.__name__, e))

    objects.backend = get_backend(args)
    objects.debug_flags = set(args.debug_flags)

    stylesheet.init()

    _init_envvars()


def _init_envvars() -> None:
    """Initialize environment variables which need to be set early."""
    if objects.backend == usertypes.Backend.QtWebEngine:
        software_rendering = config.val.qt.force_software_rendering
        if software_rendering == 'software-opengl':
            os.environ['QT_XCB_FORCE_SOFTWARE_OPENGL'] = '1'
        elif software_rendering == 'qt-quick':
            os.environ['QT_QUICK_BACKEND'] = 'software'
        elif software_rendering == 'chromium':
            os.environ['QT_WEBENGINE_DISABLE_NOUVEAU_WORKAROUND'] = '1'

    if config.val.qt.force_platform is not None:
        os.environ['QT_QPA_PLATFORM'] = config.val.qt.force_platform
    if config.val.qt.force_platformtheme is not None:
        os.environ['QT_QPA_PLATFORMTHEME'] = config.val.qt.force_platformtheme

    if config.val.window.hide_decoration:
        os.environ['QT_WAYLAND_DISABLE_WINDOWDECORATION'] = '1'

    if config.val.qt.highdpi:
        env_var = ('QT_ENABLE_HIGHDPI_SCALING'
                   if qtutils.version_check('5.14', compiled=False)
                   else 'QT_AUTO_SCREEN_SCALE_FACTOR')
        os.environ[env_var] = '1'


def _update_font_defaults(setting: str) -> None:
    """Update all fonts if fonts.default_family/_size was set."""
    if setting not in {'fonts.default_family', 'fonts.default_size'}:
        return

    configtypes.Font.set_defaults(config.val.fonts.default_family,
                                  config.val.fonts.default_size)

    for name, opt in configdata.DATA.items():
        if not isinstance(opt.typ, configtypes.Font):
            continue

        value = config.instance.get_obj(name)
        if value is None or not (value.endswith(' default_family') or
                                 'default_size ' in value):
            continue

        config.instance.changed.emit(name)


def get_backend(args: argparse.Namespace) -> usertypes.Backend:
    """Find out what backend to use based on available libraries."""
    str_to_backend = {
        'webkit': usertypes.Backend.QtWebKit,
        'webengine': usertypes.Backend.QtWebEngine,
    }

    if args.backend is not None:
        return str_to_backend[args.backend]
    else:
        return str_to_backend[config.val.backend]


def late_init(save_manager: savemanager.SaveManager) -> None:
    """Initialize the rest of the config after the QApplication is created."""
    global _init_errors
    if _init_errors is not None:
        errbox = msgbox.msgbox(parent=None,
                               title="Error while reading config",
                               text=_init_errors.to_html(),
                               icon=QMessageBox.Warning,
                               plain_text=False)
        errbox.exec_()

        if _init_errors.fatal:
            sys.exit(usertypes.Exit.err_init)

    _init_errors = None

    configtypes.Font.set_defaults(config.val.fonts.default_family,
                                  config.val.fonts.default_size)
    config.instance.changed.connect(_update_font_defaults)

    config.instance.init_save_manager(save_manager)
    configfiles.state.init_save_manager(save_manager)


def qt_args(namespace: argparse.Namespace) -> typing.List[str]:
    """Get the Qt QApplication arguments based on an argparse namespace.

    Args:
        namespace: The argparse namespace.

    Return:
        The argv list to be passed to Qt.
    """
    argv = [sys.argv[0]]

    if namespace.qt_flag is not None:
        argv += ['--' + flag[0] for flag in namespace.qt_flag]

    if namespace.qt_arg is not None:
        for name, value in namespace.qt_arg:
            argv += ['--' + name, value]

    argv += ['--' + arg for arg in config.val.qt.args]

    if objects.backend == usertypes.Backend.QtWebEngine:
        argv += list(_qtwebengine_args(namespace))

    return argv


def _qtwebengine_args(namespace: argparse.Namespace) -> typing.Iterator[str]:
    """Get the QtWebEngine arguments to use based on the config."""
    if not qtutils.version_check('5.11', compiled=False):
        # WORKAROUND equivalent to
        # https://codereview.qt-project.org/#/c/217932/
        # Needed for Qt < 5.9.5 and < 5.10.1
        yield '--disable-shared-workers'

    # WORKAROUND equivalent to
    # https://codereview.qt-project.org/c/qt/qtwebengine/+/256786
    # also see:
    # https://codereview.qt-project.org/c/qt/qtwebengine-chromium/+/265753
    if qtutils.version_check('5.12.3', compiled=False):
        if 'stack' in namespace.debug_flags:
            # Only actually available in Qt 5.12.5, but let's save another
            # check, as passing the option won't hurt.
            yield '--enable-in-process-stack-traces'
    else:
        if 'stack' not in namespace.debug_flags:
            yield '--disable-in-process-stack-traces'

    if 'chromium' in namespace.debug_flags:
        yield '--enable-logging'
        yield '--v=1'

    settings = {
        'qt.force_software_rendering': {
            'software-opengl': None,
            'qt-quick': None,
            'chromium': '--disable-gpu',
            'none': None,
        },
        'content.canvas_reading': {
            True: None,
            False: '--disable-reading-from-canvas',
        },
        'content.webrtc_ip_handling_policy': {
            'all-interfaces': None,
            'default-public-and-private-interfaces':
                '--force-webrtc-ip-handling-policy='
                'default_public_and_private_interfaces',
            'default-public-interface-only':
                '--force-webrtc-ip-handling-policy='
                'default_public_interface_only',
            'disable-non-proxied-udp':
                '--force-webrtc-ip-handling-policy='
                'disable_non_proxied_udp',
        },
        'qt.process_model': {
            'process-per-site-instance': None,
            'process-per-site': '--process-per-site',
            'single-process': '--single-process',
        },
        'qt.low_end_device_mode': {
            'auto': None,
            'always': '--enable-low-end-device-mode',
            'never': '--disable-low-end-device-mode',
        },
        'content.headers.referer': {
            'always': None,
            'never': '--no-referrers',
            'same-domain': '--reduced-referrer-granularity',
        }
    }  # type: typing.Dict[str, typing.Dict[typing.Any, typing.Optional[str]]]

    if not qtutils.version_check('5.11'):
        # On Qt 5.11, we can control this via QWebEngineSettings
        settings['content.autoplay'] = {
            True: None,
            False: '--autoplay-policy=user-gesture-required',
        }

    if qtutils.version_check('5.14'):
        settings['colors.webpage.prefers_color_scheme_dark'] = {
            True: '--force-dark-mode',
            False: None,
        }

    for setting, args in sorted(settings.items()):
        arg = args[config.instance.get(setting)]
        if arg is not None:
            yield arg