bump product version to 5.0.4.1
[LibreOffice.git] / solenv / gdb / libreoffice / util / printing.py
blob9cbae3080a6492d98c17761198dd97df8c2d79ed
1 # -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-
3 # This file is part of the LibreOffice project.
5 # This Source Code Form is subject to the terms of the Mozilla Public
6 # License, v. 2.0. If a copy of the MPL was not distributed with this
7 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
10 from collections import Mapping
11 import gdb
12 import re
13 import six
15 from libreoffice.util.compatibility import use_gdb_printing
17 class SimplePrinter(object):
19 def __init__(self, name, function):
20 self.name = name
21 self.function = function
22 self.enabled = True
24 def invoke(self, val):
25 if not self.enabled:
26 return None
27 return self.function(self.name, val)
29 class NameLookup(Mapping):
31 def __init__(self):
32 self.map = {}
33 self.name_regex = re.compile('^([\w:]+)(<.*>)?')
35 def add(self, name, printer):
36 self.map[name] = printer
38 def __len__(self):
39 return len(self.map)
41 def __getitem__(self, type):
42 typename = self._basic_type(type)
43 if typename and typename in self.map:
44 return self.map[typename]
45 return None
47 def __iter__(self):
48 return self.map
50 def _basic_type(self, type):
51 basic_type = self.basic_type(type)
52 if basic_type:
53 match = self.name_regex.match(basic_type)
54 if match:
55 return match.group(1)
56 return None
58 @staticmethod
59 def basic_type(type):
60 if type.code == gdb.TYPE_CODE_REF:
61 type = type.target()
62 type = type.unqualified().strip_typedefs()
63 return type.tag
65 class FunctionLookup(Mapping):
67 def __init__(self):
68 self.map = {}
70 def add(self, test, printer):
71 self.map[test] = printer
73 def __len__(self):
74 return len(self.map)
76 def __getitem__(self, type):
77 for (test, printer) in six.iteritems(self.map):
78 if test(type):
79 return printer
80 return None
82 def __iter__(self):
83 return self.map
85 class Printer(object):
87 def __init__(self, name):
88 self.name = name
89 self.subprinters = []
90 self.name_lookup = NameLookup()
91 self.func_lookup = FunctionLookup()
92 self.enabled = True
94 def add(self, name, function, lookup = None):
95 printer = SimplePrinter(name, function)
96 self.subprinters.append(printer)
97 if not lookup:
98 self.name_lookup.add(name, printer)
99 else:
100 self.func_lookup.add(lookup, printer)
103 def __call__(self, val):
104 printer = self.name_lookup[val.type]
105 if not printer:
106 printer = self.func_lookup[val.type]
108 if printer:
109 return printer.invoke(val)
110 return None
112 def register_pretty_printer(printer, obj):
113 '''Registers printer with objfile'''
115 if use_gdb_printing:
116 gdb.printing.register_pretty_printer(obj, printer)
117 else:
118 if obj is None:
119 obj = gdb
120 obj.pretty_printers.append(printer)
122 # vim:set shiftwidth=4 softtabstop=4 expandtab: