/[ascend]/trunk/pygtk/interface/gtkbrowser.py
ViewVC logotype

Contents of /trunk/pygtk/interface/gtkbrowser.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 271 - (show annotations) (download) (as text)
Sat Feb 4 09:08:54 2006 UTC (18 years, 4 months ago) by johnpye
File MIME type: text/x-python
File size: 29150 byte(s)
Working on adding support for listing cliques
1 #!/usr/bin/env python
2
3 import pygtk
4 pygtk.require('2.0')
5 import gtk
6 import gtk.glade
7 import pango
8 import re
9 import preferences # loading/saving of .ini options
10 import urlparse
11 import optparse
12
13 from solverparameters import * # 'solver parameters' window
14 from help import * # viewing help files
15 from incidencematrix import * # incidence/sparsity matrix matplotlib window
16 from observer import * # observer tab support
17 from properties import * # solver_var properties dialog
18 from varentry import * # for inputting of variables with units
19
20 import sys, dl
21 # This sets the flags for dlopen used by python so that the symbols in the
22 # ascend library are made available to libraries dlopened within ASCEND:
23 sys.setdlopenflags(dl.RTLD_GLOBAL|dl.RTLD_NOW)
24 import ascend
25
26 # This is my first ever GUI code so please be nice :)
27
28 # The fancy tree-view gizmo is the GtkTreeView object. See the article
29 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/300304
30 # for the original source code on which my implementation was based.
31
32 GLADE_FILE = "/home/john/src/ascend/trunk/pygtk/interface/ascend.glade"
33
34 ESCAPE_KEY = 65307
35
36 HELP_ROOT = None
37
38 BROWSER_FIXED_COLOR = "#008800"
39 BROWSER_FREE_COLOR = "#000088"
40 #======================================
41 # Browser is the main ASCEND library/model browser window
42
43 class Browser:
44
45 # ---------------------------------
46 # SETUP
47
48 def __init__(self):
49 #--------
50 # load the file referenced in the command line, if any
51
52 parser = optparse.OptionParser(usage="%prog [[-m typename] file]", version="gtkbrowser $rev$" )
53 # add options here if we want
54
55 parser.add_option("-m", "--model"
56 ,action="store", type="string", dest="model"
57 ,help="specify the model to instantiate upon loading modules")
58 (options, args) = parser.parse_args()
59
60 #print "OPTIONS_______________:",options
61
62 self.observers = []
63 self.clip = None
64
65 #--------
66 # load up the preferences ini file
67
68 self.prefs = preferences.Preferences()
69
70 #--------
71 # initialise ASCEND
72
73 self.library = ascend.Library()
74
75 self.sim = None
76
77 #-------------------
78 # Set up the window and main widget actions
79
80 glade = gtk.glade.XML(GLADE_FILE,"browserwin")
81
82 self.window = glade.get_widget("browserwin")
83
84 if not self.window:
85 raise RuntimeError("Couldn't load window from glade file")
86
87 _display = self.window.get_screen().get_display().get_name();
88 _geom=self.prefs.getGeometrySizePosition(_display,"browserwin")
89 if _geom:
90 self.window.resize(_geom[0],_geom[1]);
91 self.window.move(_geom[2],_geom[3]);
92
93 self.window.connect("delete_event", self.delete_event)
94
95 self.browserpaned=glade.get_widget("browserpaned");
96 _geom2=self.prefs.getGeometryValue(_display,"browserpaned");
97 if _geom2:
98 self.browserpaned.set_position(_geom2);
99
100 self.openbutton=glade.get_widget("openbutton")
101 self.openbutton.connect("clicked",self.open_click)
102
103 self.reloadbutton=glade.get_widget("reloadbutton")
104 self.reloadbutton.connect("clicked",self.reload_click)
105
106 self.solvebutton=glade.get_widget("solvebutton")
107 self.solvebutton.connect("clicked",self.solve_click)
108
109 self.checkbutton=glade.get_widget("checkbutton")
110 self.checkbutton.connect("clicked",self.check_click)
111
112 self.autotoggle=glade.get_widget("autotoggle")
113 self.autotoggle.connect("toggled",self.auto_toggle)
114
115 self.is_auto = self.autotoggle.get_active()
116
117 self.methodrunbutton=glade.get_widget("methodrunbutton")
118 self.methodrunbutton.connect("clicked",self.methodrun_click)
119
120 self.methodsel=glade.get_widget("methodsel")
121
122 self.maintabs = glade.get_widget("maintabs")
123
124 self.statusbar = glade.get_widget("statusbar")
125
126 self.menu = glade.get_widget("browsermenu")
127 glade.signal_autoconnect(self)
128
129 self.automenu = glade.get_widget("automenu")
130 self.automenu.set_active(self.is_auto)
131 if self.automenu == None:
132 print "NO AUTOMENU FOUND"
133
134 #-------------------
135 # waitwin
136
137 self.waitwin = gtk.gdk.Window(self.window.window,
138 gtk.gdk.screen_width(),
139 gtk.gdk.screen_height(),
140 gtk.gdk.WINDOW_CHILD,
141 0,
142 gtk.gdk.INPUT_ONLY)
143
144 _cursor = gtk.gdk.Cursor(gtk.gdk.WATCH)
145 self.waitwin.set_cursor(_cursor)
146
147 #-------------------
148 # pixbufs to be used in the error listing
149
150 self.iconok = self.window.render_icon(gtk.STOCK_YES,gtk.ICON_SIZE_MENU)
151 self.iconinfo = self.window.render_icon(gtk.STOCK_DIALOG_INFO,gtk.ICON_SIZE_MENU)
152 self.iconwarning = self.window.render_icon(gtk.STOCK_DIALOG_WARNING,gtk.ICON_SIZE_MENU)
153 self.iconerror = self.window.render_icon(gtk.STOCK_DIALOG_ERROR,gtk.ICON_SIZE_MENU)
154
155 #--------------------
156 # pixbufs for solver_var status
157
158 self.fixedimg = gtk.Image()
159 self.fixedimg.set_from_file('icons/locked.png')
160
161 self.iconstatusunknown = None
162 self.iconfixed = self.fixedimg.get_pixbuf()
163 self.iconsolved = self.window.render_icon(gtk.STOCK_YES,gtk.ICON_SIZE_MENU)
164 self.iconactive = self.window.render_icon(gtk.STOCK_NO,gtk.ICON_SIZE_MENU)
165 self.iconunsolved = None
166
167 self.statusicons={
168 ascend.ASCXX_VAR_STATUS_UNKNOWN: self.iconstatusunknown
169 ,ascend.ASCXX_VAR_FIXED: self.iconfixed
170 ,ascend.ASCXX_VAR_SOLVED: self.iconsolved
171 ,ascend.ASCXX_VAR_ACTIVE: self.iconactive
172 ,ascend.ASCXX_VAR_UNSOLVED: self.iconunsolved
173 }
174
175 #--------------------
176 # set up the context menu for fixing/freeing vars
177
178 # TODO import this menu from Glade (this code is a PITA)
179
180 self.treecontext = gtk.Menu();
181 self.fixmenuitem = gtk.ImageMenuItem("_Fix",True);
182 self.fixmenuitem.set_image(self.fixedimg)
183
184 self.freemenuitem = gtk.ImageMenuItem("F_ree",True);
185 _img = gtk.Image()
186 _img.set_from_file('icons/unlocked.png')
187 self.freemenuitem.set_image(_img)
188
189 self.plotmenuitem = gtk.ImageMenuItem("P_lot",True);
190 _img = gtk.Image()
191 _img.set_from_file('icons/plot.png')
192 self.plotmenuitem.set_image(_img)
193
194 self.propsmenuitem = gtk.ImageMenuItem("_Properties",True);
195 _img = gtk.Image()
196 _img.set_from_file('icons/properties.png')
197 self.propsmenuitem.set_image(_img)
198
199 self.observemenuitem = gtk.ImageMenuItem("_Observe",True);
200 _img = gtk.Image()
201 _img.set_from_file('icons/observe.png')
202 self.observemenuitem.set_image(_img)
203
204 self.fixmenuitem.show(); self.fixmenuitem.set_sensitive(False)
205 self.freemenuitem.show(); self.freemenuitem.set_sensitive(False)
206 self.plotmenuitem.show(); self.plotmenuitem.set_sensitive(False)
207 self.observemenuitem.show(); self.observemenuitem.set_sensitive(False)
208 self.propsmenuitem.show()
209 self.treecontext.append(self.fixmenuitem)
210 self.treecontext.append(self.freemenuitem)
211 _sep = gtk.SeparatorMenuItem(); _sep.show()
212 self.treecontext.append(_sep);
213 self.treecontext.append(self.plotmenuitem)
214 self.treecontext.append(self.observemenuitem)
215 _sep = gtk.SeparatorMenuItem(); _sep.show()
216 self.treecontext.append(_sep)
217 self.treecontext.append(self.propsmenuitem)
218 self.fixmenuitem.connect("activate",self.fix_activate)
219 self.freemenuitem.connect("activate",self.free_activate)
220 self.plotmenuitem.connect("activate",self.plot_activate)
221 self.propsmenuitem.connect("activate",self.props_activate)
222 self.observemenuitem.connect("activate",self.observe_activate)
223
224 if not self.treecontext:
225 raise RuntimeError("Couldn't create browsercontext")
226 #--------------------
227 # set up the error view
228
229 self.errorview = glade.get_widget("errorview")
230 errstorecolstypes = [gtk.gdk.Pixbuf,str,str,str,int]
231 self.errorstore = gtk.TreeStore(*errstorecolstypes)
232 errtitles = ["","Location","Message"];
233 self.errorview.set_model(self.errorstore)
234 self.errcols = [ gtk.TreeViewColumn() for _type in errstorecolstypes]
235
236 i = 0
237 for tvcolumn in self.errcols[:len(errtitles)]:
238 tvcolumn.set_title(errtitles[i])
239 self.errorview.append_column(tvcolumn)
240
241 if i>0:
242 _renderer = gtk.CellRendererText()
243 tvcolumn.pack_start(_renderer, True)
244 tvcolumn.add_attribute(_renderer, 'text', i)
245 if(i==2):
246 tvcolumn.add_attribute(_renderer, 'foreground', 3)
247 tvcolumn.add_attribute(_renderer, 'weight', 4)
248 else:
249 _renderer1 = gtk.CellRendererPixbuf()
250 tvcolumn.pack_start(_renderer1, False)
251 tvcolumn.add_attribute(_renderer1, 'pixbuf', int(0))
252
253 i = i + 1
254
255
256 #--------------------
257 # set up the error reporter callback
258 self.reporter = ascend.getReporter()
259 self.reporter.setPythonErrorCallback(self.error_callback)
260
261 #-------------------
262 # set up the module view
263
264 self.modtank = {}
265 self.moduleview = glade.get_widget("moduleview")
266 modulestorecoltypes = [str, str]
267 self.modulestore = gtk.TreeStore(*modulestorecoltypes)
268 moduleviewtitles = ["Module name", "Filename"]
269 self.moduleview.set_model(self.modulestore)
270 self.modcols = [ gtk.TreeViewColumn() for _type in modulestorecoltypes]
271 i = 0
272 for modcol in self.modcols[:len(moduleviewtitles)]:
273 modcol.set_title(moduleviewtitles[i])
274 self.moduleview.append_column(modcol)
275 _renderer = gtk.CellRendererText()
276 modcol.pack_start(_renderer, True)
277 modcol.add_attribute(_renderer, 'text', i)
278 i = i + 1
279 self.moduleview.connect("row-activated", self.module_activated )
280
281 #--------------------
282 # set up the methods combobox
283
284 self.methodstore = gtk.ListStore(str)
285 self.methodsel.set_model(self.methodstore)
286 _methodrenderer = gtk.CellRendererText()
287 self.methodsel.pack_start(_methodrenderer, True)
288 self.methodsel.add_attribute(_methodrenderer, 'text',0)
289
290 #--------
291 # set up the instance browser view
292
293 self.otank = {}
294 self.treeview = glade.get_widget("browserview")
295
296 # name, type, value, foreground, weight, editable, status-icon
297 columns = [str,str,str,str,int,bool,gtk.gdk.Pixbuf]
298 self.treestore = gtk.TreeStore(*columns)
299 titles = ["Name","Type","Value"];
300 self.treeview.set_model(self.treestore)
301 self.tvcolumns = [ gtk.TreeViewColumn() for _type in columns[:len(titles)] ]
302
303 self.treeview.connect("row-expanded", self.row_expanded )
304 self.treeview.connect("button-press-event", self.on_treeview_event )
305 self.treeview.connect("key-press-event",self.on_treeview_event )
306
307 # data columns are: name type value colour weight editable
308
309 i = 0
310 for tvcolumn in self.tvcolumns[:len(titles)]:
311 tvcolumn.set_title(titles[i])
312 self.treeview.append_column(tvcolumn)
313
314 if(i==2):
315 # add status icon
316 renderer1 = gtk.CellRendererPixbuf()
317 tvcolumn.pack_start(renderer1, False)
318 tvcolumn.add_attribute(renderer1, 'pixbuf', 6)
319
320 renderer = gtk.CellRendererText()
321 tvcolumn.pack_start(renderer, True)
322 tvcolumn.add_attribute(renderer, 'text', i)
323 tvcolumn.add_attribute(renderer, 'foreground', 3)
324 tvcolumn.add_attribute(renderer, 'weight', 4)
325 if(i==2):
326 tvcolumn.add_attribute(renderer, 'editable', 5)
327 renderer.connect('edited',self.cell_edited_callback)
328 i = i + 1
329
330
331 if(len(args)==1):
332 self.do_open(args[0])
333
334 print "Options: ",options
335
336 if options.model:
337 try:
338 _t =self.library.findType(options.model);
339 self.do_sim(_t);
340 except RuntimeError, e:
341 self.reporter.reportError("Failed to create instance of '%s': %s" %(options.model, str(e)));
342
343
344 def run(self):
345 self.window.show()
346 gtk.main()
347
348 # --------------------------------------------
349 # MAJOR GUI COMMANDS
350
351
352 def do_open(self,filename):
353 # TODO does the user want to lose their work?
354 # TODO do we need to chdir?
355
356 _context = self.statusbar.get_context_id("do_open")
357
358 self.errorstore.clear()
359
360 self.treestore.clear()
361 self.otank = {}
362
363 # self.library.clear()
364
365 self.statusbar.push(_context,"Loading '"+filename+"'")
366 self.library.load(filename)
367 self.statusbar.pop(_context)
368
369 self.filename = filename
370
371 # Load the current list of modules into self.modules
372 self.modtank = {}
373 self.modulestore.clear()
374 modules = self.library.getModules()
375 for m in reversed(modules):
376 _n = str( m.getName() )
377 _f = str( m.getFilename() )
378 #print "ADDING ROW name %s, file = %s" % (_n, _f)
379 _r = self.modulestore.append(None, [ _n, _f ])
380 for t in self.library.getModuleTypes(m):
381 _n = t.getName()
382 #print "ADDING TYPE %s" % _n
383 _piter = self.modulestore.append(_r , [ _n, "" ])
384 _path = self.modulestore.get_path(_piter)
385 self.modtank[_path]=t
386
387 #print "DONE ADDING MODULES"
388
389 self.sim = None;
390 self.maintabs.set_current_page(0);
391
392 # See http://www.daa.com.au/pipermail/pygtk/2005-October/011303.html
393 # for details on how the 'wait cursor' is done.
394 def start_waiting(self, message):
395 self.waitcontext = self.statusbar.get_context_id("waiting")
396 self.statusbar.push(self.waitcontext,message)
397
398 if self.waitwin:
399 self.waitwin.show()
400
401 while gtk.events_pending():
402 gtk.main_iteration()
403
404 def stop_waiting(self):
405 if self.waitwin:
406 self.statusbar.pop(self.waitcontext)
407 self.waitwin.hide()
408
409 def do_sim(self, type_object):
410 self.sim = None;
411 # TODO: clear out old simulation first!
412
413 print "DO_SIM(%s)" % str(type_object.getName())
414 self.start_waiting("Compiling...")
415
416 self.sim = type_object.getSimulation(str(type_object.getName())+"_sim")
417 print "...DONE 'getSimulation'"
418 self.stop_waiting()
419
420 self.start_waiting("Building simulation...")
421 print "BUILDING SIMULATION"
422 self.sim.build()
423 print "DONE BUILDING"
424 self.stop_waiting()
425
426 self.sim.setSolver(ascend.Solver("QRSlv"))
427
428 # empty things out first
429 self.methodstore.clear()
430 self.treestore.clear()
431
432 # methods
433 _methods = self.sim.getType().getMethods()
434 _activemethod = None;
435 for _m in _methods:
436 _i = self.methodstore.append([_m.getName()])
437 if _m.getName()=="default_self":
438 self.methodsel.set_active_iter(_i)
439
440 # instance hierarchy
441 self.otank = {} # map path -> (name,value)
442 self.make( self.sim.getName(),self.sim.getModel() )
443 self.maintabs.set_current_page(1);
444
445 def do_solve_if_auto(self):
446 if self.is_auto:
447 self.sim.check()
448 self.do_solve()
449 else:
450 self.sim.processVarStatus()
451 self.refreshtree()
452
453 self.sync_observers()
454
455 def do_solve(self):
456 if not self.sim:
457 self.reporter.reportError("No model selected yet")
458 return;
459
460 self.start_waiting("Solving...")
461
462 self.sim.solve(ascend.Solver("QRSlv"))
463
464 self.stop_waiting()
465
466 self.sim.processVarStatus()
467 self.refreshtree()
468
469 def do_check(self):
470 if not self.sim:
471 self.reporter.reportError("No model selected yet")
472
473 self.start_waiting("Checking system...")
474
475 if self.sim.check():
476 self.reporter.reportNote("System check OK")
477
478 self.sim.checkDoF()
479
480 self.stop_waiting()
481
482 self.refreshtree()
483
484 def do_method(self,method):
485 if not self.sim:
486 self.reporter.reportError("No model selected yet")
487
488 self.sim.run(method)
489 self.refreshtree()
490
491 def do_quit(self):
492 self.reporter.clearPythonErrorCallback()
493 _w,_h = self.window.get_size()
494 _t,_l = self.window.get_position()
495 _display = self.window.get_screen().get_display().get_name()
496 self.prefs.setGeometrySizePosition(_display,"browserwin",_w,_h,_t,_l );
497
498 _p = self.browserpaned.get_position()
499 self.prefs.setGeometryValue(_display,"browserpaned",_p);
500
501 # causes prefs to be saved unless they are still being used elsewher
502 del(self.prefs)
503
504 gtk.main_quit()
505 print "GTK QUIT"
506 return False
507
508 def on_tools_sparsity_click(self,*args):
509
510 self.reporter.reportNote("Preparing incidence matrix...")
511 _im = self.sim.getIncidenceMatrix();
512
513 self.reporter.reportNote("Plotting incidence matrix...")
514
515 _sp = IncidenceMatrixWindow(_im);
516 _sp.run();
517
518 def on_add_observer_click(self,*args):
519 if len(self.observers) >= 1:
520 self.reporter.reportError("Not supported: multiple observers")
521 return
522 self.observers.append(self.create_observer())
523
524 def on_keep_observed_click(self,*args):
525 if len(self.observers) > 1:
526 self.reporter.reportError("Not supported: multiple observers")
527 return
528 if len(self.observers) <= 0:
529 self.reporter.reportError("No observer defined!")
530 return
531 self.observers[0].do_add_row()
532
533 def on_copy_observer_matrix_click(self,*args):
534 if self.clip == None:
535 self.clip = gtk.Clipboard()
536
537 if len(self.observers) > 1:
538 self.reporter.reportError("Not supported: multiple observers")
539 return
540 if len(self.observers) <= 0:
541 self.reporter.reportError("No observer defined!")
542 return
543 self.observers[0].copy_to_clipboard(self.clip)
544
545 # --------------------------------------------
546 # MODULE LIST
547
548 def module_activated(self, treeview, path, column, *args):
549 modules = self.library.getModules()
550 print "PATH",path
551 if len(path)==1:
552 self.reporter.reportNote("Launching of external editor not yet implemented")
553 elif len(path)==2:
554 if(self.modtank.has_key(path)):
555 _type = self.modtank[path];
556 self.reporter.reportNote("Creating simulation for type %s" % str(_type.getName()) )
557 self.do_sim(_type)
558 else:
559 self.reporter.reportError("Didn't find type corresponding to row")
560
561 # --------------------------------------------
562 # INSTANCE TREE
563
564 def get_tree_row_data(self,instance): # for instance browser
565 _value = str(instance.getValue())
566 _type = str(instance.getType())
567 _name = str(instance.getName())
568 _fgcolor = "black"
569 _fontweight = pango.WEIGHT_NORMAL
570 _editable = False
571 if instance.getType().isRefinedSolverVar():
572 _editable = True
573 _fontweight = pango.WEIGHT_BOLD
574 if instance.isFixed():
575 _fgcolor = BROWSER_FIXED_COLOR
576 else:
577 _fgcolor = BROWSER_FREE_COLOR
578 _fontweight = pango.WEIGHT_BOLD
579 elif instance.isBool() or instance.isReal() or instance.isInt():
580 # TODO can't edit constants that have already been refined
581 _editable = True
582 _status = instance.getVarStatus();
583
584 _statusicon = self.statusicons[_status]
585
586 #if(len(_value) > 80):
587 # _value = _value[:80] + "..."
588
589 return [_name, _type, _value, _fgcolor, _fontweight, _editable, _statusicon]
590
591 def make_row( self, piter, name, value ): # for instance browser
592
593 _piter = self.treestore.append( piter, self.get_tree_row_data(value) )
594 return _piter
595
596 def refreshtree(self):
597 # @TODO FIXME use a better system than colour literals!
598 for _path in self.otank: # { path : (name,value) }
599 _iter = self.treestore.get_iter(_path)
600 _name, _instance = self.otank[_path]
601 self.treestore.set_value(_iter, 2, _instance.getValue())
602 if _instance.getType().isRefinedSolverVar():
603 if _instance.isFixed() and self.treestore.get_value(_iter,3)==BROWSER_FREE_COLOR:
604 self.treestore.set_value(_iter,3,BROWSER_FIXED_COLOR)
605 elif not _instance.isFixed() and self.treestore.get_value(_iter,3)==BROWSER_FIXED_COLOR:
606 self.treestore.set_value(_iter,3,BROWSER_FREE_COLOR)
607 self.treestore.set_value(_iter, 6, self.statusicons[_instance.getVarStatus()])
608
609 def cell_edited_callback(self, renderer, path, newtext, **kwargs):
610 # get back the Instance object we just edited (having to use this seems like a bug)
611 path = tuple( map(int,path.split(":")) )
612
613 if not self.otank.has_key(path):
614 raise RuntimeError("cell_edited_callback: invalid path '%s'" % path)
615 return
616
617 _name, _instance = self.otank[path]
618
619 if _instance.isReal():
620 # only real-valued things can have units
621
622 _e = RealAtomEntry(_instance,newtext);
623 try:
624 _e.checkEntry()
625 _e.setValue()
626 _e.exportPreferredUnits(self.prefs)
627 except InputError, e:
628 self.reporter.reportError(str(e))
629 return;
630
631 else:
632 if _instance.isBool():
633 _lower = newtext.lower();
634 if _lower.startswith("t") or _lower.startswith("y") or _lower.strip()=="1":
635 newtext = 1
636 elif _lower.startswith("f") or _lower.startswith("n") or _lower.strip()=="0":
637 newtext = 0
638 else:
639 self.reporter.reportError("Invalid entry for a boolean variable: '%s'" % newtext)
640 return
641 _val = bool(newtext);
642 if _val == _instance.getValue():
643 self.reporter.reportNote("Boolean atom '%s' was not altered" % _instance.getName())
644 return
645 _instance.setBoolValue(_val)
646
647 elif _instance.isInt():
648 _val = int(newtext)
649 if _val == _instance.getValue():
650 self.reporter.reportNote("Integer atom '%s' was not altered" % _instance.getName())
651 return
652 _instance.setIntValue(_val)
653 else:
654 self.reporter.reportError("Attempt to set a non-real, non-boolean, non-integer value!")
655 return
656
657 # now that the variable is set, update the GUI and re-solve if desired
658 _iter = self.treestore.get_iter(path)
659 self.treestore.set_value(_iter,2,_instance.getValue())
660
661 if _instance.getType().isRefinedSolverVar():
662 self.treestore.set_value(_iter,3,BROWSER_FIXED_COLOR) # set the row green as fixed
663
664 self.do_solve_if_auto()
665
666 def make_children(self, value, piter ):
667 if value.isCompound():
668 children=value.getChildren();
669 for child in children:
670 _name = child.getName();
671 _piter = self.make_row(piter,_name,child)
672 _path = self.treestore.get_path(_piter)
673 self.otank[_path]=(_name,child)
674 #self.reporter.reportError("2 Added %s at path %s" % (_name,repr(_path)))
675
676 def make(self, name=None, value=None, path=None, depth=1):
677 if path is None:
678 # make root node
679 piter = self.make_row( None, name, value )
680 path = self.treestore.get_path( piter )
681 self.otank[ path ] = (name, value)
682 #self.reporter.reportError("4 Added %s at path %s" % (name, path))
683 else:
684 name, value = self.otank[ path ]
685
686 piter = self.treestore.get_iter( path )
687 if not self.treestore.iter_has_child( piter ):
688 self.make_children(value,piter)
689
690 if depth:
691 for i in range( self.treestore.iter_n_children( piter ) ):
692 self.make( path = path+(i,), depth = depth - 1 )
693 else:
694 self.treeview.expand_row("0",False)
695
696 def row_expanded( self, treeview, piter, path ):
697 self.make( path = path )
698
699 # ----------------------------------
700 # ERROR PANEL
701
702 def get_error_row_data(self,sev,filename,line,msg):
703 _sevicon = {
704 0: self.iconok
705 ,1: self.iconinfo
706 ,2: self.iconwarning
707 ,3: self.iconerror
708 ,4: self.iconinfo
709 ,5: self.iconwarning
710 ,6: self.iconerror
711 }[sev]
712
713 _fontweight = pango.WEIGHT_NORMAL
714 if sev==6:
715 _fontweight = pango.WEIGHT_BOLD
716
717 _fgcolor = "black"
718 if sev==4:
719 _fgcolor = "#888800"
720 elif sev==5:
721 _fgcolor = "#884400"
722 elif sev==6:
723 _fgcolor = "#880000"
724 elif sev==0:
725 _fgcolor = BROWSER_FIXED_COLOR
726
727 if not filename and not line:
728 _fileline = ""
729 else:
730 if(len(filename) > 25):
731 filename = "..."+filename[-22:]
732 _fileline = filename + ":" + str(line)
733
734 _res = [_sevicon,_fileline,msg.rstrip(),_fgcolor,_fontweight]
735 #print _res
736 return _res
737
738 def error_callback(self,sev,filename,line,msg):
739 pos = self.errorstore.append(None, self.get_error_row_data(sev, filename,line,msg))
740 path = self.errorstore.get_path(pos)
741 col = self.errorview.get_column(3)
742 self.errorview.scroll_to_cell(path,col)
743
744 return 0;
745
746 # --------------------------------
747 # BUTTON METHODS
748
749 def open_click(self,*args):
750 dialog = gtk.FileChooserDialog("Open file...",
751 None,
752 gtk.FILE_CHOOSER_ACTION_OPEN,
753 (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
754 gtk.STOCK_OPEN, gtk.RESPONSE_OK))
755 dialog.set_default_response(gtk.RESPONSE_OK)
756
757 filter = gtk.FileFilter()
758 filter.set_name("*.a4c, *.a4l")
759 filter.add_pattern("*.[Aa]4[Cc]")
760 filter.add_pattern("*.[Aa]4[Ll]")
761 dialog.add_filter(filter)
762
763 filter = gtk.FileFilter()
764 filter.set_name("All files")
765 filter.add_pattern("*")
766 dialog.add_filter(filter)
767
768 response = dialog.run()
769 _filename = dialog.get_filename()
770 dialog.destroy()
771
772 if response == gtk.RESPONSE_OK:
773 self.reporter.reportNote("File %s selected." % dialog.get_filename() )
774 self.library.clear()
775 self.do_open( _filename)
776
777
778 def reload_click(self,*args):
779 _type = None
780 if(self.sim):
781 _type = self.sim.getType().getName().toString();
782
783 self.library.clear()
784 self.do_open(self.filename)
785
786 if _type:
787 _t = self.library.findType(_type)
788 self.do_sim(_t)
789
790 def solve_click(self,*args):
791 #self.reporter.reportError("Solving simulation '" + self.sim.getName().toString() +"'...")
792 self.do_solve()
793
794 def check_click(self,*args):
795 self.do_check()
796 #self.reporter.reportError("CHECK clicked")
797
798 def preferences_click(self,*args):
799 if not self.sim:
800 self.reporter.reportError("No simulation created yet!");
801
802 _paramswin = SolverParametersWindow(self.sim, self.reporter, GLADE_FILE)
803 _paramswin.show()
804
805 def methodrun_click(self,*args):
806 _sel = self.methodsel.get_active_text()
807 if _sel:
808 _method = None
809 _methods = self.sim.getType().getMethods()
810 for _m in _methods:
811 if _m.getName()==_sel:
812 _method = _m
813 if not _method:
814 self.reporter.reportError("Method is not valid")
815 return
816 self.do_method(_method)
817 else:
818 self.reporter.reportError("No method selected")
819
820 def auto_toggle(self,button,*args):
821 self.is_auto = button.get_active()
822 self.automenu.set_active(self.is_auto)
823
824 if self.is_auto:
825 self.reporter.reportSuccess("Auto mode is now ON")
826 else:
827 self.reporter.reportSuccess("Auto mode is now OFF")
828
829 def on_file_quit_click(self,*args):
830 self.do_quit()
831
832 def on_tools_auto_toggle(self,checkmenuitem,*args):
833 self.is_auto = checkmenuitem.get_active()
834 self.autotoggle.set_active(self.is_auto)
835
836 def on_help_about_click(self,*args):
837 _xml = gtk.glade.XML(GLADE_FILE,"aboutdialog");
838 _dialog = _xml.get_widget("aboutdialog")
839 _dialog.run()
840 _dialog.destroy()
841
842 def on_help_contents_click(self,*args):
843 _help = Help(HELP_ROOT)
844 _help.run()
845
846 def create_observer(self,name=None):
847 if name==None:
848 name="New Observer"
849
850 _xml = gtk.glade.XML(GLADE_FILE,"observervbox");
851 _label = gtk.Label();
852 _label.set_text(name)
853 _tab = self.maintabs.append_page(_xml.get_widget("observervbox"),_label);
854 self.observers.append(ObserverTab(_xml, name, self, _tab))
855
856 def sync_observers(self):
857 for _o in self.observers:
858 _o.sync()
859
860 # ------------------------------
861 # CONTEXT MENU
862
863 def on_treeview_event(self,widget,event):
864 _contextmenu = False;
865 if event.type==gtk.gdk.KEY_PRESS and gtk.gdk.keyval_name(event.keyval)=='Menu':
866 _contextmenu = True
867 _path, _col = self.treeview.get_cursor()
868 _button = 3;
869 elif event.type==gtk.gdk.BUTTON_PRESS:
870 if event.button == 3:
871 _contextmenu = True
872 _x = int(event.x)
873 _y = int(event.y)
874 _button = event.button
875 _pthinfo = self.treeview.get_path_at_pos(_x, _y)
876 if _pthinfo == None:
877 return
878 _path, _col, _cellx, _celly = _pthinfo
879
880 # which button was clicked?
881 if not _contextmenu:
882 return
883
884 _canpop = False;
885 # self.reporter.reportError("Right click on %s" % self.otank[_path][0])
886 _instance = self.otank[_path][1]
887 if _instance.getType().isRefinedSolverVar():
888 _canpop = True;
889 self.observemenuitem.set_sensitive(True)
890 if _instance.isFixed():
891 self.fixmenuitem.set_sensitive(False)
892 self.freemenuitem.set_sensitive(True)
893 else:
894 self.fixmenuitem.set_sensitive(True)
895 self.freemenuitem.set_sensitive(False)
896 elif _instance.isRelation():
897 _canpop = True;
898 self.propsmenuitem.set_sensitive(True)
899
900 if _instance.isPlottable():
901 self.plotmenuitem.set_sensitive(True)
902 _canpop = True;
903 else:
904 self.plotmenuitem.set_sensitive(False)
905
906 if not _canpop:
907 return
908
909 self.treeview.grab_focus()
910 self.treeview.set_cursor( _path, _col, 0)
911 self.treecontext.popup( None, None, None, _button, event.time)
912 return 1
913
914 def fix_activate(self,widget):
915 _path,_col = self.treeview.get_cursor()
916 _name, _instance = self.otank[_path]
917 _instance.setFixed(True)
918 self.reporter.reportNote("Fixed variable %s" % _instance.getName().toString())
919 self.do_solve_if_auto()
920 return 1
921
922 def free_activate(self,widget):
923 _path,_col = self.treeview.get_cursor()
924 _instance = self.otank[_path][1]
925 _instance.setFixed(False)
926 self.reporter.reportNote("Freed variable %s" % _instance.getName().toString())
927 self.do_solve_if_auto()
928 return 1
929
930 def plot_activate(self,widget):
931 self.reporter.reportNote("plot_activate...");
932 _path,_col = self.treeview.get_cursor()
933 _instance = self.otank[_path][1]
934 if not _instance.isPlottable():
935 self.reporter.reportError("Can't plot instance %s" % _instance.getName().toString())
936 return
937 else:
938 self.reporter.reportNote("Instance %s about to be plotted..." % _instance.getName().toString())
939
940 print("Plotting instance '%s'..." % _instance.getName().toString())
941
942 _plot = _instance.getPlot()
943
944 print "Title: ", _plot.getTitle()
945 _plot.show(True)
946
947 return 1
948
949 def props_activate(self,widget):
950 _path,_col = self.treeview.get_cursor()
951 _instance = self.otank[_path][1]
952 if _instance.isRelation():
953 print "Relation '"+_instance.getName().toString()+"':", \
954 _instance.getRelationAsString(self.sim.getModel())
955 elif _instance.getType().isRefinedSolverVar():
956 _dia = VarPropsWin(GLADE_FILE,self,_instance);
957 _dia.run();
958 else:
959 self.reporter.reportWarning("Select a variable first...")
960
961 def observe_activate(self,widget):
962 _path,_col = self.treeview.get_cursor()
963 _instance = self.otank[_path][1]
964 if _instance.getType().isRefinedSolverVar():
965 print "OBSERVING",_instance.getName().toString()
966 if len(self.observers) > 1:
967 self.reporter.reportError("Not implemented: multiple observers")
968 return
969 if len(self.observers) ==0:
970 self.create_observer()
971 _observer = self.observers[0]
972 _observer.add_instance(_instance)
973
974 def delete_event(self, widget, event):
975 self.do_quit()
976 return False
977
978 def test():
979 import ascend
980 b = Browser();
981 b.run()
982
983 if __name__ == "__main__":
984 test()

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