We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
prompt_queue is None at shutdown
Seeing this in various crash reports:

```pytb
Traceback (most recent call last):
  File "/usr/lib/python3.9/site-packages/qutebrowser/misc/quitter.py", line 225, in shutdown
    if prompt.prompt_queue.shutdown():
AttributeError: 'NoneType' object has no attribute 'shutdown'
```

https://crashes.qutebrowser.org/lists?search=prompt_queue.shutdown

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `qutebrowser/misc/quitter.py`
Content:
```
1 # Copyright 2014-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
2 #
3 # This file is part of qutebrowser.
4 #
5 # qutebrowser is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # qutebrowser is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with qutebrowser.  If not, see <https://www.gnu.org/licenses/>.
17 
18 """Helpers related to quitting qutebrowser cleanly."""
19 
20 import os
21 import os.path
22 import sys
23 import json
24 import atexit
25 import shutil
26 import argparse
27 import tokenize
28 import functools
29 import subprocess
30 from typing import Iterable, Mapping, MutableSequence, Sequence, cast
31 
32 from qutebrowser.qt.core import QObject, pyqtSignal, QTimer
33 try:
34     import hunter
35 except ImportError:
36     hunter = None
37 
38 import qutebrowser
39 from qutebrowser.api import cmdutils
40 from qutebrowser.utils import log, qtlog
41 from qutebrowser.misc import sessions, ipc, objects
42 from qutebrowser.mainwindow import prompt
43 from qutebrowser.completion.models import miscmodels
44 
45 
46 instance = cast('Quitter', None)
47 
48 
49 class Quitter(QObject):
50 
51     """Utility class to quit/restart the QApplication.
52 
53     Attributes:
54         quit_status: The current quitting status.
55         is_shutting_down: Whether we're currently shutting down.
56         _args: The argparse namespace.
57     """
58 
59     shutting_down = pyqtSignal()  # Emitted immediately before shut down
60 
61     def __init__(self, *,
62                  args: argparse.Namespace,
63                  parent: QObject = None) -> None:
64         super().__init__(parent)
65         self.quit_status = {
66             'crash': True,
67             'tabs': False,
68             'main': False,
69         }
70         self.is_shutting_down = False
71         self._args = args
72 
73     def on_last_window_closed(self) -> None:
74         """Slot which gets invoked when the last window was closed."""
75         self.shutdown(last_window=True)
76 
77     def _compile_modules(self) -> None:
78         """Compile all modules to catch SyntaxErrors."""
79         if os.path.basename(sys.argv[0]) == 'qutebrowser':
80             # Launched via launcher script
81             return
82         elif hasattr(sys, 'frozen'):
83             return
84         else:
85             path = os.path.abspath(os.path.dirname(qutebrowser.__file__))
86             if not os.path.isdir(path):
87                 # Probably running from a python egg.
88                 return
89 
90         for dirpath, _dirnames, filenames in os.walk(path):
91             for fn in filenames:
92                 if os.path.splitext(fn)[1] == '.py' and os.path.isfile(fn):
93                     with tokenize.open(os.path.join(dirpath, fn)) as f:
94                         compile(f.read(), fn, 'exec')
95 
96     def _get_restart_args(
97             self, pages: Iterable[str] = (),
98             session: str = None,
99             override_args: Mapping[str, str] = None
100     ) -> Sequence[str]:
101         """Get args to relaunch qutebrowser.
102 
103         Args:
104             pages: The pages to re-open.
105             session: The session to load, or None.
106             override_args: Argument overrides as a dict.
107 
108         Return:
109             The commandline as a list of strings.
110         """
111         if os.path.basename(sys.argv[0]) == 'qutebrowser':
112             # Launched via launcher script
113             args = [sys.argv[0]]
114         elif hasattr(sys, 'frozen'):
115             args = [sys.executable]
116         else:
117             args = [sys.executable, '-m', 'qutebrowser']
118 
119         # Add all open pages so they get reopened.
120         page_args: MutableSequence[str] = []
121         for win in pages:
122             page_args.extend(win)
123             page_args.append('')
124 
125         # Serialize the argparse namespace into json and pass that to the new
126         # process via --json-args.
127         # We do this as there's no way to "unparse" the namespace while
128         # ignoring some arguments.
129         argdict = vars(self._args)
130         argdict['session'] = None
131         argdict['url'] = []
132         argdict['command'] = page_args[:-1]
133         argdict['json_args'] = None
134         # Ensure the given session (or none at all) gets opened.
135         if session is None:
136             argdict['session'] = None
137             argdict['override_restore'] = True
138         else:
139             argdict['session'] = session
140             argdict['override_restore'] = False
141         # Ensure :restart works with --temp-basedir
142         if self._args.temp_basedir:
143             argdict['temp_basedir'] = False
144             argdict['temp_basedir_restarted'] = True
145 
146         if override_args is not None:
147             argdict.update(override_args)
148 
149         # Dump the data
150         data = json.dumps(argdict)
151         args += ['--json-args', data]
152 
153         log.destroy.debug("args: {}".format(args))
154 
155         return args
156 
157     def restart(self, pages: Sequence[str] = (),
158                 session: str = None,
159                 override_args: Mapping[str, str] = None) -> bool:
160         """Inner logic to restart qutebrowser.
161 
162         The "better" way to restart is to pass a session (_restart usually) as
163         that'll save the complete state.
164 
165         However we don't do that (and pass a list of pages instead) when we
166         restart because of an exception, as that's a lot simpler and we don't
167         want to risk anything going wrong.
168 
169         Args:
170             pages: A list of URLs to open.
171             session: The session to load, or None.
172             override_args: Argument overrides as a dict.
173 
174         Return:
175             True if the restart succeeded, False otherwise.
176         """
177         self._compile_modules()
178         log.destroy.debug("sys.executable: {}".format(sys.executable))
179         log.destroy.debug("sys.path: {}".format(sys.path))
180         log.destroy.debug("sys.argv: {}".format(sys.argv))
181         log.destroy.debug("frozen: {}".format(hasattr(sys, 'frozen')))
182 
183         # Save the session if one is given.
184         if session is not None:
185             sessions.session_manager.save(session, with_private=True)
186 
187         # Make sure we're not accepting a connection from the new process
188         # before we fully exited.
189         assert ipc.server is not None
190         ipc.server.shutdown()
191 
192         # Open a new process and immediately shutdown the existing one
193         try:
194             args = self._get_restart_args(pages, session, override_args)
195             subprocess.Popen(args)  # pylint: disable=consider-using-with
196         except OSError:
197             log.destroy.exception("Failed to restart")
198             return False
199         else:
200             return True
201 
202     def shutdown(self, status: int = 0,
203                  session: sessions.ArgType = None,
204                  last_window: bool = False,
205                  is_restart: bool = False) -> None:
206         """Quit qutebrowser.
207 
208         Args:
209             status: The status code to exit with.
210             session: A session name if saving should be forced.
211             last_window: If the shutdown was triggered due to the last window
212                             closing.
213             is_restart: If we're planning to restart.
214         """
215         if self.is_shutting_down:
216             return
217         self.is_shutting_down = True
218         log.destroy.debug("Shutting down with status {}, session {}...".format(
219             status, session))
220 
221         sessions.shutdown(session, last_window=last_window)
222         prompt.prompt_queue.shutdown()
223 
224         # If shutdown was called while we were asking a question, we're in
225         # a still sub-eventloop (which gets quit now) and not in the main
226         # one.
227         # But there's also other situations where it's problematic to shut down
228         # immediately (e.g. when we're just starting up).
229         # This means we need to defer the real shutdown to when we're back
230         # in the real main event loop, or we'll get a segfault.
231         log.destroy.debug("Deferring shutdown stage 2")
232         QTimer.singleShot(
233             0, functools.partial(self._shutdown_2, status, is_restart=is_restart))
234 
235     def _shutdown_2(self, status: int, is_restart: bool) -> None:
236         """Second stage of shutdown."""
237         log.destroy.debug("Stage 2 of shutting down...")
238 
239         # Tell everything to shut itself down
240         self.shutting_down.emit()
241 
242         # Delete temp basedir
243         if ((self._args.temp_basedir or self._args.temp_basedir_restarted) and
244                 not is_restart):
245             atexit.register(shutil.rmtree, self._args.basedir,
246                             ignore_errors=True)
247 
248         # Now we can hopefully quit without segfaults
249         log.destroy.debug("Deferring QApplication::exit...")
250         # We use a singleshot timer to exit here to minimize the likelihood of
251         # segfaults.
252         QTimer.singleShot(0, functools.partial(self._shutdown_3, status))
253 
254     def _shutdown_3(self, status: int) -> None:
255         """Finally shut down the QApplication."""
256         log.destroy.debug("Now calling QApplication::exit.")
257         if 'debug-exit' in objects.debug_flags:
258             if hunter is None:
259                 print("Not logging late shutdown because hunter could not be "
260                       "imported!", file=sys.stderr)
261             else:
262                 print("Now logging late shutdown.", file=sys.stderr)
263                 hunter.trace()
264         objects.qapp.exit(status)
265 
266 
267 @cmdutils.register(name='quit')
268 @cmdutils.argument('session', completion=miscmodels.session)
269 def quit_(save: bool = False,
270           session: sessions.ArgType = None) -> None:
271     """Quit qutebrowser.
272 
273     Args:
274         save: When given, save the open windows even if auto_save.session
275                 is turned off.
276         session: The name of the session to save.
277     """
278     if session is not None and not save:
279         raise cmdutils.CommandError("Session name given without --save!")
280     if save and session is None:
281         session = sessions.default
282 
283     instance.shutdown(session=session)
284 
285 
286 @cmdutils.register()
287 def restart() -> None:
288     """Restart qutebrowser while keeping existing tabs open."""
289     try:
290         ok = instance.restart(session='_restart')
291     except sessions.SessionError as e:
292         log.destroy.exception("Failed to save session!")
293         raise cmdutils.CommandError("Failed to save session: {}!"
294                                     .format(e))
295     except SyntaxError as e:
296         log.destroy.exception("Got SyntaxError")
297         raise cmdutils.CommandError("SyntaxError in {}:{}: {}".format(
298             e.filename, e.lineno, e))
299     if ok:
300         instance.shutdown(is_restart=True)
301 
302 
303 def init(args: argparse.Namespace) -> None:
304     """Initialize the global Quitter instance."""
305     global instance
306     instance = Quitter(args=args, parent=objects.qapp)
307     instance.shutting_down.connect(qtlog.shutdown_log)
308     objects.qapp.lastWindowClosed.connect(instance.on_last_window_closed)
309
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/qutebrowser/misc/quitter.py b/qutebrowser/misc/quitter.py
--- a/qutebrowser/misc/quitter.py
+++ b/qutebrowser/misc/quitter.py
@@ -219,7 +219,8 @@
             status, session))
 
         sessions.shutdown(session, last_window=last_window)
-        prompt.prompt_queue.shutdown()
+        if prompt.prompt_queue is not None:
+            prompt.prompt_queue.shutdown()
 
         # If shutdown was called while we were asking a question, we're in
         # a still sub-eventloop (which gets quit now) and not in the main

{"golden_diff": "diff --git a/qutebrowser/misc/quitter.py b/qutebrowser/misc/quitter.py\n--- a/qutebrowser/misc/quitter.py\n+++ b/qutebrowser/misc/quitter.py\n@@ -219,7 +219,8 @@\n             status, session))\n \n         sessions.shutdown(session, last_window=last_window)\n-        prompt.prompt_queue.shutdown()\n+        if prompt.prompt_queue is not None:\n+            prompt.prompt_queue.shutdown()\n \n         # If shutdown was called while we were asking a question, we're in\n         # a still sub-eventloop (which gets quit now) and not in the main\n", "issue": "prompt_queue is None at shutdown\nSeeing this in various crash reports:\r\n\r\n```pytb\r\nTraceback (most recent call last):\r\n  File \"/usr/lib/python3.9/site-packages/qutebrowser/misc/quitter.py\", line 225, in shutdown\r\n    if prompt.prompt_queue.shutdown():\r\nAttributeError: 'NoneType' object has no attribute 'shutdown'\r\n```\r\n\r\nhttps://crashes.qutebrowser.org/lists?search=prompt_queue.shutdown\n", "before_files": [{"content": "# Copyright 2014-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org>\n#\n# This file is part of qutebrowser.\n#\n# qutebrowser is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# qutebrowser is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with qutebrowser.  If not, see <https://www.gnu.org/licenses/>.\n\n\"\"\"Helpers related to quitting qutebrowser cleanly.\"\"\"\n\nimport os\nimport os.path\nimport sys\nimport json\nimport atexit\nimport shutil\nimport argparse\nimport tokenize\nimport functools\nimport subprocess\nfrom typing import Iterable, Mapping, MutableSequence, Sequence, cast\n\nfrom qutebrowser.qt.core import QObject, pyqtSignal, QTimer\ntry:\n    import hunter\nexcept ImportError:\n    hunter = None\n\nimport qutebrowser\nfrom qutebrowser.api import cmdutils\nfrom qutebrowser.utils import log, qtlog\nfrom qutebrowser.misc import sessions, ipc, objects\nfrom qutebrowser.mainwindow import prompt\nfrom qutebrowser.completion.models import miscmodels\n\n\ninstance = cast('Quitter', None)\n\n\nclass Quitter(QObject):\n\n    \"\"\"Utility class to quit/restart the QApplication.\n\n    Attributes:\n        quit_status: The current quitting status.\n        is_shutting_down: Whether we're currently shutting down.\n        _args: The argparse namespace.\n    \"\"\"\n\n    shutting_down = pyqtSignal()  # Emitted immediately before shut down\n\n    def __init__(self, *,\n                 args: argparse.Namespace,\n                 parent: QObject = None) -> None:\n        super().__init__(parent)\n        self.quit_status = {\n            'crash': True,\n            'tabs': False,\n            'main': False,\n        }\n        self.is_shutting_down = False\n        self._args = args\n\n    def on_last_window_closed(self) -> None:\n        \"\"\"Slot which gets invoked when the last window was closed.\"\"\"\n        self.shutdown(last_window=True)\n\n    def _compile_modules(self) -> None:\n        \"\"\"Compile all modules to catch SyntaxErrors.\"\"\"\n        if os.path.basename(sys.argv[0]) == 'qutebrowser':\n            # Launched via launcher script\n            return\n        elif hasattr(sys, 'frozen'):\n            return\n        else:\n            path = os.path.abspath(os.path.dirname(qutebrowser.__file__))\n            if not os.path.isdir(path):\n                # Probably running from a python egg.\n                return\n\n        for dirpath, _dirnames, filenames in os.walk(path):\n            for fn in filenames:\n                if os.path.splitext(fn)[1] == '.py' and os.path.isfile(fn):\n                    with tokenize.open(os.path.join(dirpath, fn)) as f:\n                        compile(f.read(), fn, 'exec')\n\n    def _get_restart_args(\n            self, pages: Iterable[str] = (),\n            session: str = None,\n            override_args: Mapping[str, str] = None\n    ) -> Sequence[str]:\n        \"\"\"Get args to relaunch qutebrowser.\n\n        Args:\n            pages: The pages to re-open.\n            session: The session to load, or None.\n            override_args: Argument overrides as a dict.\n\n        Return:\n            The commandline as a list of strings.\n        \"\"\"\n        if os.path.basename(sys.argv[0]) == 'qutebrowser':\n            # Launched via launcher script\n            args = [sys.argv[0]]\n        elif hasattr(sys, 'frozen'):\n            args = [sys.executable]\n        else:\n            args = [sys.executable, '-m', 'qutebrowser']\n\n        # Add all open pages so they get reopened.\n        page_args: MutableSequence[str] = []\n        for win in pages:\n            page_args.extend(win)\n            page_args.append('')\n\n        # Serialize the argparse namespace into json and pass that to the new\n        # process via --json-args.\n        # We do this as there's no way to \"unparse\" the namespace while\n        # ignoring some arguments.\n        argdict = vars(self._args)\n        argdict['session'] = None\n        argdict['url'] = []\n        argdict['command'] = page_args[:-1]\n        argdict['json_args'] = None\n        # Ensure the given session (or none at all) gets opened.\n        if session is None:\n            argdict['session'] = None\n            argdict['override_restore'] = True\n        else:\n            argdict['session'] = session\n            argdict['override_restore'] = False\n        # Ensure :restart works with --temp-basedir\n        if self._args.temp_basedir:\n            argdict['temp_basedir'] = False\n            argdict['temp_basedir_restarted'] = True\n\n        if override_args is not None:\n            argdict.update(override_args)\n\n        # Dump the data\n        data = json.dumps(argdict)\n        args += ['--json-args', data]\n\n        log.destroy.debug(\"args: {}\".format(args))\n\n        return args\n\n    def restart(self, pages: Sequence[str] = (),\n                session: str = None,\n                override_args: Mapping[str, str] = None) -> bool:\n        \"\"\"Inner logic to restart qutebrowser.\n\n        The \"better\" way to restart is to pass a session (_restart usually) as\n        that'll save the complete state.\n\n        However we don't do that (and pass a list of pages instead) when we\n        restart because of an exception, as that's a lot simpler and we don't\n        want to risk anything going wrong.\n\n        Args:\n            pages: A list of URLs to open.\n            session: The session to load, or None.\n            override_args: Argument overrides as a dict.\n\n        Return:\n            True if the restart succeeded, False otherwise.\n        \"\"\"\n        self._compile_modules()\n        log.destroy.debug(\"sys.executable: {}\".format(sys.executable))\n        log.destroy.debug(\"sys.path: {}\".format(sys.path))\n        log.destroy.debug(\"sys.argv: {}\".format(sys.argv))\n        log.destroy.debug(\"frozen: {}\".format(hasattr(sys, 'frozen')))\n\n        # Save the session if one is given.\n        if session is not None:\n            sessions.session_manager.save(session, with_private=True)\n\n        # Make sure we're not accepting a connection from the new process\n        # before we fully exited.\n        assert ipc.server is not None\n        ipc.server.shutdown()\n\n        # Open a new process and immediately shutdown the existing one\n        try:\n            args = self._get_restart_args(pages, session, override_args)\n            subprocess.Popen(args)  # pylint: disable=consider-using-with\n        except OSError:\n            log.destroy.exception(\"Failed to restart\")\n            return False\n        else:\n            return True\n\n    def shutdown(self, status: int = 0,\n                 session: sessions.ArgType = None,\n                 last_window: bool = False,\n                 is_restart: bool = False) -> None:\n        \"\"\"Quit qutebrowser.\n\n        Args:\n            status: The status code to exit with.\n            session: A session name if saving should be forced.\n            last_window: If the shutdown was triggered due to the last window\n                            closing.\n            is_restart: If we're planning to restart.\n        \"\"\"\n        if self.is_shutting_down:\n            return\n        self.is_shutting_down = True\n        log.destroy.debug(\"Shutting down with status {}, session {}...\".format(\n            status, session))\n\n        sessions.shutdown(session, last_window=last_window)\n        prompt.prompt_queue.shutdown()\n\n        # If shutdown was called while we were asking a question, we're in\n        # a still sub-eventloop (which gets quit now) and not in the main\n        # one.\n        # But there's also other situations where it's problematic to shut down\n        # immediately (e.g. when we're just starting up).\n        # This means we need to defer the real shutdown to when we're back\n        # in the real main event loop, or we'll get a segfault.\n        log.destroy.debug(\"Deferring shutdown stage 2\")\n        QTimer.singleShot(\n            0, functools.partial(self._shutdown_2, status, is_restart=is_restart))\n\n    def _shutdown_2(self, status: int, is_restart: bool) -> None:\n        \"\"\"Second stage of shutdown.\"\"\"\n        log.destroy.debug(\"Stage 2 of shutting down...\")\n\n        # Tell everything to shut itself down\n        self.shutting_down.emit()\n\n        # Delete temp basedir\n        if ((self._args.temp_basedir or self._args.temp_basedir_restarted) and\n                not is_restart):\n            atexit.register(shutil.rmtree, self._args.basedir,\n                            ignore_errors=True)\n\n        # Now we can hopefully quit without segfaults\n        log.destroy.debug(\"Deferring QApplication::exit...\")\n        # We use a singleshot timer to exit here to minimize the likelihood of\n        # segfaults.\n        QTimer.singleShot(0, functools.partial(self._shutdown_3, status))\n\n    def _shutdown_3(self, status: int) -> None:\n        \"\"\"Finally shut down the QApplication.\"\"\"\n        log.destroy.debug(\"Now calling QApplication::exit.\")\n        if 'debug-exit' in objects.debug_flags:\n            if hunter is None:\n                print(\"Not logging late shutdown because hunter could not be \"\n                      \"imported!\", file=sys.stderr)\n            else:\n                print(\"Now logging late shutdown.\", file=sys.stderr)\n                hunter.trace()\n        objects.qapp.exit(status)\n\n\n@cmdutils.register(name='quit')\n@cmdutils.argument('session', completion=miscmodels.session)\ndef quit_(save: bool = False,\n          session: sessions.ArgType = None) -> None:\n    \"\"\"Quit qutebrowser.\n\n    Args:\n        save: When given, save the open windows even if auto_save.session\n                is turned off.\n        session: The name of the session to save.\n    \"\"\"\n    if session is not None and not save:\n        raise cmdutils.CommandError(\"Session name given without --save!\")\n    if save and session is None:\n        session = sessions.default\n\n    instance.shutdown(session=session)\n\n\n@cmdutils.register()\ndef restart() -> None:\n    \"\"\"Restart qutebrowser while keeping existing tabs open.\"\"\"\n    try:\n        ok = instance.restart(session='_restart')\n    except sessions.SessionError as e:\n        log.destroy.exception(\"Failed to save session!\")\n        raise cmdutils.CommandError(\"Failed to save session: {}!\"\n                                    .format(e))\n    except SyntaxError as e:\n        log.destroy.exception(\"Got SyntaxError\")\n        raise cmdutils.CommandError(\"SyntaxError in {}:{}: {}\".format(\n            e.filename, e.lineno, e))\n    if ok:\n        instance.shutdown(is_restart=True)\n\n\ndef init(args: argparse.Namespace) -> None:\n    \"\"\"Initialize the global Quitter instance.\"\"\"\n    global instance\n    instance = Quitter(args=args, parent=objects.qapp)\n    instance.shutting_down.connect(qtlog.shutdown_log)\n    objects.qapp.lastWindowClosed.connect(instance.on_last_window_closed)\n", "path": "qutebrowser/misc/quitter.py"}], "after_files": [{"content": "# Copyright 2014-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org>\n#\n# This file is part of qutebrowser.\n#\n# qutebrowser is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# qutebrowser is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with qutebrowser.  If not, see <https://www.gnu.org/licenses/>.\n\n\"\"\"Helpers related to quitting qutebrowser cleanly.\"\"\"\n\nimport os\nimport os.path\nimport sys\nimport json\nimport atexit\nimport shutil\nimport argparse\nimport tokenize\nimport functools\nimport subprocess\nfrom typing import Iterable, Mapping, MutableSequence, Sequence, cast\n\nfrom qutebrowser.qt.core import QObject, pyqtSignal, QTimer\ntry:\n    import hunter\nexcept ImportError:\n    hunter = None\n\nimport qutebrowser\nfrom qutebrowser.api import cmdutils\nfrom qutebrowser.utils import log, qtlog\nfrom qutebrowser.misc import sessions, ipc, objects\nfrom qutebrowser.mainwindow import prompt\nfrom qutebrowser.completion.models import miscmodels\n\n\ninstance = cast('Quitter', None)\n\n\nclass Quitter(QObject):\n\n    \"\"\"Utility class to quit/restart the QApplication.\n\n    Attributes:\n        quit_status: The current quitting status.\n        is_shutting_down: Whether we're currently shutting down.\n        _args: The argparse namespace.\n    \"\"\"\n\n    shutting_down = pyqtSignal()  # Emitted immediately before shut down\n\n    def __init__(self, *,\n                 args: argparse.Namespace,\n                 parent: QObject = None) -> None:\n        super().__init__(parent)\n        self.quit_status = {\n            'crash': True,\n            'tabs': False,\n            'main': False,\n        }\n        self.is_shutting_down = False\n        self._args = args\n\n    def on_last_window_closed(self) -> None:\n        \"\"\"Slot which gets invoked when the last window was closed.\"\"\"\n        self.shutdown(last_window=True)\n\n    def _compile_modules(self) -> None:\n        \"\"\"Compile all modules to catch SyntaxErrors.\"\"\"\n        if os.path.basename(sys.argv[0]) == 'qutebrowser':\n            # Launched via launcher script\n            return\n        elif hasattr(sys, 'frozen'):\n            return\n        else:\n            path = os.path.abspath(os.path.dirname(qutebrowser.__file__))\n            if not os.path.isdir(path):\n                # Probably running from a python egg.\n                return\n\n        for dirpath, _dirnames, filenames in os.walk(path):\n            for fn in filenames:\n                if os.path.splitext(fn)[1] == '.py' and os.path.isfile(fn):\n                    with tokenize.open(os.path.join(dirpath, fn)) as f:\n                        compile(f.read(), fn, 'exec')\n\n    def _get_restart_args(\n            self, pages: Iterable[str] = (),\n            session: str = None,\n            override_args: Mapping[str, str] = None\n    ) -> Sequence[str]:\n        \"\"\"Get args to relaunch qutebrowser.\n\n        Args:\n            pages: The pages to re-open.\n            session: The session to load, or None.\n            override_args: Argument overrides as a dict.\n\n        Return:\n            The commandline as a list of strings.\n        \"\"\"\n        if os.path.basename(sys.argv[0]) == 'qutebrowser':\n            # Launched via launcher script\n            args = [sys.argv[0]]\n        elif hasattr(sys, 'frozen'):\n            args = [sys.executable]\n        else:\n            args = [sys.executable, '-m', 'qutebrowser']\n\n        # Add all open pages so they get reopened.\n        page_args: MutableSequence[str] = []\n        for win in pages:\n            page_args.extend(win)\n            page_args.append('')\n\n        # Serialize the argparse namespace into json and pass that to the new\n        # process via --json-args.\n        # We do this as there's no way to \"unparse\" the namespace while\n        # ignoring some arguments.\n        argdict = vars(self._args)\n        argdict['session'] = None\n        argdict['url'] = []\n        argdict['command'] = page_args[:-1]\n        argdict['json_args'] = None\n        # Ensure the given session (or none at all) gets opened.\n        if session is None:\n            argdict['session'] = None\n            argdict['override_restore'] = True\n        else:\n            argdict['session'] = session\n            argdict['override_restore'] = False\n        # Ensure :restart works with --temp-basedir\n        if self._args.temp_basedir:\n            argdict['temp_basedir'] = False\n            argdict['temp_basedir_restarted'] = True\n\n        if override_args is not None:\n            argdict.update(override_args)\n\n        # Dump the data\n        data = json.dumps(argdict)\n        args += ['--json-args', data]\n\n        log.destroy.debug(\"args: {}\".format(args))\n\n        return args\n\n    def restart(self, pages: Sequence[str] = (),\n                session: str = None,\n                override_args: Mapping[str, str] = None) -> bool:\n        \"\"\"Inner logic to restart qutebrowser.\n\n        The \"better\" way to restart is to pass a session (_restart usually) as\n        that'll save the complete state.\n\n        However we don't do that (and pass a list of pages instead) when we\n        restart because of an exception, as that's a lot simpler and we don't\n        want to risk anything going wrong.\n\n        Args:\n            pages: A list of URLs to open.\n            session: The session to load, or None.\n            override_args: Argument overrides as a dict.\n\n        Return:\n            True if the restart succeeded, False otherwise.\n        \"\"\"\n        self._compile_modules()\n        log.destroy.debug(\"sys.executable: {}\".format(sys.executable))\n        log.destroy.debug(\"sys.path: {}\".format(sys.path))\n        log.destroy.debug(\"sys.argv: {}\".format(sys.argv))\n        log.destroy.debug(\"frozen: {}\".format(hasattr(sys, 'frozen')))\n\n        # Save the session if one is given.\n        if session is not None:\n            sessions.session_manager.save(session, with_private=True)\n\n        # Make sure we're not accepting a connection from the new process\n        # before we fully exited.\n        assert ipc.server is not None\n        ipc.server.shutdown()\n\n        # Open a new process and immediately shutdown the existing one\n        try:\n            args = self._get_restart_args(pages, session, override_args)\n            subprocess.Popen(args)  # pylint: disable=consider-using-with\n        except OSError:\n            log.destroy.exception(\"Failed to restart\")\n            return False\n        else:\n            return True\n\n    def shutdown(self, status: int = 0,\n                 session: sessions.ArgType = None,\n                 last_window: bool = False,\n                 is_restart: bool = False) -> None:\n        \"\"\"Quit qutebrowser.\n\n        Args:\n            status: The status code to exit with.\n            session: A session name if saving should be forced.\n            last_window: If the shutdown was triggered due to the last window\n                            closing.\n            is_restart: If we're planning to restart.\n        \"\"\"\n        if self.is_shutting_down:\n            return\n        self.is_shutting_down = True\n        log.destroy.debug(\"Shutting down with status {}, session {}...\".format(\n            status, session))\n\n        sessions.shutdown(session, last_window=last_window)\n        if prompt.prompt_queue is not None:\n            prompt.prompt_queue.shutdown()\n\n        # If shutdown was called while we were asking a question, we're in\n        # a still sub-eventloop (which gets quit now) and not in the main\n        # one.\n        # But there's also other situations where it's problematic to shut down\n        # immediately (e.g. when we're just starting up).\n        # This means we need to defer the real shutdown to when we're back\n        # in the real main event loop, or we'll get a segfault.\n        log.destroy.debug(\"Deferring shutdown stage 2\")\n        QTimer.singleShot(\n            0, functools.partial(self._shutdown_2, status, is_restart=is_restart))\n\n    def _shutdown_2(self, status: int, is_restart: bool) -> None:\n        \"\"\"Second stage of shutdown.\"\"\"\n        log.destroy.debug(\"Stage 2 of shutting down...\")\n\n        # Tell everything to shut itself down\n        self.shutting_down.emit()\n\n        # Delete temp basedir\n        if ((self._args.temp_basedir or self._args.temp_basedir_restarted) and\n                not is_restart):\n            atexit.register(shutil.rmtree, self._args.basedir,\n                            ignore_errors=True)\n\n        # Now we can hopefully quit without segfaults\n        log.destroy.debug(\"Deferring QApplication::exit...\")\n        # We use a singleshot timer to exit here to minimize the likelihood of\n        # segfaults.\n        QTimer.singleShot(0, functools.partial(self._shutdown_3, status))\n\n    def _shutdown_3(self, status: int) -> None:\n        \"\"\"Finally shut down the QApplication.\"\"\"\n        log.destroy.debug(\"Now calling QApplication::exit.\")\n        if 'debug-exit' in objects.debug_flags:\n            if hunter is None:\n                print(\"Not logging late shutdown because hunter could not be \"\n                      \"imported!\", file=sys.stderr)\n            else:\n                print(\"Now logging late shutdown.\", file=sys.stderr)\n                hunter.trace()\n        objects.qapp.exit(status)\n\n\n@cmdutils.register(name='quit')\n@cmdutils.argument('session', completion=miscmodels.session)\ndef quit_(save: bool = False,\n          session: sessions.ArgType = None) -> None:\n    \"\"\"Quit qutebrowser.\n\n    Args:\n        save: When given, save the open windows even if auto_save.session\n                is turned off.\n        session: The name of the session to save.\n    \"\"\"\n    if session is not None and not save:\n        raise cmdutils.CommandError(\"Session name given without --save!\")\n    if save and session is None:\n        session = sessions.default\n\n    instance.shutdown(session=session)\n\n\n@cmdutils.register()\ndef restart() -> None:\n    \"\"\"Restart qutebrowser while keeping existing tabs open.\"\"\"\n    try:\n        ok = instance.restart(session='_restart')\n    except sessions.SessionError as e:\n        log.destroy.exception(\"Failed to save session!\")\n        raise cmdutils.CommandError(\"Failed to save session: {}!\"\n                                    .format(e))\n    except SyntaxError as e:\n        log.destroy.exception(\"Got SyntaxError\")\n        raise cmdutils.CommandError(\"SyntaxError in {}:{}: {}\".format(\n            e.filename, e.lineno, e))\n    if ok:\n        instance.shutdown(is_restart=True)\n\n\ndef init(args: argparse.Namespace) -> None:\n    \"\"\"Initialize the global Quitter instance.\"\"\"\n    global instance\n    instance = Quitter(args=args, parent=objects.qapp)\n    instance.shutting_down.connect(qtlog.shutdown_log)\n    objects.qapp.lastWindowClosed.connect(instance.on_last_window_closed)\n", "path": "qutebrowser/misc/quitter.py"}]}