# Copyright 2004,2005 Pierre Martineau <pmartino@users.sourceforge.net>
# This file is part of Bibus, a bibliographic database that can
# work together with OpenOffice.org to generate bibliographic indexes.
#
# Bibus is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Bibus is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Bibus; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA.
#
# generated by wxGlade 0.2 on Sun Jan 19 17:05:17 2003

import wx
import webbrowser, sys, os, cPickle,copy, StringIO, shutil, imp, csv
import BIB, DnD, RefEditor, SearchMedline, Search, myToolBar, Pref, ImportFrame, RefList, KeyTree, Multi_KeyTree, StyleEditor.Styleconverter, Export.html, display_panel, time
import CodecChoice, codecs
###Mounir Errami Imports
import SearcheTBlast

class BibFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        # importing the necessary connection module
        self.__loadConnectionModule()
        # default allowed actions for menus
        self.allowed = BIB.ALLOWED['rw']
        # for icons in Menu
        ap = wx.ArtProvider()
        #
        self.IdFileConnect = wx.NewId()
        self.IdFileImport = wx.NewId()
        self.IdFileImportText = wx.NewId()
        self.IdFileImportInstall = wx.NewId()
        # We load Import filters dynamically
        self.IdFileImportFilters = {}
        for fn in os.listdir(os.path.join(BIB.SOURCEDIR,'Import')):
            if fn.endswith('.py') and not fn.startswith('__'):
                self.IdFileImportFilters[wx.NewId()] = os.path.splitext(fn)[0],True
        for fn in os.listdir( os.path.join(BIB.CONFIG.getFilePath(),'Import') ):
            if fn.endswith('.py'):
                self.IdFileImportFilters[wx.NewId()] = os.path.splitext(fn)[0],False
        #  Idem for Export filters
        self.IdFileExportFilters = {}
        self.IdFileExport = wx.NewId()
        self.IdFileExportSQLite = wx.NewId()
        self.IdFileExportHtml = wx.NewId()
        self.IdFileExportInstall = wx.NewId()
        for fn in os.listdir(os.path.join(BIB.SOURCEDIR,'Export')):
            if fn.endswith('.py') and not fn.startswith('__') and fn != 'html.py':
                self.IdFileExportFilters[wx.NewId()] = os.path.splitext(fn)[0],True
        for fn in os.listdir( os.path.join(BIB.CONFIG.getFilePath(),'Export') ):
            if fn.endswith('.py'):
                self.IdFileExportFilters[wx.NewId()] = os.path.splitext(fn)[0],False
        #
        self.IdDownloadFilter = wx.NewId()    # Used to download Import/Export filters
        #
        self.IdFilePageSetup = wx.NewId()
        self.IdFilePrintPreview = wx.NewId()
        self.IdFilePrint = wx.NewId()
        self.IdFileQuit = wx.NewId()
        #
        self.IdCopy = wx.NewId()
        self.IdCut = wx.NewId()
        self.IdPaste = wx.NewId()
        self.IdSelectAll = wx.NewId()
        self.IdPref = wx.NewId()
        self.IdCleanDB = wx.NewId()
        #
        self.IdAddChild = wx.NewId()
        self.IdNewRef = wx.NewId()
        self.IdEditRef = wx.NewId()
        self.IdDelRef = wx.NewId()
        self.IdTagRef = wx.NewId()
        self.IdDupRef = wx.NewId()
        self.IdPubMedSearch = wx.NewId()
        self.IdeTBlastSearch = wx.NewId()
        self.IdSearch = wx.NewId()
        self.IdDoBackup = wx.NewId()
        self.IdDoRestore = wx.NewId()
        self.IdSwitchOOo = wx.NewId()
        self.IdShowLicense = wx.NewId()
        self.IdShowHelp = wx.NewId()
        self.IdShowWebSite = wx.NewId()
        self.IdFirstTimeWizard = wx.NewId()
        self.IdShowAbout = wx.NewId()
        #
        self.db = None            # dbBib object to access database
        # begin wx.Glade: BibFrame.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        kwds["size"] = (BIB.WIDTH,BIB.HEIGHT)
        kwds["pos"] = (BIB.WX,BIB.WY)
        wx.Frame.__init__(self, *args, **kwds)
        self.window_1 = wx.SplitterWindow(self, -1)
        self.window_1.SetMinimumPaneSize(1)
        self.window_1_pane_2 = wx.Panel(self.window_1, -1)
        self.window_2 = wx.SplitterWindow(self.window_1_pane_2, -1)
        self.window_2.SetMinimumPaneSize(2)
        self.window_2_pane_2 = wx.Panel(self.window_2, -1)
        self.window_2_pane_1 = wx.Panel(self.window_2, -1)
        
        # Setting keytree
        self.__CreateKeyTree()
        #
        self.bibframe1_statusbar = self.CreateStatusBar(3)

        # Menu Bar
        self.bibframe1_menubar = wx.MenuBar()
        self.SetMenuBar(self.bibframe1_menubar)
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(self.IdFileConnect, _("Connect"), _("Connect to database"))
        wxglade_tmp_menu.AppendSeparator()
        wxglade_tmp_menu_sub = wx.Menu()
        wxglade_tmp_menu_sub.Append(self.IdFileImportText, _("Text Window"), _("Import a text file"))
        for menuid,(fn,flag) in self.IdFileImportFilters.iteritems():
            wxglade_tmp_menu_sub.Append(menuid,fn)
        wxglade_tmp_menu_sub.AppendSeparator()
        wxglade_tmp_menu_sub.Append(self.IdDownloadFilter,_("Get new filters ..."))
        wxglade_tmp_menu_sub.Append(self.IdFileImportInstall,_("Install a new filter ..."))
        wxglade_tmp_menu.AppendMenu(self.IdFileImport, _("Import"), wxglade_tmp_menu_sub, _("Import a file"))
        wxglade_tmp_menu_sub = wx.Menu()
        wxglade_tmp_menu_sub.Append(self.IdFileExportSQLite, _("SQLite"), _("Export to a SQLite database"))
        wxglade_tmp_menu_sub.Append(self.IdFileExportHtml, _("HTML"), _("Export to a HTML file"))
        for menuid,(fn,flag) in self.IdFileExportFilters.iteritems():
            wxglade_tmp_menu_sub.Append(menuid,fn)
        wxglade_tmp_menu_sub.AppendSeparator()
        wxglade_tmp_menu_sub.Append(self.IdDownloadFilter,_("Get new filters ..."))
        wxglade_tmp_menu_sub.Append(self.IdFileExportInstall,_("Install a new filter ..."))
        wxglade_tmp_menu.AppendMenu(self.IdFileExport, _("Export"), wxglade_tmp_menu_sub, _("Export a file"))
        wxglade_tmp_menu.AppendSeparator()
        # wxglade_tmp_menu.Append(self.IdDoBackup,_("Archive user data"), u"Back up all locally stored user styles, databases and settings to a single archive file")
        # wxglade_tmp_menu.Append(self.IdDoRestore,_("Restore user data from archive"), u"Retrieve user styles, databases and settings from an archive file")
        # wxglade_tmp_menu.AppendSeparator()
        wxglade_tmp_menu.Append(self.IdFilePageSetup, _("Page Setup"), _("Set printer page format"))
        wxglade_tmp_menu.Append(self.IdFilePrintPreview, _("Preview ..."), _("Preview printing"))
        item = wx.MenuItem(wxglade_tmp_menu,self.IdFilePrint,_("Print ...")+"\tCtrl-%s"%BIB.KEY_PRINT,help=_("Print references"))
        item.SetBitmap(ap.GetBitmap(wx.ART_PRINT,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdFilePrint, _("Print ...")+"\tCtrl-%s"%BIB.KEY_PRINT, _("Print references"))
        wxglade_tmp_menu.AppendSeparator()
        item = wx.MenuItem(wxglade_tmp_menu,self.IdFileQuit,_("Quit")+"\tCtrl-%s"%BIB.KEY_QUIT,help=_("Quit Bibus"))
        item.SetBitmap(ap.GetBitmap(wx.ART_QUIT,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)            
        #wxglade_tmp_menu.Append(self.IdFileQuit, _("Quit")+"\tCtrl-%s"%BIB.KEY_QUIT, _("Quit Bibus"))
        self.bibframe1_menubar.Append(wxglade_tmp_menu, _("File"))
        wxglade_tmp_menu = wx.Menu()
        item = wx.MenuItem(wxglade_tmp_menu,self.IdCopy,_("Copy")+"\tCtrl-%s"%BIB.KEY_COPY)
        item.SetBitmap(ap.GetBitmap(wx.ART_COPY,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdCopy, _("Copy")+"\tCtrl-%s"%BIB.KEY_COPY, u"")
        #
        item = wx.MenuItem(wxglade_tmp_menu,self.IdCut,_("Cut")+"\tCtrl-%s"%BIB.KEY_CUT)
        item.SetBitmap(ap.GetBitmap(wx.ART_CUT,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdCut, _("Cut")+"\tCtrl-%s"%BIB.KEY_CUT, u"")
        item = wx.MenuItem(wxglade_tmp_menu,self.IdPaste,_("Paste")+"\tCtrl-%s"%BIB.KEY_PASTE)
        item.SetBitmap(ap.GetBitmap(wx.ART_PASTE,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdPaste, _("Paste")+"\tCtrl-%s"%BIB.KEY_PASTE, u"")
        wxglade_tmp_menu_sub = wx.Menu()
        for fn in os.listdir(os.path.join(BIB.SOURCEDIR,'Export')):
            if fn.endswith('.py') and not fn.startswith('__') and fn != 'html.py':
                item = wxglade_tmp_menu_sub.AppendRadioItem(wx.NewId(),os.path.splitext(fn)[0])
                wx.EVT_MENU(self,item.GetId(),self.onClipboardFormat)
                if item.GetItemLabelText() == BIB.TEXT_CLIPBOARD: item.Check()
        #for fn in os.listdir( os.path.join(BIB.CONFIG.getFilePath(),'Export') ):
        #    if fn.endswith('.py'):
        #        wxglade_tmp_menu_sub.AppendRadioItem(wx.NewId(),os.path.splitext(fn)[0])
        wxglade_tmp_menu.AppendMenu(wx.NewId(), _("Copy format"), wxglade_tmp_menu_sub, _("Switch text clipboard format"))
        #
        wxglade_tmp_menu.AppendSeparator()
        wxglade_tmp_menu.Append(self.IdSelectAll, _("Select All")+"\tCtrl-%s"%BIB.KEY_SELECT_ALL, u"")
        wxglade_tmp_menu.AppendSeparator()
        item = wx.MenuItem(wxglade_tmp_menu,self.IdPref,_("Preferences"),help=_("Set some preferences"))
        item.SetBitmap(ap.GetBitmap(wx.ART_HELP_SETTINGS,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdPref, _("Preferences"), _("Set some preferences"))
        self.bibframe1_menubar.Append(wxglade_tmp_menu, _("Edit"))
        wxglade_tmp_menu = wx.Menu()
        item = wx.MenuItem(wxglade_tmp_menu,self.IdAddChild,_("Add child"),help=_("Add a child to the selected key"))
        item.SetBitmap(ap.GetBitmap(wx.ART_ADD_BOOKMARK,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdAddChild, _("Add child"), _("Add a child to the selected key"))
        wxglade_tmp_menu.AppendSeparator()
        item = wx.MenuItem(wxglade_tmp_menu,self.IdNewRef,_("New reference")+"\tCtrl-%s"%BIB.KEY_NEW,help=_("Add a reference associated with the selected key"))
        item.SetBitmap(ap.GetBitmap(wx.ART_NEW,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdEditRef, _("New reference")+"\tCtrl-%s"%BIB.KEY_NEW, _("Add a reference associated with the selected key"))
        item = wx.MenuItem(wxglade_tmp_menu,self.IdEditRef,_("Edit reference"),help=_("Edit the selected reference"))
        item.SetBitmap(ap.GetBitmap(wx.ART_EXECUTABLE_FILE,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdEditRef, _("Edit reference"), _("Edit the selected reference"))
        item = wx.MenuItem(wxglade_tmp_menu,self.IdDelRef,_("Delete reference")+"\tCtrl-%s"%BIB.KEY_DEL,help=_("Delete the selected reference"))
        item.SetBitmap(ap.GetBitmap(wx.ART_DELETE,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdDelRef, _("Delete reference")+"\tCtrl-%s"%BIB.KEY_DEL, _("Delete the selected reference"))
        item = wx.MenuItem(wxglade_tmp_menu,self.IdTagRef,_("Tag reference")+"\tCtrl-%s"%BIB.KEY_TAG,help=_("Mark the selected reference"))
        item.SetBitmap(ap.GetBitmap(wx.ART_TICK_MARK,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdTagRef, _("Tag reference")+"\tCtrl-%s"%BIB.KEY_TAG, _("Tag the selected reference"))
        wxglade_tmp_menu.Append(self.IdDupRef, _("Duplicate reference"), _("Make a copy of the first selected reference"))
        self.bibframe1_menubar.Append(wxglade_tmp_menu, _("Reference"))
        wxglade_tmp_menu = wx.Menu()
        item = wx.MenuItem(wxglade_tmp_menu,self.IdSearch,_("Search ...")+"\tCtrl-%s"%BIB.KEY_SEARCH,help=_("Search the database"))
        item.SetBitmap(ap.GetBitmap(wx.ART_FIND,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdSearch, _("Search ...")+"\tCtrl-%s"%BIB.KEY_SEARCH, _("Search the database"))
        wxglade_tmp_menu.Append(self.IdPubMedSearch, _("Pubmed search ...")+"\tCtrl-%s"%BIB.KEY_PUBMED, _("Search Pubmed on the Web"))
        wxglade_tmp_menu.Append(self.IdeTBlastSearch, _("eTBlast on PubMed ...")+"\tCtrl-%s"%BIB.KEY_ETBLAST, _("Search Pubmed with eTBlast"))
        self.bibframe1_menubar.Append(wxglade_tmp_menu, _("Search"))

        #Styles menu
        wxglade_tmp_menu = wx.Menu()
        BIB.STYLE_MENU = wxglade_tmp_menu
        self.IdOOoStyleNew = wx.NewId()
        self.IdOOoStyleEdit = wx.NewId()
        self.IdOOoStyleLoad = wx.NewId()
        self.IdOOoStyleDownload = wx.NewId()
        item = wx.MenuItem(wxglade_tmp_menu,self.IdOOoStyleNew,_("New ..."))
        item.SetBitmap(ap.GetBitmap(wx.ART_NEW,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdOOoStyleNew, _("New ..."), u"0")
        item = wx.MenuItem(wxglade_tmp_menu,self.IdOOoStyleEdit,_("Edit ..."))
        item.SetBitmap(ap.GetBitmap(wx.ART_EXECUTABLE_FILE,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdOOoStyleEdit, _("Edit ..."), u"0")
        item = wx.MenuItem(wxglade_tmp_menu,self.IdOOoStyleLoad,_("Load ..."))
        item.SetBitmap(ap.GetBitmap(wx.ART_FILE_OPEN,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdOOoStyleLoad, _("Load ..."), u"0")
        item = wx.MenuItem(wxglade_tmp_menu,self.IdOOoStyleDownload,_("Download styles"))
        item.SetBitmap(ap.GetBitmap(wx.ART_GO_BACK,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)        
        #wxglade_tmp_menu.Append(self.IdOOoStyleDownload, _("Download styles"), u"0")
        wxglade_tmp_menu.AppendSeparator()
        self.bibframe1_menubar.Append(wxglade_tmp_menu, _("Styles"))

        if BIB.WP == 'OOo':
            # setting OOo menu if needed
            self.doc = None        # this is the connection with OOo
            self.bibframe1_menubar.Append(self.__setOOoMenu(), _("OpenOffice.org"))
            self.WP_id = self.bibframe1_menubar.FindMenu( _("OpenOffice.org"))    # we keep the Id of the menu if we need to switch to word
        elif BIB.WP == 'mswDoc':
            # setting mswWord menu if needed
            self.bibframe1_menubar.Append(self.__setWordMenu(), _("MSWord"))
            self.WP_id = self.bibframe1_menubar.FindMenu( _("MSWord"))
        elif BIB.WP == 'Lyx':
            self.bibframe1_menubar.Append(self.__setLyxMenu(), _("LyX"))
            self.WP_id = self.bibframe1_menubar.FindMenu( _("LyX"))
        else:
            self.WP_id = None
        
        # Tools menu
        wxglade_tmp_menu = wx.Menu()
        # first connection wizzard
        wxglade_tmp_menu.Append(self.IdFirstTimeWizard, _("First Connection Wizard"), u"")
        wxglade_tmp_menu.AppendSeparator()
        # clean-up database
        wxglade_tmp_menu.Append(self.IdCleanDB, _("Clean database ..."), _("Empty Trash and DB cleanup"))
        wxglade_tmp_menu.AppendSeparator()
        # back-up
        wxglade_tmp_menu.Append(self.IdDoBackup,_("Archive user data"), u"Back up all locally stored user styles, databases and settings to a single archive file")
        wxglade_tmp_menu.Append(self.IdDoRestore,_("Restore user data from archive"), u"Retrieve user styles and databases from an archive file")
        # Easy switching between Word processors
        wxglade_tmp_menu.AppendSeparator()
        #wxglade_tmp_menu.Append(self.IdSwitchOOo,_("Word Processor"))
        wxglade_tmp_menu_sub = wx.Menu()
        for wp in ("OpenOffice.org", "Word", "LyX"):
            tmpid = wx.NewId()
            wxglade_tmp_menu_sub.Append(tmpid, wp)
            wx.EVT_MENU(self,tmpid,self.switchWP)
        wxglade_tmp_menu.AppendMenu(self.IdSwitchOOo, _("Word Processor"), wxglade_tmp_menu_sub, _("Switch Word Processor support"))
        #
        self.bibframe1_menubar.Append(wxglade_tmp_menu, _("Tools"))

        # Help menu
        wxglade_tmp_menu = wx.Menu()
        item = wx.MenuItem(wxglade_tmp_menu,self.IdShowHelp,_("Documentation"))
        item.SetBitmap(ap.GetBitmap(wx.ART_HELP,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdShowHelp, _("Documentation"), u"")
        wxglade_tmp_menu.Append(self.IdShowLicense, _("License"), u"")
        item = wx.MenuItem(wxglade_tmp_menu,self.IdShowWebSite,_("Bibus WEB site"))
        item.SetBitmap(ap.GetBitmap(wx.ART_GO_HOME,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)        
        #wxglade_tmp_menu.Append(self.IdShowWebSite, _("Bibus WEB site"), u"")
        # wxglade_tmp_menu.AppendSeparator()
        # wxglade_tmp_menu.Append(self.IdFirstTimeWizard, _("First Connection Wizard"), u"")
        wxglade_tmp_menu.AppendSeparator()
        wxglade_tmp_menu.Append(self.IdShowAbout, _("About"), u"")
        self.bibframe1_menubar.Append(wxglade_tmp_menu, _("Help"))
        # Menu Bar end

        #
        self.refDisplaypanel = display_panel.DisplayPanel(self.window_2_pane_2,-1,bibframe=self)
        self.reflist = RefList.RefList(self.window_2_pane_1, self)
        self.reflist.SetImageList(BIB.ARROWS,wx.IMAGE_LIST_SMALL)                    # list of images for icon in columns (sort order)
        # toolbar = just a wx.Panel since I got too many bugs with a true toolbar
        self.toolbar = self.CreateToolBar()
        #
        self.__set_properties()
        self.__do_layout()
        self.window_2.SetSashPosition( BIB.SASH_LIST )        # we have to reset to the correct position
        self.window_1.SetSashPosition( BIB.SASH_KEYTREE )    # since __do_layout() may have move it
        # end wx.Glade
        self.__set_evt_menu()
        #
        # loading dbBib module and try to connect
        #if BIB.DB_TYPE:
        #self.SetIcon(wx.Icon("Pixmaps/bibus.xpm",wx.BITMAP_TYPE_XPM))
        self.SetIcon(wx.Icon( os.path.join(BIB.SOURCEDIR,"Pixmaps/bibus.ico"), wx.BITMAP_TYPE_ICO) )
        try:
            BIB.DB_MODULE = __import__('dbBib'+BIB.DB_TYPE)
            getattr(BIB.DB_MODULE,'dbBib')    # if the module was loaded before, re-importing won't raise ImportError. We must check directly if it works
        except (ImportError,AttributeError):
            BIB.DB_MODULE = None
            wx.LogError(_("""Sorry, but I was not able to find the python module for the %s database.\nPlease check your installation""")%BIB.DB_TYPE)
        self.autoConnect()
        # other initialisations
        self.__setStyleMenu()        # populate the StyleMenu
        self.__setStartingConverter()    # set the reference formatting
        self.refDisplaypanel.resetFormat(BIB.FORMAT_DICO)

    def autoConnect(self):
        """Try to connect to a database (the last one used or default)"""
        if BIB.DB_MODULE:        # if a module is charged
            tmp_passwd = None
            db_still_valid = True
            if BIB.DB_TYPE == 'MySQL':
                name = BIB.DB_NAME
                if not BIB.STORE_PASSWD:
                    BIB.PASSWORD = wx.GetPasswordFromUser(_("Please enter password for database %s")%BIB.DB_NAME,parent=self)
            else:
                name = BIB.SQLiteFile
                # TO DO: not only check existence
                # but also if valid Bibus file
                if not os.path.exists(BIB.SQLiteFile):
                    ### print 'File does not exist...'
                    db_still_valid = False
                    # We should try to find a way to automatically 
                    # open 'connect' dialogue
            if db_still_valid:
                try:
                    #self.db=apply(eval('dbBib'+BIB.DB_TYPE+'.dbBib'),(self,BIB.USER,tmp_passwd,BIB.DB_NAME,BIB.HOST,BIB.PORT,BIB.SOCKET))
                    # the following command already generates warnings 
                    # if the file being opened is not a proper bibus db
                    self.db = BIB.DB_MODULE.dbBib(self) 
                    self.db.selectDatabase(name) # needed for creation of tmp tables
                    self.__chargeDB()
                except:
                    self.db = None
                    self.__noDB()
                if not BIB.STORE_PASSWD: BIB.PASSWORD = ''    # clear password for security
                if self.db: self.set_grants_layout()
            else:
                self.db = None
                self.__noDB()
        else:
            self.db = None
            self.__noDB()

    def __chargeDB(self):
        self.db.selectTable()
        self.keytree.setkeytree()
        self.keytree.KeySelect(self.keytree.keyAll)
        self.keytree.SelectItem(self.keytree.keyAll)
        self.SetTitle(_("Database = %s") % self.db.getDbDescription())

    def __noDB(self):
        """No active DB => clear everything"""
        self.SetTitle(_("Database = None"))
        self.keytree.DeleteAllItems()
        self.reflist.DeleteAllItems()
        self.refDisplaypanel.Clear()

    def CreateToolBar(self,id=-1,name=u'toolBar'):
        return myToolBar.myToolBar(self,id=id,name=name)
    
    def __CreateKeyTree(self):    
        # Setting keytree
        # If we are in a multi-users environment, we display multiple panels
        # one for the current user, one shared
        self.window_1_pane_1 = wx.Panel(self.window_1, -1)
        if BIB.MULTI_USER:
            self.keytree = Multi_KeyTree.Multi_KeyTree(self,self.window_1_pane_1)
        else:
            #self.keytree = Multi_KeyTree.KeyTree_Search(self,self.window_1_pane_1)    # does not work as expected. I have to find a better interface.
            self.keytree = KeyTree.KeyTree(self,self.window_1_pane_1)

    def __set_properties(self):
        # begin wx.Glade: BibFrame.__set_properties
        # self.SetTitle("bibframe1")
        # self.SetSize((-1, -1))
        self.bibframe1_statusbar.SetStatusWidths([-4,-2,-1])
        # statusbar fields
        bibframe1_statusbar_fields = [BIB.WELCOME,_("%(total_number)s reference(s) : %(number_selected)s selected")%{'total_number':self.reflist.GetItemCount(),'number_selected':self.reflist.GetSelectedItemCount()}]
        for i in range(len(bibframe1_statusbar_fields)):
            self.bibframe1_statusbar.SetStatusText(bibframe1_statusbar_fields[i], i)
        self.window_2.SplitHorizontally(self.window_2_pane_1, self.window_2_pane_2, BIB.SASH_LIST)
        self.window_1.SplitVertically(self.window_1_pane_1, self.window_1_pane_2, BIB.SASH_KEYTREE)
        # end wx.Glade
        if BIB.WP == 'OOo':
            self.bibframe1_menubar.Check(self.IdOOoHilightCitations,self.OOoHilightCit)
            self.bibframe1_menubar.Check(self.IdOOoAutoUpdate,self.OOoAutoUpdate)
            self.bibframe1_menubar.Check(self.IdOOoCreateBib,self.OOoCreateBib)

    def __layoutKeyTree(self):
        """We need to set it independently to be able to switch between rr and rw/ro/rk"""
        sizer_1 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_1.Add(self.keytree, 1, wx.EXPAND, 0)
        self.window_1_pane_1.SetAutoLayout(1)
        self.window_1_pane_1.SetSizer(sizer_1)
        sizer_1.Fit(self.window_1_pane_1)
        #sizer_1.SetSizeHints(self.window_1_pane_1)

    def __do_layout(self):
        sizer_0 = wx.BoxSizer(wx.VERTICAL)
        # begin wx.Glade: BibFrame.__do_layout
        sizer_2 = wx.BoxSizer(wx.VERTICAL)
        sizer_4 = wx.BoxSizer(wx.HORIZONTAL)
        self.sizer_6 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_5 = wx.BoxSizer(wx.HORIZONTAL)
        self.__layoutKeyTree()
        sizer_5.Add(self.reflist, 1, wx.EXPAND, 0)
        self.window_2_pane_1.SetAutoLayout(1)
        self.window_2_pane_1.SetSizer(sizer_5)
        sizer_5.Fit(self.window_2_pane_1)
        #sizer_5.SetSizeHints(self.window_2_pane_1)
        self.sizer_6.Add(self.refDisplaypanel, 1, wx.EXPAND, 0)
        self.window_2_pane_2.SetAutoLayout(1)
        self.window_2_pane_2.SetSizer(self.sizer_6)
        self.sizer_6.Fit(self.window_2_pane_2)
        #self.sizer_6.SetSizeHints(self.window_2_pane_2)
        sizer_4.Add(self.window_2, 1, wx.EXPAND, 0)
        self.window_1_pane_2.SetAutoLayout(1)
        self.window_1_pane_2.SetSizer(sizer_4)
        sizer_4.Fit(self.window_1_pane_2)
        #sizer_4.SetSizeHints(self.window_1_pane_2)
        sizer_2.Add(self.window_1, 1, wx.EXPAND, 0)
        #sizer_2.SetSizeHints(self)
        self.SetAutoLayout(1)
        #
        sizer_0.Add(self.toolbar,0,wx.EXPAND)
        sizer_0.Add(sizer_2,1,wx.EXPAND)
        #
        self.SetSizer(sizer_0)
        self.SetSizeHints(minH=200,minW=150)
        self.Layout()
        # end wx.Glade

    def __set_evt_menu(self):
        # file menu
        wx.EVT_MENU(self,self.IdFileQuit,self.onMenuFileQuit)
        wx.EVT_MENU(self,self.IdFileConnect,self.onMenuFileConnect)
        wx.EVT_MENU(self,self.IdFilePageSetup,self.onMenuFilePageSetup)
        wx.EVT_MENU(self,self.IdFilePrintPreview,self.onMenuFilePrintPreview)
        wx.EVT_MENU(self,self.IdFilePrint,self.onMenuFilePrint)
        wx.EVT_MENU(self,self.IdFileImportText,self.onMenuFileImportText)
        wx.EVT_MENU(self,self.IdFileImportInstall,lambda evt: self.onMenuFilterInstall(evt,"Import"))
        # Dynamic Import filters
        for idmenu in self.IdFileImportFilters.iterkeys():
            wx.EVT_MENU(self,idmenu,self.onMenuFileImport)
        #
        wx.EVT_MENU(self,self.IdFileExportSQLite,self.onMenuFileExportSQLite)
        wx.EVT_MENU(self,self.IdFileExportHtml,self.onMenuFileExportHtml)
        wx.EVT_MENU(self,self.IdDownloadFilter,self.onDownloadFilters)
        wx.EVT_MENU(self,self.IdFileExportInstall,lambda evt: self.onMenuFilterInstall(evt,"Export"))
        # Dynamic Export filters
        for idmenu in self.IdFileExportFilters.iterkeys():
            wx.EVT_MENU(self,idmenu,self.onMenuFileExport)
        #
        wx.EVT_MENU(self,self.IdAddChild,self.keytree.onMenuAddChild)
        wx.EVT_MENU(self,self.IdNewRef,self.onMenuNewRef)
        wx.EVT_MENU(self,self.IdEditRef,self.onMenuEditRef)
        wx.EVT_MENU(self,self.IdDelRef,self.onMenuDelRef)
        wx.EVT_MENU(self,self.IdTagRef,self.onMenuTagRef)
        wx.EVT_MENU(self,self.IdDupRef,self.onMenuDuplicateRef)
        wx.EVT_MENU(self,self.IdPubMedSearch,self.onMenuPubMedSearch)
        wx.EVT_MENU(self,self.IdeTBlastSearch,self.onMenueTBlastSearch)
        wx.EVT_MENU(self,self.IdSearch,self.onMenuSearch)
        # Copy/Paste
        wx.EVT_MENU(self,self.IdCopy,self.onMenuCopy)
        wx.EVT_MENU(self,self.IdCut,self.onMenuCut)
        wx.EVT_MENU(self,self.IdPaste,self.onMenuPaste)
        wx.EVT_MENU(self,self.IdSelectAll,self.onMenuSelectAll)
        wx.EVT_MENU(self,self.IdPref,self.onMenuPref)
        wx.EVT_MENU(self,self.IdCleanDB,self.onMenuCleanDB)
        # Style menu
        wx.EVT_MENU(self,self.IdOOoStyleEdit,self.onMenuOOoStyleEdit)
        wx.EVT_MENU(self,self.IdOOoStyleNew,self.onMenuOOoStyleNew)
        wx.EVT_MENU(self,self.IdOOoStyleLoad,self.onMenuOOoStyleLoad)
        wx.EVT_MENU(self,self.IdOOoStyleDownload,self.onMenuOOoStyleDownload)
        # Tools menu (currently integrated in File menu)
        wx.EVT_MENU(self,self.IdDoBackup,self.doBackup)
        wx.EVT_MENU(self,self.IdDoRestore,self.doRestore)
        # Help menu
        wx.EVT_MENU(self,self.IdShowHelp,self.showHelp)
        wx.EVT_MENU(self,self.IdShowLicense,self.showLicense)
        wx.EVT_MENU(self,self.IdShowWebSite,self.showWebSite)
        wx.EVT_MENU(self,self.IdFirstTimeWizard,self.firstTimeWizard)
        wx.EVT_MENU(self,self.IdShowAbout,self.showAbout)
        # window
        wx.EVT_CLOSE(self,self.onClose)

    def set_menu(self,key):
        """Enable and Disable menus"""
        try:
            #id = self.keytree.GetPyData(self.keytree.GetSelection())[2]
            id = self.keytree.GetPyData(key)[2]
            ref = self.reflist.GetFirstSelected()
            if self.allowed[id] & BIB.CHILD_OK: self.bibframe1_menubar.Enable(self.IdAddChild,True)
            else: self.bibframe1_menubar.Enable(self.IdAddChild,False)
            if self.allowed[id] & BIB.REF_EDIT_OK and ref != -1: self.bibframe1_menubar.Enable(self.IdEditRef,True)
            else: self.bibframe1_menubar.Enable(self.IdEditRef,False)
            if self.allowed[id] & BIB.REF_NEW_OK: self.bibframe1_menubar.Enable(self.IdNewRef,True)
            else: self.bibframe1_menubar.Enable(self.IdNewRef,False)
            if self.allowed[id] & BIB.REF_DEL_OK and ref != -1: self.bibframe1_menubar.Enable(self.IdDelRef,True)
            else: self.bibframe1_menubar.Enable(self.IdDelRef,False)
            if self.allowed[id] & BIB.REF_TAG_OK and ref != -1: self.bibframe1_menubar.Enable(self.IdTagRef,True)
            else: self.bibframe1_menubar.Enable(self.IdTagRef,False)
            if self.allowed[id] & BIB.REF_DUP_OK and ref != -1: self.bibframe1_menubar.Enable(self.IdDupRef,True)
            else: self.bibframe1_menubar.Enable(self.IdDupRef,False)
            if self.allowed[id] & BIB.EXPORT_OK: self.bibframe1_menubar.Enable(self.IdFileExport,True)
            else: self.bibframe1_menubar.Enable(self.IdFileExport,False)
            # Copy/Paste
            ClipOK = wx.TheClipboard.IsSupported(BIB.DnD_FORMAT)
            if self.allowed[id] & BIB.REF_DRAG_OK and ref != -1: self.bibframe1_menubar.Enable(self.IdCopy,True)
            else: self.bibframe1_menubar.Enable(self.IdCopy,False)
            if self.allowed[id] & BIB.REF_DEL_OK and ref != -1: self.bibframe1_menubar.Enable(self.IdCut,True)
            else: self.bibframe1_menubar.Enable(self.IdCut,False)
            if self.allowed[id] & BIB.REF_DROP_OK and ClipOK: self.bibframe1_menubar.Enable(self.IdPaste,True)
            else: self.bibframe1_menubar.Enable(self.IdPaste,False)
            # OOo menu
            if self.allowed[id] & BIB.OOo_INSERT_OK and ref != -1 and BIB.WP == 'OOo': self.bibframe1_menubar.Enable(self.IdOOoInsert,True)
            else: self.bibframe1_menubar.Enable(self.IdOOoInsert,False)
            # MSW menu
            if self.allowed[id] & BIB.OOo_INSERT_OK and ref != -1 and BIB.WP == 'mswDoc': self.bibframe1_menubar.Enable(self.IdMSWInsert,True)
            else: self.bibframe1_menubar.Enable(self.IdMSWInsert,False)
            # export
            if self.allowed[id] & BIB.EXPORT_OK: self.bibframe1_menubar.Enable(self.IdFileExport,True)
            else: self.bibframe1_menubar.Enable(self.IdFileExport,False)
            # printing
            if self.allowed[id] & BIB.REF_PRINT_OK:
                self.bibframe1_menubar.Enable(self.IdFilePrintPreview,True)
                self.bibframe1_menubar.Enable(self.IdFilePrint,True)
            else:
                self.bibframe1_menubar.Enable(self.IdFilePrintPreview,False)
                self.bibframe1_menubar.Enable(self.IdFilePrint,False)
        except:
            pass    # self.keytree.GetSelection() is invalid

    def saveJournalsAbbrev(self):
        """Save the abbreviations if we have modified them"""
        if not BIB.JOURNAL_MODIF: return
        f = os.path.join(wx.StandardPaths.Get().GetUserDataDir(),'Data',BIB.JOURNAL_FILE)
        fi = file( f, "w" )
        output = csv.writer(fi)
        output.writerows( BIB.JOURNAL.itervalues() )
        fi.close()

    def onClose(self,event):
        """Allows saving default values before exiting"""
        BIB.WX, BIB.WY = self.GetPositionTuple()
        BIB.WIDTH, BIB.HEIGHT = self.GetSizeTuple()
        BIB.SASH_LIST = self.window_2.GetSashPosition()
        if self.window_1.IsSplit(): BIB.SASH_KEYTREE = self.window_1.GetSashPosition()
        BIB.LIST_COL_SIZE = tuple( [self.reflist.GetColumnWidth(col) for col in xrange(self.reflist.GetColumnCount())] )
        if BIB.WP == 'OOo':
            BIB.OO_HILIGHT = self.OOoHilightCit
            BIB.OO_AUTO_UPDATE = self.OOoAutoUpdate
            BIB.OO_CREATE_BIB = self.OOoCreateBib
        BIB.CONFIG.writeConfig(not bool(BIB.DB_STARTUP))
        BIB.CONFIG.writeShortcuts()        # save the shortcuts
        #
        self.saveJournalsAbbrev()
        self.Destroy()

    def onMenuFileQuit(self,event):
        self.Close(True)

    def onMenuNewRef(self,event):
        selectedkey=self.keytree.GetSelection()
        key_id,user,id = self.keytree.GetPyData(selectedkey)
        if self.allowed[id] & BIB.REF_NEW_OK:
            if selectedkey == self.keytree.keyAll: selectedkey = self.keytree.keyRef    # Since we now have a Trash, keyAll cannot accept references
            editor = RefEditor.RefEditor((),self.db,selectedkey,True,self,-1,u'')        # we thus create in key Ref => will appear also in All
            editor.Show(True)

    def onMenuEditRef(self,event):
        selectedkey=self.keytree.GetSelection()
        key_id,user,id = self.keytree.GetPyData(selectedkey)
        #if self.allowed[id] & BIB.REF_EDIT_OK:
        selected = self.reflist.GetFirstSelected()
        while selected != -1:
            ref_id = self.reflist.GetItemData(selected)
            # getting the reference
            if id == BIB.ID_IMPORT_ROOT:    # we are in the import list
                ref = self.db.getRefImport(ref_id,BIB.BIB_FIELDS)
            elif id == BIB.ID_ONLINE_ROOT:    # we are in the online list
                ref = self.db.getRefOnline(ref_id,BIB.BIB_FIELDS)
            else:                            # we are in ref or query
                ref = self.db.getRef(ref_id,BIB.BIB_FIELDS)
            #
            editor = RefEditor.RefEditor(ref[0],self.db,selectedkey,self.allowed[id] & BIB.REF_EDIT_OK,self,-1,u'')
            editor.Show(True)
            selected = self.reflist.GetNextSelected(selected)

    def onMenuDelRef(self,event):
        selectedkey=self.keytree.GetSelection()
        key_id,user,id = self.keytree.GetPyData(selectedkey)
        firstselected = self.reflist.GetFirstSelected()
        selected = firstselected
        while selected != -1:
            ref_id = self.reflist.GetItemData(selected)
            self.db.delLink(key_id,ref_id)
            selected = self.reflist.GetNextSelected(selected)
        self.keytree.KeySelect(selectedkey)
        #self.set_menu(selectedkey) # not needed since it's done in KeySelect
        if self.reflist.GetFirstSelected() == -1 and firstselected != -1:
            self.reflist.Select( min(firstselected,self.reflist.GetItemCount()-1) )
            self.reflist.Focus( min(firstselected,self.reflist.GetItemCount()-1) )

    def onMenuTagRef(self,event):
        selectedkey=self.keytree.GetSelection()
        key_id,user,id = self.keytree.GetPyData(selectedkey)
        if self.allowed[id] & BIB.REF_DRAG_OK:
            keyTaggedId = self.keytree.GetPyData(self.keytree.keyTagged)[0]
            selected = self.reflist.GetFirstSelected()
            while selected != -1:
                ref_id = self.reflist.GetItemData(selected)
                self.db.writeLink( (keyTaggedId,ref_id) )
                selected = self.reflist.GetNextSelected(selected)

    def onMenuDuplicateRef(self,event):
        """We duplicate the first selected reference"""
        selected = self.reflist.GetFirstSelected()
        ref_id_old = self.reflist.GetItemData(selected)
        ref = self.db.getRef(ref_id_old,BIB.BIB_FIELDS)[0]
        ref = list(ref)
        ref[0] = None
        # we must allow insertion of duplicates
        dup_saved = BIB.DUPLICATES_TEST
        BIB.DUPLICATES_TEST = False
        ref_id = self.db.writeRef(ref)
        BIB.DUPLICATES_TEST = dup_saved
        # write link between the new ref and the current key
        key_id = self.keytree.GetPyData(self.keytree.GetSelection())[0]
        self.db.writeLink((key_id,ref_id))
        # update creator table
        #self.db.updateLastModif(ref_id)
        #
        self.updateRefList()
        self.reflist.selectItem(ref_id)

    def onMenuFileConnect(self,event):
        tmptypes = BIB.DB_TYPES[:]
        tmptypes.remove(BIB.DB_TYPE)
        tmptypes.insert(0,BIB.DB_TYPE)    # We put the current choice in first to have it selected by default
        ret = wx.GetSingleChoice(_("Please, select the database type"),_("Type of database"),tmptypes)
        if ret == "": return
        savedModule = BIB.DB_MODULE
        savedDBtype = BIB.DB_TYPE
        BIB.DB_TYPE = ret
        try:
            f, pathname, description = imp.find_module('dbBib'+BIB.DB_TYPE)
            BIB.DB_MODULE = imp.load_module('dbBib'+BIB.DB_TYPE, f, pathname, description)
            #BIB.DB_MODULE = __import__('dbBib'+BIB.DB_TYPE)
            #getattr(BIB.DB_MODULE,'dbBib')    # if the module was loaded before, re-importing won't raise ImportError. We must check directly if it works
        except ImportError:
            wx.LogError(_("""Sorry, but I was not able to find the Python module for the %s database.\nPlease check your installation""")%BIB.DB_TYPE)
            BIB.DB_MODULE = savedModule
            BIB.DB_TYPE = savedDBtype
            if f: f.close()
            return
        if f: f.close()
        #
        try:
            dbWiz = BIB.DB_MODULE.dbWizard(self)
            if not dbWiz.RunWizard(dbWiz.page1):
                BIB.DB_MODULE = savedModule
                BIB.DB_TYPE = savedDBtype
                return            # the user canceled the Wizard.
            db = dbWiz.getDbSelected()
            dbWiz.Destroy()
        except AttributeError:
            wx.LogError(_("""Sorry, but I was not able to find the Python module for the %s database.\nPlease check your installation""")%BIB.DB_TYPE)
            self.db = None
            self.__noDB()    # clear everything
            return
        #
        if db == None:
            self.db = None
            self.__noDB()
            self.showError(_("You did not select a valid database"))
        else:
            self.db = db
            self.__chargeDB()    # fill the main window with data
            self.set_grants_layout()

# setting layout depending on grants
    def set_grants_layout(self):
        grants = self.keytree.getGrants()
        self.allowed = BIB.ALLOWED[grants]
        if grants == 'rw':                                # normal read-write user
            self.refDisplaypanel.ShowKeysPage()
            self.keytree.keys_perso.Show()
            self.keytree.keys_common.Show()
            self.keytree.SelectUserTree()
            if not self.window_1.IsSplit():
                self.window_1_pane_1.Show()
                self.window_1.SplitVertically(self.window_1_pane_1, self.window_1_pane_2, BIB.SASH_KEYTREE)
        elif grants == 'ro':                            # normal read-only user with permissions to classify references
            self.refDisplaypanel.ShowKeysPage()
            self.keytree.keys_perso.Show()
            self.keytree.keys_common.Show()
            self.keytree.SelectUserTree()
            if not self.window_1.IsSplit():
                self.window_1_pane_1.Show()
                self.window_1.SplitVertically(self.window_1_pane_1, self.window_1_pane_2, BIB.SASH_KEYTREE)
        elif grants == 'rk':                            # read-only with ro on keytree
            self.refDisplaypanel.ShowKeysPage()
            self.keytree.keys_perso.Show(False)
            self.keytree.keys_common.Show()
            if not self.window_1.IsSplit():
                self.window_1_pane_1.Show()
                self.window_1.SplitVertically(self.window_1_pane_1, self.window_1_pane_2, BIB.SASH_KEYTREE)
        else:                                            # restricted read-only user
            self.refDisplaypanel.ShowKeysPage(False)
            self.keytree.keys_perso.Show(False)
            self.keytree.keys_common.Show(False)
            BIB.SASH_KEYTREE = self.window_1.GetSashPosition()
            self.window_1.Unsplit( self.window_1_pane_1 )

# setting menu depending on current grants
    def __set_ro(self):
        """Delete keys and inactivate menu for read-only users with rw on keytree"""
        self.bibframe1_menubar.Enable(self.IdFileImport,False)
        self.bibframe1_menubar.Enable(self.IdPubMedSearch,False)
        self.bibframe1_menubar.Enable(self.IdeTBlastSearch,False)
        self.toolbar.withoutPubMed()
        #self.refDisplaypanel.ShowKeysPage()
        #self.keytree.keys_perso.Show()
        #self.keytree.keys_common.Show()
        #if not self.window_1.IsSplit():
        #    self.window_1_pane_1.Show()
        #    self.window_1.SplitVertically(self.window_1_pane_1, self.window_1_pane_2, BIB.SASH_KEYTREE)
            #self.window_1.SetSashPosition(BIB.SASH_KEYTREE)

    def __set_rr(self):
        """Delete keys and inactivate menu for read-restricted users"""
        #BIB.SASH_KEYTREE = self.window_1.GetSashPosition()
        #self.window_1.Unsplit( self.window_1_pane_1 )
        self.bibframe1_menubar.Enable(self.IdFileImport,False)
        self.bibframe1_menubar.Enable(self.IdPubMedSearch,False)
        self.bibframe1_menubar.Enable(self.IdeTBlastSearch,False)
        self.toolbar.withoutPubMed()
        #self.refDisplaypanel.ShowKeysPage(False)

    def __set_rk(self):
        """Delete keys and inactivate menu for read-only users with ro on shared keytree"""
        self.bibframe1_menubar.Enable(self.IdFileImport,False)
        self.bibframe1_menubar.Enable(self.IdPubMedSearch,False)
        self.bibframe1_menubar.Enable(self.IdeTBlastSearch,False)
        self.toolbar.withoutPubMed()
        self.refDisplaypanel.ShowKeysPage()
        #self.keytree.keys_perso.Show(False)
        #self.keytree.keys_common.Show()
        #if not self.window_1.IsSplit():
        #    self.window_1_pane_1.Show()
        #    self.window_1.SplitVertically(self.window_1_pane_1, self.window_1_pane_2, BIB.SASH_KEYTREE)
            #self.window_1.SetSashPosition(BIB.SASH_KEYTREE)

    def __set_rw(self):
        """Delete keys and inactivate menu for read-write users"""
        self.bibframe1_menubar.Enable(self.IdFileImport,True)
        self.bibframe1_menubar.Enable(self.IdPubMedSearch,True)
        self.bibframe1_menubar.Enable(self.IdeTBlastSearch,True)
        self.toolbar.withPubMed()
        self.refDisplaypanel.ShowKeysPage()
        #self.keytree.keys_perso.Show()
        #self.keytree.keys_common.Show()
        #if not self.window_1.IsSplit():
        #    self.window_1_pane_1.Show()
        #    self.window_1.SplitVertically(self.window_1_pane_1, self.window_1_pane_2, BIB.SASH_KEYTREE)
            #self.window_1.GetSashPosition() )
            #self.window_1.SetSashPosition(BIB.SASH_KEYTREE)

    def set_grants(self):
        """Set settings according to db grants"""
        grants = self.keytree.getGrants()
        self.allowed = BIB.ALLOWED[grants]
        #print grants
        if grants == 'rw':                                # normal read-write user
            self.__set_rw()
        elif grants == 'ro':                            # normal read-only user with permissions to classify references
            self.__set_ro()
        elif grants == 'rk':                            # read-only with ro on keytree
            self.__set_rk()
        else:                                            # restricted read-only user
            self.__set_rr()
# end of grants settings

    def onMenuSelectAll(self,event):
        for i in xrange(self.reflist.GetItemCount()):
            self.reflist.Select(i)

    def onMenuPref(self,event):
        """Dialog for preferences"""
        #import Pref
        dpref = Pref.BibPref(self.db, self,-1,_("Preferences"))
        dpref.Show(True)
        
    def onMenuCleanDB(self,event):
        import CleanDB
        dlg = CleanDB.CleanDatabase(self.db,self)
        try:
            dlg.ShowModal()
            self.keytree.KeySelect(self.keytree.GetSelection())
        finally:
            dlg.Destroy()

    def updateRefList(self):
        """We update the view corresponding to the current key"""
        if not self.toolbar.searchtxt1.GetValue():
                self.keytree.KeySelect( self.keytree.GetSelection() )
        else:
            self.toolbar.onSearch(None)    # we update the view, taking into account current search

    def updateList(self,recordList):
        self.reflist.setList(recordList)
        self.bibframe1_statusbar.SetStatusText(_("%(total_number)s reference(s) : %(number_selected)s selected")%{'total_number':self.reflist.GetItemCount(),'number_selected':self.reflist.GetSelectedItemCount()},1)

# ----------------------------- Copy/Cut/Paste -----------------------------------------
    def __copyRefs(self):
        "Return in a  DnD.bibDataObject() the list of the selected references"
        item = self.keytree.GetSelection()
        oldkey_id,user,id = self.keytree.GetPyData(item)
        allowed=self.allowed[id]
        if allowed & BIB.REF_DRAG_OK:
            if id == BIB.ID_ONLINE_ROOT or id == BIB.ID_ONLINE:
                key = u'Online'
            elif id == BIB.ID_IMPORT_ROOT or id == BIB.ID_IMPORT:
                key = u'Import'
            else:
                key = u''
            #
            dragData = DnD.bibDragData(self.db.getDbInfo(key),BIB.DnD_REF)
            item = self.reflist.GetFirstSelected()
            if id == BIB.ID_IMPORT_ROOT:    # we are in the import list
                f = self.db.getRefImport
            elif id == BIB.ID_ONLINE_ROOT:    # we are in the online list
                f = self.db.getRefOnline
            else:                # we are in ref or query
                f = self.db.getRef
            while item != -1:
                dragData.append(tuple(apply(f,(self.reflist.GetItemData(item),BIB.BIB_FIELDS))[0]))
                # tuple is needed for sqlite since returned tuple is of class sqlite.main.PgResultSetConcreteClass
                item = self.reflist.GetNextSelected(item)
            mydrag = DnD.bibDataObject()
            mydrag.setObject(dragData)
            return mydrag
        else:
            return None

    def __formatRefsAsText_old(self,refList):
        """Return references in refList as a text"""
        tmp=[]
        for ref in refList:
            for field in BIB.BIB_FIELDS:
                if ref[BIB.BIBLIOGRAPHIC_FIELDS[field]] != '':                # non empty field
                    tmp.append( "%s: %s" %(BIB.NAME_FIELD[field],BIB.LIST_FIELD_FORMAT[field]( ref[BIB.BIBLIOGRAPHIC_FIELDS[field]] ) ) )
            tmp.append('')
        return '\n'.join(tmp)
        
    def onClipboardFormat(self,evt):
        BIB.TEXT_CLIPBOARD = self.bibframe1_menubar.GetLabel(evt.GetId())
    wx.NewId()
    def __formatRefsAsText(self,refList):
        """Return a references in refList as a text, formatted using an Export filter (refer, RIS, BibTeX, ..."""
        m = __import__('Export.%s'%BIB.TEXT_CLIPBOARD)
        m = getattr(m, BIB.TEXT_CLIPBOARD)
        text = StringIO.StringIO()
        exporter = m.exportRef(text)
        # writing record
        for ref in refList:
            exporter.write(ref)
        return text.getvalue()

    def __formatRefsAsHTML(self,refList):
        """Generate fromatted list of references according to the current OOo style"""
        text = StringIO.StringIO()
        text.write(u'<html>\n<head><META http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8"></head>\n<body>\n')
        # exporter = html exporter
        exporter = Export.html.exportRef(text,BIB.FORMAT_DICO)
        for ref in refList:
            exporter.write(ref)
        text.write(u'</body>\n</html>')
        return text.getvalue()

    def onMenuCopy(self,event):
        "Copy list of the selected references. Return True on success for Cut"
        dragData = self.__copyRefs()
        if dragData and wx.TheClipboard.Open():
            mydrag = wx.DataObjectComposite()
            mydrag.Add(dragData,preferred=True)                                                # bibus format = preferred
            mydrag.Add(wx.TextDataObject(self.__formatRefsAsText(dragData.getObject()) ))        # text format
            mydrag.Add(DnD.HTMLDataObject(self.__formatRefsAsHTML(dragData.getObject()) ))    # html format
            wx.TheClipboard.SetData(mydrag)
            #wx.TheClipboard.Flush()    # needed if we want the data to be available on quit
            wx.TheClipboard.Close()
            self.set_menu(self.keytree.GetSelection())    # update menu to enable Paste if possible
            return True
        else:
            wx.TheClipboard.Close()
            return False

    def onMenuCut(self,event):
        item = self.keytree.GetSelection()
        oldkey_id,user,id = self.keytree.GetPyData(item)
        allowed=self.allowed[id]
        if allowed & BIB.REF_DEL_OK and self.onMenuCopy(event):
            # we delete the reference links
            self.onMenuDelRef(None)

    def onMenuPaste(self,event):
        item = self.keytree.GetSelection()
        newparentID,user,id = self.keytree.GetPyData(item)
        mydrag = DnD.bibDataObject()
        if wx.TheClipboard.Open() and wx.TheClipboard.GetData(mydrag):         # ask for data of the correct format
            #wx.TheClipboard.Close()
            refdragged = mydrag.getObject()
            if refdragged.format == BIB.DnD_REF:
                if refdragged.dbInfo == self.db.getDbInfo():
                    #""" The dropped data comes from the same database, table => just update the links"""
                    for ref in refdragged:
                        self.db.writeLink((newparentID,ref[0]))
                else:
                    #"""We can just copy and not move"""
                    for ref in refdragged:
                        Identifier = ref[BIB.BIBLIOGRAPHIC_FIELDS['Author']].split(',')[0].replace(' ',u'_')+ref[BIB.BIBLIOGRAPHIC_FIELDS['Year']]
                        ref = (None,Identifier)+ref[2:]
                        ref_id = self.db.writeRef(ref)
                        #self.db.modifyRef(('Identifier',),(BIB.SEP_DUP.join((ref[BIB.BIBLIOGRAPHIC_FIELDS['Identifier']],str(ref_id))),),ref_id)
                        if ref_id:
                            self.db.writeLink((newparentID,ref_id))
                #self.keytree.KeySelect(newparentID)
                self.updateList(self.db.getRefKey(newparentID,BIB.LIST_DISPLAY,BIB.LIST_ORDER,BIB.LIST_HOW,short=True))                    # update reference list
        wx.TheClipboard.Close()

# ----------------------------- File importing ------------------------------------------
    def onDownloadFilters(self,event):
        webbrowser.open("http://bibus-biblio.sourceforge.net/wiki/index.php/Import/Export_filters",new=1)
        
    def onMenuFilterInstall(self,event,typ='Import'):
        dlg = wx.FileSelector(_("Choose the %(type)s filter to install")%{'type':typ},\
                                default_extension = "py",\
                                wildcard = "Python Script (*.py)|*.py",\
                                flags = wx.FD_OPEN,\
                                parent = self)
        if dlg:
            shutil.copy(dlg,os.path.join(BIB.CONFIG.getFilePath(),typ))
            wx.MessageBox("Please restart bibus to make the filter available","Information",\
                            style = wx.OK|wx.ICON_INFORMATION,\
                            parent = self)

    def __getFile(self,question=_("Please choose the file encoding"),mode='r',enc='ascii'):
        """Get file and encoding. Return open file or None"""
        dlg = wx.FileDialog(self,_("Choose a File to import"),style = wx.OPEN | wx.CHANGE_DIR)
        try:
            answer = dlg.ShowModal()
            filename = dlg.GetPath()
        finally:
            dlg.Destroy()
        if answer == wx.ID_OK:
            if enc == None:
                return file(filename,mode)
            # ask for encoding. We put as default choice enc if it exists
            dlg = CodecChoice.CodecChoice(enc,self)
            try:
                answer = dlg.ShowModal()
                if answer == wx.ID_OK:
                    encod = dlg.getCodec()
                else:
                    encod = ''
            finally:
                dlg.Destroy()
            #
            if encod != u'':
                try:
                    f = codecs.open(filename,mode,encod)
                except LookupError:
                    f = open(filename,mode)
                    wx.LogError(_("Sorry but codec '%s' is not available.\nI will try to use ascii"%encod))
                return f
            else:
                return None
        else:
            return None

    def FileImport(self,mod,f):
        """ Import file, with conversion module mod
        Id = auto_generated by MySQL
        Identifier = AuthorYear => much more readable for insertion in OpenOffice than Id
        f = file or StringIO"""
        #
        if f != None:
            self.db.deleteImport()
            #if mod == "EndNoteXML":
            #    xmlImporter = m.importRef(f)
            #    records = xmlImporter.getLibrary()
            #else:records = m.importRef(f)
            for CurRecord in mod.importRef(f):
                #CurRecord = self.__newIdentifier(CurRecord)
                self.db.writeRefImport(CurRecord)
            f.close()
        self.keytree.KeySelect(self.keytree.keyImport)
        self.keytree.SelectItem(self.keytree.keyImport)

    def getImportModule(self,m,flag=True):
        if flag:
            im = __import__('Import')
            path = im.__path__
        else:
            path = [os.path.join(BIB.CONFIG.getFilePath(),'Import')]
        f, pathname, description = imp.find_module(m,path)
        return imp.load_module(m, f, pathname, description)

    def onMenuFileImport(self,event):
        m,flag = self.IdFileImportFilters[event.GetId()]
        mod = self.getImportModule(m,flag)
        #m = __import__('Import.%s'%mod)
        #m = getattr(m, mod)
        self.FileImport( mod, self.__getFile(enc=mod.DEFAULT_ENCODING))

    def onMenuFileImportText(self,event):
        """Open a window to paste then import text"""
        importf = ImportFrame.ImportFrame(self,-1,'')
        importf.Show(True)

# ----------------------------- End File importing ----------------------------------------

# --------------------------------- File Export --------------------------------------------
    def __saveFile(self,question=_("Please choose the file encoding"),mode='r',enc='latin_1'):
        """Get file and encoding. Return open file or None"""
        dlg = wx.FileDialog(self,_("Save as..."),style = wx.SAVE | wx.OVERWRITE_PROMPT | wx.CHANGE_DIR)
        try:
            answer = dlg.ShowModal()
            filename = dlg.GetPath()
        finally:
            dlg.Destroy()
        if answer == wx.ID_OK:
            # ask for encoding. We put as default choice enc if it exists
            dlg = CodecChoice.CodecChoice(enc,self)
            try:
                answer = dlg.ShowModal()
                if answer == wx.ID_OK:
                    encod = dlg.getCodec()
                else:
                    encod = ''
            finally:
                dlg.Destroy()
            #
            if encod != u'':
                try:
                    f = codecs.open(filename,mode,encod)
                except LookupError:
                    f = open(filename,mode)
                    wx.LogError(_("Sorry but codec '%s' is not available.\nI will try to use ascii"%encod))
                return f
            else:
                return None
        else:
            return None

    def __FileExport(self,mod,enc='latin_1'):
        """ export file, with conversion module mod"""
        # asking what we want to export
        ret = wx.GetSingleChoiceIndex(_('What do you want to export?'),_('Export'),[_('Selection'),_('Current key'),_('All')])
        if ret == -1: return
        # get the file destination
        f = self.__saveFile(_("Choose the destination file"),'w',enc)
        if f:
            # creating export converter
            exporter = mod.exportRef(f)
            # getting the references id to export
            refsId=[]
            if ret == 0:    # we export the selection
                item = self.reflist.GetFirstSelected()
                while item != -1:
                    refsId.append(self.reflist.GetItemData(item))
                    item = self.reflist.GetNextSelected(item)
            elif ret == 1:    # current key == reflist content
                for item in xrange(self.reflist.GetItemCount()):
                    refsId.append(self.reflist.GetItemData(item))
            else:            # the whole database
                tmprefs = self.db.getAllRef(self.keytree.user,collist=())
                refsId = [x[0] for x in tmprefs]
            # writing record
            for refId in refsId:
                ref = list(self.db.getRef(refId,BIB.BIB_FIELDS)[0])    # get the reference
                ref[BIB.BIBLIOGRAPHIC_FIELDS['URL']] = \
                                ref[BIB.BIBLIOGRAPHIC_FIELDS['URL']].replace("$FILES",BIB.FILES,1)
                exporter.write(ref)
            f.close()
            
    def onMenuFileExport(self,event):
        m,flag = self.IdFileExportFilters[event.GetId()]
        if flag:
            im = __import__('Export')
            path = im.__path__
        else:
            path = [os.path.join(BIB.CONFIG.getFilePath(),'Export')]
        f, pathname, description = imp.find_module(m,path)
        mod = imp.load_module(m, f, pathname, description)
        #m = __import__('Import.%s'%mod)
        #m = getattr(m, mod)
        self.__FileExport( mod, enc=mod.DEFAULT_ENCODING )

    def __saveFileHTML(self,question=_("Choose the destination file"),mode='w'):
        """Get file. Return open file or None"""
        dlg = wx.FileDialog(self,_("Save as..."),style = wx.SAVE | wx.OVERWRITE_PROMPT | wx.CHANGE_DIR)
        try:
            answer = dlg.ShowModal()
        finally:
            dlg.Destroy()
        if answer == wx.ID_OK:
            filename = dlg.GetPath()
            try:
                f = codecs.open(filename,mode,'utf_8')
            except LookupError:
                f = open(filename,mode)
                wx.LogError(_("Sorry but codec '%s' is not available.\nI will try to use ascii"%'utf_8'))
            return f
        else:
            return None

    def onMenuFileExportHtml(self,event):
        """ Export to an Html file with format """
        # asking what we want to export
        ret = wx.GetSingleChoiceIndex(_('What do you want to export?'),_('Export'),[_('Selection'),_('Current key'),_('All')])
        if ret == -1: return
        # get the file destination
        f = self.__saveFileHTML(_("Choose the destination file"),'w')
        if f:
            f.write(u'<html>\n<head><META http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8"></head>\n<body>\n')
            # creating export converter
            exporter = Export.html.exportRef(f,BIB.FORMAT_DICO)
            # getting the references id to export
            refsId=[]
            if ret == 0:    # we export the selection
                item = self.reflist.GetFirstSelected()
                while item != -1:
                    refsId.append(self.reflist.GetItemData(item))
                    item = self.reflist.GetNextSelected(item)
            elif ret == 1:    # current key == reflist content
                for item in xrange(self.reflist.GetItemCount()):
                    refsId.append(self.reflist.GetItemData(item))
            else:            # the whole database
                tmprefs = self.db.getAllRef(self.keytree.user,collist=())
                refsId = [x[0] for x in tmprefs]
            # writing record
            for refId in refsId:
                ref = self.db.getRef(refId,BIB.BIB_FIELDS)[0]    # get the reference
                exporter.write(ref)
            f.close()

    def onMenuFileExportSQLite(self,event):
        """ Export to a sqlite database """
        # asking what we want to export
        ret = wx.GetSingleChoiceIndex(_('What do you want to export?'),_('Export'),[_('Selection'),_('Current key'),_('All')])
        if ret == -1: return
        # get the file destination
        answer = wx.FileSelector(_("Choose the name of the SQLite database"), flags = wx.SAVE | wx.OVERWRITE_PROMPT | wx.CHANGE_DIR )
        if answer == '': return
        # we create the database
        try:
            import dbBibSQLite
            savedFile = BIB.SQLiteFile
            BIB.SQLiteFile = answer
            # we delete the old file if it exists
            if os.path.exists( answer ):
                os.remove( answer )
            #
            db = dbBibSQLite.dbBib()
            db.createDatabase(answer,BIB.DB_TABLE_REF,BIB.DB_TABLE_KEY,BIB.DB_TABLE_LINK,BIB.DB_TABLE_QUERY,BIB.DB_TABLE_MODIF)
            #
            refsId=[]
            if ret == 0:    # we export the selection
                item = self.reflist.GetFirstSelected()
                while item != -1:
                    refsId.append(self.reflist.GetItemData(item))
                    item = self.reflist.GetNextSelected(item)
            elif ret == 1:    # current key == reflist content
                for item in xrange(self.reflist.GetItemCount()):
                    refsId.append(self.reflist.GetItemData(item))
            else:            # the whole database
                tmprefs = self.db.getAllDatabase(collist=())
                refsId = [x[0] for x in tmprefs]
            # writing records
            for refId in refsId:
                db.writeRef( self.db.getRef(refId,BIB.BIB_FIELDS)[0] )
            # we copy the rest of the database only if we export everything
            if ret == 2:
                # now we copy the keys
                for key in self.db.getAllKeys():
                    db.dumpKey( key )
                # now the Links
                for link in self.db.getAllLinks():
                    db.writeLink( link )
                # then the queries
                for query in self.db.getAllQueries():
                    db.dumpQuery( query )
                # modifs
                for modif in self.db.getAllModifs():
                    apply( db.resetCreator, modif )
                # files
                for filen in db_old.getAllFiles():
                    db.setCreator( filen )
            #
            BIB.SQLiteFile = savedFile
        except ImportError:
            wx.LogError(_("""Sorry, but I was not able to find the python module for the %s database.\nPlease check your installation""")%'SQLite')
            return

# ----------------------------- End File exporting ----------------------------------------

    def __newIdentifier(self,record):
        """Add an Identifier to a record. Identifier = AuthorYear where Author is the first author name.
        Spaces are also replaced by _"""
        record[BIB.BIBLIOGRAPHIC_FIELDS['Identifier']] = record[BIB.BIBLIOGRAPHIC_FIELDS['Author']].split(',')[0].replace(' ','_')+record[BIB.BIBLIOGRAPHIC_FIELDS['Year']]
        return record

    def onMenuPubMedSearch(self,event):
        #self.db.deleteOnline()
        search = SearchMedline.SearchMedline(self.db,self,-1,u'')
        search.Show(True)

    def onMenuSearch(self,event):
        search = Search.Search(self,self,-1,u'')
        search.Show(True)

    def onMenueTBlastSearch(self,event):
        #print "EtBlastSearch"
        #self.db.deleteOnline()
        search = SearcheTBlast.SearcheTBlast(self.db,self,-1,u'')
        search.Show(True)

# -----------------------------------------------------------------------------------------------------------------
# -------------------------------------- Printing support ---------------------------------------------------------
# -----------------------------------------------------------------------------------------------------------------
    def __getRef(self):
        keytype = self.keytree.getKeyType()
        if keytype == 'db':
            return self.db.getRef
        elif keytype == 'online':
            return self.db.getRefOnline
        elif keytype == 'import':
            return self.db.getRefImport
        else:
            print "What are we doing here ? BibFrame.__getRef"
            
    def generateHTML(self):
        """Return a HTML string = Formatted selected references"""
        # Setting the header
        BIB.PRINTER.SetHeader( """%s<hr size="2">""" % self.db.getDbDescription() )
        BIB.PRINTER.SetFooter( """<hr size="2"><center><font size="-2">@PAGENUM@/@PAGESCNT@</font></center>""" )
        # we get the references to print.
        # if 1 or more references are selected, we use the selection
        # if no selection, we print all the reference in the current refList
        text = StringIO.StringIO()
        refsId=[]
        item = self.reflist.GetFirstSelected()
        if item != -1:                    # at least 1 selection
            while item != -1:
                refsId.append(self.reflist.GetItemData(item))
                item = self.reflist.GetNextSelected(item)
        else:
            for item in xrange(self.reflist.GetItemCount()):
                refsId.append(self.reflist.GetItemData(item))
        #
        text.write(u'<html>\n<head><META http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8"></head>\n<body>\n')
        # <meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8">\n')
        getRef = self.__getRef()
        for refId in refsId:
            ref = apply(getRef,(refId,BIB.BIB_FIELDS))    # get the reference
            for field in BIB.PRINTER_FORMAT[BIB.BIB_TYPE[int(ref[0][2])]]:
                text.write(
                u"""%s%s%s <FONT COLOR=#%s>%s: </FONT>%s%s%s%s%s%s<FONT COLOR=#%s>%s</FONT>%s%s%s<br>\n""" %
                ( '<b>'*BIB.PRINTER_STYLE[0][0], '<i>'*BIB.PRINTER_STYLE[0][1], '<u>'*BIB.PRINTER_STYLE[0][2],
                 BIB.PRINTER_COLORS[0],BIB.NAME_FIELD[field],
                '</b>'*BIB.PRINTER_STYLE[0][0], '</i>'*BIB.PRINTER_STYLE[0][1], '</u>'*BIB.PRINTER_STYLE[0][2],
                '<b>'*BIB.PRINTER_STYLE[1][0], '<i>'*BIB.PRINTER_STYLE[1][1], '<u>'*BIB.PRINTER_STYLE[1][2],
                BIB.PRINTER_COLORS[1],apply(BIB.LIST_FIELD_FORMAT[field],(ref[0][BIB.BIBLIOGRAPHIC_FIELDS[field]],) ),
                '</b>'*BIB.PRINTER_STYLE[1][0], '</i>'*BIB.PRINTER_STYLE[1][1], '</u>'*BIB.PRINTER_STYLE[1][2] )
                )
                 #
            text.write( u"<p>\n" )
        text.write(u'</body>\n</html>')
        return text.getvalue()

    def generateFormattedHTML(self):
        """Generate fromatted list of references accordinf to the current OOo style"""
        # Setting the header
        BIB.PRINTER.SetHeader( """%s<hr size="2">""" % self.db.getDbDescription() )
        BIB.PRINTER.SetFooter( """<hr size="2"><center><font size="-2">@PAGENUM@/@PAGESCNT@</font></center>""" )
        # we get the references to print.
        # if 1 or more references are selected, we use the selection
        # if no selection, we print all the reference in the current refList
        text = StringIO.StringIO()
        refsId=[]
        item = self.reflist.GetFirstSelected()
        if item != -1:                    # at least 1 selection
            while item != -1:
                refsId.append(self.reflist.GetItemData(item))
                item = self.reflist.GetNextSelected(item)
        else:
            for item in xrange(self.reflist.GetItemCount()):
                refsId.append(self.reflist.GetItemData(item))
        #
        text.write(u'<html>\n<head><META http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8"></head>\n<body>\n')
        # exporter = html exporter
        exporter = Export.html.exportRef(text,BIB.FORMAT_DICO)
        getRef = self.__getRef()
        for refId in refsId:
            ref = apply(getRef,(refId,BIB.BIB_FIELDS))[0]    # get the reference
            exporter.write(ref)
        text.write(u'</body>\n</html>')
        return text.getvalue()

    def onMenuFilePageSetup(self,event):
        BIB.PRINTER.PageSetup()

    def onMenuFilePrintPreview(self,event):
        if BIB.PRINTER_USE_OOo_FORMAT:
            text = self.generateFormattedHTML()
        else:
            text = self.generateHTML()
        BIB.PRINTER.PreviewText(text)

    def onMenuFilePrint(self,event):
        if BIB.PRINTER_USE_OOo_FORMAT:
            text = self.generateFormattedHTML()
        else:
            text = self.generateHTML()
        BIB.PRINTER.PrintText(text)

# -----------------------------------------------------------------------------------------------------------------
# ------------------- functions for formatting modules (needed only if pyuno installed) ---------------------------
# -----------------------------------------------------------------------------------------------------------------
    def __setStartingConverter(self):
        current = BIB.CONFIG.getCurrentStyle()
        for k,val in BIB.STYLES.iteritems():
            if val == current:
                self.selectStyle(k)
                return
        # we did not find the style saved as current in the config file/registry
        try:
            k = BIB.STYLES.keys()[0]    # we take the first key
            self.selectStyle(k)
            return
        except:
            #"No possible selection. Empty menu ?"
            BIB.STYLE_CURRENT = u''
            BIB.CONFIG.writeCurrentStyle(BIB.STYLE_CURRENT)
            self.bibframe1_statusbar.SetStatusText('',2)
            return

    def __installStylesFromDir(self,directory):
        tmp = os.listdir( directory )
        tmp.sort()
        for style in tmp:
            MenuId = wx.NewId()
            BIB.STYLE_MENU.AppendRadioItem(MenuId, style, u"")
            BIB.STYLES[MenuId] = os.path.join(directory,style)
            wx.EVT_MENU(self, MenuId, self.__selectStyle)

    def __setStyleMenu(self):
        """Populate the Style menu
            1) from the Style directory
            2) from files saved by the user and registered in the Configuration file
            """
        self.__installStylesFromDir( os.path.join(BIB.SOURCEDIR,'Format','Styles') )
        if  wx.Platform != '__WXMSW__':        # does not work under Windows since it
            BIB.STYLE_MENU.AppendSeparator()    # would start a new radio group
        # User styles
        self.__installStylesFromDir( os.path.join( wx.StandardPaths.Get().GetUserDataDir(), "Styles") )

    def selectStyle(self,menuId):
        # we select and load the style
        BIB.STYLE_MENU.Check(menuId,True)
        f = open(BIB.STYLES[menuId],'rb')
        BIB.FORMAT_DICO = StyleEditor.Styleconverter.style_convert( cPickle.load(f) )
        f.close()
        BIB.STYLE_CURRENT = BIB.STYLES[menuId]
        BIB.CONFIG.writeCurrentStyle(BIB.STYLE_CURRENT)        # save choice in config file
        self.bibframe1_statusbar.SetStatusText(os.path.basename(BIB.STYLE_CURRENT),2)

    def __selectStyle(self,evt):
        f = open(BIB.STYLES[evt.Id],'rb')
        try:
            BIB.FORMAT_DICO = StyleEditor.Styleconverter.style_convert( cPickle.load(f) )
            f.close()
            BIB.STYLE_CURRENT = BIB.STYLES[evt.Id]
            BIB.CONFIG.writeCurrentStyle(BIB.STYLE_CURRENT)        # save choice in config file
            self.bibframe1_statusbar.SetStatusText(os.path.basename(BIB.STYLE_CURRENT),2)    # status bar
            self.refDisplaypanel.resetFormat(BIB.FORMAT_DICO)                    # select the style for display
        except:
            wx.LogError(_("The selected style is not a bibus style"))
            BIB.STYLE_MENU.Delete(evt.Id)
            BIB.CONFIG.deleteStyle(BIB.STYLES[evt.Id])

# -------------------------------------------------------------------------------------------------------
# ----------------------------------- Utility to switch between OOo and Word ----------------------------
# -------------------------------------------------------------------------------------------------------
    def __loadConnectionModule(self):
        """importing the necessary connection module. OOo or mswDoc"""
        global OOo
        global mswDoc
        global lyx_remote
        if BIB.WP == 'OOo':
            try:
                if hasattr(self,'mswDoc'): del self.mswDoc
                if hasattr(self,'OOo'): del self.OOo
                if hasattr(self,'lyx_remote'): del self.lyx_remote
                if hasattr(self,'doc'): del self.doc # this is to drop the connection and force new settings
                import OOo
            except ImportError:
                BIB.WP = ''
        elif BIB.WP == 'mswDoc':
            try:
                if hasattr(self,'mswDoc'): del self.mswDoc
                if hasattr(self,'OOo'): del self.OOo
                if hasattr(self,'lyx_remote'): del self.lyx_remote
                global newProgressWin,time
                import mswDoc
                import newProgressWin
                import time
            except ImportError:
                BIB.WP = ''
        elif BIB.WP == 'Lyx':
            try:
                if hasattr(self,'mswDoc'): del self.mswDoc
                if hasattr(self,'OOo'): del self.OOo
                if hasattr(self,'lyx_remote'): del self.lyx_remote
                import lyx_remote
            except ImportError:
                BIB.WP = ''           

    def switchConnectionMenu(self):
        """Activate the connection Menu corresponding to the choice in BIB.WP"""
        self.__loadConnectionModule()
        if BIB.WP == 'OOo':
            tmp_menu = self.__setOOoMenu()
            if self.WP_id != None:
                self.bibframe1_menubar.Replace(self.WP_id,tmp_menu,_("OpenOffice.org"))
            else:
                ret = self.bibframe1_menubar.Insert(5,tmp_menu,_("OpenOffice.org"))
                if ret: self.WP_id = 5
        elif BIB.WP == 'mswDoc':
            tmp_menu = self.__setWordMenu()
            if self.WP_id != None:
                self.bibframe1_menubar.Replace(self.WP_id,tmp_menu,_("MSWord"))
            else:
                ret = self.bibframe1_menubar.Insert(5,tmp_menu,_("MSWord"))
                if ret: self.WP_id = 5
        elif BIB.WP == 'Lyx':
            tmp_menu = self.__setLyxMenu()
            if self.WP_id != None:
                self.bibframe1_menubar.Replace(self.WP_id,tmp_menu,_("LyX"))
            else:
                ret = self.bibframe1_menubar.Insert(5,tmp_menu,_("LyX"))
                if ret: self.WP_id = 5
        elif self.WP_id != None:
            self.bibframe1_menubar.Remove(self.WP_id)
            self.WP_id = None

# -------------------------------------------------------------------------------------------------------
# ------------------------------------------ Lyx Menu ---------------------------------------------------
# -------------------------------------------------------------------------------------------------------
    def __setLyxMenu(self):
        def __identifiers():
            key_id,user,id = self.keytree.GetPyData(self.keytree.GetSelection())
            allowed = self.allowed[id]
            identifiers = []
            if allowed & BIB.REF_DRAG_OK:
                item = self.reflist.GetFirstSelected()
                while item != -1:
                    identifiers.append( self.reflist.GetItemText(item) )
                    item = self.reflist.GetNextSelected(item)
            return identifiers
    
        def onMenuCopyId(event):
            identifiers = __identifiers()
            if identifiers:
                if wx.TheClipboard.Open():
                    wx.TheClipboard.Clear()
                    wx.TheClipboard.SetData(wx.TextDataObject( "\cite{%s}" %','.join(identifiers) ))
                wx.TheClipboard.Close()
                
        def onMenuLyxInsert(event):
            identifiers = __identifiers()
            if identifiers:
                lyx_remote.bibusLyx().insert( ','.join(identifiers) )
        
        
        self.IdLyxInsert = wx.NewId()
        self.IdCopyCite = wx.NewId()
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(self.IdLyxInsert, _("Insert in LyX")+"\tCtrl-%s"%BIB.KEY_OO_INSERT, u"")
        wxglade_tmp_menu.Append(self.IdCopyCite, _("Insert in Clipboard")+"\tCtrl-Alt-%s"%BIB.KEY_COPYID)
        wx.EVT_MENU(self,self.IdLyxInsert,onMenuLyxInsert)
        wx.EVT_MENU(self,self.IdCopyCite,onMenuCopyId)
        return wxglade_tmp_menu

# -------------------------------------------------------------------------------------------------------
# ------------------------------------------ OpenOffice.org Menus ---------------------------------------
# -------------------------------------------------------------------------------------------------------
        # Setting OOo menu.
    def __setOOoMenu(self):
        # Menu OOo
        self.IdOOoInsert = wx.NewId()
        self.IdOOoAutoUpdate = wx.NewId()    # MenuCheck if index must be updated on Insert
        self.OOoAutoUpdate = BIB.OO_AUTO_UPDATE
        self.IdOOoFormat = wx.NewId()
        self.IdOOoGoToWriter = wx.NewId()
        self.IdOOoFinalize = wx.NewId()
        self.IdOOoHilightCitations = wx.NewId()
        self.OOoHilightCit = BIB.OO_HILIGHT    # set to true if self.IdOOoHilightCitations IsChecked = Hilight citations in OOo
        self.IdOOoCreateBib = wx.NewId()
        self.OOoCreateBib = BIB.OO_CREATE_BIB    # auto create bib if needed
        self.IdOOoCaptureCitations = wx.NewId()
        #
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(self.IdOOoInsert, _("Insert Citation")+"\tCtrl-%s"%BIB.KEY_OO_INSERT, u"")
        wxglade_tmp_menu.Append(self.IdOOoFormat, _("Format Bibliography")+"\tCtrl-%s"%BIB.KEY_OO_FORMAT, u"")
        wxglade_tmp_menu.Append(self.IdOOoGoToWriter, _("GoTo Writer")+"\tCtrl-%s"%BIB.KEY_OO_GOWRITER, u"")
        wxglade_tmp_menu.Append(self.IdOOoFinalize, _("Finalize"), _("Finalize the document"))
        wxglade_tmp_menu_sub = wx.Menu()
        wxglade_tmp_menu_sub.AppendSeparator()
        wxglade_tmp_menu.Append(self.IdOOoAutoUpdate, _("Update Index on Insert"), _("Update the Bibliography automatically"),wx.ITEM_CHECK)
        wxglade_tmp_menu.Append(self.IdOOoCreateBib, _("Create Index on Insert"), _("Create the Bibliography if absent"),wx.ITEM_CHECK)
        wxglade_tmp_menu.Append(self.IdOOoHilightCitations, _("Hilight Citations"), _("Hilight citations with a yellow background"),wx.ITEM_CHECK)
        wxglade_tmp_menu.Append(self.IdOOoCaptureCitations, _("Capture Citations"),_("Capture the references absent from the database"))
        # setting events
        wx.EVT_MENU(self,self.IdOOoInsert,self.onMenuOOoInsert)
        wx.EVT_MENU(self,self.IdOOoAutoUpdate,self.onMenuOOoAutoUpdate)
        wx.EVT_MENU(self,self.IdOOoCreateBib,self.onMenuOOoCreateBib)
        wx.EVT_MENU(self,self.IdOOoFormat,self.onMenuOOoFormat)
        wx.EVT_MENU(self,self.IdOOoGoToWriter,self.onMenuOOoGoToWriter)
        wx.EVT_MENU(self,self.IdOOoFinalize,self.onMenuOOoFinalize)
        wx.EVT_MENU(self,self.IdOOoHilightCitations,self.onMenuOOoHilightCit)
        wx.EVT_MENU(self,self.IdOOoCaptureCitations,self.onMenuOOoCaptureCit)
        return wxglade_tmp_menu

    def __connectToWriter(self):
        """Try to connect to a open Writer document and return True if OK"""
        try:
            self.doc.connectToWriter(BIB.FORMAT_DICO,self.OOoHilightCit,BIB.OO_HILIGHT_COLOR,self.OOoCreateBib)    # we test if the connection is up
        except (AttributeError, OOo.bibOOo_NoConnect):
            try:
                self.doc = OOo.bibusOOo(self.db)    # connection to OOo
                self.doc.connectToWriter(BIB.FORMAT_DICO,self.OOoHilightCit,BIB.OO_HILIGHT_COLOR,self.OOoCreateBib)    # connection to OOo writer document
            except OOo.bibOOo_NoConnect,e:
                wx.LogError(_("""Cannot connect to Openoffice. See Documentation.\n%s\n%s)""") % (e.msg,e.OOo))
                return False
        return True

    def onMenuOOoInsert(self,event):
        """Inserted the selected reference in OOo. Possible only if the references are in All, Ref+children or query"""
        if not self.__connectToWriter(): return
        #
        item = self.keytree.GetSelection()
        id = self.keytree.GetPyData(item)[2]
        if id in (BIB.ID_REF,BIB.ID_REF_ROOT,BIB.ID_REF_ALL,BIB.ID_QUERY,BIB.ID_CITED,BIB.ID_TAGGED):
            item = self.reflist.GetFirstSelected()
            while item != -1:
                # ref = list(self.db.getRef(self.reflist.GetItemData(item),BIB.BIB_FIELDS[1:-1])[0])
                # list is needed for sqlite since returned tuple is of class sqlite.main.PgResultSetConcreteClass
                # ooref = self.doc.formatRef(None,ref)    # we first create and format the ref
                ooref = self.doc.formatRef( None, self.db.getRef(self.reflist.GetItemData(item),BIB.BIB_FIELDS[1:-1])[0] )
                self.doc.insertRef(ooref)        # we insert the ref in OOo
                item = self.reflist.GetNextSelected(item)
        if self.OOoAutoUpdate:
            try: self.doc.bib.update()
            except AttributeError: pass        # if self.doc.bib == None

    def onMenuOOoAutoUpdate(self,event):
        """Check menu. If checked, index is updated on insert"""
        self.OOoAutoUpdate = event.IsChecked()

    def onMenuOOoCreateBib(self,event):
        """Check menu. If checked, index is create on insert"""
        self.OOoCreateBib = event.IsChecked()

    def onMenuOOoFormat(self,event):
        """Reload references from the databases + update index"""
        if not self.__connectToWriter(): return
        self.doc.updateRef()    # we update all the ref form the db
        self.doc.updateIndex()

    def onMenuOOoGoToWriter(self,event):
        """Give focus to Writer doc"""
        if not self.__connectToWriter(): return
        self.doc.activate()

    def onMenuOOoFinalize(self,event):
        """Just to help to format Author-date before Bibus 1.0"""
        if not self.__connectToWriter(): return
        self.doc.finalize()

    def addUserStyle(self,style):
        """Add a style in the menu and return its Id"""
        # we first look if the style is already in the menu
        for menuId,filename in BIB.STYLES.iteritems():
            if filename == style:
                break
        else:
            # the file is not in the menu
            menuId = wx.NewId()
            BIB.STYLE_MENU.AppendRadioItem(menuId, os.path.basename(style), u"")
            BIB.STYLES[menuId] = style
            wx.EVT_MENU(self, menuId, self.__selectStyle)
        return menuId

    def __StyleEdit(self,filename,conv):
        import StyleEditor.FormatEditor
        editor = StyleEditor.FormatEditor.FormatEditor(self,-1,_('References formatting'),filename=filename,conv=conv)
        try:
            ret = editor.ShowModal()
            if ret == wx.ID_SAVE:    # we must reload the style because it may have changed
                try:
                    f = file( BIB.STYLE_CURRENT )
                    BIB.FORMAT_DICO = StyleEditor.Styleconverter.style_convert( cPickle.load(f) )
                    f.close()
                except:
                    wx.LogError(_("The selected style is not a bibus style"))
            elif ret == wx.ID_SAVEAS:
                filename = editor.getFileName()
                menuId = self.addUserStyle(filename)
                self.selectStyle(menuId)
        finally:
            editor.Destroy()
            self.refDisplaypanel.resetFormat(BIB.FORMAT_DICO)    # we reload the format for display

    def onMenuOOoStyleNew(self,event):
        """OOo style creation"""
        self.__StyleEdit('', None)

    def onMenuOOoStyleEdit(self,event):
        """OOo style editing"""
        filename = BIB.STYLE_CURRENT
        if os.path.dirname(filename) != os.path.join(BIB.SOURCEDIR,'Format','Styles'):
            self.__StyleEdit(filename, copy.deepcopy(BIB.FORMAT_DICO))
        else:
            wx.LogMessage(_('You cannot edit default styles\n.I have made a copy of the style for editing'))
            self.__StyleEdit('', copy.deepcopy(BIB.FORMAT_DICO))

    def onMenuOOoStyleLoad(self,event):
        """Load a style from the disk"""
        filename = wx.FileSelector(_("Please select a style file"))
        if filename:
            f = file(filename)
            basename = cPickle.load(f)['info']['name']
            f.close()
            newfilename = os.path.join( wx.StandardPaths.Get().GetUserDataDir(), "Styles", basename )
            shutil.copyfile( filename, newfilename)
            menuId = self.addUserStyle(newfilename)
            self.selectStyle(menuId)
            self.refDisplaypanel.resetFormat(BIB.FORMAT_DICO)    # we reload style for display
            
    def onMenuOOoStyleDownload(self,event):
        """Open the wiki page with user contributed styles"""
        webbrowser.open("http://bibus-biblio.sourceforge.net/wiki/index.php/Styles_repository",new=1)

    def __showIdentifiersInAll(self,Identifiers,short=False):
        """Identifiers is a list of Identifier. Display them in key 'All' as an expertSearch"""
        query,refs = self.__Identifiers2References(Identifiers, order = BIB.LIST_ORDER, short=short)
        #print  BIB.LIST_ORDER,BIB.LIST_HOW
        self.keytree.KeySelect(self.keytree.keyAll)                                # select key 'All'
        self.keytree.SelectItem(self.keytree.keyAll)
        self.updateList(refs)                                    # display the result
        self.toolbar.displaySearch(query)                        # update the toolbar query text

    def __Identifiers2References(self,Identifiers,order,short=False):
        """Identifiers is a list of Identifier. Return a List of references."""
        if Identifiers:
            Identifiers2 = [    """Identifier='%s'""" % x.replace("'","''") for x in Identifiers ] # we replace single ' by ''
            query = " OR ".join(Identifiers2)
            #query = ((""" OR Identifier='%s'"""*len(Identifiers)) %tuple(Identifiers))[4:]
        else:
            query = "NULL"
        return query,self.db.getAllRefSearch( self.keytree.user, query , BIB.LIST_DISPLAY, order, BIB.LIST_HOW, short)
        
    def onMenuOOoSelectCit(self,event):
        """Select the references cited in the current OOo document"""
        if not self.__connectToWriter(): return
        citations = [ref.Identifier for ref in self.doc]
        self.__showIdentifiersInAll(citations,short=True)

    def OOoSelectCit(self,order,short=False):
        """Return list of references cited in the current OOo document"""
        if not self.__connectToWriter(): return ()
        citations = [ref.Identifier for ref in self.doc]
        return     self.__Identifiers2References(citations,order,short)[1]

    def onMenuOOoCaptureCit(self,event):
        """Capture the references cited in the current OOo document
        if they are not present in the current database
        eventually rename them to be of the form
        Identifier=AuthorYear#Id
        Then update the current OOo document accordingly"""
        if not self.__connectToWriter(): return
        citations = self.doc.storeUnknownRef()
        self.__showIdentifiersInAll(citations)

    def onMenuOOoHilightCit(self,event):
        """Set the bibus_citation_base style to background=yellow"""
        if event.IsChecked():
            self.OOoHilightCit = True
        else:
            self.OOoHilightCit = False
        if not self.__connectToWriter():
            return
        else:
             self.doc.resetCitationStyle()

# ------------------------------
# -----------Tools (currently placed under File menu)
# ------------------------------
    def doBackup(self,evt):
        import backupUserData
        from wx.lib.dialogs import messageDialog

        userDataDir = wx.StandardPaths.Get().GetUserDataDir()
        userDocsDir = wx.StandardPaths.Get().GetDocumentsDir()

        msgstr = '''WARNING! This procedure ONLY archives style files and databases stored in the local user data folder.\n
Local user data folder: '''+userDataDir
        dlg = messageDialog(self, msgstr, _('Archive warning!'), wx.OK | wx.ICON_EXCLAMATION)

        arcstarttime=time.time()
        archivename=time.strftime('bibusbackup_%y%m%d_%H%M%S.tar', time.localtime(arcstarttime))
        dlg = wx.FileDialog(self,_("Archive all user data into file ..."),style = wx.SAVE | wx.OVERWRITE_PROMPT | wx.CHANGE_DIR)
        dlg.SetDirectory(userDocsDir)
        dlg.SetFilename(archivename)
        dlg.SetWildcard("TAR archive (*.tar)|*.tar")        
        try:
            answer = dlg.ShowModal()
            filename = dlg.GetPath()
        finally:
            dlg.Destroy()
        # print answer, filename
        if answer == wx.ID_OK:
            backupPathname = filename
            backupUserData.backup2tar(userDataDir,backupPathname)

    def doRestore(self,evt):
        import backupUserData
        from wx.lib.dialogs import messageDialog,scrolledMessageDialog

        userDataDir = wx.StandardPaths.Get().GetUserDataDir()
        userDocsDir = wx.StandardPaths.Get().GetDocumentsDir()

        msgstr = '''Bibus can restore files from an archive file for you. Or you can do it by hand (recommended).\n
\nTo do it by hand (which gives more control and flexibility):\n
Open the user data archive file using an appropriate archive manager (Double-clicking the file may work).\n
Extract the files you want to restore to the corresponding sub-folders in\n'''+userDataDir+'''\n
\n
Click OK to let Bibus restore archived user data from a file.\n
Otherwise, click Cancel.'''
        dlg = messageDialog(self, msgstr, _('Restore user data from archive'), wx.OK | wx.CANCEL | wx.ICON_EXCLAMATION)
        if not (dlg.returned==wx.ID_OK):
            return

        arcPathname = wx.FileSelector(message=_('Bibus user data archive file'), default_path=userDocsDir, wildcard="TAR archive (*.tar)|*.tar|Any file (*)|*")
        # print arcPathname
        if (arcPathname != ''):
            retmsg = backupUserData.restore_tar(arcPathname,userDataDir)
        else:
            retmsg = 'Operation cancelled by user...'

        msgstr=retmsg
        dlg = scrolledMessageDialog(self, msgstr, _('Archive restore'))
        
    def switchWP(self,evt):
        wp = self.bibframe1_menubar.GetLabel(evt.GetId())
        if wp == "OpenOffice.org":
            BIB.WP = "OOo"
        elif wp == "Word":
            BIB.WP = "mswDoc"
        elif wp == "LyX":
            BIB.WP = "Lyx"
        else:
            BIB.WP = ""
        self.switchConnectionMenu()
# ------------------------------------------------------------------------------------------------------------------
# -------------------------------------------------- Help menu -----------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------
    def showHelp(self,evt):
        if os.path.exists(BIB.DOCPATH):
            webbrowser.open(BIB.DOCPATH,new=1)

    def showLicense(self,evt):
        from wx.lib.dialogs import ScrolledMessageDialog
        if os.path.exists(BIB.LICENCEPATH):
            f=open(BIB.LICENCEPATH,'r')
            dlg = ScrolledMessageDialog(self, f.read(), _('License'))
            f.close()
            try:
                    dlg.ShowModal()
            finally:
                    dlg.Destroy()

    def showWebSite(self,evt):
        webbrowser.open("http://bibus-biblio.sourceforge.net/",new=1)

    def firstTimeWizard(self,evt):
        import FirstStart.FirstStart
        dlg = FirstStart.FirstStart.FirstStart(self)            # help to setup a sqlite database
        try:                                        # not possible for mysql
            dlg.Run()
        finally:
            dlg.Destroy()
        #
        self.switchConnectionMenu()            # we switch the menu from OOo/word/nothing if needed
        # select the correct module for database
        try:
            BIB.DB_MODULE = __import__('dbBib'+BIB.DB_TYPE)
            getattr(BIB.DB_MODULE,'dbBib')    # if the module was loaded before, re-importing won't raise ImportError. We must check directly if it works
        except (ImportError,AttributeError):
            BIB.DB_MODULE = None
            wx.LogError(_("""Sorry, but I was not able to find the python module for the %s database.\nPlease check your installation""")%BIB.DB_TYPE)
        self.autoConnect()                        # connect to the new database

    def showAbout(self,evt):
        from wx.lib.dialogs import messageDialog
        msgstr='Bibus\nby Pierre Martineau & the Bibus Team\n\
version '+BIB.BIBUS_VERSION
        dlg = messageDialog(self, msgstr, _('About'), wx.OK)

    def showError(self,message=u''):
        wx.LogError(message)
        #dlg=wx.MessageDialog(self, message, caption = u"Error", style = wx.OK | wx.CENTRE | wx.ICON_ERROR, pos = wx.DefaultPosition)
        #try:
        #    dlg.ShowModal()
        #finally:
        #    dlg.Destroy()
# ------------------------------------------------------------------------------------------------------------------
# -------------------------------------------------- MSWORD menu -----------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------
    def    __setWordMenu(self):
        # setting mswWord menu if needed
        self.IdMSWInsert = wx.NewId()
        self.IdMSWCreateBiblio = wx.NewId()
        self.IdMSWPrintConvInfo = wx.NewId()
        self.IdMSWFormatBiblio = wx.NewId()
        self.IdMSWFinalize = wx.NewId()
        self.IdMSWUpdateCitation=wx.NewId()
        self.IdMSWPreFormatCitation=wx.NewId()
        self.IdMSWPrintConvInfo=wx.NewId()
        self.IdMSWPreAll=wx.NewId()
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(self.IdMSWInsert,_("Insert Citation")+"\tCtrl-%s"%BIB.KEY_OO_INSERT,u"")
        wxglade_tmp_menu.Append(self.IdMSWUpdateCitation,_("Update Citations"),u"")
        wxglade_tmp_menu.AppendSeparator()
        wxglade_tmp_menu.Append(self.IdMSWFormatBiblio,_("Update Bibliographic Index")+"\tCtrl-%s"%BIB.KEY_OO_FORMAT,u"")
        wxglade_tmp_menu.AppendSeparator()
        wxglade_tmp_menu.Append(self.IdMSWPreAll,_("Update and Pre-format all..."),u"")
        wxglade_tmp_menu.Append(self.IdMSWFinalize,_("Finalize..."),u"")
        #wxglade_tmp_menu.AppendSeparator()
        #wxglade_tmp_menu.Append(self.IdMSWPrintConvInfo,_("Debug Info"),u"")
        # setting events
        wx.EVT_MENU(self,self.IdMSWInsert,self.onMenuMSWInsert)
        wx.EVT_MENU(self,self.IdMSWFormatBiblio,self.onMenuMSWFormatBiblio)
        wx.EVT_MENU(self,self.IdMSWUpdateCitation,self.onMenuMSWUpdateCitation)
        wx.EVT_MENU(self,self.IdMSWPreAll,self.onMenuPreAll)
        wx.EVT_MENU(self,self.IdMSWFinalize,self.onMenuMSWFinalize)
        wx.EVT_MENU(self,self.IdMSWPrintConvInfo,self.onMenuPrintConvInfo)
        return wxglade_tmp_menu

    def onMenuMSWInsert(self,event):
        mswdoc = mswDoc.mswDoc()
        item = self.keytree.GetSelection()
        id = self.keytree.GetPyData(item)[2]
        if id in (BIB.ID_REF,BIB.ID_REF_ROOT,BIB.ID_REF_ALL,BIB.ID_QUERY,BIB.ID_CITED):
            item = self.reflist.GetFirstSelected()
            while item != -1:
                ref_id =self.reflist.GetItemData(item)
                ref =self.db.getRef(ref_id,BIB.BIB_FIELDS)
                mswdoc.MSWInsert(ref)
                item = self.reflist.GetNextSelected(item)
        if mswdoc.getMSWFormatter().isNumberEntries(): #And if autoUpdate
            mswdoc.updateCitationText()

####NOTE: MINIMIZING MSWORD WINDOW results into an important gain of time!!!!!!!
#### Currently it takes 45 sec to preformatte everything when win minimized otherwise it takes 3 min

    def onMenuMSWUpdateCitation(self,event):
        aDoc = mswDoc.mswDoc()
        self.updateCitationFromDatabase()
        aDoc.updateCitationText()
        aDoc.preFormatCitations()

    def onMenuMSWPreFormatCitation(self,event):
        #Need a progress gauge here (~20 sec)
        #the progress gauge here is fake and is a psychological help, so that the user doesn't worry!!!!
        msg= newProgressWin.newProgressWin("Pre-formatting. Please, keep MsWord minimized!","Please keep MsWord minimized and wait...    ")
        aDoc = mswDoc.mswDoc()
        msg.Update(0.1,"Please keep MsWord minimized and wait...\nThe process might take up to a minute")
        aDoc.minimizeWindow()
        msg.Update(0.4,"Please keep MsWord minimized and wait...\nThe process might take up to a minute")
        time.sleep(2)
        msg.Update(0.5,"Please keep MsWord minimized and wait...\nThe process might take up to a minute")
        self.updateCitationFromDatabase()
        aDoc.preFormatCitations()
        msg.Update(1,"Pre-Formatting terminated")
        aDoc.normalWindow()
        msg.Destroy()

    def onMenuMSWFormatBiblio(self,event):
        """ This function might take up to few minutes if a lot of ref are in
        That's why it is important to inform the user at this point"""
        aDoc = mswDoc.mswDoc()
        aDoc.MSWCreateBiblio()
        aDoc.formatBiblioString()

    def onMenuPreAll(self,event):
        perf = False #Turn to true if want to get the timing
        fstmsg = ""
        msg= newProgressWin.newProgressWin("Pre-formatting. Please, keep MsWord minimized!","Please wait...         ")
        prevTime = time.time()
        prevTime1=prevTime #For total time
#        print time.asctime(time.localtime(time.time()))
        msg.Update(0.05,fstmsg+"Reading document..")
        aDoc = mswDoc.mswDoc()
        #Improve speeds a lot to minimize the window before doing anything
        aDoc.minimizeWindow()
        citationFields =mswDoc.bibMSW.mswUtils.getCitationFields(aDoc.application.ActiveDocument.Fields)
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "\n\n****Bibus - MSWord Interface Performance Monitoring****"
            print "Time for initializing doc (sec.)=%s"%duree
        msg.Update(0.1,fstmsg+"Updating Bibliography...\nPlease, wait and keep MsWord minimized.")
        self.updateCitationFromDatabase()
        aDoc.MSWCreateBiblio()
        duree = time.time()-prevTime
        prevTime = time.time()

        if perf:
            print "Time for MSWCreateBiblio (sec.)", duree
        msg.Update(0.2,fstmsg+"Updating Citation text...\nPlease, wait and keep MsWord minimized.")
        aDoc.updateCitationText()
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for updateCitationText (sec.) =", duree
        msg.Update(0.4,fstmsg+"Fusionning Citations...\nPlease, wait and keep MsWord minimized.")
        aFormatter = aDoc.getMSWFormatter()
        skipFormatBiblioString = False
        if aFormatter.isNumberEntries()==True and aFormatter.isSortByPosition()== False:
            aDoc.formatBiblioString()
            skipFormatBiblioString = True
        aDoc.fuseCitations(citationFields)
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for fuseCitations (sec.)=", duree
        msg.Update(0.5,fstmsg+"Pre-formatting Citation text...\nPlease, wait and keep MsWord minimized.")
        citationFields = aDoc.preFormatCitations()
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for preFormatCitations (sec.)=", duree
        msg.Update(0.7,fstmsg+"Formatting Bibliography...\nThe process might take few minutes (1-2)")
        if skipFormatBiblioString==False:
            aDoc.formatBiblioString()
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for formatBiblioString (sec.)=", duree
        msg.Update(0.95,fstmsg+"Refreshing content..")
        if perf:
            print "****Done in Total Time (sec.)=", prevTime-prevTime1,"****"
        #aDoc.printConverterInfo()
        msg.Destroy()
        aDoc.normalWindow()

    def onMenuMSWFinalize(self,event):
        perf = False #Turn to True if want to get the timing
        aDoc = mswDoc.mswDoc()
        aDoc.finaliseDoc(self)
        fstmsg = ""
        msg= newProgressWin.newProgressWin("Pre-formatting. Please, keep MsWord minimized!","Please wait...         ")
        prevTime = time.time()
        prevTime1=prevTime #For total time
#        print time.asctime(time.localtime(time.time()))
        msg.Update(0.05,fstmsg+"Reading document..")
        aDoc = mswDoc.mswDoc()
        #Improve speeds a lot to minimize the window before doing anything
        aDoc.minimizeWindow()
        citationFields =mswDoc.bibMSW.mswUtils.getCitationFields(aDoc.application.ActiveDocument.Fields)
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "\n\n****Bibus - MSWord Interface Performance Monitoring****"
            print "Time for initializing doc (sec.)=%s"%duree
        msg.Update(0.2,fstmsg+"Updating Citation text...\nPlease, wait and keep MsWord minimized.")
        self.updateCitationFromDatabase()
        aDoc.updateCitationText()
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for updateCitationText (sec.) =", duree
        msg.Update(0.3,fstmsg+"Resolving Duplicates...\nPlease, wait and keep MsWord minimized.")
        citationFields = aDoc.getMSWFormatter().addDuplicateInfo(citationFields)
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for addDuplicateInfo (sec.)=", duree
        msg.Update(0.4,fstmsg+"Updating Citation Duplication...\nPlease, wait and keep MsWord minimized.")
        aDoc.updateCitationText()
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for updateCitationText (sec.) =", duree
        msg.Update(0.5,fstmsg+"Fusionning Citations...\nPlease, wait and keep MsWord minimized.")
        aFormatter = aDoc.getMSWFormatter()
        skipFormatBiblioString = False
        if aFormatter.isNumberEntries()==True and aFormatter.isSortByPosition()== False:
            aDoc.MSWCreateBiblio()
            aDoc.formatBiblioString()
            skipFormatBiblioString = True
        aDoc.fuseCitations(aDoc.application.ActiveDocument.Fields)
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for fuseCitations (sec.)=", duree
        msg.Update(0.6,fstmsg+"Pre-formatting Citation text...\nPlease, wait and keep MsWord minimized.")
        aDoc.preFormatCitations()
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for preFormatCitations (sec.)=", duree
        msg.Update(0.7,fstmsg+"Updating Bibliography...\nPlease, wait and keep MsWord minimized.")
        if skipFormatBiblioString == False:
            aDoc.MSWCreateBiblio()
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for MSWCreateBiblio (sec.)", duree
        msg.Update(0.8,fstmsg+"Formatting Bibliography...\nThe process might take few minutes (1-2)")
        if skipFormatBiblioString == False:
            aDoc.formatBiblioString()
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for formatBiblioString (sec.)=", duree
        msg.Update(0.95,fstmsg+"Refreshing content..")
        if perf:
            print "****Done in Total Time (sec.)=", prevTime-prevTime1,"****"
        msg.Destroy()
        aDoc.normalWindow()

    def updateCitationFromDatabase(self):
        """ Update the citation from the citation in database, key ALL"""
        aDoc = mswDoc.mswDoc()
        mFields =  mswDoc.bibMSW.mswUtils.getCitationFields(aDoc.application.ActiveDocument.Fields)
        for aField in mFields:
            fieldRefId = mswDoc.bibMSW.mswUtils.getXmlValueFromString("Identifier",aField.Code.Text)
            ref = self.db.getRefFromIdentifier(fieldRefId,BIB.BIB_FIELDS)
            if ref==[]: continue
            #print "Ref found=", ref[0][BIB.BIBLIOGRAPHIC_FIELDS["Identifier"]]
            allRefText =mswDoc.bibMSW.mswCONST.me_MSWBIBUS_ADDIN_REF_TAG
            for t in BIB.BIB_FIELDS[:-1]:
                if unicode(ref[0][BIB.BIBLIOGRAPHIC_FIELDS[t]]) =="":
                    continue
                elif t!="BibliographicType":
                    allRefText=allRefText+"<"+str(t)+">"+unicode(ref[0][BIB.BIBLIOGRAPHIC_FIELDS[t]])+"</"+str(t)+">"
                else:
                    allRefText=allRefText+"<"+str(t)+">"+BIB.BIB_TYPE[ref[0][BIB.BIBLIOGRAPHIC_FIELDS[t]]]+"</"+str(t)+">"
            allRefText = allRefText+"<"+mswDoc.bibMSW.mswCONST.me_MSWBIBUS_CITE_RANGES+">"+"for ranges"+"</"+mswDoc.bibMSW.mswCONST.me_MSWBIBUS_CITE_RANGES+">"
            allRefText = allRefText+"<"+mswDoc.bibMSW.mswCONST.me_MSWBIBUS_CITE_DUPLICATES+"></"+mswDoc.bibMSW.mswCONST.me_MSWBIBUS_CITE_DUPLICATES+">"
            #resText is the text displayed to the user when reference is inserted ([1] or Smith et al, 2005)
            #resText depends on the style and has to be set accordingly
            #resText = "{"+ref[0][BIB.BIB_FIELDS[1]]+"}"
            resText = "{"+ref[0][1]+"}"
            aField.Code.Text= allRefText
            aField.Result.Text = resText
            aField.Data = mswDoc.bibMSW.mswCONST.me_MSWBIBUS_CITE_TAG


    def MSWSelectCit(self,order,short=False):
        """Return list of references cited in the current MSW document"""
        aDoc = mswDoc.mswDoc()
        try:
         citationFields = mswDoc.bibMSW.mswUtils.getCitationFields(aDoc.application.ActiveDocument.Fields)
        except :
            return ()
        if len(citationFields)==0:
            return ()
        #citations = [ref.Identifier for ref in self.doc]
        citations = []
        for acite in citationFields:
            citations.append(mswDoc.bibMSW.mswUtils.getXmlValueFromString("Identifier",acite.Code.Text))
        return self.__Identifiers2References(citations,order,short)[1]

    def onMenuPrintConvInfo(self,event):
        #self.updateCitationFromDatabase()
        mswDoc.mswDoc().printConverterInfo()
# end of class BibFrame




