#   Programmer: Franz Steinhaeusler
#   E-mail:     francescoa@users.sourceforge.net
#   Note:       You must reply to the verification e-mail to get through.
#
#   Copyright 2004-2005 Franz Steinhaeusler
#
#   Distributed under the terms of the GPL (GNU Public License)
#
#    DrPython 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.
#
#    This program 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 this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#Plugin
#DocList

#01.08.2004 initial version 0.0.0
#03.08.2004         version 0.0.1
#06.08.2004         version 0.0.2
#07.08.2004         version 0.0.3
#08.08.2004         version 0.0.4
#12.08.2004         version 0.0.5
#28.08.2004         version 0.0.6
#28.09.2004         version 0.0.7
#20.10.2004         version 0.0.8
#24.10.2004         version 0.0.9
#21.01.2005         version 0.1.0
#15.02.2005         version 0.1.1
#for changes please view the changelog file
#for planned features please view the todo.txt file

#this is needed for PyChecker
#import sys
#sys.path.append('c:/Eigene Dateien/python/drpython')

import wx
import cStringIO
import drScrolledMessageDialog
import os
import drPrefsFile
import wx.lib.mixins.listctrl  as  listmix


def OnAbout(DrFrame):
    Version = "0.1.1"
    NameAndVersion = "DocList:\n\nVersion: " + Version + "\n"
    AboutString = NameAndVersion + "By Franz Steinhaeusler\n\nReleased under the GPL."
    drScrolledMessageDialog.ShowMessage(DrFrame, AboutString, "About")

def OnHelp(DrFrame):
    HelpText ="\
DocList:\n\n\
This should be a quick and easy to use Document Switcher.\n\
This plugin should be pretty self explaining.\n\
Good choices for a shortcut for this plugin could be Ctrl-F6 (is common used in windows)\n\
or I use alt-down (easy to reach).\n\n\
You can rearrange the files by clicking on the column header.\n\
If you click again on the same header, the sort order ist reversed (ascending and descending)\n\
and you can also use this by the shortcuts like Norton Commander with F3, F4, F5 and F6.\n\n\
You can close and save several files at once.\n\
To rearrange the order of files, there are the up and down buttons\n\
If you press the Cancel Button, it tries to jump to the file, which was \n\
activated before calling DocList.\n\n\
There are also functions to move a document right or left.\n\n\
And a toggle Documents function.\n\
simplest way to use: select first wished document => call toggle => select second wished document\n\
=> toggle => toggle => toggle \n\n\n\
For additional Information, please see changelog.txt and todo.txt.\n\n\
if there are problems or you have suggestions, then please submit an email to francescoa@users.sourceforge.net.\n\n\
Enjoy!\
"
    drScrolledMessageDialog.ShowMessage(DrFrame, HelpText, "Help", size = wx.Size(500, 480))

def OnPreferences(DrFrame):
    d = DocListPrefsDialog(DrFrame, -1)
    d.ShowModal()
    d.Destroy()

class DocListPrefsDialog(wx.Dialog):

    def __init__(self, parent, id):

        wx.Dialog.__init__(self, parent, id, "DocList Preferences", wx.Point(50, 50), \
                        wx.Size(220, 160), wx.DEFAULT_DIALOG_STYLE | wx.MAXIMIZE_BOX | wx.THICK_FRAME | wx.RESIZE_BORDER)

        self.parent = parent

        self.chkSaveSizePosition = wx.RadioBox(self, -1, "Size-Position", \
                                                choices = ["Do not save", "Save manually", "Save automatically"],\
                                                style = wx.RA_SPECIFY_ROWS)

        self.chkSaveSizePosition.SetSelection(self.parent.DocList_savesizeposition)

        self.theSizer = wx.FlexGridSizer(5, 3, 5, 10)

        self.theSizer.Add(self.chkSaveSizePosition, 1, wx.GROW)
        self.theSizer.Add(wx.StaticText(self, -1, "   "), 1, wx.SHAPED)
        self.theSizer.Add(wx.StaticText(self, -1, "   "), 1, wx.SHAPED)

        self.SetAutoLayout(True)
        self.SetSizer(self.theSizer)

        self.buttonSizer = wx.BoxSizer(wx.HORIZONTAL)

        self.btnCancel = wx.Button(self, wx.ID_CANCEL, "&Close")
        self.btnSave = wx.Button(self, wx.ID_OK, "&Save")
        self.btnSave.SetDefault()

        self.buttonSizer.Add(self.btnCancel, 1, wx.SHAPED)
        self.buttonSizer.Add(self.btnSave, 1, wx.GROW)

        self.theSizer.Add(self.buttonSizer, 0, wx.SHAPED | wx.ALIGN_CENTER)
        self.theSizer.Add(wx.StaticText(self, -1, "   "), 0, wx.SHAPED | wx.ALIGN_CENTER)
        self.theSizer.Add(wx.StaticText(self, -1, "   "), 0, wx.SHAPED | wx.ALIGN_CENTER)

        if parent.PLATFORM_IS_WIN:
            self.SetSizerAndFit(self.theSizer)

        self.Bind(wx.EVT_BUTTON,  self.OnbtnClose, id = wx.ID_CANCEL)
        self.Bind(wx.EVT_BUTTON,  self.OnbtnSave, id = wx.ID_OK)
        self.Bind(wx.EVT_RADIOBOX,  self.OnSizePos, id = -1)

    def OnSizePos (self, event):
        if event.GetSelection() == 0:
            sizeposfile = os.path.join(parent.pluginsuserdatadirectory, 'DocList.sizepos.dat')
            if os.path.exists (sizeposfile):
                answer = wx.MessageBox("Delete sizeandposition entries?", "Warning", wx.YES_NO | wx.ICON_QUESTION)
                if answer == wx.YES:
                    os.remove(sizeposfile)


    def OnbtnClose(self, event):
        self.EndModal(0)

    def OnbtnSave (self, event):
        self.parent.DocList_savesizeposition = int(self.chkSaveSizePosition.GetSelection())
        f = file(self.parent.pluginspreferencesdirectory + "/DocList.preferences.dat", 'w')
        f.write("<doclist.savesizeposition>" + str(self.parent.DocList_savesizeposition) + "</doclist.savesizeposition>\n")
        f.close()



