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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

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