def __init__( self, aSession ): OsogoWindow.__init__( self, aSession, 'LoggerWindow.glade' ) self.theDefaultSaveDirectory='Data' self.thePopupMenu = PopupMenu( self ) self.theList = [] # --------------------------------------------------------------- # Creates save file selection # --------------------------------------------------------------- self.theSaveDirectorySelection = FileSelection( 'Select File' ) self.theSaveDirectorySelection.ok_button.connect('clicked', self.changeSaveDirectory) self.theSaveDirectorySelection.cancel_button.connect('clicked', self.closeParentWindow)
def __init__( self, dirname, data, pluginmanager, root=None ): #initializa variables: #initiates OsogoPluginWindow OsogoPluginWindow.__init__( self, dirname, data, pluginmanager, root ) self.thePluginManager = pluginmanager self.theDataGenerator = self.thePluginManager.theSession.getDataGenerator() self.displayedFullPNStringList = [] #get session self.theSession = self.thePluginManager.theSession self.theViewType = MULTIPLE self.isControlShown = False self.theSaveDirectorySelection = FileSelection( 'Select File' ) self.theSaveDirectorySelection.ok_button.connect('clicked', self.changeSaveDirectory) self.theSaveDirectorySelection.cancel_button.connect('clicked', self.closeParentWindow)
class TracerWindow( OsogoPluginWindow ): def __init__( self, dirname, data, pluginmanager, root=None ): #initializa variables: #initiates OsogoPluginWindow OsogoPluginWindow.__init__( self, dirname, data, pluginmanager, root ) self.thePluginManager = pluginmanager self.theDataGenerator = self.thePluginManager.theSession.getDataGenerator() self.displayedFullPNStringList = [] #get session self.theSession = self.thePluginManager.theSession self.theViewType = MULTIPLE self.isControlShown = False self.theSaveDirectorySelection = FileSelection( 'Select File' ) self.theSaveDirectorySelection.ok_button.connect('clicked', self.changeSaveDirectory) self.theSaveDirectorySelection.cancel_button.connect('clicked', self.closeParentWindow) def openWindow(self): OsogoPluginWindow.openWindow(self) #self.openWindow() self.theListWindow = self['clist1'] self.theTopFrame = self['top_frame'] self.theVbox2= self['vbox2'] self.thePaned = self['vpaned1'] self.theDrawingArea = self['drawingarea1'] self.theEntry = self['entry1'] self.theListStore = gtk.ListStore(gobject.TYPE_BOOLEAN,\ gobject.TYPE_OBJECT, gobject.TYPE_BOOLEAN,\ gobject.TYPE_BOOLEAN, gobject.TYPE_STRING ) self.theListWindow.set_model( self.theListStore ) onoffRenderer = gtk.CellRendererToggle() onoffRenderer.connect( 'toggled', self.onoffTogglePressed, self.theListStore ) loggerRenderer = gtk.CellRendererToggle() loggerRenderer.connect( 'toggled', self.loggerTickBoxChecked, self.theListStore ) pixbufRenderer = gtk.CellRendererPixbuf() xaxisRenderer = gtk.CellRendererToggle() xaxisRenderer.connect( 'toggled', self.xaxisToggled, self.theListStore ) pixBufColumn = gtk.TreeViewColumn( 'color', pixbufRenderer, pixbuf = COL_PIX ) fullpnColumn = gtk.TreeViewColumn( 'trace', gtk.CellRendererText(), text = COL_TXT ) loggerColumn = gtk.TreeViewColumn( 'lg', loggerRenderer, active=COL_LOG ) onoffColumn = gtk.TreeViewColumn( 'on', onoffRenderer, active = COL_ON ) xaxisColumn = gtk.TreeViewColumn ( 'x', xaxisRenderer, active = COL_X ) pixBufColumn.set_resizable( True ) fullpnColumn.set_resizable( True ) loggerColumn.set_resizable( True ) onoffColumn.set_resizable( True ) xaxisColumn.set_resizable( True ) self.theListWindow.append_column( onoffColumn ) self.theListWindow.append_column( pixBufColumn ) self.theListWindow.append_column( loggerColumn ) self.theListWindow.append_column( xaxisColumn ) self.theListWindow.append_column( fullpnColumn ) self.theScrolledWindow = self['scrolledwindow1'] self.theFixed = self['fixed1'] self.theListSelection = self.theListWindow.get_selection() self.theListSelection.set_mode( gtk.SELECTION_MULTIPLE ) self.theWindow = self.getWidget( self.__class__.__name__ ) #determine plotsize self.thePlotWidget = self.theDrawingArea #init plotter instance self.thePlotInstance = Plot( self, self.getParent(), self.thePlotWidget ) #attach plotterwidget to window aWindowWidget = self.getWidget( 'frame8' ) self.noHandle = False aWindowWidget.show_all() #add handlers to buttons self.theListWindow.connect( "button-press-event", self.buttonPressedOnList) self.setIconList( os.path.join( config.GLADEFILE_PATH, "ecell.png" ), os.path.join( config.GLADEFILE_PATH, "ecell32.png" ) ) #addtrace to plot self.addTraceToPlot( self.getFullPNList() ) #sets stripinterval, disable history buttons self.theEntry.set_text( str(self.thePlotInstance.getStripInterval()) ) self.theEntry.connect( 'activate', self.stripIntervalChangedEnter ) self.theEntry.connect( 'focus_out_event', self.stripIntervalChanged ) if not self.isStandAlone(): self.minimize() self.thePluginManager.appendInstance( self ) self.showHistory() def update(self): self.thePlotInstance.update() # later update value shown def createLogger( self, fpnlist ): if self.theSession.isRunning(): return logPolicy = self.theSession.getLogPolicyParameters() for fpn in fpnlist: if not self.hasLogger(fpn): try: aLoggerStub = self.theSession.createLoggerStub( fpn ) aLoggerStub.setLoggerPolicy( logPolicy ) aLoggerStub.create() except: self.theSession.message( 'Error while creating logger\n logger for ' + fpn + ' not created\n' ) else: self.theSession.message( "Logger created for " + fpn ) #self.checkHistoryButton() self.thePluginManager.updateFundamentalWindows() def requestData( self, numberOfElements ): for aSeries in self.thePlotInstance.getDataSeriesList(): self.theDataGenerator.requestData( aSeries, numberOfElements ) def requestDataSlice( self, aStart, anEnd, aRequiredResolution ): for aSeries in self.thePlotInstance.getDataSeriesList(): self.theDataGenerator.requestDataSlice( aSeries, aStart, anEnd, aRequiredResolution ) def requestNewData( self, aRequiredResolution ): for aSeries in self.thePlotInstance.getDataSeriesList(): self.theDataGenerator.requestNewData( aSeries, aRequiredResolution ) def allHasLogger( self ): loggerList = self.theSession.getLoggerList() for aSeries in self.thePlotInstance.getDataSeriesList(): if aSeries.getFullPNString() not in loggerList: return False return True # ======================================================================== def hasLogger(self, aFullPNString): loggerlist=self.theSession.getLoggerList() return aFullPNString in loggerlist # ======================================================================== def appendRawFullPNList( self, aRawFullPNList ): """overwrites superclass method aRawFullPNList -- a RawFullPNList to append (RawFullPNList) Returns None """ # calls superclass's method OsogoPluginWindow.appendRawFullPNList( self, aRawFullPNList ) # creates FullPNList to plot aFullPNList = map( self.supplementFullPN, aRawFullPNList ) # appends FullPNList as plot data self.addTraceToPlot( aFullPNList ) # ======================================================================== def refreshLoggers(self): #refreshes loggerlist iter = self.theListStore.get_iter_first() while iter != None: text = self.theListStore.get_value( iter, COL_TXT ) if self.hasLogger( text ): fixed=True else: fixed=False self.theListStore.set(iter, COL_LOG, fixed) iter = self.theListStore.iter_next(iter) # ======================================================================== def addTraceToPlot(self,aFullPNList): #checks that newpn has logger if mode is history #calls superclass pass_flag = 0 if self.theSession.getParameter('log_all_traces'): for aFullPN in aFullPNList: aFullPNString = createFullPNString( aFullPN ) self.createLogger( [aFullPNString] ) if self.thePlotInstance.getStripMode() == 'history': for aFullPN in aFullPNList: aFullPNString= createFullPNString( aFullPN) if not self.hasLogger(aFullPNString): self.theSession.message(aFullPNString+" doesn't have associated logger.") pass_flag = 1 if pass_flag==1: return -1 pass_list = [] for aFullPN in aFullPNList: aFullPNString = createFullPNString( aFullPN ) if aFullPNString in self.displayedFullPNStringList: continue #gets most recent value #check whether there's enough room left if len(self.displayedFullPNStringList) < self.thePlotInstance.getMaxTraces(): #adds trace to plotinstance,clist, add to displaylist, colorlist aValue = self.getLatestData( aFullPNString ) if aValue != None: self.displayedFullPNStringList.append( aFullPNString ) pass_list.append( aFullPNString ) else: self.theSession.message('%s cannot be displayed, because it is not numeric\n' % aFullPNString) added_list = self.thePlotInstance.addTrace( pass_list ) self.addTraceToList( added_list ) #self.checkHistoryButton() #self.checkRemoveButton() # ======================================================================== def getLatestData( self, fpn ): value = self.theSession.getEntityProperty( fpn ) if not operator.isNumberType( value): return None time = self.theSession.getCurrentTime() return nu.array( [time,value, value, value, value] ) # ======================================================================== # def checkRemoveButton( self ): # remove_button = self['button9'] # if len( self.displayedFullPNStringList ) > 1: # remove_button.set_sensitive( True ) # else: # remove_button.set_sensitive( False ) # ======================================================================== def getSelected(self): self.selectionList=[] self.theListSelection.selected_foreach(self.selection_function) return self.selectionList # ======================================================================== def selection_function( self, model, path, iter ): text = self.theListStore.get_value( iter, COL_TXT ) self.selectionList.append([text,iter]) # ======================================================================== def addTraceToList( self, added_list ): xAxis = self.thePlotInstance.getXAxisFullPNString() for fpn in added_list: iter=self.theListStore.append() self.noHandle = True aSeries = self.thePlotInstance.getDataSeries( fpn ) self.theListStore.set_value( iter, COL_PIX, aSeries.getPixBuf() ) #set pixbuf self.theListStore.set_value( iter, COL_TXT, fpn ) #set text self.theListStore.set_value( iter, COL_ON, aSeries.isOn() ) #trace is on by default self.theListStore.set_value( iter, COL_X, fpn == xAxis ) #set text self.noHandle = False self.refreshLoggers() # ======================================================================== def changeTraceColor(self): selected_list = self.getSelected() if len( selected_list ) > 0: fpn = selected_list[0][0] iter = selected_list[0][1] aSeries = self.thePlotInstance.getDataSeries( fpn ) aSeries.changeColor() pixbuf = aSeries.getPixBuf() self.theListStore.set_value( iter, COL_PIX, pixbuf ) def removeTraceFromList(self,aFullPNString): pass def shrink_to_fit(self): pass # ======================================================================== def maximize(self): if self.theTopFrame!= self.theVbox2.get_parent(): if self.isStandAlone(): self.__adjustWindowHeight( - self.shiftWindow ) self.theTopFrame.remove( self.theDrawingArea ) self.thePaned.add( self.theDrawingArea ) self.theTopFrame.add( self.theVbox2 ) self.thePlotInstance.showControl( True ) # ======================================================================== def minimize(self): self.thePlotInstance.showControl( False ) if self.theTopFrame== self.theVbox2.get_parent(): if self.isStandAlone(): dividerPos = self.thePaned.get_position() panedHeight = self.thePaned.get_allocation()[3] self.shiftWindow = panedHeight - dividerPos self.theTopFrame.remove( self.theVbox2 ) self.thePaned.remove( self.theDrawingArea ) self.theTopFrame.add( self.theDrawingArea ) if self.isStandAlone(): self.__adjustWindowHeight( self.shiftWindow ) def __adjustWindowHeight ( self, deltaHeight ): aWindow = self.getParent()['TracerWindow'] windowAlloc = aWindow.get_allocation() windowHeight = windowAlloc[3] windowWidth = windowAlloc[2] aWindow.resize( windowWidth , windowHeight - deltaHeight ) # ======================================================================== def setScale( self, theOrientation, theScaleType ): """ sets scale type of the axis defined by orientation theOrientation is either "Horizontal" or "Vertical" theScaleType is either "Linear" or "Log10" """ self.thePlotInstance.changeScale( theOrientation, theScaleType ) # ======================================================================== def setXAxis( self, theFullPN ): """ sets XAxis either a FullPN String or "time" literal """ if theFullPN != "Time": if theFullPN not in self.thePlotInstance.getDataSeriesNames(): return self.thePlotInstance.setXAxis( theFullPN ) #switch off trace anIter=self.theListStore.get_iter_first( ) while True: if anIter == None: return None aTitle = self.theListStore.get_value(anIter, COL_TXT ) # if aTitle == theFullPN: self.noHandle = True aSeries = self.thePlotInstance.getDataSeries( aTitle ) self.theListStore.set_value( anIter, COL_ON, aSeries.isOn() ) self.theListStore.set_value( anIter, COL_X, theFullPN == aTitle ) self.noHandle = False anIter=self.theListStore.iter_next( anIter ) # ======================================================================== def setStripInterval( self, anInterval ): """ sets striptinterval of graph to anInterval """ self.theEntry.set_text( str( anInterval ) ) self.stripIntervalChanged(None, None ) # ======================================================================== def showHistory (self): """ changes Plot to History mode e.g. draws plot from logger information will fall back to strip mode if not each and every FullPN has a logger returns None """ if self.thePlotInstance.getStripMode() != 'history': self.toggleStripAction( None ) # ======================================================================== def showStrip (self): """ changes Plot to Strip mode e.g. shows the most recent datapaoints spanning an interval set by StripInterval """ if self.thePlotInstance.getStripMode() == 'history': self.toggleStripAction( None ) # ======================================================================== def logAll(self): """ creates logger for all traces on TracerWindow """ self.logAllAction( None ) # ======================================================================== #def setTraceColor(aFullPN, red, green, blue): #TBD # ======================================================================== def setTraceVisible (self, aFullPNString, aBoolean): """ sets visible trace of identified by FullPNString aBoolean: True - Display False - Don't display trace """ if aFullPNString not in self.thePlotInstance.getDataSeriesNames(): return aSeries = self.thePlotInstance.getDataSeries( aFullPNString ) currentState = aSeries.isOn() if currentState == aBoolean: return None anIter=self.theListStore.get_iter_first() while True: if anIter == None: return None aTitle = self.theListStore.get_value(anIter, COL_TXT ) if aTitle == aFullPNString: aSeries = self.thePlotInstance.getDataSeries( aFullPNString ) if aBoolean: aSeries.switchOn() else: aSeries.switchOff() self.noHandle = True self.theListStore.set_value( anIter, COL_ON, aSeries.isOn() ) self.noHandle = False self.thePlotInstance.totalRedraw() break anIter=self.theListStore.iter_next( anIter ) # ======================================================================== def zoomIn (self, x0,x1, y0, y1 ): """ magnifies a rectangular area of Plotarea bordered by x0,x1,y0,y1 """ if x1<0 or x1<=x0 or y1<=y0: self.thePluginManager.theSession.message("bad arguments") return self.thePlotInstance.zoomIn( [float(x0), float(x1)], [float(y1), float(y0)]) # ======================================================================== def zoomOut(self, aNum = 1): """ zooms out aNum level of zoom ins """ for i in range(0, aNum): self.thePlotInstance.zoomOut() # ======================================================================== def showControl ( self ): """ shows Control and sets plot to its normal size """ self.maximize() # ======================================================================== def hideControl (self ): """doesn't change Plot size, but hides Control components """ self.minimize() # ======================================================================== def checkRun( self ): if self.theSession.isRunning(): # displays a Confirm Window. aMessage = "Cannot create new logger, because simulation is running.\n" aMessage += "Please stop simulation if you want to create a logger" aDialog = ConfirmWindow(OK_MODE,aMessage,'Warning!') return True return False #---------------------------------------------- #SIGNAL HANDLERS #------------------------------------------------- #---------------------------------------------- #this signal handler is called when ENTER is pushed on entry1 #------------------------------------------------- def stripIntervalChangedEnter( self, obj ): self.stripIntervalChanged( obj, None ) #-------------------------------------------------------- #this signal handler is called when TAB is presses on entry1 #--------------------------------------------------------- def stripIntervalChanged(self, obj, event): #this is an event handler again #get new value #call plotterinstance try: a = float( self.theEntry.get_text() ) except ValueError: self.theSession.message("Enter a valid number, please.") self.theEntry.set_text( str( self.thePlotInstance.getstripinterval() ) ) else: self.thePlotInstance.setStripInterval( a ) #-------------------------------------------------------- #this signal handler is called when mousebutton is pressed over the fullpnlist #--------------------------------------------------------- def buttonPressedOnList(self, aWidget, anEvent): if anEvent.button == 3: # user menu: remove trace, log all, save data,edit policy, hide ui, change color selectedList = self.getSelected() allHasLogger = True xAxisSelected = False xAxis = self.thePlotInstance.getXAxisFullPNString() for aSelection in selectedList: if not self.hasLogger( aSelection[0] ): allHasLogger = False if aSelection[0] == xAxis: xAxisSelected = True theMenu = gtk.Menu() listCount = len( self.displayedFullPNStringList ) if len( selectedList ) > 0 and listCount - len(selectedList ) > 0 and not xAxisSelected: removeItem = gtk.MenuItem( "Remove" ) removeItem.connect( "activate", self.removeTraceAction ) theMenu.append( removeItem ) theMenu.append( gtk.SeparatorMenuItem() ) if allHasLogger and listCount> 0: logItem = gtk.MenuItem( "Save data" ) logItem.connect( "activate", self.__saveData, selectedList ) theMenu.append( logItem ) editPolicy = gtk.MenuItem( "Edit policy" ) editPolicy.connect( "activate", self.__editPolicy, selectedList ) theMenu.append( editPolicy ) theMenu.append( gtk.SeparatorMenuItem() ) if len( selectedList ) == 1: toggleColorItem = gtk.MenuItem( "Toggle color" ) toggleColorItem.connect("activate", self.__toggleColor, selectedList ) theMenu.append( toggleColorItem ) theMenu.show_all() theMenu.popup( None, None, None, 1, 0 ) def __editPolicy( self, *args ): fpnList = args[1] if len( fpnList ) == 1: # get loggerpolicy aLoggerStub = self.theSession.createLoggerStub( fpnList[0][0] ) aLogPolicy = aLoggerStub.getLoggerPolicy() else: aLogPolicy = [ 1, 0, 0, 0 ] newLogPolicy = self.theSession.openLogPolicyWindow( aLogPolicy, "Set log policy for selected loggers" ) if newLogPolicy == None: return for anItem in fpnList: aFullPN = anItem[0] aLoggerStub = self.theSession.createLoggerStub( aFullPN ) aLoggerStub.setLoggerPolicy( newLogPolicy ) def __toggleColor( self, *args ): self.changeTraceColor() def __saveData( self, *args ): self.theSaveDirectorySelection.show_all() def changeSaveDirectory( self, obj ): aSaveDirectory = self.theSaveDirectorySelection.get_filename() self.theSaveDirectorySelection.hide() selectedFullPNList = [] for anItem in self.getSelected(): selectedFullPNList.append( anItem[0] ) # If same directory exists. if os.path.isdir(aSaveDirectory): aConfirmMessage = "%s directory already exist.\n Would you like to override it?"%aSaveDirectory confirmWindow = ConfirmWindow(1,aConfirmMessage) if confirmWindow.return_result() == 0: pass else: return None # If same directory dose not exists. else: try: os.mkdir(aSaveDirectory) except: aErrorMessage='couldn\'t create %s!\n'%aSaveDirectory aWarningWindow = ConfirmWindow(0,aErrorMessage) return None try: self.theSession.saveLoggerData( selectedFullPNList, aSaveDirectory, -1, -1, -1 ) except: anErrorMessage = "Error : could not save " aWarningWindow = ConfirmWindow(0,anErrorMessage) return None def closeParentWindow( self, obj ): aParentWindow = self.theSaveDirectorySelection.cancel_button.get_parent_window() aParentWindow.hide() #-------------------------------------------------------- #this signal handler is called when an on-off checkbox is pressed over of the fullpnlist #--------------------------------------------------------- def onoffTogglePressed(self,cell, path, model): if self.noHandle: return iter = model.get_iter( (int( path ), ) ) text = self.theListStore.get_value( iter, COL_TXT ) aSeries = self.thePlotInstance.getDataSeries( text ) if aSeries.isOn( ): aSeries.switchOff() else: aSeries.switchOn() self.thePlotInstance.totalRedraw() self.noHandle = True self.theListStore.set_value( iter, COL_ON, aSeries.isOn() ) self.noHandle = False #-------------------------------------------------------- #this signal handler is called when create logger checkbox is pressed over the fullpnlist #--------------------------------------------------------- def loggerTickBoxChecked(self, cell, path, model): if self.noHandle: return iter = model.get_iter( ( int ( path ), ) ) fixed = model.get_value( iter, COL_LOG ) text = self.theListStore.get_value( iter, COL_TXT ) if fixed == False: if self.checkRun(): return self.createLogger( [text] ) self.refreshLoggers() #-------------------------------------------------------- #this signal handler is called when xaxis is toggled #-------------------------------------------------------- def xaxisToggled(self, cell, path, model): if self.noHandle: return iter = model.get_iter( ( int ( path ), ) ) fixed = model.get_value( iter, COL_X ) text = self.theListStore.get_value( iter, COL_TXT ) if fixed == False: self.setXAxis( text ) else: self.setXAxis( "Time" ) #-------------------------------------------------------- #this signal handler is called when "Remove Trace" button is pressed #--------------------------------------------------------- def removeTraceAction(self, *args ): #identify selected FullPNs fpnlist=[] selected_list=self.getSelected() for aselected in selected_list: #remove from fullpnlist if len(self.displayedFullPNStringList)==1: break FullPNList = self.theRawFullPNList[:] for afullpn in FullPNList: if aselected[0] == createFullPNString( afullpn): self.theRawFullPNList.remove(afullpn) break #remove from displaylist self.displayedFullPNStringList.remove( aselected[0] ) fpnlist.append( aselected[0] ) self.theListStore.remove( aselected[1] ) #remove from plotinstance self.thePlotInstance.removeTrace( fpnlist ) #delete selected from list #self.checkHistoryButton() #self.checkRemoveButton() #-------------------------------------------------------- #this signal handler is called when "Log All" button is pressed #--------------------------------------------------------- def logAllAction(self,obj): if not self.checkRun(): return #creates logger in simulator for all FullPNs self.createLogger( self.displayedFullPNStringList ) self.refreshLoggers() #-------------------------------------------------------- #this signal handler is called when "Show History" button is toggled #--------------------------------------------------------- def toggleStripAction(self, obj): #if history, change to strip, try to get data for strip interval stripmode = self.thePlotInstance.getStripMode() if stripmode == 'history': self.thePlotInstance.setStripMode( 'strip' ) else: pass_flag = True for fpn in self.displayedFullPNStringList: if not self.hasLogger(fpn): pass_flag = False break if pass_flag: self.thePlotInstance.setStripMode( 'history' ) else: self.theSession.message("can't change to history mode, because not every trace has logger.\n") #-------------------------------------------------------- #this signal handler is called when "Minimize" button is pressed #-------------------------------------------------------- def hideControlAction(self,button_obj): self.minimize()
def openFileDlg(self, aType, aTarget): """displays FileSelection aType --- 'Load'/'Save' (str) aTarget --- 'Model'/'Script'/'SBML' (str) Return None [Note]:When FileSelection is already created, moves it to the top of desktop, like singleton pattern. """ # When the FileSelection is already displayed, moves it to the top of desktop. if self.theFileSelection != None: self.theFileSelection.present() # When the FileSelection is not created yet, creates and displays it. else: # creates FileSelection self.theFileSelection = FileSelection() self.theFileSelection.connect("delete_event", self.__deleteFileSelection) self.theFileSelection.cancel_button.connect("clicked", self.__deleteFileSelection) aPixbuf16 = gtk.gdk.pixbuf_new_from_file(os.path.join(config.GLADEFILE_PATH, "ecell.png")) aPixbuf32 = gtk.gdk.pixbuf_new_from_file(os.path.join(config.GLADEFILE_PATH, "ecell32.png")) self.theFileSelection.set_icon_list(aPixbuf16, aPixbuf32) # when 'Load Model' is selected if aType == "Load" and aTarget == "Model": self.theFileSelection.action = "open" self.theFileSelection.ok_button.connect("clicked", self.__loadData, aTarget) self.theFileSelection.complete("*.*") self.theFileSelection.set_title("Select %s File (%s)" % (aTarget, MODEL_FILE_EXTENSION)) # when 'Load Script' is selected elif aType == "Load" and aTarget == "Script": self.theFileSelection.action = "open" self.theFileSelection.ok_button.connect("clicked", self.__loadData, aTarget) self.theFileSelection.complete("*." + SCRIPT_FILE_EXTENSION) self.theFileSelection.set_title("Select %s File (%s)" % (aTarget, SCRIPT_FILE_EXTENSION)) # when 'Save Model' is selected elif aType == "Save" and aTarget == "Model": self.theFileSelection.action = "save" self.theFileSelection.ok_button.connect("clicked", self.__saveModel) self.theFileSelection.complete("*." + MODEL_FILE_EXTENSION) self.theFileSelection.set_title("Select %s File (%s)" % (aTarget, MODEL_FILE_EXTENSION)) # when 'Import SBML' is selected elif aType == "Load" and aTarget == "SBML": self.theFileSelection.action = "open" self.theFileSelection.ok_button.connect("clicked", self.__loadData, aTarget) self.theFileSelection.complete("*." + MODEL_FILE_EXTENSION) self.theFileSelection.set_title("Select %s File (%s)" % (aTarget, MODEL_FILE_EXTENSION)) # when 'Save Model' is selected elif aType == "Save" and aTarget == "SBML": self.theFileSelection.action = "save" self.theFileSelection.ok_button.connect("clicked", self.__exportSBML) self.theFileSelection.complete("*." + MODEL_FILE_EXTENSION) self.theFileSelection.set_title("Select %s File (%s)" % (aTarget, MODEL_FILE_EXTENSION)) else: raise "(%s,%s) does not match." % (aType, aTarget) # displays the created FileSelection self.theFileSelection.show_all()
class MainWindow(OsogoWindow): """MainWindow """ def __init__(self, aSession): # calls super class's constructor OsogoWindow.__init__(self, self, "MainWindow.glade") # ------------------------------------- # stores pointer to Session # ------------------------------------- self.theSession = aSession self.theMessageWindow = MessageWindow.MessageWindow() # initialize Timer components self.startTime = 0 self.tempTime = 0 self.isStarted = False self.timerVisible = False self.theLastTime = 0 self.theLastRealTime = 0 self.updateCount = 0 # initialize Indicator self.indicatorVisible = False # create datetime instance for Timer self.datetime = datetime.datetime(1970, 1, 1) def openWindow(self): # calls superclass's method OsogoWindow.openWindow(self) self.__button_update = False self.logoMovable = True self.theToolbarVisible = True self.theStatusbarVisible = True self.theMessageWindowVisible = True self.theEntityListWindowVisible = True # ------------------------------------- # create SimulationButton # ------------------------------------- self.SimulationButton = SimulationButton(self["SimulationButton"]) # --------------------------- # create logo button # --------------------------- self.logoAnimation = LogoAnimation() self["logo_animation"].add(self.logoAnimation.getImage()) # -------------------------- # initialize time entry # -------------------------- self["sec_step_entry"].set_property("xalign", 1) self["time_entry"].set_property("xalign", 1) # ------------------------------------- # creates MessageWindow # ------------------------------------- self.theMessageWindow.openWindow() self["messagearea"].add(self.theMessageWindow["top_frame"]) self.theSession.setMessageMethod(self.__printMessage) self.__expose(None, None) messageWindowSize = self.theMessageWindow.getActualSize() self.theMessageWindow["scrolledwindow1"].set_size_request(messageWindowSize[0], messageWindowSize[1]) # ------------------------------------- # append signal handlers # ------------------------------------- aHandlerMap = { # menu "load_model_menu_activate": self.__openFileDlgForLoadModel, "load_script_menu_activate": self.__openFileDlgForLoadScript, "save_model_menu_activate": self.__openFileDlgForSaveModel, "exit_menu_activate": self.__deleted, "message_window_menu_activate": self.__toggleMessageWindow, "entitylist_window_menu_activate": self.__toggleEntityListWindow, "interface_window_menu_activate": self.__displayInterfaceWindow, "entity_list_menu_activate": self.__createEntityListWindow, "logger_window_menu_activate": self.__displayLoggerWindow, "stepper_window_menu_activate": self.__displayStepperWindow, "board_window_menu_activate": self.__displayBoardWindow, "about_menu_activate": self.__displayAbout, # sbml "on_import_sbml_activate": self.__openFileDlgForImportSBML, "on_export_sbml_activate": self.__openFileDlgForExportSBML, # toolbars "simulation_button_clicked": self.__handleSimulation, "step_button_clicked": self.__stepSimulation, "on_sec_step_entry_activate": self.__setStepSizeOrSec, "on_timer_clear_button_clicked": self.__clearTimer, "on_load_model_button_clicked": self.__openFileDlgForLoadModel, "on_load_script_button_clicked": self.__openFileDlgForLoadScript, "on_save_model_button_clicked": self.__openFileDlgForSaveModel, "on_entitylist_button_clicked": self.__createEntityListWindow, "on_logger_button_toggled": self.__displayLoggerWindow, "on_message_togglebutton_toggled": self.__toggleMessageWindow, "on_stepper_button_toggled": self.__displayStepperWindow, "on_interface_button_toggled": self.__displayInterfaceWindow, "on_board_button_toggled": self.__displayBoardWindow, "logo_button_clicked": self.__displayAbout, "on_timer_button_toggled": self.__displayTimer, "on_indicator_button_toggled": self.__displayIndicator, "on_scrolledwindow1_expose_event": self.__expose, # view "on_toolbar_menu_activate": self.__displayToolbar, "on_statusbar_menu_activate": self.__displayStatusbar, "on_run_speed_indicator_activate": self.__displayIndicator, "on_timer_activate": self.__displayTimer, "on_logo_animation_menu_activate": self.__setAnimationSensitive, "on_logging_policy1_activate": self.__openLogPolicy, } self.__togglableWindows = { "BoardWindow": (self["board_window_menu"], self["board_button"].get_child()), "LoggerWindow": (self["logger_window_menu"], self["logger_button"].get_child()), "InterfaceWindow": (self["interface_window_menu"], self["interface_button"].get_child()), "StepperWindow": (self["stepper_window_menu"], self["stepper_button"].get_child()), "MessageWindow": (self["message_window_menu"], self["message_togglebutton"].get_child()), } self.addHandlers(aHandlerMap) self.setIconList( os.path.join(config.GLADEFILE_PATH, "ecell.png"), os.path.join(config.GLADEFILE_PATH, "ecell32.png") ) # display MainWindow self[self.__class__.__name__].show_all() self.present() self.theStepSizeOrSec = 1 # initializes FileSelection reference self.theFileSelection = None # initializes AboutDialog reference self.theAboutSessionMonitor = None self.openAboutSessionMonitor = False # ------------------------------------- # creates EntityListWindow # ------------------------------------- self.theEntityListWindow = self.theSession.createEntityListWindow("top_frame", self["statusbar"]) self["entitylistarea"].add(self.theEntityListWindow["top_frame"]) # -------------------- # set Timer entry # -------------------- self["timer_entry"].set_text(str(0)) self["timer_entry"].set_property("xalign", 1) self["timer_box"].hide() # --------------------- # initialize Indicator # --------------------- self["indicator_box"].hide() self.update() def __expose(self, *arg): """expose Return None """ pass def __setMenuAndButtonsStatus(self, aDataLoadedStatus): """sets initial widgets status aDataLoadedStatus -- the status of loading data (True: Model or Script is loaded / False: Not loaded) Returns None """ # toolbar self["simulation_button"].set_sensitive(aDataLoadedStatus) self["step_button"].set_sensitive(aDataLoadedStatus) self["timer_clear_button"].set_sensitive(aDataLoadedStatus) # self['load_model_button'].set_sensitive(not aDataLoadedStatus) # self['load_script_button'].set_sensitive(not aDataLoadedStatus) self["save_model_button"].set_sensitive(aDataLoadedStatus) self["entitylist_button"].set_sensitive(aDataLoadedStatus) self["logger_button"].set_sensitive(aDataLoadedStatus) self["stepper_button"].set_sensitive(aDataLoadedStatus) self["interface_button"].set_sensitive(aDataLoadedStatus) self["board_button"].set_sensitive(aDataLoadedStatus) self["indicator_button"].set_sensitive(aDataLoadedStatus) self["timer_button"].set_sensitive(aDataLoadedStatus) # file menu # self['load_model_menu'].set_sensitive(not aDataLoadedStatus) # self['load_script_menu'].set_sensitive(not aDataLoadedStatus) self["save_model_menu"].set_sensitive(aDataLoadedStatus) self["import_sbml"].set_sensitive(not aDataLoadedStatus) self["export_sbml"].set_sensitive(aDataLoadedStatus) # window menu self["logger_window_menu"].set_sensitive(aDataLoadedStatus) self["stepper_window_menu"].set_sensitive(aDataLoadedStatus) self["interface_window_menu"].set_sensitive(aDataLoadedStatus) self["board_window_menu"].set_sensitive(aDataLoadedStatus) self["entity_list_menu"].set_sensitive(aDataLoadedStatus) self["save_model_menu"].set_sensitive(aDataLoadedStatus) # preferences menu self["logging_policy"].set_sensitive(aDataLoadedStatus) self["run_speed_indicator"].set_sensitive(aDataLoadedStatus) self["timer_menu"].set_sensitive(aDataLoadedStatus) self["logo_animation_menu"].set_sensitive(aDataLoadedStatus) def __openFileDlgForLoadModel(self, *arg): self.openFileDlg("Load", "Model") def __openFileDlgForLoadScript(self, *arg): # when 'Load Script' is selected self.openFileDlg("Load", "Script") def __openFileDlgForSaveModel(self, *arg): # when 'Save Model' is selected self.openFileDlg("Save", "Model") def __openFileDlgForImportSBML(self, *arg): # when 'Import SBML' is selected self.openFileDlg("Load", "SBML") def __openFileDlgForExportSBML(self, *arg): # when 'Export SBML' is selected self.openFileDlg("Save", "SBML") def openFileDlg(self, aType, aTarget): """displays FileSelection aType --- 'Load'/'Save' (str) aTarget --- 'Model'/'Script'/'SBML' (str) Return None [Note]:When FileSelection is already created, moves it to the top of desktop, like singleton pattern. """ # When the FileSelection is already displayed, moves it to the top of desktop. if self.theFileSelection != None: self.theFileSelection.present() # When the FileSelection is not created yet, creates and displays it. else: # creates FileSelection self.theFileSelection = FileSelection() self.theFileSelection.connect("delete_event", self.__deleteFileSelection) self.theFileSelection.cancel_button.connect("clicked", self.__deleteFileSelection) aPixbuf16 = gtk.gdk.pixbuf_new_from_file(os.path.join(config.GLADEFILE_PATH, "ecell.png")) aPixbuf32 = gtk.gdk.pixbuf_new_from_file(os.path.join(config.GLADEFILE_PATH, "ecell32.png")) self.theFileSelection.set_icon_list(aPixbuf16, aPixbuf32) # when 'Load Model' is selected if aType == "Load" and aTarget == "Model": self.theFileSelection.action = "open" self.theFileSelection.ok_button.connect("clicked", self.__loadData, aTarget) self.theFileSelection.complete("*.*") self.theFileSelection.set_title("Select %s File (%s)" % (aTarget, MODEL_FILE_EXTENSION)) # when 'Load Script' is selected elif aType == "Load" and aTarget == "Script": self.theFileSelection.action = "open" self.theFileSelection.ok_button.connect("clicked", self.__loadData, aTarget) self.theFileSelection.complete("*." + SCRIPT_FILE_EXTENSION) self.theFileSelection.set_title("Select %s File (%s)" % (aTarget, SCRIPT_FILE_EXTENSION)) # when 'Save Model' is selected elif aType == "Save" and aTarget == "Model": self.theFileSelection.action = "save" self.theFileSelection.ok_button.connect("clicked", self.__saveModel) self.theFileSelection.complete("*." + MODEL_FILE_EXTENSION) self.theFileSelection.set_title("Select %s File (%s)" % (aTarget, MODEL_FILE_EXTENSION)) # when 'Import SBML' is selected elif aType == "Load" and aTarget == "SBML": self.theFileSelection.action = "open" self.theFileSelection.ok_button.connect("clicked", self.__loadData, aTarget) self.theFileSelection.complete("*." + MODEL_FILE_EXTENSION) self.theFileSelection.set_title("Select %s File (%s)" % (aTarget, MODEL_FILE_EXTENSION)) # when 'Save Model' is selected elif aType == "Save" and aTarget == "SBML": self.theFileSelection.action = "save" self.theFileSelection.ok_button.connect("clicked", self.__exportSBML) self.theFileSelection.complete("*." + MODEL_FILE_EXTENSION) self.theFileSelection.set_title("Select %s File (%s)" % (aTarget, MODEL_FILE_EXTENSION)) else: raise "(%s,%s) does not match." % (aType, aTarget) # displays the created FileSelection self.theFileSelection.show_all() def __deleteFileSelection(self, *arg): """deletes FileSelection Return None """ # deletes the reference to FileSelection if self.theFileSelection != None: self.theFileSelection.destroy() self.theFileSelection = None def __loadData(self, *arg): """loads model or script file arg[0] --- ok button of FileSelection arg[1] --- 'Model'/'Script' (str) Return None """ # checks the length of argument, but this is verbose if len(arg) < 2: return None aFileType = arg[1] aFileName = self.theFileSelection.get_filename() if os.path.isfile(aFileName): pass else: aMessage = " Error ! No such file. \n[%s]" % aFileName self.theSession.message(aMessage) aDialog = ConfirmWindow(OK_MODE, aMessage, "Error!") self.theFileSelection.present() return None self.__deleteFileSelection() self.theSession.message("Loading %s file %s\n" % (aFileType, aFileName)) try: if aFileType == "Model": self.theSession.loadModel(aFileName) elif aFileType == "Script": self.theSession.loadScript(aFileName) elif aFileType == "SBML": self.theSession.importSBML(aFileName) self.theSession.updateWindows() except: # expants message window, when it is folded. if self.exists(): if not (self["message_togglebutton"].get_child()).get_active(): (self["message_togglebutton"].get_child()).set_active(True) # displays confirm window aMessage = "Can't load [%s]\nSee MessageWindow for details." % aFileName aDialog = ConfirmWindow(OK_MODE, aMessage, "Error!") # displays message on MessageWindow aMessage = "Can't load [%s]" % aFileName self.theSession.message(aMessage) anErrorMessage = "\n".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) self.theSession.message(anErrorMessage) def __saveModel(self, *arg): # gets file name aFileName = self.theFileSelection.get_filename() # when the file already exists if os.path.isfile(aFileName): # displays confirm window aMessage = "Would you like to replace the existing file? \n[%s]" % aFileName aDialog = ConfirmWindow(OKCANCEL_MODE, aMessage, "Confirm File Overwrite") # when canceled, does nothing if aDialog.return_result() != OK_PRESSED: # does nothing return None # when ok is pressed, overwrites it. # deletes FileSelection self.__deleteFileSelection() try: # displays save message self.theSession.message("Save model file %s\n" % aFileName) # saves Model self.theSession.saveModel(aFileName) except: # expants message window, when it is folded. if not (self["message_togglebutton"].get_child()).get_active(): (self["message_togglebutton"].get_child()).set_active(True) # displays confirm window aMessage = "Can't save [%s]\nSee MessageWindow for details." % aFileName aDialog = ConfirmWindow(OK_MODE, aMessage, "Error!") # displays error message of MessageWindow self.theSession.message("Can't save [%s]" % aFileName) anErrorMessage = "\n".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) self.theSession.message(anErrorMessage) # updates self.update() self.theSession.updateFundamentalWindows() def __exportSBML(self, *arg): # gets file name aFileName = self.theFileSelection.get_filename() # when the file already exists if os.path.isfile(aFileName): # displays confirm window aMessage = "Would you like to replace the existing file? \n[%s]" % aFileName aDialog = ConfirmWindow(OKCANCEL_MODE, aMessage, "Confirm File Overwrite") # when canceled, does nothing if aDialog.return_result() != OK_PRESSED: # does nothing return None # when ok is pressed, overwrites it. # deletes FileSelection self.__deleteFileSelection() try: # displays save message self.theSession.message("Export SBML file %s\n" % aFileName) # saves Model self.theSession.exportSBML(aFileName) except: # expants message window, when it is folded. if not (self["message_togglebutton"].get_child()).get_active(): (self["message_togglebutton"].get_child()).set_active(True) # displays confirm window aMessage = "Can't save [%s]\nSee MessageWindow for details." % aFileName aDialog = ConfirmWindow(OK_MODE, aMessage, "Error!") # displays error message of MessageWindow self.theSession.message("Can't export [%s]" % aFileName) anErrorMessage = "\n".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) self.theSession.message(anErrorMessage) # updates self.update() self.theSession.updateFundamentalWindows() def __deleted(self, *arg): """When delete_event happens or exit menu is selected, this method is called. """ running_flag = False if self.theSession.theRunningFlag: # stop simulation temporarily self.theSession.stop() running_flag = True if self.theSession.theSession is not None: # If there is no logger data, exit this program. if len(self.theSession.getLoggerList()) != 0: aMessage = "Are you sure you want to quit?" aTitle = "Question" # Popup confirm window, and check user request aDialog = ConfirmWindow(1, aMessage, aTitle) # ok is pressed if aDialog.return_result() != OK_PRESSED: if running_flag: self.theSession.run() return True self.setStopState() self.close() self.theSession.QuitGUI() return True def close(self): """ restores message method and closes window """ self.theSession.restoreMessageMethod() if self.theSession.theSession is not None: self.theEntityListWindow.update() self.theEntityListWindow.close() OsogoWindow.close(self) def setStartState(self): self.SimulationButton.setCurrentState("run") if self.logoMovable: self.logoAnimation.start() self.isStarted = True self.startTime = time.time() def setStopState(self): self.SimulationButton.setCurrentState("stop") self.logoAnimation.stop() self.setTempTime() def setTempTime(self): self.tempTime = time.time() - self.startTime + self.tempTime def __handleSimulation(self, *arg): """handles simulation arg[0] --- simulation button (gtk.Button) Returns None """ if not self.exists(): return if self.SimulationButton.getCurrentState() == "stop": self.setStartState() self.theSession.run() elif self.SimulationButton.getCurrentState() == "run": self.setStopState() self.theSession.stop() def handleSimulation(self): """ handles simulation """ self.__handleSimulation(self, None) def __stepSimulation(self, *arg): """steps simulation arg[0] --- stop button (gtk.Button) Returns None if step measure is second, then Session.run() if step measure is step than Session.step () """ if self.getStepType(): if self.SimulationButton.getCurrentState() == "stop": self.setStartState() self.theSession.run(self.getStepSize()) self.setStopState() else: self.theSession.run(self.getStepSize()) self.setTempTime() else: if self.SimulationButton.getCurrentState() == "stop": self.setStartState() self.theSession.step(self.getStepSize()) self.setStopState() else: self.theSession.step(self.getStepSize()) self.setTempTime() def stepSimulation(self): """ steps simulation """ self.__stepSimulation(self, None) def getStepType(self): """ returns state of sec radiobutton True: seconds False: steps """ return self["sec_radiobutton"].get_active() def setStepType(self, aState): """ sets Step Type radiobutton state values for aState True : seconds False : step """ if aState == True: self["sec_radiobutton"].set_active(True) if aState == False: self["sec_radiobutton"].set_active(False) def getStepSize(self): """ returns user or script specifid step size """ self.__setStepSizeOrSec(self, None) return self.theStepSizeOrSec def setStepSize(self, num): """ sets Stepsize entry box to num """ self["sec_step_entry"].set_text(str(num)) self.__setStepSizeOrSec(self, None) def __setStepSizeOrSec(self, *arg): # gets the inputerd characters from the GtkEntry. aNewValue = self["sec_step_entry"].get_text().strip() try: # converts string to float aNewValue = float(aNewValue) # when string can't be converted to float except ValueError: # displays a Confirm Window. aMessage = '"%s" is not numerical value.' % aNewValue aMessage += "\nInput numerical character" aDialog = ConfirmWindow(OK_MODE, aMessage, "Error!") # sets the previous value self["sec_step_entry"].set_text(str(self.theStepSizeOrSec)) # when string can be converted to float else: # check for numerical constraints aMessage = "" if aNewValue <= 0: aMessage += "Input positive number.\n" # when 'step' is selected. if self["step_radiobutton"].get_active(): # step must be integer if int(aNewValue) != aNewValue: aMessage += "Input integer.\n" # convets float to int aNewValue = int(aNewValue) if len(aMessage) > 0: # aDialog = ConfirmWindow(OK_MODE,aMessage,'Error!') aDialog = ConfirmWindow(OK_MODE, aMessage, "Error!") else: self.theStepSizeOrSec = aNewValue # def getTimeSubstruction( self, aTime1, aTime ) def update(self): """updates this window Returns None """ if not self.exists(): return None # updates time aTime = self.theSession.getCurrentTime() self.theCurrentTime = aTime self["time_entry"].set_text(not math.isnan(aTime) and str(self.theCurrentTime) or "") self["sec_step_entry"].set_text(str(self.theStepSizeOrSec)) if self.SimulationButton.getCurrentState() == "run" and self.timerVisible: self["timer_entry"].set_text(self.getCurrentTime(time.time() - self.startTime + self.tempTime)) if self.indicatorVisible: if self.updateCount == 0: self.theLastTime = self.theCurrentTime self.theLastRealTime = time.time() self.updateCount += 1 if self.updateCount == 25: if aTime != self.theLastTime: self["run_speed_label"].set_text( str(round((self.theCurrentTime - self.theLastTime) / (time.time() - self.theLastRealTime), 5)) ) self.updateCount = 0 # when Model is already loaded. self.__setMenuAndButtonsStatus(self.theSession.theSession is not None) self.updateButtons() def getCurrentTime(self, aTime): theTime = self.datetime.fromtimestamp(aTime) return str(theTime.hour - 9) + " : " + str(theTime.minute) + " : " + str(theTime.second) def updateButton(self, name, state): self.__button_update = True for w in self.__togglableWindows[name]: if state != w.get_active(): w.set_active(state) self.__button_update = False def toggleWindow(self, name, state): self.updateButton(name, state) self.theSession.toggleWindow(name, state) def updateButtons(self): """ updates Buttons and menus with latest FundamentalWindow status """ if not self.exists(): return for n in self.__togglableWindows: self.updateButton(n, self.theSession.doesExist(n)) self.updateButton("MessageWindow", self.theMessageWindowVisible) def __openLogPolicy(self, *arg): """ signal handler to logging policy is called """ # get default logging policy aLogPolicy = self.theSession.getLogPolicyParameters() # open logpolicy window newLogPolicy = self.theSession.openLogPolicyWindow(aLogPolicy, "Set default log policy") if newLogPolicy != None: # save logpolicy self.theSession.setLogPolicyParameters(newLogPolicy) def __displayToolbar(self, *arg): # show Toolbar if self.theToolbarVisible: self["toolbar_handlebox"].hide() self.theToolbarVisible = False else: self["toolbar_handlebox"].show() self.theToolbarVisible = True def __displayStatusbar(self, *arg): # show Statusbar if self.theStatusbarVisible: self["statusbar"].hide() self.theStatusbarVisible = False else: self["statusbar"].show() self.theStatusbarVisible = True def __displayIndicator(self, *arg): # show Indicator if self.indicatorVisible: self["indicator_box"].hide() self.setIndicatorActive(False) self.indicatorVisible = False else: self["indicator_box"].show() self.setIndicatorActive(True) self.indicatorVisible = True self.theLastTime = self.theSession.getCurrentTime() def __displayTimer(self, *arg): # show Indicator if self.timerVisible: self["timer_box"].hide() self.setTimerActive(False) self.timerVisible = False else: self["timer_box"].show() self.setTimerActive(True) self.timerVisible = True if self.isStarted == False: self["timer_entry"].set_text("0 : 0 : 0") else: if self.SimulationButton.getCurrentState() == "stop": self["timer_entry"].set_text(self.getCurrentTime(self.tempTime)) else: self["timer_entry"].set_text(self.getCurrentTime(time.time() - self.startTime + self.tempTime)) def setIndicatorActive(self, isActive): self["run_speed_indicator"].set_active(isActive) (self["indicator_button"].get_child()).set_active(isActive) def setTimerActive(self, isActive): self["timer_menu"].set_active(isActive) (self["timer_button"].get_child()).set_active(isActive) def __displayLoggerWindow(self, *arg): if self.__button_update: return self.toggleWindow("LoggerWindow", arg[0].get_active()) def __displayStepperWindow(self, *arg): if self.__button_update: return self.toggleWindow("StepperWindow", arg[0].get_active()) def __displayInterfaceWindow(self, *arg): if self.__button_update: return self.toggleWindow("InterfaceWindow", arg[0].get_active()) def __displayBoardWindow(self, *arg): if self.__button_update: return self.toggleWindow("BoardWindow", arg[0].get_active()) def hideMessageWindow(self): self["messagehandlebox"].hide() (self["message_togglebutton"].get_child()).set_active(False) def showMessageWindow(self): self["messagehandlebox"].show() (self["message_togglebutton"].get_child()).set_active(True) def __toggleMessageWindow(self, *arg): """expands or folds MessageWindow arg[0] --- self['message_togglebutton'] or self['message_window_menu'] Returns None """ if self.__button_update: return # checks the length of argument, but this is verbose if len(arg) < 1: return None if arg[0].get_name() != "message_window_menu": anObject = arg[0].get_child() else: anObject = arg[0] # show if anObject.get_active(): self.theMessageWindowVisible = True self.showMessageWindow() else: self.theMessageWindowVisible = False self.hideMessageWindow() self.updateButtons() def __toggleEntityListWindow(self, *arg): if arg[0].get_active(): self.theEntityListWindowVisible = True self["entitylistarea"].show() else: self.theEntityListWindowVisible = False self["entitylistarea"].hide() def __displayAbout(self, *args): # show about information self.createAboutSessionMonitor() def __clearTimer(self, *arg): self["timer_entry"].set_text("0 : 0 : 0") self.tempTime = 0.0 if self.SimulationButton.getCurrentState() == "run": self.startTime = time.time() else: self.isStarted = False self.startTime = 0.0 def __setAnimationSensitive(self, *arg): if self.logoMovable: self.logoMovable = False if self.SimulationButton.getCurrentState() == "run": self.logoAnimation.stop() else: self.logoMovable = True if self.SimulationButton.getCurrentState() == "run": self.logoAnimation.start() def createAboutSessionMonitor(self): if not self.openAboutSessionMonitor: AboutSessionMonitor(self) def toggleAboutSessionMonitor(self, isOpen, anAboutSessionMonitor): self.theAboutSessionMonitor = anAboutSessionMonitor self.openAboutSessionMonitor = isOpen def openPreferences(self, *arg): """display the preference window arg[0] --- self['preferences_menu'] Return None """ # Preference Window is not implemented yet. # So, displays Warning Dialog aMessage = " Sorry ! Not implemented... [%s]\n" % "03/April/2003" aDialog = ConfirmWindow(OK_MODE, aMessage, "Sorry!") def __printMessage(self, aMessage): """prints message on MessageWindow aMessage --- a message (str or list) Return None """ # prints message on MessageWindow self.theMessageWindow.printMessage(aMessage) def __createEntityListWindow(self, *arg): anEntityListWindow = self.theSession.createEntityListWindow("EntityListWindow", self["statusbar"]) def deleted(self, *arg): """ When 'delete_event' signal is chatcked( for example, [X] button is clicked ), delete this window. Returns True """ pass
def openFileDlg(self, aType, aTarget): """displays FileSelection aType --- 'Load'/'Save' (str) aTarget --- 'Model'/'Script'/'SBML' (str) Return None [Note]:When FileSelection is already created, moves it to the top of desktop, like singleton pattern. """ # When the FileSelection is already displayed, moves it to the top of desktop. if self.theFileSelection != None: self.theFileSelection.present() # When the FileSelection is not created yet, creates and displays it. else: # creates FileSelection self.theFileSelection = FileSelection() self.theFileSelection.connect('delete_event', self.__deleteFileSelection) self.theFileSelection.cancel_button.connect( 'clicked', self.__deleteFileSelection) aPixbuf16 = gtk.gdk.pixbuf_new_from_file( os.path.join(config.GLADEFILE_PATH, 'ecell.png')) aPixbuf32 = gtk.gdk.pixbuf_new_from_file( os.path.join(config.GLADEFILE_PATH, 'ecell32.png')) self.theFileSelection.set_icon_list(aPixbuf16, aPixbuf32) # when 'Load Model' is selected if aType == 'Load' and aTarget == 'Model': self.theFileSelection.action = 'open' self.theFileSelection.ok_button.connect( 'clicked', self.__loadData, aTarget) self.theFileSelection.complete('*.' + MODEL_FILE_EXTENSION) self.theFileSelection.set_title( "Select %s File (%s)" % (aTarget, MODEL_FILE_EXTENSION)) # when 'Load Script' is selected elif aType == 'Load' and aTarget == 'Script': self.theFileSelection.action = 'open' self.theFileSelection.ok_button.connect( 'clicked', self.__loadData, aTarget) self.theFileSelection.complete('*.' + SCRIPT_FILE_EXTENSION) self.theFileSelection.set_title( "Select %s File (%s)" % (aTarget, SCRIPT_FILE_EXTENSION)) # when 'Save Model' is selected elif aType == 'Save' and aTarget == 'Model': self.theFileSelection.action = 'save' self.theFileSelection.ok_button.connect( 'clicked', self.__saveModel) self.theFileSelection.complete('*.' + MODEL_FILE_EXTENSION) self.theFileSelection.set_title( "Select %s File (%s)" % (aTarget, MODEL_FILE_EXTENSION)) # when 'Import SBML' is selected elif aType == 'Load' and aTarget == 'SBML': self.theFileSelection.action = 'open' self.theFileSelection.ok_button.connect( 'clicked', self.__loadData, aTarget) self.theFileSelection.complete('*.' + MODEL_FILE_EXTENSION) self.theFileSelection.set_title( "Select %s File (%s)" % (aTarget, MODEL_FILE_EXTENSION)) # when 'Save Model' is selected elif aType == 'Save' and aTarget == 'SBML': self.theFileSelection.action = 'save' self.theFileSelection.ok_button.connect( 'clicked', self.__exportSBML) self.theFileSelection.complete('*.' + MODEL_FILE_EXTENSION) self.theFileSelection.set_title( "Select %s File (%s)" % (aTarget, MODEL_FILE_EXTENSION)) else: raise "(%s,%s) does not match." % (aType, aTarget) # displays the created FileSelection self.theFileSelection.show_all()
class MainWindow(OsogoWindow): """MainWindow """ def __init__(self, aSession): # calls super class's constructor OsogoWindow.__init__(self, self, 'MainWindow.glade') # ------------------------------------- # stores pointer to Session # ------------------------------------- self.theSession = aSession self.theMessageWindow = MessageWindow.MessageWindow() # initialize Timer components self.startTime = 0 self.tempTime = 0 self.isStarted = False self.timerVisible = False self.theLastTime = 0 self.theLastRealTime = 0 self.updateCount = 0 # initialize Indicator self.indicatorVisible = False # create datetime instance for Timer self.datetime = datetime.datetime(1970, 1, 1) def openWindow(self): # calls superclass's method OsogoWindow.openWindow(self) self.__button_update = False self.logoMovable = True self.theToolbarVisible = True self.theStatusbarVisible = True self.theMessageWindowVisible = True self.theEntityListWindowVisible = True # ------------------------------------- # create SimulationButton # ------------------------------------- self.SimulationButton = SimulationButton(self['SimulationButton']) # --------------------------- # create logo button # --------------------------- self.logoAnimation = LogoAnimation() self['logo_animation'].add(self.logoAnimation.getImage()) # -------------------------- # initialize time entry # -------------------------- self['sec_step_entry'].set_property('xalign', 1) self['time_entry'].set_property('xalign', 1) # ------------------------------------- # creates MessageWindow # ------------------------------------- self.theMessageWindow.openWindow() self['messagearea'].add(self.theMessageWindow['top_frame']) self.theSession.setMessageMethod(self.__printMessage) self.__expose(None, None) messageWindowSize = self.theMessageWindow.getActualSize() self.theMessageWindow['scrolledwindow1'].set_size_request(\ messageWindowSize[0], messageWindowSize[1] ) # ------------------------------------- # append signal handlers # ------------------------------------- aHandlerMap = { # menu 'load_model_menu_activate': self.__openFileDlgForLoadModel, 'load_script_menu_activate': self.__openFileDlgForLoadScript, 'save_model_menu_activate': self.__openFileDlgForSaveModel, 'exit_menu_activate': self.__deleted, 'message_window_menu_activate': self.__toggleMessageWindow, 'entitylist_window_menu_activate': self.__toggleEntityListWindow, 'interface_window_menu_activate': self.__displayInterfaceWindow, 'entity_list_menu_activate': self.__createEntityListWindow, 'logger_window_menu_activate': self.__displayLoggerWindow, 'stepper_window_menu_activate': self.__displayStepperWindow, 'board_window_menu_activate': self.__displayBoardWindow, 'about_menu_activate': self.__displayAbout, #sbml 'on_import_sbml_activate': self.__openFileDlgForImportSBML, 'on_export_sbml_activate': self.__openFileDlgForExportSBML, # toolbars 'simulation_button_clicked': self.__handleSimulation, 'step_button_clicked': self.__stepSimulation, 'on_sec_step_entry_activate': self.__setStepSizeOrSec, 'on_timer_clear_button_clicked': self.__clearTimer, 'on_load_model_button_clicked': self.__openFileDlgForLoadModel, 'on_load_script_button_clicked': self.__openFileDlgForLoadScript, 'on_save_model_button_clicked': self.__openFileDlgForSaveModel, 'on_entitylist_button_clicked': self.__createEntityListWindow, 'on_logger_button_toggled': self.__displayLoggerWindow, 'on_message_togglebutton_toggled': self.__toggleMessageWindow, 'on_stepper_button_toggled': self.__displayStepperWindow, 'on_interface_button_toggled': self.__displayInterfaceWindow, 'on_board_button_toggled': self.__displayBoardWindow, 'logo_button_clicked': self.__displayAbout, 'on_timer_button_toggled': self.__displayTimer, 'on_indicator_button_toggled': self.__displayIndicator, 'on_scrolledwindow1_expose_event': self.__expose, # view 'on_toolbar_menu_activate': self.__displayToolbar, 'on_statusbar_menu_activate': self.__displayStatusbar, 'on_run_speed_indicator_activate': self.__displayIndicator, 'on_timer_activate': self.__displayTimer, 'on_logo_animation_menu_activate': self.__setAnimationSensitive, 'on_logging_policy1_activate': self.__openLogPolicy } self.__togglableWindows = { 'BoardWindow': (self['board_window_menu'], self['board_button'].get_child()), 'LoggerWindow': (self['logger_window_menu'], self['logger_button'].get_child()), 'InterfaceWindow': (self['interface_window_menu'], self['interface_button'].get_child()), 'StepperWindow': (self['stepper_window_menu'], self['stepper_button'].get_child()), 'MessageWindow': (self['message_window_menu'], self['message_togglebutton'].get_child()), } self.addHandlers(aHandlerMap) self.setIconList(os.path.join(config.GLADEFILE_PATH, "ecell.png"), os.path.join(config.GLADEFILE_PATH, "ecell32.png")) # display MainWindow self[self.__class__.__name__].show_all() self.present() self.theStepSizeOrSec = 1 # initializes FileSelection reference self.theFileSelection = None # initializes AboutDialog reference self.theAboutSessionMonitor = None self.openAboutSessionMonitor = False # ------------------------------------- # creates EntityListWindow # ------------------------------------- self.theEntityListWindow = self.theSession.createEntityListWindow( 'top_frame', self['statusbar']) self['entitylistarea'].add(self.theEntityListWindow['top_frame']) # -------------------- # set Timer entry # -------------------- self['timer_entry'].set_text(str(0)) self['timer_entry'].set_property('xalign', 1) self['timer_box'].hide() # --------------------- # initialize Indicator # --------------------- self['indicator_box'].hide() self.update() def __expose(self, *arg): """expose Return None """ pass def __setMenuAndButtonsStatus(self, aDataLoadedStatus): """sets initial widgets status aDataLoadedStatus -- the status of loading data (True: Model or Script is loaded / False: Not loaded) Returns None """ # toolbar self['simulation_button'].set_sensitive(aDataLoadedStatus) self['step_button'].set_sensitive(aDataLoadedStatus) self['timer_clear_button'].set_sensitive(aDataLoadedStatus) # self['load_model_button'].set_sensitive(not aDataLoadedStatus) # self['load_script_button'].set_sensitive(not aDataLoadedStatus) self['save_model_button'].set_sensitive(aDataLoadedStatus) self['entitylist_button'].set_sensitive(aDataLoadedStatus) self['logger_button'].set_sensitive(aDataLoadedStatus) self['stepper_button'].set_sensitive(aDataLoadedStatus) self['interface_button'].set_sensitive(aDataLoadedStatus) self['board_button'].set_sensitive(aDataLoadedStatus) self['indicator_button'].set_sensitive(aDataLoadedStatus) self['timer_button'].set_sensitive(aDataLoadedStatus) # file menu # self['load_model_menu'].set_sensitive(not aDataLoadedStatus) # self['load_script_menu'].set_sensitive(not aDataLoadedStatus) self['save_model_menu'].set_sensitive(aDataLoadedStatus) self['import_sbml'].set_sensitive(not aDataLoadedStatus) self['export_sbml'].set_sensitive(aDataLoadedStatus) # window menu self['logger_window_menu'].set_sensitive(aDataLoadedStatus) self['stepper_window_menu'].set_sensitive(aDataLoadedStatus) self['interface_window_menu'].set_sensitive(aDataLoadedStatus) self['board_window_menu'].set_sensitive(aDataLoadedStatus) self['entity_list_menu'].set_sensitive(aDataLoadedStatus) self['save_model_menu'].set_sensitive(aDataLoadedStatus) # preferences menu self['logging_policy'].set_sensitive(aDataLoadedStatus) self['run_speed_indicator'].set_sensitive(aDataLoadedStatus) self['timer_menu'].set_sensitive(aDataLoadedStatus) self['logo_animation_menu'].set_sensitive(aDataLoadedStatus) def __openFileDlgForLoadModel(self, *arg): self.openFileDlg('Load', 'Model') def __openFileDlgForLoadScript(self, *arg): # when 'Load Script' is selected self.openFileDlg('Load', 'Script') def __openFileDlgForSaveModel(self, *arg): # when 'Save Model' is selected self.openFileDlg('Save', 'Model') def __openFileDlgForImportSBML(self, *arg): # when 'Import SBML' is selected self.openFileDlg('Load', 'SBML') def __openFileDlgForExportSBML(self, *arg): # when 'Export SBML' is selected self.openFileDlg('Save', 'SBML') def openFileDlg(self, aType, aTarget): """displays FileSelection aType --- 'Load'/'Save' (str) aTarget --- 'Model'/'Script'/'SBML' (str) Return None [Note]:When FileSelection is already created, moves it to the top of desktop, like singleton pattern. """ # When the FileSelection is already displayed, moves it to the top of desktop. if self.theFileSelection != None: self.theFileSelection.present() # When the FileSelection is not created yet, creates and displays it. else: # creates FileSelection self.theFileSelection = FileSelection() self.theFileSelection.connect('delete_event', self.__deleteFileSelection) self.theFileSelection.cancel_button.connect( 'clicked', self.__deleteFileSelection) aPixbuf16 = gtk.gdk.pixbuf_new_from_file( os.path.join(config.GLADEFILE_PATH, 'ecell.png')) aPixbuf32 = gtk.gdk.pixbuf_new_from_file( os.path.join(config.GLADEFILE_PATH, 'ecell32.png')) self.theFileSelection.set_icon_list(aPixbuf16, aPixbuf32) # when 'Load Model' is selected if aType == 'Load' and aTarget == 'Model': self.theFileSelection.action = 'open' self.theFileSelection.ok_button.connect( 'clicked', self.__loadData, aTarget) self.theFileSelection.complete('*.' + MODEL_FILE_EXTENSION) self.theFileSelection.set_title( "Select %s File (%s)" % (aTarget, MODEL_FILE_EXTENSION)) # when 'Load Script' is selected elif aType == 'Load' and aTarget == 'Script': self.theFileSelection.action = 'open' self.theFileSelection.ok_button.connect( 'clicked', self.__loadData, aTarget) self.theFileSelection.complete('*.' + SCRIPT_FILE_EXTENSION) self.theFileSelection.set_title( "Select %s File (%s)" % (aTarget, SCRIPT_FILE_EXTENSION)) # when 'Save Model' is selected elif aType == 'Save' and aTarget == 'Model': self.theFileSelection.action = 'save' self.theFileSelection.ok_button.connect( 'clicked', self.__saveModel) self.theFileSelection.complete('*.' + MODEL_FILE_EXTENSION) self.theFileSelection.set_title( "Select %s File (%s)" % (aTarget, MODEL_FILE_EXTENSION)) # when 'Import SBML' is selected elif aType == 'Load' and aTarget == 'SBML': self.theFileSelection.action = 'open' self.theFileSelection.ok_button.connect( 'clicked', self.__loadData, aTarget) self.theFileSelection.complete('*.' + MODEL_FILE_EXTENSION) self.theFileSelection.set_title( "Select %s File (%s)" % (aTarget, MODEL_FILE_EXTENSION)) # when 'Save Model' is selected elif aType == 'Save' and aTarget == 'SBML': self.theFileSelection.action = 'save' self.theFileSelection.ok_button.connect( 'clicked', self.__exportSBML) self.theFileSelection.complete('*.' + MODEL_FILE_EXTENSION) self.theFileSelection.set_title( "Select %s File (%s)" % (aTarget, MODEL_FILE_EXTENSION)) else: raise "(%s,%s) does not match." % (aType, aTarget) # displays the created FileSelection self.theFileSelection.show_all() def __deleteFileSelection(self, *arg): """deletes FileSelection Return None """ # deletes the reference to FileSelection if self.theFileSelection != None: self.theFileSelection.destroy() self.theFileSelection = None def __loadData(self, *arg): """loads model or script file arg[0] --- ok button of FileSelection arg[1] --- 'Model'/'Script' (str) Return None """ # checks the length of argument, but this is verbose if len(arg) < 2: return None aFileType = arg[1] aFileName = self.theFileSelection.get_filename() if os.path.isfile(aFileName): pass else: aMessage = ' Error ! No such file. \n[%s]' % aFileName self.theSession.message(aMessage) aDialog = ConfirmWindow(OK_MODE, aMessage, 'Error!') self.theFileSelection.present() return None self.__deleteFileSelection() self.theSession.message('Loading %s file %s\n' % (aFileType, aFileName)) try: if aFileType == 'Model': self.theSession.loadModel(aFileName) elif aFileType == 'Script': self.theSession.loadScript(aFileName) elif aFileType == 'SBML': self.theSession.importSBML(aFileName) self.theSession.updateWindows() except: # expants message window, when it is folded. if self.exists(): if not (self['message_togglebutton'].get_child()).get_active(): (self['message_togglebutton'].get_child()).set_active(True) # displays confirm window aMessage = 'Can\'t load [%s]\nSee MessageWindow for details.' % aFileName aDialog = ConfirmWindow(OK_MODE, aMessage, 'Error!') # displays message on MessageWindow aMessage = 'Can\'t load [%s]' % aFileName self.theSession.message(aMessage) anErrorMessage = '\n'.join( traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) self.theSession.message(anErrorMessage) def __saveModel(self, *arg): # gets file name aFileName = self.theFileSelection.get_filename() # when the file already exists if os.path.isfile(aFileName): # displays confirm window aMessage = 'Would you like to replace the existing file? \n[%s]' % aFileName aDialog = ConfirmWindow(OKCANCEL_MODE, aMessage, 'Confirm File Overwrite') # when canceled, does nothing if aDialog.return_result() != OK_PRESSED: # does nothing return None # when ok is pressed, overwrites it. # deletes FileSelection self.__deleteFileSelection() try: # displays save message self.theSession.message('Save model file %s\n' % aFileName) # saves Model self.theSession.saveModel(aFileName) except: # expants message window, when it is folded. if not (self['message_togglebutton'].get_child()).get_active(): (self['message_togglebutton'].get_child()).set_active(True) # displays confirm window aMessage = 'Can\'t save [%s]\nSee MessageWindow for details.' % aFileName aDialog = ConfirmWindow(OK_MODE, aMessage, 'Error!') # displays error message of MessageWindow self.theSession.message('Can\'t save [%s]' % aFileName) anErrorMessage = '\n'.join( traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) self.theSession.message(anErrorMessage) # updates self.update() self.theSession.updateFundamentalWindows() def __exportSBML(self, *arg): # gets file name aFileName = self.theFileSelection.get_filename() # when the file already exists if os.path.isfile(aFileName): # displays confirm window aMessage = 'Would you like to replace the existing file? \n[%s]' % aFileName aDialog = ConfirmWindow(OKCANCEL_MODE, aMessage, 'Confirm File Overwrite') # when canceled, does nothing if aDialog.return_result() != OK_PRESSED: # does nothing return None # when ok is pressed, overwrites it. # deletes FileSelection self.__deleteFileSelection() try: # displays save message self.theSession.message('Export SBML file %s\n' % aFileName) # saves Model self.theSession.exportSBML(aFileName) except: # expants message window, when it is folded. if not (self['message_togglebutton'].get_child()).get_active(): (self['message_togglebutton'].get_child()).set_active(True) # displays confirm window aMessage = 'Can\'t save [%s]\nSee MessageWindow for details.' % aFileName aDialog = ConfirmWindow(OK_MODE, aMessage, 'Error!') # displays error message of MessageWindow self.theSession.message('Can\'t export [%s]' % aFileName) anErrorMessage = '\n'.join( traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) self.theSession.message(anErrorMessage) # updates self.update() self.theSession.updateFundamentalWindows() def __deleted(self, *arg): """When delete_event happens or exit menu is selected, this method is called. """ running_flag = False if self.theSession.theRunningFlag: # stop simulation temporarily self.theSession.stop() running_flag = True if self.theSession.theSession is not None: # If there is no logger data, exit this program. if len(self.theSession.getLoggerList()) != 0: aMessage = 'Are you sure you want to quit?' aTitle = 'Question' # Popup confirm window, and check user request aDialog = ConfirmWindow(1, aMessage, aTitle) # ok is pressed if aDialog.return_result() != OK_PRESSED: if running_flag: self.theSession.run() return True self.setStopState() self.close() self.theSession.QuitGUI() return True def close(self): """ restores message method and closes window """ self.theSession.restoreMessageMethod() if self.theSession.theSession is not None: self.theEntityListWindow.update() self.theEntityListWindow.close() OsogoWindow.close(self) def setStartState(self): self.SimulationButton.setCurrentState('run') if self.logoMovable: self.logoAnimation.start() self.isStarted = True self.startTime = time.time() def setStopState(self): self.SimulationButton.setCurrentState('stop') self.logoAnimation.stop() self.setTempTime() def setTempTime(self): self.tempTime = time.time() - self.startTime + self.tempTime def __handleSimulation(self, *arg): """handles simulation arg[0] --- simulation button (gtk.Button) Returns None """ if not self.exists(): return if (self.SimulationButton.getCurrentState() == 'stop'): self.setStartState() self.theSession.run() elif (self.SimulationButton.getCurrentState() == 'run'): self.setStopState() self.theSession.stop() def handleSimulation(self): """ handles simulation """ self.__handleSimulation(self, None) def __stepSimulation(self, *arg): """steps simulation arg[0] --- stop button (gtk.Button) Returns None if step measure is second, then Session.run() if step measure is step than Session.step () """ if self.getStepType(): if (self.SimulationButton.getCurrentState() == "stop"): self.setStartState() self.theSession.run(self.getStepSize()) self.setStopState() else: self.theSession.run(self.getStepSize()) self.setTempTime() else: if (self.SimulationButton.getCurrentState() == "stop"): self.setStartState() self.theSession.step(self.getStepSize()) self.setStopState() else: self.theSession.step(self.getStepSize()) self.setTempTime() def stepSimulation(self): """ steps simulation """ self.__stepSimulation(self, None) def getStepType(self): """ returns state of sec radiobutton True: seconds False: steps """ return self['sec_radiobutton'].get_active() def setStepType(self, aState): """ sets Step Type radiobutton state values for aState True : seconds False : step """ if aState == True: self['sec_radiobutton'].set_active(True) if aState == False: self['sec_radiobutton'].set_active(False) def getStepSize(self): """ returns user or script specifid step size """ self.__setStepSizeOrSec(self, None) return self.theStepSizeOrSec def setStepSize(self, num): """ sets Stepsize entry box to num """ self['sec_step_entry'].set_text(str(num)) self.__setStepSizeOrSec(self, None) def __setStepSizeOrSec(self, *arg): # gets the inputerd characters from the GtkEntry. aNewValue = self['sec_step_entry'].get_text().strip() try: # converts string to float aNewValue = float(aNewValue) # when string can't be converted to float except ValueError: # displays a Confirm Window. aMessage = "\"%s\" is not numerical value." % aNewValue aMessage += "\nInput numerical character" aDialog = ConfirmWindow(OK_MODE, aMessage, 'Error!') # sets the previous value self['sec_step_entry'].set_text(str(self.theStepSizeOrSec)) # when string can be converted to float else: #check for numerical constraints aMessage = "" if aNewValue <= 0: aMessage += "Input positive number.\n" # when 'step' is selected. if self['step_radiobutton'].get_active(): # step must be integer if int(aNewValue) != aNewValue: aMessage += "Input integer.\n" # convets float to int aNewValue = int(aNewValue) if len(aMessage) > 0: #aDialog = ConfirmWindow(OK_MODE,aMessage,'Error!') aDialog = ConfirmWindow(OK_MODE, aMessage, 'Error!') else: self.theStepSizeOrSec = aNewValue #def getTimeSubstruction( self, aTime1, aTime ) def update(self): """updates this window Returns None """ if not self.exists(): return None # updates time aTime = self.theSession.getCurrentTime() self.theCurrentTime = aTime self['time_entry'].set_text( not math.isnan(aTime) and str(self.theCurrentTime) or '') self['sec_step_entry'].set_text(str(self.theStepSizeOrSec)) if (self.SimulationButton.getCurrentState() == 'run' and self.timerVisible): self['timer_entry'].set_text( self.getCurrentTime(time.time() - self.startTime + self.tempTime)) if self.indicatorVisible: if (self.updateCount == 0): self.theLastTime = self.theCurrentTime self.theLastRealTime = time.time() self.updateCount += 1 if (self.updateCount == 25): if (aTime != self.theLastTime): self['run_speed_label'].set_text( str( round((self.theCurrentTime - self.theLastTime) / (time.time() - self.theLastRealTime), 5))) self.updateCount = 0 # when Model is already loaded. self.__setMenuAndButtonsStatus(self.theSession.theSession is not None) self.updateButtons() def getCurrentTime(self, aTime): theTime = self.datetime.fromtimestamp(aTime) return str(theTime.hour - 9) + " : " + str( theTime.minute) + " : " + str(theTime.second) def updateButton(self, name, state): self.__button_update = True for w in self.__togglableWindows[name]: if state != w.get_active(): w.set_active(state) self.__button_update = False def toggleWindow(self, name, state): self.updateButton(name, state) self.theSession.toggleWindow(name, state) def updateButtons(self): """ updates Buttons and menus with latest FundamentalWindow status """ if not self.exists(): return for n in self.__togglableWindows: self.updateButton(n, self.theSession.doesExist(n)) self.updateButton('MessageWindow', self.theMessageWindowVisible) def __openLogPolicy(self, *arg): """ signal handler to logging policy is called """ # get default logging policy aLogPolicy = self.theSession.getLogPolicyParameters() # open logpolicy window newLogPolicy = self.theSession.openLogPolicyWindow( aLogPolicy, "Set default log policy") if newLogPolicy != None: # save logpolicy self.theSession.setLogPolicyParameters(newLogPolicy) def __displayToolbar(self, *arg): # show Toolbar if self.theToolbarVisible: self['toolbar_handlebox'].hide() self.theToolbarVisible = False else: self['toolbar_handlebox'].show() self.theToolbarVisible = True def __displayStatusbar(self, *arg): # show Statusbar if self.theStatusbarVisible: self['statusbar'].hide() self.theStatusbarVisible = False else: self['statusbar'].show() self.theStatusbarVisible = True def __displayIndicator(self, *arg): # show Indicator if self.indicatorVisible: self['indicator_box'].hide() self.setIndicatorActive(False) self.indicatorVisible = False else: self['indicator_box'].show() self.setIndicatorActive(True) self.indicatorVisible = True self.theLastTime = self.theSession.getCurrentTime() def __displayTimer(self, *arg): # show Indicator if self.timerVisible: self['timer_box'].hide() self.setTimerActive(False) self.timerVisible = False else: self['timer_box'].show() self.setTimerActive(True) self.timerVisible = True if (self.isStarted == False): self['timer_entry'].set_text("0 : 0 : 0") else: if (self.SimulationButton.getCurrentState() == 'stop'): self['timer_entry'].set_text(self.getCurrentTime( self.tempTime)) else: self['timer_entry'].set_text( self.getCurrentTime(time.time() - self.startTime + self.tempTime)) def setIndicatorActive(self, isActive): self['run_speed_indicator'].set_active(isActive) (self['indicator_button'].get_child()).set_active(isActive) def setTimerActive(self, isActive): self['timer_menu'].set_active(isActive) (self['timer_button'].get_child()).set_active(isActive) def __displayLoggerWindow(self, *arg): if self.__button_update: return self.toggleWindow('LoggerWindow', arg[0].get_active()) def __displayStepperWindow(self, *arg): if self.__button_update: return self.toggleWindow('StepperWindow', arg[0].get_active()) def __displayInterfaceWindow(self, *arg): if self.__button_update: return self.toggleWindow('InterfaceWindow', arg[0].get_active()) def __displayBoardWindow(self, *arg): if self.__button_update: return self.toggleWindow('BoardWindow', arg[0].get_active()) def hideMessageWindow(self): self['messagehandlebox'].hide() (self['message_togglebutton'].get_child()).set_active(False) def showMessageWindow(self): self['messagehandlebox'].show() (self['message_togglebutton'].get_child()).set_active(True) def __toggleMessageWindow(self, *arg): """expands or folds MessageWindow arg[0] --- self['message_togglebutton'] or self['message_window_menu'] Returns None """ if self.__button_update: return # checks the length of argument, but this is verbose if len(arg) < 1: return None if (arg[0].get_name() != "message_window_menu"): anObject = arg[0].get_child() else: anObject = arg[0] # show if anObject.get_active(): self.theMessageWindowVisible = True self.showMessageWindow() else: self.theMessageWindowVisible = False self.hideMessageWindow() self.updateButtons() def __toggleEntityListWindow(self, *arg): if arg[0].get_active(): self.theEntityListWindowVisible = True self['entitylistarea'].show() else: self.theEntityListWindowVisible = False self['entitylistarea'].hide() def __displayAbout(self, *args): # show about information self.createAboutSessionMonitor() def __clearTimer(self, *arg): self['timer_entry'].set_text("0 : 0 : 0") self.tempTime = 0.0 if self.SimulationButton.getCurrentState() == 'run': self.startTime = time.time() else: self.isStarted = False self.startTime = 0.0 def __setAnimationSensitive(self, *arg): if self.logoMovable: self.logoMovable = False if self.SimulationButton.getCurrentState() == 'run': self.logoAnimation.stop() else: self.logoMovable = True if self.SimulationButton.getCurrentState() == 'run': self.logoAnimation.start() def createAboutSessionMonitor(self): if not self.openAboutSessionMonitor: AboutSessionMonitor(self) def toggleAboutSessionMonitor(self, isOpen, anAboutSessionMonitor): self.theAboutSessionMonitor = anAboutSessionMonitor self.openAboutSessionMonitor = isOpen def openPreferences(self, *arg): """display the preference window arg[0] --- self['preferences_menu'] Return None """ # Preference Window is not implemented yet. # So, displays Warning Dialog aMessage = ' Sorry ! Not implemented... [%s]\n' % '03/April/2003' aDialog = ConfirmWindow(OK_MODE, aMessage, 'Sorry!') def __printMessage(self, aMessage): """prints message on MessageWindow aMessage --- a message (str or list) Return None """ # prints message on MessageWindow self.theMessageWindow.printMessage(aMessage) def __createEntityListWindow(self, *arg): anEntityListWindow = self.theSession.createEntityListWindow( "EntityListWindow", self['statusbar']) def deleted(self, *arg): """ When 'delete_event' signal is chatcked( for example, [X] button is clicked ), delete this window. Returns True """ pass
class LoggerWindow(OsogoWindow): # --------------------------------------------------------------- # constructor # aSession : the reference of session # aSession : the reference of Session # --------------------------------------------------------------- def __init__( self, aSession ): OsogoWindow.__init__( self, aSession, 'LoggerWindow.glade' ) self.theDefaultSaveDirectory='Data' self.thePopupMenu = PopupMenu( self ) self.theList = [] # --------------------------------------------------------------- # Creates save file selection # --------------------------------------------------------------- self.theSaveDirectorySelection = FileSelection( 'Select File' ) self.theSaveDirectorySelection.ok_button.connect('clicked', self.changeSaveDirectory) self.theSaveDirectorySelection.cancel_button.connect('clicked', self.closeParentWindow) # end of the __init__ def openWindow(self): OsogoWindow.openWindow(self) self.theEntryList = self['loggerWindow_clist'] aListStore = gtk.ListStore( gobject.TYPE_STRING,\ gobject.TYPE_STRING,\ gobject.TYPE_STRING ) self.theEntryList.set_model( aListStore ) column=gtk.TreeViewColumn('FullPN',gtk.CellRendererText(),text=0) column.set_resizable(True) self.theEntryList.append_column(column) column=gtk.TreeViewColumn('Start',gtk.CellRendererText(),text=1) column.set_resizable(True) self.theEntryList.append_column(column) column=gtk.TreeViewColumn('End',gtk.CellRendererText(),text=2) column.set_resizable(True) self.theEntryList.append_column(column) self.theEntryList.get_selection().set_mode(gtk.SELECTION_MULTIPLE) self.initialize() # reset self.resetAllValues() # --------------------------------------------------------------- # Adds handlers # --------------------------------------------------------------- self.addHandlers({ \ # bottom basic bottons (save,close,reset) 'on_save_button_clicked' : self.saveData, 'on_close_button_clicked' : self.closeWindow, 'on_reset_button_clicked' : self.resetAllValues, # save_directory 'on_directory_button_clicked' : self.spawnSaveDirectorySelection, # data_interval 'on_datainterval_checkbox_toggled' : self.updateDataInterval, # time 'on_time_checkbox_toggled' : self.updateStartEnd, # window event #'on_exit_activate' : self.closeWindow, # popup 'button_press_event' : self.popupMenu}) # end of openWindow def close( self ): self.theEntryList = None OsogoWindow.close(self) def closeWindow( self, *args ): self.close() # --------------------------------------------------------------- # initializer # return -> None # --------------------------------------------------------------- def initialize( self ): self.update() # end of initialize # --------------------------------------------------------------- # Resets all value # return -> None # --------------------------------------------------------------- def resetAllValues( self, obj=None ): # save_directory self['directory_entry'].set_text(self.theDefaultSaveDirectory) # data_interval self['datainterval_checkbox'].set_active(1) self['datainterval_spinbutton'].set_sensitive(0) # specity_the_time_to_save self['time_checkbox'].set_active(1) self['start_spinbutton'].set_sensitive(0) self['end_spinbutton'].set_sensitive(0) self.update() # end of resetAllValues # --------------------------------------------------------------- # Closes parent window # return -> None # --------------------------------------------------------------- def closeParentWindow( self, obj ): aParentWindow = self.theSaveDirectorySelection.cancel_button.get_parent_window() aParentWindow.hide() # end of closeParentWindow # --------------------------------------------------------------- # Spawns # return -> None # --------------------------------------------------------------- def spawnSaveDirectorySelection( self, obj ): self.theSaveDirectorySelection.show_all() # end of spawnSaveDirectorySelection # --------------------------------------------------------------- # If directory_button is clicked, this method is called. # return -> None # --------------------------------------------------------------- def changeSaveDirectory( self, obj ): aSaveDirectory = self.theSaveDirectorySelection.get_filename() self['directory_entry'].set_text(aSaveDirectory) self.theSaveDirectorySelection.hide() # end of changeSaveDirectory # --------------------------------------------------------------- # If datainterval_checkbox is toggled, this method is called. # return -> None # --------------------------------------------------------------- def updateDataInterval( self, obj=None ): if self['datainterval_checkbox'].get_active(): self['datainterval_spinbutton'].set_sensitive(0) else: self['datainterval_spinbutton'].set_sensitive(1) # end of updateDataInterval # --------------------------------------------------------------- # If time_checkbox is toggled, this method is called. # return -> None # --------------------------------------------------------------- def updateStartEnd( self, obj=None ): if self['time_checkbox'].get_active(): self['start_spinbutton'].set_sensitive(0) self['end_spinbutton'].set_sensitive(0) else: self['start_spinbutton'].set_sensitive(1) self['end_spinbutton'].set_sensitive(1) # end of updateStartEnd # --------------------------------------------------------------- # If save_button is clicked, then this method is called. # return -> None # --------------------------------------------------------------- def saveData( self, obj ): aGeneralSaveErrorMessage="couldn't save files." # ------------------------------------------------- # [0] clean up statusbar # ------------------------------------------------- self["statusbar"].pop(1) # ------------------------------------------------- # [1] checks status and value of each widget # ------------------------------------------------- # [1-1] At least, one data must be selected. # If no list is selected, exit this method. if len(self.theSelectedPropertyName())==0: self["statusbar"].push(1,'Select some data.') aErrorMessage='\nNo data is selected.!\n' aWarningWindow = ConfirmWindow(0,aErrorMessage) return None # [1-2] interval must be > 0 # If interval is 0, exit this method. anInterval = -1 if not self['datainterval_checkbox'].get_active(): anInterval = self['datainterval_spinbutton'].get_value() if anInterval==0: self["statusbar"].push(1,'Set interval > 0.') aErrorMessage='Interval must be > 0.!\n' aWarningWindow = ConfirmWindow(0,aErrorMessage) return None # [1-3] Now binary type is not supported by Logger. # If binary type is selected, exit this method. aType = self["datatype_combo"].get_active_text() if aType == 'ecd': pass elif aType == 'binary': self["statusbar"].push(1,'Select ecd type.') aErrorMessage = "Sorry, binary format will be supported in the future version." aWarningWindow = ConfirmWindow(0,aErrorMessage) return None # [1-4] start < end # If start >= end, exit this method. aStartTime=-1 anEndTime=-1 if not self['time_checkbox'].get_active(): aStartTime = self['start_spinbutton'].get_value() anEndTime = self['end_spinbutton'].get_value() if aStartTime >= anEndTime: self["statusbar"].push(1,'Set start time < end time.') aErrorMessage='Start time must be < end time.!\n' aWarningWindow = ConfirmWindow(0,aErrorMessage) return None # ------------------------------------------------- # [2] Creates Data directory. # ------------------------------------------------- aSaveDirectory = self['directory_entry'].get_text() # If same directory exists. if os.path.isdir(aSaveDirectory): aConfirmMessage = "%s directory already exist.\n Would you like to override it?"%aSaveDirectory self.confirmWindow = ConfirmWindow(1,aConfirmMessage) if self.confirmWindow.return_result() == 0: pass else: self["statusbar"].push(1,'Save was canceled.') return None # If same directory dose not exists. else: try: os.mkdir(aSaveDirectory) self["statusbar"].push(1,'Set start time < end time.') except: self["statusbar"].push(1,'couldn\'t create %s'%aSaveDirectory) aErrorMessage='couldn\'t create %s!\n'%aSaveDirectory aWarningWindow = ConfirmWindow(0,aErrorMessage) return None else: self["statusbar"].push(1,'%s was created.'%aSaveDirectory) # ------------------------------------------------- # [3] Execute saving. # ------------------------------------------------- try: self.theSession.saveLoggerData( self.theSelectedPropertyName(), aSaveDirectory, aStartTime, anEndTime, anInterval ) except: anErrorMessage= "Error : could not save " self["statusbar"].push(1,anErrorMessage) return None aSuccessMessage= " All files you selected are saved. " self["statusbar"].push( 1 , aSuccessMessage ) # end of saveData # --------------------------------------------------------------- # Gets the selected PropertyName # return -> selected propertyname list # --------------------------------------------------------------- def theSelectedPropertyName( self ): self.aSelectedPropertyNameList=[] selection=self['loggerWindow_clist'].get_selection() selection.selected_foreach(self.selection_function) return self.aSelectedPropertyNameList def selection_function(self,tree,path,iter): aPropertyName = self["loggerWindow_clist"].get_model().get_value(iter,0) self.aSelectedPropertyNameList.append(aPropertyName) # end of theSelectedPropertyName # --------------------------------------------------------------- # Updates # return -> None # --------------------------------------------------------------- def update( self ): if not self.exists(): return None self.theFullPNList = self.theSession.getLoggerList() self.theList = [] for aFullPNString in self.theFullPNList : aLoggerStub = self.theSession.createLoggerStub( aFullPNString ) start = str( aLoggerStub.getStartTime() ) if self.theSession.theRunningFlag: end = 'running' else: end = str( aLoggerStub.getEndTime() ) aList = [ aFullPNString, start, end ] self.theList.append( aList ) aModel = self.theEntryList.get_model() aModel.clear() for aValue in self.theList: anIter = aModel.append() aModel.set( anIter,\ 0, aValue[0],\ 1, str(aValue[1]),\ 2, str(aValue[2]) ) # --------------------------------------------------------------- # popupMenu # - show popup menu # # aWidget : widget # anEvent : an event # return -> None # This method is throwable exception. # --------------------------------------------------------------- def popupMenu( self, aWidget, anEvent ): if len(self.theSelectedPropertyName())!=0: if anEvent.button == 3: self.thePopupMenu.popup( None, None, None, 1, 0 ) return False # end of poppuMenu # ============================================================================== def editPolicy( self, *args ): if len(self.aSelectedPropertyNameList) == 1: # get loggerpolicy aLoggerStub = self.theSession.createLoggerStub( self.aSelectedPropertyNameList[0] ) aLogPolicy = aLoggerStub.getLoggerPolicy() else: aLogPolicy = [0,0,0,0] newLogPolicy = self.theSession.openLogPolicyWindow( aLogPolicy, "Set log policy for selected loggers" ) if newLogPolicy == None: return for aFullPN in self.aSelectedPropertyNameList: aLoggerStub = self.theSession.createLoggerStub( aFullPN ) aLoggerStub.setLoggerPolicy( newLogPolicy ) # ============================================================================== def saveDataFile( self, aFullPN, aDirectory = None, anInterval = None, aStartTime = None, anEndTime = None, fileType = 'ecd' ): """ saves FullPN logger data with given parameters if parameters are not given, function defaults to window settings for parameters with a given value it sets appropriate window settings and saves FullPN into Datafile """ #find FullPM in list aFullPNString = createFullPNString ( aFullPN ) anIter = self.theEntryList.get_model().get_iter_first() while True: if anIter == None: return None aTitle = self.theEntryList.get_model().get_value(anIter, 0 ) if aTitle == aFullPNString: aPath = self.theEntryList.get_model().get_path ( anIter ) self.theEntryList.set_cursor( aPath, None, False ) break anIter = self.theEntryList.get_model().iter_next( anIter ) if aDirectory != None: self.setDirectory( aDirectory ) if anInterval != None: self.setInterval( anInterval ) if aStartTime != None: self.setStartTime ( aStartTime ) if anEndTime != None: self.setEndTime ( anEndTime ) if fileType != None: self.setDataFileType ( fileType ) self.saveData( None ) # ============================================================================== def setDirectory ( self, aDirectory ): """ sets directory field to aDirectory returns None """ self['directory_entry'].set_text( str( aDirectory ) ) # ============================================================================== def getDirectory ( self ): """ returns directory choosen by the user """ return self['directory_entry'].get_text() # ============================================================================== def setInterval ( self, anInterval ): """ sets Interval field of Loggerwindow to anInterval also sets interval checkbox True """ self['datainterval_spinbutton'].set_value( anInterval ) self['datainterval_checkbox'].set_active( True ) self.updateDataInterval() # ============================================================================== def getInterval ( self ): """ returns -1 if Interval checkbox is off rerurns interval set by user if interva check box is on """ if self['datainterval_checkbox'].get_active( ): return self['datainterval_spinbutton'].get_value( ) else: return -1 # ============================================================================== def setStartTime ( self, aTime ): """ sets StartTime field of Loggerwindow to anInterval also sets time checkbox True """ self['start_spinbutton'].set_value( aTime ) self['time_checkbox'].set_active( True ) self.updateStartEnd() # ============================================================================== def getStartTime ( self ): """ returns -1 if Interval checkbox is off rerurns interval set by user if interva check box is on """ if self['time_checkbox'].get_active( ): return self['start_spinbutton'].get_value( ) else: return -1 # ============================================================================== def setEndTime ( self, aTime ): """ sets EndTime field of Loggerwindow to anInterval also sets time checkbox True """ self['end_spinbutton'].set_value( aTime ) self['time_checkbox'].set_active( True ) self.updateStartEnd() # ============================================================================== def getEndTime ( self ): """ returns -1 if Interval checkbox is off returns interval set by user if interva check box is on """ if self['time_checkbox'].get_active( ): return self['end_spinbutton'].get_value( ) else: return -1 # ============================================================================== def getDataFileType (self ): """ returns Data Type of file choosen by the user """ return self["datatype_combo"].get_active_text() # ============================================================================== def setDataFileType (self, aDataType ): """ sets the Datatype of save file to the window aDataType can only be 'ecd' or 'binary'""" if aDataType == 'ecd' or aDataType == 'binary': self["datatype_combo"].set_text( aDataType ) # ============================================================================== def setUseDefaultInterval ( self, aBoolean ): """ sets interval checkbox to aBoolean """ if aBoolean == True or aBoolean == False: self['datainterval_checkbox'].set_active( aBoolean ) self.updateDataInterval() # ============================================================================== def setUseDefaultTime ( self, aBoolean ): """ sets time checkbox to aBoolean """ if aBoolean == True or aBoolean == False: self['time_checkbox'].set_active( aBoolean ) self.updateStartEnd() # ============================================================================== def getUseDefaultInterval ( self ): """ return state of interval checkbox """ return self['datainterval_checkbox'].get_active( ) # ============================================================================== def getUseDefaultTime ( self ): """ return state of time checkbox """ return self['time_checkbox'].get_active( )
class LoggerWindow(OsogoWindow): # --------------------------------------------------------------- # constructor # aSession : the reference of session # aSession : the reference of Session # --------------------------------------------------------------- def __init__(self, aSession): OsogoWindow.__init__(self, aSession, 'LoggerWindow.glade') self.theDefaultSaveDirectory = 'Data' self.thePopupMenu = PopupMenu(self) self.theList = [] # --------------------------------------------------------------- # Creates save file selection # --------------------------------------------------------------- self.theSaveDirectorySelection = FileSelection('Select File') self.theSaveDirectorySelection.ok_button.connect( 'clicked', self.changeSaveDirectory) self.theSaveDirectorySelection.cancel_button.connect( 'clicked', self.closeParentWindow) # end of the __init__ def openWindow(self): OsogoWindow.openWindow(self) self.theEntryList = self['loggerWindow_clist'] aListStore = gtk.ListStore( gobject.TYPE_STRING,\ gobject.TYPE_STRING,\ gobject.TYPE_STRING ) self.theEntryList.set_model(aListStore) column = gtk.TreeViewColumn('FullPN', gtk.CellRendererText(), text=0) column.set_resizable(True) self.theEntryList.append_column(column) column = gtk.TreeViewColumn('Start', gtk.CellRendererText(), text=1) column.set_resizable(True) self.theEntryList.append_column(column) column = gtk.TreeViewColumn('End', gtk.CellRendererText(), text=2) column.set_resizable(True) self.theEntryList.append_column(column) self.theEntryList.get_selection().set_mode(gtk.SELECTION_MULTIPLE) self.initialize() # reset self.resetAllValues() # --------------------------------------------------------------- # Adds handlers # --------------------------------------------------------------- self.addHandlers({ \ # bottom basic bottons (save,close,reset) 'on_save_button_clicked' : self.saveData, 'on_close_button_clicked' : self.closeWindow, 'on_reset_button_clicked' : self.resetAllValues, # save_directory 'on_directory_button_clicked' : self.spawnSaveDirectorySelection, # data_interval 'on_datainterval_checkbox_toggled' : self.updateDataInterval, # time 'on_time_checkbox_toggled' : self.updateStartEnd, # window event #'on_exit_activate' : self.closeWindow, # popup 'button_press_event' : self.popupMenu}) # end of openWindow def close(self): self.theEntryList = None OsogoWindow.close(self) def closeWindow(self, *args): self.close() # --------------------------------------------------------------- # initializer # return -> None # --------------------------------------------------------------- def initialize(self): self.update() # end of initialize # --------------------------------------------------------------- # Resets all value # return -> None # --------------------------------------------------------------- def resetAllValues(self, obj=None): # save_directory self['directory_entry'].set_text(self.theDefaultSaveDirectory) # data_interval self['datainterval_checkbox'].set_active(1) self['datainterval_spinbutton'].set_sensitive(0) # specity_the_time_to_save self['time_checkbox'].set_active(1) self['start_spinbutton'].set_sensitive(0) self['end_spinbutton'].set_sensitive(0) self.update() # end of resetAllValues # --------------------------------------------------------------- # Closes parent window # return -> None # --------------------------------------------------------------- def closeParentWindow(self, obj): aParentWindow = self.theSaveDirectorySelection.cancel_button.get_parent_window( ) aParentWindow.hide() # end of closeParentWindow # --------------------------------------------------------------- # Spawns # return -> None # --------------------------------------------------------------- def spawnSaveDirectorySelection(self, obj): self.theSaveDirectorySelection.show_all() # end of spawnSaveDirectorySelection # --------------------------------------------------------------- # If directory_button is clicked, this method is called. # return -> None # --------------------------------------------------------------- def changeSaveDirectory(self, obj): aSaveDirectory = self.theSaveDirectorySelection.get_filename() self['directory_entry'].set_text(aSaveDirectory) self.theSaveDirectorySelection.hide() # end of changeSaveDirectory # --------------------------------------------------------------- # If datainterval_checkbox is toggled, this method is called. # return -> None # --------------------------------------------------------------- def updateDataInterval(self, obj=None): if self['datainterval_checkbox'].get_active(): self['datainterval_spinbutton'].set_sensitive(0) else: self['datainterval_spinbutton'].set_sensitive(1) # end of updateDataInterval # --------------------------------------------------------------- # If time_checkbox is toggled, this method is called. # return -> None # --------------------------------------------------------------- def updateStartEnd(self, obj=None): if self['time_checkbox'].get_active(): self['start_spinbutton'].set_sensitive(0) self['end_spinbutton'].set_sensitive(0) else: self['start_spinbutton'].set_sensitive(1) self['end_spinbutton'].set_sensitive(1) # end of updateStartEnd # --------------------------------------------------------------- # If save_button is clicked, then this method is called. # return -> None # --------------------------------------------------------------- def saveData(self, obj): aGeneralSaveErrorMessage = "couldn't save files." # ------------------------------------------------- # [0] clean up statusbar # ------------------------------------------------- self["statusbar"].pop(1) # ------------------------------------------------- # [1] checks status and value of each widget # ------------------------------------------------- # [1-1] At least, one data must be selected. # If no list is selected, exit this method. if len(self.theSelectedPropertyName()) == 0: self["statusbar"].push(1, 'Select some data.') aErrorMessage = '\nNo data is selected.!\n' aWarningWindow = ConfirmWindow(0, aErrorMessage) return None # [1-2] interval must be > 0 # If interval is 0, exit this method. anInterval = -1 if not self['datainterval_checkbox'].get_active(): anInterval = self['datainterval_spinbutton'].get_value() if anInterval == 0: self["statusbar"].push(1, 'Set interval > 0.') aErrorMessage = 'Interval must be > 0.!\n' aWarningWindow = ConfirmWindow(0, aErrorMessage) return None # [1-3] Now binary type is not supported by Logger. # If binary type is selected, exit this method. aType = self["datatype_combo"].get_active_text() if aType == 'ecd': pass elif aType == 'binary': self["statusbar"].push(1, 'Select ecd type.') aErrorMessage = "Sorry, binary format will be supported in the future version." aWarningWindow = ConfirmWindow(0, aErrorMessage) return None # [1-4] start < end # If start >= end, exit this method. aStartTime = -1 anEndTime = -1 if not self['time_checkbox'].get_active(): aStartTime = self['start_spinbutton'].get_value() anEndTime = self['end_spinbutton'].get_value() if aStartTime >= anEndTime: self["statusbar"].push(1, 'Set start time < end time.') aErrorMessage = 'Start time must be < end time.!\n' aWarningWindow = ConfirmWindow(0, aErrorMessage) return None # ------------------------------------------------- # [2] Creates Data directory. # ------------------------------------------------- aSaveDirectory = self['directory_entry'].get_text() # If same directory exists. if os.path.isdir(aSaveDirectory): aConfirmMessage = "%s directory already exist.\n Would you like to override it?" % aSaveDirectory self.confirmWindow = ConfirmWindow(1, aConfirmMessage) if self.confirmWindow.return_result() == 0: pass else: self["statusbar"].push(1, 'Save was canceled.') return None # If same directory dose not exists. else: try: os.mkdir(aSaveDirectory) self["statusbar"].push(1, 'Set start time < end time.') except: self["statusbar"].push(1, 'couldn\'t create %s' % aSaveDirectory) aErrorMessage = 'couldn\'t create %s!\n' % aSaveDirectory aWarningWindow = ConfirmWindow(0, aErrorMessage) return None else: self["statusbar"].push(1, '%s was created.' % aSaveDirectory) # ------------------------------------------------- # [3] Execute saving. # ------------------------------------------------- try: self.theSession.saveLoggerData(self.theSelectedPropertyName(), aSaveDirectory, aStartTime, anEndTime, anInterval) except: anErrorMessage = "Error : could not save " self["statusbar"].push(1, anErrorMessage) return None aSuccessMessage = " All files you selected are saved. " self["statusbar"].push(1, aSuccessMessage) # end of saveData # --------------------------------------------------------------- # Gets the selected PropertyName # return -> selected propertyname list # --------------------------------------------------------------- def theSelectedPropertyName(self): self.aSelectedPropertyNameList = [] selection = self['loggerWindow_clist'].get_selection() selection.selected_foreach(self.selection_function) return self.aSelectedPropertyNameList def selection_function(self, tree, path, iter): aPropertyName = self["loggerWindow_clist"].get_model().get_value( iter, 0) self.aSelectedPropertyNameList.append(aPropertyName) # end of theSelectedPropertyName # --------------------------------------------------------------- # Updates # return -> None # --------------------------------------------------------------- def update(self): if not self.exists(): return None self.theFullPNList = self.theSession.getLoggerList() self.theList = [] for aFullPNString in self.theFullPNList: aLoggerStub = self.theSession.createLoggerStub(aFullPNString) start = str(aLoggerStub.getStartTime()) if self.theSession.theRunningFlag: end = 'running' else: end = str(aLoggerStub.getEndTime()) aList = [aFullPNString, start, end] self.theList.append(aList) aModel = self.theEntryList.get_model() aModel.clear() for aValue in self.theList: anIter = aModel.append() aModel.set( anIter,\ 0, aValue[0],\ 1, str(aValue[1]),\ 2, str(aValue[2]) ) # --------------------------------------------------------------- # popupMenu # - show popup menu # # aWidget : widget # anEvent : an event # return -> None # This method is throwable exception. # --------------------------------------------------------------- def popupMenu(self, aWidget, anEvent): if len(self.theSelectedPropertyName()) != 0: if anEvent.button == 3: self.thePopupMenu.popup(None, None, None, 1, 0) return False # end of poppuMenu # ============================================================================== def editPolicy(self, *args): if len(self.aSelectedPropertyNameList) == 1: # get loggerpolicy aLoggerStub = self.theSession.createLoggerStub( self.aSelectedPropertyNameList[0]) aLogPolicy = aLoggerStub.getLoggerPolicy() else: aLogPolicy = [0, 0, 0, 0] newLogPolicy = self.theSession.openLogPolicyWindow( aLogPolicy, "Set log policy for selected loggers") if newLogPolicy == None: return for aFullPN in self.aSelectedPropertyNameList: aLoggerStub = self.theSession.createLoggerStub(aFullPN) aLoggerStub.setLoggerPolicy(newLogPolicy) # ============================================================================== def saveDataFile(self, aFullPN, aDirectory=None, anInterval=None, aStartTime=None, anEndTime=None, fileType='ecd'): """ saves FullPN logger data with given parameters if parameters are not given, function defaults to window settings for parameters with a given value it sets appropriate window settings and saves FullPN into Datafile """ #find FullPM in list aFullPNString = createFullPNString(aFullPN) anIter = self.theEntryList.get_model().get_iter_first() while True: if anIter == None: return None aTitle = self.theEntryList.get_model().get_value(anIter, 0) if aTitle == aFullPNString: aPath = self.theEntryList.get_model().get_path(anIter) self.theEntryList.set_cursor(aPath, None, False) break anIter = self.theEntryList.get_model().iter_next(anIter) if aDirectory != None: self.setDirectory(aDirectory) if anInterval != None: self.setInterval(anInterval) if aStartTime != None: self.setStartTime(aStartTime) if anEndTime != None: self.setEndTime(anEndTime) if fileType != None: self.setDataFileType(fileType) self.saveData(None) # ============================================================================== def setDirectory(self, aDirectory): """ sets directory field to aDirectory returns None """ self['directory_entry'].set_text(str(aDirectory)) # ============================================================================== def getDirectory(self): """ returns directory choosen by the user """ return self['directory_entry'].get_text() # ============================================================================== def setInterval(self, anInterval): """ sets Interval field of Loggerwindow to anInterval also sets interval checkbox True """ self['datainterval_spinbutton'].set_value(anInterval) self['datainterval_checkbox'].set_active(True) self.updateDataInterval() # ============================================================================== def getInterval(self): """ returns -1 if Interval checkbox is off rerurns interval set by user if interva check box is on """ if self['datainterval_checkbox'].get_active(): return self['datainterval_spinbutton'].get_value() else: return -1 # ============================================================================== def setStartTime(self, aTime): """ sets StartTime field of Loggerwindow to anInterval also sets time checkbox True """ self['start_spinbutton'].set_value(aTime) self['time_checkbox'].set_active(True) self.updateStartEnd() # ============================================================================== def getStartTime(self): """ returns -1 if Interval checkbox is off rerurns interval set by user if interva check box is on """ if self['time_checkbox'].get_active(): return self['start_spinbutton'].get_value() else: return -1 # ============================================================================== def setEndTime(self, aTime): """ sets EndTime field of Loggerwindow to anInterval also sets time checkbox True """ self['end_spinbutton'].set_value(aTime) self['time_checkbox'].set_active(True) self.updateStartEnd() # ============================================================================== def getEndTime(self): """ returns -1 if Interval checkbox is off returns interval set by user if interva check box is on """ if self['time_checkbox'].get_active(): return self['end_spinbutton'].get_value() else: return -1 # ============================================================================== def getDataFileType(self): """ returns Data Type of file choosen by the user """ return self["datatype_combo"].get_active_text() # ============================================================================== def setDataFileType(self, aDataType): """ sets the Datatype of save file to the window aDataType can only be 'ecd' or 'binary'""" if aDataType == 'ecd' or aDataType == 'binary': self["datatype_combo"].set_text(aDataType) # ============================================================================== def setUseDefaultInterval(self, aBoolean): """ sets interval checkbox to aBoolean """ if aBoolean == True or aBoolean == False: self['datainterval_checkbox'].set_active(aBoolean) self.updateDataInterval() # ============================================================================== def setUseDefaultTime(self, aBoolean): """ sets time checkbox to aBoolean """ if aBoolean == True or aBoolean == False: self['time_checkbox'].set_active(aBoolean) self.updateStartEnd() # ============================================================================== def getUseDefaultInterval(self): """ return state of interval checkbox """ return self['datainterval_checkbox'].get_active() # ============================================================================== def getUseDefaultTime(self): """ return state of time checkbox """ return self['time_checkbox'].get_active()