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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

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