def on_btn_metadata(self, event): """ Initiate the series of windows to add metadata to the contribution. """ # make sure we have a measurements file if not self.check_for_meas_file(): return # make sure all files of the same type have been combined if not self.check_for_uncombined_files(): return if self.data_model_num == 2: wait = wx.BusyInfo('Compiling required data, please wait...') wx.SafeYield() self.ErMagic_frame = ErMagicBuilder.MagIC_model_builder( self.WD, self, self.er_magic) elif self.data_model_num == 3: wait = wx.BusyInfo('Compiling required data, please wait...') wx.SafeYield() self.ErMagic_frame = ErMagicBuilder.MagIC_model_builder3( self.WD, self, self.contribution) # self.ErMagic_frame.Show() self.ErMagic_frame.Center() # gets total available screen space - 10% size = wx.DisplaySize() size = (size[0] - 0.3 * size[0], size[1] - 0.3 * size[1]) self.ErMagic_frame.Raise() del wait
def CopyProject(self): """ Copies an existing project to a new one, basically transferring the project settings into a new project. """ # Get the selected item text itemText = self.GetItemText(self.selectedItem) try: # Load the project project = self.MainFrame.dataBase.LoadProject(itemText) except: # Something went wrong, the project hasn't been saved yet self.MainFrame.RunError( 2, _("This project has not been saved yet. Please save it and retry." )) return # Generate a unique project name, not conflicting with the existing ones uniqueName = self.GetUniqueProjectName() # Ask the user to enter a project name dlg = wx.TextEntryDialog(self.MainFrame, _("Enter a name for the new project:"), _("New project")) dlg.SetValue(uniqueName) if dlg.ShowModal() != wx.ID_OK: # Do you want to think about it, eh? return projectName = dlg.GetValue() dlg.Destroy() if not self.CheckProjectName(projectName): # The selected project name already exists! return busy = PyBusyInfo(_("Copying existing project configuration..."), self.MainFrame) wx.SafeYield(self) # Go with the new project treeItem = self.AppendItem(self.rootItem, projectName.encode(), image=1) self.SetPyData(treeItem, projectName) # Copy the existing project to the new one self.MainFrame.dataBase.CopyProject(project, projectName) del busy wx.SafeYield(self) transdict = dict(existingProject=project.GetName(), newProject=projectName) self.MainFrame.RunError( 0, _("Project %(existingProject)s succesfully copied to %(newProject)s" ) % transdict)
def flickerWindow(self, times, negColor): ''' Function for giving a flickering-effect as a negative-feedback ''' if self.debug: print "E_UI.flickerWindow" negColor = negColor.split("/") if len(negColor) > 1: # this is Hexadecimal-code RGBcode = negColor[1].split(",") for i in xrange(3): RGBcode[i] = commonFunc.HexToDec( RGBcode[i] ) # Converting the hexadecimal-code to the decimal number negColor = (wx.Colour(RGBcode[0], RGBcode[1], RGBcode[2])) else: negColor = negColor[0].strip() for i in range(times): self.mainPanel.SetBackgroundColour(negColor) wx.SafeYield() time.sleep(0.03) self.mainPanel.SetBackgroundColour('white') wx.SafeYield() time.sleep(0.03) self.mainPanel.SetBackgroundColour(self.mainPanelColour)
def SetItem(self, index, col, data, is_init=False): # hopefully whatever the user input is valid... (data will pass # through the validation steps on the Element side) if not is_init: var = self.__keys[index] self.__vars[var] = data # go ahead and update the text fields on display and redraw the canvas self.__UpdateItem(index) if not is_init: old_cursor = self.__parent.GetCursor() new_cursor = wx.Cursor(wx.CURSOR_WAIT) wx.SetCursor(new_cursor) wx.SafeYield() try: # self.__parent.GetContext().ReValueAll() self.__parent.GetContext().ReSortAll() self.__parent.GetContext().GoToHC() self.__parent.GetContext().RefreshFrame() except Exception as ex: raise ex finally: wx.SetCursor(old_cursor) wx.SafeYield()
def _on_save_all_button_pressed(self, event): self.save_encounter() time.sleep(0.3) event.Skip() wx.SafeYield() wx.CallAfter(self._save_all_button_pressed_bottom_half) wx.SafeYield()
def callback(self, event): self.frame.SetStatusText("Menu item clicked") wx.SafeYield() time.sleep(2) self.frame.SetStatusText("Working") wx.SafeYield() time.sleep(2) self.frame.SetStatusText("Completed")
def callback(self, event): self.frame.SetStatusText("Menu item clicked (synchronous)") wx.SafeYield() time.sleep(1) self.frame.SetStatusText("Working (synchronous)") wx.SafeYield() time.sleep(1) self.frame.SetStatusText("Completed (synchronous)") wx.SafeYield() time.sleep(1) self.frame.SetStatusText("")
def ShowPlayer(self): # TODO(emilon): Hack to work around video player tab not been properly # drawn when clicking on the stream button of a search result which # hasn't had it's torrent fetched. wx.SafeYield() self.showLibrary() wx.SafeYield() #EO Hack if self.frame.videoparentpanel: self.ShowPage('videoplayer')
def callback(self, event): self.edit.SetLabel("Button clicked (synchronous)") wx.SafeYield() time.sleep(1) self.edit.SetLabel("Working (synchronous)") wx.SafeYield() time.sleep(1) self.edit.SetLabel("Completed (synchronous)") wx.SafeYield() time.sleep(1) self.edit.SetLabel("")
def UpdatePulse(self, newmsg=""): """ Updates the dialog, setting the progress bar to the new value and, if given changes the message above it. Returns ``True`` unless the ``Cancel`` button has been pressed. If ``False`` is returned, the application can either immediately destroy the dialog or ask the user for the confirmation. :param `newmsg`: The new messages for the progress dialog text, if it is empty (which is the default) the message is not changed. """ self._gauge.Update() if newmsg and newmsg != self._msg.GetLabel(): self._msg.SetLabel(newmsg) wx.SafeYield() if self._elapsed: elapsed = int(time.time()) - self._timeStart if self._last_timeupdate < elapsed: self._last_timeupdate = elapsed self.SetTimeLabel(elapsed, self._elapsed) if self._state == Finished: if not self._agwStyle & wx.PD_AUTO_HIDE: self.EnableClose() if newmsg == "": # also provide the finishing message if the application didn't self._msg.SetLabel("Done.") wx.SafeYield() self.ShowModal() return False else: # reenable other windows before hiding this one because otherwise # Windows wouldn't give the focus back to the window which had # been previously focused because it would still be disabled self.ReenableOtherWindows() self.Hide() # we have to yield because not only we want to update the display but # also to process the clicks on the cancel and skip buttons wx.SafeYield() return self._state != Canceled
def display_splash_screen(self): bmp = wx.Image("assets/enbarr.png").ConvertToBitmap() SplashScreen(bmp, SPLASH_CENTRE_ON_SCREEN | SPLASH_TIMEOUT, config.splash_screen_time, None, -1) wx.SafeYield() time.sleep(config.splash_screen_time / 1000) self.Show()
def OnPaint(self, event): """ Handles the ``wx.EVT_PAINT`` event for L{AdvancedSplash}. :param `event`: a `wx.PaintEvent` to be processed. """ dc = wx.PaintDC(self) # Here We Redraw The Bitmap Over The Frame dc.DrawBitmap(self.bmp, 0, 0, True) # We Draw The Text Anyway, Wheter It Is Empty ("") Or Not textcolour = self.GetTextColour() textfont = self.GetTextFont() textpos = self.GetTextPosition() text = self.GetText() dc.SetFont(textfont[0]) dc.SetTextForeground(textcolour) dc.DrawText(text, textpos[0], textpos[1]) # Seems like this only helps on OS X. if wx.Platform == "__WXMAC__": wx.SafeYield(self, True)
def GetWinId(self): """ Returns the windows Id as an integer. issue with GetHandle on Linux for wx versions >3 or 4. Window must be displayed before GetHandle is called. For that, just wait for a few milliseconds/seconds before calling InitDriver a solution is given here see https://github.com/cztomczak/cefpython/issues/349 but raises an issue with wxPython 4.x finally, it seems that the sleep function does the job reported as a pythonocc issue https://github.com/tpaviot/pythonocc-core/476 """ timeout = 10 # 10 seconds win_id = self.GetHandle() init_time = time.time() delta_t = 0. # elapsed time, initialized to 0 before the while loop # if ever win_id is 0, enter the loop untill it gets a value while win_id == 0 and delta_t < timeout: time.sleep(0.1) wx.SafeYield() win_id = self.GetHandle() delta_t = time.time() - init_time # check that win_id is different from 0 if win_id == 0: raise AssertionError("Can't get win Id") # otherwise returns the window Id return win_id
def main(width=1200, height=800): r"""Launch the main CadRacks IDE UI Parameters ---------- width : int Width of the CadRacks IDE UI frame height : int Height of the CadRacks IDE UI frame """ app = wx.App() # wx.InitAllImageHandlers() model = Model() frame = CadracksIdeFrame(parent=None, model=model, config=get_config(), size=(width, height)) frame.Show(True) # SafeYield(win, onlyIfNeeded) # see https://www.wxpython.org/docs/api/wx-module.html#SafeYield wx.SafeYield() # frame.runTests() app.SetTopWindow(frame) app.MainLoop()
def RequestUserAttention(self, dc, window, text, rect, pane): """ Requests the user attention by intermittently highlighting the pane caption. :param `dc`: a `wx.DC` device context; :param `window`: an instance of `wx.Window`; :param `text`: the text to be displayed; :param `rect`: the pane caption rectangle; :param `pane`: the pane for which the text is drawn. """ state = pane.state pane.state &= ~optionActive for indx in xrange(6): active = (indx % 2 == 0 and [True] or [False])[0] if active: pane.state |= optionActive else: pane.state &= ~optionActive self.DrawCaptionBackground(dc, rect, pane) self.DrawCaption(dc, window, text, rect, pane) wx.SafeYield() wx.MilliSleep(350) pane.state = state
def OnEndDragLeft(self, x, y, keys = 0, attachment = 0): shape = self.GetShape() oldpos = getpos(shape) # (int(shape.GetX()), int(shape.GetY())) # take care of selection points ogl.ShapeEvtHandler.OnEndDragLeft(self, x, y, keys, attachment) # super if not shape.Selected(): self.OnLeftClick(x, y, keys, attachment) newpos = getpos(shape) # (int(shape.GetX()), int(shape.GetY())) print shape.node.id, "moved from", oldpos, "to", newpos # Adjust the GraphNode to match the shape x,y shape.node.left, shape.node.top = newpos self.UpdateStatusBar(shape) wx.SafeYield() time.sleep(0.2) KEY_SHIFT, KEY_CTRL = 1, 2 if keys & KEY_SHIFT: shape.GetCanvas().graphrendererogl.stateofthenation() else: shape.GetCanvas().graphrendererogl.stage2()
def stateofthenation(self, animate=False, recalibrate=False): if recalibrate: # was stateofthespring self.coordmapper.Recalibrate() self.AllToWorldCoords() if animate: from animation import GeneratePoints for node in self.graph.nodes: node.anilist = GeneratePoints((node.previous_left, node.previous_top), (node.left, node.top), steps=5) dc = wx.ClientDC(self.oglcanvas) self.oglcanvas.PrepareDC(dc) for i in range(len(self.graph.nodes[0].anilist)): for node in self.graph.nodes: point = node.anilist.pop(0) x, y = point #node.shape.Move(dc, x, y, True) # don't do this or it will flicker setpos(node.shape, x, y) node.shape.MoveLinks(dc) self.Redraw(clear=False) self.Redraw() else: for node in self.graph.nodes: self.AdjustShapePosition(node) self.Redraw() wx.SafeYield()
def key_sequence_text_ctrl(control, interaction, delay): """ Performs simulated typing of a sequence of keys on the given wxObject after a delay. Parameters ---------- control : wxTextCtrl The wx Object to be acted on. interaction : instance of command.KeySequence The interaction object holding the sequence of key inputs to be simulated being typed delay : int Time delay (in ms) in which each key click in the sequence will be performed. Raises ------ Disabled If the control is either not enabled or not editable. """ # fail early for char in interaction.sequence: check_key_compat(char) if not (control.IsEnabled() and control.IsEditable()): raise Disabled("{!r} is disabled.".format(control)) if not control.HasFocus(): control.SetFocus() control.SetInsertionPointEnd() for char in interaction.sequence: wx.MilliSleep(delay) control.WriteText(char) wx.SafeYield()
def OnPaint(self, event): """ Handles the ``wx.EVT_PAINT`` event for L{AdvancedSplash}. :param `event`: a `wx.PaintEvent` to be processed. """ dc = wx.PaintDC(self) # Here We Redraw The Bitmap Over The Frame dc.DrawBitmap(self.bmp, 0, 0, True) # We draw the text anyway, whether it is empty ("") or not textcolour = self.GetTextColour() textfont = self.GetTextFont() textpos = self.GetTextPosition() text = '%s: %s' % (self.sw_version, self.GetText()) dc.SetFont(textfont[0]) dc.SetTextForeground(textcolour) dc.DrawText(text, textpos[0], textpos[1]) # draw progress bar here if self._progress > 0.0: dc.SetPen(wx.Pen(wx.WHITE, 1)) linepos = (textpos[0], self._progress_bar_height) dc.DrawLine( linepos[0], linepos[1], linepos[0] + (self._progress / 100.0) * self._progress_line_width, linepos[1]) # Seems like this only helps on OS X. if wx.Platform == "__WXMAC__": wx.SafeYield(self, True)
def on_btnAnimate_mouseClick(self, event): event.target.enabled = False canvas = self.components.bufOff canvas.autoRefresh = False self.animate = True avgfps = 0 frame = 0 seconds = util.time() # number of frames to display a second # on faster boxes this will throttle the number # of frames calculated and displayed, but on slower # boxes it won't prevent slowdown fps = 30 # amount of time that should pass before drawing another frame timePerFrame = 1.0 / fps #print timePerFrame # hack to force a difference # between time and startTime # to avoid a division by zero exception on fast machines # aka my Windows box ;-) startTime = util.time() - 0.001 while self.animate: newSeconds = util.time() if newSeconds - seconds >= timePerFrame: seconds = newSeconds canvas.clear() for ball in self.sprites: ball.move() canvas.refresh() frame += 1 self.statusBar.text = "Average FPS: %.4f Balls: %d" % (frame / (seconds - startTime), len(self.sprites)) # give the user a chance to click Stop wx.SafeYield(self, True)
def emit(self, record): try: msg = self.format(record) msg = msg.strip('\r') status_msg = None if ('\n' not in msg and 'elapsed' not in msg): # dispay simple info messages in the status bar plain_msg = logging._defaultFormatter.format(record) if (record.levelname == 'INFO'): status_msg = (plain_msg, 1) elif (record.levelname == 'DEBUG'): status_msg = (plain_msg, 2) evt = wxLogEvent(message=msg, levelname=record.levelname, status_msg=status_msg) wx.PostEvent(self.dest, evt) # @UndefinedVariable (hours,mins,secs) = ComputeBase.elapsed_time(self.last_gui_yield_time) if (secs > 0) or (mins > 0) or (hours > 0): self.last_gui_yield_time = time.time() wx.SafeYield(None, True) # @UndefinedVariable wx.GetApp().Yield(True) # @UndefinedVariable except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record)
def on_change_dir_button(self, event): """ create change directory frame """ currentDirectory = self.WD #os.getcwd() change_dir_dialog = wx.DirDialog(self.panel, "Choose your working directory to create or edit a MagIC contribution:", defaultPath=currentDirectory, style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON | wx.DD_CHANGE_DIR) result = change_dir_dialog.ShowModal() if result == wx.ID_CANCEL: return if result == wx.ID_OK: self.WD = change_dir_dialog.GetPath() self.dir_path.SetValue(self.WD) change_dir_dialog.Destroy() wait = wx.BusyInfo('Initializing data object in new directory, please wait...') wx.SafeYield() print('-I- Initializing magic data object') # make new builder object, but reuse old data_model self.er_magic = builder.ErMagicBuilder(self.WD, self.er_magic.data_model) print('-I- Read in any available data from working directory') self.er_magic.get_all_magic_info() print('-I- Initializing headers') self.er_magic.init_default_headers() self.er_magic.init_actual_headers() del wait
def LoadFile(self, filename): extension = os.path.basename(filename).split(".").pop().lower() start_time = time.time() if extension =="step" or extension == "stp": stepReader = STEPControl.STEPControl_Reader() stepReader.ReadFile(str(filename)) numTranslated = stepReader.TransferRoots() shape = stepReader.OneShape() elif extension == "stl": shape = TopoDS.TopoDS_Shape() stl_reader = StlAPI.StlAPI_Reader() stl_reader.Read(shape,str(filename)) elif extension =="iges" or extension =="igs": i = IGESControl.IGESControl_Controller() i.Init() iges_reader = IGESControl.IGESControl_Reader() iges_reader.ReadFile(str(filename)) iges_reader.TransferRoots() shape = iges_reader.OneShape() elif extension == "brep": shape = TopoDS.TopoDS_Shape() builder = BRep.BRep_Builder() BRepTools.BRepTools().Read(shape,str(filename),builder) else: return True self.canva._3dDisplay.EraseAll() self.canva._3dDisplay.DisplayShape(shape) wx.SafeYield() self.canva._3dDisplay.View_Iso() self.canva._3dDisplay.FitAll() end_time = time.time() self.SetTitle("pythonOCC Interactive Console %s:%s"%(VERSION,filename)) duration = end_time-start_time print "%s STEP file loaded and displayed in %f seconds."%(filename,duration)
def new_results(self, message): self.p_project = message.data self.p_path_files = [] self.p_formate = 10 self.p_create = False self.p_sep = ',' NewProject(self, self.properties, True) if self.p_create: style = wx.PD_APP_MODAL style |= wx.PD_CAN_ABORT dlg = PP.PyProgress(self, -1, L('MSG_PRO_HEADER_TITLE'), " :)", agwStyle=style) res, errs = self.ppr.add_res(self.p_project, self.p_path_files, self.p_formate, self.p_sep, dlg) dlg.Close() dlg.Destroy() # ---- informe de archivos con errores if errs != []: ResultErrors(self, errs) pub().sendMessage(T.ADD_RESULTS_IN_TREE, res) wx.SafeYield() wx.GetApp().GetTopWindow().Raise()
def PreSection_SlideShow(self, preSectionType): # Process for the pre-section (Slide-Show) ; show images with the interval if self.debug: print "Experiment.PreSection_SlideShow" commonFunc.writeFile( self.exptLogFileName, "%s, Experiment.PreSection_SlideShow()\n" % commonFunc.get_time_stamp()) trialInterval = exptApp.exptDetails["-1"][ "TRIAL_INTERVAL"] / 1000 # trial-interval is in millisecond for i in range(exptApp.exptDetails["-1"]["NUM_TRIALS"]): self.currTrial = exptApp.exptDetails["-1"][str( i)] # store stimuli-list to be displayed in this trial ### randomize the stimuli when the setting allows. self.stimuliIndices = range(self.currTrial["NUM_STIMULI"] ) # indices of stimuli for this trial if exptApp.settings["RANDOMIZE_STIMULI"]: shuffle(self.stimuliIndices) self.E_UI.mediaPanel.showImage(self.currTrial) # show image wx.SafeYield() ### play the sound when it's applicable if preSectionType == "SLIDESHOW_WITH_SOUND": soundStim = self.currTrial[ str(self.currTrial["NUM_STIMULI"] - 1)] # the last one is sound-stimulus self.E_UI.mediaPanel.LoadSound(soundStim) self.E_UI.mediaPanel.PlaySound() # play it. time.sleep(trialInterval) # wait for the interval self.currTrial = "" self.stimuliIndices = []
def DownloadFileContent(self,download_file_path,req,download_progress_dlg): is_cancel = False f = open(download_file_path, "wb") try: for chunk in req.iter_content(chunk_size=512): if chunk: if not download_progress_dlg.keep_going: is_cancel = True break f.write(chunk) download_progress_dlg._progress += len(chunk) if sysutils.isWindows(): Publisher.sendMessage(NOVAL_MSG_UI_DOWNLOAD_PROGRESS,temp = download_progress_dlg._progress,msg="") else: wx.MilliSleep(50) wx.SafeYield(download_progress_dlg,True) wx.CallAfter(Publisher.sendMessage,NOVAL_MSG_UI_DOWNLOAD_PROGRESS,temp=download_progress_dlg._progress,msg="") except Exception as e: wx.MessageBox(_("Download fail:%s") % e,style=wx.OK|wx.ICON_ERROR) time.sleep(1) download_progress_dlg.Destroy() return f.close() time.sleep(1) download_progress_dlg.keep_going = False download_progress_dlg.Destroy() if self._call_back is not None and not is_cancel: wx.CallAfter(self._call_back,download_file_path)
def simulate_cut(self, widget): # returns XML data import clipboard ret = clipboard.dump_widget(widget) widget.remove() wx.SafeYield() return ret
def on_btn_thellier_gui(self, event): """ Open Thellier GUI """ if not self.check_for_meas_file(): return if not self.check_for_uncombined_files(): return outstring = "thellier_gui.py -WD %s" % self.WD print("-I- running python script:\n %s" % (outstring)) # disable and hide Pmag GUI mainframe self.Disable() self.Hide() # show busyinfo wait = wx.BusyInfo('Compiling required data, please wait...') wx.SafeYield() # create custom Thellier GUI closing event and bind it ThellierGuiExitEvent, EVT_THELLIER_GUI_EXIT = newevent.NewCommandEvent( ) self.Bind(EVT_THELLIER_GUI_EXIT, self.on_analysis_gui_exit) # make and show the Thellier GUI frame thellier_gui_frame = thellier_gui.Arai_GUI( self.WD, self, standalone=False, DM=3, evt_quit=ThellierGuiExitEvent) if not thellier_gui_frame: print("Thellier GUI failed to start aborting") del wait return thellier_gui_frame.Centre() thellier_gui_frame.Show() del wait
def on_btn_demag_gui(self, event): """ Open Demag GUI """ if not self.check_for_meas_file(): return if not self.check_for_uncombined_files(): return outstring = "demag_gui.py -WD %s" % self.WD print("-I- running python script:\n %s" % (outstring)) # disable and hide Pmag GUI mainframe self.Disable() self.Hide() # show busyinfo wait = wx.BusyInfo('Compiling required data, please wait...') wx.SafeYield() # create custom Demag GUI closing event and bind it DemagGuiExitEvent, EVT_DEMAG_GUI_EXIT = newevent.NewCommandEvent() self.Bind(EVT_DEMAG_GUI_EXIT, self.on_analysis_gui_exit) # make and show the Demag GUI frame demag_gui_frame = demag_gui.Demag_GUI(self.WD, self, write_to_log_file=False, data_model=3, evt_quit=DemagGuiExitEvent) demag_gui_frame.Centre() demag_gui_frame.Show() del wait
def doHopalong(self): self.statusBar.text = "Drawing, please wait..." canvas = self.components.bufOff a = float(self.components.fldA.text) b = float(self.components.fldB.text) c = float(self.components.fldC.text) iterations = int(self.components.fldIterations.text) xOffset = float(self.components.fldXOffset.text) yOffset = float(self.components.fldYOffset.text) scale = float(self.components.fldScale.text) numColors = int(self.components.fldColors.text) totalPointsDrawn = 0 starttime = util.time() canvas.clear() for color, points in self.hopalong(a, b, c, iterations, xOffset, yOffset, scale, numColors): canvas.foregroundColor = color canvas.drawPointList(points) totalPointsDrawn += len(points) wx.SafeYield(self) if not self.drawing: break elapsed = util.time() - starttime self.statusBar.text = "hopalong time: %f seconds (%d points drawn)" % ( elapsed, totalPointsDrawn) self.drawing = False self.components.btnDraw.enabled = True self.components.btnCancel.enabled = False