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

Contents of /trunk/pygtk/gtkbrowser.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 732 - (show annotations) (download) (as text)
Tue Jul 4 14:40:17 2006 UTC (17 years, 10 months ago) by johnpye
File MIME type: text/x-python
File size: 28854 byte(s)
Added general-purpose text-information dialog to PyGTK interface.
Added reporting of clique of a variable to PyGTK GUI.
Changed 'fixable' and 'new bounds' to use the new dialog.
Removed 'set<...>' from ascpy.i (it wasn't working), changed to vector<...>.
Exported a couple of var incidences fns to the DLL/SO.
1 #!/usr/bin/env python
2
3 import sys
4 def print_loading_status(status,msg=None):
5 sys.stderr.write("\r \r")
6 if msg!=None:
7 sys.stderr.write(msg+"\n")
8 sys.stderr.write(status+"...")
9 sys.stderr.flush()
10
11 try:
12 print_loading_status("Loading PSYCO")
13
14 #try:
15 # import psyco
16 # psyco.full()
17 # print "Running with PSYCO optimisation..."
18 #except ImportError:
19 # pass
20
21
22 print_loading_status("Loading python standard libraries")
23
24 import re
25 import urlparse
26 import optparse
27 import platform
28 import sys
29 import os.path
30
31 if platform.system() != "Windows":
32 import dl
33 # This sets the flags for dlopen used by python so that the symbols in the
34 # ascend library are made available to libraries dlopened within ASCEND:
35 sys.setdlopenflags(dl.RTLD_GLOBAL|dl.RTLD_NOW)
36
37 print_loading_status("Loading LIBASCEND/ascpy")
38 import ascpy
39
40 print_loading_status("Loading PyGTK, glade, pango")
41
42 import pygtk
43 pygtk.require('2.0')
44 import gtk
45 import gtk.glade
46 import pango
47
48 print_loading_status("Loading python matplotlib")
49 try:
50 import matplotlib
51 matplotlib.use('GTKAgg')
52
53 try:
54 print_loading_status("Trying python numpy")
55 import numpy
56 matplotlib.rcParams['numerix'] = 'numpy'
57 print_loading_status("","Using python module numpy")
58 except ImportError:
59 try:
60 print_loading_status("Trying python numarray")
61 import numarray
62 matplotlib.rcParams['numerix'] = 'numarray'
63 print_loading_status("","Using python module numarray")
64 except ImportError:
65 try:
66 print_loading_status("Trying python Numeric")
67 import Numeric
68 matplotlib.rcParams['numerix'] = 'Numeric'
69 print_loading_status("","Using python module Numeric")
70 except ImportError:
71 print_loading_status("","FAILED TO LOAD A NUMERIC MODULE FOR PYTHON")
72
73 except ImportError,e:
74 print_loading_status("","FAILED TO LOAD MATPLOTLIB")
75 raise RuntimeError("Failed to load MATPLOTLIB (is it installed?). Details:"+str(e))
76
77 print_loading_status("Loading IPython")
78 import console;
79 if not console.have_ipython:
80 print_loading_status("","IPython couldn't be loaded")
81
82 print_loading_status("Loading ASCEND python modules")
83 from preferences import * # loading/saving of .ini options
84 from solverparameters import * # 'solver parameters' window
85 from help import * # viewing help files
86 from incidencematrix import * # incidence/sparsity matrix matplotlib window
87 from observer import * # observer tab support
88 from properties import * # solver_var properties dialog
89 from varentry import * # for inputting of variables with units
90 from diagnose import * # for diagnosing block non-convergence
91 from solverreporter import * # solver status reporting
92 from modelview import * # model browser
93 from integrator import * # integrator dialog
94 from infodialog import * # general-purpose textual information dialog
95 import config
96
97 except RuntimeError, e:
98 print "ASCEND had problems starting up. Please report the following"
99 print "error message at http://mantis.cruncher2.dyndns.org/."
100 print "\n\nFull error message:",str(e)
101 print "\n\nPress ENTER to close this window."
102 sys.stdout.flush()
103 sys.stdin.readline();
104 sys.exit();
105
106 except ImportError, e:
107 print "\n\n------------------ ERROR ---------------------"
108 print "ASCEND had problems importing required models."
109 print "\nPlease ensure you have all the runtime prerequisites installed."
110 print "Please then report a bug if you continue to have problems."
111 print "\nFull error message:",str(e)
112 if platform.system()=="Windows":
113 print "\nYou will also need to report the contents of any popup error"
114 print "messages from Windows if any were shown."
115 print "\n\nPress ENTER to close this window."
116 sys.stdout.flush()
117 sys.stdin.readline();
118 sys.exit();
119
120 print_loading_status("Starting GUI")
121
122 # This is my first ever GUI code so please be nice :)
123 # But I *have* at least read
124 # http://www.joelonsoftware.com/uibook/chapters/fog0000000057.html
125 # and leafed through
126 # http://developer.gnome.org/projects/gup/hig/
127
128 # The fancy tree-view gizmo is the GtkTreeView object. See the article
129 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/300304
130 # for the original source code on which my implementation was based.
131
132 ESCAPE_KEY = 65307
133
134 HELP_ROOT = None
135
136 #======================================
137 # Browser is the main ASCEND library/model browser window
138
139 class Browser:
140
141 # ---------------------------------
142 # SETUP
143
144 def __init__(self):
145 #--------
146 # load the file referenced in the command line, if any
147
148 print_loading_status("Parsing options")
149
150 parser = optparse.OptionParser(usage="%prog [[-m typename] file]", version="gtkbrowser $rev$" )
151 # add options here if we want
152
153 parser.add_option("-m", "--model"
154 ,action="store", type="string", dest="model"
155 ,help="specify the model to instantiate upon loading modules")
156
157 parser.add_option("--pygtk-assets"
158 ,action="store", type="string", dest="assets_dir"
159 ,help="override the configuration value for the location of assets"\
160 +" required by PyGTK for the ASCEND GUI, optional"
161 ,default=config.PYGTK_ASSETS
162 )
163
164 parser.add_option("--library"
165 ,action="store", type="string", dest="library_path"
166 ,help="override the configuration value for the library path"
167 ,default=None
168 )
169
170 parser.add_option("--no-auto-sim"
171 ,action="store_false", dest="auto_sim"
172 ,help="disable auto-instantiation of MODEL named as the file stem"
173 ,default=True
174 )
175
176 (self.options, args) = parser.parse_args()
177
178 #print "OPTIONS_______________:",self.options
179
180 self.assets_dir = self.options.assets_dir
181
182 self.observers = []
183 self.clip = None
184
185 #--------
186 # load up the preferences ini file
187
188 print_loading_status("Loading preferences")
189
190 self.prefs = Preferences()
191
192 _prefpath = self.prefs.getStringPref("Directories","librarypath",None)
193 _preffileopenpath = self.prefs.getStringPref("Directories","fileopenpath",None)
194
195 #--------
196 # set up library path and the path to use for File->Open dialogs
197
198 if self.options.library_path != None:
199 _path = os.path.abspath(self.options.library_path)
200 _pathsrc = "commandline"
201 # when a special path is specified, use that as the file-open location
202 self.fileopenpath = _path
203 else:
204 if _prefpath:
205 _path = _prefpath
206 _pathsrc = "user preferences"
207 else:
208 _path = config.LIBRARY_PATH
209 _pathsrc = "default (config.py)"
210
211 if _preffileopenpath:
212 self.fileopenpath = _preffileopenpath
213 else:
214 self.fileopenpath = _path
215
216 #--------
217 # Create the ASCXX 'Library' object
218
219 print_loading_status("Creating ASCEND 'Library' object","PATH = "+_path+" FROM "+_pathsrc)
220 self.library = ascpy.Library(_path)
221
222 self.sim = None
223
224 #-------------------
225 # Set up the window and main widget actions
226
227 print_loading_status("Setting up windows")
228
229 self.glade_file = self.assets_dir+config.GLADE_FILE
230 glade = gtk.glade.XML(self.glade_file,"browserwin")
231
232 self.window = glade.get_widget("browserwin")
233
234
235 if not self.window:
236 raise RuntimeError("Couldn't load window from glade file")
237
238 _display = self.window.get_screen().get_display().get_name()
239 _geom=self.prefs.getGeometrySizePosition(_display,"browserwin")
240 if _geom:
241 self.window.resize(_geom[0],_geom[1])
242 self.window.move(_geom[2],_geom[3])
243
244 self.window.connect("delete_event", self.delete_event)
245
246 self.browserpaned=glade.get_widget("browserpaned")
247 _geom2=self.prefs.getGeometryValue(_display,"browserpaned")
248 if _geom2:
249 self.browserpaned.set_position(_geom2)
250
251 self.openbutton=glade.get_widget("openbutton")
252 self.openbutton.connect("clicked",self.open_click)
253
254 self.reloadbutton=glade.get_widget("reloadbutton")
255 self.reloadbutton.connect("clicked",self.reload_click)
256
257 self.solvebutton=glade.get_widget("solvebutton")
258 self.solvebutton.connect("clicked",self.solve_click)
259
260 self.integratebutton=glade.get_widget("integratebutton")
261 self.integratebutton.connect("clicked",self.integrate_click)
262
263 self.checkbutton=glade.get_widget("checkbutton")
264 self.checkbutton.connect("clicked",self.check_click)
265
266 self.autotoggle=glade.get_widget("autotoggle")
267 self.automenu = glade.get_widget("automenu")
268 self.autotoggle.connect("toggled",self.auto_toggle)
269
270 self.methodrunbutton=glade.get_widget("methodrunbutton")
271 self.methodrunbutton.connect("clicked",self.methodrun_click)
272
273 self.methodsel=glade.get_widget("methodsel")
274
275 self.maintabs = glade.get_widget("maintabs")
276
277 self.statusbar = glade.get_widget("statusbar")
278
279 self.menu = glade.get_widget("browsermenu")
280
281 self.show_solving_popup=glade.get_widget("show_solving_popup")
282 self.show_solving_popup.set_active(self.prefs.getBoolPref("SolverReporter","show_popup",True))
283 self.close_on_converged=glade.get_widget("close_on_converged")
284 self.close_on_converged.set_active(self.prefs.getBoolPref("SolverReporter","close_on_converged",True))
285 self.close_on_nonconverged=glade.get_widget("close_on_nonconverged")
286 self.close_on_nonconverged.set_active(self.prefs.getBoolPref("SolverReporter","close_on_nonconverged",True))
287
288 glade.signal_autoconnect(self)
289
290 #-------
291 # Status icons
292
293 self.fixedimg = gtk.Image()
294 self.fixedimg.set_from_file(self.options.assets_dir+'locked.png')
295
296 self.iconstatusunknown = None
297 self.iconfixed = self.fixedimg.get_pixbuf()
298 self.iconsolved = self.window.render_icon(gtk.STOCK_YES,gtk.ICON_SIZE_MENU)
299 self.iconactive = self.window.render_icon(gtk.STOCK_NO,gtk.ICON_SIZE_MENU)
300 self.iconunsolved = None
301
302 self.statusicons={
303 ascpy.ASCXX_VAR_STATUS_UNKNOWN: self.iconstatusunknown
304 ,ascpy.ASCXX_VAR_FIXED: self.iconfixed
305 ,ascpy.ASCXX_VAR_SOLVED: self.iconsolved
306 ,ascpy.ASCXX_VAR_ACTIVE: self.iconactive
307 ,ascpy.ASCXX_VAR_UNSOLVED: self.iconunsolved
308 }
309
310
311 self.statusmessages={
312 ascpy.ASCXX_VAR_STATUS_UNKNOWN: "Status unknown"
313 ,ascpy.ASCXX_VAR_FIXED: "Fixed"
314 ,ascpy.ASCXX_VAR_SOLVED: "Converged"
315 ,ascpy.ASCXX_VAR_ACTIVE: "Active (unconverged)"
316 ,ascpy.ASCXX_VAR_UNSOLVED: "Not yet visited"
317 }
318
319 #-------------------
320 # waitwin
321
322 self.waitwin = gtk.gdk.Window(self.window.window,
323 gtk.gdk.screen_width(),
324 gtk.gdk.screen_height(),
325 gtk.gdk.WINDOW_CHILD,
326 0,
327 gtk.gdk.INPUT_ONLY)
328
329 _cursor = gtk.gdk.Cursor(gtk.gdk.WATCH)
330 self.waitwin.set_cursor(_cursor)
331
332 #-------------------
333 # pixbufs to be used in the error listing
334
335 self.iconok = self.window.render_icon(gtk.STOCK_YES,gtk.ICON_SIZE_MENU)
336 self.iconinfo = self.window.render_icon(gtk.STOCK_DIALOG_INFO,gtk.ICON_SIZE_MENU)
337 self.iconwarning = self.window.render_icon(gtk.STOCK_DIALOG_WARNING,gtk.ICON_SIZE_MENU)
338 self.iconerror = self.window.render_icon(gtk.STOCK_DIALOG_ERROR,gtk.ICON_SIZE_MENU)
339
340 #--------------------
341 # pixbufs for solver_var status
342
343 #--------------------
344 # set up the error view
345
346 self.errorview = glade.get_widget("errorview")
347 errstorecolstypes = [gtk.gdk.Pixbuf,str,str,str,int]
348 self.errorstore = gtk.TreeStore(*errstorecolstypes)
349 errtitles = ["","Location","Message"];
350 self.errorview.set_model(self.errorstore)
351 self.errcols = [ gtk.TreeViewColumn() for _type in errstorecolstypes]
352
353 i = 0
354 for tvcolumn in self.errcols[:len(errtitles)]:
355 tvcolumn.set_title(errtitles[i])
356 self.errorview.append_column(tvcolumn)
357
358 if i>0:
359 _renderer = gtk.CellRendererText()
360 tvcolumn.pack_start(_renderer, True)
361 tvcolumn.add_attribute(_renderer, 'text', i)
362 if(i==2):
363 tvcolumn.add_attribute(_renderer, 'foreground', 3)
364 tvcolumn.add_attribute(_renderer, 'weight', 4)
365 else:
366 _renderer1 = gtk.CellRendererPixbuf()
367 tvcolumn.pack_start(_renderer1, False)
368 tvcolumn.add_attribute(_renderer1, 'pixbuf', int(0))
369
370 i = i + 1
371
372
373 #--------------------
374 # set up the error reporter callback
375 self.reporter = ascpy.getReporter()
376 self.reporter.setPythonErrorCallback(self.error_callback)
377
378 #--------
379 # Assign an icon to the main window
380
381 self.icon = None
382 if config.ICON_EXTENSION:
383 _iconpath = ""
384 try:
385 _icon = gtk.Image()
386 _iconpath = self.assets_dir+'ascend'+config.ICON_EXTENSION
387 _icon.set_from_file(_iconpath)
388 _iconpbuf = _icon.get_pixbuf()
389 self.window.set_icon(_iconpbuf)
390 self.icon = _iconpbuf
391 except Exception, e:
392 self.reporter.reportError("FAILED to set application icon '%s': %s"
393 % (_iconpath,str(e))
394 )
395
396 #-------------------
397 # set up the module view
398
399 self.modtank = {}
400 self.moduleview = glade.get_widget("moduleview")
401 modulestorecoltypes = [str, str, int] # bool=can-be-instantiated
402 self.modulestore = gtk.TreeStore(*modulestorecoltypes)
403 moduleviewtitles = ["Module name", "Filename"]
404 self.moduleview.set_model(self.modulestore)
405 self.modcols = [ gtk.TreeViewColumn() for _type in modulestorecoltypes]
406 i = 0
407 for modcol in self.modcols[:len(moduleviewtitles)]:
408 modcol.set_title(moduleviewtitles[i])
409 self.moduleview.append_column(modcol)
410 _renderer = gtk.CellRendererText()
411 modcol.pack_start(_renderer, True)
412 modcol.add_attribute(_renderer, 'text', i)
413 modcol.add_attribute(_renderer,'weight',2)
414 i = i + 1
415 self.moduleview.connect("row-activated", self.module_activated )
416
417 #--------------------
418 # set up the methods combobox
419
420 self.methodstore = gtk.ListStore(str)
421 self.methodsel.set_model(self.methodstore)
422 _methodrenderer = gtk.CellRendererText()
423 self.methodsel.pack_start(_methodrenderer, True)
424 self.methodsel.add_attribute(_methodrenderer, 'text',0)
425
426 #--------
427 # set up the instance browser view
428
429 self.modelview = ModelView(self, glade)
430
431 #--------
432 # set the state of the 'auto' toggle
433
434 self.is_auto = self.prefs.getBoolPref("Browser","auto_solve",True)
435 self.autotoggle.set_active(self.is_auto)
436 self.automenu.set_active(self.is_auto)
437
438 #--------
439 # options
440
441 if(len(args)==1):
442 self.do_open(args[0])
443
444 print "Options: ",self.options
445
446 _model = None
447 if self.options.model:
448 _model = self.options.model
449 print "MODEL: '%s'" % _model
450 elif self.options.auto_sim:
451 _head, _tail = os.path.split(args[0])
452 if(_tail):
453 _model, _ext = os.path.splitext(_tail)
454
455 if _model:
456 try:
457 _t=self.library.findType(_model)
458 try:
459 self.do_sim(_t)
460 if not self.options.model:
461 self.reporter.reportNote("Instantiating self-titled model '%s'" %_model)
462 except RuntimeError, e:
463 self.reporter.reportError("Failed to create instance of '%s': %s"
464 %(_model, str(e))
465 );
466 except RuntimeError, e:
467 if self.options.model:
468 self.reporter.reportError("Unknown model type '%s': %s"
469 %(_model, str(e))
470 );
471
472 def run(self):
473 self.window.show()
474 print_loading_status("ASCEND is now running")
475 gtk.main()
476
477 # --------------------------------------------
478 # MAJOR GUI COMMANDS
479
480 def on_fix_variable_activate(self,*args):
481 self.modelview.on_fix_variable_activate(*args)
482
483 def on_free_variable_activate(self,*args):
484 self.modelview.on_free_variable_activate(*args)
485
486 def do_open(self,filename):
487 # TODO does the user want to lose their work?
488 # TODO do we need to chdir?
489
490 _context = self.statusbar.get_context_id("do_open")
491
492 self.errorstore.clear()
493
494 self.modelview.clear()
495
496 # self.library.clear()
497
498 self.statusbar.push(_context,"Loading '"+filename+"'")
499 self.library.load(filename)
500 self.statusbar.pop(_context)
501
502 self.filename = filename
503
504 # Load the current list of modules into self.modules
505 self.modtank = {}
506 self.modulestore.clear()
507 modules = self.library.getModules()
508 self.library.listModules()
509 try:
510 _lll=len(modules)
511 except:
512 _msg = "UNABLE TO ACCESS MODULES LIST. This is bad.\n"+\
513 "Check your SWIG configuration (check for warnings during build)."
514
515 self.reporter.reportError(_msg)
516 raise RuntimeError(_msg)
517
518 for m in reversed(modules):
519 _n = str( m.getName() )
520 _f = str( m.getFilename() )
521 #print "ADDING ROW name %s, file = %s" % (_n, _f)
522 _r = self.modulestore.append(None, [ _n, _f, pango.WEIGHT_NORMAL ])
523 for t in self.library.getModuleTypes(m):
524 _n = t.getName()
525 _hasparams = t.hasParameters()
526 if _hasparams:
527 _w = pango.WEIGHT_NORMAL
528 else:
529 _w = pango.WEIGHT_BOLD
530
531 #print "ADDING TYPE %s" % _n
532 _piter = self.modulestore.append(_r , [ _n, "", _w ])
533 _path = self.modulestore.get_path(_piter)
534 self.modtank[_path]=t
535
536 #print "DONE ADDING MODULES"
537
538 self.sim = None;
539 self.maintabs.set_current_page(0);
540
541 # See http://www.daa.com.au/pipermail/pygtk/2005-October/011303.html
542 # for details on how the 'wait cursor' is done.
543 def start_waiting(self, message):
544 self.waitcontext = self.statusbar.get_context_id("waiting")
545 self.statusbar.push(self.waitcontext,message)
546
547 if self.waitwin:
548 self.waitwin.show()
549
550 while gtk.events_pending():
551 gtk.main_iteration()
552
553 def stop_waiting(self):
554 if self.waitwin:
555 self.statusbar.pop(self.waitcontext)
556 self.waitwin.hide()
557
558 def do_sim(self, type_object):
559 self.sim = None;
560 # TODO: clear out old simulation first!
561
562 print "DO_SIM(%s)" % str(type_object.getName())
563 self.start_waiting("Compiling...")
564
565 try:
566 self.sim = type_object.getSimulation(str(type_object.getName())+"_sim")
567 except RuntimeError, e:
568 self.stop_waiting()
569 self.reporter.reportError(str(e))
570 return
571
572 print "...DONE 'getSimulation'"
573 self.stop_waiting()
574
575 self.start_waiting("Building simulation...")
576 print "BUILDING SIMULATION"
577
578 try:
579 self.sim.build()
580 except RuntimeError, e:
581 self.stop_waiting()
582 self.reporter.reportError(str(e))
583 return;
584
585 print "DONE BUILDING"
586 self.stop_waiting()
587
588 self.sim.setSolver(ascpy.Solver("QRSlv"))
589
590 # methods
591 self.methodstore.clear()
592 _methods = self.sim.getType().getMethods()
593 _activemethod = None;
594 for _m in _methods:
595 _i = self.methodstore.append([_m.getName()])
596 if _m.getName()=="on_load":
597 self.methodsel.set_active_iter(_i)
598
599 self.modelview.setSimulation(self.sim)
600
601 def do_solve_if_auto(self):
602 if self.is_auto:
603 self.sim.check()
604 self.do_solve()
605 else:
606 self.sim.processVarStatus()
607 self.modelview.refreshtree()
608
609 self.sync_observers()
610
611 def do_solve(self):
612 if not self.sim:
613 self.reporter.reportError("No model selected yet")
614 return
615
616 self.start_waiting("Solving...")
617
618 if self.prefs.getBoolPref("SolverReporter","show_popup",True):
619 reporter = PopupSolverReporter(self,self.sim.getNumVars())
620 else:
621 reporter = SimpleSolverReporter(self)
622
623 self.sim.solve(ascpy.Solver("QRSlv"),reporter)
624
625 self.stop_waiting()
626
627 self.sim.processVarStatus()
628 self.modelview.refreshtree()
629
630 def do_integrate(self):
631 if not self.sim:
632 self.reporter.reportError("No model selected yet")
633 return
634 integwin = IntegratorWindow(self,self.sim)
635 _integratorreporter = integwin.run()
636 if _integratorreporter!=None:
637 _integratorreporter.run()
638 self.sim.processVarStatus()
639 self.modelview.refreshtree()
640
641
642 def do_check(self):
643 if not self.sim:
644 self.reporter.reportError("No model selected yet")
645 return
646
647 self.start_waiting("Checking system...")
648
649 try:
650 if self.sim.check():
651 self.reporter.reportNote("System check OK")
652 self.sim.checkDoF()
653 except RuntimeError, e:
654 self.stop_waiting()
655 self.reporter.reportError(str(e))
656 return
657
658 self.stop_waiting()
659
660 self.modelview.refreshtree()
661
662 def do_method(self,method):
663 if not self.sim:
664 self.reporter.reportError("No model selected yet")
665
666 self.sim.run(method)
667 self.modelview.refreshtree()
668
669 def do_quit(self):
670 print_loading_status("Saving window location")
671 self.reporter.clearPythonErrorCallback()
672
673 _w,_h = self.window.get_size()
674 _t,_l = self.window.get_position()
675 _display = self.window.get_screen().get_display().get_name()
676 self.prefs.setGeometrySizePosition(_display,"browserwin",_w,_h,_t,_l );
677
678 _p = self.browserpaned.get_position()
679 self.prefs.setGeometryValue(_display,"browserpaned",_p);
680
681 print_loading_status("Saving current directory")
682 self.prefs.setStringPref("Directories","fileopenpath",self.fileopenpath)
683
684 self.prefs.setBoolPref("Browser","auto_solve",self.is_auto)
685
686 print_loading_status("Saving preferences")
687 # causes prefs to be saved unless they are still being used elsewher
688 del(self.prefs)
689
690 print_loading_status("Closing down GTK")
691 gtk.main_quit()
692
693 print_loading_status("Clearing error callback")
694 self.reporter.clearPythonErrorCallback()
695
696 print_loading_status("Quitting")
697 return False
698
699 def on_tools_sparsity_click(self,*args):
700
701 self.reporter.reportNote("Preparing incidence matrix...")
702 _im = self.sim.getIncidenceMatrix();
703
704 self.reporter.reportNote("Plotting incidence matrix...")
705
706 _sp = IncidenceMatrixWindow(_im);
707 _sp.run();
708
709 def on_diagnose_blocks_click(self,*args):
710 try:
711 _bl = self.sim.getActiveBlock()
712 except RuntimeError, e:
713 self.reporter.reportError(str(e))
714 return
715 _db = DiagnoseWindow(self,_bl)
716 _db.run();
717
718 def on_add_observer_click(self,*args):
719 if len(self.observers) > 0:
720 self.reporter.reportError("Not supported: multiple observers")
721 return
722 self.create_observer()
723
724 def on_keep_observed_click(self,*args):
725 if len(self.observers) > 1:
726 self.reporter.reportError("Not supported: multiple observers")
727 return
728 if len(self.observers) <= 0:
729 self.reporter.reportError("No observer defined!")
730 return
731 self.observers[0].do_add_row()
732
733 def on_copy_observer_matrix_click(self,*args):
734 if self.clip == None:
735 self.clip = gtk.Clipboard()
736
737 if len(self.observers) > 1:
738 self.reporter.reportError("Not supported: multiple observers")
739 return
740 if len(self.observers) <= 0:
741 self.reporter.reportError("No observer defined!")
742 return
743 self.observers[0].copy_to_clipboard(self.clip)
744
745 def on_show_solving_popup_toggle(self,checkmenuitem,*args):
746 _v = checkmenuitem.get_active()
747 self.prefs.setBoolPref("SolverReporter","show_popup",_v)
748 print "SET TO",_v
749
750 def on_close_on_converged_toggle(self,checkmenuitem,*args):
751 _v = checkmenuitem.get_active()
752 self.prefs.setBoolPref("SolverReporter","close_on_converged",_v)
753
754 def on_close_on_nonconverged_toggle(self,checkmenuitem,*args):
755 _v = checkmenuitem.get_active()
756 self.prefs.setBoolPref("SolverReporter","close_on_nonconverged",_v)
757
758 def on_show_variables_near_bounds_activate(self,*args):
759 _epsilon = 1e-4;
760 text = "Variables New Bounds"
761 title=text;
762 text += "\n"
763 _vars = self.sim.getVariablesNearBounds(_epsilon)
764 if len(_vars):
765 for _v in _vars:
766 text += "\n%s"%_v.getName()
767 else:
768 text +="\nnone"
769 _dialog = InfoDialog(self,self.window,text,title)
770 _dialog.run()
771
772 # --------------------------------------------
773 # MODULE LIST
774
775 def module_activated(self, treeview, path, column, *args):
776 modules = self.library.getModules()
777 print "PATH",path
778 if len(path)==1:
779 self.reporter.reportNote("Launching of external editor not yet implemented")
780 elif len(path)==2:
781 if(self.modtank.has_key(path)):
782 _type = self.modtank[path];
783 self.reporter.reportNote("Creating simulation for type %s" % str(_type.getName()) )
784 self.do_sim(_type)
785 else:
786 self.reporter.reportError("Didn't find type corresponding to row")
787
788 # ----------------------------------
789 # ERROR PANEL
790
791 def get_error_row_data(self,sev,filename,line,msg):
792 _sevicon = {
793 0: self.iconok
794 ,1: self.iconinfo
795 ,2: self.iconwarning
796 ,3: self.iconerror
797 ,4: self.iconinfo
798 ,5: self.iconwarning
799 ,6: self.iconerror
800 }[sev]
801
802 _fontweight = pango.WEIGHT_NORMAL
803 if sev==6:
804 _fontweight = pango.WEIGHT_BOLD
805
806 _fgcolor = "black"
807 if sev==4:
808 _fgcolor = "#888800"
809 elif sev==5:
810 _fgcolor = "#884400"
811 elif sev==6:
812 _fgcolor = "#880000"
813 elif sev==0:
814 _fgcolor = BROWSER_FIXED_COLOR
815
816 if not filename and not line:
817 _fileline = ""
818 else:
819 if(len(filename) > 25):
820 filename = "..."+filename[-22:]
821 _fileline = filename + ":" + str(line)
822
823 _res = [_sevicon,_fileline,msg.rstrip(),_fgcolor,_fontweight]
824 #print _res
825 return _res
826
827 def error_callback(self,sev,filename,line,msg):
828 pos = self.errorstore.append(None, self.get_error_row_data(sev, filename,line,msg))
829 path = self.errorstore.get_path(pos)
830 col = self.errorview.get_column(3)
831 self.errorview.scroll_to_cell(path,col)
832
833 return 0;
834
835 # --------------------------------
836 # BUTTON METHODS
837
838 def open_click(self,*args):
839 #print_loading_status("CURRENT FILEOPENPATH is",self.fileopenpath)
840 dialog = gtk.FileChooserDialog("Open ASCEND model...",
841 self.window,
842 gtk.FILE_CHOOSER_ACTION_OPEN,
843 (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)
844 )
845 dialog.set_current_folder(self.fileopenpath)
846 dialog.set_default_response(gtk.RESPONSE_OK)
847 dialog.set_transient_for(self.window)
848 dialog.set_modal(True)
849
850 filter = gtk.FileFilter()
851 filter.set_name("*.a4c, *.a4l")
852 filter.add_pattern("*.[Aa]4[Cc]")
853 filter.add_pattern("*.[Aa]4[Ll]")
854 dialog.add_filter(filter)
855
856 filter = gtk.FileFilter()
857 filter.set_name("All files")
858 filter.add_pattern("*")
859 dialog.add_filter(filter)
860
861 response = dialog.run()
862 _filename = dialog.get_filename()
863 print "\nFILENAME SELECTED:",_filename
864
865 _path = dialog.get_current_folder()
866 if _path:
867 self.fileopenpath = _path
868
869 dialog.hide()
870
871 if response == gtk.RESPONSE_OK:
872 self.reporter.reportNote("File %s selected." % dialog.get_filename() )
873 self.library.clear()
874 self.do_open( _filename)
875
876 def reload_click(self,*args):
877 _type = None
878 if(self.sim):
879 _type = self.sim.getType().getName().toString();
880
881 self.library.clear()
882 self.do_open(self.filename)
883
884 if _type:
885 _t = self.library.findType(_type)
886 self.do_sim(_t)
887
888 def props_activate(self,widget,*args):
889 return self.modelview.props_activate(self,widget,*args)
890
891 def observe_activate(self,widget,*args):
892 return self.modelview.observe_activate(self,widget,*args)
893
894 def solve_click(self,*args):
895 #self.reporter.reportError("Solving simulation '" + self.sim.getName().toString() +"'...")
896 self.do_solve()
897
898 def console_click(self,*args):
899 try:
900 console.start(self)
901 except RuntimeError,e:
902 self.reporter.reportError("Unable to start console: "+str(e));
903
904 def integrate_click(self,*args):
905 self.do_integrate()
906
907 def check_click(self,*args):
908 self.do_check()
909 #self.reporter.reportError("CHECK clicked")
910
911 def preferences_click(self,*args):
912 if not self.sim:
913 self.reporter.reportError("No simulation created yet!");
914
915 _paramswin = SolverParametersWindow(self)
916 _paramswin.show()
917
918 def methodrun_click(self,*args):
919 _sel = self.methodsel.get_active_text()
920 if _sel:
921 _method = None
922 _methods = self.sim.getType().getMethods()
923 for _m in _methods:
924 if _m.getName()==_sel:
925 _method = _m
926 if not _method:
927 self.reporter.reportError("Method is not valid")
928 return
929 self.do_method(_method)
930 else:
931 self.reporter.reportError("No method selected")
932
933 def auto_toggle(self,button,*args):
934 self.is_auto = button.get_active()
935 if hasattr(self,'automenu'):
936 self.automenu.set_active(self.is_auto)
937 else:
938 raise RuntimeError("no automenu")
939
940 #if self.is_auto:
941 # self.reporter.reportSuccess("Auto mode is now ON")
942 #else:
943 # self.reporter.reportSuccess("Auto mode is now OFF")
944
945 def on_file_quit_click(self,*args):
946 self.do_quit()
947
948 def on_tools_auto_toggle(self,checkmenuitem,*args):
949 self.is_auto = checkmenuitem.get_active()
950 self.autotoggle.set_active(self.is_auto)
951
952 def on_help_about_click(self,*args):
953 _xml = gtk.glade.XML(self.glade_file,"aboutdialog")
954 _about = _xml.get_widget("aboutdialog")
955 _about.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
956 _about.set_transient_for(self.window);
957 _about.set_version(config.VERSION)
958 _about.run()
959 _about.destroy()
960
961 def on_help_contents_click(self,*args):
962 _help = Help(HELP_ROOT)
963 _help.run()
964
965 def on_find_fixable_variables_activate(self,*args):
966 v = self.sim.getFixableVariables()
967 text = "Fixable Variables"
968 title = text;
969 text += "\n"
970 if len(v):
971 for var in v:
972 text += "\n%s"%var
973 else:
974 text += "\nnone"
975 _dialog = InfoDialog(self,self.window,text,title)
976 _dialog.run()
977
978 def create_observer(self,name=None):
979 if name==None:
980 name="New Observer"
981
982 _xml = gtk.glade.XML(self.glade_file,"observervbox");
983 _label = gtk.Label();
984 _label.set_text(name)
985 _tab = self.maintabs.append_page(_xml.get_widget("observervbox"),_label);
986 self.observers.append(ObserverTab(_xml, name, self, _tab))
987
988 def sync_observers(self):
989 for _o in self.observers:
990 _o.sync()
991
992 def delete_event(self, widget, event):
993 self.do_quit()
994 return False
995
996 def observe(self,instance):
997 if len(self.observers) > 1:
998 self.reporter.reportError("Not implemented: multiple observers (currently %d observers)" %
999 len(self.observers) )
1000 return
1001 if len(self.observers) ==0:
1002 self.create_observer()
1003 _observer = self.observers[0]
1004 _observer.add_instance(instance)
1005
1006 if __name__ == "__main__":
1007 b = Browser();
1008 b.run()

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