Example #1
0
    def set_cursor(self, value):
        """Changes the grid cursor cell.

        Parameters
        ----------

        value: 2-tuple or 3-tuple of String
        \trow, col, tab or row, col for target cursor position

        """

        if len(value) == 3:
            self.grid._last_selected_cell = row, col, tab = value

            if tab != self.cursor[2]:
                post_command_event(self.main_window,
                                   self.GridActionTableSwitchMsg, newtable=tab)
                if is_gtk():
                    wx.Yield()
        else:
            row, col = value
            self.grid._last_selected_cell = row, col, self.grid.current_table

        if not (row is None and col is None):
            self.grid.MakeCellVisible(row, col)
            self.grid.SetGridCursor(row, col)
Example #2
0
    def progress_status(self):
        """Displays progress in statusbar"""

        if self.line % self.freq == 0:
            text = self.statustext.format(nele=self.line,
                                          totalele=self.total_lines)

            if self.main_window.grid.actions.pasting:
                try:
                    post_command_event(self.main_window,
                                       self.main_window.StatusBarMsg,
                                       text=text)
                except TypeError:
                    # The main window does not exist any more
                    pass
            else:
                # Write directly to the status bar because the event queue
                # is not emptied during file access

                self.main_window.GetStatusBar().SetStatusText(text)

            # Now wait for the statusbar update to be written on screen
            if is_gtk():
                wx.Yield()

        self.line += 1
Example #3
0
    def progress_status(self):
        """Displays progress in statusbar"""

        if self.line % self.freq == 0:
            text = self.statustext.format(nele=self.line,
                                          totalele=self.total_lines)

            if self.main_window.grid.actions.pasting:
                try:
                    post_command_event(self.main_window,
                                       self.main_window.StatusBarMsg,
                                       text=text)
                except TypeError:
                    # The main window does not exist any more
                    pass
            else:
                # Write directly to the status bar because the event queue
                # is not emptied during file access

                self.main_window.GetStatusBar().SetStatusText(text)

            # Now wait for the statusbar update to be written on screen
            if is_gtk():
                try:
                    wx.Yield()
                except:
                    pass

        self.line += 1
    def set_cursor(self, value):
        """Changes the grid cursor cell.

        Parameters
        ----------

        value: 2-tuple or 3-tuple of String
        \trow, col, tab or row, col for target cursor position

        """

        if len(value) == 3:
            self.grid._last_selected_cell = row, col, tab = value

            if tab != self.cursor[2]:
                post_command_event(self.main_window,
                                   self.GridActionTableSwitchMsg,
                                   newtable=tab)
                if is_gtk():
                    wx.Yield()
        else:
            row, col = value
            self.grid._last_selected_cell = row, col, self.grid.current_table

        if not (row is None and col is None):
            self.grid.MakeCellVisible(row, col)
            self.grid.SetGridCursor(row, col)
Example #5
0
    def __init__(self, parent, main_window, *args, **kwargs):
        wx.Panel.__init__(self, parent, *args, **kwargs)

        try:
            self.SetBackgroundColour(get_color(wx.SYS_COLOUR_FRAMEBK))
        except AttributeError:
            # Does not work on wx 2.x
            pass
        self.parent = parent
        self.main_window = main_window

        style = wx.TE_PROCESS_ENTER | wx.TE_MULTILINE
        self.entry_line = EntryLine(self, main_window, style=style)
        self.selection_toggle_button = \
            wx.ToggleButton(self, -1, size=(24, -1), label=u"\u25F0")

        tooltip = wx.ToolTip(_("Toggles link insertion mode."))
        self.selection_toggle_button.SetToolTip(tooltip)
        self.selection_toggle_button.Bind(wx.EVT_TOGGLEBUTTON, self.OnToggle)

        if not is_gtk():
            # TODO: Selections still do not work right on Windows
            self.selection_toggle_button.Disable()

        self.__do_layout()
Example #6
0
    def __init__(self, parent, main_window, *args, **kwargs):
        wx.Panel.__init__(self, parent, *args, **kwargs)

        try:
            self.SetBackgroundColour(get_color(wx.SYS_COLOUR_FRAMEBK))
        except AttributeError:
            # Does not work on wx 2.x
            pass
        self.parent = parent
        self.main_window = main_window

        style = wx.TE_PROCESS_ENTER | wx.TE_MULTILINE
        self.entry_line = EntryLine(self, main_window, style=style)
        self.selection_toggle_button = \
            wx.ToggleButton(self, -1, size=(24, -1), label=u"\u25F0")

        tooltip = wx.ToolTip(_("Toggles link insertion mode."))
        self.selection_toggle_button.SetToolTip(tooltip)
        self.selection_toggle_button.Bind(wx.EVT_TOGGLEBUTTON, self.OnToggle)

        if not is_gtk():
            # TODO: Selections still do not work right on Windows
            self.selection_toggle_button.Disable()

        self.__do_layout()
