# -*- coding: utf-8 -*-

# Copyright (c) 2004 - 2006 Detlev Offenbach <detlev@die-offenbachs.de>
#

"""
Compatibility module to use the KDE File Dialog instead of the Qt File Dialog.
"""

try:
    import os
    if os.getenv("e3nokde"):
        raise ImportError
        
    from kfile import KFileDialog, KFile, KRecentDocument
    from qt import QString, QStringList, QRegExp, qApp
    
    def __convertFilter(filter, selectedFilter = None):
        """
        Private function to convert a Qt file filter to a KDE file filter.
        
        @param filter Qt file filter (QString or string)
        @param selectedFilter this is set to the selected filter
        @return the corresponding KDE file filter (QString)
        """
        rx = QRegExp("^[^(]*\(([^)]*)\).*$")
        fileFilters = QStringList.split(';;', filter)
        
        newfilter = QStringList()
        for fileFilter in fileFilters:
            sf = selectedFilter and selectedFilter.compare(fileFilter) == 0
            namefilter = QString(fileFilter).replace(rx, "\\1")
            fileFilter = QString(fileFilter).replace('/', '\\/')
            if sf:
                newfilter.prepend("%s|%s" % (namefilter, fileFilter))
            else:
                newfilter.append("%s|%s" % (namefilter, fileFilter))
        return newfilter.join('\n')
    
    def getOpenFileName(startWith = QString.null, filter = QString.null, parent = None,
                        name = None, caption = QString.null, selectedFilter = None,
                        resolveSymlinks = 1):
        """
        Function to open a modal dialog to get the name of an existing file.
        
        @param startWith the file dialogs working directory. If this includes
            a file name, the file will be selected.
        @param filter only files matching the selected filter will be shown
        @param parent parent widget of the dialog 
        @param name name of the dialog
        @param caption the caption of the dialog
        @param selectedFilter this is set to the selected filter
        @param resolveSymlinks flag to indicate, whether symbolic links should be followed
        """
        if not QString(filter).isEmpty():
            filter = __convertFilter(filter, selectedFilter)
        dlg = KFileDialog(startWith, filter, parent, "filedialog", 1)
        dlg.setOperationMode(KFileDialog.Opening)
        
        dlg.setMode(KFile.File | KFile.LocalOnly)
        dlg.setCaption(\
            caption is QString.null and qApp.translate('KFileDialog', 'Open') or caption)
        
        dlg.exec_loop()
        
        if selectedFilter is not None:
            flt = dlg.currentFilter()
            flt.prepend("(").append(")")
            selectedFilter.replace(0, selectedFilter.length(), flt)
            
        return dlg.selectedFile()
    
    def getSaveFileName(startWith = QString.null, filter = QString.null, parent = None,
                        name = None, caption = QString.null, selectedFilter = None,
                        resolveSymlinks = 1):
        """
        Function to open a modal dialog to get the name of an existing file.
        
        @param startWith the file dialogs working directory. If this includes
            a file name, the file will be selected.
        @param filter only files matching the selected filter will be shown
        @param parent parent widget of the dialog 
        @param name name of the dialog
        @param caption the caption of the dialog
        @param selectedFilter this is set to the selected filter
        @param resolveSymlinks flag to indicate, whether symbolic links should be followed
        """
        if not QString(filter).isEmpty():
            filter = __convertFilter(filter, selectedFilter)
        specialdir = not QString(startWith).isEmpty() and str(QString(startWith).at(0)) == ':'
        dlg = KFileDialog(specialdir and startWith or QString.null,
                          filter, parent, "filedialog", 1)
        if not specialdir:
            dlg.setSelection(startWith)
        dlg.setOperationMode(KFileDialog.Saving)
        
        dlg.setMode(KFile.File | KFile.LocalOnly)
        dlg.setCaption(\
            caption is QString.null and qApp.translate('KFileDialog', 'Save As') or caption)
        
        dlg.exec_loop()
        
        filename = dlg.selectedFile()
        if not filename.isEmpty():
            KRecentDocument.add(filename)
            
            if selectedFilter is not None:
                flt = dlg.currentFilter()
                flt.prepend("(").append(")")
                selectedFilter.replace(0, selectedFilter.length(), flt)
        
        return filename
        
    def getOpenFileNames(filter = QString.null, startWith = QString.null, parent = None,
                        name = None, caption = QString.null, selectedFilter = None,
                        resolveSymlinks = 1):
        """
        Function to open a modal dialog to get the name of an existing file.
        
        @param filter only files matching the selected filter will be shown
        @param startWith the file dialogs working directory. If this includes
            a file name, the file will be selected.
        @param parent parent widget of the dialog 
        @param name name of the dialog
        @param caption the caption of the dialog
        @param selectedFilter this is set to the selected filter
        @param resolveSymlinks flag to indicate, whether symbolic links should be followed
        """
        if not QString(filter).isEmpty():
            filter = __convertFilter(filter, selectedFilter)
        dlg = KFileDialog(startWith, filter, parent, "filedialog", 1)
        dlg.setOperationMode(KFileDialog.Opening)
        
        dlg.setMode(KFile.Files | KFile.LocalOnly)
        dlg.setCaption(\
            caption is QString.null and qApp.translate('KFileDialog', 'Open') or caption)
        
        dlg.exec_loop()
        
        if selectedFilter is not None:
            flt = dlg.currentFilter()
            flt.prepend("(").append(")")
            selectedFilter.replace(0, selectedFilter.length(), flt)
            
        return dlg.selectedFiles()
        
    def getExistingDirectory(startWith = QString.null, parent = None,
                        name = None, caption = QString.null, dirOnly = 1,
                        resolveSymlinks = 1):
        """
        Function to open a modal dialog to get the name of an existing file.
        
        @param startWith the file dialogs working directory. If this includes
            a file name, the file will be selected.
        @param parent parent widget of the dialog 
        @param name name of the dialog
        @param caption the caption of the dialog
        @param dirOnly flag indicating, whether only directories should be shown
        @param resolveSymlinks flag to indicate, whether symbolic links should be followed
        """
        dlg = KFileDialog(startWith, QString.null, parent, "filedialog", 1)
        dlg.setOperationMode(KFileDialog.Opening)
        
        dlg.setMode(KFile.Directory | KFile.LocalOnly | KFile.ExistingOnly)
        dlg.setFilter(QString.null)
        dlg.setCaption(caption is QString.null and \
                       qApp.translate('KFileDialog', 'Select Directory') or caption)
        
        dlg.exec_loop()
        
        return dlg.selectedFile()
        
    __iconProvider = None
    
    def setIconProvider(provider):
        """
        Function to set the icon provider.
        
        This variant just stores the icon provider. KDE has it's own mechanisms built in.
        
        @param provider QFileIconProvider
        """
        global __iconProvider
        __iconProvider = provider
        
    def iconProvider():
        """
        Function to return the previously stored icon provider.
        
        @return QFileIconProvider
        """
        global __iconProvider
        return __iconProvider
    
except (ImportError, RuntimeError):
    import qt
    getOpenFileName = qt.QFileDialog.getOpenFileName
    getSaveFileName = qt.QFileDialog.getSaveFileName
    getOpenFileNames = qt.QFileDialog.getOpenFileNames
    getExistingDirectory = qt.QFileDialog.getExistingDirectory
    setIconProvider = qt.QFileDialog.setIconProvider
    iconProvider = qt.QFileDialog.iconProvider
