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

Contents of /trunk/pygtk/gtkbrowser.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 772 - (show annotations) (download) (as text)
Fri Jul 14 06:03:47 2006 UTC (14 years, 3 months ago) by johnpye
File MIME type: text/x-python
File size: 30705 byte(s)
Improved the reporting of structural singularities in PyGTK interface.
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 numarray")
55 import numarray
56 matplotlib.rcParams['numerix'] = 'numarray'
57 print_loading_status("","Using python module numarray")
58 except ImportError:
59 try:
60 print_loading_status("Trying python numpy")
61 import numpy
62 matplotlib.rcParams['numerix'] = 'numpy'
63 print_loading_status("","Using python module numpy")
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 self.use_relation_sharing=glade.get_widget("use_relation_sharing")
289 self.use_relation_sharing.set_active(self.prefs.getBoolPref("Compiler","use_relation_sharing",True))
290
291 glade.signal_autoconnect(self)
292
293 #-------
294 # Status icons
295
296 self.fixedimg = gtk.Image()
297 self.fixedimg.set_from_file(self.options.assets_dir+'locked.png')
298
299 self.iconstatusunknown = None
300 self.iconfixed = self.fixedimg.get_pixbuf()
301 self.iconsolved = self.window.render_icon(gtk.STOCK_YES,gtk.ICON_SIZE_MENU)
302 self.iconactive = self.window.render_icon(gtk.STOCK_NO,gtk.ICON_SIZE_MENU)
303 self.iconunsolved = None
304
305 self.statusicons={
306 ascpy.ASCXX_VAR_STATUS_UNKNOWN: self.iconstatusunknown
307 ,ascpy.ASCXX_VAR_FIXED: self.iconfixed
308 ,ascpy.ASCXX_VAR_SOLVED: self.iconsolved
309 ,ascpy.ASCXX_VAR_ACTIVE: self.iconactive
310 ,ascpy.ASCXX_VAR_UNSOLVED: self.iconunsolved
311 }
312
313
314 self.statusmessages={
315 ascpy.ASCXX_VAR_STATUS_UNKNOWN: "Status unknown"
316 ,ascpy.ASCXX_VAR_FIXED: "Fixed"
317 ,ascpy.ASCXX_VAR_SOLVED: "Converged"
318 ,ascpy.ASCXX_VAR_ACTIVE: "Active (unconverged)"
319 ,ascpy.ASCXX_VAR_UNSOLVED: "Not yet visited"
320 }
321
322 #-------------------
323 # waitwin
324
325 self.waitwin = gtk.gdk.Window(self.window.window,
326 gtk.gdk.screen_width(),
327 gtk.gdk.screen_height(),
328 gtk.gdk.WINDOW_CHILD,
329 0,
330 gtk.gdk.INPUT_ONLY)
331
332 _cursor = gtk.gdk.Cursor(gtk.gdk.WATCH)
333 self.waitwin.set_cursor(_cursor)
334
335 #-------------------
336 # pixbufs to be used in the error listing
337
338 self.iconok = self.window.render_icon(gtk.STOCK_YES,gtk.ICON_SIZE_MENU)
339 self.iconinfo = self.window.render_icon(gtk.STOCK_DIALOG_INFO,gtk.ICON_SIZE_MENU)
340 self.iconwarning = self.window.render_icon(gtk.STOCK_DIALOG_WARNING,gtk.ICON_SIZE_MENU)
341 self.iconerror = self.window.render_icon(gtk.STOCK_DIALOG_ERROR,gtk.ICON_SIZE_MENU)
342
343 #--------------------
344 # pixbufs for solver_var status
345
346 #--------------------
347 # set up the error view
348
349 self.errorview = glade.get_widget("errorview")
350 errstorecolstypes = [gtk.gdk.Pixbuf,str,str,str,int]
351 self.errorstore = gtk.TreeStore(*errstorecolstypes)
352 errtitles = ["","Location","Message"];
353 self.errorview.set_model(self.errorstore)
354 self.errcols = [ gtk.TreeViewColumn() for _type in errstorecolstypes]
355
356 i = 0
357 for tvcolumn in self.errcols[:len(errtitles)]:
358 tvcolumn.set_title(errtitles[i])
359 self.errorview.append_column(tvcolumn)
360
361 if i>0:
362 _renderer = gtk.CellRendererText()
363 tvcolumn.pack_start(_renderer, True)
364 tvcolumn.add_attribute(_renderer, 'text', i)
365 if(i==2):
366 tvcolumn.add_attribute(_renderer, 'foreground', 3)
367 tvcolumn.add_attribute(_renderer, 'weight', 4)
368 else:
369 _renderer1 = gtk.CellRendererPixbuf()
370 tvcolumn.pack_start(_renderer1, False)
371 tvcolumn.add_attribute(_renderer1, 'pixbuf', int(0))
372
373 i = i + 1
374
375
376 #--------------------
377 # set up the error reporter callback
378 self.reporter = ascpy.getReporter()
379 self.reporter.setPythonErrorCallback(self.error_callback)
380
381 #--------
382 # Assign an icon to the main window
383
384 self.icon = None
385 if config.ICON_EXTENSION:
386 _iconpath = ""
387 try:
388 _icon = gtk.Image()
389 _iconpath = self.assets_dir+'ascend'+config.ICON_EXTENSION
390 _icon.set_from_file(_iconpath)
391 _iconpbuf = _icon.get_pixbuf()
392 self.window.set_icon(_iconpbuf)
393 self.icon = _iconpbuf
394 except Exception, e:
395 self.reporter.reportError("FAILED to set application icon '%s': %s"
396 % (_iconpath,str(e))
397 )
398
399 #-------------------
400 # set up the module view
401
402 self.modtank = {}
403 self.moduleview = glade.get_widget("moduleview")
404 modulestorecoltypes = [str, str, int] # bool=can-be-instantiated
405 self.modulestore = gtk.TreeStore(*modulestorecoltypes)
406 moduleviewtitles = ["Module name", "Filename"]
407 self.moduleview.set_model(self.modulestore)
408 self.modcols = [ gtk.TreeViewColumn() for _type in modulestorecoltypes]
409 i = 0
410 for modcol in self.modcols[:len(moduleviewtitles)]:
411 modcol.set_title(moduleviewtitles[i])
412 self.moduleview.append_column(modcol)
413 _renderer = gtk.CellRendererText()
414 modcol.pack_start(_renderer, True)
415 modcol.add_attribute(_renderer, 'text', i)
416 modcol.add_attribute(_renderer,'weight',2)
417 i = i + 1
418 self.moduleview.connect("row-activated", self.module_activated )
419
420 #--------------------
421 # set up the methods combobox
422
423 self.methodstore = gtk.ListStore(str)
424 self.methodsel.set_model(self.methodstore)
425 _methodrenderer = gtk.CellRendererText()
426 self.methodsel.pack_start(_methodrenderer, True)
427 self.methodsel.add_attribute(_methodrenderer, 'text',0)
428
429 #--------
430 # set up the instance browser view
431
432 self.modelview = ModelView(self, glade)
433
434 #--------
435 # set the state of the 'auto' toggle
436
437 self.is_auto = self.prefs.getBoolPref("Browser","auto_solve",True)
438 self.autotoggle.set_active(self.is_auto)
439 self.automenu.set_active(self.is_auto)
440
441 #--------
442 # options
443
444 if(len(args)==1):
445 self.do_open(args[0])
446
447 print "Options: ",self.options
448
449 _model = None
450 if self.options.model:
451 _model = self.options.model
452 print "MODEL: '%s'" % _model
453 elif self.options.auto_sim:
454 _head, _tail = os.path.split(args[0])
455 if(_tail):
456 _model, _ext = os.path.splitext(_tail)
457
458 if _model:
459 try:
460 _t=self.library.findType(_model)
461 try:
462 self.do_sim(_t)
463 if not self.options.model:
464 self.reporter.reportNote("Instantiating self-titled model '%s'" %_model)
465 except RuntimeError, e:
466 self.reporter.reportError("Failed to create instance of '%s': %s"
467 %(_model, str(e))
468 );
469 except RuntimeError, e:
470 if self.options.model:
471 self.reporter.reportError("Unknown model type '%s': %s"
472 %(_model, str(e))
473 );
474
475 def run(self):
476 self.window.show()
477 print_loading_status("ASCEND is now running")
478 gtk.main()
479
480 # --------------------------------------------
481 # MAJOR GUI COMMANDS
482
483 def on_fix_variable_activate(self,*args):
484 self.modelview.on_fix_variable_activate(*args)
485
486 def on_free_variable_activate(self,*args):
487 self.modelview.on_free_variable_activate(*args)
488
489 def do_open(self,filename):
490 # TODO does the user want to lose their work?
491 # TODO do we need to chdir?
492
493 _context = self.statusbar.get_context_id("do_open")
494
495 self.errorstore.clear()
496
497 self.modelview.clear()
498
499 # self.library.clear()
500
501 self.statusbar.push(_context,"Loading '"+filename+"'")
502 self.library.load(filename)
503 self.statusbar.pop(_context)
504
505 self.filename = filename
506
507 # Load the current list of modules into self.modules
508 self.modtank = {}
509 self.modulestore.clear()
510 modules = self.library.getModules()
511 self.library.listModules()
512 try:
513 _lll=len(modules)
514 except:
515 _msg = "UNABLE TO ACCESS MODULES LIST. This is bad.\n"+\
516 "Check your SWIG configuration (check for warnings during build)."
517
518 self.reporter.reportError(_msg)
519 raise RuntimeError(_msg)
520
521 for m in reversed(modules):
522 _n = str( m.getName() )
523 _f = str( m.getFilename() )
524 #print "ADDING ROW name %s, file = %s" % (_n, _f)
525 _r = self.modulestore.append(None, [ _n, _f, pango.WEIGHT_NORMAL ])
526 for t in self.library.getModuleTypes(m):
527 _n = t.getName()
528 _hasparams = t.hasParameters()
529 if _hasparams:
530 _w = pango.WEIGHT_NORMAL
531 else:
532 _w = pango.WEIGHT_BOLD
533
534 #print "ADDING TYPE %s" % _n
535 _piter = self.modulestore.append(_r , [ _n, "", _w ])
536 _path = self.modulestore.get_path(_piter)
537 self.modtank[_path]=t
538
539 #print "DONE ADDING MODULES"
540
541 self.sim = None;
542 self.maintabs.set_current_page(0);
543
544 # See http://www.daa.com.au/pipermail/pygtk/2005-October/011303.html
545 # for details on how the 'wait cursor' is done.
546 def start_waiting(self, message):
547 self.waitcontext = self.statusbar.get_context_id("waiting")
548 self.statusbar.push(self.waitcontext,message)
549
550 if self.waitwin:
551 self.waitwin.show()
552
553 while gtk.events_pending():
554 gtk.main_iteration()
555
556 def stop_waiting(self):
557 if self.waitwin:
558 self.statusbar.pop(self.waitcontext)
559 self.waitwin.hide()
560
561 def do_sim(self, type_object):
562 self.sim = None;
563 # TODO: clear out old simulation first!
564
565 print "DO_SIM(%s)" % str(type_object.getName())
566 self.start_waiting("Compiling...")
567
568 try:
569 _v = self.prefs.getBoolPref("Compiler","use_relation_sharing",True)
570 ascpy.getCompiler().setUseRelationSharing(_v)
571
572 self.sim = type_object.getSimulation(str(type_object.getName())+"_sim")
573 except RuntimeError, e:
574 self.stop_waiting()
575 self.reporter.reportError(str(e))
576 return
577
578 print "...DONE 'getSimulation'"
579 self.stop_waiting()
580
581 self.start_waiting("Building simulation...")
582 print "BUILDING SIMULATION"
583
584 try:
585 self.sim.build()
586 except RuntimeError, e:
587 self.stop_waiting()
588 self.reporter.reportError(str(e))
589 return;
590
591 print "DONE BUILDING"
592 self.stop_waiting()
593
594 self.sim.setSolver(ascpy.Solver("QRSlv"))
595
596 # methods
597 self.methodstore.clear()
598 _methods = self.sim.getType().getMethods()
599 _activemethod = None;
600 for _m in _methods:
601 _i = self.methodstore.append([_m.getName()])
602 if _m.getName()=="on_load":
603 self.methodsel.set_active_iter(_i)
604
605 self.modelview.setSimulation(self.sim)
606
607 def do_solve_if_auto(self):
608 if self.is_auto:
609 self.sim.check()
610 self.do_solve()
611 else:
612 self.sim.processVarStatus()
613 self.modelview.refreshtree()
614
615 self.sync_observers()
616
617 def do_solve(self):
618 if not self.sim:
619 self.reporter.reportError("No model selected yet")
620 return
621
622 self.start_waiting("Solving...")
623
624 if self.prefs.getBoolPref("SolverReporter","show_popup",True):
625 reporter = PopupSolverReporter(self,self.sim.getNumVars())
626 else:
627 reporter = SimpleSolverReporter(self)
628
629 self.sim.solve(ascpy.Solver("QRSlv"),reporter)
630
631 self.stop_waiting()
632
633 self.sim.processVarStatus()
634 self.modelview.refreshtree()
635
636 def do_integrate(self):
637 if not self.sim:
638 self.reporter.reportError("No model selected yet")
639 return
640 integwin = IntegratorWindow(self,self.sim)
641 _integratorreporter = integwin.run()
642 if _integratorreporter!=None:
643 _integratorreporter.run()
644 self.sim.processVarStatus()
645 self.modelview.refreshtree()
646
647
648 def do_check(self):
649 if not self.sim:
650 self.reporter.reportError("No model selected yet")
651 return
652
653 self.start_waiting("Checking system...")
654
655 try:
656 if self.sim.check():
657 self.reporter.reportNote("System check OK")
658 if self.sim.checkDoF():
659 self.reporter.reportNode("System DoF check OK")
660 else:
661 sing = self.sim.getSingularityInfo()
662 title = "Structural singularity"
663 text = title
664 text += "\n\nThe singularity can be reduced by freeing the following variables:"
665 msgs = {
666 "The singularity can be reduced by freeing the following variables" : sing.freeablevars
667 ,"Relations involved in the structural singularity" : sing.rels
668 ,"Variables involved in the structural singularity" : sing.vars
669 }
670 for k,v in msgs.iteritems():
671 text+="\n\n%s:" % k
672 if len(v):
673 _l = [j.getName() for j in v]
674 _l.sort()
675 text+= "\n\t" + "\n\t".join(_l)
676 else:
677 text += "\nnone"
678
679 _dialog = InfoDialog(self,self.window,text,title)
680 _dialog.run()
681
682 self.reporter.reportError("System DoF check failed")
683 except RuntimeError, e:
684 self.stop_waiting()
685 self.reporter.reportError(str(e))
686 return
687
688 self.stop_waiting()
689
690 self.modelview.refreshtree()
691
692 def do_method(self,method):
693 if not self.sim:
694 self.reporter.reportError("No model selected yet")
695
696 self.sim.run(method)
697 self.modelview.refreshtree()
698
699 def do_quit(self):
700 print_loading_status("Saving window location")
701 self.reporter.clearPythonErrorCallback()
702
703 _w,_h = self.window.get_size()
704 _t,_l = self.window.get_position()
705 _display = self.window.get_screen().get_display().get_name()
706 self.prefs.setGeometrySizePosition(_display,"browserwin",_w,_h,_t,_l );
707
708 _p = self.browserpaned.get_position()
709 self.prefs.setGeometryValue(_display,"browserpaned",_p);
710
711 print_loading_status("Saving current directory")
712 self.prefs.setStringPref("Directories","fileopenpath",self.fileopenpath)
713
714 self.prefs.setBoolPref("Browser","auto_solve",self.is_auto)
715
716 print_loading_status("Saving preferences")
717 # causes prefs to be saved unless they are still being used elsewher
718 del(self.prefs)
719
720 print_loading_status("Closing down GTK")
721 gtk.main_quit()
722
723 print_loading_status("Clearing error callback")
724 self.reporter.clearPythonErrorCallback()
725
726 print_loading_status("Quitting")
727 return False
728
729 def on_tools_sparsity_click(self,*args):
730
731 self.reporter.reportNote("Preparing incidence matrix...")
732 _im = self.sim.getIncidenceMatrix();
733
734 self.reporter.reportNote("Plotting incidence matrix...")
735
736 _sp = IncidenceMatrixWindow(_im);
737 _sp.run();
738
739 def on_diagnose_blocks_click(self,*args):
740 try:
741 _bl = self.sim.getActiveBlock()
742 except RuntimeError, e:
743 self.reporter.reportError(str(e))
744 return
745 _db = DiagnoseWindow(self,_bl)
746 _db.run();
747
748 def on_add_observer_click(self,*args):
749 if len(self.observers) > 0:
750 self.reporter.reportError("Not supported: multiple observers")
751 return
752 self.create_observer()
753
754 def on_keep_observed_click(self,*args):
755 if len(self.observers) > 1:
756 self.reporter.reportError("Not supported: multiple observers")
757 return
758 if len(self.observers) <= 0:
759 self.reporter.reportError("No observer defined!")
760 return
761 self.observers[0].do_add_row()
762
763 def on_copy_observer_matrix_click(self,*args):
764 if self.clip == None:
765 self.clip = gtk.Clipboard()
766
767 if len(self.observers) > 1:
768 self.reporter.reportError("Not supported: multiple observers")
769 return
770 if len(self.observers) <= 0:
771 self.reporter.reportError("No observer defined!")
772 return
773 self.observers[0].copy_to_clipboard(self.clip)
774
775 def on_use_relation_sharing_toggle(self,checkmenuitem,*args):
776 _v = checkmenuitem.get_active()
777 self.prefs.setBoolPref("Compiler","use_relation_sharing",_v)
778 self.reporter.reportNote("Relation sharing set to "+str(_v))
779
780 def on_show_solving_popup_toggle(self,checkmenuitem,*args):
781 _v = checkmenuitem.get_active()
782 self.prefs.setBoolPref("SolverReporter","show_popup",_v)
783 print "SET TO",_v
784
785 def on_close_on_converged_toggle(self,checkmenuitem,*args):
786 _v = checkmenuitem.get_active()
787 self.prefs.setBoolPref("SolverReporter","close_on_converged",_v)
788
789 def on_close_on_nonconverged_toggle(self,checkmenuitem,*args):
790 _v = checkmenuitem.get_active()
791 self.prefs.setBoolPref("SolverReporter","close_on_nonconverged",_v)
792
793 def on_show_variables_near_bounds_activate(self,*args):
794 _epsilon = 1e-4;
795 text = "Variables New Bounds"
796 title=text;
797 text += "\n"
798 _vars = self.sim.getVariablesNearBounds(_epsilon)
799 if len(_vars):
800 for _v in _vars:
801 text += "\n%s"%_v.getName()
802 else:
803 text +="\nnone"
804 _dialog = InfoDialog(self,self.window,text,title)
805 _dialog.run()
806
807 # --------------------------------------------
808 # MODULE LIST
809
810 def module_activated(self, treeview, path, column, *args):
811 modules = self.library.getModules()
812 print "PATH",path
813 if len(path)==1:
814 self.reporter.reportNote("Launching of external editor not yet implemented")
815 elif len(path)==2:
816 if(self.modtank.has_key(path)):
817 _type = self.modtank[path];
818 self.reporter.reportNote("Creating simulation for type %s" % str(_type.getName()) )
819 self.do_sim(_type)
820 else:
821 self.reporter.reportError("Didn't find type corresponding to row")
822
823 # ----------------------------------
824 # ERROR PANEL
825
826 def get_error_row_data(self,sev,filename,line,msg):
827 _sevicon = {
828 0: self.iconok
829 ,1: self.iconinfo
830 ,2: self.iconwarning
831 ,3: self.iconerror
832 ,4: self.iconinfo
833 ,5: self.iconwarning
834 ,6: self.iconerror
835 }[sev]
836
837 _fontweight = pango.WEIGHT_NORMAL
838 if sev==6:
839 _fontweight = pango.WEIGHT_BOLD
840
841 _fgcolor = "black"
842 if sev==4:
843 _fgcolor = "#888800"
844 elif sev==5:
845 _fgcolor = "#884400"
846 elif sev==6:
847 _fgcolor = "#880000"
848 elif sev==0:
849 _fgcolor = BROWSER_FIXED_COLOR
850
851 if not filename and not line:
852 _fileline = ""
853 else:
854 if(len(filename) > 25):
855 filename = "..."+filename[-22:]
856 _fileline = filename + ":" + str(line)
857
858 _res = [_sevicon,_fileline,msg.rstrip(),_fgcolor,_fontweight]
859 #print _res
860 return _res
861
862 def error_callback(self,sev,filename,line,msg):
863 pos = self.errorstore.append(None, self.get_error_row_data(sev, filename,line,msg))
864 path = self.errorstore.get_path(pos)
865 col = self.errorview.get_column(3)
866 self.errorview.scroll_to_cell(path,col)
867
868 return 0;
869
870 # --------------------------------
871 # BUTTON METHODS
872
873 def open_click(self,*args):
874 #print_loading_status("CURRENT FILEOPENPATH is",self.fileopenpath)
875 dialog = gtk.FileChooserDialog("Open ASCEND model...",
876 self.window,
877 gtk.FILE_CHOOSER_ACTION_OPEN,
878 (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)
879 )
880 dialog.set_current_folder(self.fileopenpath)
881 dialog.set_default_response(gtk.RESPONSE_OK)
882 dialog.set_transient_for(self.window)
883 dialog.set_modal(True)
884
885 filter = gtk.FileFilter()
886 filter.set_name("*.a4c, *.a4l")
887 filter.add_pattern("*.[Aa]4[Cc]")
888 filter.add_pattern("*.[Aa]4[Ll]")
889 dialog.add_filter(filter)
890
891 filter = gtk.FileFilter()
892 filter.set_name("All files")
893 filter.add_pattern("*")
894 dialog.add_filter(filter)
895
896 response = dialog.run()
897 _filename = dialog.get_filename()
898 print "\nFILENAME SELECTED:",_filename
899
900 _path = dialog.get_current_folder()
901 if _path:
902 self.fileopenpath = _path
903
904 dialog.hide()
905
906 if response == gtk.RESPONSE_OK:
907 self.reporter.reportNote("File %s selected." % dialog.get_filename() )
908 self.library.clear()
909 self.do_open( _filename)
910
911 def reload_click(self,*args):
912 _type = None
913 if(self.sim):
914 _type = self.sim.getType().getName().toString();
915
916 self.library.clear()
917 self.do_open(self.filename)
918
919 if _type:
920 _t = self.library.findType(_type)
921 self.do_sim(_t)
922
923 def props_activate(self,widget,*args):
924 return self.modelview.props_activate(self,widget,*args)
925
926 def observe_activate(self,widget,*args):
927 return self.modelview.observe_activate(self,widget,*args)
928
929 def solve_click(self,*args):
930 #self.reporter.reportError("Solving simulation '" + self.sim.getName().toString() +"'...")
931 self.do_solve()
932
933 def console_click(self,*args):
934 try:
935 console.start(self)
936 except RuntimeError,e:
937 self.reporter.reportError("Unable to start console: "+str(e));
938
939 def integrate_click(self,*args):
940 self.do_integrate()
941
942 def check_click(self,*args):
943 self.do_check()
944 #self.reporter.reportError("CHECK clicked")
945
946 def preferences_click(self,*args):
947 if not self.sim:
948 self.reporter.reportError("No simulation created yet!");
949
950 _paramswin = SolverParametersWindow(self)
951 _paramswin.show()
952
953 def methodrun_click(self,*args):
954 _sel = self.methodsel.get_active_text()
955 if _sel:
956 _method = None
957 _methods = self.sim.getType().getMethods()
958 for _m in _methods:
959 if _m.getName()==_sel:
960 _method = _m
961 if not _method:
962 self.reporter.reportError("Method is not valid")
963 return
964 self.do_method(_method)
965 else:
966 self.reporter.reportError("No method selected")
967
968 def auto_toggle(self,button,*args):
969 self.is_auto = button.get_active()
970 if hasattr(self,'automenu'):
971 self.automenu.set_active(self.is_auto)
972 else:
973 raise RuntimeError("no automenu")
974
975 #if self.is_auto:
976 # self.reporter.reportSuccess("Auto mode is now ON")
977 #else:
978 # self.reporter.reportSuccess("Auto mode is now OFF")
979
980 def on_file_quit_click(self,*args):
981 self.do_quit()
982
983 def on_tools_auto_toggle(self,checkmenuitem,*args):
984 self.is_auto = checkmenuitem.get_active()
985 self.autotoggle.set_active(self.is_auto)
986
987 def on_help_about_click(self,*args):
988 _xml = gtk.glade.XML(self.glade_file,"aboutdialog")
989 _about = _xml.get_widget("aboutdialog")
990 _about.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
991 _about.set_transient_for(self.window);
992 _about.set_version(config.VERSION)
993 _about.run()
994 _about.destroy()
995
996 def on_help_contents_click(self,*args):
997 _help = Help(HELP_ROOT)
998 _help.run()
999
1000 def on_find_fixable_variables_activate(self,*args):
1001 v = self.sim.getFixableVariables()
1002 text = "Fixable Variables"
1003 title = text
1004 text += "\n"
1005 if len(v):
1006 for var in v:
1007 text += "\n%s"%var
1008 else:
1009 text += "\nnone"
1010 _dialog = InfoDialog(self,self.window,text,title)
1011 _dialog.run()
1012
1013 def on_show_external_functions_activate(self,*args):
1014 v = self.library.getExtMethods()
1015 text = "External Functions"
1016 title = text
1017 text +="\nHere is the list of external functions currently present in"
1018 text +=" the Library:"
1019
1020 if len(v):
1021 for ext in v:
1022 text += "\n\n%s (%d inputs, %d outputs):" % \
1023 (ext.getName(), ext.getNumInputs(), ext.getNumOutputs())
1024 text += "\n%s" % ext.getHelp()
1025 else:
1026 text +="\n\nNone"
1027 _dialog = InfoDialog(self,self.window,text,title)
1028 _dialog.run()
1029
1030 def create_observer(self,name=None):
1031 if name==None:
1032 name="New Observer"
1033
1034 _xml = gtk.glade.XML(self.glade_file,"observervbox");
1035 _label = gtk.Label();
1036 _label.set_text(name)
1037 _tab = self.maintabs.append_page(_xml.get_widget("observervbox"),_label);
1038 self.observers.append(ObserverTab(_xml, name, self, _tab))
1039
1040 def sync_observers(self):
1041 for _o in self.observers:
1042 _o.sync()
1043
1044 def delete_event(self, widget, event):
1045 self.do_quit()
1046 return False
1047
1048 def observe(self,instance):
1049 if len(self.observers) > 1:
1050 self.reporter.reportError("Not implemented: multiple observers (currently %d observers)" %
1051 len(self.observers) )
1052 return
1053 if len(self.observers) ==0:
1054 self.create_observer()
1055 _observer = self.observers[0]
1056 _observer.add_instance(instance)
1057
1058 if __name__ == "__main__":
1059 b = Browser();
1060 b.run()

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