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

Contents of /trunk/pygtk/gtkbrowser.py

Parent Directory Parent Directory | Revision Log Revision Log


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

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