Example #7
0
    def OnGridSelection(self, event):
        """Event handler for grid selection in selection mode adds text"""

        current_table = copy(self.main_window.grid.current_table)

        post_command_event(self,
                           self.GridActionTableSwitchMsg,
                           newtable=self.last_table)
        if is_gtk():
            try:
                wx.Yield()
            except:
                pass

        sel_start, sel_stop = self.last_selection

        shape = self.main_window.grid.code_array.shape
        selection_string = event.selection.get_access_string(
            shape, current_table)

        self.Replace(sel_start, sel_stop, selection_string)
        self.last_selection = sel_start, sel_start + len(selection_string)

        post_command_event(self,
                           self.GridActionTableSwitchMsg,
                           newtable=current_table)
Example #8
0
    def OnOpen(self, event):
        """File open event handler"""

        # If changes have taken place save of old grid

        if self.main_window.changed_since_save:
            save_choice = self.interfaces.get_save_request_from_user()

            if save_choice is None:
                # Cancelled close operation
                return

            elif save_choice:
                # User wants to save content
                post_command_event(self.main_window, self.main_window.SaveMsg)

        # Get filepath from user

        wildcard = \
            _("Pyspread file") + " (*.pys)|*.pys|" + \
            _("All files") + " (*.*)|*.*"
        message = _("Choose pyspread file to open.")
        style = wx.OPEN | wx.CHANGE_DIR
        filepath, filterindex = \
            self.interfaces.get_filepath_findex_from_user(wildcard, message,
                                                          style)

        if filepath is None:
            return

        # Change the main window filepath state

        self.main_window.filepath = filepath

        # Load file into grid
        post_command_event(self.main_window,
                           self.main_window.GridActionOpenMsg,
                           attr={"filepath": filepath})

        # Set Window title to new filepath

        title_text = filepath.split("/")[-1] + " - pyspread"
        post_command_event(self.main_window,
                           self.main_window.TitleMsg, text=title_text)

        self.main_window.grid.ForceRefresh()

        if is_gtk():
            wx.Yield()

        # Mark content as unchanged
        try:
            post_command_event(self.main_window, self.ContentChangedMsg,
                               changed=False)
        except TypeError:
            # The main window does not exist any more
            pass
Example #9
0
    def _is_aborted(self, cycle, statustext, total_elements=None, freq=None):
        """Displays progress and returns True if abort

        Parameters
        ----------

        cycle: Integer
        \tThe current operation cycle
        statustext: String
        \tLeft text in statusbar to be displayed
        total_elements: Integer:
        \tThe number of elements that have to be processed
        freq: Integer, defaults to None
        \tNo. operations between two abort possibilities, 1000 if None

        """

        if total_elements is None:
            statustext += _("{nele} elements processed. Press <Esc> to abort.")
        else:
            statustext += _("{nele} of {totalele} elements processed. "
                            "Press <Esc> to abort.")

        if freq is None:
            show_msg = False
            freq = 1000
        else:
            show_msg = True

        # Show progress in statusbar each freq (1000) cells
        if cycle % freq == 0:
            if show_msg:
                text = statustext.format(nele=cycle, totalele=total_elements)
                try:
                    post_command_event(self.main_window, self.StatusBarMsg,
                                       text=text)
                except TypeError:
                    # The main window does not exist any more
                    pass

            # Now wait for the statusbar update to be written on screen
            if is_gtk():
                try:
                    wx.Yield()
                except:
                    pass

            # Abort if we have to
            if self.need_abort:
                # We have to abort`
                return True

        # Continue
        return False
