Example #1
0
    def GetStyleSheet(self, sheet_name=None):
        """Finds the current style sheet and returns its path. The
        Lookup is done by first looking in the users config directory
        and if it is not found there it looks for one on the system
        level and if that fails it returns None.
        @param sheet_name: style sheet to look for
        @return: full path to style sheet

        """
        if sheet_name:
            style = sheet_name
            if sheet_name.split(u'.')[-1] != u"ess":
                style += u".ess"
        elif _PGET('SYNTHEME', 'str').split(u'.')[-1] != u"ess":
            style = (_PGET('SYNTHEME', 'str') + u".ess").lower()
        else:
            style = _PGET('SYNTHEME', 'str').lower()

        # Get Correct Filename if it exists
        for sheet in util.GetResourceFiles('styles', False, True, title=False):
            if sheet.lower() == style.lower():
                style = sheet
                break
        user = wx.GetApp().fonts.getStylePath(style)
        if os.path.exists(user):
            self.dprint("found user style %s at %s" % (style, user))
            return user
        sysp = os.path.join(util.GetResourceDir('styles'), style)
        if os.path.exists(sysp):
            self.dprint("found system style %s at %s" % (style, sysp))
            return sysp
        self.dprint("didn't find %s" % style)
Example #2
0
    def GetStyleSheet(self, sheet_name=None):
        """Finds the current style sheet and returns its path. The
        Lookup is done by first looking in the users config directory
        and if it is not found there it looks for one on the system
        level and if that fails it returns None.
        @param sheet_name: style sheet to look for
        @return: full path to style sheet

        """
        if sheet_name:
            style = sheet_name
            if sheet_name.split(u'.')[-1] != u"ess":
                style += u".ess"
        elif _PGET('SYNTHEME', 'str').split(u'.')[-1] != u"ess":
            style = (_PGET('SYNTHEME', 'str') + u".ess").lower()
        else:
            style = _PGET('SYNTHEME', 'str').lower()

        # Get Correct Filename if it exists
        for sheet in util.GetResourceFiles('styles', False, True, title=False):
            if sheet.lower() == style.lower():
                style = sheet
                break
        user = wx.GetApp().fonts.getStylePath(style)
        if os.path.exists(user):
            self.dprint("found user style %s at %s" % (style, user))
            return user
        sysp = os.path.join(util.GetResourceDir('styles'), style)
        if os.path.exists(sysp):
            self.dprint("found system style %s at %s" % (style, sysp))
            return sysp
        self.dprint("didn't find %s" % style)
Example #3
0
    def OnViewTb(self, evt):
        """Toggles visibility of toolbar
        @note: On OSX there is a frame button for hidding the toolbar
               that is handled internally by the osx toolbar and not this
               handler.
        @param evt: Event fired that called this handler
        @type evt: wxMenuEvent

        """
        if evt.GetId() == ID_VIEW_TOOL:
            size = self.GetSize()
            toolbar = self.GetToolBar()
            if _PGET('TOOLBAR', 'bool', False) or toolbar.IsShown():
                _PSET('TOOLBAR', False)
                toolbar.Hide()
                if wx.Platform != '__WXMAC__':
                    self.SetSize((size[0], size[1] - toolbar.GetSize()[1]))
            else:
                _PSET('TOOLBAR', True)
                toolbar.Show()
                if wx.Platform != '__WXMAC__':
                    self.SetSize((size[0], size[1] + toolbar.GetSize()[1]))
                self.UpdateToolBar()

            self.SendSizeEvent()
            self.Refresh()
            self.Update()
        else:
            evt.Skip()
