1 from __future__
import nested_scopes
7 from xml
.dom
import Node
, XMLNS_NAMESPACE
8 from Ft
.Xml
import XPath
9 from Ft
.Xml
.XPath
import FT_EXT_NAMESPACE
, Context
10 from Ft
.Xml
.cDomlette
import implementation
11 from Ft
.Xml
.Domlette
import PrettyPrint
13 import os
, re
, string
, types
, sys
15 from StringIO
import StringIO
17 from Program
import Op
, Block
21 import urllib
, urllib2
24 from constants
import *
28 for x
in node
.childNodes
:
29 if x
.nodeType
== Node
.ELEMENT_NODE
:
33 normal_chars
= string
.letters
+ string
.digits
+ "-"
35 fast_global
= re
.compile('//([-A-Za-z][-A-Za-z0-9]*:)?[-A-Za-z][-A-Za-z0-9]*$')
37 def fix_broken_html(data
):
38 """Pre-parse the data before sending to tidy to fix really really broken
39 stuff (eg, MS Word output). Returns None if data is OK"""
40 if data
.find('<o:p>') == -1:
41 return # Doesn't need fixing?
43 data
= data
.replace('<o:p></o:p>', '')
44 data
= re
.sub('<!\[[^]]*\]>', '', data
)
50 fixed
= fix_broken_html(data
)
58 tin
= os
.popen('tidy --force-output yes -q -utf8 -asxml 2>/dev/null', 'w')
60 tin
= os
.popen('tidy --force-output yes -q -asxml 2>/dev/null', 'w')
61 tin
.write(fixed
or data
)
67 data
= os
.fdopen(r
).read()
73 # - A ref to a DOM document
74 # - A set of current nodes
77 # It does not have any display code. It does contain code to perform actions
78 # (actions affect the document AND the view state).
80 # These actions can be repeated using '.'
89 "delete_node_no_clipboard",
118 "Recursivly compare two nodes."
119 if a
.nodeType
!= b
.nodeType
or a
.nodeName
!= b
.nodeName
:
121 if a
.nodeValue
!= b
.nodeValue
:
125 if len(aks
) != len(bks
):
127 for (ak
, bk
) in map(None, aks
, bks
):
132 class InProgress(Exception):
133 "Throw this if the operation will complete later..."
134 class Done(Exception):
135 "Thrown when the chain is completed successfully"
138 def __init__(self
, model
, callback_handlers
= None):
139 """callback_handlers is an (idle_add, idle_remove) tuple"""
143 self
.single_step
= 1 # 0 = Play 1 = Step-into 2 = Step-over
145 self
.chroots
= [] # (model, node, marked)
146 self
.foreach_stack
= [] # (block, [nodes], restore-nodes, restore-marks)
147 self
.current_nodes
= []
148 self
.clipboard
= None
149 self
.current_attrib
= None
152 if not callback_handlers
:
154 self
.idle_add
, self
.idle_remove
= g
.idle_add
, g
.idle_remove
156 self
.idle_add
, self
.idle_remove
= callback_handlers
158 self
.exec_point
= None # None, or (Op, Exit)
159 self
.rec_point
= None # None, or (Op, Exit)
160 self
.op_in_progress
= None
162 self
.callback_on_return
= None # Called when there are no more Ops...
163 self
.in_callback
= 0 # (not the above callback - this is the playback one)
164 self
.innermost_failure
= None
165 self
.call_on_done
= None # Called when there is nowhere to return to
166 self
.exec_stack
= [] # Ops we are inside (display use only)
168 self
.breakpoints
= {} # (op, exit) keys, values don't matter
169 self
.current_nodes
= []
170 self
.set_model(model
)
172 def get_current(self
):
173 if len(self
.current_nodes
) == 1:
174 return self
.current_nodes
[0]
175 raise Exception('This operation required exactly one selected node!')
177 def set_model(self
, model
):
178 assert not self
.marked
181 self
.model
.unlock(self
.root
)
184 self
.model
.remove_view(self
)
185 self
.model
.root_program
.watchers
.remove(self
)
187 self
.model
.root_program
.watchers
.append(self
)
189 self
.set_display_root(self
.model
.get_root())
190 self
.move_to(self
.root
)
193 return self
.idle_cb
!= 0 or self
.in_callback
195 def run_new(self
, callback
= None):
196 "Reset the playback system (stack, step-mode and point)."
197 "Call callback(exit) when execution finishes."
199 self
.idle_remove(self
.idle_cb
)
202 self
.innermost_failure
= None
203 self
.call_on_done
= callback
204 self
.callback_on_return
= None
205 while self
.exec_stack
:
207 self
.reset_foreach_stack()
208 self
.status_changed()
211 def reset_foreach_stack(self
):
212 for block
, nodes
, restore
, mark
in self
.foreach_stack
:
214 print "reset_foreach_stack: unlocking %d nodes" % len(mark
)
215 [self
.model
.unlock(x
) for x
in mark
]
216 self
.foreach_stack
= []
218 def push_stack(self
, op
):
219 if not isinstance(op
, Op
):
220 raise Exception('push_stack: not an Op', op
)
221 self
.exec_stack
.append(op
)
222 self
.update_stack(op
)
225 op
= self
.exec_stack
.pop()
226 self
.update_stack(op
)
228 def update_stack(self
, op
= None):
229 "Called when exec_stack or foreach_stack changes."
233 def set_exec(self
, pos
):
234 if self
.op_in_progress
:
235 raise Exception("Operation in progress...")
237 assert isinstance(pos
[0], Op
)
238 assert pos
[1] in ['next', 'fail']
239 self
.exec_point
= pos
241 #print "set_exec: %s:%s" % pos
245 def set_rec(self
, pos
):
249 self
.status_changed()
251 def record_at_point(self
):
252 if not self
.exec_point
:
253 alert("No current point!")
255 self
.set_rec(self
.exec_point
)
258 def stop_recording(self
):
260 self
.set_exec(self
.rec_point
)
263 alert("Not recording!")
265 def may_record(self
, action
):
266 "Perform and, possibly, record this action"
270 print "RECORD:", rec
, action
272 if action
== ['enter']:
273 new_op
= Block(op
.parent
)
274 new_op
.toggle_enter()
275 if len(self
.current_nodes
) > 1:
276 new_op
.toggle_foreach()
279 op
.link_to(new_op
, old_exit
)
284 if isinstance(new_op
, Block
):
285 self
.set_rec((new_op
.start
, 'next'))
287 self
.set_rec((new_op
, 'next'))
289 play_op
, exit
= self
.exec_point
290 # (do_one_step may have stopped recording)
292 self
.set_rec((new_op
, exit
))
298 self
.do_action(action
)
304 (type, val
, tb
) = sys
.exc_info()
305 #if not val.may_record:
311 rox
.report_exception()
314 def add_display(self
, display
):
315 "Calls move_from(old_node) when we move and update_all() on updates."
316 self
.displays
.append(display
)
317 #print "Added:", self.displays
319 def remove_display(self
, display
):
320 self
.displays
.remove(display
)
321 #print "Removed, now:", self.displays
322 if not self
.displays
:
325 def update_replace(self
, old
, new
):
328 if old
in self
.current_nodes
:
330 self
.model
.unlock(old
)
331 self
.current_nodes
.remove(old
)
332 self
.current_nodes
.append(new
)
333 self
.update_all(new
.parentNode
)
335 self
.update_all(new
.parentNode
)
337 def has_ancestor(self
, node
, ancestor
):
338 while node
!= ancestor
:
339 node
= node
.parentNode
344 def update_all(self
, node
):
345 for display
in self
.displays
:
346 display
.update_all(node
)
349 #print "View deleted"
350 self
.model
.root_program
.watchers
.remove(self
)
354 self
.model
.unlock(self
.root
)
356 self
.model
.remove_view(self
)
359 # 'nodes' may be either a node or a list of nodes.
360 # (duplicates will be removed)
361 # If it's a single node, then an 'attrib' node may also be specified
362 def move_to(self
, nodes
, attrib
= None):
363 if self
.current_nodes
== nodes
:
366 if attrib
and attrib
.nodeType
!= Node
.ATTRIBUTE_NODE
:
367 raise Exception('attrib not of type ATTRIBUTE_NODE!')
369 if type(nodes
) != types
.ListType
:
382 #if len(old) != len(nodes):
383 # print "(move_to: attempt to set duplicate nodes)"
385 old_nodes
= self
.current_nodes
386 self
.current_nodes
= nodes
388 for node
in self
.current_nodes
:
389 self
.model
.lock(node
)
390 for node
in old_nodes
:
391 self
.model
.unlock(node
)
393 self
.current_attrib
= attrib
395 for display
in self
.displays
:
396 display
.move_from(old_nodes
)
398 def move_prev_sib(self
):
399 if self
.get_current() == self
.root
or not self
.get_current().previousSibling
:
401 self
.move_to(self
.get_current().previousSibling
)
403 def move_next_sib(self
):
404 if self
.get_current() == self
.root
or not self
.get_current().nextSibling
:
406 self
.move_to(self
.get_current().nextSibling
)
410 for n
in self
.current_nodes
:
418 def move_right(self
):
420 for n
in self
.current_nodes
:
429 self
.move_to(self
.root
)
432 if not self
.get_current().childNodes
:
434 node
= self
.get_current().childNodes
[0]
435 while node
.nextSibling
:
436 node
= node
.nextSibling
439 def set_display_root(self
, root
):
440 self
.model
.lock(root
)
442 self
.model
.unlock(self
.root
)
444 self
.update_all(root
)
447 """Change the display root to a COPY of the selected node.
448 Call Leave to check changes back in."""
449 node
= self
.get_current()
450 if node
is self
.root
:
451 raise Beep
# Locking problems if this happens...
452 if self
.model
.doc
is not node
.ownerDocument
:
453 raise Exception('Current node not in view!')
457 new_model
= self
.model
.lock_and_copy(node
)
458 self
.chroots
.append((self
.model
, node
, self
.marked
))
459 self
.set_model(new_model
)
463 """Undo the effect of the last chroot()."""
471 (old_model
, old_node
, old_marked
) = self
.chroots
.pop()
474 copy
= old_model
.doc
.importNode(self
.model
.get_root(), 1)
475 old_model
.unlock(old_node
)
476 old_model
.replace_node(old_node
, copy
)
477 self
.set_model(old_model
)
479 self
.set_marked(old_marked
.keys())
482 model
.undo_stack
= None
488 def do_action(self
, action
):
489 "'action' is a tuple (function, arg1, arg2, ...)"
490 "Performs the action. Returns if action completes, or raises "
491 "InProgress if not (will call resume() later)."
492 if action
[0] in record_again
:
493 self
.last_action
= action
494 elif action
[0] == 'again':
495 action
= self
.last_action
496 fn
= getattr(self
, action
[0])
498 #print "DO:", action[0]
501 new
= apply(fn
, action
[1:])
505 if not self
.op_in_progress
:
510 if not self
.op_in_progress
:
512 traceback
.print_exc()
516 if self
.op_in_progress
:
517 op
= self
.op_in_progress
519 self
.set_exec((op
, exit
))
523 def breakpoint(self
):
524 if self
.breakpoints
.has_key(self
.exec_point
):
526 op
= self
.exec_point
[0]
527 if op
.parent
.start
== op
and op
.next
== None:
528 return 1 # Empty program
531 def do_one_step(self
):
532 "Execute the next op after exec_point, then:"
533 "- position the point on one of the exits return."
534 "- if there is no op to perform, call callback_on_return() or raise Done."
535 "- if the operation is started but not complete, raise InProgress and "
536 " arrange to resume() later."
537 if self
.op_in_progress
:
538 alert("Already executing something.")
540 if not self
.exec_point
:
541 alert("No current playback point.")
543 (op
, exit
) = self
.exec_point
545 if self
.single_step
== 0 and self
.breakpoint():
546 print "Hit a breakpoint! At " + time
.ctime(time
.time())
551 l
.show_prog(op
.get_program())
554 next
= getattr(op
, exit
)
558 self
.do_action(next
.action
) # May raise InProgress
561 if exit
== 'fail' and not self
.innermost_failure
:
562 #print "Setting innermost_failure on", op
563 self
.innermost_failure
= op
565 # If we're in a block, try exiting from it...
566 if isinstance(op
.parent
, Block
):
567 if self
.start_block_iteration(op
.parent
, continuing
= exit
):
569 if not op
.parent
.is_toplevel():
570 self
.set_exec((op
.parent
, exit
))
573 print "(skipped a whole program!)"
574 if self
.callback_on_return
:
575 cb
= self
.callback_on_return
576 self
.callback_on_return
= None
581 def set_oip(self
, op
):
582 #print "set_oip:", self.exec_point
585 self
.op_in_progress
= op
589 def fast_global(self
, name
):
590 "Search for nodes with this name anywhere under the root (//name)"
591 #print "Fast global", name
593 (prefix
, localName
) = string
.split(name
, ':', 1)
595 (prefix
, localName
) = (None, name
)
596 if self
.current_nodes
:
597 src
= self
.current_nodes
[-1]
600 namespaceURI
= self
.model
.prefix_to_namespace(src
, prefix
)
603 if node
.nodeType
!= Node
.ELEMENT_NODE
:
605 if node
.localName
== localName
and node
.namespaceURI
== namespaceURI
:
607 map(add
, node
.childNodes
)
613 def do_global(self
, pattern
):
614 if len(self
.current_nodes
) != 1:
615 self
.move_to(self
.root
)
616 if pattern
[:2] == '//':
617 if fast_global
.match(pattern
):
618 self
.fast_global(pattern
[2:])
621 assert not self
.op_in_progress
or (self
.op_in_progress
.action
[1] == pattern
)
623 code
= self
.op_in_progress
.cached_code
625 from Ft
.Xml
.XPath
import XPathParser
626 code
= XPathParser
.new().parse(self
.macro_pattern(pattern
))
627 if self
.op_in_progress
and pattern
.find('@CURRENT@') == -1:
628 self
.op_in_progress
.cached_code
= code
632 ns
= GetAllNs(self
.current_nodes
[0])
633 ns
['ext'] = FT_EXT_NAMESPACE
635 c
= Context
.Context(self
.get_current(), processorNss
= ns
)
637 nodes
= code
.evaluate(c
)
638 assert type(nodes
) == list
640 #don't select the document itself!
641 for n
in nodes
: assert n
.parentNode
643 #nodes = XPath.Evaluate(self.macro_pattern(pattern), contextNode = self.get_current())
644 #print "Found", nodes
647 def select_region(self
, path
, ns
= None):
648 if len(self
.current_nodes
) == 0:
650 src
= self
.current_nodes
[-1]
653 ns
['ext'] = FT_EXT_NAMESPACE
654 c
= Context
.Context(src
, [src
], processorNss
= ns
)
655 rt
= XPath
.Evaluate(path
, context
= c
)
658 if not self
.has_ancestor(x
, self
.root
):
659 print "[ skipping search result above root ]"
664 print "*** Search for '%s' in select_region failed" % path
665 print " (namespaces were '%s')" % ns
667 if node
.parentNode
!= src
.parentNode
:
668 print "Nodes must have same parent!"
672 for n
in src
.parentNode
.childNodes
:
674 if n
is src
or n
is node
:
678 self
.move_to(selected
)
680 def macro_pattern(self
, pattern
):
681 """Do the @CURRENT@ substitution for an XPath"""
682 if len(self
.current_nodes
) != 1:
684 node
= self
.get_current()
685 if node
.nodeType
== Node
.TEXT_NODE
:
688 if self
.current_attrib
:
689 current
= self
.current_attrib
.value
691 current
= node
.nodeName
692 pattern
= pattern
.replace('@CURRENT@', current
)
693 #print "Searching for", pattern
696 def do_search(self
, pattern
, ns
= None, toggle
= FALSE
):
697 if len(self
.current_nodes
) == 0:
700 src
= self
.current_nodes
[-1]
702 # May be from a text_search...
703 #assert not self.op_in_progress or (self.op_in_progress.action[1] == pattern)
705 code
= self
.op_in_progress
.cached_code
707 from Ft
.Xml
.XPath
import XPathParser
708 code
= XPathParser
.new().parse(self
.macro_pattern(pattern
))
709 if self
.op_in_progress
and pattern
.find('@CURRENT@') == -1:
710 self
.op_in_progress
.cached_code
= code
714 ns
['ext'] = FT_EXT_NAMESPACE
715 c
= Context
.Context(src
, [src
], processorNss
= ns
)
717 rt
= code
.evaluate(c
)
720 if not self
.has_ancestor(x
, self
.root
):
721 print "[ skipping search result above root ]"
725 #if self.node_to_line[x] > self.current_line:
729 #print "*** Search for '%s' failed" % pattern
730 #print " (namespaces were '%s')" % ns
733 new
= self
.current_nodes
[:]
742 def do_text_search(self
, pattern
):
743 pattern
= self
.macro_pattern(pattern
)
744 return self
.do_search("//text()[ext:match('%s')]" % pattern
)
746 def subst(self
, replace
, with
):
747 "re search and replace on the current node"
748 nodes
= self
.current_nodes
[:]
749 check
= len(nodes
) == 1
750 a
= self
.current_attrib
752 new
, num
= re
.subn(replace
, with
, a
.value
)
755 a
= self
.model
.set_attrib(nodes
[0], a
.name
, new
)
756 self
.move_to(nodes
[0], a
)
761 if n
.nodeType
== Node
.TEXT_NODE
:
762 old
= n
.data
.replace('\n', ' ')
763 new
, num
= re
.subn(replace
, with
, old
)
764 if check
and not num
:
767 self
.model
.set_data(n
, new
)
769 elif n
.nodeType
== Node
.ELEMENT_NODE
:
770 old
= str(n
.nodeName
)
771 new
, num
= re
.subn(replace
, with
, old
)
772 if check
and not num
:
775 new_ns
, x
= self
.model
.split_qname(n
, new
)
776 final
.append(self
.model
.set_name(n
, new_ns
, new
))
782 def python(self
, expr
):
783 "Replace node with result of expr(old_value)"
784 if self
.get_current().nodeType
== Node
.TEXT_NODE
:
785 vars = {'x': self
.get_current().data
, 're': re
, 'sub': re
.sub
, 'string': string
}
786 result
= eval(expr
, vars)
787 new
= self
.python_to_node(result
)
788 node
= self
.get_current()
790 self
.model
.replace_node(node
, new
)
795 def resume(self
, exit
= 'next'):
796 "After raising InProgress, call this to start moving again."
797 if self
.op_in_progress
:
798 op
= self
.op_in_progress
800 self
.set_exec((op
, exit
))
801 if not self
.single_step
:
803 self
.status_changed()
805 print "(nothing to resume)"
808 def ask_cb(result
, self
= self
):
812 self
.clipboard
= self
.model
.doc
.createTextNode(result
)
815 from GetArg
import GetArg
816 box
= GetArg('Input:', ask_cb
, [q
], destroy_return
= 1)
819 def python_to_node(self
, data
):
820 "Convert a python data structure into a tree and return the root."
821 if type(data
) == types
.ListType
:
822 list = self
.model
.doc
.createElementNS(DOME_NS
, 'dome:list')
823 list.setAttributeNS(XMLNS_NAMESPACE
, 'xmlns:dome', DOME_NS
)
825 list.appendChild(self
.python_to_node(x
))
827 return self
.model
.doc
.createTextNode(str(data
))
829 def yank(self
, deep
= 1):
830 if self
.current_attrib
:
831 a
= self
.current_attrib
833 self
.clipboard
= self
.model
.doc
.createElementNS(a
.namespaceURI
, a
.nodeName
)
834 self
.clipboard
.appendChild(self
.model
.doc
.createTextNode(a
.value
))
836 self
.clipboard
= self
.model
.doc
.createDocumentFragment()
837 for n
in self
.current_nodes
:
838 c
= n
.cloneNode(deep
)
840 self
.clipboard
.appendChild(c
)
842 #print "Clip now", self.clipboard
844 def shallow_yank(self
):
847 def delete_shallow(self
):
848 nodes
= self
.current_nodes
[:]
851 if self
.root
in nodes
:
856 self
.model
.delete_shallow(n
)
859 def delete_node_no_clipboard(self
):
860 self
.delete_node(yank
= 0)
862 def delete_node(self
, yank
= 1):
863 nodes
= self
.current_nodes
[:]
868 if self
.current_attrib
:
869 ca
= self
.current_attrib
870 self
.current_attrib
= None
871 self
.model
.set_attrib(self
.get_current(), ca
.name
, None)
873 if self
.root
in nodes
:
876 new
= [x
.parentNode
for x
in nodes
]
878 self
.model
.delete_nodes(nodes
)
881 nodes
= self
.current_nodes
[:]
883 self
.model
.unlock(self
.root
)
887 self
.model
.lock(self
.root
)
888 self
.move_to(filter(lambda x
: self
.has_ancestor(x
, self
.root
), nodes
))
891 nodes
= self
.current_nodes
[:]
893 self
.model
.unlock(self
.root
)
897 self
.model
.lock(self
.root
)
898 self
.move_to(filter(lambda x
: self
.has_ancestor(x
, self
.root
), nodes
))
900 def default_done(self
, exit
):
901 "Called when execution of a program returns. op_in_progress has been "
902 "restored - move to the exit."
903 #print "default_done(%s)" % exit
904 if self
.op_in_progress
:
905 op
= self
.op_in_progress
907 self
.set_exec((op
, exit
))
909 print "No operation to return to!"
910 c
= self
.call_on_done
912 self
.call_on_done
= None
915 self
.jump_to_innermost_failure()
918 def jump_to_innermost_failure(self
):
919 assert self
.innermost_failure
!= None
921 print "Returning to innermost failure:", self
.innermost_failure
922 self
.set_exec((self
.innermost_failure
, 'fail'))
924 if hasattr(l
, 'set_innermost_failure'):
925 l
.set_innermost_failure(self
.innermost_failure
)
927 def play(self
, name
, done
= None):
928 "Play this macro. When it returns, restore the current op_in_progress (if any)"
929 "and call done(exit). Default for done() moves exec_point."
930 "done() is called from do_one_step() - usual rules apply."
932 prog
= self
.name_to_prog(name
)
933 self
.innermost_failure
= None
936 done
= self
.default_done
938 def cbor(self
= self
, op
= self
.op_in_progress
, done
= done
,
940 old_cbor
= self
.callback_on_return
,
941 old_ss
= self
.single_step
):
942 "We're in do_one_step..."
944 #print "Return from '%s'..." % name
946 if old_ss
== 2 and self
.single_step
== 0:
947 self
.single_step
= old_ss
948 self
.callback_on_return
= old_cbor
950 o
, exit
= self
.exec_point
952 #print "Resume op '%s' (%s)" % (op.program.name, op)
957 self
.callback_on_return
= cbor
959 if self
.single_step
== 2:
962 if self
.op_in_progress
:
963 self
.push_stack(self
.op_in_progress
)
965 self
.play_block(prog
.code
)
967 self
.status_changed()
970 def start_block_iteration(self
, block
, continuing
= None):
971 "True if we are going to run the block, False to exit the loop"
972 "Continuing is 'next' or 'fail' if we reached the end of the block."
973 #print "Start interation"
974 if not self
.foreach_stack
:
976 stack_block
, nodes_list
, restore
, old_mark
= self
.foreach_stack
[-1]
977 if stack_block
!= block
:
978 self
.reset_foreach_stack()
980 raise Exception("Reached the end of a block we never entered")
986 restore
.extend(self
.current_nodes
)
987 if continuing
== 'fail':
988 print "Error in block; exiting early in program", block
.get_program()
990 [self
.model
.unlock(x
) for x
in old_mark
]
991 self
.foreach_stack
.pop()
994 while nodes_list
and nodes_list
[0].parentNode
== None:
995 print "Skipping deleted node", nodes_list
[0]
999 self
.foreach_stack
.pop()
1002 nodes
= filter(lambda x
: self
.has_ancestor(x
, self
.root
), restore
)
1004 if old_mark
is not None:
1005 self
.set_marked(old_mark
)
1006 [self
.model
.unlock(x
) for x
in old_mark
]
1007 return 0 # Nothing left to do
1008 nodes
= nodes_list
[0]
1013 print "[ %d after this ]" % len(nodes_list
),
1018 self
.set_exec((block
.start
, 'next'))
1021 def play_block(self
, block
):
1022 assert isinstance(block
, Block
)
1023 #print "Enter Block!"
1025 list = self
.current_nodes
[:]
1027 list = [self
.current_nodes
[:]] # List of one item, containing everything
1030 marks
= self
.marked
.copy()
1031 [self
.model
.lock(x
) for x
in marks
]
1034 self
.foreach_stack
.append((block
, list, [], marks
))
1037 if not self
.start_block_iteration(block
):
1038 # No nodes selected...
1039 if not block
.is_toplevel():
1040 self
.set_exec((block
, 'next'))
1043 self
.set_exec((block
.start
, 'next'))
1047 assert self
.op_in_progress
1048 oip
= self
.op_in_progress
1050 self
.play_block(oip
)
1051 if not self
.single_step
:
1056 if self
.op_in_progress
:
1057 raise Exception("Operation in progress")
1059 raise Exception("Already playing!")
1060 self
.idle_cb
= self
.idle_add(self
.play_callback
)
1062 def play_callback(self
):
1063 self
.idle_remove(self
.idle_cb
)
1066 self
.in_callback
= 1
1070 self
.in_callback
= 0
1072 (op
, exit
) = self
.exec_point
1073 if exit
== 'fail' and self
.innermost_failure
:
1074 self
.jump_to_innermost_failure()
1075 print "Done, at " + time
.ctime(time
.time())
1082 type, val
, tb
= sys
.exc_info()
1083 list = traceback
.extract_tb(tb
)
1084 stack
= traceback
.format_list(list[-2:])
1085 ex
= traceback
.format_exception_only(type, val
) + ['\n\n'] + stack
1086 traceback
.print_exception(type, val
, tb
)
1087 print "Error in do_one_step(): stopping playback"
1088 node
= self
.op_in_progress
1091 self
.set_exec((node
, 'fail'))
1092 self
.status_changed()
1094 if self
.op_in_progress
or self
.single_step
:
1095 self
.status_changed()
1100 def status_changed(self
):
1101 for display
in self
.displays
:
1102 if hasattr(display
, 'update_state'):
1103 display
.update_state()
1105 def map(self
, name
):
1108 nodes
= self
.current_nodes
[:]
1110 print "map of nothing: skipping..."
1112 inp
= [nodes
, None] # Nodes, next
1113 def next(exit
= exit
, self
= self
, name
= name
, inp
= inp
):
1114 "This is called while in do_one_step() - normal rules apply."
1116 print "[ %d to go ]" % len(nodes
),
1119 print "Map: nodes remaining, but an error occurred..."
1120 return self
.default_done(exit
)
1121 while nodes
and nodes
[0].parentNode
== None:
1122 print "Skipping deleted node", nodes
[0]
1125 return self
.default_done(exit
)
1126 self
.move_to(nodes
[0])
1130 #print "Map: calling play (%d after this)" % len(nodes)
1131 self
.play(name
, done
= next
) # Should raise InProgress
1132 if nodes
is self
.current_nodes
:
1133 raise Exception("Slice failed!")
1137 def name_to_prog(self
, name
):
1138 comps
= string
.split(name
, '/')
1139 prog
= self
.model
.root_program
1140 if prog
.name
!= comps
[0]:
1141 raise Exception("No such program as '%s'!" % name
)
1144 prog
= prog
.subprograms
[comps
[0]]
1148 def change_node(self
, new_data
):
1149 nodes
= self
.current_nodes
1153 if nodes
[0].nodeType
== Node
.ELEMENT_NODE
:
1154 # Slow, so do this here, even if vaguely incorrect...
1155 assert ' ' not in new_data
1157 (prefix
, localName
) = string
.split(new_data
, ':', 1)
1159 (prefix
, localName
) = (None, new_data
)
1160 namespaceURI
= self
.model
.prefix_to_namespace(nodes
[0], prefix
)
1163 if node
is self
.root
:
1164 self
.model
.unlock(self
.root
)
1165 new
= self
.model
.set_name(node
, namespaceURI
, new_data
)
1166 self
.model
.lock(new
)
1169 new
= self
.model
.set_name(node
, namespaceURI
, new_data
)
1174 self
.model
.set_data(node
, new_data
)
1177 def add_node(self
, where
, data
):
1178 cur
= self
.get_current()
1181 (prefix
, localName
) = string
.split(data
, ':', 1)
1183 (prefix
, localName
) = (None, data
)
1184 namespaceURI
= self
.model
.prefix_to_namespace(self
.get_current(), prefix
)
1185 new
= self
.model
.doc
.createElementNS(namespaceURI
, data
)
1187 new
= self
.model
.doc
.createTextNode(data
)
1191 self
.model
.insert_before(cur
, new
)
1192 elif where
[0] == 'a':
1193 self
.model
.insert_after(cur
, new
)
1194 elif where
[0] == 'e':
1195 self
.model
.insert_before(None, new
, parent
= cur
)
1197 self
.model
.insert(cur
, new
)
1203 def request_from_node(self
, node
, attrib
):
1204 """Return a urllib2.Request object. If attrib is set then the URI is
1205 taken from that, otherwise search for a good attribute."""
1207 if node
.nodeType
== Node
.TEXT_NODE
:
1208 uri
= node
.nodeValue
1212 elif node
.hasAttributeNS(None, 'uri'):
1213 uri
= node
.getAttributeNS(None, 'uri')
1215 for attr
in node
.attributes
.keys():
1216 uri
= node
.attributes
[attr
].value
1217 if uri
.find('//') != -1 or uri
.find('.htm') != -1:
1220 print "Can't suck", node
, "(no uri attribute found)"
1222 if uri
.find('//') == -1:
1223 base
= self
.model
.get_base_uri(node
)
1224 #print "Relative URI..."
1226 #print "Base URI is:", base, "add", uri
1227 uri
= urlparse
.urljoin(base
, uri
)
1230 #print "Warning: Can't find 'uri' attribute!"
1231 request
= urllib2
.Request(uri
)
1235 def http_post(self
):
1236 node
= self
.get_current()
1237 attrs
= node
.attributes
1239 request
= self
.request_from_node(node
, self
.current_attrib
)
1240 for (ns
,name
) in attrs
.keys():
1241 if ns
is not None: continue
1242 value
= str(attrs
[(ns
, name
)].value
)
1243 if name
.startswith('header-'):
1244 request
.add_header(str(name
)[7:], value
)
1246 post
.append((str(name
), value
))
1248 request
.add_data(urllib
.urlencode(post
))
1249 node
= self
.suck_node(node
, request
)
1253 def suck(self
, md5_only
= 0):
1254 nodes
= self
.current_nodes
[:]
1255 attrib
= self
.current_attrib
1259 request
= self
.request_from_node(x
, attrib
)
1261 new
= self
.suck_node(x
, request
, md5_only
= md5_only
)
1268 self
.suck(md5_only
= 1)
1270 def suck_node(self
, node
, request
, md5_only
= 0):
1271 """Load the resource specified by request and replace 'node' with the
1273 uri
= request
.get_full_url()
1274 if uri
.startswith('file:///'):
1275 print "Loading", uri
1277 assert not request
.has_data()
1278 stream
= open(uri
[7:])
1279 # (could read the mod time here...)
1282 print "Sucking", uri
1284 if request
.has_data():
1285 print "POSTING", request
.get_data()
1286 stream
= urllib2
.urlopen(request
)
1287 headers
= stream
.info().headers
1290 if x
.lower().startswith('last-modified:'):
1291 last_mod
= x
[14:].strip()
1294 current_last_mod
= node
.getAttributeNS(None, 'last-modified')
1295 if current_last_mod
and last_mod
:
1296 if current_last_mod
== last_mod
:
1297 self
.model
.set_attrib(node
, 'modified', None)
1298 print "not modified => not sucking!\n"
1301 print "Fetching page contents..."
1302 data
= stream
.read()
1303 print "got data... tidying..."
1305 if data
.startswith('<?xml'):
1308 data
= to_html(data
)
1310 old_md5
= node
.getAttributeNS(None, 'md5_sum')
1313 new_md5
= md5
.new(data
).hexdigest()
1315 if old_md5
and new_md5
== old_md5
:
1316 self
.model
.set_attrib(node
, 'modified', None)
1317 print "MD5 sums match => not parsing!"
1321 # This is a nasty hack left in for backwards compat.
1322 self
.model
.set_attrib(node
, 'md5_sum', new_md5
)
1327 from Ft
.Xml
.InputSource
import InputSourceFactory
1328 from Ft
.Xml
.cDomlette
import nonvalParse
1329 isrc
= InputSourceFactory()
1332 root
= nonvalParse(isrc
.fromString(data
, uri
))
1333 #ext.StripHtml(root)
1335 type, val
, tb
= sys
.exc_info()
1336 traceback
.print_exception(type, val
, tb
)
1337 print "parsing failed!"
1340 #rox.report_exception()
1343 print "parse OK...",
1345 new
= node
.ownerDocument
.importNode(root
.documentElement
, 1)
1346 new
.setAttributeNS(None, 'uri', uri
)
1349 new
.setAttributeNS(None, 'last-modified', last_mod
)
1350 new
.setAttributeNS(None, 'modified', 'yes')
1351 new
.setAttributeNS(None, 'md5_sum', new_md5
)
1354 if node
== self
.root
:
1355 self
.model
.unlock(self
.root
)
1356 self
.model
.replace_node(self
.root
, new
)
1357 self
.model
.strip_space(new
)
1358 self
.model
.lock(new
)
1361 self
.model
.replace_node(node
, new
)
1362 self
.model
.strip_space(new
)
1367 def put_before(self
):
1368 node
= self
.get_current()
1369 if self
.clipboard
== None:
1371 new
= self
.clipboard
.cloneNode(1)
1373 self
.model
.insert_before(node
, new
)
1377 def put_after(self
):
1378 node
= self
.get_current()
1379 if self
.clipboard
== None:
1381 new
= self
.clipboard
.cloneNode(1)
1382 self
.model
.insert_after(node
, new
)
1384 def put_replace(self
):
1385 node
= self
.get_current()
1386 if self
.clipboard
== None:
1387 print "No clipboard!"
1389 if self
.current_attrib
:
1390 if self
.clipboard
.nodeType
== Node
.DOCUMENT_FRAGMENT_NODE
:
1391 value
= self
.clipboard
.childNodes
[0].data
1393 value
= self
.clipboard
.data
1394 a
= self
.current_attrib
1395 value
= value
.replace('\n', ' ')
1396 a
= self
.model
.set_attrib(node
, a
.name
, value
)
1397 self
.move_to(node
, a
)
1399 if self
.clipboard
.nodeType
== Node
.DOCUMENT_FRAGMENT_NODE
:
1400 if len(self
.clipboard
.childNodes
) != 1:
1401 print "Multiple nodes in clipboard!"
1403 new
= self
.clipboard
.childNodes
[0].cloneNode(1)
1405 new
= self
.clipboard
.cloneNode(1)
1406 if new
.nodeType
!= Node
.ELEMENT_NODE
:
1410 if node
== self
.root
:
1411 self
.model
.unlock(self
.root
)
1413 self
.model
.replace_node(self
.root
, new
)
1416 self
.model
.lock(self
.root
)
1418 self
.model
.replace_node(node
, new
)
1421 type, val
, tb
= sys
.exc_info()
1422 traceback
.print_exception(type, val
, tb
)
1423 print "Replace failed!"
1426 def put_as_child_end(self
):
1427 self
.put_as_child(end
= 1)
1429 def put_as_child(self
, end
= 0):
1430 node
= self
.get_current()
1431 if self
.clipboard
== None:
1433 new
= self
.clipboard
.cloneNode(1)
1434 if new
.nodeType
== Node
.DOCUMENT_FRAGMENT_NODE
:
1436 for n
in new
.childNodes
:
1442 self
.model
.insert_before(None, new
, parent
= node
)
1444 self
.model
.insert(node
, new
, index
= 0)
1450 def yank_value(self
):
1451 if not self
.current_attrib
:
1453 value
= self
.current_attrib
.value
1454 self
.clipboard
= self
.model
.doc
.createTextNode(value
)
1455 #print "Clip now", self.clipboard
1457 def yank_attribs(self
, name
= None):
1459 print "yank_attribs: DEPRECATED -- use Yank instead!"
1460 self
.clipboard
= self
.model
.doc
.createDocumentFragment()
1462 if not self
.get_current().hasAttributeNS(None, name
):
1464 attribs
= [self
.get_current().getAttributeNodeNS(None, name
)]
1467 dict = self
.get_current().attributes
1468 for a
in dict.keys():
1469 attribs
.append(dict[a
])
1471 # Make sure the attributes always come out in the same order
1472 # (helps with macros).
1474 diff
= cmp(a
.name
, b
.name
)
1476 diff
= cmp(a
.namespaceURI
, b
.namespaceURI
)
1479 attribs
.sort(by_name
)
1481 n
= self
.model
.doc
.createElementNS(a
.namespaceURI
, a
.nodeName
)
1482 n
.appendChild(self
.model
.doc
.createTextNode(a
.value
))
1483 self
.clipboard
.appendChild(n
)
1484 #print "Clip now", self.clipboard
1486 def paste_attribs(self
):
1487 if self
.clipboard
.nodeType
== Node
.DOCUMENT_FRAGMENT_NODE
:
1488 attribs
= self
.clipboard
.childNodes
1490 attribs
= [self
.clipboard
]
1494 new
.append((a
.nodeName
, a
.childNodes
[0].data
))
1497 for node
in self
.current_nodes
:
1498 # XXX: Set NS attribs first...
1499 for (name
, value
) in new
:
1500 self
.model
.set_attrib(node
, name
, value
)
1503 "Ensure that all selected nodes have the same value."
1504 if len(self
.current_nodes
) < 2:
1505 raise Beep
# Not enough nodes!
1506 base
= self
.current_nodes
[0]
1507 for n
in self
.current_nodes
[1:]:
1508 if not same(base
, n
):
1509 raise Beep(may_record
= 1)
1512 raise Beep(may_record
= 1)
1517 def fail_if(self
, xpath
):
1518 """Evaluate xpath as a boolean, and fail if true."""
1519 src
= self
.get_current()
1521 ns
['ext'] = FT_EXT_NAMESPACE
1522 c
= Context
.Context(src
.parentNode
, [src
.parentNode
], processorNss
= ns
)
1524 rt
= XPath
.Evaluate(xpath
, context
= c
)
1527 raise Beep(may_record
= 1)
1529 def attribute(self
, namespace
= None, attrib
= ''):
1530 node
= self
.get_current()
1536 if attrib
== 'xmlns':
1538 #print "(ns, attrib)", `namespace`, attrib
1540 a
= node
.attributes
.get((namespace
, attrib
), None)
1543 self
.move_to(node
, a
)
1545 print "No such attribute"
1548 def set_attrib(self
, value
):
1549 a
= self
.current_attrib
1552 node
= self
.get_current()
1553 a
= self
.model
.set_attrib(node
, a
.name
, value
)
1554 self
.move_to(node
, a
)
1556 def add_attrib(self
, UNUSED
, name
, value
= ''):
1557 node
= self
.get_current()
1558 a
= self
.model
.set_attrib(node
, name
, value
)
1559 self
.move_to(node
, a
)
1561 def parse_data(self
, data
, path
):
1562 """Convert and XML document into a DOM Document."""
1563 from Ft
.Xml
.InputSource
import InputSourceFactory
1564 from Ft
.Xml
.cDomlette
import nonvalParse
1565 isrc
= InputSourceFactory()
1568 doc
= nonvalParse(isrc
.fromString(data
, path
))
1570 type, val
, tb
= sys
.exc_info()
1571 traceback
.print_exception(type, val
, tb
)
1572 print "parsing failed!"
1575 #rox.report_exception()
1578 print "parse OK...",
1581 def set_root_from_doc(self
, doc
):
1582 new
= self
.root
.ownerDocument
.importNode(doc
.documentElement
, 1)
1585 self
.model
.unlock(self
.root
)
1587 self
.model
.replace_node(self
.root
, new
)
1588 self
.model
.lock(new
)
1590 self
.move_to(self
.root
)
1592 def load_html(self
, path
):
1593 "Replace root with contents of this HTML file."
1594 print "Reading HTML..."
1595 data
= file(path
).read()
1596 data
= to_html(data
)
1597 doc
= self
.parse_data(data
, path
)
1598 #doc = ext.StripHtml(doc)
1599 self
.set_root_from_doc(doc
)
1601 def load_xml(self
, path
):
1602 "Replace root with contents of this XML (or Dome) file."
1603 print "Reading XML..."
1604 data
= file(path
).read()
1605 doc
= self
.parse_data(data
, path
)
1606 self
.set_root_from_doc(doc
)
1608 def load_node(self
, root
):
1609 new
= self
.model
.doc
.importNode(root
, 1)
1611 self
.model
.strip_space(new
)
1614 self
.model
.unlock(self
.root
)
1616 self
.model
.replace_node(self
.root
, new
)
1617 self
.model
.lock(new
)
1619 self
.move_to(self
.root
)
1621 def select_dups(self
):
1622 node
= self
.get_current()
1624 for n
in node
.parentNode
.childNodes
:
1629 self
.move_to(select
)
1631 def select_marked_region(self
, attr
= "unused"):
1633 if len(self
.marked
) != 1:
1634 print "Must be exactly one marked node!"
1636 if len(self
.current_nodes
) != 1:
1637 print "Must be exactly one selected node!"
1640 a
= Path
.path_to(self
.get_current())
1641 b
= Path
.path_to(self
.marked
.keys()[0])
1643 while a
and b
and a
[0] == b
[0]:
1652 for x
in a
.parentNode
.childNodes
:
1659 self
.move_to(select
)
1661 print "One node is a parent of the other!"
1664 def show_html(self
):
1665 from HTML
import HTML
1666 HTML(self
.model
, self
.get_current()).show()
1668 def show_canvas(self
):
1669 from Canvas
import Canvas
1670 Canvas(self
, self
.get_current()).show()
1672 def toggle_hidden(self
):
1673 nodes
= self
.current_nodes
[:]
1676 if node
.hasAttributeNS(None, 'hidden'):
1680 self
.model
.set_attrib(node
, 'hidden', new
, with_update
= 0)
1681 self
.model
.update_all(self
.root
)
1684 def soap_send(self
):
1685 copy
= node_to_xml(self
.get_current())
1686 env
= copy
.documentElement
1688 if env
.namespaceURI
!= 'http://schemas.xmlsoap.org/soap/envelope/':
1689 alert("Not a SOAP-ENV:Envelope (bad namespace)")
1691 if env
.localName
!= 'Envelope':
1692 alert("Not a SOAP-ENV:Envelope (bad local name)")
1695 if len(env
.childNodes
) != 2:
1696 alert("SOAP-ENV:Envelope must have one header and one body")
1699 kids
= elements(env
)
1703 if head
.namespaceURI
!= 'http://schemas.xmlsoap.org/soap/envelope/' or \
1704 head
.localName
!= 'Head':
1705 alert("First child must be a SOAP-ENV:Head element")
1708 if body
.namespaceURI
!= 'http://schemas.xmlsoap.org/soap/envelope/' or \
1709 body
.localName
!= 'Body':
1710 alert("Second child must be a SOAP-ENV:Body element")
1714 for header
in elements(head
):
1715 if header
.namespaceURI
== DOME_NS
and header
.localName
== 'soap-forward-to':
1718 print header
.namespaceURI
1719 print header
.localName
1722 alert("Head must contain a dome:soap-forward-to element")
1725 dest
= sft
.childNodes
[0].data
1726 parent
= sft
.parentNode
1727 if len(elements(parent
)) == 1:
1729 parent
= sft
.parentNode
# Delete the whole header
1730 parent
.removeChild(sft
)
1732 import httplib
, urlparse
1734 (scheme
, addr
, path
, p
, q
, f
) = urlparse
.urlparse(dest
, allow_fragments
= 0)
1735 if scheme
!= 'http':
1736 alert("SOAP is only supported for 'http:' -- sorry!")
1740 PrettyPrint(copy
, stream
= stream
)
1741 message
= stream
.data
1743 conn
= httplib
.HTTP(addr
)
1744 conn
.putrequest("POST", path
)
1745 conn
.putheader('Content-Type', 'text/xml; charset="utf-8"')
1746 conn
.putheader('Content-Length', str(len(message
)))
1747 conn
.putheader('SOAPAction', '')
1750 (code
, r_mess
, r_headers
) = conn
.getreply()
1752 reply
= conn
.getfile().read()
1753 print "Got:\n", reply
1755 reader
= PyExpat
.Reader() # XXX
1756 new_doc
= reader
.fromString(reply
)
1759 new
= self
.model
.doc
.importNode(new_doc
.documentElement
, 1)
1761 self
.model
.strip_space(new
)
1763 old
= self
.get_current()
1765 self
.model
.replace_node(old
, new
)
1768 def program_changed(self
, changed_op
):
1769 print "Check points..."
1771 (op
, exit
) = self
.rec_point
1773 print "Lost rec_point"
1774 self
.rec_point
= None
1776 (op
, exit
) = self
.exec_point
1778 print "Lost exec_point"
1779 self
.exec_point
= None
1780 for l
in self
.lists
:
1782 self
.status_changed()
1784 def prog_tree_changed(self
):
1787 def export_all(self
):
1788 doc
= implementation
.createDocument(DOME_NS
, 'dome', None)
1789 node
= self
.model
.root_program
.to_xml(doc
)
1790 doc
.documentElement
.appendChild(node
)
1791 node
= doc
.createElementNS(DOME_NS
, 'dome-data')
1792 doc
.documentElement
.appendChild(node
)
1795 print "*** WARNING: Saving from a chroot!"
1797 data
= doc
.importNode(model
.doc
.documentElement
, 1)
1798 node
.appendChild(data
)
1802 def blank_all(self
):
1803 doc
= implementation
.createDocument(None, 'root', None)
1805 self
.clipboard
= self
.model
.doc
.createElementNS(None, 'root')
1808 def mark_switch(self
):
1809 new
= self
.marked
.keys()
1810 self
.set_marked(self
.current_nodes
)
1813 def set_marked(self
, new
):
1814 update
= self
.marked
1815 for x
in self
.marked
.keys():
1816 self
.model
.unlock(x
)
1820 self
.marked
[x
] = None
1822 update
= update
.keys()
1823 for display
in self
.displays
:
1824 display
.marked_changed(update
)
1826 def mark_selection(self
):
1827 self
.set_marked(self
.current_nodes
)
1829 def clear_mark(self
):
1832 def normalise(self
):
1833 self
.model
.normalise(self
.get_current())
1835 def remove_ns(self
):
1836 nodes
= self
.current_nodes
[:]
1838 nodes
= map(self
.model
.remove_ns
, nodes
)
1841 def convert_to_text(self
):
1842 nodes
= self
.current_nodes
[:]
1844 nodes
= map(self
.model
.convert_to_text
, nodes
)
1850 def write(self
, str):