Example #10
0
    def _is_aborted(self, cycle, statustext, total_elements=None, freq=None):
        """Displays progress and returns True if abort

        Parameters
        ----------

        cycle: Integer
        \tThe current operation cycle
        statustext: String
        \tLeft text in statusbar to be displayed
        total_elements: Integer:
        \tThe number of elements that have to be processed
        freq: Integer, defaults to None
        \tNo. operations between two abort possibilities, 1000 if None

        """

        if total_elements is None:
            statustext += _("{nele} elements processed. Press <Esc> to abort.")
        else:
            statustext += _("{nele} of {totalele} elements processed. "
                            "Press <Esc> to abort.")

        if freq is None:
            show_msg = False
            freq = 1000
        else:
            show_msg = True

        # Show progress in statusbar each freq (1000) cells
        if cycle % freq == 0:
            if show_msg:
                text = statustext.format(nele=cycle, totalele=total_elements)
                try:
                    post_command_event(self.main_window,
                                       self.StatusBarMsg,
                                       text=text)
                except TypeError:
                    # The main window does not exist any more
                    pass

            # Now wait for the statusbar update to be written on screen
            if is_gtk():
                wx.Yield()

            # Abort if we have to
            if self.need_abort:
                # We have to abort`
                return True

        # Continue
        return False
Example #11
0
    def OnCellTextRotation(self, event):
        """Cell text rotation event handler"""

        self.grid.actions.set_attr("angle", event.angle, mark_unredo=True)

        self.grid.ForceRefresh()

        self.grid.update_attribute_toolbar()

        if is_gtk():
            wx.Yield()

        event.Skip()
Example #12
0
    def OnCellTextRotation(self, event):
        """Cell text rotation event handler"""

        self.grid.actions.set_attr("angle", event.angle, mark_unredo=True)

        self.grid.ForceRefresh()

        self.grid.update_attribute_toolbar()

        if is_gtk():
            wx.Yield()

        event.Skip()
Example #13
0
    def OnInt(self, event):
        """IntCtrl event method that updates the current table"""

        self.SetMax(self.no_tabs - 1)
        if event.GetValue() > self.GetMax():
            self.SetValue(self.GetMax())
            return

        if not self.switching:
            self.switching = True
            post_command_event(self, self.GridActionTableSwitchMsg, newtable=event.GetValue())
            if is_gtk():
                wx.Yield()
            self.switching = False
Example #14
0
    def OnCellTextRotation(self, event):
        """Cell text rotation event handler"""

        self.grid.actions.toggle_attr("angle")

        self.grid.ForceRefresh()

        self.grid.update_attribute_toolbar()

        if is_gtk():
            try:
                wx.Yield()
            except:
                pass

        event.Skip()
Example #15
0
    def OnInt(self, event):
        """IntCtrl event method that updates the current table"""

        self.SetMax(self.no_tabs - 1)
        if event.GetValue() > self.GetMax():
            self.SetValue(self.GetMax())
            return

        if not self.switching:
            self.switching = True
            post_command_event(self,
                               self.GridActionTableSwitchMsg,
                               newtable=event.GetValue())
            if is_gtk():
                wx.Yield()
            self.switching = False
Example #16
0
    def OnCellTextRotation(self, event):
        """Cell text rotation event handler"""

        self.grid.actions.toggle_attr("angle")

        self.grid.ForceRefresh()

        self.grid.update_attribute_toolbar()

        if is_gtk():
            try:
                wx.Yield()
            except:
                pass

        event.Skip()
Example #17
0
    def OnGridSelection(self, event):
        """Event handler for grid selection in selection mode adds text"""

        current_table = copy(self.main_window.grid.current_table)

        post_command_event(self, self.GridActionTableSwitchMsg, newtable=self.last_table)
        if is_gtk():
            wx.Yield()
        sel_start, sel_stop = self.last_selection

        shape = self.main_window.grid.code_array.shape
        selection_string = event.selection.get_access_string(shape, current_table)

        self.Replace(sel_start, sel_stop, selection_string)
        self.last_selection = sel_start, sel_start + len(selection_string)

        post_command_event(self, self.GridActionTableSwitchMsg, newtable=current_table)
Example #18
0
    def OnFontDialog(self, event):
        """Event handler for launching font dialog"""

        # Get current font data from current cell
        cursor = self.main_window.grid.actions.cursor
        attr = self.main_window.grid.code_array.cell_attributes[cursor]

        size, style, weight, font = \
            [attr[name] for name in ["pointsize", "fontstyle", "fontweight",
                                     "textfont"]]
        current_font = wx.Font(int(size), -1, style, weight, 0, font)

        # Get Font from dialog

        fontdata = wx.FontData()
        fontdata.EnableEffects(True)
        fontdata.SetInitialFont(current_font)

        dlg = wx.FontDialog(self.main_window, fontdata)

        if dlg.ShowModal() == wx.ID_OK:
            fontdata = dlg.GetFontData()
            font = fontdata.GetChosenFont()

            post_command_event(self.main_window,
                               self.main_window.FontMsg,
                               font=font.FaceName)
            post_command_event(self.main_window,
                               self.main_window.FontSizeMsg,
                               size=font.GetPointSize())

            post_command_event(self.main_window,
                               self.main_window.FontBoldMsg,
                               weight=font.GetWeightString())
            post_command_event(self.main_window,
                               self.main_window.FontItalicsMsg,
                               style=font.GetStyleString())

            if is_gtk():
                try:
                    wx.Yield()
                except:
                    pass

            self.main_window.grid.update_attribute_toolbar()