Example #4
0
    def OnViewTb(self, evt):
        """Toggles visibility of toolbar
        @note: On OSX there is a frame button for hidding the toolbar
               that is handled internally by the osx toolbar and not this
               handler.
        @param evt: Event fired that called this handler
        @type evt: wxMenuEvent

        """
        if evt.GetId() == ID_VIEW_TOOL:
            size = self.GetSize()
            toolbar = self.GetToolBar()
            if _PGET('TOOLBAR', 'bool', False) or toolbar.IsShown():
                _PSET('TOOLBAR', False)
                toolbar.Hide()
                if wx.Platform != '__WXMAC__':
                    self.SetSize((size[0], size[1] - toolbar.GetSize()[1]))
            else:
                _PSET('TOOLBAR', True)
                toolbar.Show()
                if wx.Platform != '__WXMAC__':
                    self.SetSize((size[0], size[1] + toolbar.GetSize()[1]))
                self.UpdateToolBar()

            self.SendSizeEvent()
            self.Refresh()
            self.Update()
        else:
            evt.Skip()
Example #5
0
    def DoOpen(self, evt, fname=u''):
        """ Do the work of opening a file and placing it
        in a new notebook page.
        @keyword fname: can be optionally specified to open
                        a file without opening a FileDialog
        @type fname: string

        """
        result = wx.ID_CANCEL
        try:
            e_id = evt.GetId()
        except AttributeError:
            e_id = evt

        if e_id == ID_OPEN:
            dlg = wx.FileDialog(self, _("Choose a File"), '', "",
                                ''.join(syntax.GenFileFilters()),
                                wx.OPEN | wx.MULTIPLE)
            dlg.SetFilterIndex(_PGET('FFILTER', 'int', 0))
            result = dlg.ShowModal()
            _PSET('FFILTER', dlg.GetFilterIndex())
            paths = dlg.GetPaths()
            dlg.Destroy()

            if result != wx.ID_OK:
                self.LOG('[mainw][info] Canceled Opening File')
            else:
                for path in paths:
                    if _PGET('OPEN_NW', default=False):
                        wx.GetApp().OpenNewWindow(path)
                    else:
                        dirname = util.GetPathName(path)
                        filename = util.GetFileName(path)
                        self.nb.OpenPage(dirname, filename)
                        self.nb.GoCurrentPage()
        else:
            self.LOG("[mainw][info] CMD Open File: %s" % fname)
            filename = util.GetFileName(fname)
            dirname = util.GetPathName(fname)
            self.nb.OpenPage(dirname, filename)
Example #6
0
    def DoOpen(self, evt, fname=u''):
        """ Do the work of opening a file and placing it
        in a new notebook page.
        @keyword fname: can be optionally specified to open
                        a file without opening a FileDialog
        @type fname: string

        """
        result = wx.ID_CANCEL
        try:
            e_id = evt.GetId()
        except AttributeError:
            e_id = evt

        if e_id == ID_OPEN:
            dlg = wx.FileDialog(self, _("Choose a File"), '', "", 
                                ''.join(syntax.GenFileFilters()), 
                                wx.OPEN | wx.MULTIPLE)
            dlg.SetFilterIndex(_PGET('FFILTER', 'int', 0))
            result = dlg.ShowModal()
            _PSET('FFILTER', dlg.GetFilterIndex())
            paths = dlg.GetPaths()
            dlg.Destroy()

            if result != wx.ID_OK:
                self.LOG('[mainw][info] Canceled Opening File')
            else:
                for path in paths:
                    if _PGET('OPEN_NW', default=False):
                        wx.GetApp().OpenNewWindow(path)
                    else:
                        dirname = util.GetPathName(path)
                        filename = util.GetFileName(path)
                        self.nb.OpenPage(dirname, filename)   
                        self.nb.GoCurrentPage()
        else:
            self.LOG("[mainw][info] CMD Open File: %s" % fname)
            filename = util.GetFileName(fname)
            dirname = util.GetPathName(fname)
            self.nb.OpenPage(dirname, filename)
Example #7
0
    def LoadFileHistory(self, size):
        """Loads file history from profile
        @return: None

        """
        try:
            hist_list = _PGET('FHIST', default=list())
            if len(hist_list) > size:
                hist_list = hist_list[:size]

            for fname in hist_list:
                if isinstance(fname, basestring) and fname:
                    self.filehistory.AddFileToHistory(fname)
        except UnicodeEncodeError, msg:
            self.LOG("[main][err] Filehistory load failed: %s" % str(msg))
