Added utility function to convert python strings to hex dump + ascii.
[samba.git] / source / python / gtkdictbrowser.py
1 #!/usr/bin/python
2 #
3 # Browse a Python dictionary in a two pane graphical interface written
4 # in GTK.
5 #
6 # The GtkDictBrowser class is supposed to be generic enough to allow
7 # applications to override enough methods and produce a
8 # domain-specific browser provided the information is presented as a
9 # Python dictionary.
10 #
11 # Possible applications:
12 #
13 #   - Windows registry browser
14 #   - SPOOLSS printerdata browser
15 #   - tdb file browser
16 #
17
18 from gtk import *
19 import string, re
20
21 class GtkDictBrowser:
22
23     def __init__(self, dict):
24         self.dict = dict
25         
26         # This variable stores a list of (regexp, function) used to
27         # convert the raw value data to a displayable string.
28
29         self.get_value_text_fns = []
30         self.get_key_text = lambda x: x
31
32         # We can filter the list of keys displayed using a regex
33
34         self.filter_regex = ""
35
36     # Create and configure user interface widgets.  A string argument is
37     # used to set the window title.
38
39     def build_ui(self, title):
40         win = GtkWindow()
41         win.set_title(title)
42
43         win.connect("destroy", mainquit)
44
45         hpaned = GtkHPaned()
46         win.add(hpaned)
47         hpaned.set_border_width(5)
48         hpaned.show()
49
50         vbox = GtkVBox()
51         hpaned.add1(vbox)
52         vbox.show()
53
54         scrolled_win = GtkScrolledWindow()
55         scrolled_win.set_policy(POLICY_AUTOMATIC, POLICY_AUTOMATIC)
56         vbox.pack_start(scrolled_win)
57         scrolled_win.show()
58
59         hbox = GtkHBox()
60         vbox.pack_end(hbox, expand = 0, padding = 5)
61         hbox.show()
62
63         label = GtkLabel("Filter:")
64         hbox.pack_start(label, expand = 0, padding = 5)
65         label.show()
66
67         self.entry = GtkEntry()
68         hbox.pack_end(self.entry, padding = 5)
69         self.entry.show()
70
71         self.entry.connect("activate", self.filter_activated)
72         
73         self.list = GtkList()
74         self.list.set_selection_mode(SELECTION_MULTIPLE)
75         self.list.set_selection_mode(SELECTION_BROWSE)
76         scrolled_win.add_with_viewport(self.list)
77         self.list.show()
78
79         self.list.connect("select_child", self.key_selected)
80
81         scrolled_win = GtkScrolledWindow()
82         scrolled_win.set_policy(POLICY_AUTOMATIC, POLICY_AUTOMATIC)
83         hpaned.add2(scrolled_win)
84         scrolled_win.set_usize(500,400)
85         scrolled_win.show()
86         
87         self.text = GtkText()
88         self.text.set_editable(FALSE)
89         scrolled_win.add_with_viewport(self.text)
90         self.text.show()
91
92         self.text.connect("event", self.event_handler)
93
94         self.menu = GtkMenu()
95         self.menu.show()
96
97         self.font = load_font("fixed")
98
99         self.update_keylist()
100
101         win.show()
102
103     # Add a key to the left hand side of the user interface
104
105     def add_key(self, key):
106         display_key = self.get_key_text(key)
107         list_item = GtkListItem(display_key)
108         list_item.set_data("raw_key", key) # Store raw key in item data
109         self.list.add(list_item)
110         list_item.show()
111
112     # Event handler registered by build_ui()
113
114     def event_handler(self, event, menu):
115         return FALSE
116
117     # Set the text to appear in the right hand side of the user interface 
118
119     def set_value_text(self, text):
120         self.text.delete_text(0, self.text.get_length())
121
122         # The text widget has trouble inserting text containing NULL
123         # characters.
124
125         text = string.replace(text, "\x00", ".")
126
127         self.text.insert(self.font, None, None, text)
128
129     # This function is called when a key is selected in the left hand side
130     # of the user interface.
131
132     def key_selected(self, list, list_item):
133         key = list_item.children()[0].get()
134
135         # Look for a match in the value display function list
136
137         text = self.dict[list_item.get_data("raw_key")]
138
139         for entry in self.get_value_text_fns:
140             if re.match(entry[0], key):
141                 text = entry[1](text)
142                 break
143
144         self.set_value_text(text)
145
146     # Refresh the key list by removing all items and re-inserting them.
147     # Items are only inserted if they pass through the filter regexp.
148
149     def update_keylist(self):
150         self.list.remove_items(self.list.children())
151         self.set_value_text("")
152         for k in self.dict.keys():
153             if re.match(self.filter_regex, k):
154                 self.add_key(k)
155
156     # Invoked when the user hits return in the filter text entry widget.
157
158     def filter_activated(self, entry):
159         self.filter_regex = entry.get_text()
160         self.update_keylist()
161
162     # Register a key display function
163
164     def register_get_key_text_fn(self, fn):
165         self.get_key_text = fn
166
167     # Register a value display function
168
169     def register_get_value_text_fn(self, regexp, fn):
170         self.get_value_text_fns.append((regexp, fn))
171
172 #
173 # A utility function to convert a string to the standard hex + ascii format.
174 # To display all values in hex do:
175 #   register_get_value_text_fn("", gtkdictbrowser.hex_string)
176 #
177
178 def hex_string(data):
179     """Return a hex dump of a string as a string.
180
181     The output produced is in the standard 16 characters per line hex +
182     ascii format:
183
184     00000000: 40 00 00 00 00 00 00 00  40 00 00 00 01 00 04 80  @....... @.......
185     00000010: 01 01 00 00 00 00 00 01  00 00 00 00              ........ ....
186     """
187     
188     pos = 0                             # Position in data
189     line = 0                            # Line of data
190     
191     hex = ""                            # Hex display
192     ascii = ""                          # ASCII display
193
194     result = ""
195     
196     while pos < len(data):
197         
198         # Start with header
199         
200         if pos % 16 == 0:
201             hex = "%08x: " % (line * 16)
202             ascii = ""
203             
204         # Add character
205             
206         hex = hex + "%02x " % (ord(data[pos]))
207         
208         if ord(data[pos]) < 32 or ord(data[pos]) > 176:
209             ascii = ascii + '.'
210         else:
211             ascii = ascii + data[pos]
212                 
213         pos = pos + 1
214             
215         # Add separator if half way
216             
217         if pos % 16 == 8:
218             hex = hex + " "
219             ascii = ascii + " "
220
221         # End of line
222
223         if pos % 16 == 0:
224             result = result + "%s %s\n" % (hex, ascii)
225             line = line + 1
226             
227     # Leftover bits
228
229     if pos % 16 != 0:
230
231         # Pad hex string
232
233         for i in range(0, (16 - (pos % 16))):
234             hex = hex + "   "
235
236         # Half way separator
237
238         if (pos % 16) < 8:
239             hex = hex + " "
240
241         result = result + "%s %s\n" % (hex, ascii)
242
243     return result
244
245 # For testing purposes, create a fixed dictionary to browse with
246
247 if __name__ == "__main__":
248
249     dict = {"chicken": "ham", "spam": "fun"}
250
251     db = GtkDictBrowser(dict)
252
253     db.build_ui("GtkDictBrowser")
254
255     # Override Python's handling of ctrl-c so we can break out of the
256     # gui from the command line.
257
258     import signal
259     signal.signal(signal.SIGINT, signal.SIG_DFL)
260
261     mainloop()