Example #19
0
    def __init__(self, parent, main_window, *args, **kwargs):
        wx.Panel.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.main_window = main_window

        style = wx.TE_PROCESS_ENTER | wx.TE_MULTILINE
        self.entry_line = EntryLine(self, main_window, style=style)
        self.selection_toggle_button = wx.ToggleButton(self, -1, size=(24, -1), label=u"\u25F0")

        tooltip = wx.ToolTip(_("Toggles link insertion mode."))
        self.selection_toggle_button.SetToolTip(tooltip)
        self.selection_toggle_button.Bind(wx.EVT_TOGGLEBUTTON, self.OnToggle)

        if not is_gtk():
            # TODO: Selections still do not work right on Windows
            self.selection_toggle_button.Disable()

        self.__do_layout()
Example #20
0
    def progress_status(self):
        """Displays progress in statusbar"""

        if self.line % self.freq == 0:
            text = self.statustext.format(nele=self.line,
                                          totalele=self.total_lines)
            try:
                post_command_event(self.main_window,
                                   self.main_window.StatusBarMsg, text=text)
            except TypeError:
                # The main window does not exist any more
                pass

            # Now wait for the statusbar update to be written on screen
            if is_gtk():
                wx.Yield()

        self.line += 1
Example #21
0
    def __init__(self, parent, main_window, *args, **kwargs):
        wx.Panel.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.main_window = main_window

        style = wx.TE_PROCESS_ENTER | wx.TE_MULTILINE
        self.entry_line = EntryLine(self, main_window, style=style)
        self.selection_toggle_button = \
            wx.ToggleButton(self, -1, size=(24, -1), label=u"\u25F0")

        tooltip = wx.ToolTip(_("Toggles link insertion mode."))
        self.selection_toggle_button.SetToolTip(tooltip)
        self.selection_toggle_button.Bind(wx.EVT_TOGGLEBUTTON, self.OnToggle)

        if not is_gtk():
            # TODO: Selections still do not work right on Windows
            self.selection_toggle_button.Disable()

        self.__do_layout()
Example #22
0
    def OnFontDialog(self, event):
        """Event handler for launching font dialog"""

        # Get current font data from current cell
        cursor = self.main_window.grid.actions.cursor
        attr = self.main_window.grid.code_array.cell_attributes[cursor]

        size, style, weight, font = \
            [attr[name] for name in ["pointsize", "fontstyle", "fontweight",
                                     "textfont"]]
        current_font = wx.Font(int(size), -1, style, weight, 0, font)

        # Get Font from dialog

        fontdata = wx.FontData()
        fontdata.EnableEffects(True)
        fontdata.SetInitialFont(current_font)

        dlg = wx.FontDialog(self.main_window, fontdata)

        if dlg.ShowModal() == wx.ID_OK:
            fontdata = dlg.GetFontData()
            font = fontdata.GetChosenFont()

            post_command_event(self.main_window, self.main_window.FontMsg,
                               font=font.FaceName)
            post_command_event(self.main_window, self.main_window.FontSizeMsg,
                               size=font.GetPointSize())

            post_command_event(self.main_window, self.main_window.FontBoldMsg,
                               weight=font.GetWeightString())
            post_command_event(self.main_window,
                               self.main_window.FontItalicsMsg,
                               style=font.GetStyleString())

            if is_gtk():
                try:
                    wx.Yield()
                except:
                    pass

            self.main_window.grid.update_attribute_toolbar()
