###############################################################################
# Name: ed_pages.py                                                           #
# Purpose: The main editor notebook                                           #
# Author: Cody Precord <cprecord@editra.org>                                  #
# Copyright: (c) 2008 Cody Precord <staff@editra.org>                         #
# License: wxWindows License                                                  #
###############################################################################

"""
This class implements Editra's main notebook control.
@summary: Editra's main notebook class

"""

__author__ = "Cody Precord <cprecord@editra.org>"
__svnid__ = "$Id: ed_pages.py 60523 2009-05-05 18:49:31Z CJP $"
__revision__ = "$Revision: 60523 $"

#--------------------------------------------------------------------------#
# Dependancies
import os
import glob
import cPickle
import wx

# Editra Libraries
import ed_glob
from profiler import Profile_Get
import ed_editv
import syntax.synglob as synglob
import syntax.syntax as syntax
import ed_search
import util
import ed_msg
import ed_txt
import ed_mdlg
import ebmlib
import eclib
from extern import flatnotebook as FNB

#--------------------------------------------------------------------------#
# Globals

_ = wx.GetTranslation
#--------------------------------------------------------------------------#

class EdPages(FNB.FlatNotebook):
    """Editras editor buffer botebook
    @todo: allow for tab styles to be configurable (maybe)

    """
    def __init__(self, parent, id_num):
        """Initialize a notebook with a blank text control in it
        @param parent: parent window of the notebook
        @param id_num: this notebooks id

        """
        FNB.FlatNotebook.__init__(self, parent, id_num,
                                  style=FNB.FNB_FF2 |
                                        FNB.FNB_X_ON_TAB |
                                        FNB.FNB_SMART_TABS |
                                        FNB.FNB_DROPDOWN_TABS_LIST |
                                        FNB.FNB_ALLOW_FOREIGN_DND
                            )

        # Notebook attributes
        self.LOG = wx.GetApp().GetLog()
        self.DocMgr = ed_editv.EdEditorView.DOCMGR
        self._searchctrl = ed_search.SearchController(self, self.GetCurrentCtrl)
        self._searchctrl.SetLookinChoices(Profile_Get('SEARCH_LOC',
                                                      default=list()))
        self._searchctrl.SetFileFilters(Profile_Get('SEARCH_FILTER', default=''))

        self.pg_num = -1              # Track new pages (aka untitled docs)
        self.control = None
        self.frame = self.GetTopLevelParent() # MainWindow
        self._index = dict()          # image list index
        self._ses_load = False
        self._menu = None

        # Set Additional Style Parameters
        self.SetNonActiveTabTextColour(wx.Colour(102, 102, 102))
        ed_icon = ed_glob.CONFIG['SYSPIX_DIR'] + u"editra.png"
        self.SetNavigatorIcon(wx.Bitmap(ed_icon, wx.BITMAP_TYPE_PNG))

        # Setup the ImageList and the default image
        imgl = wx.ImageList(16, 16)
        txtbmp = wx.ArtProvider.GetBitmap(str(synglob.ID_LANG_TXT), wx.ART_MENU)
        self._index[synglob.ID_LANG_TXT] = imgl.Add(txtbmp)
        robmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_READONLY), wx.ART_MENU)
        self._index[ed_glob.ID_READONLY] = imgl.Add(robmp)
        self.SetImageList(imgl)

        # Notebook Events
        self.Bind(FNB.EVT_FLATNOTEBOOK_PAGE_CHANGING, self.OnPageChanging)
        self.Bind(FNB.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
        self.Bind(FNB.EVT_FLATNOTEBOOK_PAGE_CLOSING, self.OnPageClosing)
        self.Bind(FNB.EVT_FLATNOTEBOOK_PAGE_CLOSED, self.OnPageClosed)
        self.Bind(wx.stc.EVT_STC_CHANGE, self.OnUpdatePageText)
        self._pages.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self._pages.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDClick)
        self._pages.Bind(wx.EVT_MIDDLE_UP, self.OnMClick)
        self.Bind(FNB.EVT_FLATNOTEBOOK_PAGE_CONTEXT_MENU, self.OnTabMenu)
        self.Bind(wx.EVT_MENU, self.OnMenu)
        self.Bind(wx.EVT_IDLE, self.OnIdle)

        # Message handlers
        ed_msg.Subscribe(self.OnThemeChanged, ed_msg.EDMSG_THEME_CHANGED)
        ed_msg.Subscribe(self.OnThemeChanged, ed_msg.EDMSG_THEME_NOTEBOOK)
        ed_msg.RegisterCallback(self.OnDocPointerRequest, ed_msg.EDREQ_DOCPOINTER)

        # Add a blank page
        self.NewPage()

    #---- End Init ----#

    def __del__(self):
        ed_msg.Unsubscribe(self.OnThemeChanged)
        ed_msg.UnRegisterCallback(self.OnDocPointerRequest)

    #---- Function Definitions ----#
    def _HandleEncodingError(self, control):
        """Handle trying to reload the file the file with a different encoding
        Until it suceeds or gives up.
        @param control: stc
        @return: bool

        """
        # Loop while the load fails prompting to try a new encoding
        tried = None
        fname = control.GetFileName().strip(os.sep)
        fname = fname.split(os.sep)[-1]
        while True:
            doc = control.GetDocument()
            doc.ClearLastError()
            if tried is None:
                enc = doc.GetEncoding()
                if enc is None:
                    enc = ed_txt.DEFAULT_ENCODING
            else:
                enc = tried

            msg = _("The correct encoding of '%s' could not be determined.\n\n"
                    "Choose an encoding and select Ok to open the file with the chosen encoding.\n"
                    "Click Cancel to abort opening the file") % fname

            # On some systems it seems that default encoding ends up being
            # None so default to utf-8 for choices.
            if enc is None:
                enc = 'utf_8'

            dlg = eclib.EncodingDialog(self, msg=msg,
                                        title=_("Choose an Encoding"),
                                        default=enc)
            bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_DOCPROP),
                                           wx.ART_OTHER)
            if bmp.IsOk():
                dlg.SetBitmap(bmp)
            dlg.CenterOnParent()
            result = dlg.ShowModal()
            enc = dlg.GetEncoding()
            dlg.Destroy()

            # Don't want to open it in another encoding
            if result == wx.ID_CANCEL:
                return False
            else:
                control.SetEncoding(enc)
                tried = enc
                ok = control.LoadFile(control.GetFileName())
                if ok:
                    return True
                else:
                    # Artifically add a short pause, because if its not there
                    # the dialog will be shown again so fast it wont seem
                    # like reloading the file was even tried.
                    wx.Sleep(1)

    def _NeedOpen(self, path):
        """Check if a file needs to be opened. If the file is already open in
        the notebook a dialog will be opened to ask if the user wants to reopen
        the file again. If the file is not open and exists or the user chooses
        to reopen the file again the function will return True else it will
        return False.
        @param path: file to check for
        @return: bool

        """
        result = wx.ID_YES
        if self.HasFileOpen(path):
            mdlg = wx.MessageDialog(self,
                                    _("File is already open in an existing "
                                      "page.\nDo you wish to open it again?"),
                                    _("Open File") + u"?",
                                    wx.YES_NO | wx.NO_DEFAULT | \
                                    wx.ICON_INFORMATION)
            result = mdlg.ShowModal()
            mdlg.Destroy()
            if result == wx.ID_NO:
                self.GotoPage(path)
        elif os.path.exists(path) and not os.path.isfile(path):
            result = wx.ID_NO
        else:
            pass

        return result == wx.ID_YES

    def AddPage(self, page, text=u'', select=True, imgId=-1):
        """Add a page to the notebook"""
        if not len(text):
            self.pg_num += 1
            text = _("Untitled - %d") % self.pg_num
        page.SetTabLabel(text)
        super(EdPages, self).AddPage(page, text, select, imgId)
        sel = self.GetSelection()
        self.EnsureVisible(sel)
        self.UpdateIndexes()

    def DocDuplicated(self, path):
        """Check for if the given path is open elswhere and duplicate the
        docpointer.
        @param path: string

        """
        doc = ed_msg.RequestResult(ed_msg.EDREQ_DOCPOINTER, [self, path])
        if hasattr(doc, 'GetDocPointer'):
            self.OpenDocPointer(doc.GetDocPointer(), doc.GetDocument())
            return True
        else:
            return False

    def GetCurrentCtrl(self):
        """Returns the control of the currently selected
        page in the notebook.
        @return: window object contained in current page or None

        """
        if hasattr(self, 'control'):
            return self.control
        else:
            return None

    def GetFileNames(self):
        """Gets the name of all open files in the notebook
        @return: list of file names

        """
        rlist = list()
        for buff in self.GetTextControls():
            fname = buff.GetFileName()
            if fname != wx.EmptyString:
                rlist.append(fname)
        return rlist

    def GetFindDialog(self):
        """Get the active find dialog or None if one is not active
        @return: FindDialog or None

        """
        return self._searchctrl.GetDialog()

    def GetMenuHandlers(self):
        """Get the (id, evt_handler) tuples that this window should
        handle.
        @return: list of tuples

        """
        rlist = [(ed_glob.ID_FIND, self._searchctrl.OnShowFindDlg),
                 (ed_glob.ID_FIND_REPLACE, self._searchctrl.OnShowFindDlg),
                 (ed_glob.ID_FIND_NEXT, self._searchctrl.OnFind),
                 (ed_glob.ID_FIND_PREVIOUS, self._searchctrl.OnFind),
                 (ed_glob.ID_FIND_SELECTED, self._searchctrl.OnFindSelected)]
        return rlist

    def GetUiHandlers(self):
        """Get the update ui handlers that this window supplies
        @return: list of tuples

        """
        return [(ed_glob.ID_FIND_NEXT, self._searchctrl.OnUpdateFindUI),
                (ed_glob.ID_FIND_PREVIOUS, self._searchctrl.OnUpdateFindUI)]

    def InsertPage(self, index, page, text, select=True, imageId=-1):
        """Insert a page into the notebook"""
        super(EdPages, self).InsertPage(index, page, text, select, imageId)
        self.UpdateIndexes()

    def SaveSessionFile(self, session):
        """Save the current open files to the given session file
        @param session: path to session file
        @return: tuple (error desc, error msg) or None

        """
        try:
            f_handle = open(session, 'wb')
        except (IOError, OSError), msg:
            return (_("Error Loading Session File"),  unicode(msg))

        try:
            sdata = dict(win1=self.GetFileNames())
            cPickle.dump(sdata, f_handle)
        finally:
            f_handle.close()

        return None

    def LoadSessionFile(self, session):
        """Load files from saved session data in profile
        @param session: session filename
        @return: tuple (error desc, error msg), or None if no error

        """
        self._ses_load = True

        if os.path.exists(session):
            try:
                f_handle = open(session)
            except IOError:
                f_handle = None
        else:
            f_handle = None

        # Invalid file
        if f_handle is None:
            return (_("Invalid File"), _("Session file doesn't exist."))

        # Load and validate file
        try:
            try:
                flist = cPickle.load(f_handle)
                # TODO: Extend in future to support loading sessions
                #       for mutiple windows.
                flist = flist.get('win1', list()) 
                for item in flist:
                    if type(item) not in (unicode, str):
                        raise TypeError('Invalid item in unpickled sequence')
            except (cPickle.UnpicklingError, TypeError), e:
                dlg.Destroy()
                return (_('Invalid file'),
                        _('Selected file is not a valid session file'))
        finally:
            f_handle.close()

        if not len(flist):
            return (_("Empty File"), _("Session file is empty."))

        # Close current files
        self.CloseAllPages()

        missingfns = []
        for loadfn in flist:
            if os.path.exists(loadfn) and os.access(loadfn, os.R_OK):
                self.OpenPage(os.path.dirname(loadfn),
                              os.path.basename(loadfn))
                # Give feedback as files are loaded
                self.Update()
            else:
                missingfns.append(loadfn)
                
        if missingfns:
            rmsg = (_("Missing session files"),
                    _("Some files in saved session could not be found on disk:\n")+
                    u'\n'.join(missingfns))
            return rmsg

        self._ses_load = False

        if self.GetPageCount() == 0:
            self.NewPage()

        return None

    def NewPage(self):
        """Create a new notebook page with a blank text control
        @postcondition: a new page with an untitled document is opened

        """
        self.Freeze()
        self.control = ed_editv.EdEditorView(self, wx.ID_ANY)
        self.control.SetEncoding(Profile_Get('ENCODING'))
        self.LOG("[ed_pages][evt] New Page Created ID: %d" % self.control.GetId())
        self.AddPage(self.control)
        self.SetPageImage(self.GetSelection(), str(self.control.GetLangId()))

        # Set the control up the the preferred default lexer
        dlexer = Profile_Get('DEFAULT_LEX', 'str', 'Plain Text')
        ext_reg = syntax.ExtensionRegister()
        ext_lst = ext_reg.get(dlexer, ['txt', ])
        self.control.FindLexer(ext_lst[0])

        # Set the modified callback notifier
        doc = self.control.GetDocument()
        doc.AddModifiedCallback(self.control.FireModified)

        self.Thaw()

    def OnMenu(self, evt):
        """Handle context menu events
        @param evt: wx.MenuEvent

        """
        ctab = self.GetCurrentPage()
        if ctab is not None:
            ctab.OnTabMenu(evt)
        else:
            evt.Skip()

    def OnDocPointerRequest(self, args):
        """Get a buffer that has the same file open as the requested path.
        @param args: [sender, path]
        @return: EdEditorView reference or ed_msg.NullValue

        """
        sender, path = args
        if sender != self:
            for buf in self.GetTextControls():
                if buf.GetFileName() == path:
                    return buf

        return ed_msg.NullValue()

    def OnLeftDClick(self, evt):
        """Handle left double clicks and open new tab when in empty area.
        @param evt: wx.EVT_LEFT_DCLICK

        """
        where, tabIdx = self._pages.HitTest(evt.GetPosition())
        if where == FNB.FNB_NOWHERE:
            self.NewPage()
        elif where == FNB.FNB_TAB:
            # Maximize Editor
            self.GetTopLevelParent().OnMaximizeEditor(None)
        else:
            evt.Skip()

    def OnMClick(self, evt):
        """Handle tab middle click event
        @param evt: wx.MouseEvent

        """
        where, tabIdx = self._pages.HitTest(evt.GetPosition())
        if where in (FNB.FNB_TAB, FNB.FNB_TAB_X):
            # If the click is on the tab, make sure the tab is selected
            # then close it.
            self.SetSelection(tabIdx)
            self.ClosePage()
        else:
            evt.Skip()

    def OnTabMenu(self, evt):
        """Show the tab context menu"""
        # Destroy any existing menu
        if self._menu is not None:
            self._menu.Destroy()
            self._menu = None

        # Construct the menu
        ctab = self.GetCurrentPage()
        if ctab is not None:
            self._menu = ctab.GetTabMenu()

        if self._menu is not None:
            self.PopupMenu(self._menu)

    def OnThemeChanged(self, msg):
        """Update icons when the theme has changed
        @param msg: Message Object

        """
        self.UpdateAllImages()

    def OpenDocPointer(self, ptr, doc, title=u''):
        """Open a page using an stc document poiner
        @param ptr: EdEditorView document Pointer
        @param doc: EdFile instance
        @keyword title: tab title

        """
        self.GetTopLevelParent().Freeze()
        nbuff = self.GetCurrentPage()
        need_add = False
        if nbuff.GetFileName() or nbuff.GetLength():
            need_add = True
            nbuff = ed_editv.EdEditorView(self)

        nbuff.SetDocPointer(ptr)
        nbuff.SetDocument(doc)
        doc.AddModifiedCallback(nbuff.FireModified)
        nbuff.FindLexer()

        path = nbuff.GetFileName()
        if Profile_Get('SAVE_POS'):
            pos = self.DocMgr.GetPos(path)
            nbuff.GotoPos(pos)
            nbuff.ScrollToColumn(0)

        if title:
            filename = title
        else:
            filename = ebmlib.GetFileName(path)

        if need_add:
            self.AddPage(nbuff, filename)
        else:
            self.SetPageText(self.GetSelection(), filename)

        self.frame.SetTitle(nbuff.GetTitleString())
        self.LOG("[ed_pages][evt] Opened Page: %s" % filename)

        # Set tab image
        # TODO: Handle read only images
        self.SetPageImage(self.GetSelection(), str(nbuff.GetLangId()))

        # Refocus on selected page
        self.control = nbuff
        self.GoCurrentPage()
        self.GetTopLevelParent().Thaw()
        ed_msg.PostMessage(ed_msg.EDMSG_FILE_OPENED, nbuff.GetFileName())

    def OpenFileObject(self, fileobj):
        """Open a new text editor page with the given file object. The file
        object must be an instance of ed_txt.EdFile.
        @param fileobj: File Object

        """
        # Create the control
        self.GetTopLevelParent().Freeze()
        control = ed_editv.EdEditorView(self, wx.ID_ANY)
        control.Hide()

        # Load the files data
        path = fileobj.GetPath()
        filename = ebmlib.GetFileName(path)
        control.SetDocument(fileobj)
        result = control.ReloadFile()

        # Setup the buffer
        fileobj.AddModifiedCallback(control.FireModified)

        # Setup the notebook
        self.control = control
        self.control.FindLexer()
        self.control.EmptyUndoBuffer()
        self.control.Show()
        self.AddPage(self.control, filename)

        self.frame.SetTitle(self.control.GetTitleString())
        self.frame.AddFileToHistory(path)
        self.SetPageText(self.GetSelection(), filename)
        self.LOG("[ed_pages][evt] Opened Page: %s" % filename)

        # Set tab image
        cpage = self.GetSelection()
        if fileobj.ReadOnly:
            super(EdPages, self).SetPageImage(cpage,
                                              self._index[ed_glob.ID_READONLY])
        else:
            self.SetPageImage(cpage, str(self.control.GetLangId()))

        self.GetTopLevelParent().Thaw()

        # Refocus on selected page
        self.GoCurrentPage()
        ed_msg.PostMessage(ed_msg.EDMSG_FILE_OPENED, self.control.GetFileName())

        if Profile_Get('WARN_EOL', default=True):
            self.control.CheckEOL()

    def OpenPage(self, path, filename, quiet=False):
        """Open a File Inside of a New Page
        @param path: files base path
        @param filename: name of file to open
        @keyword quiet: Open/Switch to the file quietly if
                        it is already open.

        """
        path2file = os.path.join(path, filename)

        # Resolve links to real file
        if ebmlib.IsLink(path2file):
            path2file = ebmlib.ResolveRealPath(path2file)
            path = ebmlib.GetPathName(path2file)
            filename = ebmlib.GetFileName(path2file)

        if self.DocDuplicated(path2file):
            return

        # Check if file needs to be opened
        # TODO: these steps could be combined together with some
        #       refactoring of the _NeedOpen method. Requires extra
        #       testing though to check for dependancies on current
        #       behavior.
        if quiet and self.HasFileOpen(path2file):
            self.GotoPage(path2file)
            return
        elif not self._NeedOpen(path2file):
            return

        # Create new control to place text on if necessary
        self.GetTopLevelParent().Freeze()
        new_pg = True
        if self.GetPageCount():
            if self.control.GetModify() or self.control.GetLength() or \
               self.control.GetFileName() != u'':
                control = ed_editv.EdEditorView(self, wx.ID_ANY)
                control.Hide()
            else:
                new_pg = False
                control = self.control
        else:
            control = ed_editv.EdEditorView(self, wx.ID_ANY)
            control.Hide()

        # Open file and get contents
        result = False
        if os.path.exists(path2file):
            try:
                result = control.LoadFile(path2file)
            except Exception, msg:
                self.LOG("[ed_pages][err] Failed to open file %s\n" % path2file)
                self.LOG("[ed_pages][err] %s" % msg)

                # File could not be opened/read give up
                # Don't raise a dialog during a session load error as if the
                # dialog is shown before the mainwindow is ready it can cause
                # the app to freeze.
                if not self._ses_load:
                    ed_mdlg.OpenErrorDlg(self, path2file, msg)
                control.GetDocument().ClearLastError()
                control.SetFileName('') # Reset the file name

                if new_pg:
                    control.Destroy()

                self.GetTopLevelParent().Thaw()
                return
        else:
            control.SetFileName(path2file)
            result = True

        # Check if there was encoding errors
        if not result and not self._ses_load:
            result = self._HandleEncodingError(control)

        # Cleanup after errors
        if not result:
            if new_pg:
                # We created a new one so destroy it
                control.Destroy()
            else:
                # We where using an existing buffer so reset it
                "CLEARED IT"
                control.SetText('')
                control.SetDocument(ed_txt.EdFile())
                control.SetSavePoint()

            self.GetTopLevelParent().Thaw()
            return

        # Put control into page an place page in notebook
        if new_pg:
            control.Show()
            self.control = control

        # Setup Document
        self.control.FindLexer()
        self.control.EmptyUndoBuffer()
        doc = self.control.GetDocument()
        doc.AddModifiedCallback(self.control.FireModified)

        # Add the buffer to the notebook
        if new_pg:
            self.AddPage(self.control, filename)

        self.frame.SetTitle(self.control.GetTitleString())
        self.frame.AddFileToHistory(path2file)
        self.SetPageText(self.GetSelection(), filename)

        # Set tab image
        cpage = self.GetSelection()
        if doc.ReadOnly:
            super(EdPages, self).SetPageImage(cpage,
                                              self._index[ed_glob.ID_READONLY])
        else:
            self.SetPageImage(cpage, str(self.control.GetLangId()))

        if Profile_Get('WARN_EOL', default=True):
            self.control.CheckEOL()

        if not control.IsLoading():
            self.DoPostLoad()

        # Refocus on selected page
        self.GoCurrentPage()
        self.GetTopLevelParent().Thaw()
        self.LOG("[ed_pages][evt] Opened Page: %s" % filename)

    def DoPostLoad(self):
        """Perform post file open actions"""
        if Profile_Get('SAVE_POS'):
            pos = self.DocMgr.GetPos(self.control.GetFileName())
            self.control.GotoPos(pos)
            self.control.ScrollToColumn(0)

        ed_msg.PostMessage(ed_msg.EDMSG_FILE_OPENED, self.control.GetFileName())

    def GoCurrentPage(self):
        """Move Focus to Currently Selected Page.
        @postcondition: focus is set to current page

        """
        current_page = self.GetSelection()
        if current_page < 0:
            return current_page

        control = self.GetPage(current_page)
        control.SetFocus()
        self.control = control
        return current_page

    def GotoPage(self, fname):
        """Go to the page containing the buffer with the given file.
        @param fname: file path (string)

        """
        for page in xrange(self.GetPageCount()):
            ctrl = self.GetPage(page)
            if fname == ctrl.GetFileName():
                self.ChangePage(page)
                break

    def GetPageText(self, pg_num):
        """Gets the tab text from the given page number, stripping
        the * mark if there is one.
        @param pg_num: index of page to get tab text from
        @return: the tabs text

        """
        # Often times this raises an index error in the flatnotebook code
        # even though the pg_num here is one that is obtained by calling
        # GetSelection which should return a valid index.
        try:
            txt = super(EdPages, self).GetPageText(pg_num)
        except IndexError:
            txt = ''

        if not txt or txt[0] != u"*":
            return txt
        return txt[1:]

    def GetRawPageText(self, pg_num):
        """Get the unformatted raw page text
        @param pg_num: int
        @return: string

        """
        try:
            txt = super(EdPages, self).GetPageText(pg_num)
        except IndexError:
            txt = ''
        return txt

    def ImageIsReadOnly(self, index):
        """Does the given page currently have a ReadOnly Image
        shown on it?
        @return: bool

        """
        return self.GetPageImage(index) == self._index[ed_glob.ID_READONLY]

    def SetPageText(self, pg_num, txt):
        """Set the pages tab text
        @param pg_num: page index
        @param txt: string

        """
        super(EdPages, self).SetPageText(pg_num, txt)
        page = self.GetPage(pg_num)
        page.SetTabLabel(txt)

    def GetTextControls(self):
        """Gets all the currently opened text controls
        @return: list containing reference to all stc controls opened in the
                 notebook.

        """
        pages = [self.GetPage(page) for page in xrange(self.GetPageCount())]
        return [page for page in pages if page.GetName() == "EditraTextCtrl"]

    def HasFileOpen(self, fpath):
        """Checks if one of the currently active buffers has
        the named file in it.
        @param fpath: full path of file to check
        @return: bool indicating whether file is currently open or not

        """
        for ctrl in self.GetTextControls():
            if fpath == ctrl.GetFileName():
                return True
        return False

    #---- Event Handlers ----#
    def OnDrop(self, files):
        """Opens dropped files
        @param files: list of file paths
        @postcondition: all files that could be properly opend are added to
                        the notebook

        """
        # Check file properties and make a "clean" list of file(s) to open
        valid_files = list()
        for fname in files:
            self.LOG("[ed_pages][evt] File(s) Dropped: %s" % fname)
            if not os.path.exists(fname):
                self.frame.PushStatusText(_("Invalid file: %s") % fname, \
                                          ed_glob.SB_INFO)
            elif os.path.isdir(fname):
                dcnt = glob.glob(os.path.join(fname, '*'))
                dcnt = util.FilterFiles(dcnt)
                dlg = None
                if not len(dcnt):
                    dlg = wx.MessageDialog(self,
                                           _("There are no files that Editra"
                                             " can open in %s") % fname,
                                           _("No Valid Files to Open"),
                                           style=wx.OK | wx.CENTER | \
                                                 wx.ICON_INFORMATION)
                elif len(dcnt) > 5:
                    # Warn when the folder contains many files
                    dlg = wx.MessageDialog(self,
                                           _("Do you wish to open all %d files"
                                             " in this directory?\n\nWarning:"
                                             " opening many files at once may"
                                             " cause the editor to temporarily "
                                             " freeze.") % len(dcnt),
                                           _("Open Directory?"),
                                           style=wx.YES | wx.NO | \
                                                 wx.ICON_INFORMATION)
                if dlg is not None:
                    result = dlg.ShowModal()
                    dlg.Destroy()
                else:
                    result = wx.ID_YES

                if result == wx.ID_YES:
                    valid_files.extend(dcnt)
                else:
                    pass
            else:
                valid_files.append(fname)

        for fname in valid_files:
            pathname = ebmlib.GetPathName(fname)
            the_file = ebmlib.GetFileName(fname)
            self.OpenPage(pathname, the_file)
            self.frame.PushStatusText(_("Opened file: %s") % fname, \
                                      ed_glob.SB_INFO)
        return

    def OnIdle(self, evt):
        """Update tabs and check if files have been modified
        @param evt: Event that called this handler
        @type evt: wx.IdleEvent

        """
        if wx.GetApp().IsActive():
            page = self.GetCurrentPage()
            if page is not None:
                page.DoOnIdle()

