def GenPage(self, gameId, pageId=1, START=True, typ='Images'): wx.BeginBusyCursor() self.stb.SetStatusText('Fetching %s imgs page %s....' % (gameId, pageId)) urls = { 'Images': bgg_img_browse_url, 'Files': bgg_file_browse_url, 'Links': bgg_link_browse_url, } url = urls[typ] src = urlretrieve(url % (int(gameId), int(pageId))) src = src[0] texts = [ "<h1>%s of %s (#%s) - Page %d</h1>" % (typ, self.results.GetItemText( self.results.Selection), gameId, pageId), '<ol>' ] if typ == "Images": bs = BS(file(src).read()) imgs = [x.get('src') for x in bs.findAll('img', {"class": None})] for index, img in enumerate(imgs): href = img.replace('_mt.jpg', '.jpg') img = img.replace('_mt.jpg', '_t.jpg') texts.append('%d:<a href="%s"><img src="%s"></a></li>' % (index, href, img)) texts.append('</ol>') else: texts.append(file(src).read().decode('cp1252')) texts.append('</ol>') #texts.append('<div align="center"><input type="button" value"Download Selected"></div></form>') from tempfile import mktemp from os import linesep, startfile if not self.currentfile: dst = mktemp(suffix=".html") file(dst, 'wb').write(linesep.join(texts).encode('cp1252')) self.currentfile = dst else: dst = self.currentfile file(dst, 'ab').write(linesep.join(texts).encode('cp1252')) wx.EndBusyCursor() if START: startfile(self.currentfile)
def showSubmitDebugLogDialog(): dlg = SubmitDebugReportDialog(None,wx.ID_ANY,"",self.loggerOutput.getvalue(),self.globalLauncherConfig,self.globalLauncherPreferencesFilePath,showFailedToOpenRemoteDesktopMessage=showFailedToOpenRemoteDesktopMessage) try: if wx.IsBusy(): wx.EndBusyCursor() stoppedBusyCursor = True else: stoppedBusyCursor = False result = dlg.ShowModal() if stoppedBusyCursor: wx.BeginBusyCursor() launcherMainFrame.submit_log = result == wx.ID_OK if launcherMainFrame.submit_log: self.name = dlg.getName() self.email = dlg.getEmail() self.comments = dlg.getComments() self.pleaseContactMe = dlg.getPleaseContactMe() finally: dlg.Destroy() launcherMainFrame.submitDebugLogDialogCompleted = True
def OnPortSettings(self, event): wx.BeginBusyCursor() lab_val = self.thread.dispath(event, 's') self.res0_val.SetLabel(lab_val[0]) self.res1_val.SetLabel(lab_val[1]) self.res2_val.SetLabel(lab_val[2]) self.res3_val.SetLabel(lab_val[3]) self.button_cancel.Enable() self.button_find.Disable() self.button_ok.Disable() self.GetParent().GetParent().GetParent().enableOpPanelBtn() self.panel_results.Show() self.Layout() wx.EndBusyCursor()
def _func_decorated_with_required_role_checking(*args, **kwargs): if _known_roles.index(minimum_role) > _known_roles.index( _curr_staff['role']): _log.info('access denied: %s', activity) _log.debug('required role: %s', minimum_role) _log.debug('current role: %s (<%s>)', _curr_staff['l10n_role'], _curr_staff['role']) _log.debug('current user: %s (<%s>)', _curr_staff['short_alias'], _curr_staff['db_user']) wx.EndBusyCursor() if fail_silently: return return_value_on_failure gmGuiHelpers.gm_show_error( aTitle=_('Access denied'), aMessage= _('Your account is not set up to access this part of GNUmed:\n' '\n' ' [%s]') % activity) return return_value_on_failure return original_function(*args, **kwargs)
def doAutoDetect( self, event ): wx.BeginBusyCursor() self.shutdown() impinjHost = AutoDetect( ImpinjInboundPort, self.autoDetectCallback ) wx.EndBusyCursor() if impinjHost: self.useStaticAddress.SetValue( True ) self.useHostName.SetValue( False ) self.impinjHost.SetValue( impinjHost ) self.doReset() self.writeOptions() wx.Bell() else: dlg = wx.MessageDialog(self, 'Auto Detect Failed.\nCheck that reader has power and is connected to the router.', 'Auto Detect Failed', wx.OK | wx.ICON_INFORMATION ) dlg.ShowModal() dlg.Destroy()
def OnSearch(self, event=None): value = self.filter.GetValue() if not value: self.objectList.PopulateList() return wx.BeginBusyCursor() newData = dict() newId = 1 for prevId,data in self.objectList.objectCounts.items(): for entry in data: if re.search(str(value), str(entry), re.I): newData[newId] = data newId += 1 break self.objectList.PopulateList(newData) ## Send a size event to refresh the scroll bar # self.objectList.list.SendSizeEvent() # self.dataPanel.SendSizeEvent() # self.onButtonFunctions() wx.EndBusyCursor()
def EndBusyCursorIfRequired(event): """ The built in wx.EndBusyCursor raises an ugly exception if the busy cursor has already been stopped. """ # pylint: disable=no-member # Otherwise pylint complains about PyAssertionError. # pylint: disable=protected-access try: wx.EndBusyCursor() if event.settingsDialog: if wx.version().startswith("3.0.3.dev"): arrowCursor = wx.Cursor(wx.CURSOR_ARROW) else: arrowCursor = wx.StockCursor(wx.CURSOR_ARROW) event.settingsDialog.dialogPanel.SetCursor(arrowCursor) except wx._core.PyAssertionError, err: if "no matching wxBeginBusyCursor()" not in str(err): logger.error(str(err)) raise
def OnGridSalSelected(event): row = event.GetRow() if row<self.dbctr.mov.RowsCount(): db = self.gridmas.dbmas mov = self.dbctr.mov mov.MoveRow(row) if mov.giorno is None: d1 = None d2 = self.FindWindowByName('cscdatini').GetValue() if d2: d2 -= 1 else: d1 = d2 = mov.reg.datreg db.ClearMovFilters() db.SetDateStart(d1) db.SetDateEnd(d2) wx.BeginBusyCursor() db.Get(self.dbctr.id) wx.EndBusyCursor() self.gridmas.UpdateGrid() event.Skip()
def ShowDialog(message): """ Show error dialog in main thread. """ logger.error(message) # pylint: disable=no-member # Otherwise pylint complains about PyAssertionError. # pylint: disable=protected-access try: wx.EndBusyCursor() if wx.version().startswith("3.0.3.dev"): arrowCursor = wx.Cursor(wx.CURSOR_ARROW) else: arrowCursor = wx.StockCursor(wx.CURSOR_ARROW) event.settingsDialog.dialogPanel.SetCursor(arrowCursor) except wx._core.PyAssertionError, err: if "no matching wxBeginBusyCursor()" \ not in str(err): logger.error(str(err)) raise
def OnOpen(self, evt): '''wx.ID_OPEN handler.''' if not self.AskSave(): return exts = 'XRC files (*.xrc)|*.xrc' if g.useMeta: exts += '|CRX files (*.crx)|*.crx' dlg = wx.FileDialog(self.frame, 'Open', os.path.dirname(Presenter.path), '', exts, wx.OPEN | wx.CHANGE_DIR) if dlg.ShowModal() == wx.ID_OK: if self.testWin.IsShown(): self.testWin.Destroy() # Clear old undo data g.undoMan.Clear() path = dlg.GetPath() wx.BeginBusyCursor() try: Presenter.open(path) self.frame.SetStatusText('Data loaded') self.SaveRecent(path) finally: wx.EndBusyCursor() dlg.Destroy()
def OnCyclops(self, event): model = self.getModel() if model: if self.checkUnsaved(model): return self.editor.setStatus(_('Running Cyclops on %s ...')%model.filename) wx.BeginBusyCursor() try: report = model.cyclops() finally: wx.EndBusyCursor() resName = _('Cyclops report: %s')%time.strftime('%H:%M:%S', time.localtime(time.time())) if not model.views.has_key(resName): resultView = self.editor.addNewView(resName, EditorViews.CyclopsView) else: resultView = model.views[resName] resultView.tabName = resName resultView.report = report resultView.refresh() resultView.focus()
def _updateImageAndControlsResync(self, image, label): # Hide the busy cursor. wx.EndBusyCursor() if image is None: # Provide a black bitmap. bitmap = wx.EmptyBitmap(self._maxImageSize, self._maxImageSize / 2) else: # Convert the image to bitmap format. bitmap = WxUtils.wxBitmapFromCvImage(image) # Show the bitmap. self._staticBitmap.SetBitmap(bitmap) # Show the label. self._labelStaticText.SetLabel(label) # Resize the sizer and frame. self._rootSizer.Fit(self) # Re-enable the controls. self._enableControls() # Refresh. self.Refresh()
def DoCapture(self): if sniffer is None: wx.MessageBox('There is no SUMP device connected.', 'SUMP Error', wx.CANCEL | wx.ICON_ERROR) return tw = self._selected_page() wx.BeginBusyCursor() sniffer.send_settings(tw.settings) try: d = sniffer.capture(tw.settings) except KeyboardInterrupt: sniffer.reset() d = None sys.stderr.write('interrupted\n') sys.stderr.flush() wx.EndBusyCursor() if d is not None: sys.stderr.write('captured\n') sys.stderr.flush() tw.SetData(self._captured_sump_data(tw.settings, d))
def OnCallDoc(self, event): row = event.GetRow() dbmov = self.dbmov if 0 <= row < dbmov.RowsCount(): dbmov.MoveRow(row) wx.BeginBusyCursor() try: Dialog = magazz.GetDataentryDialogClass() dlg = Dialog(aw.awu.GetParentFrame(self)) dlg.SetOneDocOnly(dbmov.doc.id) dlg.CenterOnScreen() finally: wx.EndBusyCursor() r = dlg.ShowModal() if r in (magazz.DOC_MODIFIED, magazz.DOC_DELETED): self.UpdateGrid() if r == magazz.DOC_MODIFIED: wx.CallAfter(lambda: self.SelectRow(row)) dlg.Destroy() event.Skip()
def OnButtonClick(self, evt): ide = evt.GetId() if ide == ID_FEEDBACK: ShowFeedbackDialog(self, preferences=self.preferences) elif ide == ID_EXT_BUG: wx.BeginBusyCursor() try: webbrowser.open( "https://github.com/brigittebigi/sppas/issues/", 1) except: pass wx.EndBusyCursor() else: obj = evt.GetEventObject() evt = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, obj.GetId()) evt.SetEventObject(self) wx.PostEvent(self.GetParent(), evt)
def UpdateGridAgenti(self, ra, rz): if ra: if self.agente_mode == 'anag': col = 'agente.id' else: col = 'agecod' elif rz: col = 'zonacli.id' dbscad = self.dbscad dbscad._info.group.groups[0][0] = col dbscad._info.group.groups[1][0] = '0.0' wx.BeginBusyCursor() try: if not dbscad.Retrieve(): awc.util.MsgDialog(self,\ "Problema in lettura dati:\n\n%s"\ % repr(dbscad.GetError())) finally: wx.EndBusyCursor() self.gridtot1.ChangeData(copy.deepcopy(dbscad.GetRecordset()))
def writeHex(self, hexdata): wx.BeginBusyCursor() if hexdata: try: f = tempfile.TemporaryFile(delete=False) f.write(hexdata) f.close() if self.erase() and self.burn(f.name): delete_file(f.name) done = kadeProgrammed(None, self.firmware) done.ShowModal() done.Destroy() else: delete_file(f.name) self.popup("problem") except: self.popup("problem") else: self.popup("select") wx.EndBusyCursor()
def on_timer(self, *args): if self.which_case == 0: tree = self.dir_ctrl.GetTreeCtrl() item = tree.GetSelection() #if item != tree.GetRootItem(): path = self.dir_ctrl.GetPath() self.picture_list.set_path(path) elif self.which_case == 1: tb = self.GetToolBar() tb.ToggleTool(wx.xrc.XRCID('report_view'), True) tb.ToggleTool(wx.xrc.XRCID('thumbs_view'), False) self.GetMenuBar().Check(wx.xrc.XRCID('report_view'), True) self.picture_list.show_details() elif self.which_case == 2: tb = self.GetToolBar() tb.ToggleTool(wx.xrc.XRCID('report_view'), False) tb.ToggleTool(wx.xrc.XRCID('thumbs_view'), True) self.GetMenuBar().Check(wx.xrc.XRCID('thumbs_view'), True) self.picture_list.show_thumbs() if wx.IsBusy(): wx.EndBusyCursor()
def OpenFileDialog(self, event): dlg = wx.FileDialog(self, wildcard="*.pdf") filePath = None if dlg.ShowModal() == wx.ID_OK: wx.BeginBusyCursor() self.pageNr = 1 filePath = dlg.GetPath() # Upload file to venue try: self.dataStoreClient.Upload(filePath) except: self.log.exception("OpenFileDialog: Upload file %s failed"%(filePath)) self.PopulateCombobox(default = os.path.basename(filePath)) wx.EndBusyCursor() dlg.Destroy()
def PopulateCombobox(self, default = None): # Get pdf files from venue fileNames = [] wx.BeginBusyCursor() try: self.dataStoreClient.LoadData() fileNames = self.dataStoreClient.QueryMatchingFiles("*.pdf") except: self.log.exception("FileSelectorDialog.PopulateCombobox: QueryMatchingFiles failed.") wx.EndBusyCursor() self.pdfList.Clear() for file in fileNames: self.pdfList.Append(file) if default and not len(default) == 0: self.pdfList.SetValue(default) else: self.pdfList.SetSelection(0)
def OnScreenshotTimer(self): oldpos = self.Parent.Position try: top = self.Top top.Move((-top.Size.width - 50, -top.Size.height - 50)) wx.BeginBusyCursor() wx.WakeUpIdle() wx.MilliSleep(500) global num_screenshots num_screenshots += 1 log.info('taking screenshot %d', num_screenshots) screen_full, screen = app_windows_image() diag = ScreenshotDialog(self, screen_full, screen, pos=oldpos + Point(40, 40)) except: print_exc() screen = None finally: wx.EndBusyCursor() self.Top.Move(oldpos) if screen is None: return try: if diag.ShowModal() == wx.ID_OK: self.screenshot = diag.SelectedScreenshot self.screenshot_link.Label = _("Remove Screenshot") else: self.screenshot_link.Label = _('Take Screenshot') finally: diag.Destroy() self.Layout() self.Refresh()
def on_slice_data(self, evt): """Handles request to export a slice of data""" slice_dlg = dlg.ExportSliceDialog(parent=self.view, datafile=self.view.data_panel.data) if slice_dlg.ShowModal() == wx.ID_OK: try: wx.BeginBusyCursor() sliced_data = dataio.get_data(self.view.data_panel.data, slice_dlg.get_slice()) sliced_data_fname = "_".join( ["sliced", os.path.basename(self.view.data_panel.data)]) fname_dlg = wx.TextEntryDialog( parent=self.view, message="Please specify a filename for the sliced data.", caption="Save Sliced Data", defaultValue=sliced_data_fname) if fname_dlg.ShowModal() == wx.ID_OK: dest_fname = os.path.join(pathfinder.data_path(), fname_dlg.GetValue()) dataio.save_data(dest_fname, sliced_data) self.view.data_panel.populate() except TypeError: # bad dimensions err_dlg = wx.MessageDialog( self.view, message="Specified dimensions out of range for this data.", caption="Unable To Slice Data", style=wx.ICON_ERROR) err_dlg.ShowModal() err_dlg.Destroy() except ValueError: # zero-length slices, etc. err_dlg = wx.MessageDialog( self.view, message="Zero-length slices are not permitted.", caption="Unable To Slice Data", style=wx.ICON_ERROR) err_dlg.ShowModal() err_dlg.Destroy() finally: wx.EndBusyCursor() slice_dlg.Destroy()
def Open(self): """ Opens a scenery file """ openDialog = wx.FileDialog(self, "Choose scenery file", \ "", "", "Textual format (*.*)|*.*") openDialog.CentreOnParent() openDialog.SetDirectory(self.workingDirectory) if openDialog.ShowModal() == wx.ID_OK: path = openDialog.GetPath() try: wx.BeginBusyCursor() sceneryFile = file(path, "r") try: scenery = yaml.load(sceneryFile, sptyaml.SptLoader) if not isinstance(scenery, model.scenery.Scenery): raise Exception("Input file is not scenery") self.editor.SetScenery(scenery) self.modified = False self.path = path self.UpdateTitle() finally: sceneryFile.close() wx.EndBusyCursor() except yaml.YAMLError, inst: logging.warning("Error while parsing scenery file: ", exc_info=inst) mark_str = "" if hasattr(inst, "problem_mark"): mark = inst.problem_mark mark_str = "Line: %d, Column: %d" % (mark.line+1, mark.column+1) wx.MessageBox("Error while parsing scenery file:\n" \ + inst.problem + "\n" + mark_str, \ "Parsing error", wx.OK | wx.ICON_ERROR, self) except Exception, inst: logging.exception("Error while reading scenery file:") wx.MessageBox("Error while reading scenery file:\n" \ + str(inst), \ "Open file error", wx.OK | wx.ICON_ERROR, self)
def OnAddFiles(self, filenames): for file in filenames: if file is None: continue # failed dragdrop? file_stat=os.stat(file) mtime=file_stat.st_mtime if self._raw_media: target=self.get_media_name_from_filename(file) data=open(file, 'rb').read() self.AddToIndex(target, self.active_section, data, self._data, mtime) else: # do we want to convert file? afi=fileinfo.identify_audiofile(file) if afi.size<=0: continue # zero length file or other issues newext,convertinfo=self.mainwindow.phoneprofile.QueryAudio(None, common.getext(file), afi) if convertinfo is not afi: filedata=None wx.EndBusyCursor() try: filedata=self.ConvertFormat(file, convertinfo) finally: # ensure they match up wx.BeginBusyCursor() if filedata is None: continue else: filedata=open(file, "rb").read() # check for the size limit on the file, if specified max_size=getattr(convertinfo, 'MAXSIZE', None) if max_size is not None and len(filedata)>max_size: # the data is too big self.log('ringtone %s is too big!'%common.basename(file)) with guihelper.WXDialogWrapper(wx.MessageDialog(self, 'Ringtone %s may be too big. Do you want to proceed anway?'%common.basename(file), 'Warning', style=wx.YES_NO|wx.ICON_ERROR), True) as (dlg, dlg_resp): if dlg_resp==wx.ID_NO: continue target=self.get_media_name_from_filename(file, newext) self.AddToIndex(target, self.active_section, filedata, self._data, mtime) self.OnRefresh()
def define_cscan(self): """Specify a range of data and a function to generate a C Scan plot""" if self.model.data is not None: rng_dlg = dialogs.FloatRangeDialog( "Please specify the index range in Z.") if rng_dlg.ShowModal() == wx.ID_OK: try: start_pos, end_pos = rng_dlg.GetValue() fn_dlg = wx.SingleChoiceDialog( parent=self.view, caption="Choose C Scan Function", message= "Please choose a function to generate the C Scan data.", choices=self.scnr.available_cscan_function_names) if fn_dlg.ShowModal() == wx.ID_OK: wx.BeginBusyCursor() cscan_data = self.scnr.gen_cscan( start_pos, end_pos, fn=self.scnr.available_cscan_functions[ fn_dlg.GetSelection()]) self.plot_cscan(cscan_data, self.slice_idx) plot_title = "C Scan {0} z={1}:{2}".format( self.scnr.available_cscan_function_names[ fn_dlg.GetSelection()], start_pos, end_pos) self.set_titles(self.view.cscan_axes, plot=plot_title) wx.EndBusyCursor() except ValueError as err: module_logger.error( "Unable to generate C-scan: {0}".format(err)) err_msg = "{0}".format(err) err_dlg = wx.MessageDialog( self.view, message=err_msg, caption="Unable To Generate C Scan", style=wx.ICON_ERROR) err_dlg.ShowModal() err_dlg.Destroy() finally: rng_dlg.Destroy()
def start(self, evt=None): """Start a new interpreter process. """ if self.isStarted: # nop if started already self.toolbar.update() return # inform the user that we're starting the console self.txtTerm.Clear() self.txtTerm.WriteText( "Starting Python interpreter session, please wait ...\n") self.txtTerm._applyAppTheme() # setup the sub-process wx.BeginBusyCursor() self._process = wx.Process(self) self._process.Redirect() # get the path to the interpreter interpPath = '"' + sys.executable + '"' # start the sub-process self._pid = wx.Execute( r' '.join([interpPath, r'-i']), wx.EXEC_ASYNC, self._process) # bind the event called when the process ends self._process.Bind(wx.EVT_END_PROCESS, self.onTerminate) # clear all text in the widget and display the welcome message self.txtTerm.Clear() self.txtTerm.WriteText( "Python shell in PsychoPy (pid:{}) - type some commands!\n\n".format( self._pid)) # show the subprocess PID for reference self._lastTextPos = self.txtTerm.GetLastPosition() self.toolbar.update() self.setFonts() wx.EndBusyCursor()
def doAutoDetect( self, event ): wx.BeginBusyCursor() self.gracefulShutdown() self.shutdown() impinjHost, crossMgrHost = AutoDetect(ImpinjInboundPort)[0], '127.0.0.1' wx.EndBusyCursor() if impinjHost and crossMgrHost: self.useStaticAddress.SetValue( True ) self.useHostName.SetValue( False ) self.impinjHost.SetValue( impinjHost ) self.crossMgrHost.SetValue( crossMgrHost ) else: dlg = wx.MessageDialog(self, 'Auto Detect Failed.\nCheck that reader has power and is connected to the router.', 'Auto Detect Failed', wx.OK | wx.ICON_INFORMATION ) dlg.ShowModal() dlg.Destroy() self.doReset( event, False )
def _paste(parent, sizer, pos, clipboard_data): "parse XML and insert widget" option, span, flag, border, xml_unicode = clipboard2widget(clipboard_data) if not xml_unicode: return False import xml_parse try: wx.BeginBusyCursor() # widget representation is still unicode, but parser need UTF8 xml_utf8 = xml_unicode.encode('utf8') parser = xml_parse.ClipboardXmlWidgetBuilder(parent, sizer, pos, option, span, flag, border) with parent and parent.frozen() or misc.dummy_contextmanager(): parser.parse_string(xml_utf8) common.app_tree.saved = False return True # Widget hierarchy pasted. except xml_parse.XmlParsingError: if config.debugging: raise return False finally: wx.EndBusyCursor()
def _CreateEdit(self, value_as_string, extra, typ, height, border, CtrlMixin): #create ctrl class Ctrl = ctrl_factory(typ, CtrlMixin) #adjust border if issubclass(Ctrl, TextCtrl): border = max(border, TEXTCTRL_BORDER) #create ctrl instance if Ctrl._busy_cursor: wx.BeginBusyCursor() self.edit = Ctrl(self, value=Ctrl._to_english(value_as_string), size=(height, height - 2 * border), **extra) #check min size if self.edit.GetSize()[1] > height: self.edit.SetMinSize((self.edit.GetMinSize()[0], height)) #self.edit.SetFocus() if Ctrl._busy_cursor: wx.EndBusyCursor() return border
def _paste(parent, pos, clipboard_data): "parse XML and insert widget" option, span, flag, border, xml_unicode = clipboard2widget( clipboard_data ) if not xml_unicode: return False import xml_parse try: wx.BeginBusyCursor() # widget representation is still unicode, but parser need UTF8 xml_utf8 = xml_unicode.encode('utf8') parser = xml_parse.ClipboardXmlWidgetBuilder(parent, pos, option, span, flag, border) with parent and parent.frozen() or misc.dummy_contextmanager(): parser.parse_string(xml_utf8) if parent and hasattr(parent, "on_child_pasted"): parent.on_child_pasted() # trigger e.g. re-sizing of the children misc.rebuild_tree( parser.top_obj ) return True # Widget hierarchy pasted. except xml_parse.XmlParsingError: if config.debugging: raise return False finally: wx.EndBusyCursor()