Example #23
0
    def set_cursor(self, value):
        """Changes the grid cursor cell.

        Parameters
        ----------

        value: 2-tuple or 3-tuple of String
        \trow, col, tab or row, col for target cursor position

        """

        shape = self.grid.code_array.shape

        if len(value) == 3:
            self.grid._last_selected_cell = row, col, tab = value
            if row < 0 or col < 0 or tab < 0 or \
               row >= shape[0] or col >= shape[1] or tab >= shape[2]:
                raise ValueError("Cell {value} outside of {shape}".format(
                                 value=value, shape=shape))

            if tab != self.cursor[2]:
                post_command_event(self.main_window,
                                   self.GridActionTableSwitchMsg, newtable=tab)
                if is_gtk():
                    try:
                        wx.Yield()
                    except:
                        pass
        else:
            row, col = value
            if row < 0 or col < 0 or row >= shape[0] or col >= shape[1]:
                raise ValueError("Cell {value} outside of {shape}".format(
                                 value=value, shape=shape))

            self.grid._last_selected_cell = row, col, self.grid.current_table

        if not (row is None and col is None):
            self.grid.MakeCellVisible(row, col)
            self.grid.SetGridCursor(row, col)
Example #24
0
    def OnDrawItem(self, dc, rect, item, flags):

        if item == wx.NOT_FOUND:
            return

        __rect = wx.Rect(*rect)  # make a copy
        __rect.Deflate(3, 5)

        font_string = self.GetString(item)

        font = get_default_font()
        font.SetFaceName(font_string)
        if not is_gtk():
            # Do not display fonts in font coice box for Windows
            font.SetFamily(wx.FONTFAMILY_SWISS)
        dc.SetFont(font)

        text_width, text_height = dc.GetTextExtent(font_string)
        text_x = __rect.x
        text_y = __rect.y + int((__rect.height - text_height) / 2.0)

        # Draw the example text in the combobox
        dc.DrawText(font_string, text_x, text_y)
Example #25
0
    def OnOpen(self, event):
        """File open event handler"""

        # If changes have taken place save of old grid

        if self.main_window.changed_since_save:
            save_choice = self.interfaces.get_save_request_from_user()

            if save_choice is None:
                # Cancelled close operation
                return

            elif save_choice:
                # User wants to save content
                post_command_event(self.main_window, self.main_window.SaveMsg)

        # Get filepath from user

        try:
            import xlrd
            wildcard = \
                _("Pyspread file") + " (*.pys)|*.pys|" + \
                _("Excel file") + " (*.xls)|*.xls|" + \
                _("All files") + " (*.*)|*.*"

        except ImportError:
            wildcard = \
                _("Pyspread file") + " (*.pys)|*.pys|" + \
                _("All files") + " (*.*)|*.*"
            xlrd = None

        message = _("Choose file to open.")
        style = wx.OPEN
        filepath, filterindex = \
            self.interfaces.get_filepath_findex_from_user(wildcard, message,
                                                          style)

        if filepath is None:
            return

        filetype = "pys" if xlrd is None or filterindex != 1 else "xls"

        # Change the main window filepath state

        self.main_window.filepath = filepath

        # Load file into grid
        post_command_event(self.main_window,
                           self.main_window.GridActionOpenMsg,
                           attr={"filepath": filepath, "filetype": filetype})

        # Set Window title to new filepath

        title_text = filepath.split("/")[-1] + " - pyspread"
        post_command_event(self.main_window,
                           self.main_window.TitleMsg, text=title_text)

        self.main_window.grid.ForceRefresh()

        if is_gtk():
            wx.Yield()

        # Mark content as unchanged
        try:
            post_command_event(self.main_window, self.ContentChangedMsg,
                               changed=False)
        except TypeError:
            # The main window does not exist any more
            pass
Example #26
0
    def OnNew(self, event):
        """New grid event handler"""

        # If changes have taken place save of old grid

        if self.main_window.changed_since_save:
            save_choice = self.interfaces.get_save_request_from_user()

            if save_choice is None:
                # Cancelled close operation
                return

            elif save_choice:
                # User wants to save content
                post_command_event(self.main_window, self.main_window.SaveMsg)

        # Get grid dimensions

        shape = self.interfaces.get_dimensions_from_user(no_dim=3)

        if shape is None:
            return

        # Set new filepath and post it to the title bar

        self.main_window.filepath = None
        post_command_event(self.main_window, self.main_window.TitleMsg,
                           text="pyspread")

        # Clear globals
        self.main_window.grid.actions.clear_globals_reload_modules()

        # Create new grid
        post_command_event(self.main_window, self.main_window.GridActionNewMsg,
                           shape=shape)

        # Update TableChoiceIntCtrl
        post_command_event(self.main_window, self.main_window.ResizeGridMsg,
                           shape=shape)

        if is_gtk():
            wx.Yield()

        self.main_window.grid.actions.change_grid_shape(shape)

        self.main_window.grid.GetTable().ResetView()
        self.main_window.grid.ForceRefresh()

        # Display grid creation in status bar
        msg = _("New grid with dimensions {dim} created.").format(dim=shape)
        post_command_event(self.main_window, self.main_window.StatusBarMsg,
                           text=msg)

        self.main_window.grid.ForceRefresh()

        if is_gtk():
            wx.Yield()

        # Mark content as unchanged
        try:
            post_command_event(self.main_window, self.ContentChangedMsg,
                               changed=False)
        except TypeError:
            # The main window does not exist any more
            pass
