INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Selects a single cell
def select_cell(self, row, col, add_to_selected=False): """Selects a single cell""" self.grid.SelectBlock(row, col, row, col, addToSelected=add_to_selected)
Selects a slice of cells Parameters ---------- * row_slc: Integer or Slice \tRows to be selected * col_slc: Integer or Slice \tColumns to be selected * add_to_selected: Bool, defaults to False \tOld selections are cleared if False
def select_slice(self, row_slc, col_slc, add_to_selected=False): """Selects a slice of cells Parameters ---------- * row_slc: Integer or Slice \tRows to be selected * col_slc: Integer or Slice \tColumns to be selected * add_to_selected: Bool, defaults to False \tOld selections are cleared if False """ if not add_to_selected: self.grid.ClearSelection() if row_slc == row_slc == slice(None, None, None): # The whole grid is selected self.grid.SelectAll() elif row_slc.stop is None and col_slc.stop is None: # A block is selected: self.grid.SelectBlock(row_slc.start, col_slc.start, row_slc.stop - 1, col_slc.stop - 1) else: for row in xrange(row_slc.start, row_slc.stop, row_slc.step): for col in xrange(col_slc.start, col_slc.stop, col_slc.step): self.select_cell(row, col, add_to_selected=True)
Deletes selection, marks content as changed If selection is None then the current grid selection is used. Parameters ---------- selection: Selection, defaults to None \tSelection that shall be deleted
def delete_selection(self, selection=None): """Deletes selection, marks content as changed If selection is None then the current grid selection is used. Parameters ---------- selection: Selection, defaults to None \tSelection that shall be deleted """ # Mark content as changed post_command_event(self.main_window, self.ContentChangedMsg) if selection is None: selection = self.get_selection() current_table = self.grid.current_table for row, col, tab in self.grid.code_array.dict_grid.keys(): if tab == current_table and (row, col) in selection: self.grid.actions.delete_cell((row, col, tab)) self.grid.code_array.result_cache.clear()
Deletes a selection if any else deletes the cursor cell Refreshes grid after deletion
def delete(self): """Deletes a selection if any else deletes the cursor cell Refreshes grid after deletion """ if self.grid.IsSelection(): # Delete selection self.grid.actions.delete_selection() else: # Delete cell at cursor cursor = self.grid.actions.cursor self.grid.actions.delete_cell(cursor) # Update grid self.grid.ForceRefresh()
Quotes selected cells, marks content as changed
def quote_selection(self): """Quotes selected cells, marks content as changed""" selection = self.get_selection() current_table = self.grid.current_table for row, col, tab in self.grid.code_array.dict_grid.keys(): if tab == current_table and (row, col) in selection: self.grid.actions.quote_code((row, col, tab)) self.grid.code_array.result_cache.clear()
Copys access_string to selection to the clipboard An access string is Python code to reference the selection If there is no selection then a reference to the current cell is copied
def copy_selection_access_string(self): """Copys access_string to selection to the clipboard An access string is Python code to reference the selection If there is no selection then a reference to the current cell is copied """ selection = self.get_selection() if not selection: cursor = self.grid.actions.cursor selection = Selection([], [], [], [], [tuple(cursor[:2])]) shape = self.grid.code_array.shape tab = self.grid.current_table access_string = selection.get_access_string(shape, tab) # Copy access string to clipboard self.grid.main_window.clipboard.set_clipboard(access_string) # Display copy operation and access string in status bar statustext = _("Cell reference copied to clipboard: {access_string}") statustext = statustext.format(access_string=access_string) post_command_event(self.main_window, self.StatusBarMsg, text=statustext)
Pastes cell formats Pasting starts at cursor or at top left bbox corner
def paste_format(self): """Pastes cell formats Pasting starts at cursor or at top left bbox corner """ row, col, tab = self.grid.actions.cursor selection = self.get_selection() if selection: # Use selection rather than cursor for top left cell if present row, col = [tl if tl is not None else 0 for tl in selection.get_bbox()[0]] cell_attributes = self.grid.code_array.cell_attributes string_data = self.grid.main_window.clipboard.get_clipboard() format_data = ast.literal_eval(string_data) ca = format_data["cell_attributes"] rh = format_data["row_heights"] cw = format_data["col_widths"] assert isinstance(ca, types.ListType) assert isinstance(rh, types.DictType) assert isinstance(cw, types.DictType) # Cell attributes for selection_params, tab, attrs in ca: base_selection = Selection(*selection_params) shifted_selection = base_selection.shifted(row, col) if "merge_area" not in attrs: # Do not paste merge areas because this may have # inintended consequences for existing merge areas new_cell_attribute = shifted_selection, tab, attrs cell_attributes.append(new_cell_attribute) # Row heights row_heights = self.grid.code_array.row_heights for __row, __tab in rh: row_heights[__row+row, tab] = rh[__row, __tab] # Column widths col_widths = self.grid.code_array.col_widths for __col, __tab in cw: col_widths[__col+col, tab] = cw[(__col, __tab)]
Copies the format of the selected cells to the Clipboard Cells are shifted so that the top left bbox corner is at 0,0
def copy_format(self): """Copies the format of the selected cells to the Clipboard Cells are shifted so that the top left bbox corner is at 0,0 """ row, col, tab = self.grid.actions.cursor code_array = self.grid.code_array # Cell attributes new_cell_attributes = [] selection = self.get_selection() if not selection: # Current cell is chosen for selection selection = Selection([], [], [], [], [(row, col)]) # Format content is shifted so that the top left corner is 0,0 ((top, left), (bottom, right)) = \ selection.get_grid_bbox(self.grid.code_array.shape) cell_attributes = code_array.cell_attributes for __selection, table, attrs in cell_attributes: if tab == table: new_selection = selection & __selection if new_selection: new_shifted_selection = new_selection.shifted(-top, -left) if "merge_area" not in attrs: selection_params = new_shifted_selection.parameters cellattribute = selection_params, table, attrs new_cell_attributes.append(cellattribute) # Rows shifted_new_row_heights = {} for row, table in code_array.row_heights: if tab == table and top <= row <= bottom: shifted_new_row_heights[row-top, table] = \ code_array.row_heights[row, table] # Columns shifted_new_col_widths = {} for col, table in code_array.col_widths: if tab == table and left <= col <= right: shifted_new_col_widths[col-left, table] = \ code_array.col_widths[col, table] format_data = { "cell_attributes": new_cell_attributes, "row_heights": shifted_new_row_heights, "col_widths": shifted_new_col_widths, } attr_string = repr(format_data) self.grid.main_window.clipboard.set_clipboard(attr_string)
Return next position of event_find_string in MainGrid Parameters: ----------- gridpos: 3-tuple of Integer \tPosition at which the search starts find_string: String \tString to find in grid flags: List of strings \tSearch flag out of \t["UP" xor "DOWN", "WHOLE_WORD", "MATCH_CASE", "REG_EXP"] search_result: Bool, defaults to True \tIf True then the search includes the result string (slower)
def find(self, gridpos, find_string, flags, search_result=True): """Return next position of event_find_string in MainGrid Parameters: ----------- gridpos: 3-tuple of Integer \tPosition at which the search starts find_string: String \tString to find in grid flags: List of strings \tSearch flag out of \t["UP" xor "DOWN", "WHOLE_WORD", "MATCH_CASE", "REG_EXP"] search_result: Bool, defaults to True \tIf True then the search includes the result string (slower) """ findfunc = self.grid.code_array.findnextmatch if "DOWN" in flags: if gridpos[0] < self.grid.code_array.shape[0]: gridpos[0] += 1 elif gridpos[1] < self.grid.code_array.shape[1]: gridpos[1] += 1 elif gridpos[2] < self.grid.code_array.shape[2]: gridpos[2] += 1 else: gridpos = (0, 0, 0) elif "UP" in flags: if gridpos[0] > 0: gridpos[0] -= 1 elif gridpos[1] > 0: gridpos[1] -= 1 elif gridpos[2] > 0: gridpos[2] -= 1 else: gridpos = [dim - 1 for dim in self.grid.code_array.shape] return findfunc(tuple(gridpos), find_string, flags, search_result)
Return list of all positions of event_find_string in MainGrid. Only the code is searched. The result is not searched here. Parameters: ----------- gridpos: 3-tuple of Integer \tPosition at which the search starts find_string: String \tString to find in grid flags: List of strings \t Search flag out of \t ["UP" xor "DOWN", "WHOLE_WORD", "MATCH_CASE", "REG_EXP"]
def find_all(self, find_string, flags): """Return list of all positions of event_find_string in MainGrid. Only the code is searched. The result is not searched here. Parameters: ----------- gridpos: 3-tuple of Integer \tPosition at which the search starts find_string: String \tString to find in grid flags: List of strings \t Search flag out of \t ["UP" xor "DOWN", "WHOLE_WORD", "MATCH_CASE", "REG_EXP"] """ code_array = self.grid.code_array string_match = code_array.string_match find_keys = [] for key in code_array: if string_match(code_array(key), find_string, flags) is not None: find_keys.append(key) return find_keys
Replaces occurrences of find_string with replace_string at findpos and marks content as changed Parameters ---------- findpositions: List of 3-Tuple of Integer \tPositions in grid that shall be replaced find_string: String \tString to be overwritten in the cell replace_string: String \tString to be used for replacement
def replace_all(self, findpositions, find_string, replace_string): """Replaces occurrences of find_string with replace_string at findpos and marks content as changed Parameters ---------- findpositions: List of 3-Tuple of Integer \tPositions in grid that shall be replaced find_string: String \tString to be overwritten in the cell replace_string: String \tString to be used for replacement """ # Mark content as changed post_command_event(self.main_window, self.ContentChangedMsg) for findpos in findpositions: old_code = self.grid.code_array(findpos) new_code = old_code.replace(find_string, replace_string) self.grid.code_array[findpos] = new_code statustext = _("Replaced {no_cells} cells.") statustext = statustext.format(no_cells=len(findpositions)) post_command_event(self.main_window, self.StatusBarMsg, text=statustext) self.grid.ForceRefresh()
Replaces occurrences of find_string with replace_string at findpos and marks content as changed Parameters ---------- findpos: 3-Tuple of Integer \tPosition in grid that shall be replaced find_string: String \tString to be overwritten in the cell replace_string: String \tString to be used for replacement
def replace(self, findpos, find_string, replace_string): """Replaces occurrences of find_string with replace_string at findpos and marks content as changed Parameters ---------- findpos: 3-Tuple of Integer \tPosition in grid that shall be replaced find_string: String \tString to be overwritten in the cell replace_string: String \tString to be used for replacement """ # Mark content as changed post_command_event(self.main_window, self.ContentChangedMsg) old_code = self.grid.code_array(findpos) new_code = old_code.replace(find_string, replace_string) self.grid.code_array[findpos] = new_code self.grid.actions.cursor = findpos statustext = _("Replaced {old} with {new} in cell {key}.") statustext = statustext.format(old=old_code, new=new_code, key=findpos) post_command_event(self.main_window, self.StatusBarMsg, text=statustext) self.grid.ForceRefresh()
Returns bbox, in which None is replaced by grid boundaries
def _replace_bbox_none(self, bbox): """Returns bbox, in which None is replaced by grid boundaries""" (bb_top, bb_left), (bb_bottom, bb_right) = bbox if bb_top is None: bb_top = 0 if bb_left is None: bb_left = 0 if bb_bottom is None: bb_bottom = self.code_array.shape[0] - 1 if bb_right is None: bb_right = self.code_array.shape[1] - 1 return (bb_top, bb_left), (bb_bottom, bb_right)
Returns OrderedDict of filetypes to wildcards The filetypes that are provided in the filetypes parameter are checked for availability. Only available filetypes are inluded in the return ODict. Parameters ---------- filetypes: Iterable of strings \tFiletype list
def get_filetypes2wildcards(filetypes): """Returns OrderedDict of filetypes to wildcards The filetypes that are provided in the filetypes parameter are checked for availability. Only available filetypes are inluded in the return ODict. Parameters ---------- filetypes: Iterable of strings \tFiletype list """ def is_available(filetype): return filetype not in FILETYPE_AVAILABILITY or \ FILETYPE_AVAILABILITY[filetype] available_filetypes = filter(is_available, filetypes) return OrderedDict((ft, FILETYPE2WILDCARD[ft]) for ft in available_filetypes)
Displays parameter entry dialog and returns parameter dict Parameters ---------- gpg_key_param_list: List of 2-tuples \tContains GPG key generation parameters but not name_real
def get_key_params_from_user(gpg_key_param_list): """Displays parameter entry dialog and returns parameter dict Parameters ---------- gpg_key_param_list: List of 2-tuples \tContains GPG key generation parameters but not name_real """ params = [[_('Real name'), 'name_real']] vals = [""] * len(params) while "" in vals: dlg = GPGParamsDialog(None, -1, "Enter GPG key parameters", params) dlg.CenterOnScreen() for val, textctrl in zip(vals, dlg.textctrls): textctrl.SetValue(val) if dlg.ShowModal() != wx.ID_OK: dlg.Destroy() return vals = [textctrl.Value for textctrl in dlg.textctrls] dlg.Destroy() if "" in vals: msg = _("Please enter a value in each field.") dlg = GMD.GenericMessageDialog(None, msg, _("Missing value"), wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() for (__, key), val in zip(params, vals): gpg_key_param_list.insert(-2, (key, val)) return dict(gpg_key_param_list)
Queries grid dimensions in a model dialog and returns n-tuple Parameters ---------- no_dim: Integer \t Number of grid dimensions, currently must be 3
def get_dimensions_from_user(self, no_dim): """Queries grid dimensions in a model dialog and returns n-tuple Parameters ---------- no_dim: Integer \t Number of grid dimensions, currently must be 3 """ # Grid dimension dialog if no_dim != 3: raise NotImplementedError( _("Currently, only 3D grids are supported.")) dim_dialog = DimensionsEntryDialog(self.main_window) if dim_dialog.ShowModal() != wx.ID_OK: dim_dialog.Destroy() return dim = tuple(dim_dialog.dimensions) dim_dialog.Destroy() return dim
Launches preferences dialog and returns dict with preferences
def get_preferences_from_user(self): """Launches preferences dialog and returns dict with preferences""" dlg = PreferencesDialog(self.main_window) change_choice = dlg.ShowModal() preferences = {} if change_choice == wx.ID_OK: for (parameter, _), ctrl in zip(dlg.parameters, dlg.textctrls): if isinstance(ctrl, wx.Choice): value = ctrl.GetStringSelection() if value: preferences[parameter] = repr(value) else: preferences[parameter] = repr(ctrl.Value) dlg.Destroy() return preferences
Queries user if grid should be saved
def get_save_request_from_user(self): """Queries user if grid should be saved""" msg = _("There are unsaved changes.\nDo you want to save?") dlg = GMD.GenericMessageDialog( self.main_window, msg, _("Unsaved changes"), wx.YES_NO | wx.ICON_QUESTION | wx.CANCEL) save_choice = dlg.ShowModal() dlg.Destroy() if save_choice == wx.ID_YES: return True elif save_choice == wx.ID_NO: return False
Opens a file dialog and returns filepath and filterindex Parameters ---------- wildcard: String \tWildcard string for file dialog message: String \tMessage in the file dialog style: Integer \tDialog style, e. g. wx.OPEN | wx.CHANGE_DIR filterindex: Integer, defaults to 0 \tDefault filterindex that is selected when the dialog is displayed
def get_filepath_findex_from_user(self, wildcard, message, style, filterindex=0): """Opens a file dialog and returns filepath and filterindex Parameters ---------- wildcard: String \tWildcard string for file dialog message: String \tMessage in the file dialog style: Integer \tDialog style, e. g. wx.OPEN | wx.CHANGE_DIR filterindex: Integer, defaults to 0 \tDefault filterindex that is selected when the dialog is displayed """ dlg = wx.FileDialog(self.main_window, wildcard=wildcard, message=message, style=style, defaultDir=os.getcwd(), defaultFile="") # Set the initial filterindex dlg.SetFilterIndex(filterindex) filepath = None filter_index = None if dlg.ShowModal() == wx.ID_OK: filepath = dlg.GetPath() filter_index = dlg.GetFilterIndex() dlg.Destroy() return filepath, filter_index
Displays a warning message
def display_warning(self, message, short_message, style=wx.OK | wx.ICON_WARNING): """Displays a warning message""" dlg = GMD.GenericMessageDialog(self.main_window, message, short_message, style) dlg.ShowModal() dlg.Destroy()
Launches proceeding dialog and returns True if ok to proceed
def get_warning_choice(self, message, short_message, style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_WARNING): """Launches proceeding dialog and returns True if ok to proceed""" dlg = GMD.GenericMessageDialog(self.main_window, message, short_message, style) choice = dlg.ShowModal() dlg.Destroy() return choice == wx.ID_YES
Opens print setup dialog and returns print_data
def get_print_setup(self, print_data): """Opens print setup dialog and returns print_data""" psd = wx.PageSetupDialogData(print_data) # psd.EnablePrinter(False) psd.CalculatePaperSizeFromId() dlg = wx.PageSetupDialog(self.main_window, psd) dlg.ShowModal() # this makes a copy of the wx.PrintData instead of just saving # a reference to the one inside the PrintDialogData that will # be destroyed when the dialog is destroyed data = dlg.GetPageSetupData() new_print_data = wx.PrintData(data.GetPrintData()) new_print_data.PaperId = data.PaperId new_print_data.PaperSize = data.PaperSize dlg.Destroy() return new_print_data
Launches the csv dialog and returns csv_info csv_info is a tuple of dialect, has_header, digest_types Parameters ---------- path: String \tFile path of csv file
def get_csv_import_info(self, path): """Launches the csv dialog and returns csv_info csv_info is a tuple of dialect, has_header, digest_types Parameters ---------- path: String \tFile path of csv file """ csvfilename = os.path.split(path)[1] try: filterdlg = CsvImportDialog(self.main_window, csvfilepath=path) except csv.Error, err: # Display modal warning dialog msg = _("'{filepath}' does not seem to be a valid CSV file.\n \n" "Opening it yielded the error:\n{error}") msg = msg.format(filepath=csvfilename, error=err) short_msg = _('Error reading CSV file') self.display_warning(msg, short_msg) return if filterdlg.ShowModal() == wx.ID_OK: dialect, has_header = filterdlg.csvwidgets.get_dialect() digest_types = filterdlg.grid.dtypes encoding = filterdlg.csvwidgets.encoding else: filterdlg.Destroy() return filterdlg.Destroy() return dialect, has_header, digest_types, encoding
Shows csv export preview dialog and returns csv_info csv_info is a tuple of dialect, has_header, digest_types Parameters ---------- preview_data: Iterable of iterables \tContains csv export data row-wise
def get_csv_export_info(self, preview_data): """Shows csv export preview dialog and returns csv_info csv_info is a tuple of dialect, has_header, digest_types Parameters ---------- preview_data: Iterable of iterables \tContains csv export data row-wise """ preview_rows = 100 preview_cols = 100 export_preview = list(list(islice(col, None, preview_cols)) for col in islice(preview_data, None, preview_rows)) filterdlg = CsvExportDialog(self.main_window, data=export_preview) if filterdlg.ShowModal() == wx.ID_OK: dialect, has_header = filterdlg.csvwidgets.get_dialect() digest_types = [types.StringType] else: filterdlg.Destroy() return filterdlg.Destroy() return dialect, has_header, digest_types
Shows Cairo export dialog and returns info Parameters ---------- filetype: String in ["pdf", "svg"] \tFile type for which export info is gathered
def get_cairo_export_info(self, filetype): """Shows Cairo export dialog and returns info Parameters ---------- filetype: String in ["pdf", "svg"] \tFile type for which export info is gathered """ export_dlg = CairoExportDialog(self.main_window, filetype=filetype) if export_dlg.ShowModal() == wx.ID_OK: info = export_dlg.get_info() export_dlg.Destroy() return info else: export_dlg.Destroy()
Opens an integer entry dialog and returns integer Parameters ---------- title: String \tDialog title cond_func: Function \tIf cond_func of int(<entry_value> then result is returned. \tOtherwise the dialog pops up again.
def get_int_from_user(self, title="Enter integer value", cond_func=lambda i: i is not None): """Opens an integer entry dialog and returns integer Parameters ---------- title: String \tDialog title cond_func: Function \tIf cond_func of int(<entry_value> then result is returned. \tOtherwise the dialog pops up again. """ is_integer = False while not is_integer: dlg = wx.TextEntryDialog(None, title, title) if dlg.ShowModal() == wx.ID_OK: result = dlg.GetValue() else: return None dlg.Destroy() try: integer = int(result) if cond_func(integer): is_integer = True except ValueError: pass return integer
Opens a PasteAsDialog and returns parameters dict
def get_pasteas_parameters_from_user(self, obj): """Opens a PasteAsDialog and returns parameters dict""" dlg = PasteAsDialog(None, -1, obj) dlg_choice = dlg.ShowModal() if dlg_choice != wx.ID_OK: dlg.Destroy() return None parameters = {} parameters.update(dlg.parameters) dlg.Destroy() return parameters
Called to create the control, which must derive from wx.Control. *Must Override*
def Create(self, parent, id, evtHandler): """ Called to create the control, which must derive from wx.Control. *Must Override* """ style = wx.TE_MULTILINE self._tc = wx.TextCtrl(parent, id, "", style=style) # Disable if cell is clocked, enable if cell is not locked grid = self.main_window.grid key = grid.actions.cursor locked = grid.code_array.cell_attributes[key]["locked"] or \ grid.code_array.cell_attributes[key]["button_cell"] self._tc.Enable(not locked) self._tc.Show(not locked) if locked: grid.code_array.result_cache.clear() self._execute_cell_code(key[0], key[1], grid) self._tc.SetInsertionPoint(0) self.SetControl(self._tc) if evtHandler: self._tc.PushEventHandler(evtHandler)
Called to position/size the edit control within the cell rectangle. If you don't fill the cell (the rect) then be sure to override PaintBackground and do something meaningful there.
def SetSize(self, rect): """ Called to position/size the edit control within the cell rectangle. If you don't fill the cell (the rect) then be sure to override PaintBackground and do something meaningful there. """ grid = self.main_window.grid key = grid.actions.cursor drawn_rect = grid.grid_renderer._get_drawn_rect(grid, key, rect) self._tc.SetDimensions(drawn_rect.x, drawn_rect.y, drawn_rect.width+2, drawn_rect.height+2, wx.SIZE_ALLOW_MINUS_ONE) self._tc.Layout()
Show or hide the edit control. You can use the attr (if not None) to set colours or fonts for the control.
def Show(self, show, attr): """ Show or hide the edit control. You can use the attr (if not None) to set colours or fonts for the control. """ super(GridCellEditor, self).Show(show, attr)
Executes cell code
def _execute_cell_code(self, row, col, grid): """Executes cell code""" key = row, col, grid.current_table grid.code_array[key] grid.ForceRefresh()
Fetch the value from the table and prepare the edit control to begin editing. Set the focus to the edit control. *Must Override*
def BeginEdit(self, row, col, grid): """ Fetch the value from the table and prepare the edit control to begin editing. Set the focus to the edit control. *Must Override* """ # Disable if cell is locked, enable if cell is not locked grid = self.main_window.grid key = grid.actions.cursor locked = grid.code_array.cell_attributes[key]["locked"]or \ grid.code_array.cell_attributes[key]["button_cell"] self._tc.Enable(not locked) self._tc.Show(not locked) if locked: grid.code_array.result_cache.clear() self._execute_cell_code(row, col, grid) # Mirror our changes onto the main_window's code bar self._tc.Bind(wx.EVT_CHAR, self.OnChar) self._tc.Bind(wx.EVT_KEY_UP, self.OnKeyUp) # Save cell and grid info self._row = row self._col = [col, ] # List of columns we are occupying self._grid = grid start_value = grid.GetTable().GetValue(*key) try: start_value_list = [start_value[i:i+self.max_char_width] for i in xrange(0, len(start_value), self.max_char_width)] startValue = "\n".join(start_value_list) self.startValue = startValue except TypeError: self.startValue = u"" # Set up the textcontrol to look like this cell (TODO: Does not work) try: self._tc.SetValue(unicode(startValue)) except (TypeError, AttributeError, UnboundLocalError): self._tc.SetValue(u"") self._tc.SetFont(grid.GetCellFont(row, col)) self._tc.SetBackgroundColour(grid.GetCellBackgroundColour(row, col)) self._update_control_length() self._tc.SetInsertionPointEnd() h_scroll_pos = grid.GetScrollPos(wx.SB_HORIZONTAL) v_scroll_pos = grid.GetScrollPos(wx.SB_VERTICAL) self._tc.SetFocus() # GTK Bugfix for jumping grid when focusing the textctrl if grid.GetScrollPos(wx.SB_HORIZONTAL) != h_scroll_pos or \ grid.GetScrollPos(wx.SB_VERTICAL) != v_scroll_pos: wx.ScrolledWindow.Scroll(grid, (h_scroll_pos, v_scroll_pos)) # Select the text self._tc.SetSelection(0, self._tc.GetLastPosition())
End editing the cell. This function must check if the current value of the editing control is valid and different from the original value (available as oldval in its string form.) If it has not changed then simply return None, otherwise return the value in its string form. *Must Override*
def EndEdit(self, row, col, grid, oldVal=None): """ End editing the cell. This function must check if the current value of the editing control is valid and different from the original value (available as oldval in its string form.) If it has not changed then simply return None, otherwise return the value in its string form. *Must Override* """ # Mirror our changes onto the main_window's code bar self._tc.Unbind(wx.EVT_KEY_UP) self.ApplyEdit(row, col, grid) del self._col del self._row del self._grid
This function should save the value of the control into the grid or grid table. It is called only after EndEdit() returns a non-None value. *Must Override*
def ApplyEdit(self, row, col, grid): """ This function should save the value of the control into the grid or grid table. It is called only after EndEdit() returns a non-None value. *Must Override* """ val = self._tc.GetValue() grid.GetTable().SetValue(row, col, val) # update the table self.startValue = '' self._tc.SetValue('')
Reset the value in the control back to its starting value. *Must Override*
def Reset(self): """ Reset the value in the control back to its starting value. *Must Override* """ try: self._tc.SetValue(self.startValue) except TypeError: # Start value was None pass self._tc.SetInsertionPointEnd() # Update the Entry Line post_command_event(self.main_window, self.TableChangedMsg, updated_cell=self.startValue)
Return True to allow the given key to start editing: the base class version only checks that the event has no modifiers. F2 is special and will always start the editor.
def IsAcceptedKey(self, evt): """ Return True to allow the given key to start editing: the base class version only checks that the event has no modifiers. F2 is special and will always start the editor. """ ## We can ask the base class to do it #return super(MyCellEditor, self).IsAcceptedKey(evt) # or do it ourselves accepted = super(GridCellEditor, self).IsAcceptedKey(evt) accepted = accepted and not evt.ControlDown() accepted = accepted and not evt.AltDown() accepted = accepted and (evt.GetKeyCode() != wx.WXK_SHIFT) return accepted
If the editor is enabled by pressing keys on the grid, this will be called to let the editor do something about that first key if desired.
def StartingKey(self, evt): """ If the editor is enabled by pressing keys on the grid, this will be called to let the editor do something about that first key if desired. """ key = evt.GetKeyCode() ch = None if key in [ wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2, wx.WXK_NUMPAD3, wx.WXK_NUMPAD4, wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_NUMPAD7, wx.WXK_NUMPAD8, wx.WXK_NUMPAD9]: ch = ch = chr(ord('0') + key - wx.WXK_NUMPAD0) elif key < 256 and key >= 0 and chr(key) in string.printable: ch = chr(key) if ch is not None and self._tc.IsEnabled(): # For this example, replace the text. Normally we would append it. #self._tc.AppendText(ch) self._tc.SetValue(ch) self._tc.SetInsertionPointEnd() else: evt.Skip()
Returns page information What is the page range available, and what is the selected page range.
def GetPageInfo(self): """Returns page information What is the page range available, and what is the selected page range. """ return self.first_tab, self.last_tab, self.first_tab, self.last_tab
Returns quoted code if not already quoted and if possible Parameters ---------- code: String \tCode thta is quoted
def quote(code): """Returns quoted code if not already quoted and if possible Parameters ---------- code: String \tCode thta is quoted """ try: code = code.rstrip() except AttributeError: # code is not a string, may be None --> There is no code to quote return code if code and code[0] + code[-1] not in ('""', "''", "u'", '"') \ and '"' not in code: return 'u"' + code + '"' else: return code
Sets grid states
def _states(self): """Sets grid states""" # The currently visible table self.current_table = 0 # The cell that has been selected before the latest selection self._last_selected_cell = 0, 0, 0 # If we are viewing cells based on their frozen status or normally # (When true, a cross-hatch is displayed for frozen cells) self._view_frozen = False # Timer for updating frozen cells self.timer_running = False
Initial layout of grid
def _layout(self): """Initial layout of grid""" self.EnableGridLines(False) # Standard row and col sizes for zooming default_cell_attributes = \ self.code_array.cell_attributes.default_cell_attributes self.std_row_size = default_cell_attributes["row-height"] self.std_col_size = default_cell_attributes["column-width"] self.SetDefaultRowSize(self.std_row_size) self.SetDefaultColSize(self.std_col_size) # Standard row and col label sizes for zooming self.col_label_size = self.GetColLabelSize() self.row_label_size = self.GetRowLabelSize() self.SetRowMinimalAcceptableHeight(1) self.SetColMinimalAcceptableWidth(1) self.SetCellHighlightPenWidth(0)
Bind events to handlers
def _bind(self): """Bind events to handlers""" main_window = self.main_window handlers = self.handlers c_handlers = self.cell_handlers # Non wx.Grid events self.Bind(wx.EVT_MOUSEWHEEL, handlers.OnMouseWheel) self.Bind(wx.EVT_KEY_DOWN, handlers.OnKey) # Grid events self.GetGridWindow().Bind(wx.EVT_MOTION, handlers.OnMouseMotion) self.Bind(wx.grid.EVT_GRID_RANGE_SELECT, handlers.OnRangeSelected) # Context menu self.Bind(wx.grid.EVT_GRID_CELL_RIGHT_CLICK, handlers.OnContextMenu) # Cell code events main_window.Bind(self.EVT_CMD_CODE_ENTRY, c_handlers.OnCellText) main_window.Bind(self.EVT_CMD_INSERT_BMP, c_handlers.OnInsertBitmap) main_window.Bind(self.EVT_CMD_LINK_BMP, c_handlers.OnLinkBitmap) main_window.Bind(self.EVT_CMD_VIDEO_CELL, c_handlers.OnLinkVLCVideo) main_window.Bind(self.EVT_CMD_INSERT_CHART, c_handlers.OnInsertChartDialog) # Cell attribute events main_window.Bind(self.EVT_CMD_COPY_FORMAT, c_handlers.OnCopyFormat) main_window.Bind(self.EVT_CMD_PASTE_FORMAT, c_handlers.OnPasteFormat) main_window.Bind(self.EVT_CMD_FONT, c_handlers.OnCellFont) main_window.Bind(self.EVT_CMD_FONTSIZE, c_handlers.OnCellFontSize) main_window.Bind(self.EVT_CMD_FONTBOLD, c_handlers.OnCellFontBold) main_window.Bind(self.EVT_CMD_FONTITALICS, c_handlers.OnCellFontItalics) main_window.Bind(self.EVT_CMD_FONTUNDERLINE, c_handlers.OnCellFontUnderline) main_window.Bind(self.EVT_CMD_FONTSTRIKETHROUGH, c_handlers.OnCellFontStrikethrough) main_window.Bind(self.EVT_CMD_FROZEN, c_handlers.OnCellFrozen) main_window.Bind(self.EVT_CMD_LOCK, c_handlers.OnCellLocked) main_window.Bind(self.EVT_CMD_BUTTON_CELL, c_handlers.OnButtonCell) main_window.Bind(self.EVT_CMD_MARKUP, c_handlers.OnCellMarkup) main_window.Bind(self.EVT_CMD_MERGE, c_handlers.OnMerge) main_window.Bind(self.EVT_CMD_JUSTIFICATION, c_handlers.OnCellJustification) main_window.Bind(self.EVT_CMD_ALIGNMENT, c_handlers.OnCellAlignment) main_window.Bind(self.EVT_CMD_BORDERWIDTH, c_handlers.OnCellBorderWidth) main_window.Bind(self.EVT_CMD_BORDERCOLOR, c_handlers.OnCellBorderColor) main_window.Bind(self.EVT_CMD_BACKGROUNDCOLOR, c_handlers.OnCellBackgroundColor) main_window.Bind(self.EVT_CMD_TEXTCOLOR, c_handlers.OnCellTextColor) main_window.Bind(self.EVT_CMD_ROTATION0, c_handlers.OnTextRotation0) main_window.Bind(self.EVT_CMD_ROTATION90, c_handlers.OnTextRotation90) main_window.Bind(self.EVT_CMD_ROTATION180, c_handlers.OnTextRotation180) main_window.Bind(self.EVT_CMD_ROTATION270, c_handlers.OnTextRotation270) main_window.Bind(self.EVT_CMD_TEXTROTATATION, c_handlers.OnCellTextRotation) # Cell selection events self.Bind(wx.grid.EVT_GRID_CMD_SELECT_CELL, c_handlers.OnCellSelected) # Grid edit mode events main_window.Bind(self.EVT_CMD_ENTER_SELECTION_MODE, handlers.OnEnterSelectionMode) main_window.Bind(self.EVT_CMD_EXIT_SELECTION_MODE, handlers.OnExitSelectionMode) # Grid view events main_window.Bind(self.EVT_CMD_VIEW_FROZEN, handlers.OnViewFrozen) main_window.Bind(self.EVT_CMD_REFRESH_SELECTION, handlers.OnRefreshSelectedCells) main_window.Bind(self.EVT_CMD_TIMER_TOGGLE, handlers.OnTimerToggle) self.Bind(wx.EVT_TIMER, handlers.OnTimer) main_window.Bind(self.EVT_CMD_DISPLAY_GOTO_CELL_DIALOG, handlers.OnDisplayGoToCellDialog) main_window.Bind(self.EVT_CMD_GOTO_CELL, handlers.OnGoToCell) main_window.Bind(self.EVT_CMD_ZOOM_IN, handlers.OnZoomIn) main_window.Bind(self.EVT_CMD_ZOOM_OUT, handlers.OnZoomOut) main_window.Bind(self.EVT_CMD_ZOOM_STANDARD, handlers.OnZoomStandard) main_window.Bind(self.EVT_CMD_ZOOM_FIT, handlers.OnZoomFit) # Find events main_window.Bind(self.EVT_CMD_FIND, handlers.OnFind) main_window.Bind(self.EVT_CMD_REPLACE, handlers.OnShowFindReplace) main_window.Bind(wx.EVT_FIND, handlers.OnReplaceFind) main_window.Bind(wx.EVT_FIND_NEXT, handlers.OnReplaceFind) main_window.Bind(wx.EVT_FIND_REPLACE, handlers.OnReplace) main_window.Bind(wx.EVT_FIND_REPLACE_ALL, handlers.OnReplaceAll) main_window.Bind(wx.EVT_FIND_CLOSE, handlers.OnCloseFindReplace) # Grid change events main_window.Bind(self.EVT_CMD_INSERT_ROWS, handlers.OnInsertRows) main_window.Bind(self.EVT_CMD_INSERT_COLS, handlers.OnInsertCols) main_window.Bind(self.EVT_CMD_INSERT_TABS, handlers.OnInsertTabs) main_window.Bind(self.EVT_CMD_DELETE_ROWS, handlers.OnDeleteRows) main_window.Bind(self.EVT_CMD_DELETE_COLS, handlers.OnDeleteCols) main_window.Bind(self.EVT_CMD_DELETE_TABS, handlers.OnDeleteTabs) main_window.Bind(self.EVT_CMD_SHOW_RESIZE_GRID_DIALOG, handlers.OnResizeGridDialog) main_window.Bind(self.EVT_CMD_QUOTE, handlers.OnQuote) main_window.Bind(wx.grid.EVT_GRID_ROW_SIZE, handlers.OnRowSize) main_window.Bind(wx.grid.EVT_GRID_COL_SIZE, handlers.OnColSize) main_window.Bind(self.EVT_CMD_SORT_ASCENDING, handlers.OnSortAscending) main_window.Bind(self.EVT_CMD_SORT_DESCENDING, handlers.OnSortDescending) # Undo/Redo events main_window.Bind(self.EVT_CMD_UNDO, handlers.OnUndo) main_window.Bind(self.EVT_CMD_REDO, handlers.OnRedo)
True if key in merged area shall be drawn This is the case if it is the top left most visible key of the merge area on the screen.
def is_merged_cell_drawn(self, key): """True if key in merged area shall be drawn This is the case if it is the top left most visible key of the merge area on the screen. """ row, col, tab = key # Is key not merged? --> False cell_attributes = self.code_array.cell_attributes top, left, __ = cell_attributes.get_merging_cell(key) # Case 1: Top left cell of merge is visible # --> Only top left cell returns True top_left_drawn = \ row == top and col == left and \ self.IsVisible(row, col, wholeCellVisible=False) # Case 2: Leftmost column is visible # --> Only top visible leftmost cell returns True left_drawn = \ col == left and \ self.IsVisible(row, col, wholeCellVisible=False) and \ not self.IsVisible(row-1, col, wholeCellVisible=False) # Case 3: Top row is visible # --> Only left visible top cell returns True top_drawn = \ row == top and \ self.IsVisible(row, col, wholeCellVisible=False) and \ not self.IsVisible(row, col-1, wholeCellVisible=False) # Case 4: Top row and leftmost column are invisible # --> Only top left visible cell returns True middle_drawn = \ self.IsVisible(row, col, wholeCellVisible=False) and \ not self.IsVisible(row-1, col, wholeCellVisible=False) and \ not self.IsVisible(row, col-1, wholeCellVisible=False) return top_left_drawn or left_drawn or top_drawn or middle_drawn
Updates the entry line Parameters ---------- key: 3-tuple of Integer, defaults to current cell \tCell to which code the entry line is updated
def update_entry_line(self, key=None): """Updates the entry line Parameters ---------- key: 3-tuple of Integer, defaults to current cell \tCell to which code the entry line is updated """ if key is None: key = self.actions.cursor cell_code = self.GetTable().GetValue(*key) post_command_event(self, self.EntryLineMsg, text=cell_code)
Updates the attribute toolbar Parameters ---------- key: 3-tuple of Integer, defaults to current cell \tCell to which attributes the attributes toolbar is updated
def update_attribute_toolbar(self, key=None): """Updates the attribute toolbar Parameters ---------- key: 3-tuple of Integer, defaults to current cell \tCell to which attributes the attributes toolbar is updated """ if key is None: key = self.actions.cursor post_command_event(self, self.ToolbarUpdateMsg, key=key, attr=self.code_array.cell_attributes[key])
Updates the panel cell attrutes of a panel cell
def _update_video_volume_cell_attributes(self, key): """Updates the panel cell attrutes of a panel cell""" try: video_cell_panel = self.grid_renderer.video_cells[key] except KeyError: return old_video_volume = self.code_array.cell_attributes[key]["video_volume"] new_video_volume = video_cell_panel.volume if old_video_volume == new_video_volume: return selection = Selection([], [], [], [], [key]) self.actions.set_attr("video_volume", new_video_volume, selection)
Refresh hook
def ForceRefresh(self, *args, **kwargs): """Refresh hook""" wx.grid.Grid.ForceRefresh(self, *args, **kwargs) for video_cell_key in self.grid_renderer.video_cells: if video_cell_key[2] == self.current_table: video_cell = self.grid_renderer.video_cells[video_cell_key] rect = self.CellToRect(video_cell_key[0], video_cell_key[1]) drawn_rect = self.grid_renderer._get_drawn_rect(self, video_cell_key, rect) video_cell.SetClientRect(drawn_rect) self._update_video_volume_cell_attributes(video_cell_key)
Text entry event handler
def OnCellText(self, event): """Text entry event handler""" row, col, _ = self.grid.actions.cursor self.grid.GetTable().SetValue(row, col, event.code) event.Skip()
Insert bitmap event handler
def OnInsertBitmap(self, event): """Insert bitmap event handler""" key = self.grid.actions.cursor # Get file name wildcard = _("Bitmap file") + " (*)|*" if rsvg is not None: wildcard += "|" + _("SVG file") + " (*.svg)|*.svg" message = _("Select image for current cell") style = wx.OPEN | wx.CHANGE_DIR filepath, index = \ self.grid.interfaces.get_filepath_findex_from_user(wildcard, message, style) if index == 0: # Bitmap loaded try: img = wx.EmptyImage(1, 1) img.LoadFile(filepath) except TypeError: return if img.GetSize() == (-1, -1): # Bitmap could not be read return code = self.grid.main_window.actions.img2code(key, img) elif index == 1 and rsvg is not None: # SVG loaded with open(filepath) as infile: try: code = infile.read() except IOError: return if is_svg(code): code = 'u"""' + code + '"""' else: # Does not seem to be an svg file return else: code = None if code: self.grid.actions.set_code(key, code)
Link bitmap event handler
def OnLinkBitmap(self, event): """Link bitmap event handler""" # Get file name wildcard = "*" message = _("Select bitmap for current cell") style = wx.OPEN | wx.CHANGE_DIR filepath, __ = \ self.grid.interfaces.get_filepath_findex_from_user(wildcard, message, style) try: bmp = wx.Bitmap(filepath) except TypeError: return if bmp.Size == (-1, -1): # Bitmap could not be read return code = "wx.Bitmap(r'{filepath}')".format(filepath=filepath) key = self.grid.actions.cursor self.grid.actions.set_code(key, code)
VLC video code event handler
def OnLinkVLCVideo(self, event): """VLC video code event handler""" key = self.grid.actions.cursor if event.videofile: try: video_volume = \ self.grid.code_array.cell_attributes[key]["video_volume"] except KeyError: video_volume = None self.grid.actions.set_attr("panel_cell", True) if video_volume is not None: code = 'vlcpanel_factory("{}", {})'.format( event.videofile, video_volume) else: code = 'vlcpanel_factory("{}")'.format(event.videofile) self.grid.actions.set_code(key, code) else: try: video_panel = self.grid.grid_renderer.video_cells.pop(key) video_panel.player.stop() video_panel.player.release() video_panel.Destroy() except KeyError: pass self.grid.actions.set_code(key, u"")
Chart dialog event handler
def OnInsertChartDialog(self, event): """Chart dialog event handler""" key = self.grid.actions.cursor cell_code = self.grid.code_array(key) if cell_code is None: cell_code = u"" chart_dialog = ChartDialog(self.grid.main_window, key, cell_code) if chart_dialog.ShowModal() == wx.ID_OK: code = chart_dialog.get_code() key = self.grid.actions.cursor self.grid.actions.set_code(key, code)
Paste format event handler
def OnPasteFormat(self, event): """Paste format event handler""" with undo.group(_("Paste format")): self.grid.actions.paste_format() self.grid.ForceRefresh() self.grid.update_attribute_toolbar() self.grid.actions.zoom()
Cell font event handler
def OnCellFont(self, event): """Cell font event handler""" with undo.group(_("Font")): self.grid.actions.set_attr("textfont", event.font) self.grid.ForceRefresh() self.grid.update_attribute_toolbar() event.Skip()
Cell font size event handler
def OnCellFontSize(self, event): """Cell font size event handler""" with undo.group(_("Font size")): self.grid.actions.set_attr("pointsize", event.size) self.grid.ForceRefresh() self.grid.update_attribute_toolbar() event.Skip()
Cell font bold event handler
def OnCellFontBold(self, event): """Cell font bold event handler""" with undo.group(_("Bold")): try: try: weight = getattr(wx, event.weight[2:]) except AttributeError: msg = _("Weight {weight} unknown").format( weight=event.weight) raise ValueError(msg) self.grid.actions.set_attr("fontweight", weight) except AttributeError: self.grid.actions.toggle_attr("fontweight") self.grid.ForceRefresh() self.grid.update_attribute_toolbar() event.Skip()
Cell font underline event handler
def OnCellFontUnderline(self, event): """Cell font underline event handler""" with undo.group(_("Underline")): self.grid.actions.toggle_attr("underline") self.grid.ForceRefresh() self.grid.update_attribute_toolbar() event.Skip()
Cell frozen event handler
def OnCellFrozen(self, event): """Cell frozen event handler""" with undo.group(_("Frozen")): self.grid.actions.change_frozen_attr() self.grid.ForceRefresh() self.grid.update_attribute_toolbar() event.Skip()
Button cell event handler
def OnButtonCell(self, event): """Button cell event handler""" # The button text text = event.text with undo.group(_("Button")): self.grid.actions.set_attr("button_cell", text) self.grid.ForceRefresh() self.grid.update_attribute_toolbar() event.Skip()
Merge cells event handler
def OnMerge(self, event): """Merge cells event handler""" with undo.group(_("Merge cells")): self.grid.actions.merge_selected_cells(self.grid.selection) self.grid.ForceRefresh() self.grid.update_attribute_toolbar()
Cell border width event handler
def OnCellBorderWidth(self, event): """Cell border width event handler""" with undo.group(_("Border width")): self.grid.actions.set_border_attr("borderwidth", event.width, event.borders) self.grid.ForceRefresh() self.grid.update_attribute_toolbar() event.Skip()
Cell border color event handler
def OnCellBorderColor(self, event): """Cell border color event handler""" with undo.group(_("Border color")): self.grid.actions.set_border_attr("bordercolor", event.color, event.borders) self.grid.ForceRefresh() self.grid.update_attribute_toolbar() event.Skip()
Cell background color event handler
def OnCellBackgroundColor(self, event): """Cell background color event handler""" with undo.group(_("Background color")): self.grid.actions.set_attr("bgcolor", event.color) self.grid.ForceRefresh() self.grid.update_attribute_toolbar() event.Skip()
Text rotation dialog event handler
def OnTextRotation0(self, event): """Text rotation dialog event handler""" with undo.group(_("Rotation 0°")): self.grid.actions.set_attr("angle", 0) self.grid.ForceRefresh() self.grid.update_attribute_toolbar()
Cell text rotation event handler
def OnCellTextRotation(self, event): """Cell text rotation event handler""" with undo.group(_("Rotation")): self.grid.actions.toggle_attr("angle") self.grid.ForceRefresh() self.grid.update_attribute_toolbar() if is_gtk(): try: wx.Yield() except: pass event.Skip()
Cell selection event handler
def OnCellSelected(self, event): """Cell selection event handler""" key = row, col, tab = event.Row, event.Col, self.grid.current_table # Is the cell merged then go to merging cell cell_attributes = self.grid.code_array.cell_attributes merging_cell = cell_attributes.get_merging_cell(key) if merging_cell is not None and merging_cell != key: post_command_event(self.grid, self.grid.GotoCellMsg, key=merging_cell) # Check if the merging cell is a button cell if cell_attributes[merging_cell]["button_cell"]: # Button cells shall be executed on click self.grid.EnableCellEditControl() return # If in selection mode do nothing # This prevents the current cell from changing if not self.grid.IsEditable(): return # Redraw cursor self.grid.ForceRefresh() # Disable entry line if cell is locked self.grid.lock_entry_line( self.grid.code_array.cell_attributes[key]["locked"]) # Update entry line self.grid.update_entry_line(key) # Update attribute toolbar self.grid.update_attribute_toolbar(key) self.grid._last_selected_cell = key event.Skip()
Mouse motion event handler
def OnMouseMotion(self, event): """Mouse motion event handler""" grid = self.grid pos_x, pos_y = grid.CalcUnscrolledPosition(event.GetPosition()) row = grid.YToRow(pos_y) col = grid.XToCol(pos_x) tab = grid.current_table key = row, col, tab merge_area = self.grid.code_array.cell_attributes[key]["merge_area"] if merge_area is not None: top, left, bottom, right = merge_area row, col = top, left grid.actions.on_mouse_over((row, col, tab)) event.Skip()
Handles non-standard shortcut events
def OnKey(self, event): """Handles non-standard shortcut events""" def switch_to_next_table(): newtable = self.grid.current_table + 1 post_command_event(self.grid, self.GridActionTableSwitchMsg, newtable=newtable) def switch_to_previous_table(): newtable = self.grid.current_table - 1 post_command_event(self.grid, self.GridActionTableSwitchMsg, newtable=newtable) grid = self.grid actions = grid.actions shift, alt, ctrl = 1, 1 << 1, 1 << 2 # Shortcuts key tuple: (modifier, keycode) # Modifier may be e. g. shift | ctrl shortcuts = { # <Esc> pressed (0, 27): lambda: setattr(actions, "need_abort", True), # <Del> pressed (0, 127): actions.delete, # <Home> pressed (0, 313): lambda: actions.set_cursor((grid.GetGridCursorRow(), 0)), # <Ctrl> + R pressed (ctrl, 82): actions.copy_selection_access_string, # <Ctrl> + + pressed (ctrl, 388): actions.zoom_in, # <Ctrl> + - pressed (ctrl, 390): actions.zoom_out, # <Shift> + <Space> pressed (shift, 32): lambda: grid.SelectRow(grid.GetGridCursorRow()), # <Ctrl> + <Space> pressed (ctrl, 32): lambda: grid.SelectCol(grid.GetGridCursorCol()), # <Shift> + <Ctrl> + <Space> pressed (shift | ctrl, 32): grid.SelectAll, } if self.main_window.IsFullScreen(): # <Arrow up> pressed shortcuts[(0, 315)] = switch_to_previous_table # <Arrow down> pressed shortcuts[(0, 317)] = switch_to_next_table # <Space> pressed shortcuts[(0, 32)] = switch_to_next_table keycode = event.GetKeyCode() modifier = shift * event.ShiftDown() | \ alt * event.AltDown() | ctrl * event.ControlDown() if (modifier, keycode) in shortcuts: shortcuts[(modifier, keycode)]() else: event.Skip()
Event handler for grid selection
def OnRangeSelected(self, event): """Event handler for grid selection""" # If grid editing is disabled then pyspread is in selection mode if not self.grid.IsEditable(): selection = self.grid.selection row, col, __ = self.grid.sel_mode_cursor if (row, col) in selection: self.grid.ClearSelection() else: self.grid.SetGridCursor(row, col) post_command_event(self.grid, self.grid.SelectionMsg, selection=selection)
Show cells as frozen status
def OnViewFrozen(self, event): """Show cells as frozen status""" self.grid._view_frozen = not self.grid._view_frozen self.grid.grid_renderer.cell_cache.clear() self.grid.ForceRefresh() event.Skip()
Shift a given cell into view
def OnGoToCell(self, event): """Shift a given cell into view""" row, col, tab = event.key try: self.grid.actions.cursor = row, col, tab except ValueError: msg = _("Cell {key} outside grid shape {shape}").format( key=event.key, shape=self.grid.code_array.shape) post_command_event(self.grid.main_window, self.grid.StatusBarMsg, text=msg) event.Skip() return self.grid.MakeCellVisible(row, col) event.Skip()
Event handler for entering selection mode, disables cell edits
def OnEnterSelectionMode(self, event): """Event handler for entering selection mode, disables cell edits""" self.grid.sel_mode_cursor = list(self.grid.actions.cursor) self.grid.EnableDragGridSize(False) self.grid.EnableEditing(False)
Event handler for leaving selection mode, enables cell edits
def OnExitSelectionMode(self, event): """Event handler for leaving selection mode, enables cell edits""" self.grid.sel_mode_cursor = None self.grid.EnableDragGridSize(True) self.grid.EnableEditing(True)
Event handler for refreshing the selected cells via menu
def OnRefreshSelectedCells(self, event): """Event handler for refreshing the selected cells via menu""" self.grid.actions.refresh_selected_frozen_cells() self.grid.ForceRefresh() event.Skip()
Toggles the timer for updating frozen cells
def OnTimerToggle(self, event): """Toggles the timer for updating frozen cells""" if self.grid.timer_running: # Stop timer self.grid.timer_running = False self.grid.timer.Stop() del self.grid.timer else: # Start timer self.grid.timer_running = True self.grid.timer = wx.Timer(self.grid) self.grid.timer.Start(config["timer_interval"])
Update all frozen cells because of timer call
def OnTimer(self, event): """Update all frozen cells because of timer call""" self.timer_updating = True shape = self.grid.code_array.shape[:2] selection = Selection([(0, 0)], [(shape)], [], [], []) self.grid.actions.refresh_selected_frozen_cells(selection) self.grid.ForceRefresh()
Event handler for resetting grid zoom
def OnZoomStandard(self, event): """Event handler for resetting grid zoom""" self.grid.actions.zoom(zoom=1.0) event.Skip()
Context menu event handler
def OnContextMenu(self, event): """Context menu event handler""" self.grid.PopupMenu(self.grid.contextmenu) event.Skip()
Event handler for mouse wheel actions Invokes zoom when mouse when Ctrl is also pressed
def OnMouseWheel(self, event): """Event handler for mouse wheel actions Invokes zoom when mouse when Ctrl is also pressed """ if event.ControlDown(): if event.WheelRotation > 0: post_command_event(self.grid, self.grid.ZoomInMsg) else: post_command_event(self.grid, self.grid.ZoomOutMsg) elif self.main_window.IsFullScreen(): if event.WheelRotation > 0: newtable = self.grid.current_table - 1 else: newtable = self.grid.current_table + 1 post_command_event(self.grid, self.GridActionTableSwitchMsg, newtable=newtable) return else: wheel_speed = config["mouse_wheel_speed_factor"] x, y = self.grid.GetViewStart() direction = wheel_speed if event.GetWheelRotation() < 0 \ else -wheel_speed if event.ShiftDown(): # Scroll sideways if shift is pressed. self.grid.Scroll(x + direction, y) else: self.grid.Scroll(x, y + direction)
Find functionality, called from toolbar, returns find position
def OnFind(self, event): """Find functionality, called from toolbar, returns find position""" # Search starts in next cell after the current one gridpos = list(self.grid.actions.cursor) text, flags = event.text, event.flags findpos = self.grid.actions.find(gridpos, text, flags) if findpos is None: # If nothing is found mention it in the statusbar and return statustext = _("'{text}' not found.").format(text=text) else: # Otherwise select cell with next occurrence if successful self.grid.actions.cursor = findpos # Update statusbar statustext = _(u"Found '{text}' in cell {key}.") statustext = statustext.format(text=text, key=findpos) post_command_event(self.grid.main_window, self.grid.StatusBarMsg, text=statustext) event.Skip()
Calls the find-replace dialog
def OnShowFindReplace(self, event): """Calls the find-replace dialog""" data = wx.FindReplaceData(wx.FR_DOWN) dlg = wx.FindReplaceDialog(self.grid, data, "Find & Replace", wx.FR_REPLACEDIALOG) dlg.data = data # save a reference to data dlg.Show(True)
Called when a find operation is started from F&R dialog
def OnReplaceFind(self, event): """Called when a find operation is started from F&R dialog""" event.text = event.GetFindString() event.flags = self._wxflag2flag(event.GetFlags()) self.OnFind(event)
Called when a replace operation is started, returns find position
def OnReplace(self, event): """Called when a replace operation is started, returns find position""" find_string = event.GetFindString() flags = self._wxflag2flag(event.GetFlags()) replace_string = event.GetReplaceString() gridpos = list(self.grid.actions.cursor) findpos = self.grid.actions.find(gridpos, find_string, flags, search_result=False) if findpos is None: statustext = _(u"'{find_string}' not found.") statustext = statustext.format(find_string=find_string) else: with undo.group(_("Replace")): self.grid.actions.replace(findpos, find_string, replace_string) self.grid.actions.cursor = findpos # Update statusbar statustext = _(u"Replaced '{find_string}' in cell {key} with " u"{replace_string}.") statustext = statustext.format(find_string=find_string, key=findpos, replace_string=replace_string) post_command_event(self.grid.main_window, self.grid.StatusBarMsg, text=statustext) event.Skip()
Called when a replace all operation is started
def OnReplaceAll(self, event): """Called when a replace all operation is started""" find_string = event.GetFindString() flags = self._wxflag2flag(event.GetFlags()) replace_string = event.GetReplaceString() findpositions = self.grid.actions.find_all(find_string, flags) with undo.group(_("Replace all")): self.grid.actions.replace_all(findpositions, find_string, replace_string) event.Skip()
Returns tuple of number of rows and cols from bbox
def _get_no_rowscols(self, bbox): """Returns tuple of number of rows and cols from bbox""" if bbox is None: return 1, 1 else: (bb_top, bb_left), (bb_bottom, bb_right) = bbox if bb_top is None: bb_top = 0 if bb_left is None: bb_left = 0 if bb_bottom is None: bb_bottom = self.grid.code_array.shape[0] - 1 if bb_right is None: bb_right = self.grid.code_array.shape[1] - 1 return bb_bottom - bb_top + 1, bb_right - bb_left + 1
Insert the maximum of 1 and the number of selected rows
def OnInsertRows(self, event): """Insert the maximum of 1 and the number of selected rows""" bbox = self.grid.selection.get_bbox() if bbox is None or bbox[1][0] is None: # Insert rows at cursor ins_point = self.grid.actions.cursor[0] - 1 no_rows = 1 else: # Insert at lower edge of bounding box ins_point = bbox[0][0] - 1 no_rows = self._get_no_rowscols(bbox)[0] with undo.group(_("Insert rows")): self.grid.actions.insert_rows(ins_point, no_rows) self.grid.GetTable().ResetView() # Update the default sized cell sizes self.grid.actions.zoom() event.Skip()
Inserts the maximum of 1 and the number of selected columns
def OnInsertCols(self, event): """Inserts the maximum of 1 and the number of selected columns""" bbox = self.grid.selection.get_bbox() if bbox is None or bbox[1][1] is None: # Insert rows at cursor ins_point = self.grid.actions.cursor[1] - 1 no_cols = 1 else: # Insert at right edge of bounding box ins_point = bbox[0][1] - 1 no_cols = self._get_no_rowscols(bbox)[1] with undo.group(_("Insert columns")): self.grid.actions.insert_cols(ins_point, no_cols) self.grid.GetTable().ResetView() # Update the default sized cell sizes self.grid.actions.zoom() event.Skip()
Insert one table into grid
def OnInsertTabs(self, event): """Insert one table into grid""" with undo.group(_("Insert table")): self.grid.actions.insert_tabs(self.grid.current_table - 1, 1) self.grid.GetTable().ResetView() self.grid.actions.zoom() event.Skip()
Deletes rows from all tables of the grid
def OnDeleteRows(self, event): """Deletes rows from all tables of the grid""" bbox = self.grid.selection.get_bbox() if bbox is None or bbox[1][0] is None: # Insert rows at cursor del_point = self.grid.actions.cursor[0] no_rows = 1 else: # Insert at lower edge of bounding box del_point = bbox[0][0] no_rows = self._get_no_rowscols(bbox)[0] with undo.group(_("Delete rows")): self.grid.actions.delete_rows(del_point, no_rows) self.grid.GetTable().ResetView() # Update the default sized cell sizes self.grid.actions.zoom() event.Skip()
Deletes columns from all tables of the grid
def OnDeleteCols(self, event): """Deletes columns from all tables of the grid""" bbox = self.grid.selection.get_bbox() if bbox is None or bbox[1][1] is None: # Insert rows at cursor del_point = self.grid.actions.cursor[1] no_cols = 1 else: # Insert at right edge of bounding box del_point = bbox[0][1] no_cols = self._get_no_rowscols(bbox)[1] with undo.group(_("Delete columns")): self.grid.actions.delete_cols(del_point, no_cols) self.grid.GetTable().ResetView() # Update the default sized cell sizes self.grid.actions.zoom() event.Skip()
Deletes tables
def OnDeleteTabs(self, event): """Deletes tables""" with undo.group(_("Delete table")): self.grid.actions.delete_tabs(self.grid.current_table, 1) self.grid.GetTable().ResetView() self.grid.actions.zoom() event.Skip()
Resizes current grid by appending/deleting rows, cols and tables
def OnResizeGridDialog(self, event): """Resizes current grid by appending/deleting rows, cols and tables""" # Get grid dimensions new_shape = self.interfaces.get_dimensions_from_user(no_dim=3) if new_shape is None: return with undo.group(_("Resize grid")): self.grid.actions.change_grid_shape(new_shape) statustext = _("Grid dimensions changed to {shape}.") statustext = statustext.format(shape=new_shape) post_command_event(self.grid.main_window, self.grid.StatusBarMsg, text=statustext) event.Skip()
Quotes selection or if none the current cell
def OnQuote(self, event): """Quotes selection or if none the current cell""" grid = self.grid grid.DisableCellEditControl() with undo.group(_("Quote cell(s)")): # Is a selection present? if self.grid.IsSelection(): # Enclose all selected cells self.grid.actions.quote_selection() # Update grid self.grid.ForceRefresh() else: row = self.grid.GetGridCursorRow() col = self.grid.GetGridCursorCol() key = row, col, grid.current_table self.grid.actions.quote_code(key) grid.MoveCursorDown(False)
Row size event handler
def OnRowSize(self, event): """Row size event handler""" row = event.GetRowOrCol() tab = self.grid.current_table rowsize = self.grid.GetRowSize(row) / self.grid.grid_renderer.zoom # Detect for resizing group of rows rows = self.grid.GetSelectedRows() if len(rows) == 0: rows = [row, ] # Detect for selection of rows spanning all columns selection = self.grid.selection num_cols = self.grid.code_array.shape[1]-1 for box in zip(selection.block_tl, selection.block_br): leftmost_col = box[0][1] rightmost_col = box[1][1] if leftmost_col == 0 and rightmost_col == num_cols: rows += range(box[0][0], box[1][0]+1) # All row resizing is undone in one click with undo.group(_("Resize Rows")): for row in rows: self.grid.code_array.set_row_height(row, tab, rowsize) zoomed_rowsize = rowsize * self.grid.grid_renderer.zoom self.grid.SetRowSize(row, zoomed_rowsize) # Mark content as changed post_command_event(self.grid.main_window, self.grid.ContentChangedMsg) event.Skip() self.grid.ForceRefresh()
Column size event handler
def OnColSize(self, event): """Column size event handler""" col = event.GetRowOrCol() tab = self.grid.current_table colsize = self.grid.GetColSize(col) / self.grid.grid_renderer.zoom # Detect for resizing group of cols cols = self.grid.GetSelectedCols() if len(cols) == 0: cols = [col, ] # Detect for selection of rows spanning all columns selection = self.grid.selection num_rows = self.grid.code_array.shape[0]-1 for box in zip(selection.block_tl, selection.block_br): top_row = box[0][0] bottom_row = box[1][0] if top_row == 0 and bottom_row == num_rows: cols += range(box[0][1], box[1][1]+1) # All column resizing is undone in one click with undo.group(_("Resize Columns")): for col in cols: self.grid.code_array.set_col_width(col, tab, colsize) zoomed_colsize = colsize * self.grid.grid_renderer.zoom self.grid.SetColSize(col, zoomed_colsize) # Mark content as changed post_command_event(self.grid.main_window, self.grid.ContentChangedMsg) event.Skip() self.grid.ForceRefresh()
Sort ascending event handler
def OnSortAscending(self, event): """Sort ascending event handler""" try: with undo.group(_("Sort ascending")): self.grid.actions.sort_ascending(self.grid.actions.cursor) statustext = _(u"Sorting complete.") except Exception, err: statustext = _(u"Sorting failed: {}").format(err) post_command_event(self.grid.main_window, self.grid.StatusBarMsg, text=statustext)
Calls the grid undo method
def OnUndo(self, event): """Calls the grid undo method""" statustext = undo.stack().undotext() undo.stack().undo() # Update content changed state try: post_command_event(self.grid.main_window, self.grid.ContentChangedMsg) except TypeError: # The main window does not exist any more pass self.grid.code_array.result_cache.clear() post_command_event(self.grid.main_window, self.grid.TableChangedMsg, updated_cell=True) # Reset row heights and column widths by zooming self.grid.actions.zoom() # Change grid table dimensions self.grid.GetTable().ResetView() # Update TableChoiceIntCtrl shape = self.grid.code_array.shape post_command_event(self.main_window, self.grid.ResizeGridMsg, shape=shape) # Update toolbars self.grid.update_entry_line() self.grid.update_attribute_toolbar() post_command_event(self.grid.main_window, self.grid.StatusBarMsg, text=statustext)
Adjusts row heights and column widths to match the template Parameters ---------- target_tab: Integer \tTable to be adjusted template_tab: Integer, defaults to 0 \tTemplate table
def rowcol_from_template(target_tab, template_tab=0): """Adjusts row heights and column widths to match the template Parameters ---------- target_tab: Integer \tTable to be adjusted template_tab: Integer, defaults to 0 \tTemplate table """ for row, tab in S.row_heights.keys(): # Delete all row heights in target table if tab == target_tab: S.row_heights.pop((row, tab)) if tab == template_tab: S.row_heights[(row, target_tab)] = \ S.row_heights[(row, tab)] for col, tab in S.col_widths.keys(): # Delete all column widths in target table if tab == target_tab: S.col_widths.pop((col, tab)) if tab == template_tab: S.col_widths[(col, target_tab)] = \ S.col_widths[(col, tab)] return "Table {tab} adjusted.".format(tab=target_tab)
Adjusts cell paarmeters to match the template Parameters ---------- target_tab: Integer \tTable to be adjusted template_tab: Integer, defaults to 0 \tTemplate table
def cell_attributes_from_template(target_tab, template_tab=0): """Adjusts cell paarmeters to match the template Parameters ---------- target_tab: Integer \tTable to be adjusted template_tab: Integer, defaults to 0 \tTemplate table """ new_cell_attributes = [] for attr in S.cell_attributes: if attr[1] == template_tab: new_attr = (attr[0], target_tab, attr[2]) new_cell_attributes.append(new_attr) S.cell_attributes.extend(new_cell_attributes) return "Table {tab} adjusted.".format(tab=target_tab)
Returns wx.Font from fontdata string
def get_font_from_data(fontdata): """Returns wx.Font from fontdata string""" textfont = get_default_font() if fontdata != "": nativefontinfo = wx.NativeFontInfo() nativefontinfo.FromString(fontdata) # OS X does not like a PointSize of 0 # Therefore, it is explicitly set to the system default font point size if not nativefontinfo.GetPointSize(): nativefontinfo.SetPointSize(get_default_font().GetPointSize()) textfont.SetNativeFontInfo(nativefontinfo) return textfont