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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 268 - (show annotations) (download) (as text)
Sat Feb 4 06:09:57 2006 UTC (14 years, 9 months ago) by johnpye
File MIME type: text/x-python
File size: 28806 byte(s)
Adding ability to edit upper/lower bounds and nominal values
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.tree_click )
305
306 # data columns are: name type value colour weight editable
307
308 i = 0
309 for tvcolumn in self.tvcolumns[:len(titles)]:
310 tvcolumn.set_title(titles[i])
311 self.treeview.append_column(tvcolumn)
312
313 if(i==2):
314 # add status icon
315 renderer1 = gtk.CellRendererPixbuf()
316 tvcolumn.pack_start(renderer1, False)
317 tvcolumn.add_attribute(renderer1, 'pixbuf', 6)
318
319 renderer = gtk.CellRendererText()
320 tvcolumn.pack_start(renderer, True)
321 tvcolumn.add_attribute(renderer, 'text', i)
322 tvcolumn.add_attribute(renderer, 'foreground', 3)
323 tvcolumn.add_attribute(renderer, 'weight', 4)
324 if(i==2):
325 tvcolumn.add_attribute(renderer, 'editable', 5)
326 renderer.connect('edited',self.cell_edited_callback)
327 i = i + 1
328
329
330 if(len(args)==1):
331 self.do_open(args[0])
332
333 print "Options: ",options
334
335 if options.model:
336 try:
337 _t =self.library.findType(options.model);
338 self.do_sim(_t);
339 except RuntimeError, e:
340 self.reporter.reportError("Failed to create instance of '%s': %s" %(options.model, str(e)));
341
342
343 def run(self):
344 self.window.show()
345 gtk.main()
346
347 # --------------------------------------------
348 # MAJOR GUI COMMANDS
349
350
351 def do_open(self,filename):
352 # TODO does the user want to lose their work?
353 # TODO do we need to chdir?
354
355 _context = self.statusbar.get_context_id("do_open")
356
357 self.errorstore.clear()
358
359 self.treestore.clear()
360 self.otank = {}
361
362 # self.library.clear()
363
364 self.statusbar.push(_context,"Loading '"+filename+"'")
365 self.library.load(filename)
366 self.statusbar.pop(_context)
367
368 self.filename = filename
369
370 # Load the current list of modules into self.modules
371 self.modtank = {}
372 self.modulestore.clear()
373 modules = self.library.getModules()
374 for m in reversed(modules):
375 _n = str( m.getName() )
376 _f = str( m.getFilename() )
377 #print "ADDING ROW name %s, file = %s" % (_n, _f)
378 _r = self.modulestore.append(None, [ _n, _f ])
379 for t in self.library.getModuleTypes(m):
380 _n = t.getName()
381 #print "ADDING TYPE %s" % _n
382 _piter = self.modulestore.append(_r , [ _n, "" ])
383 _path = self.modulestore.get_path(_piter)
384 self.modtank[_path]=t
385
386 #print "DONE ADDING MODULES"
387
388 self.sim = None;
389 self.maintabs.set_current_page(0);
390
391 # See http://www.daa.com.au/pipermail/pygtk/2005-October/011303.html
392 # for details on how the 'wait cursor' is done.
393 def start_waiting(self, message):
394 self.waitcontext = self.statusbar.get_context_id("waiting")
395 self.statusbar.push(self.waitcontext,message)
396
397 if self.waitwin:
398 self.waitwin.show()
399
400 while gtk.events_pending():
401 gtk.main_iteration()
402
403 def stop_waiting(self):
404 if self.waitwin:
405 self.statusbar.pop(self.waitcontext)
406 self.waitwin.hide()
407
408 def do_sim(self, type_object):
409 self.sim = None;
410 # TODO: clear out old simulation first!
411
412 print "DO_SIM(%s)" % str(type_object.getName())
413 self.start_waiting("Compiling...")
414
415 self.sim = type_object.getSimulation(str(type_object.getName())+"_sim")
416 print "...DONE 'getSimulation'"
417 self.stop_waiting()
418
419 self.start_waiting("Building simulation...")
420 print "BUILDING SIMULATION"
421 self.sim.build()
422 print "DONE BUILDING"
423 self.stop_waiting()
424
425 self.sim.setSolver(ascend.Solver("QRSlv"))
426
427 # empty things out first
428 self.methodstore.clear()
429 self.treestore.clear()
430
431 # methods
432 _methods = self.sim.getType().getMethods()
433 _activemethod = None;
434 for _m in _methods:
435 _i = self.methodstore.append([_m.getName()])
436 if _m.getName()=="default_self":
437 self.methodsel.set_active_iter(_i)
438
439 # instance hierarchy
440 self.otank = {} # map path -> (name,value)
441 self.make( self.sim.getName(),self.sim.getModel() )
442 self.maintabs.set_current_page(1);
443
444 def do_solve_if_auto(self):
445 if self.is_auto:
446 self.sim.check()
447 self.do_solve()
448 else:
449 self.sim.processVarStatus()
450 self.refreshtree()
451
452 self.sync_observers()
453
454 def do_solve(self):
455 if not self.sim:
456 self.reporter.reportError("No model selected yet")
457 return;
458
459 self.start_waiting("Solving...")
460
461 self.sim.solve(ascend.Solver("QRSlv"))
462
463 self.stop_waiting()
464
465 self.sim.processVarStatus()
466 self.refreshtree()
467
468 def do_check(self):
469 if not self.sim:
470 self.reporter.reportError("No model selected yet")
471
472 self.start_waiting("Checking system...")
473
474 if self.sim.check():
475 self.reporter.reportNote("System check OK")
476
477 self.sim.checkDoF()
478
479 self.stop_waiting()
480
481 self.refreshtree()
482
483 def do_method(self,method):
484 if not self.sim:
485 self.reporter.reportError("No model selected yet")
486
487 self.sim.run(method)
488 self.refreshtree()
489
490 def do_quit(self):
491 self.reporter.clearPythonErrorCallback()
492 _w,_h = self.window.get_size()
493 _t,_l = self.window.get_position()
494 _display = self.window.get_screen().get_display().get_name()
495 self.prefs.setGeometrySizePosition(_display,"browserwin",_w,_h,_t,_l );
496
497 _p = self.browserpaned.get_position()
498 self.prefs.setGeometryValue(_display,"browserpaned",_p);
499
500 # causes prefs to be saved unless they are still being used elsewher
501 del(self.prefs)
502
503 gtk.main_quit()
504 print "GTK QUIT"
505 return False
506
507 def on_tools_sparsity_click(self,*args):
508
509 self.reporter.reportNote("Preparing incidence matrix...")
510 _im = self.sim.getIncidenceMatrix();
511
512 self.reporter.reportNote("Plotting incidence matrix...")
513
514 _sp = IncidenceMatrixWindow(_im);
515 _sp.run();
516
517 def on_add_observer_click(self,*args):
518 if len(self.observers) >= 1:
519 self.reporter.reportError("Not supported: multiple observers")
520 return
521 self.observers.append(self.create_observer())
522
523 def on_keep_observed_click(self,*args):
524 if len(self.observers) > 1:
525 self.reporter.reportError("Not supported: multiple observers")
526 return
527 if len(self.observers) <= 0:
528 self.reporter.reportError("No observer defined!")
529 return
530 self.observers[0].do_add_row()
531
532 def on_copy_observer_matrix_click(self,*args):
533 if self.clip == None:
534 self.clip = gtk.Clipboard()
535
536 if len(self.observers) > 1:
537 self.reporter.reportError("Not supported: multiple observers")
538 return
539 if len(self.observers) <= 0:
540 self.reporter.reportError("No observer defined!")
541 return
542 self.observers[0].copy_to_clipboard(self.clip)
543 # --------------------------------------------
544 # MODULE LIST
545
546 def module_activated(self, treeview, path, column, *args):
547 modules = self.library.getModules()
548 print "PATH",path
549 if len(path)==1:
550 self.reporter.reportNote("Launching of external editor not yet implemented")
551 elif len(path)==2:
552 if(self.modtank.has_key(path)):
553 _type = self.modtank[path];
554 self.reporter.reportNote("Creating simulation for type %s" % str(_type.getName()) )
555 self.do_sim(_type)
556 else:
557 self.reporter.reportError("Didn't find type corresponding to row")
558
559 # --------------------------------------------
560 # INSTANCE TREE
561
562 def get_tree_row_data(self,instance): # for instance browser
563 _value = str(instance.getValue())
564 _type = str(instance.getType())
565 _name = str(instance.getName())
566 _fgcolor = "black"
567 _fontweight = pango.WEIGHT_NORMAL
568 _editable = False
569 if instance.getType().isRefinedSolverVar():
570 _editable = True
571 _fontweight = pango.WEIGHT_BOLD
572 if instance.isFixed():
573 _fgcolor = BROWSER_FIXED_COLOR
574 else:
575 _fgcolor = BROWSER_FREE_COLOR
576 _fontweight = pango.WEIGHT_BOLD
577 elif instance.isBool() or instance.isReal() or instance.isInt():
578 # TODO can't edit constants that have already been refined
579 _editable = True
580 _status = instance.getVarStatus();
581
582 _statusicon = self.statusicons[_status]
583
584 #if(len(_value) > 80):
585 # _value = _value[:80] + "..."
586
587 return [_name, _type, _value, _fgcolor, _fontweight, _editable, _statusicon]
588
589 def make_row( self, piter, name, value ): # for instance browser
590
591 _piter = self.treestore.append( piter, self.get_tree_row_data(value) )
592 return _piter
593
594 def refreshtree(self):
595 # @TODO FIXME use a better system than colour literals!
596 for _path in self.otank: # { path : (name,value) }
597 _iter = self.treestore.get_iter(_path)
598 _name, _instance = self.otank[_path]
599 self.treestore.set_value(_iter, 2, _instance.getValue())
600 if _instance.getType().isRefinedSolverVar():
601 if _instance.isFixed() and self.treestore.get_value(_iter,3)==BROWSER_FREE_COLOR:
602 self.treestore.set_value(_iter,3,BROWSER_FIXED_COLOR)
603 elif not _instance.isFixed() and self.treestore.get_value(_iter,3)==BROWSER_FIXED_COLOR:
604 self.treestore.set_value(_iter,3,BROWSER_FREE_COLOR)
605 self.treestore.set_value(_iter, 6, self.statusicons[_instance.getVarStatus()])
606
607 def cell_edited_callback(self, renderer, path, newtext, **kwargs):
608 # get back the Instance object we just edited (having to use this seems like a bug)
609 path = tuple( map(int,path.split(":")) )
610
611 if not self.otank.has_key(path):
612 raise RuntimeError("cell_edited_callback: invalid path '%s'" % path)
613 return
614
615 _name, _instance = self.otank[path]
616
617 if _instance.isReal():
618 # only real-valued things can have units
619
620 _e = RealAtomEntry(_instance,newtext);
621 try:
622 _e.checkEntry()
623 _e.setValue()
624 _e.exportPreferredUnits(self.prefs)
625 except InputError, e:
626 self.reporter.reportError(str(e))
627 return;
628
629 else:
630 if _instance.isBool():
631 _lower = newtext.lower();
632 if _lower.startswith("t") or _lower.startswith("y") or _lower.strip()=="1":
633 newtext = 1
634 elif _lower.startswith("f") or _lower.startswith("n") or _lower.strip()=="0":
635 newtext = 0
636 else:
637 self.reporter.reportError("Invalid entry for a boolean variable: '%s'" % newtext)
638 return
639 _val = bool(newtext);
640 if _val == _instance.getValue():
641 self.reporter.reportNote("Boolean atom '%s' was not altered" % _instance.getName())
642 return
643 _instance.setBoolValue(_val)
644
645 elif _instance.isInt():
646 _val = int(newtext)
647 if _val == _instance.getValue():
648 self.reporter.reportNote("Integer atom '%s' was not altered" % _instance.getName())
649 return
650 _instance.setIntValue(_val)
651 else:
652 self.reporter.reportError("Attempt to set a non-real, non-boolean, non-integer value!")
653 return
654
655 # now that the variable is set, update the GUI and re-solve if desired
656 _iter = self.treestore.get_iter(path)
657 self.treestore.set_value(_iter,2,_instance.getValue())
658
659 if _instance.getType().isRefinedSolverVar():
660 self.treestore.set_value(_iter,3,BROWSER_FIXED_COLOR) # set the row green as fixed
661
662 self.do_solve_if_auto()
663
664 def make_children(self, value, piter ):
665 if value.isCompound():
666 children=value.getChildren();
667 for child in children:
668 _name = child.getName();
669 _piter = self.make_row(piter,_name,child)
670 _path = self.treestore.get_path(_piter)
671 self.otank[_path]=(_name,child)
672 #self.reporter.reportError("2 Added %s at path %s" % (_name,repr(_path)))
673
674 def make(self, name=None, value=None, path=None, depth=1):
675 if path is None:
676 # make root node
677 piter = self.make_row( None, name, value )
678 path = self.treestore.get_path( piter )
679 self.otank[ path ] = (name, value)
680 #self.reporter.reportError("4 Added %s at path %s" % (name, path))
681 else:
682 name, value = self.otank[ path ]
683
684 piter = self.treestore.get_iter( path )
685 if not self.treestore.iter_has_child( piter ):
686 self.make_children(value,piter)
687
688 if depth:
689 for i in range( self.treestore.iter_n_children( piter ) ):
690 self.make( path = path+(i,), depth = depth - 1 )
691 else:
692 self.treeview.expand_row("0",False)
693
694 def row_expanded( self, treeview, piter, path ):
695 self.make( path = path )
696
697 # ----------------------------------
698 # ERROR PANEL
699
700 def get_error_row_data(self,sev,filename,line,msg):
701 _sevicon = {
702 0: self.iconok
703 ,1: self.iconinfo
704 ,2: self.iconwarning
705 ,3: self.iconerror
706 ,4: self.iconinfo
707 ,5: self.iconwarning
708 ,6: self.iconerror
709 }[sev]
710
711 _fontweight = pango.WEIGHT_NORMAL
712 if sev==6:
713 _fontweight = pango.WEIGHT_BOLD
714
715 _fgcolor = "black"
716 if sev==4:
717 _fgcolor = "#888800"
718 elif sev==5:
719 _fgcolor = "#884400"
720 elif sev==6:
721 _fgcolor = "#880000"
722 elif sev==0:
723 _fgcolor = BROWSER_FIXED_COLOR
724
725 if not filename and not line:
726 _fileline = ""
727 else:
728 if(len(filename) > 25):
729 filename = "..."+filename[-22:]
730 _fileline = filename + ":" + str(line)
731
732 _res = [_sevicon,_fileline,msg.rstrip(),_fgcolor,_fontweight]
733 #print _res
734 return _res
735
736 def error_callback(self,sev,filename,line,msg):
737 pos = self.errorstore.append(None, self.get_error_row_data(sev, filename,line,msg))
738 path = self.errorstore.get_path(pos)
739 col = self.errorview.get_column(3)
740 self.errorview.scroll_to_cell(path,col)
741
742 return 0;
743
744 # --------------------------------
745 # BUTTON METHODS
746
747 def open_click(self,*args):
748 dialog = gtk.FileChooserDialog("Open file...",
749 None,
750 gtk.FILE_CHOOSER_ACTION_OPEN,
751 (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
752 gtk.STOCK_OPEN, gtk.RESPONSE_OK))
753 dialog.set_default_response(gtk.RESPONSE_OK)
754
755 filter = gtk.FileFilter()
756 filter.set_name("*.a4c, *.a4l")
757 filter.add_pattern("*.[Aa]4[Cc]")
758 filter.add_pattern("*.[Aa]4[Ll]")
759 dialog.add_filter(filter)
760
761 filter = gtk.FileFilter()
762 filter.set_name("All files")
763 filter.add_pattern("*")
764 dialog.add_filter(filter)
765
766 response = dialog.run()
767 _filename = dialog.get_filename()
768 dialog.destroy()
769
770 if response == gtk.RESPONSE_OK:
771 self.reporter.reportNote("File %s selected." % dialog.get_filename() )
772 self.library.clear()
773 self.do_open( _filename)
774
775
776 def reload_click(self,*args):
777 _type = None
778 if(self.sim):
779 _type = self.sim.getType().getName().toString();
780
781 self.library.clear()
782 self.do_open(self.filename)
783
784 if _type:
785 _t = self.library.findType(_type)
786 self.do_sim(_t)
787
788 def solve_click(self,*args):
789 #self.reporter.reportError("Solving simulation '" + self.sim.getName().toString() +"'...")
790 self.do_solve()
791
792 def check_click(self,*args):
793 self.do_check()
794 #self.reporter.reportError("CHECK clicked")
795
796 def preferences_click(self,*args):
797 if not self.sim:
798 self.reporter.reportError("No simulation created yet!");
799
800 _paramswin = SolverParametersWindow(self.sim, self.reporter, GLADE_FILE)
801 _paramswin.show()
802
803 def methodrun_click(self,*args):
804 _sel = self.methodsel.get_active_text()
805 if _sel:
806 _method = None
807 _methods = self.sim.getType().getMethods()
808 for _m in _methods:
809 if _m.getName()==_sel:
810 _method = _m
811 if not _method:
812 self.reporter.reportError("Method is not valid")
813 return
814 self.do_method(_method)
815 else:
816 self.reporter.reportError("No method selected")
817
818 def auto_toggle(self,button,*args):
819 self.is_auto = button.get_active()
820 self.automenu.set_active(self.is_auto)
821
822 if self.is_auto:
823 self.reporter.reportSuccess("Auto mode is now ON")
824 else:
825 self.reporter.reportSuccess("Auto mode is now OFF")
826
827 def on_file_quit_click(self,*args):
828 self.do_quit()
829
830 def on_tools_auto_toggle(self,checkmenuitem,*args):
831 self.is_auto = checkmenuitem.get_active()
832 self.autotoggle.set_active(self.is_auto)
833
834 def on_help_about_click(self,*args):
835 _xml = gtk.glade.XML(GLADE_FILE,"aboutdialog");
836 _dialog = _xml.get_widget("aboutdialog")
837 _dialog.run()
838 _dialog.destroy()
839
840 def on_help_contents_click(self,*args):
841 _help = Help(HELP_ROOT)
842 _help.run()
843
844 def create_observer(self,name=None):
845 if name==None:
846 name="New Observer"
847
848 _xml = gtk.glade.XML(GLADE_FILE,"observervbox");
849 _label = gtk.Label();
850 _label.set_text(name)
851 _tab = self.maintabs.append_page(_xml.get_widget("observervbox"),_label);
852 self.observers.append(ObserverTab(_xml, name, self, _tab))
853
854 def sync_observers(self):
855 for _o in self.observers:
856 _o.sync()
857
858 # ------------------------------
859 # CONTEXT MENU
860
861 def tree_click(self,widget,event):
862 # which button was clicked?
863 if event.button == 3:
864 _x = int(event.x)
865 _y = int(event.y)
866 _time = event.time
867 _pthinfo = self.treeview.get_path_at_pos(_x, _y)
868 if _pthinfo != None:
869 _canpop = False;
870 _path, _col, _cellx, _celly = _pthinfo
871 # self.reporter.reportError("Right click on %s" % self.otank[_path][0])
872 _instance = self.otank[_path][1]
873 if _instance.getType().isRefinedSolverVar():
874 _canpop = True;
875 self.observemenuitem.set_sensitive(True)
876 if _instance.isFixed():
877 self.fixmenuitem.set_sensitive(False)
878 self.freemenuitem.set_sensitive(True)
879 else:
880 self.fixmenuitem.set_sensitive(True)
881 self.freemenuitem.set_sensitive(False)
882 elif _instance.isRelation():
883 _canpop = True;
884 self.propsmenuitem.set_sensitive(True)
885
886 if _instance.isPlottable():
887 self.plotmenuitem.set_sensitive(True)
888 _canpop = True;
889 else:
890 self.plotmenuitem.set_sensitive(False)
891
892 if _canpop:
893 self.treeview.grab_focus()
894 self.treeview.set_cursor( _path, _col, 0)
895 self.treecontext.popup( None, None, None, event.button, _time)
896 return 1
897
898 def fix_activate(self,widget):
899 _path,_col = self.treeview.get_cursor()
900 _name, _instance = self.otank[_path]
901 _instance.setFixed(True)
902 self.reporter.reportNote("Fixed variable %s" % _instance.getName().toString())
903 self.do_solve_if_auto()
904 return 1
905
906 def free_activate(self,widget):
907 _path,_col = self.treeview.get_cursor()
908 _instance = self.otank[_path][1]
909 _instance.setFixed(False)
910 self.reporter.reportNote("Freed variable %s" % _instance.getName().toString())
911 self.do_solve_if_auto()
912 return 1
913
914 def plot_activate(self,widget):
915 self.reporter.reportNote("plot_activate...");
916 _path,_col = self.treeview.get_cursor()
917 _instance = self.otank[_path][1]
918 if not _instance.isPlottable():
919 self.reporter.reportError("Can't plot instance %s" % _instance.getName().toString())
920 return
921 else:
922 self.reporter.reportNote("Instance %s about to be plotted..." % _instance.getName().toString())
923
924 print("Plotting instance '%s'..." % _instance.getName().toString())
925
926 _plot = _instance.getPlot()
927
928 print "Title: ", _plot.getTitle()
929 _plot.show(True)
930
931 return 1
932
933 def props_activate(self,widget):
934 _path,_col = self.treeview.get_cursor()
935 _instance = self.otank[_path][1]
936 if _instance.isRelation():
937 print "Relation '"+_instance.getName().toString()+"':", \
938 _instance.getRelationAsString(self.sim.getModel())
939 elif _instance.getType().isRefinedSolverVar():
940 _dia = VarPropsWin(GLADE_FILE,self,_instance);
941 _dia.run();
942 else:
943 self.reporter.reportWarning("props_activate not implemented")
944
945 def observe_activate(self,widget):
946 _path,_col = self.treeview.get_cursor()
947 _instance = self.otank[_path][1]
948 if _instance.getType().isRefinedSolverVar():
949 print "OBSERVING",_instance.getName().toString()
950 if len(self.observers) > 1:
951 self.reporter.reportError("Not implemented: multiple observers")
952 return
953 if len(self.observers) ==0:
954 self.create_observer()
955 _observer = self.observers[0]
956 _observer.add_instance(_instance)
957
958 def delete_event(self, widget, event, data=None):
959 self.do_quit()
960 return False
961
962 def test():
963 import ascend
964 b = Browser();
965 b.run()
966
967 if __name__ == "__main__":
968 test()

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