Choose type to create from new box, not by key.
[dom-editor.git] / Dome / GUIView.py
blob9ae5c7a03bc5cdeec7181341e56ecbd607949b4e
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', '', '<Ctrl>S'),
20 ('/File/Blank document', 'do_blank_all', '', '<Ctrl>N'),
21 ('/File/Clear undo buffer', 'menu_clear_undo', '', ''),
23 ('/Edit', None, '<Branch>', ''),
24 ('/Edit/Copy attributes', 'do_yank_attributes', '', ''),
25 ('/Edit/Paste attributes', 'do_paste_attribs', '', ''),
26 ('/Edit/Copy attrib value', 'do_yank_value', '', ''),
27 ('/Edit/Rename attribute', 'menu_rename_attr', '', ''),
28 ('/Edit/', '', '', '<separator>'),
29 ('/Edit/Cut', 'do_delete_node', '', '<Ctrl>X'),
30 ('/Edit/Delete', 'do_delete_node_no_clipboard', '', ''),
31 ('/Edit/Shallow cut', 'do_delete_shallow', '', '<Shift>X'),
32 ('/Edit/', '', '', '<separator>'),
33 ('/Edit/Copy', 'do_yank', '', '<Ctrl>C'),
34 ('/Edit/Shallow copy', 'do_shallow_yank', '', '<Shift>Y'),
35 ('/Edit/', '', '', '<separator>'),
36 ('/Edit/Paste (replace)','do_put_replace', '', '<Ctrl>V'),
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', '', '<Ctrl>Z'),
44 ('/Edit/Redo', 'do_redo', '', '<Ctrl>Y'),
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 node', 'menu_insert_element', '', 'I'),
79 ('/Create/Append node', 'menu_append_element', '', 'A'),
80 ('/Create/Open node inside', 'menu_open_element', '', 'O'),
81 ('/Create/Open node at end', 'menu_open_element_end', '', 'E'),
83 ('/Process', None, '<Branch>', ''),
84 ('/Process/Substitute', 'menu_show_subst', '', 's'),
85 ('/Process/Python expression', 'menu_show_pipe', '', '<Shift>exclam'),
86 ('/Process/XPath expression', 'menu_show_xpath', '', ''),
87 ('/Process/Normalise', 'do_normalise', '', ''),
88 ('/Process/Remove default namespaces', 'do_remove_ns', '', 'r'),
89 ('/Process/Convert to text', 'do_convert_to_text', '', ''),
90 ('/Process/Convert to comment', 'do_convert_to_comment', '', ''),
92 ('/Program', None, '<Branch>', ''),
93 ('/Program/Input', 'menu_show_ask', '', 'question'),
94 ('/Program/Compare', 'do_compare', '', 'equal'),
95 ('/Program/Fail', 'do_fail', '', ''),
96 ('/Program/Pass', 'do_pass', '', ''),
97 ('/Program/Repeat last', 'do_again', '', 'dot'),
99 ('/View', None, '<Branch>', ''),
100 ('/View/Toggle hidden', 'do_toggle_hidden', '', '<Ctrl>H'),
101 ('/View/Show as HTML', 'do_show_html', '', ''),
102 ('/View/Show as canvas', 'do_show_canvas', '', ''),
103 ('/View/Close Window', 'menu_close_window', '', '<Ctrl>Q'),
105 #('/Options...', 'menu_options', '', '<Ctrl>O'),
108 def make_do(action):
109 return lambda(self): self.view.may_record([action])
111 class GUIView(Display, XDSLoader):
112 def __init__(self, window, view):
113 Display.__init__(self, window, view)
114 XDSLoader.__init__(self, ['application/x-dome', 'text/xml',
115 'application/xml'])
116 window.connect('key-press-event', self.key_press)
117 self.cursor_node = None
118 self.edit_dialog = None
119 self.update_state()
121 menu.attach(window, self)
123 def destroyed(self, widget):
124 print "GUIView destroyed!"
125 Display.destroyed(self, widget)
126 del self.cursor_node
128 def update_state(self):
129 if self.view.rec_point:
130 state = "(recording)"
131 elif self.view.idle_cb or self.view.op_in_progress:
132 state = "(playing)"
133 else:
134 state = ""
135 self.parent_window.set_state(state)
136 self.do_update_now()
138 def xds_load_from_stream(self, path, type, stream):
139 if not path:
140 raise Exception('Can only load from files... sorry!')
141 if path.endswith('.html'):
142 self.view.load_html(path)
143 else:
144 self.view.load_xml(path)
145 if self.view.root == self.view.model.get_root():
146 self.parent_window.uri = path
147 self.parent_window.update_title()
149 def key_press(self, widget, kev):
150 focus = widget.focus_widget
151 if focus and focus is not widget and focus.get_toplevel() is widget:
152 if focus.event(kev):
153 return TRUE # Handled
155 if self.cursor_node:
156 return 0
157 if kev.keyval == keysyms.Up:
158 self.view.may_record(['move_prev_sib'])
159 elif kev.keyval == keysyms.Down:
160 self.view.may_record(['move_next_sib'])
161 elif kev.keyval == keysyms.Left:
162 self.view.may_record(['move_left'])
163 elif kev.keyval == keysyms.Right:
164 self.view.may_record(['move_right'])
165 elif kev.keyval == keysyms.KP_Add:
166 self.menu_show_add_attrib()
167 elif kev.keyval == keysyms.Tab:
168 self.toggle_edit()
169 else:
170 return 0
171 return 1
173 def node_clicked(self, node, bev):
174 print "Clicked", node.namespaceURI, node.localName
175 if node:
176 if bev.type == g.gdk.BUTTON_PRESS:
177 if len(self.view.current_nodes) == 0:
178 src = self.view.root
179 else:
180 src = self.view.current_nodes[-1]
181 shift = bev.state & g.gdk.SHIFT_MASK
182 add = bev.state & g.gdk.CONTROL_MASK
183 select_region = shift and node.nodeType == Node.ELEMENT_NODE
184 lit = shift and not select_region
186 ns = {}
187 path = make_relative_path(src, node, lit, ns)
188 if path == '.' and self.view.current_nodes and not self.view.current_attrib:
189 return
190 if select_region:
191 self.view.may_record(["select_region", path, ns])
192 else:
193 self.view.may_record(["do_search", path, ns, add])
194 else:
195 self.view.may_record(["toggle_hidden"])
197 def attrib_clicked(self, element, attrib, event):
198 if len(self.view.current_nodes) == 0:
199 src = self.view.root
200 else:
201 src = self.view.current_nodes[-1]
202 ns = {}
204 print "attrib_clicked", attrib, attrib.namespaceURI, attrib.localName
205 path = make_relative_path(src, element, FALSE, ns)
206 if path != '.':
207 self.view.may_record(["do_search", path, ns, FALSE])
208 self.view.may_record(["attribute", attrib.namespaceURI, attrib.localName])
210 def menu_save(self):
211 self.parent_window.save()
213 def show_menu(self, bev):
214 menu.popup(self, bev)
216 def playback(self, macro, map):
217 "Called when the user clicks on a macro button."
218 Exec.exec_state.clean()
219 if map:
220 self.view.may_record(['map', macro.uri])
221 else:
222 self.view.may_record(['play', macro.uri])
224 def menu_show_ask(self):
225 def do_ask(q, self = self):
226 action = ["ask", q]
227 self.view.may_record(action)
228 GetArg('Input:', do_ask, ('Prompt:',))
230 def menu_show_subst(self):
231 def do_subst(args, self = self):
232 action = ["subst", args[0], args[1]]
233 self.view.may_record(action)
234 GetArg('Substitute:', do_subst, ('Replace:', 'With:'))
236 def move_from(self, old = []):
237 self.hide_editbox()
238 Display.move_from(self, old)
240 def hide_editbox(self):
241 if self.cursor_node:
242 if self.cursor_attrib:
243 self.cursor_hidden_text.set(text = '%s=%s' %
244 (self.cursor_attrib.name, self.cursor_attrib.value))
245 self.cursor_hidden_text.show()
246 self.auto_highlight(self.cursor_node)
247 self.cursor_node = None
248 self.edit_box_item.destroy()
250 def show_editbox(self):
251 "Edit the current node/attribute"
252 self.do_update_now()
254 if self.cursor_node:
255 self.hide_editbox()
257 if not self.visible:
258 raise Exception("Can't edit while display is hidden!")
260 self.cursor_node = self.view.current_nodes[0]
261 group = self.node_to_group[self.cursor_node]
262 self.cursor_attrib = self.view.current_attrib
264 self.highlight(group, FALSE)
266 if self.cursor_attrib:
267 group = group.attrib_to_group[self.cursor_attrib]
269 self.cursor_hidden_text = group.text
270 if not self.cursor_attrib:
271 # Don't hide for attributes, so we can still see the name
272 group.text.hide()
273 else:
274 group.text.set(text = str(self.cursor_attrib.name) + '=')
276 self.update_now() # GnomeCanvas bug?
277 lx, ly, hx, hy = group.text.get_bounds()
278 x, y = group.i2w(lx, ly)
280 text = g.TextView()
281 text.show()
283 eb = g.Frame()
284 eb.add(text)
285 self.edit_box = eb
286 self.edit_box_text = text
287 m = 3
289 #s = eb.get_style().copy()
290 #s.font = load_font('fixed')
291 #eb.set_style(s)
292 #if self.cursor_attrib:
293 # name_width = s.font.measure(self.cursor_attrib.name + '=') + 1
294 #else:
295 # name_width = 0
296 name_width = 0
298 self.edit_box_item = self.root().add(canvas.CanvasWidget, widget = eb,
299 x = x - m + name_width, y = y - m,
300 anchor = g.ANCHOR_NW)
302 #text.set_editable(TRUE)
303 text.get_buffer().insert_at_cursor(self.get_edit_text(), -1)
304 text.set_wrap_mode(g.WRAP_NONE)
305 text.get_buffer().connect('changed', self.eb_changed)
306 text.connect('key-press-event', self.eb_key)
307 eb.show()
308 text.realize()
309 self.size_eb()
310 text.grab_focus()
311 #eb.select_region(0, -1)
312 eb.show()
314 def get_edit_text(self):
315 if node.nodeType == Node.ELEMENT_NODE:
316 if self.cursor_attrib:
317 return str(self.cursor_attrib.value)
318 return node.nodeName
319 else:
320 return node.nodeValue
322 def eb_key(self, eb, kev):
323 key = kev.keyval
324 if key == g.keysyms.KP_Enter:
325 key = g.keysyms.Return
326 if key == g.keysyms.Escape:
327 self.hide_editbox()
328 elif key == g.keysyms.Return and kev.state & g.gdk.CONTROL_MASK:
329 eb.insert_defaults('\n')
330 self.size_eb()
331 elif key == g.keysyms.Tab or key == g.keysyms.Return:
332 buffer = eb.get_buffer()
333 s = buffer.get_start_iter()
334 e = buffer.get_end_iter()
335 text = buffer.get_text(s, e, TRUE)
336 try:
337 if text != self.get_edit_text():
338 self.commit_edit(text)
339 finally:
340 self.hide_editbox()
341 return 0
343 def commit_edit(self, new):
344 if self.cursor_attrib:
345 self.view.may_record(['set_attrib', new])
346 else:
347 self.view.may_record(['change_node', new])
349 def eb_changed(self, eb):
350 self.size_eb()
352 def size_eb(self):
353 def cb():
354 req = self.edit_box_text.size_request()
355 print "Wants", req
356 width = max(req[0], 10)
357 height = max(req[1], 10)
358 self.edit_box_item.set(width = width + 12, height = height + 4)
359 g.idle_add(cb)
361 def toggle_edit(self):
362 node = self.view.current_nodes[0]
363 attrib = self.view.current_attrib
365 if self.edit_dialog:
366 self.edit_dialog.destroy()
367 self.edit_dialog = rox.Dialog()
368 eb = self.edit_dialog
370 if node.nodeType == Node.ELEMENT_NODE:
371 if attrib:
372 text = unicode(attrib.value)
373 else:
374 text = node.nodeName
375 entry = g.Entry()
376 entry.set_text(text)
377 entry.set_activates_default(True)
378 def get_text(): return entry.get_text()
379 else:
380 text = node.nodeValue
381 entry = g.TextView()
382 buffer = entry.get_buffer()
383 buffer.insert_at_cursor(text, -1)
384 entry.set_size_request(400, 200)
386 def get_text():
387 start = buffer.get_start_iter()
388 end = buffer.get_end_iter()
389 return buffer.get_text(start, end, True)
390 eb.vbox.pack_start(entry, TRUE, FALSE, 0)
392 eb.add_button(g.STOCK_CANCEL, g.RESPONSE_CANCEL)
393 eb.add_button(g.STOCK_APPLY, g.RESPONSE_OK)
394 eb.set_default_response(g.RESPONSE_OK)
395 entry.grab_focus()
396 def destroy(eb):
397 self.edit_dialog = None
398 eb.connect('destroy', destroy)
399 def response(eb, resp):
400 if resp == g.RESPONSE_CANCEL:
401 eb.destroy()
402 elif resp == g.RESPONSE_OK:
403 new = get_text()
404 if new != text:
405 if attrib:
406 self.view.may_record(['set_attrib', new])
407 else:
408 self.view.may_record(['change_node', new])
409 eb.destroy()
410 eb.connect('response', response)
412 eb.show_all()
414 #if self.cursor_node:
415 # self.hide_editbox()
416 #else:
417 # self.show_editbox()
419 def menu_select_attrib(self):
420 def do_attrib(name):
421 if ':' in name:
422 (prefix, localName) = name.split(':', 1)
423 namespaceURI = self.view.model.prefix_to_namespace(self.view.get_current(), prefix)
424 else:
425 (prefix, localName) = (None, name)
426 namespaceURI = None
427 action = ["attribute", namespaceURI, localName]
428 self.view.may_record(action)
429 GetArg('Select attribute:', do_attrib, ['Name:'])
431 def menu_show_add_attrib(self):
432 def do_it(name):
433 action = ["add_attrib", "UNUSED", name]
434 self.view.may_record(action)
435 GetArg('Create attribute:', do_it, ['Name:'])
437 def menu_show_pipe(self):
438 def do_pipe(expr):
439 action = ["python", expr]
440 self.view.may_record(action)
441 GetArg('Python expression:', do_pipe, ['Eval:'], "'x' is the old text...")
443 def menu_show_xpath(self):
444 def go(expr):
445 action = ["xpath", expr]
446 self.view.may_record(action)
447 GetArg('XPath expression:', go, ['Eval:'], "Result goes on the clipboard")
449 def menu_show_global(self):
450 def do_global(pattern):
451 action = ["do_global", pattern]
452 self.view.may_record(action)
453 GetArg('Global:', do_global, ['Pattern:'],
454 '(@CURRENT@ is the current node\'s value)\n' +
455 'Perform next action on all nodes matching')
457 def menu_show_text_search(self):
458 def do_text_search(pattern):
459 action = ["do_text_search", pattern]
460 self.view.may_record(action)
461 GetArg('Search for:', do_text_search, ['Text pattern:'],
462 '(@CURRENT@ is the current node\'s value)\n')
464 def menu_show_search(self):
465 def do_search(pattern):
466 action = ["do_search", pattern]
467 self.view.may_record(action)
468 GetArg('Search for:',
469 do_search, ['XPath:'],
470 '(@CURRENT@ is the current node\'s value)')
472 def menu_rename_attr(self):
473 def do(name):
474 action = ["rename_attrib", name]
475 self.view.may_record(action)
476 GetArg('Rename to:', do, ['New name:'])
479 def do_create(self, action, nodeType, data):
480 action = action[0]
481 qname = True
482 if nodeType == Node.ELEMENT_NODE:
483 action += 'e'
484 elif nodeType == Node.TEXT_NODE:
485 action += 't'
486 qname = False
487 elif nodeType == Node.ATTRIBUTE_NODE:
488 action += 'a'
490 if qname:
491 # Check name is valid
492 # XXX: Should be more strict
493 data = data.strip()
494 assert '\n' not in data
495 assert ' ' not in data
497 self.view.may_record(['add_node', action, data])
499 def show_add_box(self, action):
500 if action[0] == 'i':
501 text = 'Insert'
502 elif action[0] == 'a':
503 text = 'Append'
504 elif action[0] == 'o':
505 text = 'Open'
506 elif action[0] == 'e':
507 text = 'Open at end'
508 else:
509 assert 0
510 if action[1] == 'e':
511 text += ' element'
512 prompt = 'Node name'
513 elif action[1] == 't':
514 text += ' text'
515 prompt = 'Text'
516 else:
517 assert 0
519 box = g.Dialog()
520 text = g.TextView()
521 box.vbox.pack_start(text, TRUE, FALSE, 0)
522 text.set_size_request(400, 200)
523 box.set_has_separator(False)
525 box.add_button(g.STOCK_CANCEL, g.RESPONSE_CANCEL)
526 box.add_button('Add _Element', Node.ELEMENT_NODE)
527 box.add_button('Add _Text', Node.TEXT_NODE)
528 box.add_button('Add _Attribute', Node.ATTRIBUTE_NODE)
529 box.set_default_response(g.RESPONSE_OK)
530 text.grab_focus()
531 def response(box, resp):
532 if resp == g.RESPONSE_CANCEL:
533 box.destroy()
534 return
535 buffer = text.get_buffer()
536 start = buffer.get_start_iter()
537 end = buffer.get_end_iter()
538 new = buffer.get_text(start, end, True)
539 if new:
540 self.do_create(action, resp, new)
541 box.destroy()
542 box.connect('response', response)
544 box.show_all()
546 def new_name(self):
547 cur = self.view.get_current()
548 if cur.nodeType == Node.ELEMENT_NODE:
549 return cur.nodeName
550 return cur.parentNode.nodeName
552 def menu_insert_element(self):
553 "Insert element"
554 self.show_add_box('ie')
556 def menu_append_element(self):
557 "Append element"
558 self.show_add_box('ae')
560 def menu_open_element(self):
561 "Open element"
562 self.show_add_box('oe')
564 def menu_open_element_end(self):
565 "Open element at end"
566 self.show_add_box('ee')
568 def menu_insert_text(self):
569 "Insert text"
570 self.show_add_box('it')
572 def menu_append_text(self):
573 "Append text"
574 self.show_add_box('at')
576 def menu_open_text(self):
577 "Open text"
578 self.show_add_box('ot')
580 def menu_open_text_end(self):
581 "Open text at end"
582 self.show_add_box('et')
584 def menu_close_window(self):
585 self.parent_window.destroy()
587 def menu_options(self):
588 rox.edit_options()
590 def menu_clear_undo(self):
591 if rox.confirm('Really clear the undo buffer?',
592 g.STOCK_CLEAR):
593 self.view.model.clear_undo()
595 do_blank_all = make_do('blank_all')
596 do_enter = make_do('enter')
597 do_leave = make_do('leave')
598 do_suck = make_do('suck')
599 do_http_post = make_do('http_post')
600 do_soap_send = make_do('soap_send')
601 do_select_dups = make_do('select_dups')
602 do_paste_attribs = make_do('paste_attribs')
603 do_yank_value = make_do('yank_value')
604 do_yank_attributes = make_do('yank_attribs')
605 do_delete_node = make_do('delete_node')
606 do_delete_node_no_clipboard = make_do('delete_node_no_clipboard')
607 do_delete_shallow = make_do('delete_shallow')
608 do_yank = make_do('yank')
609 do_shallow_yank = make_do('shallow_yank')
610 do_put_replace = make_do('put_replace')
611 do_put_as_child = make_do('put_as_child')
612 do_put_before = make_do('put_before')
613 do_put_after = make_do('put_after')
614 do_undo = make_do('undo')
615 do_redo = make_do('redo')
616 do_fail = make_do('fail')
617 do_pass = make_do('do_pass')
618 do_toggle_hidden = make_do('toggle_hidden')
619 do_show_html = make_do('show_html')
620 do_show_canvas = make_do('show_canvas')
621 do_compare = make_do('compare')
622 do_again = make_do('again')
623 do_normalise = make_do('normalise')
624 do_convert_to_text = make_do('convert_to_text')
625 do_convert_to_comment = make_do('convert_to_comment')
626 do_convert_to_pi = make_do('convert_to_pi')
627 do_remove_ns = make_do('remove_ns')
629 do_clear_mark = make_do('clear_mark')
630 do_mark_switch = make_do('mark_switch')
631 do_mark_selection = make_do('mark_selection')
632 do_select_marked = make_do('select_marked_region')
633 do_select_children = make_do('select_children')
635 move_home = make_do('move_home')
636 move_end = make_do('move_end')
637 move_left = make_do('move_left')
638 move_right = make_do('move_right')
639 move_next_sib = make_do('move_next_sib')
640 move_prev_sib = make_do('move_prev_sib')