/[ascend]/trunk/pygtk/canvas/blocklist.py
ViewVC logotype

Contents of /trunk/pygtk/canvas/blocklist.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1938 - (show annotations) (download) (as text)
Thu Oct 30 02:12:24 2008 UTC (13 years, 8 months ago) by jpye
File MIME type: text/x-python
File size: 6407 byte(s)
Add support for deletion of canvas elements (no undo yet).
1 from __future__ import with_statement
2 import os, sys
3
4 os.chdir(os.path.dirname(sys.argv[0]))
5 os.environ['ASCENDLIBRARY'] = "../../models"
6 os.environ['LD_LIBRARY_PATH'] = "../.."
7 sys.path.append("..")
8
9
10 if sys.platform.startswith("win"):
11 # Fetchs gtk2 path from registry
12 import _winreg
13 import msvcrt
14 try:
15 k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "Software\\GTK\\2.0")
16 except EnvironmentError:
17 # use TkInter to report the error :-)
18 from TkInter import *
19 root = Tk()
20 w = Label(root,"You must install the Gtk+ 2.2 Runtime Environment to run this program")
21 w.pack()
22 root.mainloop()
23 sys.exit(1)
24 else:
25 gtkdir = _winreg.QueryValueEx(k, "Path")
26 import os
27 # we must make sure the gtk2 path is the first thing in the path
28 # otherwise, we can get errors if the system finds other libs with
29 # the same name in the path...
30 os.environ['PATH'] = "%s/lib;%s/bin;" % (gtkdir[0], gtkdir[0]) + os.environ['PATH']
31
32 import ascpy
33
34 L = ascpy.Library()
35
36 # FIXME need to add way to add/remove modules from the Library?
37 L.load('test/canvas/blocktypes.a4c')
38
39 D = L.getAnnotationDatabase()
40
41 M = L.getModules()
42
43 blocktypes = set()
44
45 class Block:
46 def __init__(self, typedesc, notesdb):
47 self.type = typedesc
48 self.notesdb = notesdb
49
50 nn = notesdb.getTypeRefinedNotesLang(self.type,ascpy.SymChar("inline"))
51
52 self.inputs = []
53 self.outputs = []
54 for n in nn:
55 t = n.getText()
56 if t[0:min(len(t),3)]=="in:":
57 self.inputs += [n]
58 elif t[0:min(len(t),4)]=="out:":
59 self.outputs += [n]
60
61 def get_icon(self, width, height):
62 return gtk.gdk.pixbuf_new_from_file_at_size("defaultblock.svg",width,height)
63
64
65 for m in M:
66 T = L.getModuleTypes(m)
67 for t in T:
68 # 'block' types must not be parametric, because they must be able to
69 # exist even without being connected, and parametric models impose
70 # restrictions on the use of ARE_THE_SAME and similar.
71 if t.hasParameters():
72 continue
73 x = D.getNotes(t,ascpy.SymChar("block"),ascpy.SymChar("SELF"))
74 if x:
75 blocktypes.add(t)
76
77 blocks = []
78
79 print "block types:"
80 if not blocktypes:
81 print "NONE FOUND"
82 for t in blocktypes:
83
84 b = Block(t,D)
85
86 blocks += [b]
87
88 print b.type.getName()
89
90 print "\t\tinputs:",[n.getId() for n in b.inputs]
91 for n in b.inputs:
92 print "\t\t\t%s: %s (type = %s)" % (n.getId(),n.getText(),n.getType())
93 print "\t\toutputs:",[n.getId() for n in b.outputs]
94 for n in b.outputs:
95 print "\t\t\t%s: %s" % (n.getId(),n.getText())
96
97
98 # render icon table
99 import threading
100 import gtk
101 import os, os.path, re
102
103 import cairo
104 from gaphas import GtkView, View
105 from gaphas.tool import HoverTool, PlacementTool, HandleTool, ToolChain
106 from gaphas.tool import ItemTool, RubberbandTool
107 from port import *
108
109 def factory(view, cls):
110 """
111 Simple canvas item factory.
112 """
113 def wrapper():
114 item = cls()
115 view.canvas.add(item)
116 return item
117 return wrapper
118
119 gtk.gdk.threads_init()
120
121 class BlockIconView(gtk.IconView):
122 def __init__(self,blocks,app):
123 # the mode containing the icons themselves...
124 self.model = gtk.ListStore(str, gtk.gdk.Pixbuf)
125 self.app = app
126 self.otank = {}
127 thread = threading.RLock()
128 n = 0
129 with thread:
130 for b in blocks:
131 n += 1
132 pixbuf = b.get_icon(64,64)
133 iter = self.model.append([b.type.getName(), pixbuf])
134 path = self.model.get_path(iter)
135 self.otank[path] = b
136
137 gtk.IconView.__init__(self)
138 self.set_model(self.model)
139 self.set_text_column(0)
140 self.set_pixbuf_column(1)
141 self.set_columns(-1)
142 self.set_size_request(180,100)
143 self.connect("item-activated", self.item_activated)
144 self.connect("selection-changed", self.selection_changed)
145 def item_activated(self,iconview,path):
146 b = self.otank[path]
147 self.app.status.push(0, "Activated '%s'..." % b.type.getName())
148 #view.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.CROSSHAIR))
149 self.app.set_placement_tool(b)
150
151 def selection_changed(self,iconview):
152 s = self.get_selected_items()
153 if len(s)==1:
154 b = self.otank[s[0]]
155 self.app.set_placement_tool(b)
156 self.app.status.push(0,"Selected '%s'..." % b.type.getName())
157
158 class app(gtk.Window):
159 def __init__(self):
160 self.status = gtk.Statusbar()
161
162 # the Gaphas canvas
163 canvas = BlockCanvas()
164
165 # the main window
166 gtk.Window.__init__(self)
167 self.set_title("ASCEND Blocks")
168 self.set_default_size(400, 500)
169 self.connect("destroy", gtk.main_quit)
170 self.connect("key-press-event", self.key_press_event)
171
172 # vbox containing the main view and the status bar at the bottom
173 vbox = gtk.VBox()
174
175 # hbox occupies top part of vbox, with icons on left & canvas on right.
176 hbox = gtk.HBox()
177
178 # the 'view' widget implemented by Gaphas
179 self.view = GtkView()
180 self.view.tool = DefaultExampleTool()
181
182 # table containing scrollbars and main canvas
183 t = gtk.Table(2,2)
184 self.view.canvas = canvas
185 self.view.zoom(1)
186 self.view.set_size_request(600, 500)
187 hs = gtk.HScrollbar(self.view.hadjustment)
188 vs = gtk.VScrollbar(self.view.vadjustment)
189 t.attach(self.view, 0, 1, 0, 1)
190 t.attach(hs, 0, 1, 1, 2, xoptions=gtk.FILL, yoptions=gtk.FILL)
191 t.attach(vs, 1, 2, 0, 1, xoptions=gtk.FILL, yoptions=gtk.FILL)
192
193 # a scrolling window to contain the icon palette
194 scroll = gtk.ScrolledWindow()
195 scroll.set_border_width(2)
196 scroll.set_shadow_type(gtk.SHADOW_ETCHED_IN)
197 scroll.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC)
198
199 # icon palette
200 self.blockiconview = BlockIconView(blocks, self)
201 scroll.add(self.blockiconview)
202
203 hbox.pack_start(scroll, True, True)
204 hbox.pack_start(t, True, True)
205 vbox.pack_start(hbox, True, True)
206 vbox.pack_start(self.status, False, False)
207 self.add(vbox)
208 self.show_all()
209
210 # a message about the found blocks
211 self.status.push(0, "Found %d block types." % (len(blocks)))
212
213 def set_placement_tool(self,block):
214 # TODO: add undo handler
215 label = block.type.getName()
216 def my_block_factory():
217 def wrapper():
218 b = DefaultBlock(label,inputs=len(block.inputs),outputs=len(block.outputs))
219 self.view.canvas.add(b)
220 return b
221 return wrapper
222 self.view.tool.grab(PlacementTool(my_block_factory(), HandleTool(), 2))
223
224 def key_press_event(self,widget,event):
225 # TODO: add undo handler
226 key = gtk.gdk.keyval_name(event.keyval)
227 if key == 'Delete' and self.view.focused_item:
228 self.view.canvas.remove(self.view.focused_item)
229 self.status.push(0,"Item deleted.")
230
231 a = app()
232 gtk.main()
233

john.pye@anu.edu.au
ViewVC Help
Powered by ViewVC 1.1.22