Example #8
0
    def LoadFileHistory(self, size):
        """Loads file history from profile
        @return: None

        """
        try:
            hist_list = _PGET('FHIST', default=list())
            if len(hist_list) > size:
                hist_list = hist_list[:size]

            for fname in hist_list:
                if isinstance(fname, basestring) and fname:
                    self.filehistory.AddFileToHistory(fname)
        except UnicodeEncodeError, msg:
            self.LOG("[main][err] Filehistory load failed: %s" % str(msg))
Example #9
0
    def OnPrint(self, evt):
        """Handles sending the current document to the printer,
        showing print previews, and opening the printer settings
        dialog.
        @todo: is any manual cleanup required for the printer objects?
        @param evt: Event fired that called this handler
        @type evt: wxMenuEvent

        """
        e_id = evt.GetId()
        printer = ed_print.EdPrinter(self, self.nb.GetCurrentCtrl)
        printer.SetColourMode(_PGET('PRINT_MODE', "str").\
                              replace(u'/', u'_').lower())
        if e_id == ID_PRINT:
            printer.Print()
        elif e_id == ID_PRINT_PRE:
            printer.Preview()
        elif e_id == ID_PRINT_SU:
            printer.PageSetup()
        else:
            evt.Skip()
Example #10
0
    def OnPrint(self, evt):
        """Handles sending the current document to the printer,
        showing print previews, and opening the printer settings
        dialog.
        @todo: is any manual cleanup required for the printer objects?
        @param evt: Event fired that called this handler
        @type evt: wxMenuEvent

        """
        e_id = evt.GetId()
        printer = ed_print.EdPrinter(self, self.nb.GetCurrentCtrl)
        printer.SetColourMode(_PGET('PRINT_MODE', "str").\
                              replace(u'/', u'_').lower())
        if e_id == ID_PRINT:
            printer.Print()
        elif e_id == ID_PRINT_PRE:
            printer.Preview()
        elif e_id == ID_PRINT_SU:
            printer.PageSetup()
        else:
            evt.Skip()
Example #11
0
    def OnClose(self, evt=None):
        """Close this frame and unregister it from the applications
        mainloop.
        @note: Closing the frame will write out all session data to the
               users configuration directory.
        @keyword evt: Event fired that called this handler
        @type evt: wxMenuEvent
        @return: None on destroy, or True on cancel

        """
        # Cleanup Controls
        _PSET('LAST_SESSION', self.nb.GetFileNames())
        self._exiting = True
        controls = self.nb.GetPageCount()
        self.LOG("[main_evt][exit] Number of controls: %d" % controls)
        while controls:
            if controls <= 0:
                self.Close(True)  # Force exit since there is a problem

            self.LOG("[main_evt][exit] Requesting Page Close")
            result = self.nb.ClosePage()
            if result == wx.ID_CANCEL:
                break
            controls -= 1

        if result == wx.ID_CANCEL:
            self._exiting = False
            return True

        ### If we get to here there is no turning back so cleanup
        ### additional items and save user settings

        # Write out saved document information
        self.nb.DocMgr.WriteBook()
        syntax.SyntaxMgr().SaveState()

        # Save Shelf contents
        _PSET('SHELF_ITEMS', self._shelf.GetItemStack())

        # Save Window Size/Position for next launch
        # XXX On wxMac the window size doesnt seem to take the toolbar
        #     into account so destroy it so that the window size is accurate.
        if wx.Platform == '__WXMAC__' and self.GetToolBar():
            self.GetToolBar().Destroy()
        _PSET('WSIZE', self.GetSizeTuple())
        _PSET('WPOS', self.GetPositionTuple())
        self.LOG("[main_evt] [exit] Closing editor at pos=%s size=%s" % \
                 (_PGET('WPOS', 'str'), _PGET('WSIZE', 'str')))

        # Update profile
        profiler.AddFileHistoryToProfile(self.filehistory)
        profiler.Profile().Write(_PGET('MYPROFILE'))

        # Cleanup file history
        try:
            del self.filehistory
        except AttributeError:
            self.LOG("[main][exit][err] Trapped AttributeError OnExit")

        # Post exit notice to all aui panes
        panes = self._mgr.GetAllPanes()
        exit_evt = ed_event.MainWindowExitEvent(ed_event.edEVT_MAINWINDOW_EXIT,
                                                wx.ID_ANY)
        for pane in panes:
            wx.PostEvent(pane.window, exit_evt)

        # Finally close the window
        self.LOG("[main_info] Closing Main Frame")
        wx.GetApp().UnRegisterWindow(repr(self))
        self.Destroy()
