Example #1
0
    def pluginMenu(self, evt):

        #Wont need this check once Issue 72 is fixed.
        if self.data.has_key('rtdose'):

            #Load RTPlan and first DICOM slice.
            rtd = self.data['rtdose']
            ct1 = self.data['images'][0]
            #Number of slices.
            N = len(self.data['images'])

            #Get slice spacing t, use difference instead of tags to get direction.
            t = self.data['images'][1].ImagePositionPatient[2]-self.data['images'][0].ImagePositionPatient[2]
            zpos = ct1.ImagePositionPatient[2]
            #Check current type of GFOV and switch.
            if rtd.has_key('GridFrameOffsetVector'):
                if rtd.GridFrameOffsetVector[0] == 0.:
                    logger.info("Found Type A - Relative Coordinates\nConverting to Type B - Absolute")
                    #Convert to Type B (Absolute)
                    rtd.GridFrameOffsetVector = list(np.arange(zpos, zpos + t*N, t))
                elif rtd.GridFrameOffsetVector[0] == zpos:
                    logger.info("Found Type B - Absolute Coordinates\nConverting to Type A - Relative")
                    #Convert to Type A (Relative)
                    rtd.GridFrameOffsetVector = list(np.arange(0., abs(t)*N,abs(t)))
            else:
                logger.info("GridFrameOffsetVector key not found in RT-Dose!")

            #Print results.
            np.set_printoptions(precision=2)
            logger.info(np.array(rtd.GridFrameOffsetVector))
            #Publish new rtdose.
            pub.sendMessage('patient.updated.raw_data', self.data)

        else:
            logger.info("Please load a RT-Dose file!")
Example #2
0
	def __init__(self, model):
		self.model = model
		self.data = None
		self.config = model.getConfig()
		self.confPath = "."
		Publisher.subscribe(self.psXmlChanged, "status.change.xmlchanged")
		Publisher().subscribe(self.psConfigPathChanged, "config.path.changed")
Example #3
0
    def SetPlotColors(self):
        """
        
            Set canvas plot colors.
        
        """
        # get number of arrays with custom color
        Nc = 0
        for x in self.plots:
            x.color = None
            if x.array!=None:
                if x.array.color!=None:
                    x.color = x.array.color
                    Nc+=1

        Np = len(self.plots)-Nc        
        np = Np-1
        for x in self.plots:
            if x.color != None:
                color = x.color
            else:
                color = (1.0-(np+1.0)/(Np*1.0),0.0,(np+1.0)/(Np*1.0))
                np -= 1
            if x.source==None:
                x.SetColor(color)
                y = x.children
                while len(y)>0:
                    for z in y:
                        z.SetColor(color)
                    y = y[-1].children
        
        # send color change event to notify history from change
        pub.sendMessage("plot.color_change")
Example #4
0
File: Gui.py Project: willmore/D2C
    def __init__(self, dao, parent=None, id=-1, title='D2C'):
        wx.Frame.__init__(self, parent, id, title, size=(750, 550))

        self.Center()

        self.__initMenuBar()

        toolbar = self.CreateToolBar()
        
        toolbar.AddLabelTool(self.ID_CONF, '', wx.Bitmap(pkg_resources.resource_filename(__package__, "icons/keys-icon.png")))
        toolbar.AddLabelTool(self.ID_CLOUD, '', wx.Bitmap(pkg_resources.resource_filename(__package__, "icons/cloud-hd-icon.png")))
        toolbar.AddLabelTool(self.ID_ADD_DEPLOYMENT, '', wx.Bitmap(pkg_resources.resource_filename(__package__, "icons/network-icon.png")))
     
        self.tabContainer = wx.Notebook(self, -1, style=wx.NB_TOP)
        
        self.imageTab = ImageTab(dao, self.tabContainer, -1)
        self.tabContainer.AddPage(self.imageTab, "Images")
        
        self.imagePanel = RawImagePanel(self.tabContainer, -1)
        #self.tabContainer.AddPage(self.imagePanel, "Source Images")
        
        self.amiPanel = AMIPanel(self.tabContainer, -1)
        self.tabContainer.AddPage(self.amiPanel, "AMIs")
        
        self.deploymentPanel = DeploymentTab(dao, self.tabContainer, -1)
        self.tabContainer.AddPage(self.deploymentPanel, "Deployment Templates/Deployments")
        
        #TODO move to controller
        pub.subscribe(self.__createAMI, "CREATE AMI")
Example #5
0
    def __init__(self, *args, **kwargs):
        MyPanel.__init__(self, *args, **kwargs)        
        sum_box = wx.StaticBox(self, label="Fairness")
        box_sizer = wx.StaticBoxSizer(sum_box, wx.VERTICAL)
        fgs = wx.FlexGridSizer(rows=2, cols=4, hgap = 10)
        box_sizer.Add(fgs, proportion=1, flag=wx.EXPAND)

        fgs.Add(wx.StaticText(self, style=wx.ALIGN_RIGHT), flag = wx.EXPAND)
        fgs.Add(wx.StaticText(self, label="Dept", style=wx.ALIGN_RIGHT), flag=wx.EXPAND) 
        fgs.Add(wx.StaticText(self, label="Room", style=wx.ALIGN_RIGHT), flag=wx.EXPAND)
        fgs.Add(wx.StaticText(self, label="Time", style=wx.ALIGN_RIGHT), flag=wx.EXPAND)

        self.minDeptFields = [wx.StaticText(self, size=self.sz_num_field, style=wx.ALIGN_RIGHT), 
                wx.StaticText(self, style=wx.ALIGN_RIGHT), 
                wx.StaticText(self, size=self.sz_num_field, style=wx.ALIGN_RIGHT)] 
        fgs.Add(wx.StaticText(self, label="Min", style=wx.ALIGN_RIGHT), flag = wx.EXPAND)
        for field in self.minDeptFields:
            fgs.Add(field, flag=wx.EXPAND)

        self.maxDeptFields = [wx.StaticText(self, size=self.sz_num_field, style=wx.ALIGN_RIGHT), 
                wx.StaticText(self, style=wx.ALIGN_RIGHT), 
                wx.StaticText(self, size=self.sz_num_field, style=wx.ALIGN_RIGHT)]
        fgs.Add(wx.StaticText(self, label="Max", style=wx.ALIGN_RIGHT), flag = wx.EXPAND)
        for field in self.maxDeptFields:
            fgs.Add(field, flag=wx.EXPAND)

        self.SetSizerAndFit(box_sizer)
        self.sizer = box_sizer
        pub.subscribe(self.update, "assignments_calced")
		def terminate(self, error = False, msg = None):
			""" Thread termination routine
				param error: False if thread is terminate without error
				param msg: message to submit
			"""

			if not self.end_flag:
				if error:

					###for traceback
					etype = msg[0]
					evalue = msg[1]
					etb = traceback.extract_tb(msg[2])
					sys.stderr.write('Error in routine: your routine here\n')
					sys.stderr.write('Error Type: ' + str(etype) + '\n')
					sys.stderr.write('Error Value: ' + str(evalue) + '\n')
					sys.stderr.write('Traceback: ' + str(etb) + '\n')

					### only for displayed application (-nogui)
					if wx.GetApp():
						wx.CallAfter(Publisher.sendMessage, "error", msg)
						### error sound
						wx.CallAfter(playSound, SIMULATION_ERROR_SOUND_PATH)

				else:
					for m in filter(lambda a: hasattr(a, 'finish'), self.model.componentSet):
						### call finished method
						Publisher.sendMessage('%d.finished'%(id(m)))

					### only for displayed application (-nogui)
					if wx.GetApp() : wx.CallAfter(playSound, SIMULATION_SUCCESS_SOUND_PATH)

			self.end_flag = True
Example #7
0
 def _close_application(self, message):
     self.session.strategy_manager.save_strategies()
     pub.unsubAll()
     self.view.frame.Show(False)
     wx.Yield()
     self.view.frame.Destroy()
     wx.GetApp().Exit()
Example #8
0
    def __init__(self, parent, id = -1):

        pre = wx.PrePanel()

        res = xmlres.loadGuiResource('ViewSelectPanel.xrc')
        res.LoadOnPanel(pre, parent, "ID_VIEWSELECTPANEL")
        self.PostCreate(pre)
        
        self._view_select = xrc.XRCCTRL(self, "ID_VIEW_SELECT")
        
        self._find_text = xrc.XRCCTRL(self, "ID_REFRESH_FIND")
        self._clear_filter = xrc.XRCCTRL(self, "ID_CLEAR_FIND")
        self._filter_text = xrc.XRCCTRL(self, "ID_TEXT_FILTER")
                
        # temp var for delayed selection of view
        self._the_view = -1

        self._our_problem = False
        
        self._initViewSelect()
              
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self._onViewSelected, self._view_select)
        self.Bind(wx.EVT_TEXT, self._onFilterText, self._filter_text)
        self.Bind(wx.EVT_BUTTON, self._onRefreshFilter, self._find_text)
        self.Bind(wx.EVT_BUTTON, self._onClearFilter, self._clear_filter)
        self.Bind(wx.EVT_TEXT_ENTER, self._onRefreshFilter, self._filter_text)
        self.Bind(wx.EVT_UPDATE_UI, self._onUpdateUI)
        Publisher.subscribe(self._onViewChanged, signals.SET_VIEW)
Example #9
0
	def __init__(self, model, view, xmlData):
		self.model = model
		self.view = view
		self.xmlData = xmlData
		
		Publisher.subscribe(self.psXmlDataChanged, "status.change.xmldatachanged")
		Publisher.subscribe(self.itemSelected, "config.function.selected")
