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

Contents of /trunk/pygtk/gtkbrowser.py

Parent Directory Parent Directory | Revision Log Revision Log


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

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