def activate(self, callingWindow, fullContext, mainItem, i): fitID = self.mainFrame.getActiveFit() Fit.getInstance().setAsPattern(fitID, mainItem) wx.PostEvent(self.mainFrame, GE.FitChanged(fitIDs=(fitID, )))
def Undo(self): success = self.internalHistory.undoAll() Fit.getInstance().recalc(self.fitID) wx.PostEvent(gui.mainFrame.MainFrame.getInstance(), GE.FitChanged(fitID=self.fitID)) return success
def OnFind(self, event): """ Search after or before the current position. """ # Firstly, check if a text to find is given! success = self.text.GetValidator().Validate(self.text) if success is False: return ruler = self.GetParent()._display.GetRuler() self._pmin = ruler.GetSelectionIndicatorMinValue() self._pmax = ruler.GetSelectionIndicatorMaxValue() # Get search criteria criteria = self.lp.GetCriteria() patterns = self.text.GetValue().split(',') # Get search direction forward = True direction = 1 if event.GetId() == wx.ID_BACKWARD: forward = False direction = -1 # Convert criteria into "functions" function = criteria['function'] if criteria['case_sensitive'] is False and function != "regexp": function = "i"+function # Search... On which tier? tieridx = self.tp.GetSelection() tier = self._trs[tieridx] if forward is True: annidx = tier.Near(self._pmax, direction) else: annidx = tier.Near(self._pmin, direction) # Now, can search the next/previous occurrence #logging.debug(' Search %s in %s with function %s in forward direction=%d'%(patterns,tier.GetName(),function,forward)) annidx = tier.Search(patterns,function,annidx,forward,criteria['reverse']) # Show the search result if annidx == -1: self.text.SetForegroundColour(wx.RED) #self.text.SetFocus() self.text.Refresh() #logging.debug(' ... no occurrence. ') else: self.text.SetForegroundColour(wx.BLACK) ann = tier[annidx] #logging.debug(' ... success: %s '%ann) if ann.GetLocation().IsPoint(): radius = ann.GetLocation().GetPointRadius() s = ann.GetLocation().GetPointMidpoint() - radius e = ann.GetLocation().GetPointMidpoint() + radius else: s = ann.GetLocation().GetBeginMidpoint() e = ann.GetLocation().GetEndMidpoint() evt = SearchedEvent(start=s, end=e) evt.SetEventObject(self) wx.PostEvent(self.GetParent(), evt)
def SearchNotice(self, title, text): evt = Wammu.Events.ShowMessageEvent( message = text, title = title, type = wx.ICON_WARNING) wx.PostEvent(self, evt)
def OnLinkClicked(self, linkinfo): wx.PostEvent(self, HtmlWindowUrlClick(linkinfo))
def onCircular(self, event, ismask=False): """ perform circular averaging on Data2D :param event: wx.menu event """ # Find the best number of bins npt = math.sqrt(len(self.data2D.data[numpy.isfinite( self.data2D.data)])) npt = math.floor(npt) from sas.dataloader.manipulations import CircularAverage ## compute the maximum radius of data2D self.qmax = max(math.fabs(self.data2D.xmax), math.fabs(self.data2D.xmin)) self.ymax = max(math.fabs(self.data2D.ymax), math.fabs(self.data2D.ymin)) self.radius = math.sqrt( math.pow(self.qmax, 2) + math.pow(self.ymax, 2)) ##Compute beam width bin_width = (self.qmax + self.qmax) / npt ## Create data1D circular average of data2D Circle = CircularAverage(r_min=0, r_max=self.radius, bin_width=bin_width) circ = Circle(self.data2D, ismask=ismask) from sas.guiframe.dataFitting import Data1D if hasattr(circ, "dxl"): dxl = circ.dxl else: dxl = None if hasattr(circ, "dxw"): dxw = circ.dxw else: dxw = None new_plot = Data1D(x=circ.x, y=circ.y, dy=circ.dy, dx=circ.dx) new_plot.dxl = dxl new_plot.dxw = dxw new_plot.name = "Circ avg " + self.data2D.name new_plot.source = self.data2D.source #new_plot.info = self.data2D.info new_plot.interactive = True new_plot.detector = self.data2D.detector ## If the data file does not tell us what the axes are, just assume... new_plot.xaxis("\\rm{Q}", "A^{-1}") if hasattr(self.data2D, "scale") and \ self.data2D.scale == 'linear': new_plot.ytransform = 'y' new_plot.yaxis("\\rm{Residuals} ", "normalized") else: new_plot.yaxis("\\rm{Intensity} ", "cm^{-1}") new_plot.group_id = "2daverage" + self.data2D.name new_plot.id = "Circ avg " + self.data2D.name new_plot.is_data = True self.parent.update_theory(data_id=self.data2D.id, \ theory=new_plot) wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot, title=new_plot.name))
def handleMode(self, event): option = self.optionIds[event.Id] self.settings.set(option.lower(), event.Int) wx.PostEvent(self.mainFrame, GE.FitChanged(fitID=self.mainFrame.getActiveFit()))
def msg_box(self, msg, title="Info"): import wx wx.PostEvent(self.mWindow, ResultEvent(lambda: wx.MessageBox(msg, title)))
def Notify(self): wx.PostEvent(self, SwitchEvent(self.GetId(), index=self.GetSelection()))
def _sort_callback(self, *evnt): event = gui.SortEvent(anon=self.anonQ.IsChecked(), fields=self.GetFormatFields()) wx.PostEvent(self, event)
def add_status_msg(msg, status_ctrl, simulate): if status_ctrl and not simulate: evt = custom_events.wxStatusEvent(message=msg) wx.PostEvent(status_ctrl, evt) else: print msg.encode('ascii', errors='ignore')
def Notify(self, *evnt): event = gui.PathEvent(path=self.path) wx.PostEvent(self, event)
def OnClose(self, event): fitID = self.mainFrame.getActiveFit() if fitID is not None: wx.PostEvent(self.mainFrame, GE.FitChanged(fitIDs=(fitID, ))) event.Skip()
def run(self): while True: time.sleep(0.02) if self.loginFlag: self.loggedIn = self.elementBase.Login(self.loginFlag[0],self.loginFlag[1]) print self.loggedIn evt = ElementBaseLoginEvent(success = self.elementBase.loggedIn) wx.PostEvent(self.wx, evt) self.loginFlag = False if self.elementBase.loggedIn: if self.loadBaseFlag: loadStatus = self.elementBase.loadBase() evt = BaseLoadedEvent(success = loadStatus) wx.PostEvent(self.wx, evt) self.loadBaseFlag = False if self.loadCollectionList: loadStatus = self.elementBase.getCollections() evt = CollectionListLoadedEvent(success = loadStatus) wx.PostEvent(self.wx, evt) self.loadCollectionList = False if len(self.LoadElementList): collection_id = self.LoadElementList.pop(0) self.elementBase.getElements(collection_id) evt = ElementListLoadedEvent(success = loadStatus, collection_id = collection_id) wx.PostEvent(self.wx, evt) if len(self.LoadCategoryList): collection_id = self.LoadCategoryList.pop(0) self.elementBase.getCategories(collection_id) evt = CategoryListLoadedEvent(success = loadStatus, collection_id = collection_id) wx.PostEvent(self.wx, evt) if len(self.LoadPropertyList): collection_id = self.LoadPropertyList.pop(0) self.elementBase.getProperties(collection_id) evt = PropertyListLoadedEvent(success = loadStatus, collection_id = collection_id) wx.PostEvent(self.wx, evt) if len(self.LoadProductList): collection_id = self.LoadProductList.pop(0) self.elementBase.getProducts(collection_id) evt = ProductListLoadedEvent(success = loadStatus, collection_id = collection_id) wx.PostEvent(self.wx, evt) if len(self.LoadOrderList): collection_id = self.LoadOrderList.pop(0) self.elementBase.getOrders(collection_id) evt = OrderListLoadedEvent(success = loadStatus, collection_id = collection_id) wx.PostEvent(self.wx, evt) if len(self.ReadElementList): [collection_id, element_num] = self.ReadElementList.pop(0) value = self.elementBase.ReadQuantity(collection_id, element_num) if isinstance( value, int ): evt = ElementUpdateEvent(collection_id = collection_id, element_num = element_num, value = value) wx.PostEvent(self.wx, evt) if len(self.WriteElementList): [collection_id, element_num, diff] = self.WriteElementList.pop(0) value = self.elementBase.ReadQuantity(collection_id, element_num) self.elementBase.UpdateQuantity(collection_id, element_num, str(int(value)+diff)) value = self.elementBase.ReadQuantity(collection_id, element_num) if isinstance( value, int ): evt = ElementUpdateEvent(collection_id = collection_id, element_num = element_num, value = value) wx.PostEvent(self.wx, evt) if len(self.DeleteElementList): element_num = self.DeleteElementList.pop(0) self.elementBase.DeleteElement(element_num) if len(self.AddElementList): [category_id,name,quantity,description,properties] = self.AddElementList.pop(0) self.elementBase.AddElement(category_id,name,quantity,description,properties) if len(self.AddProductList): [name,description,elements] = self.AddProductList.pop(0) self.elementBase.AddProduct(name,description,elements) if len(self.DeleteProductList): product_id = self.DeleteProductList.pop(0) self.elementBase.DeleteProduct(product_id) if len(self.EditElementList): [element_id, name, quantity, comment, category_id, properties] = self.EditElementList.pop(0) self.elementBase.EditElement(element_id, name, quantity, comment, category_id, properties) if self.elementBase.loggedIn == False: evt = ElementBaseLoginEvent(success = self.elementBase.loggedIn) wx.PostEvent(self.wx, evt)
def action_callback(O): wx.PostEvent( O, wx_viewer.ViewerUpdateEvent(data=O.tardy_model.sites_moved()))
def LoadWorkspaceList(self): success = self.buildSys.Prepare() evt = WorkspaceListLoadedEvent(listLoaded=success) wx.PostEvent(self.workspacesTab, evt)
def onContextMenu(self, event): """ 2D plot context menu :param event: wx context event """ ids = iter(self._menu_ids) slicerpop = PanelMenu() slicerpop.set_plots(self.plots) slicerpop.set_graph(self.graph) wx_id = ids.next() slicerpop.Append(wx_id, '&Save Image') wx.EVT_MENU(self, wx_id, self.onSaveImage) wx_id = ids.next() slicerpop.Append(wx_id, '&Print Image', 'Print image') wx.EVT_MENU(self, wx_id, self.onPrint) wx_id = ids.next() slicerpop.Append(wx_id, '&Copy to Clipboard', 'Copy to the clipboard') wx.EVT_MENU(self, wx_id, self.OnCopyFigureMenu) slicerpop.AppendSeparator() # saving data plot = self.data2D wx_id = ids.next() slicerpop.Append(wx_id, "&Data Info") wx.EVT_MENU(self, wx_id, self._onDataShow) wx_id = ids.next() slicerpop.Append(wx_id, "&Save as a File (DAT)") self.action_ids[str(wx_id)] = plot wx.EVT_MENU(self, wx_id, self._onSave) slicerpop.AppendSeparator() if len(self.data2D.detector) == 1: item_list = self.parent.get_current_context_menu(self) if (not item_list == None) and (not len(item_list) == 0) and\ self.data2D.name.split(" ")[0] != 'Residuals': # The line above; Not for trunk # Note: reusing menu ids for the sub-menus. See Plotter1D. for item, wx_id in zip(item_list, self._menu_ids): try: slicerpop.Append(wx_id, item[0], item[1]) wx.EVT_MENU(self, wx_id, item[2]) except: msg = "ModelPanel1D.onContextMenu: " msg += "bad menu item %s" % sys.exc_value wx.PostEvent(self.parent, StatusEvent(status=msg)) slicerpop.AppendSeparator() wx_id = ids.next() slicerpop.Append(wx_id, '&Perform Circular Average') wx.EVT_MENU(self, wx_id, self.onCircular) \ # For Masked Data if not plot.mask.all(): wx_id = ids.next() slicerpop.Append(wx_id, '&Masked Circular Average') wx.EVT_MENU(self, wx_id, self.onMaskedCircular) wx_id = ids.next() slicerpop.Append(wx_id, '&Sector [Q View]') wx.EVT_MENU(self, wx_id, self.onSectorQ) wx_id = ids.next() slicerpop.Append(wx_id, '&Annulus [Phi View ]') wx.EVT_MENU(self, wx_id, self.onSectorPhi) wx_id = ids.next() slicerpop.Append(wx_id, '&Box Sum') wx.EVT_MENU(self, wx_id, self.onBoxSum) wx_id = ids.next() slicerpop.Append(wx_id, '&Box Averaging in Qx') wx.EVT_MENU(self, wx_id, self.onBoxavgX) wx_id = ids.next() slicerpop.Append(wx_id, '&Box Averaging in Qy') wx.EVT_MENU(self, wx_id, self.onBoxavgY) if self.slicer != None: wx_id = ids.next() slicerpop.Append(wx_id, '&Clear Slicer') wx.EVT_MENU(self, wx_id, self.onClearSlicer) if self.slicer.__class__.__name__ != "BoxSum": wx_id = ids.next() slicerpop.Append(wx_id, '&Edit Slicer Parameters') wx.EVT_MENU(self, wx_id, self._onEditSlicer) slicerpop.AppendSeparator() wx_id = ids.next() slicerpop.Append(wx_id, '&Edit Graph Label', 'Edit Graph Label') wx.EVT_MENU(self, wx_id, self.onEditLabels) slicerpop.AppendSeparator() # ILL mod here wx_id = ids.next() slicerpop.Append(wx_id, '&Modify graph appearance', 'Modify graph appearance') wx.EVT_MENU(self, wx_id, self.modifyGraphAppearance) slicerpop.AppendSeparator() wx_id = ids.next() slicerpop.Append(wx_id, '&2D Color Map') wx.EVT_MENU(self, wx_id, self._onEditDetector) slicerpop.AppendSeparator() wx_id = ids.next() slicerpop.Append(wx_id, '&Toggle Linear/Log Scale') wx.EVT_MENU(self, wx_id, self._onToggleScale) slicerpop.AppendSeparator() wx_id = ids.next() slicerpop.Append(wx_id, '&Window Title') wx.EVT_MENU(self, wx_id, self.onChangeCaption) try: pos_evt = event.GetPosition() pos = self.ScreenToClient(pos_evt) except: pos_x, pos_y = self.toolbar.GetPositionTuple() pos = (pos_x, pos_y + 5) self.PopupMenu(slicerpop, pos)
def run(self): """Run Worker Thread.""" ser = serial.Serial('/dev/tty.HC-06-DevB', 9600, timeout=1) ser.close() serIsOpen = False while not serIsOpen: try: ser.open() serIsOpen = True except: serIsOpen = False MAX_SIT_TIME = int(self._notify_window.maxSitTime.GetValue()) WAIT_TIME = int(self._notify_window.waitTime.GetValue()) MIN_ACTIVE_TIME = int(self._notify_window.minActiveTime.GetValue()) MIN_NOTIFICATION_TIME = int( self._notify_window.minNotificationTime.GetValue()) MAX_DISTANCE = int(self._notify_window.maxDistance.GetValue()) numberNotifications = 0 notifcationTime = 0 sittingTime = 0 activeTime = 0 totalSitTime = 0 totalActiveTime = 0 countNoteTime = False sitting = checkSitting(ser, MAX_DISTANCE) while (True): if self._want_abort: totalActiveTime += activeTime totalSitTime += sittingTime print "Sitting Time: ", totalSitTime print "Active Time", totalActiveTime sedFile = open("sedentary.txt", "a") todayDate = time.strftime("%m/%d/%Y") outputStr = todayDate + "\t" + str(totalSitTime) + "\t" + str( totalActiveTime) + "\n" sedFile.write(outputStr) sedFile.close() wx.PostEvent(self._notify_window, ResultEvent(None)) ser.close() return start_time = time.time() if (checkSitting(ser, MAX_DISTANCE)): sittingTime += WAIT_TIME else: activeTime += WAIT_TIME if countNoteTime: notifcationTime += WAIT_TIME if notifcationTime >= MIN_NOTIFICATION_TIME: sendNotification(sittingTime) notifcationTime = 0 if ((sittingTime) / (MAX_SIT_TIME * 1.0)) >= (numberNotifications + 1): sendNotification(sittingTime) numberNotifications += 1 countNoteTime = True print "SittingTime: ", sittingTime print "MAX_SIT_TIME", MAX_SIT_TIME print "NumberNotifications", numberNotifications time.sleep(WAIT_TIME) if activeTime >= MIN_ACTIVE_TIME: totalActiveTime += activeTime totalSitTime += sittingTime sittingTime = 0 activeTime = 0 numberNotifications = 0 notifcationTime = 0 countNoteTime = False ser.close() if ser.IsOpen(): ser.close() wx.PostEvent(self._notify_window, ResultEvent(10))
except IOError, msg: return False finally: if not self._proc.stdout.closed: fcntl.fcntl(self._proc.stdout, fcntl.F_SETFL, flags) # Ignore encoding errors and return an empty line instead try: result = read.decode(sys.getfilesystemencoding()) except UnicodeDecodeError: result = os.linesep if self.Parent: evt = OutputBufferEvent(edEVT_UPDATE_TEXT, self.Parent.GetId(), result) wx.PostEvent(self.Parent, evt) return True else: return False # Parent is dead no need to keep running def __KillPid(self, pid): """Kill a process by process id, causing the run loop to exit @param pid: Id of process to kill """ # Dont kill if the process if it is the same one we # are running under (i.e we are running a shell command) if pid == os.getpid(): return if wx.Platform != '__WXMSW__':
def copyFit(self, event=None): sFit = Fit.getInstance() fitID = sFit.copyFit(self.fitID) self.shipBrowser.fitIDMustEditName = fitID wx.PostEvent(self.shipBrowser, Stage3Selected(shipID=self.shipID)) wx.PostEvent(self.mainFrame, FitSelected(fitID=fitID))
def onOkButton(self, event): event = ConsoleEvent(kind="error", msg="Hello") #print("Firing %s" % event) wx.PostEvent(self.console, event)
def selectFit(self, event=None, newTab=False): if newTab: wx.PostEvent(self.mainFrame, FitSelected(fitID=self.fitID, startup=2)) else: wx.PostEvent(self.mainFrame, FitSelected(fitID=self.fitID))
def SearchMessage(self, text): """ This has to send message as it is called from different thread. """ evt = Wammu.Events.TextEvent(text = text + '\n') wx.PostEvent(self, evt)
def change_status(self, status): evt = StatusChange(tp_EVT_STATUS_CHANGE, -1, status) wx.PostEvent(self, evt)
def post_event(self): wx.PostEvent(self.frame, self.result_event(result=self.result, elapsed_time=self.elapsed_time))
def removeBooster(self, booster): fitID = self.mainFrame.getActiveFit() sFit = service.Fit.getInstance() sFit.removeBooster(fitID, self.origional.index(booster)) wx.PostEvent(self.mainFrame, GE.FitChanged(fitID=fitID))
def Layout(self): wx.GridBagSizer.Layout(self) if self.win: wx.PostEvent(self.win, GBSizerExLayoutEvent(val=True))
def postNetworkEvent(self, message): """ called by the Communicator when something happens. For thread safety, this can't have any gui code, so it just posts an event so an event handler function (onNetworkEvent) can respond. """ event = NetworkEvent(message=message) wx.PostEvent(self, event)
def Start(self): """ Starts the playback. Called as a thread from dialog boxes """ self.paused = False wx.PostEvent(self.parentWin, JetStatusEvent(JetDefs.PST_PLAY, None)) # create a temporary config file, and jet output file FileKillClean(JetDefs.TEMP_JET_CONFIG_FILE) self.jet_file = JetFile(JetDefs.TEMP_JET_CONFIG_FILE, "") self.jet_file.AddSegment( self.segment.segname, self.segment.filename, self.segment.start, self.segment.end, self.segment.length, SegmentOutputFile(self.segment.segname, JetDefs.TEMP_JET_CONFIG_FILE), self.segment.quantize, self.segment.jetevents, self.segment.dlsfile, None, self.segment.transpose, self.segment.repeat, self.segment.mute_flags) userID = 0 dls_num = -1 seg_num = 0 if len(self.segment.dlsfile) > 0: self.jet_file.libraries.append(self.segment.dlsfile) dls_num = 0 self.jet_file.SaveJetConfig(JetDefs.TEMP_JET_CONFIG_FILE) self.jet_file.WriteJetFileFromConfig(JetDefs.TEMP_JET_CONFIG_FILE) if not ValidateConfig(self.jet_file): return self.queueSegs = [] self.queueSegs.append( QueueSeg(self.segment.segname, userID, seg_num, dls_num, self.segment.repeat, self.segment.transpose, self.segment.mute_flags)) self.jet = JET() self.jet.eas.StartWave() self.jet.OpenFile(self.jet_file.config.filename) # queue first segment and start playback index = 0 Queue(self.jet, self.queueSegs[index]) index += 1 self.jet.Play() self.SetKeepPlayingFlag(True) while self.GetKeepPlayingFlag(): self.jet.Render() status = self.jet.Status() # if no more segments - we're done if status.numQueuedSegments == 0: break self.jet.GetAppEvent() # if less than 2 segs queued - queue another one if (index < len(self.queueSegs)) and (status.numQueuedSegments < 2): Queue(self.jet, self.queueSegs[index]) index += 1 wx.PostEvent( self.parentWin, JetStatusEvent(JetDefs.PST_UPD_LOCATION, status.location)) SafeJetShutdown(self.playerLock, self.jet) FileKillClean( SegmentOutputFile(self.segment.segname, JetDefs.TEMP_JET_CONFIG_FILE)) FileKillClean(JetDefs.TEMP_JET_CONFIG_FILE) FileKillClean(self.jet_file.config.filename) self.SetKeepPlayingFlag(False) wx.PostEvent(self.parentWin, JetStatusEvent(JetDefs.PST_DONE, None)) wx.PostEvent(self.parentWin, JetStatusEvent(JetDefs.PST_UPD_LOCATION, 0))
def call_event(control, event_type): """Force an event to be called on the GUI.""" evt = wx.CommandEvent(event_type.typeId, control.GetId()) evt.SetEventObject(control) wx.PostEvent(control, evt)