Example #10
0
	def __init__(self, *args, **kwargs):
		"""
		General Notebook class for Diagram Notebook on the right part of DEVSimPy.
		"""

		# for splash screen
		pub.sendMessage('object.added', message='Loading notebook diagram...\n')

		Printable.__init__(self)

		# local copy
		self.parent = args[0]
		self.pages = []			# keeps track of pages

		### to propagate the dsp file path in __setstate__ of Block object
		self.current_dsp_file_path = ""

		#icon under tab
		imgList = wx.ImageList(16, 16)
		for img in [os.path.join(ICON_PATH_16_16,'network.png')]:
			imgList.Add(wx.Image(img, wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		self.AssignImageList(imgList)

		### binding
		self.Bind(wx.EVT_LEFT_DCLICK, self.__AddPage)
Example #11
0
    def OnOK(self, evt):
        """Return the patient data if the patient is selected or the button
            is pressed."""
        item = self.tcPatients.GetSelection()
        if self.tcPatients.GetPyData(item):
            # Since we have decided to use this location to import from,
            # update the location in the preferences for the next session
            # if the 'import_location_setting' is "Remember Last Used"
            if (self.import_location_setting == "Remember Last Used"):
                pub.sendMessage('preferences.updated.value',
                    {'general.dicom.import_location':self.path})

            # Since we have updated the search subfolders setting,
            # update the setting in preferences
            pub.sendMessage('preferences.updated.value',
                {'general.dicom.import_search_subfolders':
                 self.import_search_subfolders})

            filearray = self.tcPatients.GetPyData(item)['filearray']
            self.btnSelect.Enable(False)
            self.txtRxDose.Enable(False)
            self.terminate = False
            self.importThread=threading.Thread(target=self.GetPatientData,
            args=(self.path, filearray, self.txtRxDose.GetValue(),
                self.SetThreadStatus, self.OnUpdateProgress))
            self.importThread.start()
Example #12
0
    def LoadMarkets(self):
        self.markets = self.session.GetAvailableMarkets()

        if self.markets == None:
            return False

        self.treeMarkets.DeleteAllItems()
        root = self.treeMarkets.AddRoot('Markets')

        # Add all markets to the tree
        items = {}
        for market in self.markets:
            path = ''
            parent = root
            # Iterate over the market path
            for item in market.menuPathParts:
                path = path + item
                if path in items:
                    parent = items[path]
                    continue
                # Add this node if it doesn't exist
                parent = items[path] = self.treeMarkets.AppendItem(parent, item)
            # After all of the parent nodes are present, at the market type
            items[path + market.marketName] = self.treeMarkets.AppendItem(items[path], market.marketName)
            # Attach the market information to the tree object for extraction later
            self.treeMarkets.SetPyData(items[path + market.marketName], market)

        self.treeMarkets.Expand(root)

        pub.sendMessage(SUBJECT_STATUSBAR,
            'Found ' + str(len(self.markets)) + ' available ' + self.session.sessionType + ' markets')

        return True
Example #13
0
    def save(self):
        fout = open("library.db",'wb')
        pickle.dump(self.books,fout)
        fout.close()

        print "Saved", len(self.books), "books"
        pub.sendMessage("SAVED",len(self.books))
Example #14
0
    def __init__(self, iview):
        '''
        Constructor
        '''
        # ---- projectos
        pub().subscribe(self.add_project_in_tree, T.ADD_PROJECT_IN_TREE)
        pub().subscribe(self.pre_close, T.CLOSE_PROJECT)
        pub().subscribe(self.pre_open, T.OPEN_PROJECT)
        pub().subscribe(self.pre_hide, T.HIDE_PROJECT)
        pub().subscribe(self.pre_unhide, T.UNHIDE_PROJECT)
        pub.subscribe(self.pre_delete, T.DELETE_PROJECT)
        pub().subscribe(self.update_language, T.LANGUAGE_CHANGED)

        # ---- vistas
        pub().subscribe(self.add_view_in_tree, T.ADD_VIEW_IN_TREE)
        pub().subscribe(self.delete_view, T.DELETE_VIEW_TREE)

        # --- results
        pub().subscribe(self.add_results_in_tree, T.ADD_RESULTS_IN_TREE)
        pub().subscribe(self.delete_result, T.DELETE_RESULT_TREE)

        self.iview = iview
        self.init_tree()

        # ---- variables de estado
        self.last_sate_project = None
        self.less_project = False
Example #15
0
 def __init__(self, ip, portFrom, portTo):
     Thread.__init__(self)
     self.IP = ip
     self.portFrom = portFrom
     self.portTo = portTo
     Publisher.sendMessage("scanThread", "started")
     self.start()
Example #16
0
	def __onNewFile(self, event):
		data = {
				'file': None,
				'prjid': None
				}

		pub.sendMessage('notebook.addpage', data)
Example #17
0
    def saveSettings(self):
        """
        Save settings
        """
        db = WpDatabaseAPI()

        ## Saving tab size
        self.configobj.settings['editor-tabsize'] = self.tabsizeinput.GetValue()
        db.AddRegisterSetting('tabsize', self.configobj.settings['editor-tabsize'], 'editor')

        # Saving if tab is to be used
        self.configobj.settings['editor-usetab'] = 1 if self.checkbox.IsChecked() == True else 0
        db.AddRegisterSetting('usetab', self.configobj.settings['editor-usetab'], 'editor')

        ## Saving margin settings
        self.configobj.settings['editor-textmargin'] = self.marginSizeInput.GetValue()
        db.AddRegisterSetting( 'textmargin', self.configobj.settings['editor-textmargin'], 'editor' )

        ## Saving code folding
        self.configobj.settings['editor-foldcode'] = 1 if self.codeFoldCheckbox.IsChecked() == True else 0
        db.AddRegisterSetting('foldcode', self.configobj.settings['editor-foldcode'], 'editor')

        ## Saving code folding style
        self.configobj.settings['editor-foldcodestyle'] = self.foldCodeStyleSelect.GetCurrentSelection()
        db.AddRegisterSetting('foldcodestyle', self.configobj.settings['editor-foldcodestyle'], 'editor')

        ## Saving fonts
        self.configobj.settings['editor-fontface'] = self.fontListCtrl.GetStringSelection()
        self.configobj.settings['editor-fontsize'] = int( self.fontSizeSelect.GetString( self.fontSizeSelect.GetSelection() ) )
        db.AddRegisterSetting( 'fontface', self.configobj.settings['editor-fontface'], 'editor' )
        db.AddRegisterSetting( 'fontsize', self.configobj.settings['editor-fontsize'], 'editor' )

        ## Notify the editor to refrsh
        pub.sendMessage('editor.refresh', True)
Example #18
0
def _createRooms(d, roomInventory, respectRoom, num_prefs = 3):
    """return a prefernece ordered, list of rooms.  
    d is a dictionary of room_prefs {"Room 1":"E51-135", "Room 2":"E62-133"}
    blank requests are ignored.
    Rooms not in inventory will be created if respectRoom = True.
    If room not inventory, and not "respect", will log error."""
    out, all_in_inv = [], True
    for ix_pref in range(1, num_prefs + 1):
        roomName = d.get("Room " + str(ix_pref), "").strip()
        del d["Room " + str(ix_pref)]

        if not roomName:
            continue
        
        #search for it in the list.  
        room_list = filter(lambda x: str(x) == roomName, roomInventory)
        
        if room_list:
            assert len(room_list) == 1
            out.append(room_list[0])
#         elif respectRoom:
#             out.append(ses.Room(roomName, ses.Room.MAX_SIZE))
        else:
            out.append(ses.Room(roomName, ses.Room.MAX_SIZE))
            all_in_inv = False

            #only issue warning if not respect room
            if not respectRoom:
                pub.sendMessage("warning", "Room %s not in inventory" % roomName)


    return out, all_in_inv
Example #19
0
    def _trial_added(self, message):
        trial = message.data
        trial_name = trial.display_name
            
        new_row = self._num_nonempty_rows
        self._trial_ids.append(trial.trial_id)
        self._trials[trial.trial_id] = trial
        self._set_trial_name(new_row, trial_name)

        self._autosize_cols()
        if self._num_empty_rows > 1:
            self._num_empty_rows -= 1
        else:
            self.AppendRows()
        assert len(self._trial_ids) == self._num_nonempty_rows

        # make new trial come in correctly marked.
        row = self._get_row_from_trial_id(trial.trial_id)
        self.SetCellRenderer(row, 0, gridlib.GridCellBoolRenderer())
        self._set_marked_status(row, trial.is_marked)

        # only select new trial if nothing is selected.
        if self._last_trial_id_selected is None:
            self._last_trial_id_selected = 'Not-None'
            wx.CallLater(1000, self._select_row, row)

        pub.sendMessage('SET_RUN_BUTTONS_STATE', data=[True, True])
Example #20
0
    def OnEnablePlugin(self, evt=None):
        """Publish the enabled/disabled state of the plugin."""

        item = self.tcPlugins.GetSelection()
        n = self.tcPlugins.GetPyData(item)
        plugin = self.plugins[n]
        p = plugin['plugin']

        # Set the checkbox to the appropriate state if the event
        # comes from the treeview
        if (evt.EventType == wx.EVT_TREE_ITEM_ACTIVATED.typeId):
            self.checkEnabled.SetValue(not self.checkEnabled.IsChecked())

        if self.checkEnabled.IsChecked():
            self.tcPlugins.SetItemImage(item, 1)
            self.tcPlugins.SetItemTextColour(item, wx.BLACK)
            self.pluginsDisabled.remove(p.__name__)
            logger.debug("%s enabled", p.__name__)
        else:
            self.tcPlugins.SetItemImage(item, 2)
            self.tcPlugins.SetItemTextColour(item, wx.Colour(169, 169, 169))
            self.pluginsDisabled.add(p.__name__)
            logger.debug("%s disabled", p.__name__)

        pub.sendMessage('preferences.updated.value',
                {'general.plugins.disabled_list': list(self.pluginsDisabled)})
Example #21
0
    def __init__(self, parent, plugin_manager, **kwargs):
        wx.Panel.__init__(self, parent, **kwargs)

        self.stage_choosers = []
        for stage_name in stages.stages:
            stage_display_name = stages.get_stage_display_name(stage_name)
            method_names = plugin_manager.get_plugins_by_stage(
                    stage_name).keys()
            self.stage_choosers.append(StageCtrl(self, stage_name,
                                                        stage_display_name,
                                                        sorted(method_names)))
        self.stage_choosers.append(AuxiliaryCtrl(self, 'auxiliary',
                stages.get_stage_display_name('auxiliary')))
        
        # issued when user chooses a stage to adjust its parameters, not when
        # user clicks on results tab.
        pub.subscribe(self.select_stage, "STAGE_CHOSEN")

        sizer = wx.BoxSizer(orient=wx.VERTICAL)
        for stage_chooser in self.stage_choosers:
            sizer.Add(stage_chooser, flag=wx.EXPAND)

        self.SetSizer(sizer)

        pub.subscribe(self._results_notebook_page_changed, 
                      topic='RESULTS_NOTEBOOK_PAGE_CHANGED')

        self._current_stage = stages.stages[0]
Example #22
0
 def _rename_trial(self, event=None):
     if event is not None: # came in through menu
         row = self._row_right_clicked
     else:
         row = self._row_left_dclicked
     trial_id = self._get_trial_id_from_row(row)
     pub.sendMessage(topic='OPEN_RENAME_TRIAL_DIALOG', data=trial_id)
Example #23
0
    def __init__(self, app):

        self.mainwindow = MyParentFrame()
        self.mainwindow.Bind(wx.EVT_MENU, self.On5MinAnalysis, id=ID_Menu_5Min)
        self.mainwindow.Bind(wx.EVT_MENU, self.On30MinAnalysis, id=ID_Menu_30Min)
        self.mainwindow.Bind(wx.EVT_MENU, self.OnDayAnalysis, id=ID_Menu_Day)
        self.mainwindow.Bind(wx.EVT_MENU, self.OnNewRealtimeWindow, id=ID_Menu_Realtime)

        self.mainwindow.Show(True)
        app.SetTopWindow(self.mainwindow)

        self.mainwindow.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        self.mainwindow.symbol_ctrl.Bind(wx.EVT_TEXT_ENTER, self.OnSymbolCtrlEnter)

        self.data_manager = DataManager()
        self.data_manager.start()
        self.symbol = "000001"
        self.data_manager.UpdateSymbol(self.symbol)
        # self.realtime_data = self.data_manager.GetQuoteData(self.symbol, 60, 1).df
        # self.analysis_data = self.data_manager.GetQuoteData(self.symbol, 1800, 30).df
        self._lastclose = self.data_manager.GetLastClose(self.symbol)
        self.realtime_data = None
        self.analysis_data = None
        # for d in self.data_manager.symbol_quote_dict.keys():
        pub.subscribe(self.AnalysisDataArrive, "ANALYSISDATA")
        pub.subscribe(self.RealtimeDataArrive, "REALTIMEDATA")
        self.mainwindow.SetFocus()
        self.realtime_window = None
        self.analysis_window = None
Example #24
0
 def _show_toolbars(self, event):
     if self._toolbars_shown:
         pub.sendMessage(topic='HIDE_TOOLBAR', data=None)
         self._toolbars_shown = False
     else:
         pub.sendMessage(topic='SHOW_TOOLBAR', data=None)
         self._toolbars_shown = True
Example #25
0
 def _update_strategy(self, value=None):
     '''
         Called when a control_panel's value is changed and is valid.  Also
     called when the user changes the method of a stage.
     '''
     strategy = self.get_current_strategy()
     pub.sendMessage('SET_CURRENT_STRATEGY', data=strategy)
Example #26
0
    def run(self):

        old = datetime.datetime.now() + datetime.timedelta(minutes = -1)
        old = datetime.datetime(old.year, old.month, old.day, old.hour, old.minute)
        while not self.done:
            try:                
                now = datetime.datetime.now()                
               # print now, "  ", old
                
                if self._IsMarketOpen(now):#now > old: 
                    self._RealtimeMode() 
                    #time.sleep(1)                   
 
                else:
                    q = GoogleIntradayQuote(self.symbol,self.period, self.num_day)
                    self.quotedata = q
                    pub.sendMessage(self._message_topic, self.quotedata.df) 
                    self.done = True 
                time.sleep(1)   
                        
                         
     
                
            except:
                print str(sys.exc_info())
                self.done = False
Example #27
0
 def _RealtimeMode(self):
     now = datetime.datetime.now() 
     oldtime = self.lastupdate + datetime.timedelta(seconds=self.period)
     if self.lastupdate.date().year != 2000:            
         if oldtime.date() != now.date():
             oldtime = datetime.datetime(now.date().year, now.date().month, now.date().day, 9, 30, 0) + datetime.timedelta(seconds=self.period)
         if self.lastupdate.time() == datetime.time(11, 30, 0):
             oldtime = datetime.datetime(self.lastupdate.date().year, self.lastupdate.date().month,  self.lastupdate.date().day, 13, 0, 0)\
             + datetime.timedelta(seconds=self.period)
                                    
     
               
     #now =  datetime.datetime(now.year, now.month, now.day, now.hour, now.minute) 
     
     if now > oldtime :
         print now, ",",  oldtime                
         q = GoogleIntradayQuote(self.symbol,self.period, self.num_day)
         if self.lastupdate == q.df.index[-1]:
             return
         if True:#q.dtstamp[-1] == now:
             self.lastupdate = q.df.index[-1]
             if self.period == 60:
                 self.realtimedata = q.df
                 pub.sendMessage(self._message_topic, self.realtimedata) 
             else:                    
                 self.quotedata = q
                 pub.sendMessage(self._message_topic, self.quotedata.df) 
Example #28
0
 def GetQuoteData(self, quote, period=300, num_day=5): 
     try:       
         self.quotedata = GoogleIntradayQuote(quote,period, num_day)
         pub.sendMessage("ANALYSISDATA", self.quotedata.df)
         return self.quotedata
     except:
         pass       
Example #29
0
 def decrementClientMinutes(self, subminutes):
     """
     subtrack some of the minutes the client is having
     """
     Publisher.sendMessage("sendingRemaing.Minutes",  data=subminutes)
     self.decrement = self.getClientMinutes() - subminutes
     self.saveRunningStatus(self.decrement)
     
     if(self.setClientMinutes(self.decrement) == False):
         raise ValueError("Unable to set client time")
     else:
         try:
             #print "Doing something like sending to the server"
             #Publish a message to the window.py which will send a message to
             #the server.
             try:
                 #print "Duplicating"
                 Publisher.sendMessage("sendRemainingMinutes", data=str(self.getClientMinutes()))
             except:
                 raise 
             else:
                 self._parent.owed_timetext.SetLabel(str(self.getClientMinutes()))
                 
         except:
             return False
         
     #set the client runtime
     self.setClientRuntime(self.getClientRuntime() + int(subminutes))
     try:
         self.incrementRuntime(self.getClientRuntime())
     except:
         raise 
Example #30
0
    def __init__(self, *args, **kwargs):
        MyPanel.__init__(self, *args, **kwargs)        

        sum_box = wx.StaticBox(self, label="Preferences")
        box_sizer = wx.StaticBoxSizer(sum_box, wx.VERTICAL)
        fgs = wx.FlexGridSizer(rows=3, cols=5)
        box_sizer.Add(fgs, proportion=1, flag=wx.EXPAND)

        fgs.AddMany([(wx.StaticText(self, style=wx.ALIGN_LEFT), 0, wx.EXPAND), 
                    (wx.StaticText(self, label="1st", style=wx.ALIGN_LEFT), 0, wx.EXPAND), 
                    (wx.StaticText(self, label="2nd", style=wx.ALIGN_LEFT), 0, wx.EXPAND),  
                    (wx.StaticText(self, label="3rd", style=wx.ALIGN_LEFT), 0, wx.EXPAND), 
                    (wx.StaticText(self, label="Other", style=wx.ALIGN_LEFT), 0, wx.EXPAND) ])

        self.RoomPrefFields = [wx.StaticText(self, size=self.sz_num_field, style=wx.ALIGN_LEFT), 
                wx.StaticText(self, size=self.sz_num_field, style=wx.ALIGN_LEFT), 
                wx.StaticText(self, size=self.sz_num_field, style=wx.ALIGN_LEFT), 
                wx.StaticText(self, size=self.sz_num_field, style=wx.ALIGN_LEFT)] 
        fgs.Add(wx.StaticText(self, label="Rooms   ", style=wx.TE_LEFT), flag = wx.EXPAND)
        for field in self.RoomPrefFields:
            fgs.Add(field, flag=wx.EXPAND)

        self.TimePrefFields = [wx.StaticText(self, size=self.sz_num_field, style=wx.ALIGN_LEFT), 
                wx.StaticText(self, size=self.sz_num_field, style=wx.ALIGN_LEFT), 
                wx.StaticText(self, size=self.sz_num_field, style=wx.ALIGN_LEFT), 
                wx.StaticText(self, size=self.sz_num_field, style=wx.ALIGN_LEFT)]
        fgs.Add(wx.StaticText(self, label="Times   ", style=wx.TE_LEFT), flag = wx.EXPAND)
        for field in self.TimePrefFields:
            fgs.Add(field, flag=wx.EXPAND)

        self.SetSizerAndFit(box_sizer)
        pub.subscribe(self.updatePrefs, "assignments_calced")
Example #31
0
 def HandleMsg(self, bufsize, fddata, th):
     recvmsg = NetSocketFun.NetSocketRecv(fddata.GetData("sockfd"), bufsize)
     recvlist = NetSocketFun.NetUnPackMsgBody(recvmsg)
     wx.CallAfter(Publisher().sendMessage,
                  CommonData.ViewPublisherc.LOGIN_SWITCH, recvlist)
 def registerPublisher(self):
     Publisher().subscribe(self.tryAgain,
                           CommonData.ViewPublisherc.REGISTER_TRYAGAIN)
     Publisher().subscribe(self.SwitchView,
                           CommonData.ViewPublisherc.REGISTER_SWITCH)
Example #33
0
lastpercentage = 0
i = 0
l = len(lines)
oldValueUnknown = False
TWinstances = 0


try:
	targetL_i = int(targetL)
	targetZ = 100000
except:
	targetL_i = -100000

if Publisher is not None:
	if targetL_i > -100000:
		wx.CallAfter(Publisher().sendMessage, "pluginupdate",
					 "OpenPluginProgressWindow;TweakAtZ;Tweak At Z plugin is executed at layer " + str(targetL_i))
	else:
		wx.CallAfter(Publisher().sendMessage, "pluginupdate",
					 "OpenPluginProgressWindow;TweakAtZ;Tweak At Z plugin is executed at height " + str(targetZ) + "mm")
with open(filename, "w") as file:
	for line in lines:
		if int(i*100/l) > lastpercentage and Publisher is not None: #progressbar
			lastpercentage = int(i*100/l)
			wx.CallAfter(Publisher().sendMessage, "pluginupdate", "Progress;" + str(lastpercentage))
		if ';Layer count:' in line:
			TWinstances += 1
			file.write(';TweakAtZ instances: %d\n' % TWinstances)
		if not ('M84' in line or 'M25' in line or ('G1' in line and TweakPrintSpeed and state==3) or ';TweakAtZ instances:' in line):
			file.write(line)
		IsUM2 = ('FLAVOR:UltiGCode' in line) or IsUM2 #Flavor is UltiGCode!
Example #34
0
    def __init__(self):
        super(mainWindow,
              self).__init__(None, title=_('Cura - ') + version.getVersion())

        wx.EVT_CLOSE(self, self.OnClose)

        # allow dropping any file, restrict later
        self.SetDropTarget(dropTarget.FileDropTarget(self.OnDropFiles))

        # TODO: wxWidgets 2.9.4 has a bug when NSView does not register for dragged types when wx drop target is set. It was fixed in 2.9.5
        if sys.platform.startswith('darwin'):
            try:
                import objc
                nswindow = objc.objc_object(
                    c_void_p=self.MacGetTopLevelWindowRef())
                view = nswindow.contentView()
                view.registerForDraggedTypes_([u'NSFilenamesPboardType'])
            except:
                pass

        self.normalModeOnlyItems = []

        mruFile = os.path.join(profile.getBasePath(), 'mru_filelist.ini')
        self.config = wx.FileConfig(appName="Cura",
                                    localFilename=mruFile,
                                    style=wx.CONFIG_USE_LOCAL_FILE)

        self.ID_MRU_MODEL1, self.ID_MRU_MODEL2, self.ID_MRU_MODEL3, self.ID_MRU_MODEL4, self.ID_MRU_MODEL5, self.ID_MRU_MODEL6, self.ID_MRU_MODEL7, self.ID_MRU_MODEL8, self.ID_MRU_MODEL9, self.ID_MRU_MODEL10 = [
            wx.NewId() for line in xrange(10)
        ]
        self.modelFileHistory = wx.FileHistory(10, self.ID_MRU_MODEL1)
        self.config.SetPath("/ModelMRU")
        self.modelFileHistory.Load(self.config)

        self.ID_MRU_PROFILE1, self.ID_MRU_PROFILE2, self.ID_MRU_PROFILE3, self.ID_MRU_PROFILE4, self.ID_MRU_PROFILE5, self.ID_MRU_PROFILE6, self.ID_MRU_PROFILE7, self.ID_MRU_PROFILE8, self.ID_MRU_PROFILE9, self.ID_MRU_PROFILE10 = [
            wx.NewId() for line in xrange(10)
        ]
        self.profileFileHistory = wx.FileHistory(10, self.ID_MRU_PROFILE1)
        self.config.SetPath("/ProfileMRU")
        self.profileFileHistory.Load(self.config)

        self.menubar = wx.MenuBar()
        self.fileMenu = wx.Menu()
        i = self.fileMenu.Append(-1, _("Load model file...\tCTRL+L"))
        self.Bind(wx.EVT_MENU, lambda e: self.scene.showLoadModel(), i)
        i = self.fileMenu.Append(-1, _("Save model...\tCTRL+S"))
        self.Bind(wx.EVT_MENU, lambda e: self.scene.showSaveModel(), i)
        i = self.fileMenu.Append(-1, _("Reload platform\tF5"))
        self.Bind(wx.EVT_MENU, lambda e: self.scene.reloadScene(e), i)
        i = self.fileMenu.Append(-1, _("Clear platform"))
        self.Bind(wx.EVT_MENU, lambda e: self.scene.OnDeleteAll(e), i)

        self.fileMenu.AppendSeparator()
        i = self.fileMenu.Append(-1, _("Print...\tCTRL+P"))
        self.Bind(wx.EVT_MENU, lambda e: self.scene.OnPrintButton(1), i)
        i = self.fileMenu.Append(-1, _("Save GCode..."))
        self.Bind(wx.EVT_MENU, lambda e: self.scene.showSaveGCode(), i)
        i = self.fileMenu.Append(-1, _("Show slice engine log..."))
        self.Bind(wx.EVT_MENU, lambda e: self.scene._showEngineLog(), i)

        self.fileMenu.AppendSeparator()
        i = self.fileMenu.Append(-1, _("Open Profile..."))
        self.normalModeOnlyItems.append(i)
        self.Bind(wx.EVT_MENU, self.OnLoadProfile, i)
        i = self.fileMenu.Append(-1, _("Save Profile..."))
        self.normalModeOnlyItems.append(i)
        self.Bind(wx.EVT_MENU, self.OnSaveProfile, i)
        i = self.fileMenu.Append(-1, _("Load Profile from GCode..."))
        self.normalModeOnlyItems.append(i)
        self.Bind(wx.EVT_MENU, self.OnLoadProfileFromGcode, i)
        self.fileMenu.AppendSeparator()
        i = self.fileMenu.Append(-1, _("Reset Profile to default"))
        self.normalModeOnlyItems.append(i)
        self.Bind(wx.EVT_MENU, self.OnResetProfile, i)

        self.fileMenu.AppendSeparator()
        i = self.fileMenu.Append(-1, _("Preferences...\tCTRL+,"))
        self.Bind(wx.EVT_MENU, self.OnPreferences, i)
        i = self.fileMenu.Append(-1, _("Machine settings..."))
        self.Bind(wx.EVT_MENU, self.OnMachineSettings, i)
        self.fileMenu.AppendSeparator()

        # Model MRU list
        modelHistoryMenu = wx.Menu()
        self.fileMenu.AppendMenu(wx.NewId(), '&' + _("Recent Model Files"),
                                 modelHistoryMenu)
        self.modelFileHistory.UseMenu(modelHistoryMenu)
        self.modelFileHistory.AddFilesToMenu()
        self.Bind(wx.EVT_MENU_RANGE,
                  self.OnModelMRU,
                  id=self.ID_MRU_MODEL1,
                  id2=self.ID_MRU_MODEL10)

        # Profle MRU list
        profileHistoryMenu = wx.Menu()
        self.fileMenu.AppendMenu(wx.NewId(), _("Recent Profile Files"),
                                 profileHistoryMenu)
        self.profileFileHistory.UseMenu(profileHistoryMenu)
        self.profileFileHistory.AddFilesToMenu()
        self.Bind(wx.EVT_MENU_RANGE,
                  self.OnProfileMRU,
                  id=self.ID_MRU_PROFILE1,
                  id2=self.ID_MRU_PROFILE10)

        self.fileMenu.AppendSeparator()
        i = self.fileMenu.Append(wx.ID_EXIT, _("Quit"))
        self.Bind(wx.EVT_MENU, self.OnQuit, i)
        self.menubar.Append(self.fileMenu, '&' + _("File"))

        toolsMenu = wx.Menu()
        #i = toolsMenu.Append(-1, 'Batch run...')
        #self.Bind(wx.EVT_MENU, self.OnBatchRun, i)
        #self.normalModeOnlyItems.append(i)

        if minecraftImport.hasMinecraft():
            i = toolsMenu.Append(-1, _("Minecraft map import..."))
            self.Bind(wx.EVT_MENU, self.OnMinecraftImport, i)

        if version.isDevVersion():
            i = toolsMenu.Append(-1, _("PID Debugger..."))
            self.Bind(wx.EVT_MENU, self.OnPIDDebugger, i)
            i = toolsMenu.Append(-1, _("Auto Firmware Update..."))
            self.Bind(wx.EVT_MENU, self.OnAutoFirmwareUpdate, i)

        i = toolsMenu.Append(-1, _("Copy profile to clipboard"))
        self.Bind(wx.EVT_MENU, self.onCopyProfileClipboard, i)

        toolsMenu.AppendSeparator()
        self.allAtOnceItem = toolsMenu.Append(-1,
                                              _("Print all at once"),
                                              kind=wx.ITEM_RADIO)
        self.Bind(wx.EVT_MENU, self.onOneAtATimeSwitch, self.allAtOnceItem)
        self.oneAtATime = toolsMenu.Append(-1,
                                           _("Print one at a time"),
                                           kind=wx.ITEM_RADIO)
        self.Bind(wx.EVT_MENU, self.onOneAtATimeSwitch, self.oneAtATime)
        if profile.getPreference('oneAtATime') == 'True':
            self.oneAtATime.Check(True)
        else:
            self.allAtOnceItem.Check(True)

        self.menubar.Append(toolsMenu, _("Tools"))

        #Machine menu for machine configuration/tooling
        self.machineMenu = wx.Menu()
        self.updateMachineMenu()

        self.menubar.Append(self.machineMenu, _("Machine"))

        expertMenu = wx.Menu()
        i = expertMenu.Append(-1,
                              _("Switch to quickprint..."),
                              kind=wx.ITEM_RADIO)
        self.switchToQuickprintMenuItem = i
        self.Bind(wx.EVT_MENU, self.OnSimpleSwitch, i)

        i = expertMenu.Append(-1,
                              _("Switch to full settings..."),
                              kind=wx.ITEM_RADIO)
        self.switchToNormalMenuItem = i
        self.Bind(wx.EVT_MENU, self.OnNormalSwitch, i)
        expertMenu.AppendSeparator()

        i = expertMenu.Append(-1, _("Open expert settings...\tCTRL+E"))
        self.normalModeOnlyItems.append(i)
        self.Bind(wx.EVT_MENU, self.OnExpertOpen, i)
        expertMenu.AppendSeparator()
        self.bedLevelWizardMenuItem = expertMenu.Append(
            -1, _("Run bed leveling wizard..."))
        self.Bind(wx.EVT_MENU, self.OnBedLevelWizard,
                  self.bedLevelWizardMenuItem)
        self.headOffsetWizardMenuItem = expertMenu.Append(
            -1, _("Run head offset wizard..."))
        self.Bind(wx.EVT_MENU, self.OnHeadOffsetWizard,
                  self.headOffsetWizardMenuItem)

        self.menubar.Append(expertMenu, _("Expert"))

        helpMenu = wx.Menu()
        i = helpMenu.Append(-1, _("Online documentation..."))
        self.Bind(wx.EVT_MENU,
                  lambda e: webbrowser.open('http://lulzbot.com/cura'), i)
        i = helpMenu.Append(-1, _("Report a problem..."))
        self.Bind(
            wx.EVT_MENU, lambda e: webbrowser.open(
                'https://github.com/alephobjects/Cura/issues'), i)
        #i = helpMenu.Append(-1, _("Check for update..."))
        #self.Bind(wx.EVT_MENU, self.OnCheckForUpdate, i)
        #i = helpMenu.Append(-1, _("Open YouMagine website..."))
        #self.Bind(wx.EVT_MENU, lambda e: webbrowser.open('https://www.youmagine.com/'), i)
        i = helpMenu.Append(-1, _("About Cura..."))
        self.Bind(wx.EVT_MENU, self.OnAbout, i)
        self.menubar.Append(helpMenu, _("Help"))
        self.SetMenuBar(self.menubar)

        self.splitter = wx.SplitterWindow(self,
                                          style=wx.SP_3D | wx.SP_LIVE_UPDATE)
        self.leftPane = wx.Panel(self.splitter, style=wx.BORDER_NONE)
        self.rightPane = wx.Panel(self.splitter, style=wx.BORDER_NONE)
        self.splitter.Bind(wx.EVT_SPLITTER_DCLICK, lambda evt: evt.Veto())

        #Preview window
        self.scene = sceneView.SceneView(self.rightPane)

        ##Gui components##
        self.simpleSettingsPanel = simpleMode.simpleModePanel(
            self.leftPane, self.scene.sceneUpdated)
        self.normalSettingsPanel = normalSettingsPanel(self.leftPane,
                                                       self.scene.sceneUpdated)

        self.leftSizer = wx.BoxSizer(wx.VERTICAL)
        self.leftSizer.Add(self.simpleSettingsPanel, 1)
        self.leftSizer.Add(self.normalSettingsPanel, 1, wx.EXPAND)
        self.leftPane.SetSizer(self.leftSizer)

        #Main sizer, to position the preview window, buttons and tab control
        sizer = wx.BoxSizer()
        self.rightPane.SetSizer(sizer)
        sizer.Add(self.scene, 1, flag=wx.EXPAND)

        # Main window sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(sizer)
        sizer.Add(self.splitter, 1, wx.EXPAND)
        sizer.Layout()
        self.sizer = sizer

        self.updateProfileToAllControls()

        self.SetBackgroundColour(
            self.normalSettingsPanel.GetBackgroundColour())

        self.simpleSettingsPanel.Show(False)
        self.normalSettingsPanel.Show(False)

        # Set default window size & position
        self.SetSize((wx.Display().GetClientArea().GetWidth() / 2,
                      wx.Display().GetClientArea().GetHeight() / 2))
        self.Centre()

        #Timer set; used to check if profile is on the clipboard
        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.onTimer)
        self.timer.Start(1000)
        self.lastTriedClipboard = profile.getProfileString()

        # Restore the window position, size & state from the preferences file
        try:
            if profile.getPreference('window_maximized') == 'True':
                self.Maximize(True)
            else:
                posx = int(profile.getPreference('window_pos_x'))
                posy = int(profile.getPreference('window_pos_y'))
                width = int(profile.getPreference('window_width'))
                height = int(profile.getPreference('window_height'))
                if posx > 0 or posy > 0:
                    self.SetPosition((posx, posy))
                if width > 0 and height > 0:
                    self.SetSize((width, height))

            self.normalSashPos = int(
                profile.getPreference('window_normal_sash'))
        except:
            self.normalSashPos = 0
            self.Maximize(True)
        if self.normalSashPos < self.normalSettingsPanel.printPanel.GetBestSize(
        )[0] + 5:
            self.normalSashPos = self.normalSettingsPanel.printPanel.GetBestSize(
            )[0] + 5

        self.splitter.SplitVertically(self.leftPane, self.rightPane,
                                      self.normalSashPos)

        if wx.Display.GetFromPoint(self.GetPosition()) < 0:
            self.Centre()
        if wx.Display.GetFromPoint(
            (self.GetPositionTuple()[0] + self.GetSizeTuple()[1],
             self.GetPositionTuple()[1] + self.GetSizeTuple()[1])) < 0:
            self.Centre()
        if wx.Display.GetFromPoint(self.GetPosition()) < 0:
            self.SetSize((800, 600))
            self.Centre()

        self.updateSliceMode()
        self.scene.SetFocus()
        self.dialogframe = None
        if Publisher is not None:
            Publisher().subscribe(self.onPluginUpdate, "pluginupdate")
oldValueUnknown = False
TWinstances = 0

try:
    targetL_i = int(targetL)
    targetZ = 100000
except:
    targetL_i = -100000

with open(filename, "w") as file:
    for line in lines:
        if int(i * 100 /
               l) > lastpercentage and Publisher is not None:  #progressbar
            lastpercentage = int(i * 100 / l)
            if targetL_i > -100000:
                wx.CallAfter(Publisher().sendMessage, "pluginupdate",
                             ("TweakAtZ Layer %d" % targetL_i) + ";" +
                             str(lastpercentage))
            else:
                wx.CallAfter(Publisher().sendMessage, "pluginupdate",
                             ("TweakAtZ %1.2f" % targetZ) + "mm;" +
                             str(lastpercentage))
        if ';Layer count:' in line:
            TWinstances += 1
            file.write(';TweakAtZ instances: %d\n' % TWinstances)
        if not ('M84' in line or 'M25' in line or
                ('G1' in line and TweakPrintSpeed and state == 3)
                or ';TweakAtZ instances:' in line):
            file.write(line)
        IsUM2 = ('FLAVOR:UltiGCode' in line) or IsUM2  #Flavor is UltiGCode!
        if ';TweakAtZ-state' in line:  #checks for state change comment
Example #36
0
 def run(self):
     """Run Worker Thread."""
     # This is the code executing in the new thread.
     for i in range(20):
         time.sleep(0.25)
         wx.CallAfter(Publisher().sendMessage, "update", "")
Example #37
0
 def applyPreferences(self):
     PluginPage.applyPreferences(self)
     # Send the plugin changed message when the plugin settings are
     # applied
     Publisher().sendMessage('peppy.plugins.changed')
Example #38
0
                    "Some default values have changed that affect\nlocal view settings.  Do you want to update the\nlocal settings for all affected views?\n\nIf not, the settings will not change current views\nbut will remain the defaults to be applied the\nnext time a view is created.",
                    "Apply Local Settings?", wx.YES_NO | wx.ICON_QUESTION)
                retval = dlg2.ShowModal()
                dlg2.Destroy()
                if retval != wx.ID_YES:
                    locals = {}
            Publisher().sendMessage('peppy.preferences.changed', locals)
        dlg.Destroy()

    def action(self, index=-1, multiplier=1):
        self.showDialog()


