1 ! Copyright (C) 2008 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors sequences assocs arrays continuations
4 destructors combinators kernel threads concurrency.messaging
5 concurrency.mailboxes concurrency.promises io.files io.monitors
7 IN: io.monitors.recursive
9 ! Simulate recursive monitors on platforms that don't have them
11 TUPLE: recursive-monitor < monitor children thread ready disposed ;
13 : notify? ( -- ? ) monitor tget ready>> promise-fulfilled? ;
15 DEFER: add-child-monitor
17 : qualify-path ( path -- path' )
18 monitor tget path>> prepend-path ;
20 : add-child-monitors ( path -- )
21 #! We yield since this directory scan might take a while.
23 [ append-path ] with map
24 [ add-child-monitor ] each yield
25 ] with-directory-files ;
27 : add-child-monitor ( path -- )
28 notify? [ dup { +add-file+ } monitor tget queue-change ] when
29 qualify-path dup link-info directory? [
30 [ add-child-monitors ]
33 _ [ f my-mailbox (monitor) ] keep
34 monitor tget children>> set-at
39 : remove-child-monitor ( monitor -- )
40 monitor tget children>> delete-at* [ dispose ] [ drop ] if ;
42 M: recursive-monitor dispose*
43 [ "stop" swap thread>> send-synchronous drop ]
48 monitor tget children>> [ nip dispose ] assoc-each ;
50 : pump-step ( msg -- )
51 first3 path>> swap [ prepend-path ] dip monitor tget 3array
55 : child-added ( path monitor -- )
56 path>> prepend-path add-child-monitor ;
58 : child-removed ( path monitor -- )
59 path>> prepend-path remove-child-monitor ;
61 : update-hierarchy ( msg -- )
64 { +add-file+ [ child-added ] }
65 { +remove-file+ [ child-removed ] }
66 { +rename-file-old+ [ child-removed ] }
67 { +rename-file-new+ [ child-added ] }
73 receive dup synchronous? [
74 [ stop-pump t ] dip reply-synchronous
76 [ '[ _ update-hierarchy ] ignore-errors ] [ pump-step ] bi
80 : monitor-ready ( error/t -- )
81 monitor tget ready>> fulfill ;
83 : pump-thread ( monitor -- )
85 [ "" add-child-monitor t monitor-ready ]
86 [ [ self <linked-error> monitor-ready ] keep rethrow ]
90 : start-pump-thread ( monitor -- )
91 dup '[ _ pump-thread ]
92 "Recursive monitor pump" spawn
95 : wait-for-ready ( monitor -- )
96 ready>> ?promise ?linked drop ;
98 : <recursive-monitor> ( path mailbox -- monitor )
99 [ (normalize-path) ] dip
100 recursive-monitor new-monitor
101 H{ } clone >>children
103 dup start-pump-thread