Fix YouTube format detection (bug 967)
[gpodder.git] / doc / dev / gtk-builder-clean.py
blob0aad29f94de55795af71e0395906cbb7dc44093a
1 #!/usr/bin/python
3 # gtk-builder-clean.py - Remove unnecessary properties in GtkBuilder UI files
4 # Thomas Perl <thpinfo.com>; 2009-05-08
6 # Tries to instanciate GObjects defined in the GtkBuilder .ui file in order to
7 # get their default properties and then tries to compare the values defined in
8 # the .ui file. If the value in the .ui file is the same as the default value,
9 # the property is dropped from the UI file (because it is redundant).
11 # Usage: python gtk-builder-clean.py my.ui | xmllint --format - >my.ui.fixed
14 from xml.dom import minidom
16 import sys
17 import gtk
18 import gtk.gdk
19 import gobject
20 import pango
22 if len(sys.argv) != 2:
23 print >>sys.stderr, """
24 Usage: %s interfacefile.ui
25 """ % sys.argv[0]
26 sys.exit(1)
28 ui = minidom.parse(sys.argv[1])
30 builder = gtk.Builder()
32 removed_properties = 0
34 def get_text(nodes):
35 return ''.join(n.data for n in nodes if n.nodeType == n.TEXT_NODE)
37 def check_default(default, value):
38 try:
39 if default is not None:
40 value = type(default)(value)
41 except TypeError, ve:
42 if value.startswith('GTK_') or value.startswith('PANGO_') or value.startswith('GDK_'):
43 try:
44 value = eval(value.replace('GTK_', 'gtk.').replace('PANGO_', 'pango.').replace('GDK_', 'gtk.gdk.'))
45 except NameError, ne:
46 print >>sys.stderr, ne
47 except AttributeError, at:
48 print >>sys.stderr, ae
49 else:
50 print >>sys.stderr, ve
51 return False
53 #print default, '<=>', value
54 return default == value
56 def recurse(node):
57 global removed_properties
58 for child in node.childNodes:
59 if child.nodeType != child.ELEMENT_NODE:
60 recurse(child)
61 continue
63 class_ = child.getAttribute('class')
64 if class_:
65 type_ = builder.get_type_from_name(class_)
66 object = gobject.new(type_)
67 for property in gobject.list_properties(type_):
68 try:
69 default = object.get_property(property.name)
70 except TypeError, te:
71 default = None
73 for child_node in child.childNodes:
74 if getattr(child_node, 'tagName', None) == 'property' \
75 and child_node.getAttribute('name') == property.name:
76 if check_default(default, get_text(child_node.childNodes)):
77 removed_properties += 1
78 child.removeChild(child_node)
79 child_node.unlink()
80 recurse(child)
82 recurse(ui.documentElement)
84 print >>sys.stderr, 'Removed %d default properties in %s' % (removed_properties, sys.argv[1])
85 print ui.toprettyxml('', '', 'utf-8')