Example #27
0
    def OnOpen(self, event):
        """File open event handler"""

        # If changes have taken place save of old grid

        if self.main_window.changed_since_save:
            save_choice = self.interfaces.get_save_request_from_user()

            if save_choice is None:
                # Cancelled close operation
                return

            elif save_choice:
                # User wants to save content
                post_command_event(self.main_window, self.main_window.SaveMsg)

        # Get filepath from user
        f2w = get_filetypes2wildcards(
            ["pys", "pysu", "xls", "xlsx", "ods", "all"])
        filetypes = f2w.keys()
        wildcards = f2w.values()
        wildcard = "|".join(wildcards)

        message = _("Choose file to open.")
        style = wx.OPEN

        default_filetype = config["default_open_filetype"]
        try:
            default_filterindex = filetypes.index(default_filetype)
        except ValueError:
            # Be graceful if the user has entered an unkown filetype
            default_filterindex = 0

        get_fp_fidx = self.interfaces.get_filepath_findex_from_user
        filepath, filterindex = get_fp_fidx(wildcard,
                                            message,
                                            style,
                                            filterindex=default_filterindex)

        if filepath is None:
            return

        filetype = filetypes[filterindex]

        # Change the main window filepath state

        self.main_window.filepath = filepath

        # Load file into grid
        post_command_event(self.main_window,
                           self.main_window.GridActionOpenMsg,
                           attr={
                               "filepath": filepath,
                               "filetype": filetype
                           })

        # Set Window title to new filepath

        title_text = filepath.split("/")[-1] + " - pyspread"
        post_command_event(self.main_window,
                           self.main_window.TitleMsg,
                           text=title_text)

        self.main_window.grid.ForceRefresh()

        if is_gtk():
            try:
                wx.Yield()
            except:
                pass

        # Mark content as unchanged
        try:
            post_command_event(self.main_window,
                               self.ContentChangedMsg,
                               changed=False)
        except TypeError:
            # The main window does not exist any more
            pass
Example #28
0
    def OnNew(self, event):
        """New grid event handler"""

        # If changes have taken place save of old grid

        if self.main_window.changed_since_save:
            save_choice = self.interfaces.get_save_request_from_user()

            if save_choice is None:
                # Cancelled close operation
                return

            elif save_choice:
                # User wants to save content
                post_command_event(self.main_window, self.main_window.SaveMsg)

        # Get grid dimensions

        shape = self.interfaces.get_dimensions_from_user(no_dim=3)

        if shape is None:
            return

        # Set new filepath and post it to the title bar

        self.main_window.filepath = None
        post_command_event(self.main_window,
                           self.main_window.TitleMsg,
                           text="pyspread")

        # Clear globals
        self.main_window.grid.actions.clear_globals_reload_modules()

        # Create new grid
        post_command_event(self.main_window,
                           self.main_window.GridActionNewMsg,
                           shape=shape)

        # Update TableChoiceIntCtrl
        post_command_event(self.main_window,
                           self.main_window.ResizeGridMsg,
                           shape=shape)

        if is_gtk():
            try:
                wx.Yield()
            except:
                pass

        self.main_window.grid.actions.change_grid_shape(shape)

        self.main_window.grid.GetTable().ResetView()
        self.main_window.grid.ForceRefresh()

        # Display grid creation in status bar
        msg = _("New grid with dimensions {dim} created.").format(dim=shape)
        post_command_event(self.main_window,
                           self.main_window.StatusBarMsg,
                           text=msg)

        self.main_window.grid.ForceRefresh()

        if is_gtk():
            try:
                wx.Yield()
            except:
                pass

        # Mark content as unchanged
        try:
            post_command_event(self.main_window,
                               self.ContentChangedMsg,
                               changed=False)
        except TypeError:
            # The main window does not exist any more
            pass