# FIXME: this is probably not the standard way I want to set up
# messages, but it works for now.  Will refactor at some point.
Publisher().subscribe(Preferences.showDialog, 'peppy.preferences.show')


class PeppyPrefClassList(PrefClassList):
    """Add icon support to PrefClassTree"""
    def setIconStorage(self):
        getIconStorage().assignList(self)

    def getIcon(self, cls):
        icon = None
        if hasattr(cls, 'icon') and cls.icon is not None:
            icon = getIconStorage(cls.icon)
        else:
            icon = getIconStorage("icons/blank.png")
        return icon
Example #39
0
from swap.xmltools.XmlSettings import XmlSettings
from swap.xmltools.XmlNetwork import XmlNetwork
from swap.modem.CcPacket import CcPacket

import time
import os
import sys

import wx.lib.agw.aui as aui
import wx
import wxversion

if wxversion.checkInstalled("2.8"):
    wx_version = "2.8"
    from wx.lib.pubsub import Publisher
    pub = Publisher()
elif wxversion.checkInstalled("2.9"):
    wx_version = "2.9"
    from wx.lib.pubsub import pub
elif wxversion.checkInstalled("3.0"):
    wx_version = "3.0"
    from wx.lib.pubsub import pub
else:
    print "version of wxpython not supported"