Example #12
0
    def __init__(self, parent, id_, wsize, title):
        """Initialiaze the Frame and Event Handlers.
        @param wsize: Windows initial size
        @param title: Windows Title

        """
        wx.Frame.__init__(self,
                          parent,
                          id_,
                          title,
                          size=wsize,
                          style=wx.DEFAULT_FRAME_STYLE)

        self._mgr = wx.aui.AuiManager(flags=wx.aui.AUI_MGR_DEFAULT | \
                                      wx.aui.AUI_MGR_TRANSPARENT_DRAG | \
                                      wx.aui.AUI_MGR_TRANSPARENT_HINT)
        self._mgr.SetManagedWindow(self)
        viewmgr.PerspectiveManager.__init__(self, self._mgr, \
                                            CONFIG['CACHE_DIR'])

        # Setup app icon and title
        self.SetTitle()
        util.SetWindowIcon(self)

        # Check if user wants Metal Style under OS X
        # NOTE: soon to be deprecated
        if wx.Platform == '__WXMAC__' and _PGET('METAL'):
            self.SetExtraStyle(wx.FRAME_EX_METAL)

        # Attributes
        self.LOG = wx.GetApp().GetLog()
        self._handlers = dict(menu=list(), ui=list())

        #---- Sizers to hold subapplets ----#
        self.sizer = wx.BoxSizer(wx.VERTICAL)

        #---- Setup File History ----#
        self.filehistory = wx.FileHistory(_PGET('FHIST_LVL', 'int', 5))

        #---- Status bar on bottom of window ----#
        self.CreateStatusBar(3, style=wx.ST_SIZEGRIP)
        self.SetStatusWidths([-1, 120, 155])
        #---- End Statusbar Setup ----#

        #---- Notebook that contains the editting buffers ----#
        edit_pane = wx.Panel(self)
        self.nb = ed_pages.EdPages(edit_pane, wx.ID_ANY)
        edit_pane.nb = self.nb
        self.sizer.Add(self.nb, 1, wx.EXPAND)
        edit_pane.SetSizer(self.sizer)
        self._mgr.AddPane(edit_pane, wx.aui.AuiPaneInfo(). \
                          Name("EditPane").Center().Layer(1).Dockable(False). \
                          CloseButton(False).MaximizeButton(False). \
                          CaptionVisible(False))

        #---- Command Bar ----#
        self._cmdbar = ed_cmdbar.CommandBar(edit_pane, ID_COMMAND_BAR)
        self._cmdbar.Hide()

        #---- Setup Toolbar ----#
        self.SetToolBar(ed_toolbar.EdToolBar(self))
        if not _PGET('TOOLBAR'):
            self.GetToolBar().Hide()
        #---- End Toolbar Setup ----#

        #---- Menus ----#
        menbar = ed_menu.EdMenuBar()
        self._menus = dict(file=menbar.GetMenuByName("file"),
                           edit=menbar.GetMenuByName("edit"),
                           view=menbar.GetMenuByName("view"),
                           viewedit=menbar.GetMenuByName("viewedit"),
                           format=menbar.GetMenuByName("format"),
                           settings=menbar.GetMenuByName("settings"),
                           tools=menbar.GetMenuByName("tools"),
                           lineformat=menbar.GetMenuByName("lineformat"),
                           language=syntax.GenLexerMenu())

        # Todo this should not be hard coded
        self._menus['view'].InsertMenu(5, ID_PERSPECTIVES, _("Perspectives"),
                                       self.GetPerspectiveControls())

        ## Setup additional menu items
        self.filehistory.UseMenu(menbar.GetMenuByName("filehistory"))
        self._menus['settings'].AppendMenu(ID_LEXER, _("Lexers"),
                                           self._menus['language'],
                                           _("Manually Set a Lexer/Syntax"))

        # On mac, do this to make help menu appear in correct location
        # Note it must be done before setting the menu bar and after the
        # menus have been created.
        if wx.Platform == '__WXMAC__':
            wx.GetApp().SetMacHelpMenuTitleName(_("Help"))

        #---- Menu Bar ----#
        self.SetMenuBar(menbar)

        #---- Actions to take on menu events ----#
        self.Bind(wx.EVT_MENU_OPEN, self.UpdateMenu)
        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_MENU_HIGHLIGHT, \
                      self.OnMenuHighlight, id=ID_LEXER)
            self.Bind(wx.EVT_MENU_HIGHLIGHT, \
                      self.OnMenuHighlight, id=ID_EOL_MODE)

        # Collect Menu Event handler pairs
        self._handlers['menu'].extend([  # File Menu
            (ID_NEW, self.OnNew),
            (ID_OPEN, self.OnOpen),
            (ID_CLOSE, self.OnClosePage),
            (ID_CLOSE_WINDOW, self.OnClose),
            (ID_CLOSEALL, self.OnClosePage),
            (ID_SAVE, self.OnSave),
            (ID_SAVEAS, self.OnSaveAs),
            (ID_SAVEALL, self.OnSave),
            (ID_SAVE_PROFILE, self.OnSaveProfile),
            (ID_LOAD_PROFILE, self.OnLoadProfile),
            (ID_EXIT, wx.GetApp().OnExit),
            (ID_PRINT, self.OnPrint),
            (ID_PRINT_PRE, self.OnPrint),
            (ID_PRINT_SU, self.OnPrint),

            # Edit Menu
            (ID_FIND, self.nb.FindService.OnShowFindDlg),
            (ID_FIND_REPLACE, self.nb.FindService.OnShowFindDlg),
            (ID_QUICK_FIND, self.OnCommandBar),
            (ID_PREF, self.OnPreferences),

            # View Menu
            (ID_GOTO_LINE, self.OnCommandBar),
            (ID_VIEW_TOOL, self.OnViewTb),

            # Format Menu
            (ID_FONT, self.OnFont),

            # Tool Menu
            (ID_COMMAND, self.OnCommandBar),
            (ID_STYLE_EDIT, self.OnStyleEdit),
            (ID_PLUGMGR, self.OnPluginMgr),

            # Help Menu
            (ID_ABOUT, self.OnAbout),
            (ID_HOMEPAGE, self.OnHelp),
            (ID_DOCUMENTATION, self.OnHelp),
            (ID_CONTACT, self.OnHelp)
        ])

        self._handlers['menu'].extend([(l_id, self.DispatchToControl)
                                       for l_id in syntax.SyntaxIds()])

        # Extra menu handlers (need to work these into above system yet
        self.Bind(wx.EVT_MENU, self.DispatchToControl)
        self.Bind(wx.EVT_MENU, self.OnGenerate)
        self.Bind(wx.EVT_MENU_RANGE,
                  self.OnFileHistory,
                  id=wx.ID_FILE1,
                  id2=wx.ID_FILE9)

        #---- End Menu Setup ----#

        #---- Other Event Handlers ----#
        # Frame
        self.Bind(wx.EVT_ACTIVATE, self.OnActivate)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.Bind(ed_event.EVT_STATUS, self.OnStatus)

        # Find Dialog
        self.Bind(wx.EVT_FIND, self.nb.FindService.OnFind)
        self.Bind(wx.EVT_FIND_NEXT, self.nb.FindService.OnFind)
        self.Bind(wx.EVT_FIND_REPLACE, self.nb.FindService.OnFind)
        self.Bind(wx.EVT_FIND_REPLACE_ALL, self.nb.FindService.OnFind)
        self.Bind(wx.EVT_FIND_CLOSE, self.nb.FindService.OnFindClose)

        #---- End other event actions ----#

        #---- Final Setup Calls ----#
        self._exiting = False
        self.LoadFileHistory(_PGET('FHIST_LVL', fmt='int'))
        self.UpdateToolBar()

        # Call add on plugins
        self.LOG("[main][info] Loading MainWindow Plugins ")
        plgmgr = wx.GetApp().GetPluginManager()
        addons = MainWindowAddOn(plgmgr)
        addons.Init(self)
        self._handlers['menu'].extend(addons.GetEventHandlers())
        self._handlers['ui'].extend(addons.GetEventHandlers(ui_evt=True))
        self._shelf = iface.Shelf(plgmgr)
        self._shelf.Init(self)
        self.LOG("[main][info] Loading Generator plugins")
        generator.Generator(plgmgr).InstallMenu(self._menus['tools'])

        # Set Perspective
        self.SetPerspective(_PGET('DEFAULT_VIEW'))
        self._mgr.Update()