def Plugin(DrFrame):

    class DocumentListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
        def __init__(self, parent, ID, pos = wx.DefaultPosition, size = wx.DefaultSize, style = 0):
            wx.ListCtrl.__init__(self, parent, ID, pos, size, style) # wx.LC_REPORT|wx.LC_HRULES|wx.LC_VRULES)
            self.SetBackgroundColour(wx.Colour(235, 231, 235))
            listmix.ListCtrlAutoWidthMixin.__init__(self)

    class drDocumentListDialog(wx.Dialog):
        def __init__(self, parent, id, title):
            wx.Dialog.__init__(self, parent, id, title, wx.DefaultPosition, wx.DefaultSize, wx.DEFAULT_DIALOG_STYLE | wx.MAXIMIZE_BOX | wx.THICK_FRAME | wx.RESIZE_BORDER)

            self.parent = parent
            ID_CLOSEDOCUMENT = DrFrame.GetNewId()
            ID_UP = DrFrame.GetNewId()
            ID_DOWN = DrFrame.GetNewId()
            ID_SAVE = DrFrame.GetNewId()
            ID_PREFERENCES = DrFrame.GetNewId()
            ID_ABOUT = DrFrame.GetNewId()
            ID_HELP = DrFrame.GetNewId()
            ID_SAVESIZEPOS = DrFrame.GetNewId()

            #buttons
            self.OkBtn = wx.Button (self, wx.ID_OK, "&Select",  wx.DefaultPosition, size = (90, -1))
            self.BtnUp  = wx.Button (self, ID_UP, "&Up",  wx.DefaultPosition, size = (90, -1))
            self.BtnDown  = wx.Button (self, ID_DOWN, "&Down",  wx.DefaultPosition, size = (90, -1))
            self.CloseDocumentBtn  = wx.Button (self, ID_CLOSEDOCUMENT, "C&lose File",  wx.DefaultPosition, size = (90, -1))
            self.BtnSave  = wx.Button (self, ID_SAVE, "Save &File",  wx.DefaultPosition, size = (90, -1))
            self.BtnSaveSize = wx.Button(self, ID_SAVESIZEPOS, "Sa&ve Size", size = (90, -1))
            self.BtnPreferencs  = wx.Button (self, ID_PREFERENCES, "&Preferences",  wx.DefaultPosition, size = (90, -1))
            self.BtnAbout  = wx.Button (self, ID_ABOUT, "&About",  wx.DefaultPosition, size = (90, -1))
            self.BtnHelp  = wx.Button (self, ID_HELP, "&Help",  wx.DefaultPosition, size = (90, -1))
            self.CancelBtn  = wx.Button (self, wx.ID_CANCEL, "&Cancel",  wx.DefaultPosition, size = (90, -1))

            #list ctrl
            self.ResultList  = DocumentListCtrl (self, -1, wx.DefaultPosition, wx.DefaultSize, wx.LC_REPORT|wx.SUNKEN_BORDER )#wxLC_VIRTUAL|
            self.il = wx.ImageList(16, 16)
            try:
                self.idx1 = self.il.Add(self.getModifiedBitmap())
            except:
                self.idx1 = -1
            try:
                self.sm_up = self.il.Add(self.getSmallUpArrowBitmap())
            except:
                self.sm_up = -1
            try:
                self.sm_dn = self.il.Add(self.getSmallDnArrowBitmap())
            except:
                self.sm_dn = -1

            self.ResultList.SetImageList(self.il, wx.IMAGE_LIST_SMALL)

            self.ResultList.InsertColumn(0, "Filename",  wx.LIST_FORMAT_LEFT, 200)
            self.ResultList.InsertColumn(1, "Ext.",   wx.LIST_FORMAT_LEFT,  60)
            self.ResultList.InsertColumn(2, "Nr.",   wx.LIST_FORMAT_LEFT,  60)
            #leave out the wide argument; it is done by the ListCtrlAutoWidthMixin class
            self.ResultList.InsertColumn(3, "Path",  wx.LIST_FORMAT_LEFT)

            self.ResultList .SetDimensions(0, 0, 0, 0)

            # sizer stuff
            topsizer = wx.BoxSizer( wx.VERTICAL )

            upperSizer = wx.BoxSizer(wx.HORIZONTAL)

            helpsizer = wx.BoxSizer(wx.VERTICAL)
            helpsizer.Add((0, 5), 0, wx.ALL, 0)
            helpsizer.Add(self.OkBtn, 0, wx.ALL, 0)
            helpsizer.Add((0, 15), 0, wx.ALL, 0)
            helpsizer.Add(self.BtnUp, 0, wx.ALL, 0)
            helpsizer.Add((0, 5), 0, wx.ALL, 0)
            helpsizer.Add(self.BtnDown, 0, wx.ALL, 0)
            helpsizer.Add((0, 15), 0, wx.ALL, 0)
            helpsizer.Add(self.CloseDocumentBtn, 0, wx.ALL, 0)
            helpsizer.Add((0, 5), 0, wx.ALL, 0)
            helpsizer.Add(self.BtnSave, 0, wx.ALL, 0)
            helpsizer.Add((0, 15), 0, wx.ALL, 0)
            helpsizer.Add(self.BtnSaveSize, 0, wx.ALL, 0)
            helpsizer.Add((0, 15), 0, wx.ALL, 0)
            helpsizer.Add(self.BtnPreferencs, 0, wx.ALL, 0)
            helpsizer.Add((0, 5), 0, wx.ALL, 0)
            helpsizer.Add(self.BtnAbout, 0, wx.ALL, 0)
            helpsizer.Add((0, 5), 0, wx.ALL, 0)
            helpsizer.Add(self.BtnHelp, 0, wx.ALL, 0)
            helpsizer.Add((0, 15), 0, wx.ALL, 0)
            helpsizer.Add(self.CancelBtn, 0, wx.ALL, 0)

            lowerSizer = wx.BoxSizer(wx.HORIZONTAL)
            lowerSizer.Add(self.ResultList,1, wx.EXPAND | wx.ALL, 5)
            lowerSizer.Add(helpsizer,0, wx.RIGHT | wx.LEFT | wx.BOTTOM, 10)

            topsizer.Add(upperSizer, 0, wx.EXPAND |wx.ALL, 5 )
            topsizer.Add(lowerSizer, 1, wx.EXPAND | wx.ALL, 5 )
            self.SetSizer(topsizer)

            #feed listbox
            txtDocumentArraySic = DrFrame.txtDocumentArray[:]
            #txtPromptArraySic = DrFrame.txtPromptArray[:]
            self.BtnSaveSize.Enable (self.parent.DocList_savesizeposition == 1)

            self.listfiles = []
            for i in range (len(DrFrame.txtDocumentArray)):
                fname = txtDocumentArraySic[i].filename
                if not txtDocumentArraySic[i].filename:
                    documentname = "Untitled " + str(txtDocumentArraySic[i].untitlednumber)
                else:
                    documentname = os.path.split(txtDocumentArraySic[i].filename)[1]

                if not fname:
                    self.listfiles.append ([documentname, "", str(i+1), ""])
                else:
                    self.listfiles.append ([documentname, os.path.splitext (fname)[1][1:], str(i+1), os.path.split(fname)[0]])
            self.RefreshListFiles()

            self.SetDimensions(0, 0, 706, 382)
            self.Centre()

            self.OkBtn.SetDefault()
            self.lastselected = DrFrame.txtDocument.targetPosition
            self.ResultList.SetItemState(DrFrame.txtDocument.targetPosition, wx.LIST_STATE_SELECTED|wx.LIST_STATE_FOCUSED , wx.LIST_STATE_SELECTED|wx.LIST_STATE_FOCUSED)
            self.ResultList.EnsureVisible(DrFrame.txtDocument.targetPosition)
            self.ResultList.SetFocus()
            self.oldsortcolumn = -1
            self.sort_asc = True
            self.reorderd = False

            self.SetSizeHints(410, 382)

            self.Bind(wx.EVT_BUTTON, self.OnbtnOK, id = wx.ID_OK)
            self.Bind(wx.EVT_BUTTON, self.OnbtnCancel, id = wx.ID_CANCEL)
            self.Bind(wx.EVT_BUTTON, self.OnCloseDocument, id = ID_CLOSEDOCUMENT)
            self.Bind(wx.EVT_BUTTON, self.OnUp, id = ID_UP)
            self.Bind(wx.EVT_BUTTON, self.OnDown, id = ID_DOWN)
            self.Bind(wx.EVT_BUTTON, self.OnSave, id = ID_SAVE)
            self.Bind(wx.EVT_BUTTON, self.OnSaveSizePos, id = ID_SAVESIZEPOS)
            self.Bind(wx.EVT_BUTTON, self.OnHelp, id = ID_HELP)
            self.Bind(wx.EVT_BUTTON, self.OnAbout, id = ID_ABOUT)
            self.Bind(wx.EVT_BUTTON, self.OnPreferences, id = ID_PREFERENCES)

            self.Bind(wx.EVT_LIST_KEY_DOWN, self.OnKeyDown, id = -1)
            self.Bind(wx.EVT_LIST_COL_CLICK, self.OnHeaderClick, id = -1)
            self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnbtnOK, id = -1)
            if self.parent.DocList_savesizeposition:
                self.parent.LoadDialogSizeAndPosition(self, 'DocList.sizepos.dat', self.parent.pluginsuserdatadirectory)

        def OnCloseW (self, event):
            if self.parent.DocList_savesizeposition == 2:
                self.parent.SaveDialogSizeAndPosition(self, 'DocList.sizepos.dat', self.parent.pluginsuserdatadirectory)
            if event is not None:
                event.Skip()

        def OnSaveSizePos (self, event):
            if self.parent.DocList_savesizeposition == 1:
                self.parent.SaveDialogSizeAndPosition(self, 'DocList.sizepos.dat', self.parent.pluginsuserdatadirectory)


        def OnAbout(self, event):
            OnAbout(DrFrame)

        def OnPreferences(self, event):
            OnPreferences(DrFrame)
            self.BtnSaveSize.Enable (self.parent.DocList_savesizeposition == 1)

        def OnSave(self, event):
            index = -1
            for i in range (self.ResultList.GetItemCount()):
                index = self.ResultList.GetNextItem(index, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
                if index == -1:
                    break
                oldindex = int (self.getColumnText(index, 2)) - 1
                if DrFrame.txtDocumentArray[oldindex].GetModify():
                    DrFrame.documentnotebook.SetSelection (oldindex)
                    DrFrame.documentnotebook.SetTab()

                    DrFrame.OnSave(None)
                    #if really_saved
                    #ask again
                    if not DrFrame.txtDocumentArray[oldindex].GetModify():

                        #change icon to not modified
                        self.ResultList.SetItemImage(index, -1, -1)
                        #update filename in listctrl
                        self.ResultList.SetStringItem(index, 0, DrFrame.documentnotebook.GetPageText(oldindex))


            self.ResultList.SetFocus()

        def OnHelp(self, event):
            OnHelp(DrFrame)

        def OnUp(self, event):
            firstindex = self.ResultList.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
            #is it on the top?
            if firstindex < 1: #or null
                return

            #deselect all other items
            index = firstindex
            for i in range (self.ResultList.GetItemCount()):
                index = self.ResultList.GetNextItem(index, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
                if index == -1:
                    break
                self.ResultList.SetItemState(index, 0, wx.LIST_STATE_SELECTED)

            self.reorderd = True
            a = self.getColumnText(firstindex, 0)
            b = self.getColumnText(firstindex, 1)
            c = self.getColumnText(firstindex, 2)
            d = self.getColumnText(firstindex, 3)
            a_ind = self.ResultList.GetItem(firstindex, 0).GetImage()


            self.ResultList.DeleteItem (firstindex)
            newindex = firstindex - 1

            self.ResultList.InsertImageStringItem(newindex, a, a_ind)

            self.ResultList.SetStringItem(newindex, 1, b)
            self.ResultList.SetStringItem(newindex, 2, c)
            self.ResultList.SetStringItem(newindex, 3, d)
            self.ResultList.SetItemState(newindex, wx.LIST_STATE_SELECTED|wx.LIST_STATE_FOCUSED , wx.LIST_STATE_SELECTED|wx.LIST_STATE_FOCUSED)
            self.ResultList.SetFocus()

        def OnDown(self, event):
            firstindex = self.ResultList.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
            #is it on the bottom?
            if firstindex + 1 >= self.ResultList.GetItemCount():
                return

            index = firstindex
            for i in range (self.ResultList.GetItemCount()):
                index = self.ResultList.GetNextItem(index, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
                if index == -1:
                    break
                self.ResultList.SetItemState(index, 0, wx.LIST_STATE_SELECTED)

            self.reorderd = True
            a = self.getColumnText (firstindex, 0)
            b = self.getColumnText (firstindex, 1)
            c = self.getColumnText (firstindex, 2)
            d = self.getColumnText (firstindex, 3)
            a_ind = self.ResultList.GetItem(firstindex, 0).GetImage()


            self.ResultList.DeleteItem (firstindex)
            newindex = firstindex+1

            self.ResultList.InsertImageStringItem(newindex, a, a_ind)

            self.ResultList.SetStringItem(newindex, 1, b)
            self.ResultList.SetStringItem(newindex, 2, c)
            self.ResultList.SetStringItem(newindex, 3, d)
            self.ResultList.SetItemState(newindex, wx.LIST_STATE_SELECTED|wx.LIST_STATE_FOCUSED , wx.LIST_STATE_SELECTED|wx.LIST_STATE_FOCUSED)
            self.ResultList.SetFocus()


        def OnCloseDocument(self, event):
            firstindex = self.ResultList.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)


            index = -1
            indexarray = []
            #how many are selected: save indexes
            for i in range (self.ResultList.GetItemCount()):
                index = self.ResultList.GetNextItem(index, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
                if index == -1:
                    break
                indexarray.append (index)

            while indexarray != []:
                #take the first
                index = indexarray.pop (0)
                to_close = True
                oldindex = int (self.getColumnText(index, 2))

                if to_close:
                    DrFrame.setDocumentTo(oldindex - 1)
                    oldpagecount = DrFrame.documentnotebook.GetPageCount()

                    DrFrame.OnClose(None)

                    if DrFrame.documentnotebook.GetPageCount() != oldpagecount:
                        self.ResultList.DeleteItem (index)
                        if indexarray != []:
                            for l in range(len(indexarray)):
                                indexarray [l] -= 1
                        #refresh indexes above the deleted
                        for i in range (self.ResultList.GetItemCount()):
                            oldnr = int (self.getColumnText(i, 2))

                            if oldnr > oldindex:
                                self.ResultList.SetStringItem(i, 2, str (oldnr-1))


            cnt = self.ResultList.GetItemCount()
            to_select = firstindex
            if firstindex >= cnt:
                to_select = cnt -1

            self.ResultList.SetItemState(to_select, wx.LIST_STATE_SELECTED|wx.LIST_STATE_FOCUSED , wx.LIST_STATE_SELECTED|wx.LIST_STATE_FOCUSED)

            #document position should comply with listctrl
            DrFrame.documentnotebook.SetSelection (to_select)
            DrFrame.documentnotebook.SetTab()
            self.ResultList.SetFocus()


        def OnKeyDown(self, event):
            keycode = event.GetKeyCode()
            if keycode == wx.WXK_DELETE:
                self.OnCloseDocument(event)
            else:
                #sort columns
                sort_column = -1
                if keycode == wx.WXK_F3:
                    sort_column = 0
                elif keycode == wx.WXK_F4:
                    sort_column = 1
                elif keycode == wx.WXK_F5:
                    sort_column = 2
                elif keycode == wx.WXK_F2:
                    sort_column = 3
                if sort_column != -1:
                    self.nCol = sort_column
                    self.SortHeader()

        def OnHeaderClick(self, event):

            self.nCol = event.GetColumn()
            self.SortHeader()
            event.Skip()

        def SortHeader(self):
            self.reorderd = True
            if self.oldsortcolumn != -1:
                self.ResultList.ClearColumnImage(self.oldsortcolumn)

            if self.oldsortcolumn != self.nCol:
                self.sort_asc = True
                self.oldsortcolumn = self.nCol
            else:
                self.sort_asc = not self.sort_asc

            if self.sort_asc:
                idx = self.sm_up
            else:
                idx = self.sm_dn
            self.ResultList.SetColumnImage(self.nCol, idx)

            self.ResultList.SortItems(self.columnSorter)

            nItem = self.ResultList.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
            self.ResultList.EnsureVisible(nItem)



        #refresh listbox
        def RefreshListFiles(self):
            self.ResultList.DeleteAllItems()
            for i in range (len(DrFrame.txtDocumentArray)):
                if DrFrame.txtDocumentArray[i].GetModify():
                    self.ResultList.InsertImageStringItem(i, self.listfiles[i][0], self.idx1)
                else:
                    self.ResultList.InsertImageStringItem(i, self.listfiles[i][0], -1)
                self.ResultList.SetStringItem(i, 1, self.listfiles[i][1])
                self.ResultList.SetStringItem(i, 2, self.listfiles[i][2])
                self.ResultList.SetStringItem(i, 3, self.listfiles[i][3])
                self.ResultList.SetItemData(i, i)
                """
                if i % 2:
                    print "rechts"
                    self.ResultList.SetBackgroundColour((128, 128, 128))
                    self.ResultList.SetTextColour((255, 0, 0))
                else:
                    print "links"
                    self.ResultList.SetBackgroundColour((255, 0, 0))
                    self.ResultList.SetTextColour((128, 128, 128))
                """

        def columnSorter(self, key1, key2):
            #lowercase is best solution
            if not self.sort_asc:
                key1, key2 = key2, key1
            item1 = self.listfiles[key1][self.nCol].lower()
            item2 = self.listfiles[key2][self.nCol].lower()
            #numerical for Nr
            if self.nCol == 2:
                item1 = int (item1)
                item2 = int (item2)
            if item1 == item2:
                #path: sort filenames then
                if self.nCol == 3:
                    item1 = self.listfiles[key1][0].lower()
                    item2 = self.listfiles[key2][0].lower()
                    if item1 == item2:
                        return 0
                    elif item1 < item2:
                        return -1
                    else:
                        return 1
                #ext: sort path then
                elif self.nCol == 1:
                    item1 = self.listfiles[key1][3].lower()
                    item2 = self.listfiles[key2][3].lower()
                    if item1 == item2:
                        item1 = self.listfiles[key1][0].lower()
                        item2 = self.listfiles[key2][0].lower()
                        #ext: sort filename then
                        if item1 == item2:
                            return 0
                        elif item1 < item2:
                            return -1
                        else:
                            return 1
                        return 0
                    elif item1 < item2:
                        return -1
                    else:
                        return 1
                #filename: not likely, that to many are the same
                else:
                    return 0
            elif item1 < item2:
                return -1
            else:
                return 1

        def MakeNewDocumentList(self):
            txtDocumentArraySic = DrFrame.txtDocumentArray[:]
            #txtPromptArraySic = DrFrame.txtPromptArray[:]
            pagessic = []
            for i in range (self.ResultList.GetItemCount()):
                pagessic.append (DrFrame.documentnotebook.GetPage(0))
                DrFrame.documentnotebook.RemovePage (0)

            #rearrange documents and txtDocumentArray
            DrFrame.txtDocumentArray = []
            #DrFrame.txtPromptArray = []
            for i in range (self.ResultList.GetItemCount()):
                oldindex = int (self.getColumnText(i, 2)) -1
                DrFrame.txtDocumentArray.append (txtDocumentArraySic[oldindex])
                #DrFrame.txtPromptArray.append (txtPromptArraySic[oldindex])
                DrFrame.txtDocumentArray[i].targetPosition = i
                #DrFrame.txtPromptArray[i].targetPosition = i
                DrFrame.documentnotebook.AddPage (pagessic[oldindex], self.getColumnText(i, 0))
                DrFrame.txtDocumentArray[i].OnModified (None)
                if DrFrame.txtDocumentArray[i].GetModify():
                    DrFrame.documentnotebook.SetPageImage (i, 1)
                else:
                    DrFrame.documentnotebook.SetPageImage (i, 0)


        def getColumnText(self, index, col):
            item = self.ResultList.GetItem(index, col)
            return item.GetText()

        def OnbtnOK(self, event):
            #find the first selected item
            nItem = self.ResultList.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
            if self.reorderd:
                self.MakeNewDocumentList()
            DrFrame.documentnotebook.SetSelection (nItem)
            DrFrame.documentnotebook.SetTab()
            self.Destroy()

        def OnbtnCancel(self, event):
            if self.reorderd:
                self.MakeNewDocumentList()
                #look for old selected item and try to select again
                for i in range (self.ResultList.GetItemCount()):
                    if int (self.getColumnText (i, 2)) == self.lastselected + 1:
                        nItem = i
                        break
                #if it doesn't exist anymore (deleted) jump to first item
                else:
                    nItem = 0
                DrFrame.documentnotebook.SetSelection (nItem)
                DrFrame.documentnotebook.SetTab()
            else:
                pass

            DrFrame.Raise()
            DrFrame.SetFocus()
            DrFrame.txtDocument.SetFocus()
            self.Destroy()

        def getModifiedBitmap(self):
            return wx.BitmapFromImage(self.getModifiedImage())

        def getModifiedImage(self):
            stream = cStringIO.StringIO(self.getModifiedData())
            return wx.ImageFromStream(stream)

        def getSmallUpArrowBitmap(self):
            return wx.BitmapFromImage(self.getSmallUpArrowImage())

        def getSmallUpArrowImage(self):
            stream = cStringIO.StringIO(self.getSmallUpArrowData())
            return wx.ImageFromStream(stream)

        def getSmallDnArrowBitmap(self):
            return wx.BitmapFromImage(self.getSmallDnArrowImage())

        def getSmallDnArrowImage(self):
            stream = cStringIO.StringIO(self.getSmallDnArrowData())
            return wx.ImageFromStream(stream)

        def getModifiedData(self):
            return \
'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\
\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
\x00\x01\xe3IDATx\x9c\xa5\x93\xbdjTA\x14\x80\xbf\x99\xc9\xee\xb2\x12c\x14Q0D\
\x14\x1ba\xed\xd2\x08b\x91\xd6\xd6\xc2\'\xb0\xf3\x01\xc4\xda\x17\xb0\xf3%D+\
\x11\r"H@\xd0BC\x10d%\x85,"A\xa3\xac\xe1\xde;?\xe7\x1c\x8b\xdd\xec\xde\x08\
\xda\xe4\xc0p\xa6\x98\xf9\xce\xc793\xce\xcc\x8c#\xc4\x02\xc0\xab\xa5S\xac\
\xde\xbc\xc5\xee\xd5u\x9c9\x8a*E\xa1\x14Cd\xb2W5\x0ej\r^?\xe3\xdb\xcb\xa7\\\
\xab\xf7&\x80\xc53\xe7\xb8\xb8~\x83t\xf9:1))\x1a\x12\x05\xa2\xa1\xd9p@hU\xdd\
\xdcx\xc2\x95\xb3\x97\xe6\x06\x00\x1e\xe3\xe4\x8a\x91\xb3RJA\xc4\xe1=x\x1fp.\
\xe0\xbd\xc7{O\x08\x01\xf7h\x85\xbc\xb3{\x18\x00\x9e\x85\x9e@(t\x9d\x9b\x1d\
\xfe;\x87\x10\xf8\xe9\x1c\xaaq\x0e03Ld\x82iU\xfaW6QHy\x0ep"X\x8ex\xefq\xce\
\xfd\xf72\x80\xe5\x8c\xe5\xd6\x14L\x14\x9a4\x03\x1c\x84\xaa\xa2\xaa\xc8\xd4\
\xee\xc0\x96"hJm\x80\xe0wF,\xdf}\x00U\x83V5\x12#\x163\xda4h\x93\xb0\x98\xd04\
\xc9\xfd:R\x17i5Q\x05\x9a\xc8xc\x93\xe1\xe0<\x9dN\x07z@\xaf\x03K\x9dI\xe9/_\
\xc9[\x9f\xb8\xb0x\x02\xdf\xed\xa2\xed\x1e\x98\x08T\r\x14\xa1\xdc\xbbM\xf7\
\xddG:k\x03\x8e\xaf\xae\xcc\xd4\x7f<~\xc1\xc2\xdbmL\xa6\xfa\xa5Lg7\xed\x816\
\x11-\x85\xf1xL\xbas\x9f\xea\xcd{\xea\xba\x9e-\x91\xcc1<\xbe\x08\xa4L\xc2\
\xe6\x06\xaa\x82\xd45&B\xce\x13\xb5\x9c3UU\xcd\x0cD\x84e\x02N\x14Q=\x0c\xf0\
\xc5a1C\x11B\x08\xec=\x7fH\xaf\xd7\xc3Z\x00\'\xc2i\x02\xbf\xcd\xa80\n\xad16\
\xcd>\xdfG\x9f\xc9\xa5\xc2>l\xd1\xed\xf71 \xce\x9f)n8d\x97\x9a_&\xecc\x8c\
\xd8g\rpG\xfd\xce\x7f\x00\x84\xd8)\x90\xe6\x1ct\xb0\x00\x00\x00\x00IEND\xaeB\
`\x82'


        def getSmallUpArrowData(self):
            return \
'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\
\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
\x00\x00<IDATx\x9ccddbf\xa0\x040Q\xa4{h\x18\xf0\xff\xdf\xdf\xffd\x1b\x00\xd3\
\x8c\xcf\x10\x9c\x06\xa0k\xc2e\x08m\xc2\x00\x97m\xd8\xc41\x0c \x14h\xe8\xf2\
\x8c\xa3)q\x10\x18\x00\x00R\xd8#\xec\x95{\xc4\x11\x00\x00\x00\x00IEND\xaeB`\
\x82'


#----------------------------------------------------------------------

        def getSmallDnArrowData(self):
            return \
"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\
\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
\x00\x00HIDATx\x9ccddbf\xa0\x040Q\xa4{\xd4\x00\x06\x06\x06\x06\x06\x16t\x81\
\xff\xff\xfe\xfe'\xa4\x89\x91\x89\x99\x11\xa7\x0b\x90%\ti\xc6j\x00>C\xb0\x89\
\xd3.\x10\xd1m\xc3\xe5*\xbc.\x80i\xc2\x17.\x8c\xa3y\x81\x01\x00\xa1\x0e\x04e\
\x1d\xc4;\xb7\x00\x00\x00\x00IEND\xaeB`\x82"

#----------------------------------------------------------------------

    def OnDocumentList(event):
        if not DrFrame.txtDocumentArray:
            drScrolledMessageDialog.ShowMessage(DrFrame, \
                "Nothing to do", "Documentument List", wx.DefaultPosition, wx.Size(200, 150))
        else:
            d = drDocumentListDialog(DrFrame, -1, "Document List")
            d.Show()

    def SwapDocuments (first, second):


        #remove document
        secondpage = DrFrame.documentnotebook.GetPage(second)

        #this is easy
        secondpagetext = DrFrame.documentnotebook.GetPageText(second)
        DrFrame.documentnotebook.RemovePage (second)
        #secondtxtdocument = DrFrame.txtDocumentArray[second]

        #exchange documents
        firsttxtdocument = DrFrame.txtDocumentArray[first]
        #firsttxtprompt = DrFrame.txtPromptArray[first]

        DrFrame.txtDocumentArray[first] = DrFrame.txtDocumentArray[second]
        #DrFrame.txtPromptArray[first] = DrFrame.txtPromptArray[second]

        DrFrame.txtDocumentArray[second] = firsttxtdocument
        #DrFrame.txtPromptArray[second] = firsttxtprompt

        #exchange targetpositions
        DrFrame.txtDocumentArray[second].targetPosition = second
        #DrFrame.txtPromptArray[second].targetPosition = second

        DrFrame.txtDocumentArray[first].targetPosition = first
        #DrFrame.txtPromptArray[first].targetPosition = first

        #thanks Dan's bug report
        DrFrame.documentnotebook.InsertPage(first, secondpage, secondpagetext, 0)

        #fix: otherwise the pageimages are not displayed properly
        if DrFrame.txtDocumentArray[first].GetModify():
            DrFrame.documentnotebook.SetPageImage (first, 1)
        else:
            DrFrame.documentnotebook.SetPageImage (first, 0)
        DrFrame.documentnotebook.oldselection = second
        #end fix

        DrFrame.documentnotebook.SetSelection (second)
        DrFrame.documentnotebook.SetTab()


    def OnMoveDocumentRight(event):
        first = DrFrame.txtDocument.targetPosition
        if first >= len(DrFrame.txtDocumentArray) - 1:
            return
        second = first + 1
        SwapDocuments (first, second)


    def OnMoveDocumentLeft(event):
        first = DrFrame.txtDocument.targetPosition
        if first < 1:
            return
        second = first - 1
        SwapDocuments (first, second)

    def OnToggleDocuments(event):
        if DrFrame.DocumentList_to_toggle == -1 or \
            DrFrame.DocumentList_to_toggle >= len(DrFrame.txtDocumentArray):
            DrFrame.DocumentList_to_toggle = 0

        oldpos = DrFrame.docPosition
        if oldpos == DrFrame.DocumentList_to_toggle:
            if DrFrame.DocumentList_to_toggle == 0:
                if len(DrFrame.txtDocumentArray) > 1:
                    DrFrame.DocumentList_to_toggle = 1
                else:
                    #nothing other possible
                    DrFrame.DocumentList_to_toggle = 0
            else:
                DrFrame.DocumentList_to_toggle = 0
        DrFrame.setDocumentTo(DrFrame.DocumentList_to_toggle)
        DrFrame.DocumentList_to_toggle = oldpos

    DrFrame.DocumentList_to_toggle = -1
    ID_DOCUMENTLIST = DrFrame.GetNewId()
    ID_MOVEDOCUMENTLEFT = DrFrame.GetNewId()
    ID_MOVEDOCUMENTRIGHT = DrFrame.GetNewId()
    ID_TOGGLEDOCUMENTS = DrFrame.GetNewId()
    DrFrame.DocList_savesizeposition = 0

    if os.path.exists(DrFrame.pluginspreferencesdirectory + "/DocList.preferences.dat"):
        f = file(DrFrame.pluginspreferencesdirectory + "/DocList.preferences.dat", 'r')
        text = f.read()
        f.close()
        DrFrame.DocList_savesizeposition = drPrefsFile.GetPrefFromText(DrFrame.DocList_savesizeposition, text, "doclist.savesizeposition", True)


    DrFrame.Bind(wx.EVT_MENU, OnDocumentList, id = ID_DOCUMENTLIST)
    DrFrame.Bind(wx.EVT_MENU, OnMoveDocumentLeft, id = ID_MOVEDOCUMENTLEFT)
    DrFrame.Bind(wx.EVT_MENU, OnMoveDocumentRight, id = ID_MOVEDOCUMENTRIGHT)
    DrFrame.Bind(wx.EVT_MENU, OnToggleDocuments, id = ID_TOGGLEDOCUMENTS)

    DrFrame.AddPluginShortcutFunction("DocList", "Document List", OnDocumentList)
    DrFrame.AddPluginShortcutFunction("DocList", "Move Document Left", OnMoveDocumentLeft)
    DrFrame.AddPluginShortcutFunction("DocList", "Move Document Right", OnMoveDocumentRight)
    DrFrame.AddPluginShortcutFunction("DocList", "Toggle Documents", OnToggleDocuments)

    DrFrame.AddPluginPopUpMenuFunction("DocList", "Document List", OnDocumentList)
    DrFrame.AddPluginPopUpMenuFunction("DocList", "Move Document Left", OnMoveDocumentLeft)
    DrFrame.AddPluginPopUpMenuFunction("DocList", "Move Document Right", OnMoveDocumentRight)
    DrFrame.AddPluginPopUpMenuFunction("DocList", "Toggle Documents", OnToggleDocuments)

    DrFrame.LoadPluginShortcuts('DocList')

    #exist already?
    try:
        DrFrame.miscmenu
    except:
        #else create
        DrFrame.miscmenu = wx.Menu()

        if DrFrame.PLATFORM_IS_WIN:
            menuBarName = "&Misc"
        else:
            menuBarName = "Misc"
    
        DrFrame.menuBar.Insert(8, DrFrame.miscmenu, menuBarName)

    doclistmenu = wx.Menu()
    doclistmenu.Append(ID_DOCUMENTLIST, DrFrame.GetPluginMenuLabel('DocList', 'Document List', 'Document List...'))
    doclistmenu.Append(ID_MOVEDOCUMENTLEFT, DrFrame.GetPluginMenuLabel('DocList', 'Move Document Left', 'Move Document Left'))
    doclistmenu.Append(ID_MOVEDOCUMENTRIGHT, DrFrame.GetPluginMenuLabel('DocList', 'Move Document Right', 'Move Document Right'))
    doclistmenu.Append(ID_TOGGLEDOCUMENTS, DrFrame.GetPluginMenuLabel('DocList', 'Toggle Documents', 'Toggle Documents'))

    DrFrame.miscmenu.AppendMenu(DrFrame.GetNewId(), "DocList", doclistmenu)

    #DrFrame.documentsmenu.InsertSeparator(6)
    #DrFrame.documentsmenu.Insert(7, ID_DOCUMENTLIST, DrFrame.GetPluginMenuLabel('DocList', 'Document List', 'Document List...'))
    #DrFrame.documentsmenu.Insert(8, ID_MOVEDOCUMENTLEFT, DrFrame.GetPluginMenuLabel('DocList', 'Move Document Left', 'Move Document Left'))
    #DrFrame.documentsmenu.Insert(9, ID_MOVEDOCUMENTRIGHT, DrFrame.GetPluginMenuLabel('DocList', 'Move Document Right', 'Move Document Right'))
    #DrFrame.documentsmenu.Insert(10, ID_TOGGLEDOCUMENTS, DrFrame.GetPluginMenuLabel('DocList', 'Toggle Documents', 'Toggle Documents'))
    #DrFrame.menuBar.Append(DrFrame.miscmenu,"&Misc")
