qutebrowser/qutebrowser/utils/debug.py

224 lines
6.8 KiB
Python
Raw Normal View History

2014-06-19 09:04:37 +02:00
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
2014-03-03 21:22:20 +01:00
# Copyright 2014 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/>.
"""Utilities used for debugging."""
2014-06-23 07:11:15 +02:00
import re
2014-03-03 21:22:20 +01:00
import sys
import types
2014-08-26 19:10:14 +02:00
import functools
2014-03-03 21:22:20 +01:00
2014-09-04 20:35:26 +02:00
from PyQt5.QtCore import QEvent, QCoreApplication
2014-03-03 21:22:20 +01:00
2014-08-26 20:20:17 +02:00
from qutebrowser.utils import log, utils
from qutebrowser.commands import cmdutils
2014-08-28 09:51:54 +02:00
from qutebrowser.config import config, style
2014-03-03 21:22:20 +01:00
2014-04-22 23:50:56 +02:00
2014-06-17 11:12:55 +02:00
@cmdutils.register(debug=True)
2014-09-02 21:54:07 +02:00
def debug_crash(typ : ('exception', 'segfault') = 'exception'):
2014-06-17 11:12:55 +02:00
"""Crash for debugging purposes.
Args:
2014-08-03 00:33:39 +02:00
typ: either 'exception' or 'segfault'.
2014-06-17 11:12:55 +02:00
Raises:
raises Exception when typ is not segfault.
segfaults when typ is (you don't say...)
"""
if typ == 'segfault':
# From python's Lib/test/crashers/bogus_code_obj.py
co = types.CodeType(0, 0, 0, 0, 0, b'\x04\x71\x00\x00', (), (), (),
'', '', 1, b'')
exec(co) # pylint: disable=exec-used
raise Exception("Segfault failed (wat.)")
else:
raise Exception("Forced crash")
@cmdutils.register(debug=True)
def debug_all_widgets():
"""Print a list of all widgets to debug log."""
2014-06-17 23:04:58 +02:00
s = QCoreApplication.instance().get_all_widgets()
2014-08-26 20:15:41 +02:00
log.misc.debug(s)
2014-06-17 11:12:55 +02:00
2014-06-17 23:16:06 +02:00
2014-06-17 11:12:55 +02:00
@cmdutils.register(debug=True)
2014-06-17 23:16:06 +02:00
def debug_all_objects():
2014-08-03 00:33:39 +02:00
"""Print a list of all objects to the debug log."""
2014-06-17 23:04:58 +02:00
s = QCoreApplication.instance().get_all_objects()
2014-08-26 20:15:41 +02:00
log.misc.debug(s)
2014-06-17 11:12:55 +02:00
2014-08-27 22:23:37 +02:00
2014-08-27 20:16:04 +02:00
@cmdutils.register(debug=True)
def debug_cache_stats():
2014-08-28 09:51:54 +02:00
"""Print LRU cache stats."""
config_info = config.instance().get.cache_info()
style_info = style.get_stylesheet.cache_info()
log.misc.debug('config: {}'.format(config_info))
log.misc.debug('style: {}'.format(style_info))
2014-06-17 11:12:55 +02:00
2014-08-27 22:23:37 +02:00
2014-06-17 11:12:55 +02:00
def log_events(klass):
"""Class decorator to log Qt events."""
old_event = klass.event
2014-08-26 19:10:14 +02:00
@functools.wraps(old_event)
2014-06-17 11:12:55 +02:00
def new_event(self, e, *args, **kwargs):
"""Wrapper for event() which logs events."""
2014-08-26 20:15:41 +02:00
log.misc.debug("Event in {}: {}".format(klass.__name__,
qenum_key(QEvent, e.type())))
2014-06-17 11:12:55 +02:00
return old_event(self, e, *args, **kwargs)
klass.event = new_event
return klass
2014-03-03 21:22:20 +01:00
def trace_lines(do_trace):
"""Turn on/off printing each executed line.
Args:
do_trace: Whether to start tracing (True) or stop it (False).
"""
def trace(frame, event, arg):
2014-04-17 17:44:27 +02:00
"""Trace function passed to sys.settrace.
Return:
Itself, so tracing continues.
"""
if sys is not None:
loc = '{}:{}'.format(frame.f_code.co_filename, frame.f_lineno)
if arg is not None:
2014-08-26 19:10:14 +02:00
arg = utils.compact_text(str(arg), 200)
else:
arg = ''
print("{:11} {:80} {}".format(event, loc, arg), file=sys.stderr)
return trace
else:
# When tracing while shutting down, it seems sys can be None
# sometimes... if that's the case, we stop tracing.
return None
2014-03-03 21:22:20 +01:00
if do_trace:
sys.settrace(trace)
else:
sys.settrace(None)
2014-06-15 11:11:08 +02:00
2014-08-07 07:35:05 +02:00
def qenum_key(base, value, add_base=False, klass=None):
2014-06-15 11:11:08 +02:00
"""Convert a Qt Enum value to its key as a string.
Args:
base: The object the enum is in, e.g. QFrame.
value: The value to get.
2014-08-07 07:35:05 +02:00
add_base: Whether the base should be added to the printed name.
klass: The enum class the value belongs to.
If None, the class will be auto-guessed.
2014-06-15 11:11:08 +02:00
Return:
2014-08-07 07:35:05 +02:00
The key associated with the value as a string if it could be found.
The original value as a string if not.
2014-06-15 11:11:08 +02:00
"""
2014-08-07 07:35:05 +02:00
if klass is None:
klass = value.__class__
if klass == int:
raise TypeError("Can't guess enum class of an int!")
2014-06-15 11:11:08 +02:00
try:
idx = klass.staticMetaObject.indexOfEnumerator(klass.__name__)
except AttributeError:
idx = -1
if idx != -1:
2014-08-07 07:35:05 +02:00
ret = klass.staticMetaObject.enumerator(idx).valueToKey(value)
2014-06-15 11:11:08 +02:00
else:
for name, obj in vars(base).items():
if isinstance(obj, klass) and obj == value:
2014-08-07 07:35:05 +02:00
ret = name
break
else:
ret = '0x{:04x}'.format(int(value))
2014-08-07 07:35:05 +02:00
if add_base and hasattr(base, '__name__'):
return '.'.join([base.__name__, ret])
else:
return ret
2014-06-23 07:11:15 +02:00
2014-08-07 14:41:39 +02:00
def qflags_key(base, value, add_base=False, klass=None):
"""Convert a Qt QFlags value to its keys as string.
Note: Passing a combined value (such as Qt.AlignCenter) will get the names
for the individual bits (e.g. Qt.AlignVCenter | Qt.AlignHCenter). FIXME
Args:
base: The object the flags are in, e.g. QtCore.Qt
value: The value to get.
add_base: Whether the base should be added to the printed names.
klass: The flags class the value belongs to.
If None, the class will be auto-guessed.
Return:
The keys associated with the flags as a '|' separated string if they
could be found. Hex values as a string if not.
"""
if klass is None:
# We have to store klass here because it will be lost when iterating
# over the bits.
klass = value.__class__
if klass == int:
raise TypeError("Can't guess enum class of an int!")
bits = []
names = []
mask = 0x01
value = int(value)
while mask < value:
if value & mask:
bits.append(mask)
mask <<= 1
for bit in bits:
# We have to re-convert to an enum type here or we'll sometimes get an
# empty string back.
names.append(qenum_key(base, klass(bit), add_base))
return '|'.join(names)
2014-06-23 07:11:15 +02:00
def signal_name(sig):
"""Get a cleaned up name of a signal.
Args:
sig: The pyqtSignal
Return:
The cleaned up signal name.
"""
m = re.match(r'[0-9]+(.*)\(.*\)', sig.signal)
return m.group(1)
def dbg_signal(sig, args):
"""Get a string representation of a signal for debugging.
Args:
sig: A pyqtSignal.
args: The arguments as list of strings.
Return:
A human-readable string representation of signal/args.
"""
2014-08-26 19:10:14 +02:00
argstr = ', '.join([utils.elide(str(a).replace('\n', ' '), 20)
for a in args])
2014-06-23 07:11:15 +02:00
return '{}({})'.format(signal_name(sig), argstr)