Example #13
0
    def __init__(self, parent, id_, wsize, title):
        """Initialiaze the Frame and Event Handlers.
        @param wsize: Windows initial size
        @param title: Windows Title

        """
        wx.Frame.__init__(self, parent, id_, title, size=wsize,
                          style=wx.DEFAULT_FRAME_STYLE)

        self._mgr = wx.aui.AuiManager(flags=wx.aui.AUI_MGR_DEFAULT | \
                                      wx.aui.AUI_MGR_TRANSPARENT_DRAG | \
                                      wx.aui.AUI_MGR_TRANSPARENT_HINT)
        self._mgr.SetManagedWindow(self)
        viewmgr.PerspectiveManager.__init__(self, self._mgr, \
                                            CONFIG['CACHE_DIR'])

        # Setup app icon and title 
        self.SetTitle()
        util.SetWindowIcon(self)

        # Check if user wants Metal Style under OS X
        # NOTE: soon to be deprecated
        if wx.Platform == '__WXMAC__' and _PGET('METAL'):
            self.SetExtraStyle(wx.FRAME_EX_METAL)

        # Attributes
        self.LOG = wx.GetApp().GetLog()
        self._handlers = dict(menu=list(), ui=list())

        #---- Sizers to hold subapplets ----#
        self.sizer = wx.BoxSizer(wx.VERTICAL)

        #---- Setup File History ----#
        self.filehistory = wx.FileHistory(_PGET('FHIST_LVL', 'int', 5))

        #---- Status bar on bottom of window ----#
        self.CreateStatusBar(3, style=wx.ST_SIZEGRIP)
        self.SetStatusWidths([-1, 120, 155])
        #---- End Statusbar Setup ----#

        #---- Notebook that contains the editting buffers ----#
        edit_pane = wx.Panel(self)
        self.nb = ed_pages.EdPages(edit_pane, wx.ID_ANY)
        edit_pane.nb = self.nb
        self.sizer.Add(self.nb, 1, wx.EXPAND)
        edit_pane.SetSizer(self.sizer)
        self._mgr.AddPane(edit_pane, wx.aui.AuiPaneInfo(). \
                          Name("EditPane").Center().Layer(1).Dockable(False). \
                          CloseButton(False).MaximizeButton(False). \
                          CaptionVisible(False))

        #---- Command Bar ----#
        self._cmdbar = ed_cmdbar.CommandBar(edit_pane, ID_COMMAND_BAR)
        self._cmdbar.Hide()

        #---- Setup Toolbar ----#
        self.SetToolBar(ed_toolbar.EdToolBar(self))
        if not _PGET('TOOLBAR'):
            self.GetToolBar().Hide()
        #---- End Toolbar Setup ----#

        #---- Menus ----#
        menbar = ed_menu.EdMenuBar()
        self._menus = dict(file=menbar.GetMenuByName("file"),
                           edit=menbar.GetMenuByName("edit"),
                           view=menbar.GetMenuByName("view"),
                           viewedit=menbar.GetMenuByName("viewedit"),
                           format=menbar.GetMenuByName("format"),
                           settings=menbar.GetMenuByName("settings"),
                           tools=menbar.GetMenuByName("tools"),
                           lineformat=menbar.GetMenuByName("lineformat"),
                           language=syntax.GenLexerMenu())

        # Todo this should not be hard coded
        self._menus['view'].InsertMenu(5, ID_PERSPECTIVES, _("Perspectives"), 
                                       self.GetPerspectiveControls())

        ## Setup additional menu items
        self.filehistory.UseMenu(menbar.GetMenuByName("filehistory"))
        self._menus['settings'].AppendMenu(ID_LEXER, _("Lexers"), 
                                           self._menus['language'],
                                           _("Manually Set a Lexer/Syntax"))

        # On mac, do this to make help menu appear in correct location
        # Note it must be done before setting the menu bar and after the
        # menus have been created.
        if wx.Platform == '__WXMAC__':
            wx.GetApp().SetMacHelpMenuTitleName(_("Help"))

        #---- Menu Bar ----#
        self.SetMenuBar(menbar)

        #---- Actions to take on menu events ----#
        self.Bind(wx.EVT_MENU_OPEN, self.UpdateMenu)
        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_MENU_HIGHLIGHT, \
                      self.OnMenuHighlight, id=ID_LEXER)
            self.Bind(wx.EVT_MENU_HIGHLIGHT, \
                      self.OnMenuHighlight, id=ID_EOL_MODE)

        # Collect Menu Event handler pairs
        self._handlers['menu'].extend([# File Menu
                                       (ID_NEW, self.OnNew),
                                       (ID_OPEN, self.OnOpen),
                                       (ID_CLOSE, self.OnClosePage),
                                       (ID_CLOSE_WINDOW, self.OnClose),
                                       (ID_CLOSEALL, self.OnClosePage),
                                       (ID_SAVE, self.OnSave),
                                       (ID_SAVEAS, self.OnSaveAs),
                                       (ID_SAVEALL, self.OnSave),
                                       (ID_SAVE_PROFILE, self.OnSaveProfile),
                                       (ID_LOAD_PROFILE, self.OnLoadProfile),
                                       (ID_EXIT, wx.GetApp().OnExit),
                                       (ID_PRINT, self.OnPrint),
                                       (ID_PRINT_PRE, self.OnPrint),
                                       (ID_PRINT_SU, self.OnPrint),

                                       # Edit Menu
                                       (ID_FIND, 
                                        self.nb.FindService.OnShowFindDlg),
                                       (ID_FIND_REPLACE, 
                                        self.nb.FindService.OnShowFindDlg),
                                       (ID_QUICK_FIND, self.OnCommandBar),
                                       (ID_PREF, self.OnPreferences),

                                       # View Menu
                                       (ID_GOTO_LINE, self.OnCommandBar),
                                       (ID_VIEW_TOOL, self.OnViewTb),

                                       # Format Menu
                                       (ID_FONT, self.OnFont),

                                       # Tool Menu
                                       (ID_COMMAND, self.OnCommandBar),
                                       (ID_STYLE_EDIT, self.OnStyleEdit),
                                       (ID_PLUGMGR, self.OnPluginMgr),

                                       # Help Menu
                                       (ID_ABOUT, self.OnAbout),
                                       (ID_HOMEPAGE, self.OnHelp),
                                       (ID_DOCUMENTATION, self.OnHelp),
                                       (ID_CONTACT, self.OnHelp)])

        self._handlers['menu'].extend([(l_id, self.DispatchToControl) 
                                       for l_id in syntax.SyntaxIds()])

        # Extra menu handlers (need to work these into above system yet
        self.Bind(wx.EVT_MENU, self.DispatchToControl)
        self.Bind(wx.EVT_MENU, self.OnGenerate)
        self.Bind(wx.EVT_MENU_RANGE, self.OnFileHistory, 
                  id=wx.ID_FILE1, id2=wx.ID_FILE9)

        #---- End Menu Setup ----#

        #---- Other Event Handlers ----#
        # Frame
        self.Bind(wx.EVT_ACTIVATE, self.OnActivate)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.Bind(ed_event.EVT_STATUS, self.OnStatus)

        # Find Dialog
        self.Bind(wx.EVT_FIND, self.nb.FindService.OnFind)
        self.Bind(wx.EVT_FIND_NEXT, self.nb.FindService.OnFind)
        self.Bind(wx.EVT_FIND_REPLACE, self.nb.FindService.OnFind)
        self.Bind(wx.EVT_FIND_REPLACE_ALL, self.nb.FindService.OnFind)
        self.Bind(wx.EVT_FIND_CLOSE, self.nb.FindService.OnFindClose)

        #---- End other event actions ----#

        #---- Final Setup Calls ----#
        self._exiting = False
        self.LoadFileHistory(_PGET('FHIST_LVL', fmt='int'))
        self.UpdateToolBar()

        # Call add on plugins
        self.LOG("[main][info] Loading MainWindow Plugins ")
        plgmgr = wx.GetApp().GetPluginManager()
        addons = MainWindowAddOn(plgmgr)
        addons.Init(self)
        self._handlers['menu'].extend(addons.GetEventHandlers())
        self._handlers['ui'].extend(addons.GetEventHandlers(ui_evt=True))
        self._shelf = iface.Shelf(plgmgr)
        self._shelf.Init(self)
        self.LOG("[main][info] Loading Generator plugins")
        generator.Generator(plgmgr).InstallMenu(self._menus['tools'])

        # Set Perspective
        self.SetPerspective(_PGET('DEFAULT_VIEW'))
        self._mgr.Update()