#            # Update document indicator state
#            if hasattr(page, 'GetDocument'):
#                doc = page.GetDocument()
#                sel = self.GetSelection()
#                img = self.GetPageImage(sel)
#                roidx = self._index[ed_glob.ID_READONLY]
#                if doc.ReadOnly and img != roidx:
#                    FNB.FlatNotebook.SetPageImage(sel, roidx)

    def OnLeftUp(self, evt):
        """Traps clicks sent to page close buttons and
        redirects the action to the ClosePage function
        @param evt: Event that called this handler
        @type evt: wx.MouseEvent

        """
        cord = self._pages.HitTest(evt.GetPosition())[0]
        if cord == FNB.FNB_X:
            # Make sure that the button was pressed before
            if self._pages._nXButtonStatus != FNB.FNB_BTN_PRESSED:
                return
            self._pages._nXButtonStatus = FNB.FNB_BTN_HOVER
            self.ClosePage()
        elif cord == FNB.FNB_TAB_X:
            # Make sure that the button was pressed before
            if self._pages._nTabXButtonStatus != FNB.FNB_BTN_PRESSED:
                return
            self._pages._nTabXButtonStatus = FNB.FNB_BTN_HOVER
            self.ClosePage()
        else:
            evt.Skip()

    def OnPageChanging(self, evt):
        """Page changing event handler.
        @param evt: event that called this handler
        @type evt: flatnotebook.EVT_FLATNOTEBOOK_PAGE_CHANGING

        """
        evt.Skip()
        pages = (evt.GetOldSelection(), evt.GetSelection())
        self.LOG("[ed_pages][evt] Control Changing from Page: "
                  "%d to Page: %d\n" % pages)

        # Check if it has been destroyed already
        if isinstance(self.control, wx.Window):
            self.control.DoDeactivateTab()

        ed_msg.PostMessage(ed_msg.EDMSG_UI_NB_CHANGING, (self,) + pages)

    def ChangePage(self, pg_num, old=-2):
        """Change the page and focus to the the given page id
        @param pg_num: Page number to change
        @keyword old: previous selection

        """
        cpage = self.GetSelection()
        if cpage != pg_num:
            self.SetSelection(pg_num)

        # Get the window that is the current page
        window = self.GetPage(pg_num)
        window.SetFocus()
        self.control = window

        # Update Frame Title
        self.frame.SetTitle(self.control.GetTitleString())

        # Only post page changes when the change is not from the app exiting
        # NOTE: -2 is used as default value, cant use -1 as it comes from
        #       page close events.
        if old > -2:
            cpage = old

        if not self.frame.IsExiting() and cpage != pg_num:
            ed_msg.PostMessage(ed_msg.EDMSG_UI_NB_CHANGED, (self, pg_num))

    def OnPageChanged(self, evt):
        """Actions to do after a page change
        @param evt: event that called this handler
        @type evt: wx.lib.flatnotebook.EVT_FLATNOTEBOOK_PAGE_CHANGED

        """
        cpage = evt.GetSelection()
        self.ChangePage(cpage, old=evt.GetOldSelection())
        evt.Skip()
        self.LOG("[ed_pages][evt] Page Changed to %d" % cpage)
        
        # Call the tab specific selection handler
        page = self.GetCurrentPage()
        page.DoTabSelected()

        self.EnsureVisible(cpage)

    def OnPageClosing(self, evt):
        """Checks page status to flag warnings before closing
        @param evt: event that called this handler
        @type evt: wx.lib.flatnotebook.EVT_FLATNOTEBOOK_PAGE_CLOSING

        """
        self.LOG("[ed_pages][evt] Closing Page: #%d" % self.GetSelection())

        # Call the tab specific close handler
        page = self.GetCurrentPage()
        if page is not None:
            page.DoTabClosing()

        evt.Skip()
        ed_msg.PostMessage(ed_msg.EDMSG_UI_NB_CLOSING,
                           (self, self.GetSelection()))

    def OnPageClosed(self, evt):
        """Handles Paged Closed Event
        @param evt: event that called this handler
        @type evt: wx.lib.flatnotebook.EVT_FLATNOTEBOOK_PAGE_CLOSED

        """
        cpage = self.GetSelection()
        evt.Skip()
        self.LOG("[ed_pages][evt] Closed Page: #%d" % cpage)
        self.UpdateIndexes()
        ed_msg.PostMessage(ed_msg.EDMSG_UI_NB_CLOSED, (self, cpage))

    #---- End Event Handlers ----#

    def CloseAllPages(self):
        """Closes all open pages
        @postcondition: all pages in the notebook are closed

        """
        for page in xrange(self.GetPageCount()):
            if not self.ClosePage():
                break

    def ClosePage(self):
        """Closes Currently Selected Page
        @return: bool

        """
        frame = self.GetTopLevelParent()
        frame.Freeze()
        self.GoCurrentPage()
        page = self.GetCurrentPage()
        pg_num = self.GetSelection()
        result = page.CanCloseTab()

        if result:
            self.DeletePage(pg_num)
            self.GoCurrentPage()

        frame.Thaw()
        if not self.GetPageCount() and \
           hasattr(frame, 'IsExiting') and not frame.IsExiting():
            self.NewPage()
        return result

    def SetPageImage(self, pg_num, lang_id):
        """Sets the page image by querying the ArtProvider based
        on the language id associated with the type of open document.
        Any unknown filetypes are associated with the plaintext page
        image.
        @param pg_num: page index to set image for
        @param lang_id: language id of file type to get mime image for

        """
        # Only set icons when enabled in preferences
        if not Profile_Get('TABICONS'):
            return

        imglst = self.GetImageList()
        if lang_id not in self._index:
            bmp = wx.ArtProvider.GetBitmap(lang_id, wx.ART_MENU)
            if bmp.IsNull():
                self._index.setdefault(lang_id, \
                                       self._index[synglob.ID_LANG_TXT])
            else:
                self._index[lang_id] = imglst.Add(wx.ArtProvider.\
                                              GetBitmap(lang_id, wx.ART_MENU))
        super(EdPages, self).SetPageImage(pg_num, self._index[lang_id])

    def UpdateAllImages(self):
        """Reload and Reset all images in the notebook pages and
        the corresponding imagelist to match those of the current theme
        @postcondition: all images in control are updated

        """
        # If icons preference has been disabled then clear all icons
        if not Profile_Get('TABICONS'):
            for page in xrange(self.GetPageCount()):
                super(EdPages, self).SetPageImage(page, -1)
        else:
            # Reload the image list with new icons from the ArtProvider
            imglst = self.GetImageList()
            for lang, index in self._index.iteritems():
                bmp = wx.ArtProvider.GetBitmap(str(lang), wx.ART_MENU)
                if bmp.IsNull():
                    self._index.setdefault(lang, \
                                           self._index[synglob.ID_LANG_TXT])
                else:
                    imglst.Replace(index, bmp)

            for page in xrange(self.GetPageCount()):
                self.SetPageImage(page, str(self.GetPage(page).GetLangId()))

        self.Refresh()

    def UpdateIndexes(self):
        """Update all page indexes"""
        pages = [self.GetPage(page) for page in xrange(self.GetPageCount())]
        for idx, page in enumerate(pages):
            page.SetTabIndex(idx)

    def UpdatePageImage(self):
        """Updates the page tab image
        @postcondition: page image is updated to reflect any changes in ctrl

        """
        self.SetPageImage(self.GetSelection(), str(self.control.GetLangId()))

    def OnUpdatePageText(self, evt):
        """Update the title text of the current page
        @param evt: event that called this handler
        @type evt: stc.EVT_STC_MODIFY (unused)
        @note: this method must complete its work very fast it gets
               called everytime a character is entered or removed from
               the document.

        """
        try:
            e_id = evt.GetId()
            if self.control.GetId() == e_id:
                pg_num = self.GetSelection()
                title = self.GetPageText(pg_num)
                if self.control.GetModify():
                    title = u"*" + title

                # Only Update if the text has changed
                if title != super(EdPages, self).GetPageText(pg_num):
                    self.SetPageText(pg_num, title)
                    ftitle = self.control.GetTitleString()
                    self.frame.SetTitle(ftitle)
            else:
                # A background page has changed
                for page in range(self.GetPageCount()):
                    control = self.GetPage(page)
                    if control.GetId() == e_id:
                        title = self.GetPageText(page)
                        if control.GetModify():
                            title = u"*" + title
                        if title != super(EdPages, self).GetPageText(page):
                            self.SetPageText(page, title)
        except wx.PyDeadObjectError:
            pass

    def UpdateTextControls(self, meth=None, args=list()):
        """Updates all text controls to use any new settings that have
        been changed since initialization.
        @postcondition: all stc controls in the notebook are reconfigured
                        to match profile settings

        """
        for control in self.GetTextControls():
            if meth is not None:
                getattr(control, meth)(*args)
            else:
                control.UpdateAllStyles()
                control.Configure()

#---- End Function Definitions ----#