Example #29
0
    def OnOpen(self, event):
        """File open event handler"""

        # If changes have taken place save of old grid
        if undo.stack().haschanged():
            save_choice = self.interfaces.get_save_request_from_user()

            if save_choice is None:
                # Cancelled close operation
                return

            elif save_choice:
                # User wants to save content
                post_command_event(self.main_window, self.main_window.SaveMsg)

        # Get filepath from user
        f2w = get_filetypes2wildcards(
            ["pys", "pysu", "xls", "xlsx", "ods", "all"])
        filetypes = f2w.keys()
        wildcards = f2w.values()
        wildcard = "|".join(wildcards)

        message = _("Choose file to open.")
        style = wx.OPEN

        default_filetype = config["default_open_filetype"]
        try:
            default_filterindex = filetypes.index(default_filetype)
        except ValueError:
            # Be graceful if the user has entered an unkown filetype
            default_filterindex = 0

        get_fp_fidx = self.interfaces.get_filepath_findex_from_user
        filepath, filterindex = get_fp_fidx(wildcard, message, style,
                                            filterindex=default_filterindex)

        if filepath is None:
            return

        filetype = filetypes[filterindex]

        # Change the main window filepath state

        self.main_window.filepath = filepath

        # Load file into grid
        post_command_event(self.main_window,
                           self.main_window.GridActionOpenMsg,
                           attr={"filepath": filepath, "filetype": filetype})

        # Set Window title to new filepath

        title_text = filepath.split("/")[-1] + " - pyspread"
        post_command_event(self.main_window,
                           self.main_window.TitleMsg, text=title_text)

        self.main_window.grid.ForceRefresh()

        if is_gtk():
            try:
                wx.Yield()
            except:
                pass

        # Update savepoint and clear the undo stack
        undo.stack().clear()
        undo.stack().savepoint()

        # Update content changed state
        try:
            post_command_event(self.main_window, self.ContentChangedMsg)
        except TypeError:
            # The main window does not exist any more
            pass
Example #30
0
    def __init__(self, parent, *args, **kwargs):
        try:
            S = kwargs.pop("S")

        except KeyError:
            S = None

        try:
            dimensions = kwargs.pop("dimensions")

        except KeyError:
            dimensions = (
                config["grid_rows"],
                config["grid_columns"],
                config["grid_tables"])

        wx.Frame.__init__(self, parent, *args, **kwargs)

        self.interfaces = GuiInterfaces(self)

        try:
            self._mgr = aui.AuiManager(self)

        except Exception:
            # This may fail if py.test runs under Windows
            # Therefore, we set up a basic framework for the unit tests
            self.grid = Grid(self, -1, S=S, dimensions=dimensions)
            self.clipboard = Clipboard()
            self.actions = AllMainWindowActions(self.grid)

        self.parent = parent

        self.handlers = MainWindowEventHandlers(self)

        # Program states
        # --------------

        self._states()

        # GUI elements
        # ------------

        # Menu Bar
        self.menubar = wx.MenuBar()
        self.main_menu = MainMenu(parent=self, menubar=self.menubar)
        self.SetMenuBar(self.menubar)

        # Disable menu item for leaving safe mode
        post_command_event(self, self.SafeModeExitMsg)

        # Status bar
        statusbar = StatusBar(self)
        self.SetStatusBar(statusbar)

        welcome_text = _("Welcome to pyspread.")
        post_command_event(self, self.StatusBarMsg, text=welcome_text)

        # Toolbars
        self.main_toolbar = MainToolbar(self, -1)
        self.macro_toolbar = MacroToolbar(self, -1)
        self.find_toolbar = FindToolbar(self, -1)
        self.attributes_toolbar = AttributesToolbar(self, -1)
        self.widget_toolbar = WidgetToolbar(self, -1)

        # Entry line
        self.entry_line_panel = EntryLineToolbarPanel(self, -1)

        # Main grid
        self.grid = Grid(self, -1, S=S, dimensions=dimensions)

        # TableChoiceListCtrl
        self.table_list_panel = TableChoiceListCtrl(self, self.grid)

        # Macro panel
        macros = self.grid.code_array.macros
        self.macro_panel = MacroPanel(self, macros, -1)

        # Clipboard
        self.clipboard = Clipboard()

        # Main window actions

        self.actions = AllMainWindowActions(self.grid)

        # Layout and bindings

        self._set_properties()
        self._do_layout()
        self._bind()

        if is_gtk():
            try:
                wx.Yield()
            except:
                pass

        # Update undo stack savepoint
        undo.stack().savepoint()

        # 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