Example #14
0
    def OnClose(self, evt=None):
        """Close this frame and unregister it from the applications
        mainloop.
        @note: Closing the frame will write out all session data to the
               users configuration directory.
        @keyword evt: Event fired that called this handler
        @type evt: wxMenuEvent
        @return: None on destroy, or True on cancel

        """
        # Cleanup Controls
        _PSET('LAST_SESSION', self.nb.GetFileNames())
        self._exiting = True
        controls = self.nb.GetPageCount()
        self.LOG("[main_evt][exit] Number of controls: %d" % controls)
        while controls:
            if controls <= 0:
                self.Close(True) # Force exit since there is a problem

            self.LOG("[main_evt][exit] Requesting Page Close")
            result = self.nb.ClosePage()
            if result == wx.ID_CANCEL:
                break
            controls -= 1

        if result == wx.ID_CANCEL:
            self._exiting = False
            return True

        ### If we get to here there is no turning back so cleanup
        ### additional items and save user settings

        # Write out saved document information
        self.nb.DocMgr.WriteBook()
        syntax.SyntaxMgr().SaveState()

        # Save Shelf contents
        _PSET('SHELF_ITEMS', self._shelf.GetItemStack())

        # Save Window Size/Position for next launch
        # XXX On wxMac the window size doesnt seem to take the toolbar
        #     into account so destroy it so that the window size is accurate.
        if wx.Platform == '__WXMAC__' and self.GetToolBar():
            self.GetToolBar().Destroy()
        _PSET('WSIZE', self.GetSizeTuple())
        _PSET('WPOS', self.GetPositionTuple())
        self.LOG("[main_evt] [exit] Closing editor at pos=%s size=%s" % \
                 (_PGET('WPOS', 'str'), _PGET('WSIZE', 'str')))
        
        # Update profile
        profiler.AddFileHistoryToProfile(self.filehistory)
        profiler.Profile().Write(_PGET('MYPROFILE'))

        # Cleanup file history
        try:
            del self.filehistory
        except AttributeError:
            self.LOG("[main][exit][err] Trapped AttributeError OnExit")

        # Post exit notice to all aui panes
        panes = self._mgr.GetAllPanes()
        exit_evt = ed_event.MainWindowExitEvent(ed_event.edEVT_MAINWINDOW_EXIT,
                                                wx.ID_ANY)
        for pane in panes:
            wx.PostEvent(pane.window, exit_evt)

        # Finally close the window
        self.LOG("[main_info] Closing Main Frame")
        wx.GetApp().UnRegisterWindow(repr(self))
        self.Destroy()