def runExportPeaklist(self, path): """Export peeaklist data.""" # get peaklist selection = {'All Peaks': '', 'Selected Peaks': 'S'} filters = selection[self.peaklistSelect_choice.GetStringSelection()] peaklist = self.parent.getCurrentPeaklist(filters) # check peaklist if not peaklist: wx.Bell() return # export to ascii if config.export['peaklistFormat'] in ('ASCII', 'ASCII with Headers'): buff = '' # set separator separator = config.export['peaklistSeparator'] if config.export['peaklistSeparator'] == 'tab': separator = '\t' # export headers if config.export['peaklistFormat'] == 'ASCII with Headers': header = '' if 'mz' in config.export['peaklistColumns']: header += "m/z" + separator if 'ai' in config.export['peaklistColumns']: header += "a.i." + separator if 'base' in config.export['peaklistColumns']: header += "base" + separator if 'int' in config.export['peaklistColumns']: header += "int" + separator if 'rel' in config.export['peaklistColumns']: header += "r.int." + separator if 'sn' in config.export['peaklistColumns']: header += "s/n" + separator if 'z' in config.export['peaklistColumns']: header += "z" + separator if 'mass' in config.export['peaklistColumns']: header += "mass" + separator if 'fwhm' in config.export['peaklistColumns']: header += "fwhm" + separator if 'resol' in config.export['peaklistColumns']: header += "resol." + separator if 'group' in config.export['peaklistColumns']: header += "group" + separator buff += '%s\n' % (header.rstrip()) # export data for peak in peaklist: line = '' if 'mz' in config.export['peaklistColumns']: line += str(peak.mz) + separator if 'ai' in config.export['peaklistColumns']: line += str(peak.ai) + separator if 'base' in config.export['peaklistColumns']: line += str(peak.base) + separator if 'int' in config.export['peaklistColumns']: line += str(peak.intensity) + separator if 'rel' in config.export['peaklistColumns']: line += str(peak.ri * 100) + separator if 'sn' in config.export['peaklistColumns']: line += str(peak.sn) + separator if 'z' in config.export['peaklistColumns']: line += str(peak.charge) + separator if 'mass' in config.export['peaklistColumns']: line += str(peak.mass()) + separator if 'fwhm' in config.export['peaklistColumns']: line += str(peak.fwhm) + separator if 'resol' in config.export['peaklistColumns']: line += str(peak.resolution) + separator if 'group' in config.export['peaklistColumns']: line += str(peak.group) + separator buff += '%s\n' % (line.replace("None", "").rstrip()) # export to mgf elif config.export['peaklistFormat'] == 'MGF': # export data buff = 'BEGIN IONS\n' for peak in peaklist: buff += '%f %f\n' % (peak.mz, peak.intensity) buff += 'END IONS' # save file try: save = file(path, 'w') save.write(buff.encode("utf-8")) save.close() except IOError: wx.Bell()
def getParams(self): """Get dialog params.""" try: config.profound['title'] = self.paramTitle_value.GetValue() config.profound['database'] = self.paramDatabase_choice.GetStringSelection() config.profound['taxonomy'] = self.paramTaxonomy_choice.GetStringSelection() config.profound['enzyme'] = self.paramEnzyme_choice.GetStringSelection() config.profound['miscleavages'] = self.paramMiscleavages_choice.GetStringSelection() config.profound['proteinMassLow'] = self.paramProteinMassLow_value.GetValue() config.profound['proteinMassHigh'] = self.paramProteinMassHigh_value.GetValue() config.profound['proteinPILow'] = self.paramProteinPILow_value.GetValue() config.profound['proteinPIHigh'] = self.paramProteinPIHigh_value.GetValue() config.profound['peptideTol'] = self.paramPeptideTol_value.GetValue() config.profound['peptideTolUnits'] = self.paramPeptideTolUnits_choice.GetStringSelection() config.profound['massType'] = self.paramMassType_choice.GetStringSelection() config.profound['charge'] = self.paramCharge_choice.GetStringSelection() config.profound['expectation'] = self.paramExpectation_value.GetValue() config.profound['candidates'] = self.paramCandidates_value.GetValue() if self.paramZscore_radio.GetValue(): config.profound['ranking'] = 'zscore' else: config.profound['ranking'] = 'expect' fixedMods = self.paramFixedMods_listbox.GetStrings() variableMods = self.paramVariableMods_listbox.GetStrings() config.profound['fixedMods'] = [] config.profound['variableMods'] = [] for item in self.paramFixedMods_listbox.GetSelections(): config.profound['fixedMods'].append(fixedMods[item]) for item in self.paramVariableMods_listbox.GetSelections(): config.profound['variableMods'].append(variableMods[item]) if config.profound['proteinMassLow']: config.profound['proteinMassLow'] = float(config.profound['proteinMassLow']) if config.profound['proteinMassHigh']: config.profound['proteinMassHigh'] = float(config.profound['proteinMassHigh']) if config.profound['proteinPILow']: config.profound['proteinPILow'] = float(config.profound['proteinPILow']) if config.profound['proteinPIHigh']: config.profound['proteinPIHigh'] = float(config.profound['proteinPIHigh']) if config.profound['peptideTol']: config.profound['peptideTol'] = float(config.profound['peptideTol']) if config.profound['expectation']: config.profound['expectation'] = float(config.profound['expectation']) if config.profound['candidates']: config.profound['candidates'] = int(config.profound['candidates']) return True except: wx.Bell() return False
def onImport(self, evt): """Import items from xml library.""" # show open file dialog wildcard = "Library files|*.xml;*.XML" dlg = wx.FileDialog(self, "Import Library", wildcard=wildcard, style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() dlg.Destroy() else: dlg.Destroy() return # read data importedItems = self.readLibraryXML(path) if importedItems == False: wx.Bell() dlg = mwx.dlgMessage( self, title="Unrecognized library format.", message="Specified file is not a valid reference library.") dlg.ShowModal() dlg.Destroy() return elif importedItems == {}: wx.Bell() dlg = mwx.dlgMessage(self, title="No data to import.", message="Specified library contains no data.") dlg.ShowModal() dlg.Destroy() return # select groups to import dlg = dlgSelectItemsToImport(self, importedItems) if dlg.ShowModal() == wx.ID_OK: selected = dlg.selected dlg.Destroy() else: dlg.Destroy() return # check same items selectAfter = 'Reference lists' replaceAll = False for item in selected: if replaceAll or not item in libs.references: libs.references[item] = importedItems[item] selectAfter = item else: title = 'Group entitled "%s"\nis already in you library. Do you want to replace it?' % item message = "All references within this group will be lost." buttons = [(ID_dlgReplaceAll, "Replace All", 120, False, 40), (ID_dlgSkip, "Skip", 80, False, 15), (ID_dlgReplace, "Replace", 80, True, 0)] dlg = mwx.dlgMessage(self, title, message, buttons) ID = dlg.ShowModal() if ID == ID_dlgSkip: continue elif ID == ID_dlgReplaceAll: replaceAll = True libs.references[item] = importedItems[item] selectAfter = item elif ID == ID_dlgReplace: libs.references[item] = importedItems[item] selectAfter = item # update gui self.updateGroups() self.groupName_choice.SetStringSelection(selectAfter) self.onGroupSelected()
def onGenerate(self, evt=None): """Generate compounds ions.""" # check processing if self.processing: return # clear recent self.currentCompounds = None compounds = {} # clear match panel if self.matchPanel: self.matchPanel.clear() # get params if not self.getParams(): self.updateCompoundsList() return # get compounds from selected group or formula if self.currentTool == 'compounds': group = self.compounds_choice.GetStringSelection() if group and group in libs.compounds: compounds = libs.compounds[group] else: formula = self.formula_value.GetValue() if formula: try: compounds[formula] = mspy.compound(formula) except: wx.Bell() # check compounds if not compounds: self.updateCompoundsList() return # show processing gauge self.onProcessing(True) self.generate_butt.Enable(False) self.match_butt.Enable(False) self.annotate_butt.Enable(False) # do processing self.processing = threading.Thread(target=self.runGenerateIons, kwargs={'compounds': compounds}) self.processing.start() # pulse gauge while working while self.processing and self.processing.isAlive(): self.gauge.pulse() # update compounds list self._compoundsFilter = 0 self.updateCompoundsList() # hide processing gauge self.onProcessing(False) self.generate_butt.Enable(True) self.match_butt.Enable(True) self.annotate_butt.Enable(True) # send data to match panel if self.matchPanel: self.matchPanel.setData(self.currentCompounds)
def OnFind(self, evt): """Does the work of finding the text @param evt: Event that called this handler """ # Map of search flags flag_map = { wx.FR_MATCHCASE : wx.stc.STC_FIND_MATCHCASE, wx.FR_WHOLEWORD : wx.stc.STC_FIND_WHOLEWORD, wx.FR_MATCHCASE | wx.FR_WHOLEWORD : \ wx.stc.STC_FIND_MATCHCASE | \ wx.stc.STC_FIND_WHOLEWORD, 0 : 0 } # Get Search Type search_id = evt.GetEventType() # Get the Search Flags s_flags = self._data.GetFlags() pool = self.FetchPool() query = self._data.GetFindString() if search_id in [wx.wxEVT_COMMAND_FIND, wx.wxEVT_COMMAND_FIND_NEXT]: if search_id == wx.wxEVT_COMMAND_FIND_NEXT: if wx.FR_DOWN & s_flags: if self._posinfo['found'] < 0: pool.SetCurrentPos(0) # Start at top again else: pool.SetCurrentPos(pool.GetCurrentPos() + len(query)) else: # Searching previous if self._posinfo['found'] < 0: pool.SetCurrentPos(pool.GetLength()) else: pool.SetCurrentPos(pool.GetCurrentPos() - len(query)) pool.SearchAnchor() if not s_flags & wx.FR_DOWN: found = pool.SearchPrev(flag_map[s_flags] | \ wx.stc.STC_FIND_REGEXP, query) else: found = pool.SearchNext(flag_map[s_flags - wx.FR_DOWN] | \ wx.stc.STC_FIND_REGEXP, query) if found > 0: pool.SetCurrentPos(found) # HACK to ensure selection is visible sel = pool.GetSelection() pool.SetSelection(sel[1], sel[0]) else: # Try search from begining/end again self.SetStart(pool) self.SetScroll(pool) if not s_flags & wx.FR_DOWN: pool.SetCurrentPos(pool.GetLength()) pool.SetSelection(pool.GetLength(), pool.GetLength()) else: pool.SetCurrentPos(0) pool.SetSelection(0, 0) pool.SearchAnchor() if not s_flags & wx.FR_DOWN: found = pool.SearchPrev(flag_map[s_flags] | \ wx.stc.STC_FIND_REGEXP, query) else: found = pool.SearchNext(flag_map[s_flags - wx.FR_DOWN] | \ wx.stc.STC_FIND_REGEXP, query) if found < 0: # Couldnt find it anywhere so set screen back to start position pool.ScrollToLine(self._posinfo['scroll']) pool.SetCurrentPos(self._posinfo['start']) pool.SetSelection(self._posinfo['start'], self._posinfo['start']) wx.Bell() # alert user to unfound string else: pool.SetCurrentPos(found) # HACK to ensure selection is visible sel = pool.GetSelection() pool.SetSelection(sel[1], sel[0]) self._posinfo['found'] = found elif search_id == wx.wxEVT_COMMAND_FIND_REPLACE: replacestring = evt.GetReplaceString() pool.ReplaceSelection(replacestring) elif search_id == wx.wxEVT_COMMAND_FIND_REPLACE_ALL: replacestring = evt.GetReplaceString() self.SetStart(pool) # Save Start point self.SetScroll(pool) # Save scroll pos pool.SetTargetStart(0) pool.SetTargetEnd(pool.GetLength()) pool.SetSearchFlags(flag_map[s_flags - wx.FR_DOWN] | \ wx.stc.STC_FIND_REGEXP) replaced = 0 pool.BeginUndoAction() while pool.SearchInTarget(query) > 0: pool.SetSelection(pool.GetTargetStart(), pool.GetTargetEnd()) pool.ReplaceSelection(replacestring) replaced += 1 pool.SetTargetStart(pool.GetTargetStart() + len(replacestring)) pool.SetTargetEnd(pool.GetLength()) pool.EndUndoAction() pool.ScrollToLine(self._posinfo['scroll']) pool.SetCurrentPos(self._posinfo['start']) # Move cursor to start pool.SetSelection(self._posinfo['start'], self._posinfo['start']) dlg = wx.MessageDialog(self._parent, _("Replace All Finished\n" "A Total of %d matches were replaced") % \ replaced, _("All Done"), wx.OK | wx.ICON_INFORMATION) dlg.CenterOnParent() dlg.ShowModal() dlg.Destroy() else: evt.Skip()
def OnChar(self, event): """ Validates keystrokes to make sure the resulting value will a legal value. Erasing the value causes it to be set to 0, with the value selected, so it can be replaced. Similarly, replacing the value with a '-' sign causes the value to become -1, with the value selected. Leading zeros are removed if introduced by selection, and are prevented from being inserted. """ key = event.GetKeyCode() ctrl = event.GetEventObject() value = ctrl.GetValue() textval = wx.TextCtrl.GetValue(ctrl) allow_none = ctrl.IsNoneAllowed() pos = ctrl.GetInsertionPoint() sel_start, sel_to = ctrl.GetSelection() select_len = sel_to - sel_start # (Uncomment for debugging:) ## print 'keycode:', key ## print 'pos:', pos ## print 'sel_start, sel_to:', sel_start, sel_to ## print 'select_len:', select_len ## print 'textval:', textval # set defaults for processing: allow_event = 1 set_to_none = 0 set_to_zero = 0 set_to_minus_one = 0 paste = 0 internally_set = 0 new_value = value new_text = textval new_pos = pos # Validate action, and predict resulting value, so we can # range check the result and validate that too. if key in (wx.WXK_DELETE, wx.WXK_BACK, WXK_CTRL_X): if select_len: new_text = textval[:sel_start] + textval[sel_to:] elif key == wx.WXK_DELETE and pos < len(textval): new_text = textval[:pos] + textval[pos + 1:] elif key == wx.WXK_BACK and pos > 0: new_text = textval[:pos - 1] + textval[pos:] # (else value shouldn't change) if new_text in ('', '-'): # Deletion of last significant digit: if allow_none and new_text == '': new_value = None set_to_none = 1 else: new_value = 0 set_to_zero = 1 else: try: new_value = ctrl._fromGUI(new_text) except ValueError: allow_event = 0 elif key == WXK_CTRL_V: # (see comments at top of file) # Only allow paste if number: paste_text = ctrl._getClipboardContents() new_text = textval[:sel_start] + paste_text + textval[sel_to:] if new_text == '' and allow_none: new_value = None set_to_none = 1 else: try: # Convert the resulting strings, verifying they # are legal integers and will fit in proper # size if ctrl limited to int. (if not, # disallow event.) new_value = ctrl._fromGUI(new_text) if paste_text: paste_value = ctrl._fromGUI(paste_text) else: paste_value = 0 new_pos = sel_start + len(str(paste_value)) # if resulting value is 0, truncate and highlight value: if new_value == 0 and len(new_text) > 1: set_to_zero = 1 elif paste_value == 0: # Disallow pasting a leading zero with nothing selected: if (select_len == 0 and value is not None and ((value >= 0 and pos == 0) or (value < 0 and pos in [0, 1]))): allow_event = 0 paste = 1 except ValueError: allow_event = 0 elif key < wx.WXK_SPACE or key > 255: pass # event ok elif chr(key) == '-': # Allow '-' to result in -1 if replacing entire contents: if (value is None or (value == 0 and pos == 0) or (select_len >= len(str(abs(value))))): new_value = -1 set_to_minus_one = 1 # else allow negative sign only at start, and only if # number isn't already zero or negative: elif pos != 0 or (value is not None and value < 0): allow_event = 0 else: new_text = '-' + textval new_pos = 1 try: new_value = ctrl._fromGUI(new_text) except ValueError: allow_event = 0 elif chr(key) in string.digits: # disallow inserting a leading zero with nothing selected if (chr(key) == '0' and select_len == 0 and value is not None and ((value >= 0 and pos == 0) or (value < 0 and pos in [0, 1]))): allow_event = 0 # disallow inserting digits before the minus sign: elif value is not None and value < 0 and pos == 0: allow_event = 0 else: new_text = textval[:sel_start] + chr(key) + textval[sel_to:] try: new_value = ctrl._fromGUI(new_text) except ValueError: allow_event = 0 else: # not a legal char allow_event = 0 if allow_event: # Do range checking for new candidate value: if ctrl.IsLimited() and not ctrl.IsInBounds(new_value): allow_event = 0 elif new_value is not None: # ensure resulting text doesn't result in a leading 0: if not set_to_zero and not set_to_minus_one: if ((new_value > 0 and new_text[0] == '0') or (new_value < 0 and new_text[1] == '0') or (new_value == 0 and select_len > 1)): # Allow replacement of leading chars with # zero, but remove the leading zero, effectively # making this like "remove leading digits" # Account for leading zero when positioning cursor: if (key == wx.WXK_BACK or (paste and paste_value == 0 and new_pos > 0)): new_pos = new_pos - 1 wx.CallAfter(ctrl.SetValue, new_value) wx.CallAfter(ctrl.SetInsertionPoint, new_pos) internally_set = 1 elif paste: # Always do paste numerically, to remove # leading/trailing spaces wx.CallAfter(ctrl.SetValue, new_value) wx.CallAfter(ctrl.SetInsertionPoint, new_pos) internally_set = 1 elif (new_value == 0 and len(new_text) > 1): allow_event = 0 if allow_event: ctrl._colorValue(new_value) # (one way or t'other) # (Uncomment for debugging:) ## if allow_event: ## print 'new value:', new_value ## if paste: print 'paste' ## if set_to_none: print 'set_to_none' ## if set_to_zero: print 'set_to_zero' ## if set_to_minus_one: print 'set_to_minus_one' ## if internally_set: print 'internally_set' ## else: ## print 'new text:', new_text ## print 'disallowed' ## print if allow_event: if set_to_none: wx.CallAfter(ctrl.SetValue, new_value) elif set_to_zero: # select to "empty" numeric value wx.CallAfter(ctrl.SetValue, new_value) wx.CallAfter(ctrl.SetInsertionPoint, 0) wx.CallAfter(ctrl.SetSelection, 0, 1) elif set_to_minus_one: wx.CallAfter(ctrl.SetValue, new_value) wx.CallAfter(ctrl.SetInsertionPoint, 1) wx.CallAfter(ctrl.SetSelection, 1, 2) elif not internally_set: event.Skip() # allow base wxTextCtrl to finish processing elif not wx.Validator_IsSilent(): wx.Bell()
def _copy(): if focused_widget is None or focused_widget.IS_SLOT: wx.Bell() return clipboard.copy(focused_widget)
def OnQrCodeImage(self, event): """Display the QR code image.""" GetLogger().info("%s displaying QR code image.", self.GetName()) if not self.DisplayQrCodeImage(): wx.Bell() event.Skip()
def OnFind(self, event): findstr = self.finddata.GetFindString() if not self.FindString(findstr): wx.Bell() # beep at the user for no match
def _cut(): global focused_widget if not _can_remove(): wx.Bell() return clipboard.cut(focused_widget)
def move_item_up(self, event): "moves the selected menu item before the previous one at the same level in self.menu_items" if self.selected_index <= 0: wx.Bell() return self._do_move_item(event, self.selected_index, False)
def _copy(): if focused_widget is None or focused_widget.klass=="sizerslot": wx.Bell() return clipboard.copy(focused_widget)
def _cut(): global focused_widget if not _can_remove() or focused_widget.klass=="sizerslot": wx.Bell() return clipboard.cut(focused_widget)
def open_url_in_bookworm(self, url: str): if not (url := url.strip()): wx.Bell() return
def _paste(): if focused_widget is None: return if not hasattr(focused_widget, "clipboard_paste"): wx.Bell() return clipboard.paste(focused_widget)
def SpecialControlKey(self, event, key): if not event.ControlDown(): return False if not self.Dispatch(self.SetSpecialControlFuncs, key, event): wx.Bell() return True
def OnChar(self, event): """Verify that the caracters entered in the control are compatible with a float number""" key = event.GetKeyCode() # Accept delete and special caracters. if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255: event.Skip() return window = self.GetWindow() answer = window.GetValue() selection_span = window.GetSelection() # Accept the digits, except before a dash. if chr(key) in string.digits: if selection_span[1] == len(answer) or answer[selection_span[1]] != "-": event.Skip() return # Dash can be used in negative numbers and in the exponential # notation. elif chr(key) == "-": # If the dash is at the beginning of the control, the minimum # must be negative. if selection_span[0] == 0: if self.minimum is None or self.minimum < 0.0: if selection_span[1] == len(answer) or answer[selection_span[1]] != "-": event.Skip() return # If the dash is not at the beginning of the control, it must # immediatly follow an e. else: if answer[selection_span[0]-1] in ["e", "E"] and "-" not in answer[selection_span[1]:]: event.Skip() return # If the character is a point, verify that the control doesn't # already contain a point or that point is in the selection. # (window.GetValue() gets the value before the addition of the new # decimal point.) elif chr(key) == ".": before = answer[:selection_span[0]] if "e" not in before and "E" not in before: if not "." in answer or "." in answer[selection_span[0]:selection_span[1]]: event.Skip() return # If the character is a e, verify that the control doesn't # already contain a e that is not in the selection. elif chr(key) in ["e", "E"]: selection = answer[selection_span[0]:selection_span[1]] if "e" not in answer and "E" not in answer or "e" in selection or "E" in selection: if "." not in answer[selection_span[1]:]: event.Skip() return if not wx.Validator_IsSilent(): wx.Bell()
def beep(): """Sound the system bell.""" wx.Bell()
def Validate(self, parent): """Validate the content of the control This method takes a single argument: parent the control that is validated and it returns True if the content of the control is a float within the imposed limits or False otherwise.""" # If the condition for testing is not filled, the test is not # performed. if self.condition and not self.condition(): return True error = False window = self.GetWindow() answer = window.GetValue() # First try to convert the value to a float. try: value = float(answer) except ValueError: error = True # Check if the value is NaN or another similar condition. if not error: if value - value != 0.0: error = True # Then verify that the value fits in acceptable values. if not error: if self.minimum is not None: if callable(self.minimum): minimum = self.minimum() else: minimum = self.minimum if self.include_minimum: if value < minimum: error = True else: if value <= minimum: error = True if self.maximum is not None: if callable(self.maximum): maximum = self.maximum() else: maximum = self.maximum if self.include_maximum: if value > maximum: error = True else: if value >= maximum: error = True if error: if not wx.Validator_IsSilent(): wx.Bell() window.SetFocus() window.SetSelection(0, len(answer)) window.Refresh() return False return True
def OnChar(self, event): key = event.GetKeyCode() tc = self.GetWindow() val = tc.GetValue() pos = tc.GetInsertionPoint() if event.GetUnicodeKey() != wx.WXK_NONE: if key in [wx.WXK_RETURN, wx.WXK_TAB, wx.WXK_BACK]: event.Skip() return if chr(key) in string.digits: if len(val) == 0: event.Skip() return if pos == 0 and val[0] == '-': if not wx.Validator_IsSilent(): wx.Bell() return event.Skip() return if chr(key) == '.' and '.' not in val: if 'e' in val: # Check so that the . ends up correctly relative e if pos > val.index('e'): if not wx.Validator_IsSilent(): wx.Bell() return if len(val) == 0: event.Skip() return if pos == 0 and val[0] == '-': if not wx.Validator_IsSilent(): wx.Bell() return event.Skip() return if chr(key) == 'e' and 'e' not in val: if '.' in val: # Check so that the e ends up correctly relative . if pos <= val.index('.'): if not wx.Validator_IsSilent(): wx.Bell() return if len(val) == 0: event.Skip() return if pos == 0 and val[0] == '-': if not wx.Validator_IsSilent(): wx.Bell() return event.Skip() return if chr(key) == '-': if val[0] != '-' and pos == 0: event.Skip() return elif val[pos - 1] == 'e' and '-' not in val[pos - 1:]: event.Skip() return elif key in [wx.WXK_TAB, wx.WXK_RETURN, wx.WXK_DOWN, wx.WXK_UP, wx.WXK_LEFT, wx.WXK_RIGHT, wx.WXK_NUMPAD_LEFT, wx.WXK_NUMPAD_RIGHT, wx.WXK_DELETE, wx.WXK_BACK]: event.Skip() return if not wx.Validator.IsSilent(): wx.Bell() # Does not allow the event to propagate (kills it) return
def display(self, text): self.SetInsertionPointEnd() self.Freeze() if self.global_queue: text = self.global_queue + text self.global_queue = '' # it is not clear whether this is the correct (a) thing to do, or # (b) place to do it, but some wackass MUDs seem to be sending \r\n # with an ANSI blob in between(!!!). Going Unixy and just using \n text = re.sub('\r', '', text) # line-based filters should do their thing, returning None if they ate # everything they should enqueue any partial lines they're "in the # middle of" handling and be ready for the rest of the line; then they # should examine the remainder for further handling or enqueueing. for fil in self.filters: text = fil(self, text) if text == None: return # output_filter must return None if it handled it #if (True or prefs.get('render_emoji'): # TODO - preference? "if (we detect an emoji)?" #text = emoji.emojize(text, use_aliases = True) if prefs.get('use_ansi'): # Dear lord this is sorta ugly # TODO -- let's make this whole thing an external filter that # returns text chunks and TextAttrs to blat at the screen. For # now, we can still do it line-by-line, but eventually we might # want to be properly character-based/VT supporting. # For now, we'll stick the FANSI character poop into an # external filter. if self.connection.world.get("use_fansi"): text = fansi_replace(text) # snip and ring bells # TODO -- "if beep is enabled in the prefs" text, count = re.subn("\007", '', text) for b in range(0, count): print("DEBUG: found an ANSI beep") wx.Bell() # chop the text into text, ansi, text, ansi.... bits = re.split('\033\[(\d+(?:;\d+)*)m', text) for idx, bit in enumerate(bits): # if we're on the last bit, check whether it might be a partial ANSI blob if idx == len(bits) - 1: if re.search('\033', bit): print( f"I think I have a spare ANSI bit ({bit}), requeueing it" ) self.global_queue += bit break if bit == '': continue # if it's ansi... if (idx % 2): # pick apart the ANSI stuff. codes = [int(c) for c in bit.split(';')] while codes: command, payload = ansi_codes[codes.pop(0)] if command == 'foreground' or command == "background": if payload == "extended": subtype = codes.pop(0) # 24-bit color if subtype == 2: colour = self.theme.rgb_to_hex( (codes.pop(0), codes.pop(0), codes.pop(0))) # 256-color elif subtype == 5: colour = self.theme.index256_to_hex( codes.pop(0)) else: print( "Got an unknown fg/bg ANSI subtype: " + str(subtype)) else: colour = payload if command == "foreground": self.fg_colour = colour else: self.bg_colour = colour self.set_current_colours() elif command == 'control': switcher = { 'normal': self.doansi_normal, 'bright': self.doansi_bright, 'dim': self.doansi_dim, 'italic': self.BeginItalic, 'underline': self.BeginUnderline, 'blink': self.doansi_blink, 'inverse': self.doansi_inverse, 'conceal': self.doansi_conceal, 'strike': self.doansi_strike, 'normal_weight': self.doansi_normal_weight, 'no_italic': self.EndItalic, 'no_underline': self.EndUnderline, 'no_blink': self.doansi_no_blink, 'no_conceal': self.doansi_no_conceal, 'no_strike': self.doansi_no_strike, 'framed': self.doansi_framed, 'encircled': self.doansi_encircled, 'overline': self.doansi_overline, 'no_framed_encircled': self.doansi_no_framed_encircled, 'no_overline': self.doansi_no_overline, 'default_fg': self.doansi_default_fg, 'default_bg': self.doansi_default_bg, } ansifunc = switcher.get( payload, lambda: "Unknown ANSI sequence") ansifunc() else: print("unknown ANSI command:", command) else: # is a text-only chunk, check for URLs if prefs.get('highlight_urls'): matches = utility.URL_REGEX.split(bit) for chunk in matches: if not chunk: continue if utility.URL_REGEX.match(chunk): self.BeginURL(chunk) self.BeginUnderline() current_intensity = self.intensity self.intensity = 'normal' self.BeginTextColour( self.lookup_colour('blue')) self.intensity = current_intensity self.WriteText(chunk) self.EndTextColour() self.EndUnderline() self.EndURL() else: self.WriteText(chunk) else: self.WriteText(bit) else: self.WriteText(text) self.Thaw()
def OnButton(self, event): wx.Bell()
def error_output(self, text): wx.Bell() frame = self.GetParent().GetParent().GetParent() frame.SetStatusText(str(text))
def OnAllEdit(self, event): if self.selected_all_item: self.OpenPlayerNotesDialog(self.selected_all_item) else: wx.Bell()
def undo(self, focused_widget): if not self.actions: return wx.Bell() action = self.actions.pop(0) action.undo() self.actions_redo.append(action)
def getParams(self): """Get all params from dialog.""" try: # image config.export['imageWidth'] = float( self.imageWidth_value.GetValue()) config.export['imageHeight'] = float( self.imageHeight_value.GetValue()) config.export[ 'imageUnits'] = self.imageUnits_choice.GetStringSelection() config.export[ 'imageFormat'] = self.imageFormat_choice.GetStringSelection() config.export['imageResolution'] = int( self.imageResolution_choice.GetStringSelection()) config.export['imageFontsScale'] = int( self.imageFontsScale_slider.GetValue()) config.export['imageDrawingsScale'] = int( self.imageDrawingsScale_slider.GetValue()) # peaklist data config.export['peaklistColumns'] = [] if self.peaklistColumnMz_check.IsChecked(): config.export['peaklistColumns'].append('mz') if self.peaklistColumnAi_check.IsChecked(): config.export['peaklistColumns'].append('ai') if self.peaklistColumnBase_check.IsChecked(): config.export['peaklistColumns'].append('base') if self.peaklistColumnInt_check.IsChecked(): config.export['peaklistColumns'].append('int') if self.peaklistColumnRel_check.IsChecked(): config.export['peaklistColumns'].append('rel') if self.peaklistColumnZ_check.IsChecked(): config.export['peaklistColumns'].append('z') if self.peaklistColumnMass_check.IsChecked(): config.export['peaklistColumns'].append('mass') if self.peaklistColumnSn_check.IsChecked(): config.export['peaklistColumns'].append('sn') if self.peaklistColumnFwhm_check.IsChecked(): config.export['peaklistColumns'].append('fwhm') if self.peaklistColumnResol_check.IsChecked(): config.export['peaklistColumns'].append('resol') if self.peaklistColumnGroup_check.IsChecked(): config.export['peaklistColumns'].append('group') choices = {'Comma': ',', 'Semicolon': ';', 'Tab': 'tab'} config.export['peaklistSeparator'] = choices[ self.peaklistSeparator_choice.GetStringSelection()] # spectrum data choices = {'Comma': ',', 'Semicolon': ';', 'Tab': 'tab'} config.export['spectrumSeparator'] = choices[ self.spectrumSeparator_choice.GetStringSelection()] # ring error bell if error except: wx.Bell() return False return True
def end_edit_label(self, evt): # Finish editing a label. This can be prevented by calling Veto() if evt.IsEditCancelled(): return item = evt.Item widget = self._GetItemData(item) if "name" not in widget.properties: return new_value = evt.Label if new_value == widget._get_tree_label(): return new_name = new_label = new_title = new_tab = new_class = new_stockitem = None if widget.check_prop_truth("class"): if new_value.count("(") == 1 and new_value.count(")") == 1: pre, new_class = new_value.split("(") new_class, post = new_class.split(")") if pre.endswith(" "): pre = pre[:-1] new_value = pre + post if widget.check_prop_truth("stockitem"): if ":" in new_value: new_name, new_stockitem = new_value.split(":", 1) new_stockitem = new_stockitem.strip().upper() if not new_stockitem in widget.STOCKITEMS: new_stockitem = None elif new_value.strip().upper() in widget.STOCKITEMS: new_stockitem = new_value.strip().upper() else: new_name = new_value elif "label" in widget.properties and widget._label_editable(): new_name, new_label = self._split_name_label(new_value) elif "label" in widget.properties: # label is not editable, but name may have changed new_name, dummy = self._split_name_label(new_value) elif getattr(widget, "has_title", None): new_name, new_title = self._split_name_label(new_value) elif getattr( widget, "parent", None ) and widget.parent.WX_CLASS == "wxNotebook" and "]" in new_value: # notebook pages: include page title: "[title] name" new_tab, new_name = new_value.rsplit("]", 1) if "[" in new_tab: new_tab = new_tab.split("[", 1)[-1] new_name = new_name.strip() else: new_name = new_value # check name if new_name: name_p = widget.properties["name"] if new_name == name_p.get(): new_name = None if new_name: # check warning, error = name_p.check_value(new_name) if warning or error: new_name = None # check class/klass if new_class: class_p = widget.properties["klass"] if new_class == class_p.get(): new_class = None if new_class: # check warning, error = name_p.check_value(new_class) if warning or error: new_class = None # check label if new_label is not None: label_p = widget.properties["label"] if new_label == label_p.get(): new_label = None if (not new_name and new_label is None and new_title is None and new_tab is None and new_class is None and not new_stockitem): # no change or an error wx.Bell() evt.Veto() return # check title if new_stockitem is not None: stockitem_p = widget.properties["stockitem"] if new_stockitem == stockitem_p.get(): new_stockitem = None # check title if new_title is not None: title_p = widget.properties["title"] if new_title == title_p.get(): new_title = None # check notabook tab if new_tab is not None: notebook = widget.parent tabs_p = notebook.properties["tabs"] if widget in notebook.children: index = notebook.children.index(widget) if notebook.tabs[index][0] == new_tab: new_tab = None else: new_tabs = notebook.tabs[:] new_tabs[index][0] = new_tab else: new_tab = None # actually modify the values modified = set() if new_name: name_p.previous_value = name_p.value name_p.set(new_name, notify=False) modified.add("name") if new_class: class_p.previous_value = class_p.value class_p.set(new_class, notify=False) modified.add("class") if new_label: label_p.previous_value = label_p.value label_p.set(new_label, notify=False) modified.add("label") if new_stockitem: stockitem_p.previous_value = stockitem_p.value stockitem_p.set(new_stockitem, notify=False) modified.add("stockitem") if new_title: title_p.previous_value = title_p.value title_p.set(new_title, notify=False) modified.add("title") if modified: widget.properties_changed(modified) self.root.saved = False # update the status of the app if new_tab: tabs_p.previous_value = tabs_p.value tabs_p.set(new_tabs, notify=True) wx.CallAfter(self.refresh, widget, refresh_label=True ) # setting from within the event handler does not work
def __init__(self, parent, traceback=''): wx.Dialog.__init__(self, parent, id=wx.ID_ANY, title=u"PsychoPy3 Error", pos=wx.DefaultPosition, size=wx.Size(750, -1), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) self.details = traceback # message to show at the top of the error box, needs translation msg = u"PsychoPy encountered an unhandled internal error! " \ u"Please send the report under \"Details\" to the " \ u"developers with a description of what you were doing " \ u"with the software when the error occurred." self.SetSizeHints(wx.DefaultSize, wx.DefaultSize) szErrorMsg = wx.BoxSizer(wx.VERTICAL) szHeader = wx.FlexGridSizer(0, 3, 0, 0) szHeader.AddGrowableCol(1) szHeader.SetFlexibleDirection(wx.BOTH) szHeader.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED) self.imgErrorIcon = wx.StaticBitmap( self, wx.ID_ANY, wx.ArtProvider.GetBitmap( wx.ART_ERROR, wx.ART_MESSAGE_BOX), wx.DefaultPosition, wx.DefaultSize, 0) szHeader.Add(self.imgErrorIcon, 0, wx.ALL, 5) self.lblErrorMsg = wx.StaticText( self, wx.ID_ANY, msg, wx.DefaultPosition, wx.DefaultSize, 0) self.lblErrorMsg.Wrap(560) szHeader.Add(self.lblErrorMsg, 0, wx.ALL, 5) szHeaderButtons = wx.BoxSizer(wx.VERTICAL) self.cmdOK = wx.Button( self, wx.ID_OK, u"&OK", wx.DefaultPosition, wx.DefaultSize, 0) szHeaderButtons.Add(self.cmdOK, 0, wx.LEFT | wx.EXPAND, 5) self.cmdExit = wx.Button( self, wx.ID_EXIT, u"E&xit PsychoPy", wx.DefaultPosition, wx.DefaultSize, 0) szHeaderButtons.Add(self.cmdExit, 0, wx.TOP | wx.LEFT | wx.EXPAND, 5) szHeader.Add(szHeaderButtons, 0, wx.ALL | wx.EXPAND, 5) szErrorMsg.Add(szHeader, 0, wx.TOP | wx.LEFT | wx.RIGHT | wx.EXPAND, 5) self.pnlDetails = wx.CollapsiblePane( self, wx.ID_ANY, u"&Details", wx.DefaultPosition, wx.DefaultSize, wx.CP_DEFAULT_STYLE) self.pnlDetails.Collapse(True) szDetailsPane = wx.BoxSizer(wx.VERTICAL) self.txtErrorOutput = wx.TextCtrl( self.pnlDetails.GetPane(), wx.ID_ANY, self.details, wx.DefaultPosition, wx.Size(640, 150), wx.TE_AUTO_URL | wx.TE_BESTWRAP | wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_WORDWRAP) szDetailsPane.Add(self.txtErrorOutput, 1, wx.ALL | wx.EXPAND, 5) szTextButtons = wx.BoxSizer(wx.HORIZONTAL) self.cmdCopyError = wx.Button( self.pnlDetails.GetPane(), wx.ID_ANY, u"&Copy", wx.DefaultPosition, wx.DefaultSize, 0) szTextButtons.Add(self.cmdCopyError, 0, wx.RIGHT, 5) self.cmdSaveError = wx.Button( self.pnlDetails.GetPane(), wx.ID_ANY, u"&Save", wx.DefaultPosition, wx.DefaultSize, 0) szTextButtons.Add(self.cmdSaveError, 0) szDetailsPane.Add(szTextButtons, 0, wx.ALL | wx.ALIGN_RIGHT, 5) self.pnlDetails.Expand() self.pnlDetails.GetPane().SetSizer(szDetailsPane) self.pnlDetails.GetPane().Layout() szDetailsPane.Fit(self.pnlDetails.GetPane()) szErrorMsg.Add(self.pnlDetails, 1, wx.ALL | wx.BOTTOM | wx.EXPAND, 5) self.SetSizer(szErrorMsg) self.Layout() self.Fit() self.Centre(wx.BOTH) # Connect Events self.cmdOK.Bind(wx.EVT_BUTTON, self.onOkay) self.cmdExit.Bind(wx.EVT_BUTTON, self.onExit) self.cmdCopyError.Bind(wx.EVT_BUTTON, self.onCopyDetails) self.cmdSaveError.Bind(wx.EVT_BUTTON, self.onSaveDetails) # ding! wx.Bell()
def __init__(self, parent): self.name = '&Track' super(TrackMenu, self).__init__() parent.Bind( wx.EVT_MENU, application.frame.select_playing, self.Append(wx.ID_ANY, '&Focus Playing\tALT+RETURN', 'Select the currently playing result.')) parent.Bind( wx.EVT_MENU, application.frame.load_artist_tracks, self.Append( wx.ID_ANY, 'Goto &Artist\tCTRL+4', 'View all tracks by the artist of the currently focused track.' )) parent.Bind( wx.EVT_MENU, application.frame.load_related_artist, self.Append( wx.ID_ANY, 'Go To &Related Artist...\tCTRL+7', 'Select an artist related to the artist of the currently selected result.' )) parent.Bind( wx.EVT_MENU, application.frame.load_current_album, self.Append(wx.ID_ANY, 'Go To A&lbum\tCTRL+5', 'Load the album of the currently selected track.')) parent.Bind( wx.EVT_MENU, application.frame.load_album, self.Append( wx.ID_ANY, '&Choose Album\tCTRL+6', 'Choose an album from the artist of the currently selected artist.' )) parent.Bind( wx.EVT_MENU, application.frame.load_top_tracks, self.Append( wx.ID_ANY, '&Top Tracks\tCTRL+;', 'Load the top tracks for the artist of the currently selected track.' )) parent.Bind( wx.EVT_MENU, application.frame.toggle_library, self.Append( wx.ID_ANY, 'Add / Remove From &Library\tCTRL+/', 'Add or remove the currently selected track from library.')) parent.Bind( wx.EVT_MENU, lambda event: playlist_action( 'Select a playlist to add this track to', 'Select A Playlist', add_to_playlist, application.frame.get_result()) if application.frame.get_result() is not None else wx.Bell(), self.Append(wx.ID_ANY, 'Add To &Playlist...\tCTRL+8', 'Add the currently selected track to a playlist.')) parent.Bind( wx.EVT_MENU, lambda event: add_to_playlist(application.frame.last_playlist, application.frame.get_result()) if application.frame.last_playlist is not None and application. frame.application.frame.get_result() is not None else wx.Bell(), self.Append( wx.ID_ANY, 'Add To Most Recent Playlist\tCTRL+RETURN', 'Add the currently selected track to the most recent playlist.' )) parent.Bind( wx.EVT_MENU, application.frame.do_delete, self.Append( wx.ID_ANY, '&Delete\tDELETE', 'Delete the currently selected track from the current view.')) parent.Bind( wx.EVT_MENU, parent.edit_lyrics, self.Append(wx.ID_ANY, 'Edit &Lyrics...\tCTRL+SHIFT+L', 'Edit the lyrics for the currently-selected track.')) parent.Bind( wx.EVT_MENU, self.copy_id, self.Append(wx.ID_ANY, '&Copy ID\tCTRL+SHIFT+C', 'Copy the ID of the current track to the clipboard.'))