Example #31
0
    def OnOpen(self, event):
        """File open event handler"""

        # If changes have taken place save of old grid

        if self.main_window.changed_since_save:
            save_choice = self.interfaces.get_save_request_from_user()

            if save_choice is None:
                # Cancelled close operation
                return

            elif save_choice:
                # User wants to save content
                post_command_event(self.main_window, self.main_window.SaveMsg)

        # Get filepath from user

        if xlrd is None:
            # Do not offer xls if xlrd is missing
            wildcard = \
                _("Pyspread file") + " (*.pys)|*.pys|" + \
                _("Uncompressed pyspread file") + " (*.pysu)|*.pysu|" + \
                _("All files") + " (*.*)|*.*"
            filetypes = ["pys", "pysu", "pys"]
        else:
            wildcard = \
                _("Pyspread file") + " (*.pys)|*.pys|" + \
                _("Uncompressed pyspread file") + " (*.pysu)|*.pysu|" + \
                _("Excel 1997-2003 file") + " (*.xls)|*.xls|" + \
                _("Excel 2007+ file values") + " (*.xlsx)|*.xlsx|" + \
                _("Excel 2007+ file formulas") + " (*.xlsx)|*.xlsx|" + \
                _("All files") + " (*.*)|*.*"
            filetypes = ["pys", "pysu", "xls", "xlsv", "xlsf", "pys"]

        message = _("Choose file to open.")
        style = wx.OPEN
        filepath, filterindex = \
            self.interfaces.get_filepath_findex_from_user(wildcard, message,
                                                          style)

        if filepath is None:
            return

        filetype = filetypes[filterindex]

        # Change the main window filepath state

        self.main_window.filepath = filepath

        # Load file into grid
        post_command_event(self.main_window,
                           self.main_window.GridActionOpenMsg,
                           attr={"filepath": filepath, "filetype": filetype})

        # Set Window title to new filepath

        title_text = filepath.split("/")[-1] + " - pyspread"
        post_command_event(self.main_window,
                           self.main_window.TitleMsg, text=title_text)

        self.main_window.grid.ForceRefresh()

        if is_gtk():
            try:
                wx.Yield()
            except:
                pass

        # Mark content as unchanged
        try:
            post_command_event(self.main_window, self.ContentChangedMsg,
                               changed=False)
        except TypeError:
            # The main window does not exist any more
            pass
Example #32
0
    def Draw(self, grid, attr, dc, rect, row, col, isSelected, printing=False):
        """Draws the cell border and content"""

        key = row, col, grid.current_table

        rect = self.get_merged_rect(grid, key, rect)
        if rect is None:
            # Merged cell
            if grid.is_merged_cell_drawn(key):
                row, col, __ = key = self.get_merging_cell(grid, key)
                rect = grid.CellToRect(row, col)
                rect = self.get_merged_rect(grid, key, rect)
            else:
                return

        if isSelected:
            grid.selection_present = True

            bg = Background(grid, rect, self.data_array, row, col,
                            grid.current_table, isSelected)
        else:
            width, height = rect.width, rect.height

            bg_components = ["bgcolor",
                             "borderwidth_bottom", "borderwidth_right",
                             "bordercolor_bottom", "bordercolor_right"]
            if grid._view_frozen:
                bg_components += ['frozen']

            bg_key = tuple([width, height] +
                           [self.data_array.cell_attributes[key][bgc]
                               for bgc in bg_components])

            try:
                bg = self.backgrounds[bg_key]

            except KeyError:
                if len(self.backgrounds) > 10000:
                    # self.backgrounds may grow quickly

                    self.backgrounds = {}

                bg = self.backgrounds[bg_key] = \
                    Background(grid, rect, self.data_array, *key)

        if is_gtk() and not printing:
            mask_type = wx.AND
        else:
            mask_type = wx.COPY

        dc.Blit(rect.x, rect.y, rect.width, rect.height,
                bg.dc, 0, 0, mask_type)

        # Check if the dc is drawn manually be a return func
        try:
            res = self.data_array[row, col, grid.current_table]

        except IndexError:
            return

        if isinstance(res, types.FunctionType):
            # Add func_dict attribute
            # so that we are sure that it uses a dc
            try:
                res(grid, attr, dc, rect)
            except TypeError:
                pass

        elif isinstance(res, wx._gdi.Bitmap):
            # A bitmap is returned --> Draw it!
            self.draw_bitmap(dc, res, rect, grid, key)

        elif isinstance(res, matplotlib.pyplot.Figure):
            # A matplotlib figure is returned --> Draw it!
            self.draw_matplotlib_figure(dc, res, rect, grid, key)

        elif res is not None:
            self.draw_text_label(dc, res, rect, grid, key)

        if grid.actions.cursor[:2] == (row, col):
            self.update_cursor(dc, grid, row, col)