Editing works again.
[dom-editor.git] / Dome / GUIView.py
bloba4fb1d4633485bde567ef7db23e177a64099afcf
1 from xml.dom import Node
2 from rox.loading import XDSLoader
4 import rox
5 from rox import g, TRUE, FALSE
6 keysyms = g.keysyms
8 from View import View
9 from Display2 import Display
10 from Beep import Beep
11 from GetArg import GetArg
12 from Path import make_relative_path
14 from rox.Menu import Menu
15 from gnome import canvas
17 menu = Menu('main', [
18 ('/File', None, '<Branch>', ''),
19 ('/File/Save', 'menu_save', '', 'F3'),
20 ('/File/Blank document', 'do_blank_all', '', '<Ctrl>N'),
21 ('/File/Clear undo buffer', 'menu_clear_undo', '', ''),
23 ('/Edit', None, '<Branch>', ''),
24 ('/Edit/Yank attributes', 'do_yank_attributes', '', ''),
25 ('/Edit/Paste attributes', 'do_paste_attribs', '', ''),
26 ('/Edit/Yank attrib value', 'do_yank_value', '', ''),
27 ('/Edit/Rename attribute', 'menu_rename_attr', '', ''),
28 ('/Edit/', '', '', '<separator>'),
29 ('/Edit/Cut', 'do_delete_node', '', 'x'),
30 ('/Edit/Delete', 'do_delete_node_no_clipboard', '', '<Ctrl>X'),
31 ('/Edit/Shallow cut', 'do_delete_shallow', '', '<Shift>X'),
32 ('/Edit/', '', '', '<separator>'),
33 ('/Edit/Yank', 'do_yank', '', 'y'),
34 ('/Edit/Shallow yank', 'do_shallow_yank', '', '<Shift>Y'),
35 ('/Edit/', '', '', '<separator>'),
36 ('/Edit/Paste (replace)','do_put_replace', '', '<Shift>R'),
37 ('/Edit/Paste (inside)', 'do_put_as_child', '', 'bracketright'),
38 ('/Edit/Paste (before)', 'do_put_before', '', '<Shift>P'),
39 ('/Edit/Paste (after)', 'do_put_after', '', 'p'),
40 ('/Edit/', '', '', '<separator>'),
41 ('/Edit/Edit value', 'toggle_edit', '', 'Return'),
42 ('/Edit/', '', '', '<separator>'),
43 ('/Edit/Undo', 'do_undo', '', 'u'),
44 ('/Edit/Redo', 'do_redo', '', '<Ctrl>R'),
46 ('/Move', None, '<Branch>', ''),
47 ('/Move/XPath search', 'menu_show_search', '', 'slash'),
48 ('/Move/Text search', 'menu_show_text_search', '', 'T'),
49 ('/Move/Enter', 'do_enter', '', '<Shift>greater'),
50 ('/Move/Leave', 'do_leave', '', '<Shift>less'),
52 ('/Move/Root node', 'move_home', '', 'Home'),
53 ('/Move/Previous sibling', 'move_prev_sib', '', 'Up'),
54 ('/Move/Next sibling', 'move_next_sib', '', 'Down'),
55 ('/Move/Parent', 'move_left', '', 'Left'),
56 ('/Move/First child', 'move_right', '', 'Right'),
57 ('/Move/Last child', 'move_end', '', 'End'),
59 ('/Move/To attribute', 'menu_select_attrib', '', 'At'),
61 ('/Select', None, '<Branch>', ''),
62 ('/Select/By XPath', 'menu_show_global', '', 'numbersign'),
63 ('/Select/Duplicate Siblings', 'do_select_dups', '', ''),
64 ('/Select/To Mark', 'do_select_marked', '', 'minus'),
65 ('/Select/Child Nodes', 'do_select_children', '', 'asterisk'),
67 ('/Mark', None, '<Branch>', ''),
68 ('/Mark/Mark Selection', 'do_mark_selection', '', 'm'),
69 ('/Mark/Switch with Selection', 'do_mark_switch', '', 'comma'),
70 ('/Mark/Clear Mark', 'do_clear_mark', '', ''),
72 ('/Network', None, '<Branch>', ''),
73 ('/Network/HTTP GET', 'do_suck', '', '<Shift>asciicircum'),
74 ('/Network/HTTP POST', 'do_http_post', '', ''),
75 ('/Network/Send SOAP message', 'do_soap_send', '', ''),
77 ('/Create', None, '<Branch>', ''),
78 ('/Create/Insert element', 'menu_insert_element', '', '<Shift>I'),
79 ('/Create/Append element', 'menu_append_element', '', '<Shift>A'),
80 ('/Create/Open element', 'menu_open_element', '', '<Shift>O'),
81 ('/Create/Open element at end', 'menu_open_element_end', '', '<Shift>E'),
83 ('/Create/', '', '', '<separator>'),
85 ('/Create/Insert text node', 'menu_insert_text', '', 'I'),
86 ('/Create/Append text node', 'menu_append_text', '', 'A'),
87 ('/Create/Open text node', 'menu_open_text', '', 'O'),
88 ('/Create/Open text node at end', 'menu_open_text_end', '', 'E'),
90 ('/Create/', '', '', '<separator>'),
92 ('/Create/Attribute', 'menu_show_add_attrib', '', '<Shift>plus'),
94 ('/Process', None, '<Branch>', ''),
95 ('/Process/Substitute', 'menu_show_subst', '', 's'),
96 ('/Process/Python expression', 'menu_show_pipe', '', '<Shift>exclam'),
97 ('/Process/XPath expression', 'menu_show_xpath', '', ''),
98 ('/Process/Normalise', 'do_normalise', '', ''),
99 ('/Process/Remove default namespaces', 'do_remove_ns', '', 'r'),
100 ('/Process/Comment to text', 'do_convert_to_text', '', ''),
102 ('/Program', None, '<Branch>', ''),
103 ('/Program/Input', 'menu_show_ask', '', 'question'),
104 ('/Program/Compare', 'do_compare', '', 'equal'),
105 ('/Program/Fail', 'do_fail', '', ''),
106 ('/Program/Pass', 'do_pass', '', ''),
107 ('/Program/Repeat last', 'do_again', '', 'dot'),
109 ('/View', None, '<Branch>', ''),
110 ('/View/Toggle hidden', 'do_toggle_hidden', '', '<Ctrl>H'),
111 ('/View/Show as HTML', 'do_show_html', '', ''),
112 ('/View/Show as canvas', 'do_show_canvas', '', ''),
113 ('/View/Close Window', 'menu_close_window', '', '<Ctrl>Q'),
115 ('/Options...', 'menu_options', '', '<Ctrl>O'),
118 def make_do(action):
119 return lambda(self): self.view.may_record([action])
121 class GUIView(Display, XDSLoader):
122 def __init__(self, window, view):
123 Display.__init__(self, window, view)
124 XDSLoader.__init__(self, ['application/x-dome', 'text/xml',
125 'application/xml'])
126 window.connect('key-press-event', self.key_press)
127 self.cursor_node = None
128 self.edit_dialog = None
129 self.update_state()
131 menu.attach(window, self)
133 def update_state(self):
134 if self.view.rec_point:
135 state = "(recording)"
136 elif self.view.idle_cb or self.view.op_in_progress:
137 state = "(playing)"
138 else:
139 state = ""
140 self.parent_window.set_state(state)
141 self.do_update_now()
143 def xds_load_from_stream(self, path, type, stream):
144 if not path:
145 raise Exception('Can only load from files... sorry!')
146 if path.endswith('.html'):
147 self.view.load_html(path)
148 else:
149 self.view.load_xml(path)
150 if self.view.root == self.view.model.get_root():
151 self.parent_window.uri = path
152 self.parent_window.update_title()
154 def key_press(self, widget, kev):
155 focus = widget.focus_widget
156 if focus and focus is not widget and focus.get_toplevel() is widget:
157 if focus.event(kev):
158 return TRUE # Handled
160 if self.cursor_node:
161 return 0
162 if kev.keyval == keysyms.Up:
163 self.view.may_record(['move_prev_sib'])
164 elif kev.keyval == keysyms.Down:
165 self.view.may_record(['move_next_sib'])
166 elif kev.keyval == keysyms.Left:
167 self.view.may_record(['move_left'])
168 elif kev.keyval == keysyms.Right:
169 self.view.may_record(['move_right'])
170 elif kev.keyval == keysyms.KP_Add:
171 self.menu_show_add_attrib()
172 elif kev.keyval == keysyms.Tab:
173 self.toggle_edit()
174 else:
175 return 0
176 return 1
178 def node_clicked(self, node, bev):
179 print "Clicked", node.namespaceURI, node.localName
180 if node:
181 if bev.type == g.gdk.BUTTON_PRESS:
182 if len(self.view.current_nodes) == 0:
183 src = self.view.root
184 else:
185 src = self.view.current_nodes[-1]
186 shift = bev.state & g.gdk.SHIFT_MASK
187 add = bev.state & g.gdk.CONTROL_MASK
188 select_region = shift and node.nodeType == Node.ELEMENT_NODE
189 lit = shift and not select_region
191 ns = {}
192 path = make_relative_path(src, node, lit, ns)
193 if path == '.' and self.view.current_nodes and not self.view.current_attrib:
194 return
195 if select_region:
196 self.view.may_record(["select_region", path, ns])
197 else:
198 self.view.may_record(["do_search", path, ns, add])
199 else:
200 self.view.may_record(["toggle_hidden"])
202 def attrib_clicked(self, element, attrib, event):
203 if len(self.view.current_nodes) == 0:
204 src = self.view.root
205 else:
206 src = self.view.current_nodes[-1]
207 ns = {}
209 print "attrib_clicked", attrib, attrib.namespaceURI, attrib.localName
210 path = make_relative_path(src, element, FALSE, ns)
211 if path != '.':
212 self.view.may_record(["do_search", path, ns, FALSE])
213 self.view.may_record(["attribute", attrib.namespaceURI, attrib.localName])
215 def menu_save(self):
216 self.parent_window.save()
218 def show_menu(self, bev):
219 menu.popup(self, bev)
221 def playback(self, macro, map):
222 "Called when the user clicks on a macro button."
223 Exec.exec_state.clean()
224 if map:
225 self.view.may_record(['map', macro.uri])
226 else:
227 self.view.may_record(['play', macro.uri])
229 def menu_show_ask(self):
230 def do_ask(q, self = self):
231 action = ["ask", q]
232 self.view.may_record(action)
233 GetArg('Input:', do_ask, ('Prompt:',))
235 def menu_show_subst(self):
236 def do_subst(args, self = self):
237 action = ["subst", args[0], args[1]]
238 self.view.may_record(action)
239 GetArg('Substitute:', do_subst, ('Replace:', 'With:'))
241 def move_from(self, old = []):
242 self.hide_editbox()
243 Display.move_from(self, old)
245 def hide_editbox(self):
246 if self.cursor_node:
247 if self.cursor_attrib:
248 self.cursor_hidden_text.set(text = '%s=%s' %
249 (self.cursor_attrib.name, self.cursor_attrib.value))
250 self.cursor_hidden_text.show()
251 self.auto_highlight(self.cursor_node)
252 self.cursor_node = None
253 self.edit_box_item.destroy()
255 def show_editbox(self):
256 "Edit the current node/attribute"
257 self.do_update_now()
259 if self.cursor_node:
260 self.hide_editbox()
262 if not self.visible:
263 raise Exception("Can't edit while display is hidden!")
265 self.cursor_node = self.view.current_nodes[0]
266 group = self.node_to_group[self.cursor_node]
267 self.cursor_attrib = self.view.current_attrib
269 self.highlight(group, FALSE)
271 if self.cursor_attrib:
272 group = group.attrib_to_group[self.cursor_attrib]
274 self.cursor_hidden_text = group.text
275 if not self.cursor_attrib:
276 # Don't hide for attributes, so we can still see the name
277 group.text.hide()
278 else:
279 group.text.set(text = str(self.cursor_attrib.name) + '=')
281 self.update_now() # GnomeCanvas bug?
282 lx, ly, hx, hy = group.text.get_bounds()
283 x, y = group.i2w(lx, ly)
285 text = g.TextView()
286 text.show()
288 eb = g.Frame()
289 eb.add(text)
290 self.edit_box = eb
291 self.edit_box_text = text
292 m = 3
294 #s = eb.get_style().copy()
295 #s.font = load_font('fixed')
296 #eb.set_style(s)
297 #if self.cursor_attrib:
298 # name_width = s.font.measure(self.cursor_attrib.name + '=') + 1
299 #else:
300 # name_width = 0
301 name_width = 0
303 self.edit_box_item = self.root().add(canvas.CanvasWidget, widget = eb,
304 x = x - m + name_width, y = y - m,
305 anchor = g.ANCHOR_NW)
307 #text.set_editable(TRUE)
308 text.get_buffer().insert_at_cursor(self.get_edit_text(), -1)
309 text.set_wrap_mode(g.WRAP_NONE)
310 text.get_buffer().connect('changed', self.eb_changed)
311 text.connect('key-press-event', self.eb_key)
312 eb.show()
313 text.realize()
314 self.size_eb()
315 text.grab_focus()
316 #eb.select_region(0, -1)
317 eb.show()
319 def get_edit_text(self):
320 if node.nodeType == Node.ELEMENT_NODE:
321 if self.cursor_attrib:
322 return str(self.cursor_attrib.value)
323 return node.nodeName
324 else:
325 return node.nodeValue
327 def eb_key(self, eb, kev):
328 key = kev.keyval
329 if key == g.keysyms.KP_Enter:
330 key = g.keysyms.Return
331 if key == g.keysyms.Escape:
332 self.hide_editbox()
333 elif key == g.keysyms.Return and kev.state & g.gdk.CONTROL_MASK:
334 eb.insert_defaults('\n')
335 self.size_eb()
336 elif key == g.keysyms.Tab or key == g.keysyms.Return:
337 buffer = eb.get_buffer()
338 s = buffer.get_start_iter()
339 e = buffer.get_end_iter()
340 text = buffer.get_text(s, e, TRUE)
341 try:
342 if text != self.get_edit_text():
343 self.commit_edit(text)
344 finally:
345 self.hide_editbox()
346 return 0
348 def commit_edit(self, new):
349 if self.cursor_attrib:
350 self.view.may_record(['set_attrib', new])
351 else:
352 self.view.may_record(['change_node', new])
354 def eb_changed(self, eb):
355 self.size_eb()
357 def size_eb(self):
358 def cb():
359 req = self.edit_box_text.size_request()
360 print "Wants", req
361 width = max(req[0], 10)
362 height = max(req[1], 10)
363 self.edit_box_item.set(width = width + 12, height = height + 4)
364 g.idle_add(cb)
366 def toggle_edit(self):
367 node = self.view.get_current()
368 attrib = self.view.current_attrib
370 if self.edit_dialog:
371 self.edit_dialog.destroy()
372 self.edit_dialog = rox.Dialog()
373 eb = self.edit_dialog
375 entry = g.Entry()
376 if node.nodeType == Node.ELEMENT_NODE:
377 if attrib:
378 text = str(attrib)
379 text = node.nodeName
380 else:
381 text = node.nodeValue
382 entry.set_text(text)
383 eb.vbox.pack_start(entry, TRUE, FALSE, 0)
385 eb.add_button(g.STOCK_CANCEL, g.RESPONSE_CANCEL)
386 eb.add_button(g.STOCK_APPLY, g.RESPONSE_OK)
387 eb.set_default_response(g.RESPONSE_OK)
388 entry.grab_focus()
389 entry.set_activates_default(True)
390 def destroy(eb):
391 self.edit_dialog = None
392 eb.connect('destroy', destroy)
393 def response(eb, resp):
394 if resp == g.RESPONSE_CANCEL:
395 eb.destroy()
396 elif resp == g.RESPONSE_OK:
397 new = entry.get_text()
398 if new != text:
399 if attrib:
400 self.view.may_record(['set_attrib', new])
401 else:
402 self.view.may_record(['change_node', new])
403 eb.destroy()
404 eb.connect('response', response)
406 eb.show_all()
408 #if self.cursor_node:
409 # self.hide_editbox()
410 #else:
411 # self.show_editbox()
413 def menu_select_attrib(self):
414 def do_attrib(name):
415 if ':' in name:
416 (prefix, localName) = name.split(':', 1)
417 else:
418 (prefix, localName) = (None, name)
419 namespaceURI = self.view.model.prefix_to_namespace(self.view.get_current(), prefix)
420 action = ["attribute", namespaceURI, localName]
421 self.view.may_record(action)
422 GetArg('Select attribute:', do_attrib, ['Name:'])
424 def menu_show_add_attrib(self):
425 def do_it(name):
426 action = ["add_attrib", "UNUSED", name]
427 self.view.may_record(action)
428 GetArg('Create attribute:', do_it, ['Name:'])
430 def menu_show_pipe(self):
431 def do_pipe(expr):
432 action = ["python", expr]
433 self.view.may_record(action)
434 GetArg('Python expression:', do_pipe, ['Eval:'], "'x' is the old text...")
436 def menu_show_xpath(self):
437 def go(expr):
438 action = ["xpath", expr]
439 self.view.may_record(action)
440 GetArg('XPath expression:', go, ['Eval:'], "Result goes on the clipboard")
442 def menu_show_global(self):
443 def do_global(pattern):
444 action = ["do_global", pattern]
445 self.view.may_record(action)
446 GetArg('Global:', do_global, ['Pattern:'],
447 '(@CURRENT@ is the current node\'s value)\n' +
448 'Perform next action on all nodes matching')
450 def menu_show_text_search(self):
451 def do_text_search(pattern):
452 action = ["do_text_search", pattern]
453 self.view.may_record(action)
454 GetArg('Search for:', do_text_search, ['Text pattern:'],
455 '(@CURRENT@ is the current node\'s value)\n')
457 def menu_show_search(self):
458 def do_search(pattern):
459 action = ["do_search", pattern]
460 self.view.may_record(action)
461 GetArg('Search for:',
462 do_search, ['XPath:'],
463 '(@CURRENT@ is the current node\'s value)')
465 def menu_rename_attr(self):
466 def do(name):
467 action = ["rename_attrib", name]
468 self.view.may_record(action)
469 GetArg('Rename to:', do, ['New name:'])
472 def show_add_box(self, action):
473 if action[0] == 'i':
474 text = 'Insert'
475 elif action[0] == 'a':
476 text = 'Append'
477 elif action[0] == 'o':
478 text = 'Open'
479 elif action[0] == 'e':
480 text = 'Open at end'
481 else:
482 assert 0
483 if action[1] == 'e':
484 text += ' element'
485 prompt = 'Node name'
486 elif action[1] == 't':
487 text += ' text'
488 prompt = 'Text'
489 else:
490 assert 0
492 def cb(value):
493 self.view.may_record(['add_node', action, value])
494 GetArg('Add node', cb, [prompt], text)
496 def new_name(self):
497 cur = self.view.get_current()
498 if cur.nodeType == Node.ELEMENT_NODE:
499 return cur.nodeName
500 return cur.parentNode.nodeName
502 def menu_insert_element(self):
503 "Insert element"
504 self.show_add_box('ie')
506 def menu_append_element(self):
507 "Append element"
508 self.show_add_box('ae')
510 def menu_open_element(self):
511 "Open element"
512 self.show_add_box('oe')
514 def menu_open_element_end(self):
515 "Open element at end"
516 self.show_add_box('ee')
518 def menu_insert_text(self):
519 "Insert text"
520 self.show_add_box('it')
522 def menu_append_text(self):
523 "Append text"
524 self.show_add_box('at')
526 def menu_open_text(self):
527 "Open text"
528 self.show_add_box('ot')
530 def menu_open_text_end(self):
531 "Open text at end"
532 self.show_add_box('et')
534 def menu_close_window(self):
535 self.parent_window.destroy()
537 def menu_options(self):
538 rox.edit_options()
540 def menu_clear_undo(self):
541 if rox.confirm('Really clear the undo buffer?',
542 g.STOCK_CLEAR):
543 self.view.model.clear_undo()
545 do_blank_all = make_do('blank_all')
546 do_enter = make_do('enter')
547 do_leave = make_do('leave')
548 do_suck = make_do('suck')
549 do_http_post = make_do('http_post')
550 do_soap_send = make_do('soap_send')
551 do_select_dups = make_do('select_dups')
552 do_paste_attribs = make_do('paste_attribs')
553 do_yank_value = make_do('yank_value')
554 do_yank_attributes = make_do('yank_attribs')
555 do_delete_node = make_do('delete_node')
556 do_delete_node_no_clipboard = make_do('delete_node_no_clipboard')
557 do_delete_shallow = make_do('delete_shallow')
558 do_yank = make_do('yank')
559 do_shallow_yank = make_do('shallow_yank')
560 do_put_replace = make_do('put_replace')
561 do_put_as_child = make_do('put_as_child')
562 do_put_before = make_do('put_before')
563 do_put_after = make_do('put_after')
564 do_undo = make_do('undo')
565 do_redo = make_do('redo')
566 do_fail = make_do('fail')
567 do_pass = make_do('do_pass')
568 do_toggle_hidden = make_do('toggle_hidden')
569 do_show_html = make_do('show_html')
570 do_show_canvas = make_do('show_canvas')
571 do_compare = make_do('compare')
572 do_again = make_do('again')
573 do_normalise = make_do('normalise')
574 do_convert_to_text = make_do('convert_to_text')
575 do_remove_ns = make_do('remove_ns')
577 do_clear_mark = make_do('clear_mark')
578 do_mark_switch = make_do('mark_switch')
579 do_mark_selection = make_do('mark_selection')
580 do_select_marked = make_do('select_marked_region')
581 do_select_children = make_do('select_children')
583 move_home = make_do('move_home')
584 move_end = make_do('move_end')
585 move_left = make_do('move_left')
586 move_right = make_do('move_right')
587 move_next_sib = make_do('move_next_sib')
588 move_prev_sib = make_do('move_prev_sib')