class MainFrame(wx.Frame):
    '''
    Main GUI frame
    '''
    def __init__(self, title, parent=None, server=None):
Example #40
0
    def __init__(self, parent, id, title, aDEVS, separator=" "):
        """ Constructor
		"""

        wx.Frame.__init__(self,
                          parent,
                          wx.ID_ANY,
                          aDEVS.getBlockModel().label,
                          size=(550, 500),
                          style=wx.DEFAULT_FRAME_STYLE
                          | wx.NO_FULL_REPAINT_ON_RESIZE | wx.STAY_ON_TOP)

        self.model = aDEVS
        self.sep = separator

        ### toolbar setting
        toolbar = wx.ToolBar(self,
                             wx.ID_ANY,
                             style=wx.TB_HORIZONTAL | wx.NO_BORDER | wx.TB_FLAT
                             | wx.TB_TEXT)
        toolbar.SetToolBitmapSize((25, 25))  # just for windows
        new = toolbar.AddSimpleTool(
            wx.NewId(),
            wx.Image(os.path.join(ICON_PATH, 'new.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap(), _('New'), '')
        open_file = toolbar.AddSimpleTool(
            wx.NewId(),
            wx.Image(os.path.join(ICON_PATH, 'open.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap(), _('Open'), '')
        saveas = toolbar.AddSimpleTool(
            wx.NewId(),
            wx.Image(os.path.join(ICON_PATH, 'save.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap(), _('SaveAs'), '')
        toolbar.AddSeparator()
        cut = toolbar.AddSimpleTool(
            wx.NewId(),
            wx.Image(os.path.join(ICON_PATH, 'cut.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap(), _('Cut'), '')
        copy = toolbar.AddSimpleTool(
            wx.NewId(),
            wx.Image(os.path.join(ICON_PATH, 'copy.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap(), _('Copy'), '')
        paste = toolbar.AddSimpleTool(
            wx.NewId(),
            wx.Image(os.path.join(ICON_PATH, 'paste.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap(), _('Paste'), '')
        self.delete = toolbar.AddSimpleTool(
            wx.NewId(),
            wx.Image(os.path.join(ICON_PATH, 'close.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap(), _('Delete'), '')
        toolbar.AddSeparator()
        update = toolbar.AddSimpleTool(
            wx.NewId(),
            wx.Image(os.path.join(ICON_PATH, 'reload.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap(), _('Update'), '')
        toolbar.AddSeparator()
        self.chart = toolbar.AddSimpleTool(
            wx.NewId(),
            wx.Image(os.path.join(ICON_PATH, 'graph_guru.png'),
                     wx.BITMAP_TYPE_PNG).ConvertToBitmap(), _('Chart'), '')
        toolbar.EnableTool(self.chart.GetId(), False)
        toolbar.Realize()

        self.SetToolBar(toolbar)

        self.statusbar = self.CreateStatusBar()

        ### notebook setting
        self.notebook = wx.Notebook(self, wx.ID_ANY)

        ### Load data form devs model
        self.LoadingDataInPage()

        ### Layout
        box = wx.BoxSizer(wx.VERTICAL)
        box.Add(self.notebook, 1, wx.EXPAND)
        self.SetSizer(box)

        ### binding
        self.Bind(wx.EVT_TOOL, self.OnNew, new)
        self.Bind(wx.EVT_TOOL, self.OnOpen, open_file)
        self.Bind(wx.EVT_TOOL, self.OnSaveAs, saveas)
        self.Bind(wx.EVT_TOOL, self.OnCopy, copy)
        self.Bind(wx.EVT_TOOL, self.OnCut, cut)
        self.Bind(wx.EVT_TOOL, self.OnPaste, paste)
        self.Bind(wx.EVT_TOOL, self.OnDelete, self.delete)
        self.Bind(wx.EVT_TOOL, self.OnUpdate, update)
        self.Bind(wx.EVT_TOOL, self.OnGraph, self.chart)

        self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnTab, self.notebook)

        ### pubsub
        ### when is sheet is full, graph icon is enabled
        Publisher.subscribe(self.EnableGraphIcon, ("isfull"))
        Publisher.subscribe(self.OnProgress, ("progress"))
Example #41
0
def publish(topic, data=None):
    Publisher.sendMessage(topic, data)
Example #42
0
 def postTime(self, amt):
     """
     Send time to GUI
     """
     amtOfTime = (amt + 1) * 10
     Publisher().sendMessage("update", amtOfTime)
Example #43
0
def subscribe(listener, topic):
    Publisher.subscribe(listener, topic)
Example #44
0
def unsubscribe(listener):
    Publisher.unsubscribe(listener)
Example #45
0
class fcEventManager(object):
    ''' Simple wrapper around pubsub to allow for easy exchange against other
        event libraries. Could probably need a rewrite. I am not sure the
        EventTypeTemplate and **keys methods are the best way to do this.
        Maybe just wrap send, subscribe, ... directly.
    '''
    class EventTypeTemplate(type):
        ''' Meta-class to create a specific event-type'''
        def __init__(cls, name, bases, dikt):
            type.__init__(cls, name, bases, dikt)

            def __init__(self, **keys):
                self.__dict__.update(**keys)
                self.vars = keys

            cls.__init__ = __init__

    def __init__(self):
        self.publisher = Publisher()
        self.event_types = {}
        self._wrapper_funcs = {}

    def send(self, event_name, **keys):
        try:
            evt_type = self.event_types[event_name]
        except KeyError:
            evt_type = self.event_types[event_name] = self.EventTypeTemplate(
                event_name, (), {})

        event_instance = evt_type(**keys)
        return self.publisher.sendMessage(event_name, event_instance)

    def sendEvent(self, event_name, event):
        return self.publisher.sendMessage(event_name, event)

    def subscribe(self, subscriber, event_name):
        def wrap(msg):
            return subscriber(msg.data)

        # we need to add this into a dictionary, because we have to keep a
        # reference to the wrap function. publisher uses weakrefs.
        self._wrapper_funcs.setdefault(_getId(subscriber),
                                       {})[event_name] = wrap
        return self.publisher.subscribe(wrap, event_name)

    def unsubscribe(self, subscriber, event_name=None):
        try:
            self._wrapper_funcs[_getId(subscriber)]
        except KeyError:  # isn't subscribed here, ignore it
            return

        if event_name is None:
            func = self._wrapper_funcs[_getId(subscriber)].values()[0]
        else:
            func = self._wrapper_funcs[_getId(subscriber)][event_name]

        result = self.publisher.unsubscribe(func, event_name)

        if event_name is None:
            del self._wrapper_funcs[_getId(subscriber)]
        else:
            del self._wrapper_funcs[_getId(subscriber)][event_name]

        return result
Example #46
0
 def __init__(self):
     self.publisher = Publisher()
     self.event_types = {}
     self._wrapper_funcs = {}
Example #47
0
def bestmatch(A,
              imgpaths,
              bb=None,
              img2flip=None,
              do_smooth=0,
              xwinA=3,
              ywinA=3,
              xwinI=3,
              ywinI=3,
              prevmatches=None,
              jobid=None,
              queue_mygauge=None,
              patch_outpaths=None):
    """ Runs template matching on IMGPATHS, searching for best match
    for A. 
    Input:
        A: Either a string (path), or an IplImage.
        list IMGPATHS: List of imgpaths to search over
        tuple BB: (x1,y1,x2,y2)
            Search window to do template matching over.
        dict IMG2FLIP: maps {str imgpath: bool isflipped}
        int DO_SMOOTH:
        dict PREVMATCHES: {imgpath: [(x_i, y_i), ...]}. Matches to ignore.
        obj QUEUE_MYGAUGE:
            Used to signal to a running MyGauge instance that one job has
            completed. (Typically, this gauge lives in a separate process)
        dict PATCH_OUTPATHS: {str imgpath: str patch_outpath}
            If given, then save each patch to disk given by the patchpath in
            PATCH_OUTPATHS.
    Output:
        dict {str IMGPATH: (x1, y1, float score)}.
    """
    if type(A) in (str, unicode):
        A_im = cv.LoadImage(A, cv.CV_LOAD_IMAGE_GRAYSCALE)
    else:
        A_im = A
    if do_smooth == SMOOTH_BOTH_BRD or do_smooth == SMOOTH_A_BRD:
        A_im = smooth(A_im, xwinA, ywinA, bordertype='const', val=255)
    elif do_smooth in (SMOOTH_BOTH, SMOOTH_A):
        A_im = smooth(A_im, xwinA, ywinA)
    w_A, h_A = cv.GetSize(A_im)
    results = {}
    for i, imgpath in enumerate(imgpaths):
        if type(imgpath) in (str, unicode):
            I = cv.LoadImage(imgpath, cv.CV_LOAD_IMAGE_GRAYSCALE)
            Iorig = I
        else:
            I = imgpath
            Iorig = I
            imgpath = i
        if do_smooth in (SMOOTH_BOTH_BRD, SMOOTH_IMG_BRD):
            I = smooth(I, xwinI, ywinI, bordertype='const', val=255)
        elif do_smooth in (SMOOTH_BOTH, SMOOTH_IMG):
            I = smooth(I, xwinI, ywinI)
        if img2flip and img2flip[imgpath]:
            cv.Flip(I, I, flipMode=-1)
            Iorig = I
        if bb != None:
            new_roi = tuple(
                map(int, (bb[0], bb[1], bb[2] - bb[0], bb[3] - bb[1])))
            cv.SetImageROI(I, new_roi)
        w_I, h_I = cv.GetSize(I)
        matchmat = cv.CreateMat(h_I - h_A + 1, w_I - w_A + 1, cv.CV_32F)
        cv.MatchTemplate(I, A_im, matchmat, cv.CV_TM_CCOEFF_NORMED)
        # 0.) Suppress previously-found matches, if any
        prevmats = prevmatches.get(imgpath, []) if prevmatches else []
        for (x, y) in prevmats:
            print 'suppressing: {0} at {1}'.format(imgpath, (x, y))
            _x1 = max(0, int(x - (w_A / 3)))
            _y1 = max(0, int(y - (h_A / 3)))
            _x2 = min(matchmat.cols, int(x + (w_A / 3)))
            _y2 = min(matchmat.rows, int(y + (h_A / 3)))
            matchmat[_y1:_y2, _x1:_x2] = -1.0
        minResp, maxResp, minLoc, maxLoc = cv.MinMaxLoc(matchmat)
        x, y = maxLoc[0], maxLoc[1]
        if bb != None:
            x += bb[0]
            y += bb[1]
        results[imgpath] = (x, y, maxResp)
        # Save the patch to disk if necessary
        if patch_outpaths:
            outpath = patch_outpaths.get(imgpath, None)
            if outpath:
                try:
                    os.makedirs(os.path.split(outpath)[0])
                except:
                    pass
                cv.SetImageROI(Iorig, (int(x), int(y), int(w_A), int(h_A)))
                cv.SaveImage(outpath, Iorig)
        if jobid and wx.App.IsMainLoopRunning():
            wx.CallAfter(Publisher().sendMessage, "signals.MyGauge.tick",
                         (jobid, ))
        if queue_mygauge != None:
            queue_mygauge.put(True)

    return results
Example #48
0
    def __init__(self, parent, id, title, master):
        """ Constructor
		"""

        #		if isinstance(parent, wx.Panel):
        #			wx.Panel.__init__(self, parent, id)
        #			self.SetBackgroundColour(wx.NullColour)
        #			self.panel = self
        #
        #			### panel inherit of the left splitter size
        #			self.panel.SetSize(parent.GetParent().GetSize())
        #
        #			# status bar of main application
        #			self.statusbar = parent.GetTopLevelParent().statusbar
        #		else:
        #			wx.Frame.__init__(self, parent, id, title, style= wx.DEFAULT_FRAME_STYLE)
        #
        #			### adapt size of frame depending on the plate-form
        #			if  '__WXMSW__' in wx.PlatformInfo:
        #				self.SetSize((320,280))
        #			else:
        #				self.SetSize((280,160))
        #
        #			# disable the roll out of the frame
        #			self.SetMinSize(self.GetSize())
        #
        #			self.panel = wx.Panel(self, -1)
        #
        #			wx.CallAfter(self.CreateBar)
        #
        #			self.__set_properties()

        # local copy
        self.parent = parent
        self.master = master
        self.title = title

        ### current master for multi-simulation without simulationDialog reloading (show OnOk)
        self.current_master = None

        # simulator strategy
        self.selected_strategy = DEFAULT_SIM_STRATEGY

        ### dynamic structure only for local PyPDEVS simulation
        self.dynamic_structure_flag = __builtin__.__dict__['DYNAMIC_STRUCTURE']

        ### PyPDEVS threaded real time simulation
        self.real_time_flag = __builtin__.__dict__['REAL_TIME']

        ### profiling simulation with hotshot
        self.prof = False

        ### No time limit simulation (defined in the builtin dictionary from .devsimpy file)
        self.ntl = __builtin__.__dict__['NTL']

        self.verbose = __builtin__.__dict__['VERBOSE']

        # definition of the thread, the timer and the counter for the simulation progress
        self.thread = None
        self.timer = wx.Timer(self, wx.NewId())
        self.count = 10.0
        self.stdioWin = None

        self.__widgets()
        self.__do_layout()
        self.__set_events()

        ### create a pubsub receiver (simple way to communicate with thread)
        pub.subscribe(self.ErrorManager, "error")
Example #49
0
    def __init__(self, parent):
        """"""
        wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)

        panel = self
        sizer = wx.GridBagSizer(6, 5)

        xIndex = 0
    # [0] Main Database Text, Entry and Browse Button --------------------------
        label_MainDatabase = wx.StaticText(panel, label="Database:")
        help_Database = "The 'Database' is the main collection of music you will create or update. Click BROWSE to select a previously created database, or enter a new name here."
        label_MainDatabase.SetToolTip(wx.ToolTip(help_Database))
        sizer.Add(label_MainDatabase, pos=(xIndex, 0), flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL|wx.TOP, border=10)

        self.tc_MainDatabase = wx.TextCtrl(panel)
        self.tc_MainDatabase.SetToolTip(wx.ToolTip(help_Database))
        self.tc_MainDatabase.Value = guiFunctions.configMe("scan", "database")
        sizer.Add(self.tc_MainDatabase, pos=(xIndex, 1), span=(1, 4), flag=wx.TOP|wx.EXPAND|wx.ALIGN_CENTER_VERTICAL, border=10)

        self.bt_MainDatabase = wx.Button(panel, label="Browse...")
        self.bt_MainDatabase.SetToolTip(wx.ToolTip(help_Database))
        sizer.Add(self.bt_MainDatabase, pos=(xIndex, 5), flag=wx.RIGHT|wx.TOP|wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border=10)
        self.bt_MainDatabase.Bind(wx.EVT_BUTTON, self.bt_MainDatabaseClick,self.bt_MainDatabase)
        xIndex += 1
    # [0] INI Overide ----------------------------------------------------------
#        label_INI = wx.StaticText(panel, label="INI File:")
#        help_INI = "Override scan.ini with your own INI file."
#        label_INI.SetToolTip(wx.ToolTip(help_Database))
#        sizer.Add(label_INI, pos=(xIndex, 0), flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL|wx.TOP, border=10)
#
#        self.tc_INI = wx.TextCtrl(panel)
#        self.tc_INI.SetToolTip(wx.ToolTip(help_INI))
#        self.tc_INI.Value = guiFunctions.configMe("scan", "inioverride")
#        sizer.Add(self.tc_INI, pos=(xIndex, 1), span=(1, 4), flag=wx.TOP|wx.EXPAND|wx.ALIGN_CENTER_VERTICAL, border=10)
#
#        self.bt_INI = wx.Button(panel, label="Browse...")
#        self.bt_INI.SetToolTip(wx.ToolTip(help_INI))
#        sizer.Add(self.bt_INI, pos=(xIndex, 5), flag=wx.RIGHT|wx.TOP|wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border=10)
#        self.bt_INI.Bind(wx.EVT_BUTTON, self.bt_INIClick,self.bt_INI)
#        xIndex += 1
    # --------------------------------------------------------------------------
    # [1] Paths to scan for new Music ------------------------------------------
        self.sb_FoldersToScan = wx.StaticBox(panel, label="Folders to Scan:", size=(200, 100))
        help_FoldersToScan = "Folders you will scan for music files are listed here. Click ADD to browse for a *top-level* folder. Scan will search all sub-folders for valid music."
        folderBoxSizer = wx.StaticBoxSizer(self.sb_FoldersToScan, wx.VERTICAL)
        self.multiText = wx.TextCtrl(panel, -1,"",size=(300, 100), style=wx.TE_MULTILINE|wx.TE_READONLY)
        self.multiText.SetToolTip(wx.ToolTip(help_FoldersToScan))
        self.multiText.SetInsertionPoint(0)
        self.multiText.Value = guiFunctions.configMe("scan", "folder", parse=True)
        folderBoxSizer.Add(self.multiText, flag=wx.EXPAND)
        sizer.Add(folderBoxSizer, pos=(xIndex, 0), span=(1, 6), flag=wx.EXPAND|wx.TOP|wx.LEFT|wx.RIGHT, border=10)
        xIndex += 1
    # --------------------------------------------------------------------------
    # [2] Buttons to Add Folder, Clear Scan Area -------------------------------
        # ADD FOLDER
        self.bt_FoldersToScanAdd = wx.Button(panel, label="Add")
        help_FoldersToScanAdd = "Add a top-level folder to the 'Folders to Scan' field. The scan will search any sub-folders beneath whatever folder you add."
        self.bt_FoldersToScanAdd.SetToolTip(wx.ToolTip(help_FoldersToScanAdd))
        self.bt_FoldersToScanAdd.Bind(wx.EVT_BUTTON, self.bt_FoldersToScanAddClick, self.bt_FoldersToScanAdd)
        sizer.Add(self.bt_FoldersToScanAdd, pos=(xIndex,0), span=(1,2), flag=wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, border=10)

        # CLEAR SCAN AREA
        self.bt_FoldersToScanClear = wx.Button(panel, label="Clear")
        help_FoldersToScanClear = "Clear the Folders to Scan field."
        self.bt_FoldersToScanClear.SetToolTip(wx.ToolTip(help_FoldersToScanClear))
        sizer.Add(self.bt_FoldersToScanClear, pos=(xIndex,5), flag=wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border=10)
        self.bt_FoldersToScanClear.Bind(wx.EVT_BUTTON, self.bt_FoldersToScanClearClick, self.bt_FoldersToScanClear)
        xIndex += 1
    # --------------------------------------------------------------------------
    # [3] Separator line -------------------------------------------------------
        hl_SepLine1 = wx.StaticLine(panel, 0, (250, 50), (300,1))
        sizer.Add(hl_SepLine1, pos=(xIndex, 0), span=(1, 6), flag=wx.EXPAND, border=10)
        xIndex += 1
    # --------------------------------------------------------------------------
    # [4] Add Scan Options and Scan Button -------------------------------------
        # SCAN/UPDATE
        self.bt_ScanUpdate = wx.Button(panel, label="Scan/Update")
        help_ScanUpdate = "Click here to begin your scan of the folders listed above. This will create a new database if one doesn't exist. Otherwise it will update the database with any new music it finds."
        self.bt_ScanUpdate.SetToolTip(wx.ToolTip(help_ScanUpdate))
        self.bt_ScanUpdate.Bind(wx.EVT_BUTTON, self.bt_ScanUpdateClick, self.bt_ScanUpdate)
        sizer.Add(self.bt_ScanUpdate, pos=(xIndex,0), flag=wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, border=10)

        # REPAIR
        self.bt_ScanRepair = wx.Button(panel, label="Repair")
        help_ScanRepair = "Click here to repair the 'Database' listed above."
        self.bt_ScanRepair.SetToolTip(wx.ToolTip(help_ScanRepair))
        self.bt_ScanRepair.Bind(wx.EVT_BUTTON, self.bt_ScanRepairClick, self.bt_ScanRepair)
        sizer.Add(self.bt_ScanRepair, pos=(xIndex,1), span=(1,2), flag=wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, border=10)

        # VERBOSE
        self.ck_ScanVerbose = wx.CheckBox(panel, label="Verbose")
        help_ScanVerbose = "Select this checkbox if you want to turn on the verbose settings during the scan."
        self.ck_ScanVerbose.SetToolTip(wx.ToolTip(help_ScanVerbose))
        self.ck_ScanVerbose.Value = guiFunctions.configMe("scan", "verbose", bool=True)
        sizer.Add(self.ck_ScanVerbose, pos=(xIndex,3), flag=wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, border=10)

        # SAVE LOG TO FILE
        self.bt_SaveLog = wx.Button(panel, label="Save Log")
        help_SaveLogToFile = "Save the log below to a file."
        self.bt_SaveLog.SetToolTip(wx.ToolTip(help_SaveLogToFile))
        self.bt_SaveLog.Bind(wx.EVT_BUTTON, self.bt_SaveLogClick, self.bt_SaveLog)
        sizer.Add(self.bt_SaveLog, pos=(xIndex,4), flag=wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, border=5)

        # SAVE AS DEFAULTS
        self.bt_SaveDefaults = wx.Button(panel, label="Save Defaults")
        help_SaveDefaults = "Save current settings as default."
        self.bt_SaveDefaults.SetToolTip(wx.ToolTip(help_SaveDefaults))
        self.bt_SaveDefaults.Bind(wx.EVT_BUTTON, self.bt_SaveDefaultsClick, self.bt_SaveDefaults)
        sizer.Add(self.bt_SaveDefaults, pos=(xIndex,5), flag=wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, border=10)
        xIndex += 1
    # --------------------------------------------------------------------------
    # [5] Separator line ------------------------------------------------------
        hl_SepLine2 = wx.StaticLine(panel, 0, (250, 50), (330,1))
        sizer.Add(hl_SepLine2, pos=(xIndex, 0), span=(1, 6), flag=wx.EXPAND, border=10)
        xIndex += 1
    # --------------------------------------------------------------------------
    # [6] Output/Log Box -------------------------------------------------------
        self.LogWindow = wx.TextCtrl(panel, -1,"",size=(100, 310), style=wx.TE_MULTILINE|wx.TE_READONLY)
        LogFont = wx.Font(7.5, wx.SWISS, wx.NORMAL, wx.NORMAL, False)
        self.LogWindow.SetFont(LogFont)
        self.LogWindow.Disable()
        help_LogWindow = "Results of a scan or repair will appear here."
        self.LogWindow.SetToolTip(wx.ToolTip(help_LogWindow))
        self.LogWindow.SetInsertionPoint(0)
        sizer.Add(self.LogWindow, pos=(xIndex,0), span=(1,6), flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, border=10)
        xIndex += 1

        # Indicate we don't have a worker thread yet
        EVT_RESULT(self,self.onResult)
        self.worker = None

        Publisher().subscribe(self.setScanPanel, 'setScanPanel')

        sizer.AddGrowableCol(2)
        panel.SetSizer(sizer)
Example #50
0
def get_tempmatches(A,
                    imgpaths,
                    img2flip=None,
                    T=0.8,
                    bb=None,
                    do_smooth=0,
                    xwinA=13,
                    ywinA=13,
                    xwinI=13,
                    ywinI=13,
                    MAX_MATS=50,
                    prevmatches=None,
                    DELT=0.5,
                    atleastone=False,
                    jobid=None,
                    queue_mygauge=None):
    """ Runs template matching, trying to find image A within each image
    in IMGPATHS. Returns location (and responses) of all matches greater than
    some threshold T.
    Input:
        IplImage A:
        list IMGPATHS:
        dict IMG2FLIP: maps {str imgpath: bool isflipped}
        float T: Template-matching sensitivity
        tuple BB: (x1,y1,x2,y2)
            Search in each img in IMGPATHS inside this BB only.
        float DELT: How much we should perform non-maximal suppression,
            on each axis.
        dict PREVMATCHES: maps {str imgpath: [(x1,y1,x2,y2), ...]}
    Output:
        dict MATCHES, of the form {str imgpath: [(x1, y1, x2, y2, float score), ...]}
    """
    if do_smooth == SMOOTH_BOTH_BRD or do_smooth == SMOOTH_A_BRD:
        A_im = smooth(A, xwinA, ywinA, bordertype='const', val=255)
    elif do_smooth in (SMOOTH_BOTH, SMOOTH_A):
        A_im = smooth(A, xwinA, ywinA)
    else:
        A_im = A
    wA, hA = cv.GetSize(A_im)
    results = {}  # {str imgpath: [(x1,y1,x2,y2,score),...]}
    for i, imgpath in enumerate(imgpaths):
        if isinstance(imgpath, str) or isinstance(imgpath, unicode):
            I = cv.LoadImage(imgpath, cv.CV_LOAD_IMAGE_GRAYSCALE)
        else:
            I = imgpath
            imgpath = i
        if do_smooth in (SMOOTH_BOTH_BRD, SMOOTH_IMG_BRD):
            I = smooth(I, xwinI, ywinI, bordertype='const', val=255)
        elif do_smooth in (SMOOTH_BOTH, SMOOTH_IMG):
            I = smooth(I, xwinI, ywinI)
        if img2flip and img2flip[imgpath]:
            cv.Flip(I, I, flipMode=-1)
        if bb != None:
            new_roi = tuple(
                map(int, (bb[0], bb[1], bb[2] - bb[0], bb[3] - bb[1])))
            cv.SetImageROI(I, new_roi)
        wI, hI = cv.GetSize(I)
        M = cv.CreateMat(hI - hA + 1, wI - wA + 1, cv.CV_32F)
        cv.MatchTemplate(I, A_im, M, cv.CV_TM_CCOEFF_NORMED)
        M_np = np.array(M)
        # 0.) Suppress previously-found matches, if any
        prevmats = prevmatches.get(imgpath, []) if prevmatches else []
        for (x1, y1, x2, y2) in prevmats:
            #print 'suppressing: {0} at {1}'.format(imgpath, (x1, y1))
            _x1 = max(0, int(x1 - max(1, (wA * DELT))))
            _y1 = max(0, int(y1 - max(1, (hA * DELT))))
            _x2 = min(M_np.shape[1], int(x1 + max(1, (wA * DELT))))
            _y2 = min(M_np.shape[0], int(y1 + max(1, (hA * DELT))))
            M_np[_y1:_y2, _x1:_x2] = -1.0
        score = np.inf
        #print 'best score:', np.max(M_np)
        num_mats = 0
        matches = []
        while score > T and num_mats < MAX_MATS:
            M_idx = np.argmax(M_np)
            i = int(M_idx / M.cols)
            j = M_idx % M.cols
            if bb != None:
                i += bb[1]
                j += bb[0]

            score = M_np[i, j]
            if score < T:
                break
            matches.append((j, i, j + wA, i + hA, score))
            # Suppression
            _x1 = max(0, int(j - max(1, (wA * DELT))))
            _y1 = max(0, int(i - max(1, (hA * DELT))))
            _x2 = min(M_np.shape[1], int(j + max(1, (wA * DELT))))
            _y2 = min(M_np.shape[0], int(i + max(1, (hA * DELT))))
            M_np[_y1:_y2, _x1:_x2] = -1.0
            #M_np[i-(hA/2):i+(hA/2),
            #     j-(wA/2):j+(wA/2)] = -1.0
            num_mats += 1
        if not matches and atleastone:
            print 'DOO DOO DOO'
            M_idx = np.argmax(M_np)
            i = int(M_idx / M.cols)
            j = M_idx % M.cols
            if bb != None:
                i += bb[1]
                j += bb[0]
            score = M_np[i, j]
            matches.append((j, i, j + wA, i + hA, score))
        results[imgpath] = matches
        if jobid and wx.App.IsMainLoopRunning():
            # Note: I don't think this actually does anything, since this
            # is living in a separate process, which can't communicate
            # to the wx App instance living in the original host process
            wx.CallAfter(Publisher().sendMessage, "signals.MyGauge.tick",
                         (jobid, ))
        if jobid and queue_mygauge != None and wx.App.IsMainLoopRunning():
            queue_mygauge.put(True)
    return results
Example #51
0
    def addInputs(self):
        """Add the textboxes for the optimization inputs"""
        #create a static boxsizer
        static_box = wx.StaticBox(self, label="Step 2: Optimize")
        box_sizer = wx.StaticBoxSizer(static_box, wx.VERTICAL)
        fgs = wx.FlexGridSizer(rows=4, cols=4, vgap=10, hgap=10)
        box_sizer.Add(fgs, proportion=1, flag=wx.EXPAND)

        fgs.Add(wx.StaticText(self, label="Score Weights"))
        self.prefWghts1 = wx.lib.intctrl.IntCtrl(self,
                                                 value=10,
                                                 min=0,
                                                 max=100,
                                                 size=(34, 22))
        self.prefWghts2 = wx.lib.intctrl.IntCtrl(self,
                                                 value=10,
                                                 min=0,
                                                 max=100,
                                                 size=(34, 22))
        self.prefWghts3 = wx.lib.intctrl.IntCtrl(self,
                                                 value=10,
                                                 min=0,
                                                 max=100,
                                                 size=(34, 22))

        fgs.AddMany([(self.prefWghts1), (self.prefWghts2), (self.prefWghts3)])

        fgs.Add(wx.StaticText(self, label="Preferences"))
        self.Prefs = wx.lib.intctrl.IntCtrl(self,
                                            value=10,
                                            min=0,
                                            max=100,
                                            size=(34, 22))
        fgs.AddMany([(self.Prefs), (wx.StaticText(self)),
                     (wx.StaticText(self))])

        fgs.Add(wx.StaticText(self, label="Excess Capacity"))
        self.ExcessCap = wx.lib.intctrl.IntCtrl(self,
                                                value=10,
                                                min=0,
                                                max=100,
                                                size=(34, 22))
        fgs.AddMany([(self.ExcessCap), (wx.StaticText(self)),
                     (wx.StaticText(self))])

        fgs.Add(wx.StaticText(self, label="Congestion"))
        self.CongPenalty = wx.lib.intctrl.IntCtrl(self,
                                                  value=10,
                                                  min=0,
                                                  max=100,
                                                  size=(34, 22))
        fgs.AddMany([(self.CongPenalty), (wx.StaticText(self)),
                     (wx.StaticText(self))])

        fgs.Add(wx.StaticText(self, label="Dept. Fairness"))
        self.DeptFairness = wx.lib.intctrl.IntCtrl(self,
                                                   value=10,
                                                   min=0,
                                                   max=100,
                                                   size=(34, 22))
        fgs.AddMany([(self.DeptFairness), (wx.StaticText(self)),
                     (wx.StaticText(self))])

        fgs.Add(wx.StaticText(self, label="Back to Back"))
        self.Back2Back = wx.lib.intctrl.IntCtrl(self,
                                                value=10,
                                                min=0,
                                                max=100,
                                                size=(34, 22))
        fgs.AddMany([(self.Back2Back), (wx.StaticText(self)),
                     (wx.StaticText(self))])

        self.optimize_btn = wx.Button(self, label="Optimize")
        self.optimize_btn.Bind(wx.EVT_BUTTON, self.onOptimize)
        fgs.Add(self.optimize_btn)

        self.SetSizerAndFit(box_sizer)
        self.Disable()

        pub.subscribe(self.enable, "data_loaded")
        pub.subscribe(self.updateWeights, "update_weights")
Example #52
0
 def onOptimize(self, event):
     pub.sendMessage("status_bar", "")
     self.model.optimize()
Example #53
0
    def OnRemove(self, event):  # wxGlade: ServerAdd.<event_handler>
        """
     @description: Called on Remove button press. Deleted the server info selected to be deleted. 
     @todo:None
     @param self: reference variable
     @param event: event associated
     @return: None
        """
        if self.selectedUid == None:
            message = _("No server selected. Remove unsuccessful")
            self.ShowMessage(message, _('Warning'))
            grass.warning(message)
            StatusBar_fields = [message]
            self.StatusBar.SetStatusText(StatusBar_fields[0], 0)
            return
        else:
            if (removeServerInfo(self.soup, self.selectedUid)):
                if (not self.saveXMLData()):
                    uid = self.selectedUid
                    servername = self.servers[uid].servername
                    url = self.servers[uid].url
                    username = self.servers[uid].username
                    password = self.servers[uid].password
                    if (addServerInfo(self.soup, self.soup.serverinfo, uid,
                                      servername, url, username, password)):
                        message = 'Unable to write data in file, Changes reverted, Remove unsuccessful'
                        grass.warning(message)
                        StatusBar_fields = [message]
                        self.StatusBar.SetStatusText(StatusBar_fields[0], 0)
                        return
                    else:
                        message = 'Unable to write data in file, Unable to revert changes, Remove unsuccessful'
                        grass.warning(message)
                        StatusBar_fields = [message]
                        self.StatusBar.SetStatusText(StatusBar_fields[0], 0)
                        return

                message = "Remove Successful"
                StatusBar_fields = [message]
                self.StatusBar.SetStatusText(StatusBar_fields[0], 0)
                grass.message(message)
                del self.map_servernameTouid[self.selectedServer.servername]
                if (len(self.servers) > 0):
                    self.ServerList.SetSelection(0)
                if (len(self.servers) == 0):
                    self.ServerList.Clear()

                del self.servers[self.selectedUid]
                self.selectedUid = None
                self.__update_URL_List()
                self.selectedServer = None
                self.ServerNameText.Clear()
                self.PasswordText.Clear()
                self.URLText.Clear()
                self.UsernameText.Clear()
                msg = self.servers
                Publisher().sendMessage(("update.serverList"), msg)
            else:
                message = "Remove Unsuccessful"
                self.ShowMessage(message, 'Warning')
                grass.warning(message)
                StatusBar_fields = [message]
                self.StatusBar.SetStatusText(StatusBar_fields[0], 0)
                return

        self.editOn = False
        event.Skip()
Example #54
0
    def __init__(self, *args, **kwargs):
        MyPanel.__init__(self, *args, **kwargs)
        self.addLoadPaths()

        pub.subscribe(self.assignmentsCalced, "assignments_calced")
Example #55
0
    def Init(self, res):
        """Method called after the panel has been initialized."""

        # Bind ui events to the proper methods
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)

        # Initialize variables
        self.images = []
        self.structures = {}
        self.window = 0
        self.level = 0
        self.zoom = 1
        self.pan = [0, 0]
        self.bwidth = 0
        self.bheight = 0
        self.xpos = 0
        self.ypos = 0
        self.mousepos = wx.Point(-10000, -10000)
        self.mouse_in_window = False
        self.isodose_line_style = 'Solid'
        self.isodose_fill_opacity = 25
        self.structure_line_style = 'Solid'
        self.structure_fill_opacity = 50
        self.plugins = {}

        # Setup toolbar controls
        if guiutil.IsGtk():
            drawingstyles = ['Solid', 'Transparent', 'Dot']
        else:
            drawingstyles = ['Solid', 'Transparent', 'Dot', 'Dash', 'Dot Dash']
        zoominbmp = wx.Bitmap(util.GetResourcePath('magnifier_zoom_in.png'))
        zoomoutbmp = wx.Bitmap(util.GetResourcePath('magnifier_zoom_out.png'))
        toolsbmp = wx.Bitmap(util.GetResourcePath('cog.png'))
        self.tools = []
        self.tools.append({
            'label': "Zoom In",
            'bmp': zoominbmp,
            'shortHelp': "Zoom In",
            'eventhandler': self.OnZoomIn
        })
        self.tools.append({
            'label': "Zoom Out",
            'bmp': zoomoutbmp,
            'shortHelp': "Zoom Out",
            'eventhandler': self.OnZoomOut
        })
        self.tools.append({
            'label': "Tools",
            'bmp': toolsbmp,
            'shortHelp': "Tools",
            'eventhandler': self.OnToolsMenu
        })

        # Set up preferences
        self.preferences = [{
            'Drawing Settings': [{
                'name':
                'Isodose Line Style',
                'type':
                'choice',
                'values':
                drawingstyles,
                'default':
                'Solid',
                'callback':
                '2dview.drawingprefs.isodose_line_style'
            }, {
                'name':
                'Isodose Fill Opacity',
                'type':
                'range',
                'values': [0, 100],
                'default':
                25,
                'units':
                '%',
                'callback':
                '2dview.drawingprefs.isodose_fill_opacity'
            }, {
                'name':
                'Structure Line Style',
                'type':
                'choice',
                'values':
                drawingstyles,
                'default':
                'Solid',
                'callback':
                '2dview.drawingprefs.structure_line_style'
            }, {
                'name':
                'Structure Fill Opacity',
                'type':
                'range',
                'values': [0, 100],
                'default':
                50,
                'units':
                '%',
                'callback':
                '2dview.drawingprefs.structure_fill_opacity'
            }]
        }]

        # Set up pubsub
        pub.subscribe(self.OnUpdatePatient, 'patient.updated.parsed_data')
        pub.subscribe(self.OnStructureCheck, 'structures.checked')
        pub.subscribe(self.OnIsodoseCheck, 'isodoses.checked')
        pub.subscribe(self.OnRefresh, '2dview.refresh')
        pub.subscribe(self.OnDrawingPrefsChange, '2dview.drawingprefs')
        pub.subscribe(self.OnPluginLoaded, 'plugin.loaded.2dview')
        pub.sendMessage('preferences.requested.values', '2dview.drawingprefs')
Example #56
0
    def OnSave(self, event):  # wxGlade: ServerAdd.<event_handler>
        """
     @description: Called on Save button press. Validates the information provided.
     Saves or updates the provided information.  
     @todo:None
     @param self: reference variable
     @param event: event associated
     @return: None
        """
        newServerName = unicode(self.ServerNameText.GetValue())
        newUrl = self.URLText.GetValue()
        newUserName = self.UsernameText.GetValue()
        newPassword = self.PasswordText.GetValue()

        newUrl = self.parse_WMS_URL(newUrl.strip())
        if not newUrl:
            message = _("Provided WMS URL is not valid.")
            self.ShowMessage(message, _('Error'))
            grass.warning(message)
            return

        if self.selectedUid == None:
            update = False
        else:
            update = True

        serverData = ServerData()

        if len(newServerName) != 0:
            if self.selectedServer is not None:
                if not self.selectedServer.servername == newServerName:
                    if self.valueExists(self.servers, newServerName):
                        message = _(
                            "Server name already exists. Please enter a different server name"
                        )
                        self.ShowMessage(message, _('Warning'))
                        grass.warning(message)
                        StatusBar_fields = [message]
                        self.StatusBar.SetStatusText(StatusBar_fields[0], 0)
                        return

            validUrl, message = self.validateUrl(newUrl)
            if not validUrl:
                message = _("Unable to validate URL (%s)") % message
                self.ShowMessage(message, _('Warning'))
                grass.warning(message)
            else:
                message = _("Url validated (%s)") % message

            StatusBar_fields = [message]
            self.StatusBar.SetStatusText(StatusBar_fields[0], 0)
            serverData.servername = newServerName
            serverData.url = newUrl
            serverData.username = newUserName
            serverData.password = newPassword

            if update:
                if updateServerInfo(self.soup, self.soup.serverinfo,
                                    self.selectedUid, newServerName, newUrl,
                                    newUserName, newPassword):
                    if not self.saveXMLData():
                        oldInfo = self.servers[self.selectedUid]
                        if updateServerInfo(self.soup, self.soup.serverinfo,
                                            self.selectedUid,
                                            oldInfo.servername, oldInfo.url,
                                            oldInfo.username,
                                            oldInfo.password):
                            message = _(
                                'Unable to save XML, changes reverted back')
                            grass.warning(message)
                            return
                        else:
                            message = _(
                                'Unable to save XML, changes will be reverted back on restart'
                            )
                            grass.warning(message)
                            return
                    message = 'update save successful'
                    grass.message(message)
                    self.servers[self.selectedUid] = serverData
                    del self.map_servernameTouid[
                        self.selectedServer.servername]
                    self.selectedServer = serverData
                    self.map_servernameTouid[newServerName] = self.selectedUid

                    msg = self.servers
                    Publisher().sendMessage(("update.serverList"), msg)

                    msg = self.map_servernameTouid
                    Publisher().sendMessage(("update.map_servernameTouid"),
                                            msg)
                    message = _("Server Info Updated")
                    grass.message(message)
                    StatusBar_fields = [message]
                    self.StatusBar.SetStatusText(StatusBar_fields[0], 0)
                    self.setModified(False)
                else:
                    message = _("Update not Successful")
                    self.ShowMessage(message, 'Warning')
                    grass.warning(message)
                    StatusBar_fields = [message]
                    self.StatusBar.SetStatusText(StatusBar_fields[0], 0)
            else:
                uid = str(uuid.uuid4())
                if addServerInfo(self.soup, self.soup.serverinfo, uid,
                                 newServerName, newUrl, newUserName,
                                 newPassword):
                    if not self.saveXMLData():
                        if removeServerInfo(self.soup, uid):
                            message = _('Unable to save XML. Info not saved')
                            grass.warning(message)
                            return
                        else:
                            message = _(
                                'Unable to save XML. Changes will be reverted back on restart'
                            )
                            grass.warning(message)
                            return
                    message = 'soup save successfully'
                    grass.message(message)
                    self.selectedUid = uid
                    self.servers[self.selectedUid] = serverData
                    self.selectedServer = serverData
                    self.map_servernameTouid[newServerName] = uid
                    msg = self.servers
                    Publisher().sendMessage(("update.serverList"), msg)
                    msg = self.map_servernameTouid
                    Publisher().sendMessage(("update.map_servernameTouid"),
                                            msg)
                    message = "Server Info Saved Successfully"
                    grass.message(message)
                    StatusBar_fields = [message]
                    self.StatusBar.SetStatusText(StatusBar_fields[0], 0)
                    self.setModified(False)
                else:
                    message = "Save not successful"
                    self.ShowMessage(message, 'Warning')
                    "Server Info Saved Successfully"
                    StatusBar_fields = [message]
                    self.StatusBar.SetStatusText(StatusBar_fields[0], 0)

            self.selectedURL = newUrl
            self.__update_URL_List()
        else:
            message = _("Please fill in server name")
            self.ShowMessage(message, _('Warning'))
            grass.warning(message)
            StatusBar_fields = [message]
            self.StatusBar.SetStatusText(StatusBar_fields[0], 0)

        self.editOn = False
        if (event):
            event.Skip()
Example #57
0
    def __init__(self, *args, **kwds):
        # begin wxGlade: wmsFrame.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.StatusBar = self.CreateStatusBar(1, 0)
        self.URL = wx.StaticText(self, -1, "URL")
        self.ServerList = wx.ComboBox(self,
                                      -1,
                                      choices=[],
                                      style=wx.CB_DROPDOWN | wx.CB_SIMPLE)
        self.LayerTree = wx.TreeCtrl(self,
                                     -1,
                                     style=wx.TR_HAS_BUTTONS | wx.TR_NO_LINES
                                     | wx.TR_MULTIPLE | wx.TR_MULTIPLE
                                     | wx.TR_DEFAULT_STYLE | wx.SUNKEN_BORDER)
        self.username = wx.StaticText(self, -1, "UserName")
        self.usernameInput = wx.TextCtrl(self, -1, "", style=wx.TE_PROCESS_TAB)
        self.EPSG = wx.StaticText(self, -1, "EPSG")
        self.password = wx.StaticText(self, -1, "Password")
        self.passwordInput = wx.TextCtrl(self,
                                         -1,
                                         "",
                                         style=wx.TE_PROCESS_TAB
                                         | wx.TE_PASSWORD)
        self.epsgList = wx.ComboBox(self,
                                    -1,
                                    choices=[],
                                    style=wx.CB_DROPDOWN | wx.CB_SIMPLE
                                    | wx.CB_DROPDOWN)
        self.GetCapabilities = wx.Button(self, -1, "GetCapabilities")
        self.GetMaps = wx.Button(self, -1, "GetMaps")
        self.addServer = wx.Button(self, -1, "Manage Servers")

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_TEXT_ENTER, self.OnServerListEnter, self.ServerList)
        self.Bind(wx.EVT_COMBOBOX, self.OnServerList, self.ServerList)
        self.Bind(wx.EVT_COMBOBOX, self.OnEPSGList, self.epsgList)
        self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnLayerTreeSelChanged,
                  self.LayerTree)
        self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnLayerTreeActivated,
                  self.LayerTree)
        self.Bind(wx.EVT_BUTTON, self.OnGetCapabilities, self.GetCapabilities)
        self.Bind(wx.EVT_BUTTON, self.OnGetMaps, self.GetMaps)
        self.Bind(wx.EVT_BUTTON, self.OnAddServer, self.addServer)
        # end wxGlade

        self.usernameInput.Disable()
        self.passwordInput.Disable()
        if (not loadConfigFile(self)):
            grass.fatal_error(
                'Config File Error, Unable to start application...')
            self.Close()
            return

        self.soup, open = initServerInfoBase('ServersList.xml')
        if (not open):
            self.Close()
            return
        self.__populate_Url_List(self.ServerList)
        self.selectedURL = "No server selected"
        self.layerTreeRoot = self.LayerTree.AddRoot("Layers")
        Publisher().subscribe(self.onAddServerFrameClose,
                              ("Add_Server_Frame_Closed"))
        Publisher().subscribe(self.onUpdateServerListmessage,
                              ("update.serverList"))
        Publisher().subscribe(self.onUpdateMapListmessage,
                              ("update.map_servernameTouid"))

        self.keyToEPSGCodes = {}
        self.Bind(wx.EVT_CLOSE, self.OnQuit)
        self.AddServerisClosed = True
        self.layerName = ""
        self.layerDataDict1 = {}
        self.selectedEPSG = None
Example #58
0
    def startProgress(self,
                      text,
                      max=100,
                      cancel=False,
                      message=None,
                      delay=0,
                      disable=False):
        """Create a progress meter in the status bar.
        
        Creates a gauge in the status bar with optional cancel button.  Unless
        a delay is used, it is up to the user to call wx.Yield to show the
        progress bar.
        
        If a delay is used, wx.Yield will be called after the initial delay and
        during calls to updateProgress after the same number of ticks pass as
        occurred during the initial delay.
        
        @param text: text to display to the left of the progress bar
        
        @param max: maximum number of ticks in the gauge
        
        @param cancel: (optional) True to display a cancel button
        
        @param message: (optional) wx.lib.pubsub message that will be listened
        for to update the progress bar
        
        @param delay: (optional) delay in seconds before displaying the gauge.
        This can be used if the length of the operation is unknown but want
        to avoid the progress bar if it turns out to be quick.
        """
        if self.debug_progress:
            dprint("Start progress: %s, msg=%s max=%d" % (text, message, max))
        self.in_progress = True
        self.gauge_max = max
        self.cancelled = False
        self.show_cancel = cancel
        self.disable_during_progress = disable

        self.gauge_text = text
        self.gauge_delay = delay
        self.gauge_show_time = time.time() + delay
        self.gauge_shown = False
        self.gauge_refresh_trigger = 0
        self.gauge_refresh_count = 0

        self.overlays = []
        self.overlays.append((self.parent.gauge, self.gauge_width))

        if self.show_cancel:
            dc = wx.ClientDC(self.parent)
            tw, th = dc.GetTextExtent(self.cancel_label)
            tw += 20  # add some padding to the text for button border
            self.overlays.append((self.parent.cancel, tw))

        if message:
            Publisher().subscribe(self.updateMessage, message)
            self.message = message

        self.updateProgress(0)
        if self.gauge_delay == 0:
            if self.parent.info == self:
                self._showProgress()
            self.gauge_shown = True
Example #59
0
 def OnRedrawTimer(self, event):
     # if paused do not add data, but still redraw the plot
     # (to respond to scale modifications, grid change, etc.)
     #
     pub.sendMessage("WANT MONEY", 0.0)
Example #60
0
    def OnPaint(self, evt):
        """Update the panel when it needs to be refreshed."""

        # Bind motion event when the panel has been painted to avoid a blank
        # image on Windows if a file is loaded too quickly before the plugin
        # is initialized
        self.Bind(wx.EVT_MOTION, self.OnMouseMotion)

        # Special case for Windows to account for flickering
        # if and only if images are loaded
        if (guiutil.IsMSWindows() and len(self.images)):
            dc = wx.BufferedPaintDC(self)
            self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
        else:
            dc = wx.PaintDC(self)

        width, height = self.GetClientSize()
        try:
            gc = wx.GraphicsContext.Create(dc)
        except NotImplementedError:
            dc.DrawText(
                "This build of wxPython does not support the "
                "wx.GraphicsContext family of classes.", 25, 25)
            return

        # If we have images loaded, process and show the image
        if len(self.images):
            # Save the original drawing state
            gc.PushState()
            # Scale the image by the zoom factor
            gc.Scale(self.zoom, self.zoom)

            # Redraw the background on Windows
            if guiutil.IsMSWindows():
                gc.SetBrush(wx.Brush(wx.Colour(0, 0, 0)))
                gc.SetPen(wx.Pen(wx.Colour(0, 0, 0)))
                gc.DrawRectangle(0, 0, width, height)

            image = guiutil.convert_pil_to_wx(
                self.images[self.imagenum - 1].GetImage(
                    self.window, self.level))
            bmp = wx.BitmapFromImage(image)
            self.bwidth, self.bheight = image.GetSize()

            # Center the image
            transx = self.pan[0] + (width -
                                    self.bwidth * self.zoom) / (2 * self.zoom)
            transy = self.pan[1] + (height -
                                    self.bheight * self.zoom) / (2 * self.zoom)
            gc.Translate(transx, transy)
            gc.DrawBitmap(bmp, 0, 0, self.bwidth, self.bheight)
            gc.SetBrush(wx.Brush(wx.Colour(0, 0, 255, 30)))
            gc.SetPen(wx.Pen(wx.Colour(0, 0, 255, 30)))

            # Draw the structures if present
            imdata = self.images[self.imagenum - 1].GetImageData()
            self.z = '%.2f' % imdata['position'][2]

            # Determine whether the patient is prone or supine
            if 'p' in imdata['patientposition'].lower():
                prone = True
            else:
                prone = False
            # Determine whether the patient is feet first or head first
            if 'ff' in imdata['patientposition'].lower():
                feetfirst = True
            else:
                feetfirst = False
            for id, structure in self.structures.iteritems():
                self.DrawStructure(structure, gc, self.z, prone, feetfirst)

            # Draw the isodoses if present
            if len(self.isodoses):
                grid = self.dose.GetDoseGrid(float(self.z))
                if not (grid == []):
                    x, y = np.meshgrid(np.arange(grid.shape[1]),
                                       np.arange(grid.shape[0]))
                    # Instantiate the isodose generator for this slice
                    isodosegen = cntr.Cntr(x, y, grid)
                    for id, isodose in iter(sorted(self.isodoses.iteritems())):
                        self.DrawIsodose(isodose, gc, isodosegen)

            # Restore the translation and scaling
            gc.PopState()

            # Prepare the font for drawing the information text
            font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
            if guiutil.IsMac():
                font.SetPointSize(10)
            gc.SetFont(font, wx.WHITE)

            # Draw the information text
            imtext = "Image: " + str(self.imagenum) + "/" + str(
                len(self.images))
            te = gc.GetFullTextExtent(imtext)
            gc.DrawText(imtext, 10, 7)
            impos = "Position: " + str(self.z) + " mm"
            gc.DrawText(impos, 10, 7 + te[1] * 1.1)
            if ("%.3f" % self.zoom == "1.000"):
                zoom = "1"
            else:
                zoom = "%.3f" % self.zoom
            imzoom = "Zoom: " + zoom + ":1"
            gc.DrawText(imzoom, 10, height - 17)
            imsize = "Image Size: " + str(self.bheight) + "x" + str(
                self.bwidth) + " px"
            gc.DrawText(imsize, 10, height - 17 - te[1] * 1.1)
            imwinlevel = "W/L: " + str(self.window) + ' / ' + str(self.level)
            te = gc.GetFullTextExtent(imwinlevel)
            gc.DrawText(imwinlevel, width - te[0] - 7, 7)
            impatpos = "Patient Position: " + imdata['patientposition']
            te = gc.GetFullTextExtent(impatpos)
            gc.DrawText(impatpos, width - te[0] - 7, height - 17)

            # Send message with the current image number and various properties
            pub.sendMessage(
                '2dview.updated.image',
                {
                    'number': self.imagenum,  # slice number
                    'z': self.z,  # slice location
                    'window': self.window,  # current window value
                    'level': self.level,  # curent level value
                    'gc': gc,  # wx.GraphicsContext
                    'scale': self.zoom,  # current zoom level
                    'transx': transx,  # current x translation
                    'transy': transy,  # current y translation
                    'imdata': imdata,  # image data dictionary
                    'patientpixlut': self.structurepixlut
                })