/[ascend]/trunk/pygtk/modelview.py
ViewVC logotype

Contents of /trunk/pygtk/modelview.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 894 - (show annotations) (download) (as text)
Mon Oct 23 01:07:58 2006 UTC (15 years, 8 months ago) by johnpye
File MIME type: text/x-python
File size: 14598 byte(s)
Improved error message in integrator.c (added names of variables with clashing ode_id).
Removed debug output from observer.py.
Fixed icon paths in modelview (context menu)
1 import gtk
2 import gtk.glade
3 import pango
4 import ascpy
5
6 from varentry import *
7 from properties import *
8
9 BROWSER_FIXED_COLOR = "#008800"
10 BROWSER_FREE_COLOR = "#000088"
11 BROWSER_SETTING_COLOR = "#4444AA"
12
13 BROWSER_ACTIVE_COLOR = "black"
14 BROWSER_INACTIVE_COLOR = "#888888"
15
16 class ModelView:
17 def __init__(self,browser,glade):
18 self.browser = browser # the parent object: the entire ASCEND browser
19
20 self.modelview = glade.get_widget("browserview")
21
22 # name, type, value, foreground, weight, editable, status-icon
23 columns = [str,str,str,str,int,bool,gtk.gdk.Pixbuf]
24
25 self.otank = {}
26
27 # name, type, value, foreground, weight, editable, status-icon
28 columns = [str,str,str,str,int,bool,gtk.gdk.Pixbuf]
29 self.modelstore = gtk.TreeStore(*columns)
30 titles = ["Name","Type","Value"];
31 self.modelview.set_model(self.modelstore)
32 self.tvcolumns = [ gtk.TreeViewColumn() for _type in columns[:len(titles)] ]
33
34 self.modelview.connect("row-expanded", self.row_expanded )
35 self.modelview.connect("button-press-event", self.on_treeview_event )
36 self.modelview.connect("key-press-event",self.on_treeview_event )
37
38 # data columns are: name type value colour weight editable
39
40 i = 0
41 for tvcolumn in self.tvcolumns[:len(titles)]:
42 tvcolumn.set_title(titles[i])
43 self.modelview.append_column(tvcolumn)
44
45 if(i==2):
46 # add status icon
47 renderer1 = gtk.CellRendererPixbuf()
48 tvcolumn.pack_start(renderer1, False)
49 tvcolumn.add_attribute(renderer1, 'pixbuf', 6)
50
51 renderer = gtk.CellRendererText()
52 tvcolumn.pack_start(renderer, True)
53 tvcolumn.add_attribute(renderer, 'text', i)
54 tvcolumn.add_attribute(renderer, 'foreground', 3)
55 tvcolumn.add_attribute(renderer, 'weight', 4)
56 if(i==2):
57 tvcolumn.add_attribute(renderer, 'editable', 5)
58 renderer.connect('edited',self.cell_edited_callback)
59 i = i + 1
60
61 #--------------------
62 # set up the context menu for fixing/freeing vars
63
64 # TODO import this menu from Glade (this code is a PITA)
65
66 print "'free' ICON IS AT %s" % (self.browser.options.assets_dir+'/unlocked.png')
67 self.treecontext = gtk.Menu();
68 self.fixmenuitem = gtk.ImageMenuItem("_Fix",True);
69 self.fixmenuitem.set_image(self.browser.fixedimg)
70
71 self.freemenuitem = gtk.ImageMenuItem("F_ree",True);
72 _img = gtk.Image()
73 _img.set_from_file(self.browser.options.assets_dir+'/unlocked.png')
74 self.freemenuitem.set_image(_img)
75
76 self.propsmenuitem = gtk.ImageMenuItem("_Properties",True);
77 _img = gtk.Image()
78 _img.set_from_file(self.browser.options.assets_dir+'/properties.png')
79 self.propsmenuitem.set_image(_img)
80
81 self.observemenuitem = gtk.ImageMenuItem("_Observe",True);
82 _img = gtk.Image()
83 _img.set_from_file(self.browser.options.assets_dir+'/observe.png')
84 self.observemenuitem.set_image(_img)
85
86 self.fixmenuitem.show(); self.fixmenuitem.set_sensitive(False)
87 self.freemenuitem.show(); self.freemenuitem.set_sensitive(False)
88 self.observemenuitem.show(); self.observemenuitem.set_sensitive(False)
89 self.propsmenuitem.show()
90 self.treecontext.append(self.fixmenuitem)
91 self.treecontext.append(self.freemenuitem)
92 _sep = gtk.SeparatorMenuItem(); _sep.show()
93 self.treecontext.append(_sep);
94 self.treecontext.append(self.observemenuitem)
95 _sep = gtk.SeparatorMenuItem(); _sep.show()
96 self.treecontext.append(_sep)
97 self.treecontext.append(self.propsmenuitem)
98 self.fixmenuitem.connect("activate",self.fix_activate)
99 self.freemenuitem.connect("activate",self.free_activate)
100 self.propsmenuitem.connect("activate",self.props_activate)
101 self.observemenuitem.connect("activate",self.observe_activate)
102
103 if not self.treecontext:
104 raise RuntimeError("Couldn't create browsercontext")
105
106 def setSimulation(self,sim):
107 # instance hierarchy
108 self.sim = sim
109 self.modelstore.clear()
110 self.otank = {} # map path -> (name,value)
111 self.make( self.sim.getName(),self.sim.getModel() )
112 self.browser.maintabs.set_current_page(1);
113
114 def clear(self):
115 self.modelstore.clear()
116 self.otank = {}
117
118 # --------------------------------------------
119 # INSTANCE TREE
120
121 def get_tree_row_data(self,instance): # for instance browser
122 _value = str(instance.getValue())
123 _type = str(instance.getType())
124 _name = str(instance.getName())
125 _fgcolor = BROWSER_ACTIVE_COLOR
126 _fontweight = pango.WEIGHT_NORMAL
127 _editable = False
128 _statusicon = None
129 if instance.getType().isRefinedSolverVar():
130 _editable = True
131 _fontweight = pango.WEIGHT_BOLD
132 if instance.isFixed():
133 _fgcolor = BROWSER_FIXED_COLOR
134 else:
135 _fgcolor = BROWSER_FREE_COLOR
136 _fontweight = pango.WEIGHT_BOLD
137 _status = instance.getVarStatus();
138 _statusicon = self.browser.statusicons[_status]
139 elif instance.isRelation():
140 if not instance.isActive():
141 _fgcolor = BROWSER_INACTIVE_COLOR
142 elif instance.isBool() or instance.isReal() or instance.isInt():
143 # TODO can't edit constants that have already been refined
144 _editable = True
145 _fgcolor = BROWSER_SETTING_COLOR
146 _fontweight = pango.WEIGHT_BOLD
147 elif instance.isSymbol() and not instance.isConst():
148 _editable = True
149 _fgcolor = BROWSER_SETTING_COLOR
150 _fontweight = pango.WEIGHT_BOLD
151
152 #if(len(_value) > 80):
153 # _value = _value[:80] + "..."
154
155 return [_name, _type, _value, _fgcolor, _fontweight, _editable, _statusicon]
156
157 def make_row( self, piter, name, value ): # for instance browser
158
159 _piter = self.modelstore.append( piter, self.get_tree_row_data(value) )
160 return _piter
161
162 def refreshtree(self):
163 # @TODO FIXME use a better system than colour literals!
164 for _path in self.otank: # { path : (name,value) }
165 _iter = self.modelstore.get_iter(_path)
166 _name, _instance = self.otank[_path]
167 self.modelstore.set_value(_iter, 2, _instance.getValue())
168 if _instance.getType().isRefinedSolverVar():
169 if _instance.isFixed() and self.modelstore.get_value(_iter,3)==BROWSER_FREE_COLOR:
170 self.modelstore.set_value(_iter,3,BROWSER_FIXED_COLOR)
171 elif not _instance.isFixed() and self.modelstore.get_value(_iter,3)==BROWSER_FIXED_COLOR:
172 self.modelstore.set_value(_iter,3,BROWSER_FREE_COLOR)
173 self.modelstore.set_value(_iter, 6, self.browser.statusicons[_instance.getVarStatus()])
174 elif _instance.isRelation():
175 if _instance.isActive():
176 self.modelstore.set_value(_iter,3,BROWSER_ACTIVE_COLOR)
177 else:
178 self.modelstore.set_value(_iter,3,BROWSER_INACTIVE_COLOR)
179
180 def cell_edited_callback(self, renderer, path, newtext, **kwargs):
181 # get back the Instance object we just edited (having to use this seems like a bug)
182 path = tuple( map(int,path.split(":")) )
183
184 if not self.otank.has_key(path):
185 raise RuntimeError("cell_edited_callback: invalid path '%s'" % path)
186 return
187
188 _name, _instance = self.otank[path]
189
190 if _instance.isReal():
191 # only real-valued things can have units
192
193 _e = RealAtomEntry(_instance,newtext);
194 try:
195 _e.checkEntry()
196 _e.setValue()
197 _e.exportPreferredUnits(self.browser.prefs)
198 except InputError, e:
199 self.browser.reporter.reportError(str(e))
200 return;
201
202 else:
203 if _instance.isBool():
204 _lower = newtext.lower();
205 if _lower.startswith("t") or _lower.startswith("y") or _lower.strip()=="1":
206 newtext = 1
207 elif _lower.startswith("f") or _lower.startswith("n") or _lower.strip()=="0":
208 newtext = 0
209 else:
210 self.browser.reporter.reportError("Invalid entry for a boolean variable: '%s'" % newtext)
211 return
212 _val = bool(newtext);
213 if _val == _instance.getValue():
214 self.browser.reporter.reportNote("Boolean atom '%s' was not altered" % _instance.getName())
215 return
216 _instance.setBoolValue(_val)
217
218 elif _instance.isInt():
219 _val = int(newtext)
220 if _val == _instance.getValue():
221 self.browser.reporter.reportNote("Integer atom '%s' was not altered" % _instance.getName())
222 return
223 _instance.setIntValue(_val)
224 elif _instance.isSymbol():
225 _val = str(newtext)
226 if _val == _instance.getValue():
227 self.browser.reporter.reportNote("Symbol atom '%s' was not altered" % _instance.getName())
228 return
229 _instance.setSymbolValue(ascpy.SymChar(_val))
230
231 else:
232 self.browser.reporter.reportError("Attempt to set a non-real, non-boolean, non-integer value!")
233 return
234
235 # now that the variable is set, update the GUI and re-solve if desired
236 _iter = self.modelstore.get_iter(path)
237 self.modelstore.set_value(_iter,2,_instance.getValue())
238
239 if _instance.getType().isRefinedSolverVar():
240 self.modelstore.set_value(_iter,3,BROWSER_FIXED_COLOR) # set the row green as fixed
241
242 self.browser.do_solve_if_auto()
243
244 def make_children(self, value, piter ):
245 if value.isCompound():
246 children=value.getChildren();
247 for child in children:
248 _name = child.getName();
249 _piter = self.make_row(piter,_name,child)
250 _path = self.modelstore.get_path(_piter)
251 self.otank[_path]=(_name,child)
252 #self.browser.reporter.reportError("2 Added %s at path %s" % (_name,repr(_path)))
253
254 def make(self, name=None, value=None, path=None, depth=1):
255 if path is None:
256 # make root node
257 piter = self.make_row( None, name, value )
258 path = self.modelstore.get_path( piter )
259 self.otank[ path ] = (name, value)
260 #self.browser.reporter.reportError("4 Added %s at path %s" % (name, path))
261 else:
262 name, value = self.otank[ path ]
263
264 piter = self.modelstore.get_iter( path )
265 if not self.modelstore.iter_has_child( piter ):
266 self.make_children(value,piter)
267
268 if depth:
269 for i in range( self.modelstore.iter_n_children( piter ) ):
270 self.make( path = path+(i,), depth = depth - 1 )
271 else:
272 self.modelview.expand_row("0",False)
273
274 def row_expanded( self, modelview, piter, path ):
275 self.make( path = path )
276
277
278 # ------------------------------
279 # CONTEXT MENU
280
281 def on_treeview_event(self,widget,event):
282 _contextmenu = False;
283 if event.type==gtk.gdk.KEY_PRESS and gtk.gdk.keyval_name(event.keyval)=='Menu':
284 _contextmenu = True
285 _path, _col = self.modelview.get_cursor()
286 _button = 3;
287 elif event.type==gtk.gdk.BUTTON_PRESS:
288 if event.button == 3:
289 _contextmenu = True
290 _x = int(event.x)
291 _y = int(event.y)
292 _button = event.button
293 _pthinfo = self.modelview.get_path_at_pos(_x, _y)
294 if _pthinfo == None:
295 return
296 _path, _col, _cellx, _celly = _pthinfo
297
298 # which button was clicked?
299 if not _contextmenu:
300 return
301
302 _canpop = False;
303 # self.browser.reporter.reportError("Right click on %s" % self.otank[_path][0])
304 _instance = self.otank[_path][1]
305 if _instance.getType().isRefinedSolverVar():
306 _canpop = True
307 self.observemenuitem.set_sensitive(True)
308 if _instance.isFixed():
309 self.fixmenuitem.set_sensitive(False)
310 self.freemenuitem.set_sensitive(True)
311 else:
312 self.fixmenuitem.set_sensitive(True)
313 self.freemenuitem.set_sensitive(False)
314 elif _instance.isRelation():
315 _canpop = True
316 self.propsmenuitem.set_sensitive(True)
317 elif _instance.isModel():
318 # MODEL instances have a special context menu:
319 _menu = self.get_model_context_menu(_instance)
320 self.modelview.grab_focus()
321 self.modelview.set_cursor(_path,_col,0)
322 print "RUNNING POPUP MENU"
323 _menu.popup(None,None,None,_button,event.time)
324 return
325
326 if not _canpop:
327 return
328
329 self.modelview.grab_focus()
330 self.modelview.set_cursor( _path, _col, 0)
331 self.treecontext.popup( None, None, None, _button, event.time)
332 return 1
333
334 def get_model_context_menu(self,instance):
335 menu = gtk.Menu()
336
337 if instance.isPlottable():
338 print "PLOTTABLE"
339 mi = gtk.ImageMenuItem("P_lot",True);
340 img = gtk.Image()
341 img.set_from_file(self.browser.options.assets_dir+'plot.png')
342 mi.set_image(img)
343 mi.show()
344 mi.connect("activate",self.plot_activate)
345 menu.append(mi);
346 sep = gtk.SeparatorMenuItem(); sep.show()
347 menu.append(sep)
348
349 mi = gtk.ImageMenuItem("Run method...",False)
350 mi.set_sensitive(False)
351 img = gtk.Image()
352 img.set_from_stock(gtk.STOCK_EXECUTE,gtk.ICON_SIZE_MENU)
353 mi.set_image(img)
354 mi.show()
355 menu.append(mi)
356
357 sep = gtk.SeparatorMenuItem(); sep.show()
358 menu.append(sep)
359
360 t = instance.getType()
361 ml = t.getMethods()
362 if len(ml):
363 for m in ml:
364 mi = gtk.MenuItem(m.getName(),False)
365 mi.show()
366 mi.connect("activate",self.run_activate,instance,m)
367 menu.append(mi)
368
369 return menu
370
371 def run_activate(self,widget,instance,method):
372 print "RUNNING %s" % method.getName()
373 self.browser.sim.run(method,instance)
374 self.refreshtree()
375
376 def fix_activate(self,widget):
377 _path,_col = self.modelview.get_cursor()
378 _name, _instance = self.otank[_path]
379 self.set_fixed(_instance,True);
380 _instance.setFixed(True)
381 return 1
382
383 def free_activate(self,widget):
384 _path,_col = self.modelview.get_cursor()
385 _instance = self.otank[_path][1]
386 self.set_fixed(_instance,False)
387 return 1
388
389 def plot_activate(self,widget):
390
391 self.browser.reporter.reportNote("plot_activate...");
392 _path,_col = self.modelview.get_cursor()
393 _instance = self.otank[_path][1]
394 if not _instance.isPlottable():
395 self.browser.reporter.reportError("Can't plot instance %s" % _instance.getName().toString())
396 return
397 else:
398 self.browser.reporter.reportNote("Instance %s about to be plotted..." % _instance.getName().toString())
399
400 print("Plotting instance '%s'..." % _instance.getName().toString())
401
402 _plot = _instance.getPlot()
403
404 print "Title: ", _plot.getTitle()
405 _plot.show(True)
406
407 return 1
408
409 def props_activate(self,widget,*args):
410 _path,_col = self.modelview.get_cursor()
411 _instance = self.otank[_path][1]
412 if _instance.isRelation():
413 print "Relation '"+_instance.getName().toString()+"':", \
414 _instance.getRelationAsString(self.sim.getModel())
415 _dia = RelPropsWin(self.browser,_instance);
416 _dia.run();
417 elif _instance.getType().isRefinedSolverVar():
418 _dia = VarPropsWin(self.browser,_instance);
419 _dia.run();
420 else:
421 self.browser.reporter.reportWarning("Select a variable first...")
422
423 def observe_activate(self,widget,*args):
424 _path,_col = self.modelview.get_cursor()
425 _instance = self.otank[_path][1]
426 if _instance.getType().isRefinedSolverVar():
427 print "OBSERVING",_instance.getName().toString()
428 self.browser.observe(_instance)
429
430 def on_fix_variable_activate(self,*args):
431 _path,_col = self.modelview.get_cursor()
432 _instance = self.otank[_path][1]
433 self.set_fixed(_instance,True)
434
435 def on_free_variable_activate(self,*args):
436 _path,_col = self.modelview.get_cursor()
437 _instance = self.otank[_path][1]
438 self.set_fixed(_instance,False)
439
440 def set_fixed(self,instance,val):
441 if instance.getType().isRefinedSolverVar():
442 f = instance.isFixed();
443 if (f and not val) or (not f and val):
444 instance.setFixed(val)
445 self.browser.do_solve_if_auto()

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