#include "uimanager.h"
#include "dialogs.h"
#include <qdir.h> // needed first because of X header conflict
#include "aniplayer.h"
#include "slideshow.h"
#include "screengrab.h"
#include "dirtree.h"
#include "hotlistbox.h"
#include "imagepreview.h"
#include "browser.h"
#include "menuid.h"
#include "imageheaders.h"
#include "htmlexportwizard.h"
#include "htmlexport.h"
#include "imagecompare.h"
#include "rightclick.h"

#include "imagebuffer.h"
#include "ifapp.h"
#include "dndlistbox.h"
#include "imagelistitem.h"
#include "scaledtoplevel.h"
#include "scrolltoplevel.h"
#include "fullscreen.h"
#include "filelist.h"
#include "about.h"
#include "imageutils.h"
#include "catagorymgr.h"
#include <qlabel.h>
#include <qcursor.h>
#include <qtabwidget.h>
#include <qinputdialog.h>
#include <qfile.h>
#include <qfileinfo.h>
#include <qtoolbutton.h>
#include <qstatusbar.h>
#include <qtextstream.h>
#include <qclipboard.h>
#include <qpainter.h>
#include <qpaintdevicemetrics.h>

#include <klocale.h>
//#include <kimageeffect.h>
#include <kprogress.h>
#include <kprinter.h>
#include <ktoolbar.h>
#include <kglobal.h>
#include <kstddirs.h>
#include <kiconloader.h>
#include <kmenubar.h>
#include <kfiledialog.h>
#include <krun.h>
#include <kurl.h>
#include <kmimetype.h>
#include <kmessagebox.h>
#include <kstdaccel.h>
#include <kstatusbar.h>
#include <kcolordialog.h>
//#include <kwinmodule.h>

#include <kio/previewjob.h>

#include <sys/stat.h>
#include <sys/types.h>

UIManager::UIManager(KIFFileList *list, const char *)
    : KDockMainWindow()
{
    connect(kifapp(), SIGNAL(hideAllWindows()), this,
            SLOT(slotHideAll()));
    connect(kifapp(), SIGNAL(showAllWindows()), this,
            SLOT(slotShowAll()));

    loadAllSettings();
    isBlocked = false;
    showOnlyCatagory = -1;
    pathStr = QDir::current().absPath();

    KStatusBar *sBar = statusBar(); // Statusbar
    progress = new KProgress(100, sBar);
    progress->setMinimumWidth(80);
    sBar->addWidget(progress);
    statusLbl = new QLabel(sBar);
    statusLbl->setText(i18n("Pixie (C)BSD Daniel M. Duley"));
    sBar->addWidget(statusLbl, true);

    KDockWidget *mainDock = createDockWidget(i18n("Thumbnails"), QPixmap());

    mainWidget = new PixieBrowser(this, mainDock);
    connect(mainWidget, SIGNAL(clicked(Thumbnail *)), this,
            SLOT(slotThumbClicked(Thumbnail *)));
    connect(mainWidget, SIGNAL(doubleClicked(Thumbnail *)), this,
            SLOT(slotThumbDblClicked(Thumbnail *)));
    connect(mainWidget, SIGNAL(returnPressed(Thumbnail *)), this,
            SLOT(slotThumbDblClicked(Thumbnail *)));
    connect(mainWidget, SIGNAL(enableStopButton(bool)), this,
            SLOT(slotEnableStopBtn(bool)));
    connect(mainWidget, SIGNAL(updateProgress(int)), progress,
            SLOT(setValue(int)));
    connect(mainWidget, SIGNAL(setStatusBarText(const QString &)), this,
            SLOT(slotSetStatus(const QString &)));
    connect(mainWidget, SIGNAL(updateMe()), this,
            SLOT(slotUpdateView()));

    connect(mainWidget, SIGNAL(enableUpDir(bool)), this,
            SLOT(slotEnableUpDir(bool)));
    connect(mainWidget, SIGNAL(enableBackDir(bool)), this,
            SLOT(slotEnableBackDir(bool)));
    connect(mainWidget, SIGNAL(enableForwardDir(bool)), this,
            SLOT(slotEnableForwardDir(bool)));

    mainDock->setWidget(mainWidget);
    setView(mainDock);
    setMainDockWidget(mainDock);
    KDockWidget *treeDock = createDockWidget(i18n("Files"), QPixmap(), NULL,
                                             i18n("Directory tree/loaded files"));
    treeTabWidget = new QTabWidget(treeDock);

    dirTree = new PixieDirTree(treeTabWidget);
    //treeTabWidget->addTab(dirTree, SmallIcon("folder.png"), i18n("Folders"));
    treeTabWidget->addTab(dirTree, i18n("Folders"));
    /*
    connect(dirTree, SIGNAL(doubleClicked(QListViewItem *)), this,
            SLOT(slotTreeClicked(QListViewItem *)));
    connect(mainWidget, SIGNAL(dirChanged(const QString &)), dirTree,
            SLOT(slotReloadPath(const QString &)));*/
    connect(dirTree, SIGNAL(locationChanged(const QString &)), this,
            SLOT(slotDirectoryTree(const QString &)));

    fileList = new KIFFileList(treeTabWidget);
    if(list)
       *fileList = *list;
    connect(fileList, SIGNAL(editImage(const QString &)), this,
            SLOT(slotLoadEditorFile(const QString &)));
    connect(fileList, SIGNAL(save()), this,
            SLOT(slotSaveFileList()));

    treeTabWidget->addTab(fileList, i18n("Files"));
    connect(fileList, SIGNAL(selected(QListBoxItem *)), this,
            SLOT(slotURLSelected(QListBoxItem *)));

    KIFHotListBox *hotList = new KIFHotListBox(this, treeTabWidget);
    connect(hotList, SIGNAL(hotListClicked(const QString &)), this,
            SLOT(slotHotListClicked(const QString &)));
    treeTabWidget->addTab(hotList, i18n("HotList"));

    KConfig *config = KGlobal::config();
    config->setGroup("UISettings");
    treeTabWidget->setCurrentPage(config->readNumEntry("TreeTab", 0));
    treeDock->setWidget(treeTabWidget);
    treeDock->manualDock(mainDock, KDockWidget::DockLeft, 40);


    imageBuffer = new KIFImage(this);
    KDockWidget *imageDock = createDockWidget(i18n("Image preview"), QPixmap(), NULL,
                                              i18n("Image Preview"));
    imagePreview = new KIFImagePreview(imageDock);

    scaledTopLevel = NULL;
    scrollTopLevel = NULL;
    fullScreenTopLevel = NULL;
    if(viewMode == ScaledWindowID){
        scaledTopLevel = new KIFScaledTopLevel(imageBuffer, NULL);
        connect(scaledTopLevel, SIGNAL(selectionChanged(const QRect &)),
                imageBuffer, SLOT(slotSelectionChanged(const QRect &)));
        connect(scaledTopLevel, SIGNAL(prevList()), fileList,
                SLOT(slotPrevInList()));
        connect(scaledTopLevel, SIGNAL(nextList()), fileList,
                SLOT(slotNextInList()));
        connect(scaledTopLevel, SIGNAL(prevImage()), this,
                SLOT(slotPrevInDir()));
        connect(scaledTopLevel, SIGNAL(nextImage()), this,
                SLOT(slotNextInDir()));
    }
    else if(viewMode == ScrollWindowID){
        scrollTopLevel = new KIFScrollTopLevel(imageBuffer, NULL);
        connect(scrollTopLevel, SIGNAL(prevList()), fileList,
                SLOT(slotPrevInList()));
        connect(scrollTopLevel, SIGNAL(nextList()), fileList,
                SLOT(slotNextInList()));
        connect(scrollTopLevel, SIGNAL(prevImage()), this,
                SLOT(slotPrevInDir()));
        connect(scrollTopLevel, SIGNAL(nextImage()), this,
                SLOT(slotNextInDir()));
    }
    else if(viewMode == FullscreenID){
        fullScreenTopLevel = new KIFFullScreen(imageBuffer, false, NULL);
        connect(fullScreenTopLevel, SIGNAL(prevList()), fileList,
                SLOT(slotPrevInList()));
        connect(fullScreenTopLevel, SIGNAL(nextList()), fileList,
                SLOT(slotNextInList()));
        connect(fullScreenTopLevel, SIGNAL(prevImage()), this,
                SLOT(slotPrevInDir()));
        connect(fullScreenTopLevel, SIGNAL(nextImage()), this,
                SLOT(slotNextInDir()));
    }
    else if(viewMode == FullscreenMaxpectID){
        fullScreenTopLevel = new KIFFullScreen(imageBuffer, true, NULL);
        connect(fullScreenTopLevel, SIGNAL(prevList()), fileList,
                SLOT(slotPrevInList()));
        connect(fullScreenTopLevel, SIGNAL(nextList()), fileList,
                SLOT(slotNextInList()));
        connect(fullScreenTopLevel, SIGNAL(prevImage()), this,
                SLOT(slotPrevInDir()));
        connect(fullScreenTopLevel, SIGNAL(nextImage()), this,
                SLOT(slotNextInDir()));
    }

    imageDock->setWidget(imagePreview);
    imageDock->manualDock(treeDock, KDockWidget::DockBottom, 40);

    //keys = new QAccel(this);
    createMenu(this);
    createToolbar(this);

    resize(525,350);
    readDockConfig(KGlobal::config(), "DockSetup");
    show();
    kapp->processEvents();

    backDirBtn->setEnabled(false);
    forwardDirBtn->setEnabled(false);
    upDirBtn->setEnabled(false);
    mainWidget->loadPath(pathStr, sizeToPixels(iconSize), sorting,
                         showOnlyCatagory, catagoriesFirst, imageOnly,
                         imagesOnTop, "");
    //dirTree->setPath(pathStr);
    historyIt = historyList.prepend(pathStr);
    backDirBtn->setEnabled(false);
    forwardDirBtn->setEnabled(false);
    setCaption(i18n("Pixie Image/Photo Editing Browser"));
}

UIManager::~UIManager()
{
    writeDockConfig(KGlobal::config(), "DockSetup");

    KConfig *config = KGlobal::config();
    config->setGroup("UISettings");
    config->writeEntry("TreeTab", treeTabWidget->currentPageIndex());
    config->sync();
    if(scaledTopLevel)
        delete scaledTopLevel;
    else if(scrollTopLevel)
        delete scrollTopLevel;
    else if(fullScreenTopLevel)
        delete fullScreenTopLevel;

    delete fileComp;
    delete editMnu;

}

bool UIManager::imageShown()
{
    if((scaledTopLevel && scaledTopLevel->isVisible()) ||
       (scrollTopLevel && scrollTopLevel->isVisible()) ||
       (fullScreenTopLevel && fullScreenTopLevel->isVisible()))
        return(true);
    return(false);
}

void UIManager::loadAllSettings()
{
    KConfig *config  = KGlobal::config();
    config->setGroup("UISettings");
    sorting = config->readNumEntry("Sorting", (int)AscendingByNameID);

    catagoriesFirst = config->readBoolEntry("CatagoryFirst", false);

    iconSize = config->readNumEntry("IconSize", (int)LargeID);

    viewMode = config->readNumEntry("ViewMode", (int)FullscreenID);

    imageOnly = config->readBoolEntry("ImageOnly", false);

    imagesOnTop = config->readBoolEntry("ImagesOnTop", true);

    autoPreview = config->readBoolEntry("AutoPreview", false);

    internalImagePreview = config->readBoolEntry("InternalPreview", true);
    lowQualityPreview = config->readBoolEntry("LowQualityPreview", false);
    useEmbeddedTIFF = config->readBoolEntry("EmbeddedTIFFPreview", true);
    useEmbeddedJPEG = config->readBoolEntry("EmbeddedJPEGPreview", false);

    previewText = config->readBoolEntry("PreviewText", false);
    previewClipart = config->readBoolEntry("PreviewClipart", false);
    previewPSPDF = config->readBoolEntry("PreviewPS", false);
    previewKOffice = config->readBoolEntry("PreviewKOffice", false);
    previewOffice = config->readBoolEntry("PreviewOffice", false);
    previewArchive = config->readBoolEntry("PreviewArchive", false);
    previewHTML = config->readBoolEntry("PreviewHTML", false);
    previewSound = config->readBoolEntry("PreviewSound", false);

    previewVideo = config->readBoolEntry("PreviewVideo", false);
    /*videoMPlayer = config->readBoolEntry("VideoMPlayer", true);
     videoKDE = config->readBoolEntry("VideoKDE", false);*/
    linkView = config->readBoolEntry("LinkView", false);
}

void UIManager::slotDirectoryTree(const QString &str)
{
    if(linkView){
        pathStr = str;
        pathEdit->setEditText(pathStr);
        pathEdit->addToHistory(pathStr);
        mainWidget->loadPath(pathStr, sizeToPixels(iconSize), sorting,
                             showOnlyCatagory, catagoriesFirst, imageOnly,
                             imagesOnTop, "");

        historyIt = historyList.prepend(pathStr);
        slotEnableForwardDir(false);
        slotEnableBackDir(historyIt != historyList.fromLast());
    }
}

void UIManager::slotHotListClicked(const QString &path)
{
    QDir d(path);
    if(d.exists()){
        pathStr = d.absPath(); // get rid of crap in the URL
        pathEdit->setEditText(pathStr);
        pathEdit->addToHistory(pathStr);
        //dirTree->setPath(pathStr);
        mainWidget->loadPath(pathStr, sizeToPixels(iconSize), sorting,
                             showOnlyCatagory, catagoriesFirst, imageOnly,
                             imagesOnTop, "");

        historyIt = historyList.prepend(pathStr);
        slotEnableForwardDir(false);
        slotEnableBackDir(historyIt != historyList.fromLast());
    }
}

void UIManager::resetImageBuffer()
{
    imagePreview->resetFilename();
}

void UIManager::slotURLSelected(QListBoxItem *i)
{
    if(imagePreview->filename() == ((KIFImageListItem *)i)->fileName()){
        qWarning("Using cached image");
        imageBuffer->setImage(imagePreview->currentImage());
    }
    else{
        QApplication::setOverrideCursor(WaitCursor);
        imageBuffer->slotSetFile(((KIFImageListItem *)i)->fileName());
        QApplication::restoreOverrideCursor();
    }

    if(scaledTopLevel){
        if(!scaledTopLevel->isVisible())
            scaledTopLevel->show();
        scaledTopLevel->setCaption(i->text());
    }
    else if(scrollTopLevel){
        if(!scrollTopLevel->isVisible())
            scrollTopLevel->show();
        scrollTopLevel->setCaption(i->text());
    }
    else if(fullScreenTopLevel){
        if(!fullScreenTopLevel->isVisible())
            fullScreenTopLevel->show();
    }
}

void UIManager::slotAddAndSetURL(const QString &path)
{
    if(QFile::exists(path)){
        fileList->slotAppendAndSet(path);
        QListBoxItem *i = fileList->findItem(path);
        slotURLSelected(i);
    }
    else{

    }
}

void UIManager::slotAddURL(const QString &path)
{
    if(QFile::exists(path)){
        fileList->slotAppend(path);
    }
}

// remove
void UIManager::slotSetTopItem()
{
    if(fileList->count() > 0){
        fileList->setCurrentItem(0);
        imageBuffer->slotSetFile(((KIFImageListItem *)fileList->item(0))->
                                  fileName());
    }
}

// remove
int UIManager::findURLIndex(const QString &url)
{
    unsigned int i;
    for(i=0; i < fileList->count(); ++i){
        if(fileList->text(i) == url)
            return(i);
    }
    return(-1);
}

void UIManager::slotOpen()
{
    qWarning("In slotOpen");
    QString str = KFileDialog::getOpenFileName(QDir::currentDirPath(),
                                               QString::null, this,
                                               i18n("Open image"));
    if(!str.isEmpty())
        slotAddAndSetURL(str);
}

#ifndef CONVERT_FUNCS_DEFINED
#define CONVERT_FUNCS_DEFINED
inline double convertMMToInch(double mm){return(mm*0.039370147);}
inline double convertInchToMM(double inch){return(inch*25.399956);}
#endif
#define US_MEASURE 0
#define METRIC_MEASURE 1

void UIManager::slotPrint()
{
    KPrinter printer;
    if(printer.setup(this)){
        // get page layout options
        bool dither, zoomSmall, scaleLarge;
        int metricType;
        KConfig *config = KGlobal::config();
        QSize defMargin = printer.margins();
        QPaintDeviceMetrics metrics(&printer);

        config->setGroup("Print");
        dither = config->readBoolEntry("Dither", false);
        scaleLarge = config->readBoolEntry("Scale", true);
        zoomSmall = config->readBoolEntry("Zoom", false);
        metricType = config->readBoolEntry("MetricType", 0);

        // do the margins
        double l, r, t, b;
        double defH, defV;
        defH = ((double)defMargin.width())/metrics.logicalDpiX();
        defV = ((double)defMargin.height())/metrics.logicalDpiY();
        if(metricType == METRIC_MEASURE){
            defH = convertInchToMM(defH);
            defV = convertInchToMM(defV);
        }
        l = config->readDoubleNumEntry("LMargin", defH);
        r = config->readDoubleNumEntry("RMargin", defH);
        t = config->readDoubleNumEntry("TMargin", defV);
        b = config->readDoubleNumEntry("BMargin", defV);
        if(metricType == METRIC_MEASURE){
            l = convertMMToInch(l);
            r = convertMMToInch(r);
            t = convertMMToInch(t);
            b = convertMMToInch(b);
        }
        l = l*metrics.logicalDpiX();
        r = l*metrics.logicalDpiX();
        t = l*metrics.logicalDpiY();
        b = l*metrics.logicalDpiY();
        int x, y, w, h;
        x = (int)l;
        y = (int)t;
        w = (int)(metrics.width()-l-r);
        h = (int)(metrics.height()-t-b);

        // okay, margins done - x, y, w, h are the coords in dots
        QPixmap pix;
        //pix.convertFromImage(*imageBuffer->image());
        // FIXME - background color?
        convertImageToPixmap(*imageBuffer->image(), pix);

        if(scaleLarge && (pix.width() > w || pix.height() > h)){
            int newW = pix.width();
            int newH = pix.height();
            while(newW > w || newH > h){
                if(newW > w){
                    float percent = ((float)w)/newW;
                    newW = (int)(newW*percent);
                    newH = (int)(newH*percent);
                    qWarning("Scaling width");
                }
                if(newH > h){
                    float percent = ((float)h)/newH;
                    newW = (int)(newW*percent);
                    newH = (int)(newH*percent);
                    qWarning("Scaling height");
                }
            }
            QImage img = pix.convertToImage();
            img = img.smoothScale(newW, newH);
            // might as well dither here while we have a QImage
            if(dither && (img.numColors() == 0)){
                qWarning("Dithering");
                img = img.convertDepth(8, AvoidDither | DiffuseDither);
            }
            pix.convertFromImage(img);
        }
        else if(dither && pix.depth() > 8 || pix.depth() == 0){
            QImage img = pix.convertToImage();
            img = img.convertDepth(8, AvoidDither | DiffuseDither);
            pix.convertFromImage(img);
        }
        QPainter p(&printer);
        p.drawPixmap(x, y, pix);
    }
}

void UIManager::slotCopy()
{
    mainWidget->copy();
}

void UIManager::slotPaste()
{
    mainWidget->paste();
}

void UIManager::slotPageLayout()
{
    KPrinter p;
    KIFPrintDialog dlg(p, this);
    dlg.exec();
}


void UIManager::slotSlideShow()
{
    KIFSlideDialog dlg(this);
    if(dlg.exec() == QDialog::Accepted){
        QStringList list;
        if(dlg.useFileList()){
            if(fileList->count() == 0){
                KMessageBox::sorry(this,
                             i18n("The FileList is empty!\nTry the folder option."),
                             i18n("Pixie Slideshow Error"));
                return;
            }
            QListBoxItem *item = fileList->firstItem();
            while(item){
                list.append(item->text());
                item = item->next();
            }
        }
        else{
            QString fn;
            QStringList selList;
            mainWidget->sortSelectionByView();
            mainWidget->selectionStringList(selList);
            if(!selList.isEmpty()){
                for(QStringList::Iterator it = selList.begin(); it != selList.end(); ++it){
                    if(isImageType(*it))
                        list.append(pathStr + "/" + (*it));
                }
            }
            else{
                Thumbnail *itemList = mainWidget->allItems();
                int i, c = mainWidget->count();
                for(i=0; i < c; ++i){
                    if(isImageType(itemList[i].filename))
                        list.append(pathStr + "/" + itemList[i].filename);
                }
            }
            if(list.isEmpty()){
                KMessageBox::sorry(this,
                                   i18n("No images in the current folder!"),
                                   i18n("Pixie SlideShow Error"));
                return;
            }
        }
        (void)new KIFSlideShow(list, dlg.delay(), dlg.useMaxpect(),
                               dlg.loop(), dlg.effect(), dlg.animationDelay());
    }
}

void UIManager::slotReload()
{
    slotUpdateView();
}

void UIManager::slotGrab()
{
    (void)new KIFScreenGrab(this);
}

void UIManager::slotLoadEditor()
{
    /* Being replaced with MosfetPaint */
}

void UIManager::slotLoadEditorFile(const QString &str)
{
    kifapp()->loadEditor(str);
}

void UIManager::slotOpenFileList()
{
    QString fn = KFileDialog::getOpenFileName(pathStr, "*.flst", this,
                                              i18n("Open Pixie FileList"));
    if(fn.isNull())
        return;
    QFile f(fn);
    if(f.open(IO_ReadOnly)){
        fileList->clear();
        QTextStream t(&f);
        if(t.readLine() != "PixieList"){
            KMessageBox::sorry(this,  i18n("Invalid FileList file!"),
                               i18n("Pixie FileList Error!"));
            f.close();
            return;
        }
        while (!t.eof()){
            fileList->slotAppend(t.readLine());
        }
        f.close();
        fileListName = fn;
        fileMnu->setItemEnabled(100, true);
    }
    else
        KMessageBox::sorry(this,  i18n("Unable to open file!"),
                           i18n("Pixie FileList Error!"));

}

void UIManager::slotSaveFileList()
{
    if(fileListName.isNull())
        slotSaveFileListAs();
    else{
        QFile f(fileListName);
        if(f.open(IO_WriteOnly)){
            QTextStream t(&f);
            t << "PixieList\n";
            unsigned int i;
            for(i=0; i < fileList->count(); ++i)
                t << fileList->text(i) << '\n';
            f.close();
        }
        else
            KMessageBox::sorry(this, i18n("Unable to open file!"),
                               i18n("Pixie FileList Error!"));
    }
}

void UIManager::slotSaveFileListAs()
{
    QString fn = KFileDialog::getSaveFileName(pathStr, "*.flst", this,
                                              i18n("Open Pixie FileList"));
    if(fn.isNull())
        return;
    QFile f(fn);
    if(f.open(IO_WriteOnly)){
        QTextStream t(&f);
        t << "PixieList\n";
        unsigned int i;
        for(i=0; i < fileList->count(); ++i)
            t << fileList->text(i) << '\n';
        f.close();
        fileListName = fn;
        fileMnu->setItemEnabled(100, true);
    }
    else
        KMessageBox::information(this,  i18n("Unable to open file!"),
                                 i18n("Pixie FileList Error!"));
}


void UIManager::createMenu(KMainWindow *parent)
{
    KMenuBar *mbar = parent->menuBar();

    fileMnu = new QPopupMenu(parent);
    fileMnu->insertItem(BarIcon("window_new", 16), i18n("New Window"), this, SLOT(slotNewWindow()));
    fileMnu->insertSeparator();
    fileMnu->insertItem(i18n("Take a screenshot..."), this, SLOT(slotGrab()));
    fileMnu->insertItem(i18n("Slide Show..."), this, SLOT(slotSlideShow()));
    fileMnu->insertItem(i18n("Make Web Image Gallery..."), this, SLOT(slotExportHTML()));
    fileMnu->insertItem(i18n("Find Similiar Images..."), this, SLOT(slotCompareImages()));
    fileMnu->insertSeparator();
    fileMnu->insertItem(i18n("Create/Edit file categories..."), this,
                        SLOT(slotEditCatagories()));
    fileMnu->insertSeparator();
    fileMnu->insertItem(i18n("Convert PixiePlus previews to Konqueror format"),
                        this, SLOT(slotConvertThumbsToKonq()));
    fileMnu->insertItem(i18n("Convert Konqueror previews to PixiePlus format"),
                        this, SLOT(slotConvertThumbsToPixie()));
    fileMnu->insertSeparator();
    fileMnu->insertItem(BarIcon("fileopen", 16), i18n("Open..."), this, SLOT(slotOpen()));
    fileMnu->insertItem(BarIcon("folder", 16), i18n("Create a new folder..."), this, SLOT(slotNewFolder()));
    fileMnu->insertItem(i18n("Page Layout..."), this, SLOT(slotPageLayout()));
    fileMnu->insertItem(BarIcon("fileprint", 16), i18n("Print"), this, SLOT(slotPrint()));
    fileMnu->insertSeparator();
    fileMnu->insertItem(BarIcon("fileopen", 16), i18n("Open FileList..."), this, SLOT(slotOpenFileList()));
    fileMnu->insertItem(BarIcon("filesave", 16), i18n("Save FileList"), this, SLOT(slotSaveFileList()),
                        0, 100);
    fileMnu->setItemEnabled(100, false);
    fileMnu->insertItem(BarIcon("filesave", 16), i18n("Save FileList As..."), this, SLOT(slotSaveFileListAs()));
    fileMnu->insertSeparator();
    fileMnu->insertItem(BarIcon("exit", 16), i18n("&Quit"), kifapp(), SLOT(quit()));
    mbar->insertItem(i18n("&File"), fileMnu);


    editMnu = new EditMenu(this, parent);
    mbar->insertItem(i18n("&Edit"), editMnu);

    viewMenu = new QPopupMenu(parent);

    sortMenu = new QPopupMenu(viewMenu);
    sortMenu->insertItem(i18n("Ascending by name"), AscendingByNameID);
    sortMenu->insertItem(i18n("Descending by name"), DescendingByNameID);
    sortMenu->insertItem(i18n("Ascending by date"), AscendingByDateID);
    sortMenu->insertItem(i18n("Descending by date"), DescendingByDateID);
    sortMenu->insertItem(i18n("Ascending by size"), AscendingBySizeID);
    sortMenu->insertItem(i18n("Descending by size"), DescendingBySizeID);
    //sortMenu->insertItem(i18n("Ascending size/same sizes first"),
    //                     AscendingSameSizesFirstID);
    sortMenu->setItemChecked(sorting, true);
    sortMenu->insertSeparator();
    sortMenu->insertItem(i18n("Images and folders only"), ImageOnlyID);
    sortMenu->insertItem(i18n("Images on top"), ImagesOnTopID);
    sortMenu->insertItem(i18n("Categorized items on top"), CatOnTopID);
    
    sortMenu->setItemChecked(ImageOnlyID, imageOnly);
    sortMenu->setItemChecked(ImagesOnTopID, imagesOnTop);
    sortMenu->setItemChecked(CatOnTopID, catagoriesFirst);
    connect(sortMenu, SIGNAL(activated(int)), this, SLOT(slotSortMenu(int)));
    viewMenu->insertItem(i18n("Sorting"), sortMenu, 1);


    sizeMenu = new QPopupMenu(viewMenu);
    sizeMenu->insertItem(i18n("Small"), (int)SmallID);
    sizeMenu->insertItem(i18n("Medium"), (int)MediumID);
    sizeMenu->insertItem(i18n("Large"), (int)LargeID);
    sizeMenu->insertItem(i18n("Huge"), (int)HugeID);
    sizeMenu->setItemChecked(iconSize, true);
    connect(sizeMenu, SIGNAL(activated(int)), this, SLOT(slotSizeMenu(int)));
    viewMenu->insertItem(i18n("Thumbnail Size"), sizeMenu, 2);

    previewMenu = new QPopupMenu(viewMenu);
    /*
    videoMenu = new QPopupMenu(previewMenu);
    videoMenu->insertItem(i18n("Preview video files"), VideoPreviewID);
    videoMenu->insertItem(i18n("Builtin PixiePlus/MPlayer previewer"), VideoMPlayerID);
    videoMenu->insertItem(i18n("KDE/Xine previewer"), VideoKDEID);
    videoMenu->setItemChecked(VideoPreviewID, previewVideo);
    videoMenu->setItemChecked(VideoMPlayerID, videoMPlayer);
    videoMenu->setItemChecked(VideoKDEID, videoKDE);
    if(!previewVideo){
        videoMenu->setItemEnabled(VideoMPlayerID, false);
        videoMenu->setItemEnabled(VideoKDEID, false);
    }
    connect(videoMenu, SIGNAL(activated(int)), this, SLOT(slotVideoMenu(int)));
    */
    previewMenu->insertItem(i18n("Use Pixie's thumbnail format"), InternalPreviewID);
    previewMenu->insertItem(i18n("Low quality dithered previews"), LowQualityPreviewID);
    previewMenu->insertItem(i18n("Check for embedded TIFF previews"), EmbedTIFFPreviewID);
    previewMenu->insertItem(i18n("Check for embedded JPEG previews"), EmbedJPEGPreviewID);
    previewMenu->insertSeparator();
    //previewMenu->insertItem(i18n("Video files"), videoMenu);
    previewMenu->insertItem(i18n("Preview text files"), TextPreviewID);
    previewMenu->insertItem(i18n("Preview clipart files"), ClipartPreviewID);
    previewMenu->insertItem(i18n("Preview PDF/Postscript files"), PSPDFPreviewID);
    previewMenu->insertItem(i18n("Preview KOffice files"), KOfficePreviewID);
    previewMenu->insertItem(i18n("Preview other office files"), OfficePreviewID);
    previewMenu->insertItem(i18n("Preview web archives"), ArchivePreviewID);
    previewMenu->insertItem(i18n("Preview HTML pages"), HTMLPreviewID);
    previewMenu->insertItem(i18n("Preview video files"), VideoPreviewID);
    //previewMenu->insertItem(i18n("Preview sound clips"), SoundPreviewID);

    previewMenu->setItemChecked(InternalPreviewID, internalImagePreview);
    previewMenu->setItemChecked(LowQualityPreviewID, lowQualityPreview);
    previewMenu->setItemChecked(EmbedTIFFPreviewID, useEmbeddedTIFF);
    previewMenu->setItemChecked(EmbedJPEGPreviewID, useEmbeddedJPEG);
    previewMenu->setItemChecked(TextPreviewID, previewText);
    previewMenu->setItemChecked(ClipartPreviewID, previewClipart);
    previewMenu->setItemChecked(PSPDFPreviewID, previewPSPDF);
    previewMenu->setItemChecked(KOfficePreviewID, previewKOffice);
    previewMenu->setItemChecked(OfficePreviewID, previewOffice);
    previewMenu->setItemChecked(ArchivePreviewID, previewArchive);
    previewMenu->setItemChecked(HTMLPreviewID, previewHTML);
    previewMenu->setItemChecked(VideoPreviewID, previewVideo);
    //previewMenu->setItemChecked(SoundPreviewID, previewSound);

    connect(previewMenu, SIGNAL(activated(int)), this, SLOT(slotPreviewMenu(int)));
    viewMenu->insertItem(i18n("Previews"), previewMenu, 3);

    imageMenu = new QPopupMenu(viewMenu);
    imageMenu->insertItem(i18n("New window, scaled to desktop size"),
                          ScaledWindowID);
    imageMenu->insertItem(i18n("New scrollable window"), ScrollWindowID);
    imageMenu->insertItem(i18n("Fullscreen"), FullscreenID);
    imageMenu->insertItem(i18n("Fullscreen/Maxpect"), FullscreenMaxpectID);
    imageMenu->insertSeparator();
    imageMenu->insertItem(i18n("Fullscreen background color..."),
                          FullscreenColorID);

    imageMenu->setItemChecked(viewMode, true);
    connect(imageMenu, SIGNAL(activated(int)), this, SLOT(slotImageMenu(int)));
    viewMenu->insertItem(i18n("View images as..."), imageMenu, 4);

    viewMenu->insertItem(i18n("Link directory tree to browser"), 50);
    viewMenu->setItemChecked(50, linkView);

    connect(viewMenu, SIGNAL(activated(int)), this, SLOT(slotViewMenu(int)));

    mbar->insertItem(i18n("&View"), viewMenu);

    QPopupMenu *windowMenu = dockHideShowMenu();
    mbar->insertItem(i18n("&Windows"), windowMenu);

    QPopupMenu *helpMenu = new QPopupMenu(parent);
    helpMenu->insertItem(BarIcon("contents", 16), i18n("PixiePlus User's Guide"),
                         this, SLOT(slotDocumentation()));
    helpMenu->insertItem(SmallIcon("pixie", 16), i18n("About Pixie..."),
                         this, SLOT(slotAbout()));

    mbar->insertSeparator();
    mbar->insertItem(i18n("&Help"), helpMenu);
    mbar->show(); // needed for KDE3.1
}                   

void UIManager::createToolbar(KMainWindow *parent)
{
    KToolBar *tBar = parent->toolBar();

    catagoryShowMenu = new QPopupMenu();
    connect(catagoryShowMenu, SIGNAL(aboutToShow()), this,
            SLOT(slotAboutToShowCatagoryMenu()));
    connect(catagoryShowMenu, SIGNAL(activated(int)), this,
            SLOT(slotCatagoryShowMenuActivated(int)));

    tBar->insertButton("fileopen", 0, SIGNAL(clicked()), this,
                       SLOT(slotOpen()), true,
                       KStdAccel::description(KStdAccel::Open));
    tBar->insertButton("fileprint", 1, SIGNAL(clicked()), this,
                       SLOT(slotPrint()), true,
                       KStdAccel::description(KStdAccel::Print));
    tBar->insertButton("editcopy", 2, SIGNAL(clicked()), this,
                       SLOT(slotCopy()), true,
                       KStdAccel::description(KStdAccel::Copy));
    tBar->insertButton("editpaste", 3, SIGNAL(clicked()), this,
                       SLOT(slotPaste()), true,
                       KStdAccel::description(KStdAccel::Paste));
    tBar->insertButton("window_new", 4, SIGNAL(clicked()), this,
                       SLOT(slotNewWindow()), true, i18n("New Window"));
    fileTb = tBar;

    // Thumbnail viewer stuff
    tBar = parent->toolBar("thumbToolBar");
    tBar->insertButton("up", 0, SIGNAL(clicked()), this,
                       SLOT(slotUpDir()), true,
                       KStdAccel::description(KStdAccel::Up));
    tBar->insertButton("back", 1, SIGNAL(clicked()), this,
                       SLOT(slotBackDir()), true,
                       KStdAccel::description(KStdAccel::Back));
    tBar->insertButton("forward", 2, SIGNAL(clicked()), this,
                       SLOT(slotForwardDir()), true,
                       KStdAccel::description(KStdAccel::Forward));
    tBar->insertButton("gohome", 3, SIGNAL(clicked()), this,
                       SLOT(slotHomeClicked()), true,
                       KStdAccel::description(KStdAccel::Home));
    tBar->insertButton("reload", 4, SIGNAL(clicked()), this,
                       SLOT(slotReload()), true,
                       KStdAccel::description(KStdAccel::Reload));
    tBar->insertButton("thumb", 5, SIGNAL(clicked()), this,
                       SLOT(slotUpdateClicked()), true,
                       i18n("Create Thumbnails"));
    tBar->insertButton("stop", 6, SIGNAL(clicked()), this,
                       SLOT(slotStopClicked()), true, i18n("Stop"));
    tBar->insertButton("catagory", 7, catagoryShowMenu, true,
                      i18n("Show Only Categories..."));


    upDirBtn = tBar->getButton(0);
    backDirBtn = tBar->getButton(1);
    forwardDirBtn = tBar->getButton(2);
    stopBtn = tBar->getButton(6);

    tBar->addSeparator();
    pathEdit = new KHistoryCombo(tBar);
    pathEdit->setDuplicatesEnabled(false);
    fileComp = new PixieComp(mainWidget);
    pathEdit->setCompletionObject(fileComp);
    pathEdit->setEditText(QDir::current().absPath());
    pathEdit->addToHistory(QDir::current().absPath());
    connect(pathEdit, SIGNAL(returnPressed(const QString &)), this,
            SLOT(slotPathEdit(const QString &)));
    pathEdit->setDuplicatesEnabled(false);
    pathEdit->setMinimumWidth(200);

    tBar->setStretchableWidget(pathEdit);
    thumbTb = tBar;
}

void UIManager::slotAboutToShowCatagoryMenu()
{
    QStringList catList(*kifapp()->catagoryManager()->catagoryList());
    QStringList::Iterator it;
    int id;
    bool valid = false;

    catagoryShowMenu->clear();
    catagoryShowMenu->insertItem(i18n("Show All Items"), 5000);
    QString tmpStr(i18n("Show only: "));
    for(it=catList.begin(); it != catList.end(); ++it){
        id = kifapp()->catagoryManager()->id((*it));
        catagoryShowMenu->insertItem(tmpStr + (*it), id);
        qWarning("Inserting category %s, id: %d",
                 ((*it)).latin1(), id);
        if(showOnlyCatagory == id){
            valid = true;
            catagoryShowMenu->setItemChecked(id, true);
        }
    }
    if(!valid)
        showOnlyCatagory = -1;
    qWarning("Show only catagory: %d", showOnlyCatagory);
}

void UIManager::slotCatagoryShowMenuActivated(int id)
{
    unsigned int i;
    for(i=0; i < catagoryShowMenu->count(); ++i)
        catagoryShowMenu->setItemChecked(catagoryShowMenu->idAt(i), false);
    if(id != 5000){
        catagoryShowMenu->setItemChecked(id, true);
        showOnlyCatagory = id;
    }
    else
        showOnlyCatagory = -1;
    slotUpdateView();
}

void UIManager::slotPathEdit(const QString &str)
{
    QFileInfo fi(str);
    fileComp->addItem(str);
    pathEdit->addToHistory(str);
    if(fi.exists() && fi.isDir()){
        pathStr = str;
        //dirTree->setPath(pathStr);
        mainWidget->loadPath(pathStr, sizeToPixels(iconSize), sorting,
                             showOnlyCatagory, catagoriesFirst, imageOnly,
                             imagesOnTop, "");
    }
    else{
        pathStr = fi.dirPath();
        //dirTree->setPath(pathStr);
        mainWidget->loadPath(pathStr, sizeToPixels(iconSize), sorting,
                             showOnlyCatagory, catagoriesFirst, imageOnly,
                             imagesOnTop, fi.fileName());
    }
    historyIt = historyList.prepend(str);
    slotEnableForwardDir(false);
    slotEnableBackDir(historyIt != historyList.fromLast());
}

void UIManager::slotUpDir()
{
    QDir dir(pathStr);
    if(dir.cdUp()){
        pathStr = dir.absPath();
        pathEdit->setEditText(pathStr);
        pathEdit->addToHistory(pathStr);
        //dirTree->setPath(pathStr);
        mainWidget->loadPath(pathStr, sizeToPixels(iconSize), sorting,
                             showOnlyCatagory, catagoriesFirst, imageOnly,
                             imagesOnTop, "");
        historyIt = historyList.prepend(pathStr);
        slotEnableForwardDir(false);
        slotEnableBackDir(historyIt != historyList.fromLast());
    }
}

void UIManager::slotBackDir()
{
    if(historyIt == historyList.fromLast()){ // shouldn't happen
        historyIt = historyList.fromLast();
        slotEnableForwardDir(historyIt != historyList.begin());
        slotEnableBackDir(false);
        return;
    }
    ++historyIt;
    QString str(*historyIt);
    QFileInfo fi(str);
    pathEdit->setEditText(str);
    if(fi.exists() && fi.isDir()){
        pathStr = str;
        //dirTree->setPath(pathStr);
        mainWidget->loadPath(pathStr, sizeToPixels(iconSize), sorting,
                             showOnlyCatagory, catagoriesFirst, imageOnly,
                             imagesOnTop, "");
    }
    else{
        pathStr = fi.dirPath();
        //dirTree->setPath(pathStr);
        mainWidget->loadPath(pathStr, sizeToPixels(iconSize), sorting,
                             showOnlyCatagory, catagoriesFirst, imageOnly,
                             imagesOnTop, fi.fileName());
    }
    slotEnableForwardDir(historyIt != historyList.begin());
    slotEnableBackDir(historyIt != historyList.fromLast());
}

void UIManager::slotForwardDir()
{
    if(historyIt == historyList.begin()){ // shouldn't happen
        slotEnableForwardDir(false);
        slotEnableBackDir(historyIt != historyList.fromLast());
        return;
    }
    --historyIt;
    QString str(*historyIt);
    QFileInfo fi(str);
    pathEdit->setEditText(str);
    if(fi.exists() && fi.isDir()){
        pathStr = str;
        //dirTree->setPath(pathStr);
        mainWidget->loadPath(pathStr, sizeToPixels(iconSize), sorting,
                             showOnlyCatagory, catagoriesFirst, imageOnly,
                             imagesOnTop, "");
    }
    else{
        pathStr = fi.dirPath();
        //dirTree->setPath(pathStr);
        mainWidget->loadPath(pathStr, sizeToPixels(iconSize), sorting,
                             showOnlyCatagory, catagoriesFirst, imageOnly,
                             imagesOnTop, fi.fileName());
    }
    slotEnableForwardDir(historyIt != historyList.begin());
    slotEnableBackDir(historyIt != historyList.fromLast());
}

void UIManager::slotEnableUpDir(bool en)
{
    if(isBlocked)
        cachedUpEnabled = en;
    else
        upDirBtn->setEnabled(en);
}

void UIManager::slotEnableBackDir(bool en)
{
    if(isBlocked)
        cachedBackEnabled = en;
    else
        backDirBtn->setEnabled(en);
}

void UIManager::slotEnableForwardDir(bool en)
{
    if(isBlocked)
        cachedForwardEnabled = en;
    else
    forwardDirBtn->setEnabled(en);
}

void UIManager::slotHomeClicked()
{
    pathStr = QDir::homeDirPath();
    pathEdit->setEditText(pathStr);
    pathEdit->addToHistory(pathStr);
    //dirTree->setPath(pathStr);
    mainWidget->loadPath(pathStr, sizeToPixels(iconSize), sorting,
                         showOnlyCatagory, catagoriesFirst, imageOnly,
                         imagesOnTop, "");
    historyIt = historyList.prepend(pathStr);
    slotEnableForwardDir(false);
    slotEnableBackDir(historyIt != historyList.fromLast());
}

void UIManager::slotUpdateView()
{
    mainWidget->loadPath(pathStr, sizeToPixels(iconSize), sorting,
                         showOnlyCatagory, catagoriesFirst, imageOnly,
                         imagesOnTop, "");
}

void UIManager::slotUpdateClicked()
{
    mainWidget->slotGenerateThumbnails();
}

void UIManager::slotStopClicked()
{
    mainWidget->stop();
}

void UIManager::slotThumbClicked(Thumbnail *i)
{
    if(!imagePreview->isVisible()){
        slotSetStatus(i18n("Double click to view fullsize"));
        return;
    }
    if(!i)
        return;
    QString fullPathStr = pathStr + "/" + i->filename;
    if(fullPathStr == imagePreview->filename())
        return;
    if(S_ISDIR(i->status->st_mode)){
        slotSetStatus(i18n("Double click to enter folder"));
    }
    else{
        if(mainWidget->isImage(i, fullPathStr, false)){
            QApplication::setOverrideCursor(WaitCursor);
            imagePreview->slotSetFile(fullPathStr);
            QApplication::restoreOverrideCursor();
            setCaption(i->filename);
            slotSetStatus(i18n("Double click to view fullsize"));
        }
        else
            slotSetStatus(i18n("Double click to run"));
    }
}

void UIManager::slotThumbDblClicked(Thumbnail *i)
{
    if(!i)
        return;
    QString fullPathStr = pathStr + "/" + i->filename;
    if(S_ISDIR(i->status->st_mode)){
        QDir d(fullPathStr);
        pathStr = d.absPath(); // get rid of crap in the URL
        pathEdit->setEditText(pathStr);
        pathEdit->addToHistory(pathStr);
        //dirTree->setPath(pathStr);
        mainWidget->loadPath(pathStr, sizeToPixels(iconSize), sorting,
                             showOnlyCatagory, catagoriesFirst, imageOnly,
                             imagesOnTop, "");
        slotSetStatus(i18n("Entered new folder"));
        historyIt = historyList.prepend(pathStr);
        slotEnableForwardDir(false);
        slotEnableBackDir(historyIt != historyList.fromLast());
    }
    else{
        // if it's an image, display and add to filelist - else exec
        // default app
        if(mainWidget->isImage(i, fullPathStr, false)){
            const char *ext = extension(i->filename);
            bool isGIF = qstricmp(ext, "gif") == 0;
            if(isGIF && isAnimatedGIF(QFile::encodeName(fullPathStr)))
                (void)new KIFAniPlayer(fullPathStr);
            else
                slotAddAndSetURL(fullPathStr);
            slotSetStatus(i18n("Image Loaded"));
        }
        else{
            slotSetStatus(i18n("Running application for ") + i->filename);
            new KRun(KURL("file:"+fullPathStr));
        }
    }
}

void UIManager::slotNextInDir()
{
    int i, c = mainWidget->count();
    Thumbnail *itemList = mainWidget->allItems();

    i = mainWidget->currentIndex();
    if(i == -1)
        i = 0;
    else
        ++i;
    while(i < c){
        if(mainWidget->isImage(&itemList[i], mainWidget->absPath() + "/" +
                               itemList[i].filename, false)){
            mainWidget->setCurrentItem(i);
            slotAddAndSetURL(pathStr+"/"+itemList[i].filename);
            slotSetStatus(i18n("Image loaded"));
            return;
        }
        ++i;
    }
}

void UIManager::slotPrevInDir()
{
    int i;
    Thumbnail *itemList = mainWidget->allItems();

    i = mainWidget->currentIndex();
    if(i == -1)
        return;
    --i;
    while(i >= 0){
        if(mainWidget->isImage(&itemList[i], mainWidget->absPath() + "/" +
                               itemList[i].filename, false)){
            mainWidget->setCurrentItem(i);
            slotAddAndSetURL(pathStr+"/"+itemList[i].filename);
            slotSetStatus(i18n("Image loaded"));
            return;
        }
        --i;
    }
}


void UIManager::slotEnableStopBtn(bool on)
{
    stopBtn->setEnabled(on);
}

void UIManager::slotSetStatus(const QString &str)
{
    statusLbl->setText(str);
}

void UIManager::slotViewMenu(int id)
{
    qWarning("In slotViewMenu, id: %d", id);
    if(id == 50){
        KConfig *config = KGlobal::config();
        QString oldGrp = config->group();
        config->setGroup("UISettings");
        linkView = !linkView;
        config->writeEntry("LinkView", linkView);
        config->sync();
        viewMenu->setItemChecked(50, linkView);
    }
}

void UIManager::slotSortMenu(int i)
{
    KConfig *config = KGlobal::config();
    QString oldGrp = config->group();
    config->setGroup("UISettings");
    if(i == CatOnTopID){
        catagoriesFirst = !catagoriesFirst;
        sortMenu->setItemChecked(CatOnTopID, catagoriesFirst);
        config->writeEntry("CatagoryFirst", catagoriesFirst);
    }
    else if(i == ImagesOnTopID){
        imagesOnTop = !imagesOnTop;
        sortMenu->setItemChecked(ImagesOnTopID, imagesOnTop);
        config->writeEntry("ImagesOnTop", imagesOnTop);
    }
    else if(i == ImageOnlyID){
        imageOnly = !imageOnly;
        sortMenu->setItemChecked(ImagesOnTopID, imageOnly);
        config->writeEntry("ImageOnly", imageOnly);
    }
    else{
        int tmp;
        for(tmp=0; tmp < 6; ++tmp)
            sortMenu->setItemChecked(tmp, false);
        sortMenu->setItemChecked(i, true);
        sorting = i;

        config->writeEntry("Sorting", sorting);
    }
    config->sync();
    config->setGroup(oldGrp);
    mainWidget->loadPath(pathStr, sizeToPixels(iconSize), sorting,
                         showOnlyCatagory, catagoriesFirst, imageOnly,
                         imagesOnTop, "");
}

void UIManager::slotPreviewMenu(int id)
{
    KConfig *config = KGlobal::config();
    QString oldGrp = config->group();
    config->setGroup("UISettings");

    if(id == InternalPreviewID){
        internalImagePreview = !internalImagePreview;
        previewMenu->setItemChecked(InternalPreviewID, internalImagePreview);
        config->writeEntry("InternalPreview", internalImagePreview);
    }
    else if(id == EmbedTIFFPreviewID){
        useEmbeddedTIFF = !useEmbeddedTIFF;
        previewMenu->setItemChecked(EmbedTIFFPreviewID, useEmbeddedTIFF);
        config->writeEntry("EmbeddedTIFFPreview", useEmbeddedTIFF);
    }
    else if(id == EmbedJPEGPreviewID){
        useEmbeddedJPEG = !useEmbeddedJPEG;
        previewMenu->setItemChecked(EmbedJPEGPreviewID, useEmbeddedJPEG);
        config->writeEntry("EmbeddedJPEGPreview", useEmbeddedJPEG);
    }
    else if(id == LowQualityPreviewID){
        lowQualityPreview = !lowQualityPreview;
        previewMenu->setItemChecked(LowQualityPreviewID, lowQualityPreview);
        config->writeEntry("LowQualityPreview", lowQualityPreview);
    }
    else if(id == TextPreviewID){
        previewText = !previewText;
        previewMenu->setItemChecked(TextPreviewID, previewText);
        config->writeEntry("PreviewText", previewText);
    }
    else if(id == ClipartPreviewID){
        previewClipart = !previewClipart;
        previewMenu->setItemChecked(ClipartPreviewID, previewClipart);
        config->writeEntry("PreviewClipart", previewClipart);
    }
    else if(id == PSPDFPreviewID){
        previewPSPDF = !previewPSPDF;
        previewMenu->setItemChecked(PSPDFPreviewID, previewPSPDF);
        config->writeEntry("PreviewPS", previewPSPDF);
    }
    else if(id == KOfficePreviewID){
        previewKOffice = !previewKOffice;
        previewMenu->setItemChecked(KOfficePreviewID, previewKOffice);
        config->writeEntry("PreviewKOffice", previewKOffice);
    }
    else if(id == OfficePreviewID){
        previewOffice = !previewOffice;
        previewMenu->setItemChecked(OfficePreviewID, previewOffice);
        config->writeEntry("PreviewOffice", previewOffice);
    }
    else if(id == ArchivePreviewID){
        previewArchive = !previewArchive;
        previewMenu->setItemChecked(ArchivePreviewID, previewArchive);
        config->writeEntry("PreviewArchive", previewArchive);
    }
    else if(id == HTMLPreviewID){
        previewHTML = !previewHTML;
        previewMenu->setItemChecked(HTMLPreviewID, previewHTML);
        config->writeEntry("PreviewHTML", previewHTML);
    }/*
    else if(id == SoundPreviewID){
        previewSound = !previewSound;
        previewMenu->setItemChecked(SoundPreviewID, previewSound);
        config->writeEntry("PreviewSound", previewSound);
    }*/
    else if(id == VideoPreviewID){
        previewVideo = !previewVideo;
        previewMenu->setItemChecked(VideoPreviewID, previewVideo);
        config->writeEntry("PreviewVideo", previewVideo);
    }

    config->sync();
    config->setGroup(oldGrp);
    mainWidget->loadPath(pathStr, sizeToPixels(iconSize), sorting,
                         showOnlyCatagory, catagoriesFirst, imageOnly,
                         imagesOnTop, "");
}


void UIManager::slotSizeMenu(int i)
{
    KConfig *config = KGlobal::config();
    config->setGroup("UISettings");
    sizeMenu->setItemChecked((int)SmallID, false);
    sizeMenu->setItemChecked((int)MediumID, false);
    sizeMenu->setItemChecked((int)LargeID, false);
    sizeMenu->setItemChecked((int)HugeID, false);
    sizeMenu->setItemChecked(i, true);
    config->writeEntry("IconSize", i);
    iconSize = i;
    config->sync();
    mainWidget->loadPath(pathStr, sizeToPixels(iconSize), sorting,
                         showOnlyCatagory, catagoriesFirst, imageOnly,
                         imagesOnTop, "");
}

void UIManager::slotVideoMenu(int id)
{
    KConfig *config = KGlobal::config();
    QString oldGrp = config->group();
    config->setGroup("UISettings");

    if(id == VideoPreviewID){
        previewVideo = !previewVideo;
        videoMenu->setItemChecked(VideoPreviewID, previewVideo);
        config->writeEntry("PreviewVideo", previewVideo);
        videoMenu->setItemEnabled(VideoKDEID, previewVideo);
        videoMenu->setItemEnabled(VideoMPlayerID, previewVideo);
    }
    if(id == VideoKDEID){
        videoKDE = !videoKDE;
        videoMenu->setItemChecked(VideoKDEID, videoKDE);
        config->writeEntry("VideoKDE", videoKDE);
    }
    else if(id == VideoMPlayerID){
        videoMPlayer = !videoMPlayer;
        videoMenu->setItemChecked(VideoMPlayerID, videoMPlayer);
        config->writeEntry("VideoMPlayer", videoMPlayer);

    }
    config->sync();
}

void UIManager::slotImageMenu(int id)
{
    KConfig *config = KGlobal::config();
    config->setGroup("UISettings");

    if(id == FullscreenColorID){
        QColor c(config->readColorEntry("FullScreenColor", &Qt::white));
        if(KColorDialog::getColor(c, this) == QDialog::Accepted){
            if(fullScreenTopLevel)
                fullScreenTopLevel->setColor(c);
            config->writeEntry("FullScreenColor", c);
            config->sync();
        }
        return;
    }
    viewMode = id;
    imageMenu->setItemChecked((int)ScaledWindowID, false);
    imageMenu->setItemChecked((int)ScrollWindowID, false);
    imageMenu->setItemChecked((int)FullscreenID, false);
    imageMenu->setItemChecked((int)FullscreenMaxpectID, false);
    imageMenu->setItemChecked(id, true);
    if(scaledTopLevel){
        delete scaledTopLevel;
        scaledTopLevel = NULL;
    }
    if(scrollTopLevel){
        delete scrollTopLevel;
        scrollTopLevel = NULL;
    }
    if(fullScreenTopLevel){
        delete fullScreenTopLevel;
        fullScreenTopLevel = NULL;
    }

    if(viewMode == ScaledWindowID){
        scaledTopLevel = new KIFScaledTopLevel(imageBuffer, NULL);
        connect(scaledTopLevel, SIGNAL(prevList()), fileList,
                SLOT(slotPrevInList()));
        connect(scaledTopLevel, SIGNAL(nextList()), fileList,
                SLOT(slotNextInList()));

        connect(scaledTopLevel, SIGNAL(prevImage()), this,
                SLOT(slotPrevInDir()));
        connect(scaledTopLevel, SIGNAL(nextImage()), this,
                SLOT(slotNextInDir()));
    }
    else if(viewMode == ScrollWindowID){
        scrollTopLevel = new KIFScrollTopLevel(imageBuffer, NULL);
        connect(scrollTopLevel, SIGNAL(prevList()), fileList,
                SLOT(slotPrevInList()));
        connect(scrollTopLevel, SIGNAL(nextList()), fileList,
                SLOT(slotNextInList()));

        connect(scrollTopLevel, SIGNAL(prevImage()), this,
                SLOT(slotPrevInDir()));
        connect(scrollTopLevel, SIGNAL(nextImage()), this,
                SLOT(slotNextInDir()));
    }
    else if(viewMode == FullscreenID){
        fullScreenTopLevel = new KIFFullScreen(imageBuffer, false, NULL);
        connect(fullScreenTopLevel, SIGNAL(prevList()), fileList,
                SLOT(slotPrevInList()));
        connect(fullScreenTopLevel, SIGNAL(nextList()), fileList,
                SLOT(slotNextInList()));

        connect(fullScreenTopLevel, SIGNAL(prevImage()), this,
                SLOT(slotPrevInDir()));
        connect(fullScreenTopLevel, SIGNAL(nextImage()), this,
                SLOT(slotNextInDir()));
    }
    else if(viewMode == FullscreenMaxpectID){
        fullScreenTopLevel = new KIFFullScreen(imageBuffer, true, NULL);
        connect(fullScreenTopLevel, SIGNAL(prevList()), fileList,
                SLOT(slotPrevInList()));
        connect(fullScreenTopLevel, SIGNAL(nextList()), fileList,
                SLOT(slotNextInList()));

        connect(fullScreenTopLevel, SIGNAL(prevImage()), this,
                SLOT(slotPrevInDir()));
        connect(fullScreenTopLevel, SIGNAL(nextImage()), this,
                SLOT(slotNextInDir()));
    }

    config->writeEntry("ViewMode", id);
    config->sync();
}

void UIManager::slotHideAll()
{
    visible = isVisible();
    if(visible)
        hide();
}

void UIManager::slotShowAll()
{
    if(visible)
        show();
}


void UIManager::slotNewWindow()
{
    kifapp()->loadBrowser(NULL);
}

void UIManager::slotAbout()
{
    KIFAboutDialog dlg;
    dlg.exec();
}

void UIManager::slotDocumentation()
{
    KURL url(KGlobal::dirs()->findResource("appdata", "doc/en/index.html"));
    new KRun(url, 0, true);
}

void UIManager::slotExportHTML()
{
    QStringList list;
    Thumbnail *itemList = mainWidget->allItems();
    QValueList<int> *selection = mainWidget->selection();
    int i, c = mainWidget->count();

    if(!c){
        KMessageBox::sorry(this,
                           i18n("The current folder is empty!"),
                           i18n("Pixie HTML Gallery Error"));
        return;
    }
    else if(selection->count() != 0){
        QValueList<int>::Iterator it;
        for(it = selection->begin(); it != selection->end(); ++it){
            i = (*it);
            if(qstrncmp("thb_", itemList[i].filename, 4) != 0){
                if(mainWidget->isImage(&itemList[i], mainWidget->absPath() +
                                       "/" + itemList[i].filename, false))
                    list.append(itemList[i].filename);
            }
        }
        if(list.isEmpty()){
            KMessageBox::sorry(this,
                               i18n("No images in the current selection!"),
                               i18n("Pixie HTML Gallery Error"));
            return;
        }
    }
    else{
        // no selection, use entire folder
        qWarning("No selection, using entire folder.");
        for(i=0; i < c; ++i){
            if(qstrncmp("thb_", itemList[i].filename, 4) != 0){
                if(mainWidget->isImage(&itemList[i], mainWidget->absPath() +
                                       "/" + itemList[i].filename, false))
                    list.append(itemList[i].filename);
            }
        }
        if(list.isEmpty()){
            KMessageBox::sorry(this,
                               i18n("No images in the current folder!"),
                               i18n("Pixie HTML Gallery Error"));
            return;
        }
    }
    list.sort();

    HTMLExportWizard wiz(list, this);
    if(wiz.exec() != QDialog::Rejected){
        HTMLExportBase exporter;
        connect(&exporter, SIGNAL(updateProgress(int)), progress,
                SLOT(setValue(int)));
        connect(&exporter, SIGNAL(setStatusBarText(const QString &)), this,
                SLOT(slotSetStatus(const QString &)));

        exporter.run(pathStr, list);
    }
}

void UIManager::slotEditCatagories()
{
    CatagoryDialog dlg(this);
    if(dlg.exec() == QDialog::Accepted)
        dlg.sync();
}

void UIManager::slotCompareImages()
{
    // This is goofy >:) A second window is created, but you need to delete
    // the compare object before it's used because KIFCompare is modal.
    KIFCompare *compare = new KIFCompare(pathStr, sizeToPixels(iconSize),
                                         this);
    KIFCompareView *view = compare->compareView();
    delete compare;
    if(view)
        view->makeThumbnails();
    else
        qWarning("Null compare view");
}

void UIManager::slotNewFolder()
{
    bool okay;
    QString folderStr = QInputDialog::getText(i18n("Folder Name"),
                                              i18n("Please enter a name for the new folder."),
                                              QLineEdit::Normal, QString::null,
                                              &okay,
                                              this);
    if(okay){
        if(mkdir((pathStr + "/" + folderStr).ascii(), 0777) == -1){
            KMessageBox::sorry(this, i18n("Could not create folder!"));
        }
    }
}

void UIManager::slotConvertThumbsToKonq()
{
    mainWidget->convertToKonqThumbs();
}

void UIManager::slotConvertThumbsToPixie()
{
    mainWidget->convertToPixieThumbs();
}

KProgress* UIManager::progressBar()
{
    return(progress);
}

QLabel* UIManager::progressLabel()
{
    return(statusLbl);
}

QStringList* UIManager::kioThumbnailTypes()
{
    kioThumbList.clear();
    if(previewMenu->isItemChecked(TextPreviewID))
        kioThumbList.append("textthumbnail");
    if(previewMenu->isItemChecked(ClipartPreviewID))
        kioThumbList.append("clipartthumbnail");
    if(previewMenu->isItemChecked(PSPDFPreviewID))
        kioThumbList.append("gsthumbnail");
    if(previewMenu->isItemChecked(KOfficePreviewID))
        kioThumbList.append("kofficethumbnail");
    if(previewMenu->isItemChecked(OfficePreviewID))
        kioThumbList.append("otherofficethumbnail");
    if(previewMenu->isItemChecked(ArchivePreviewID))
        kioThumbList.append("webarchivethumbnail");
    if(previewMenu->isItemChecked(HTMLPreviewID))
        kioThumbList.append("htmlthumbnail");
    //if(videoMenu->isItemChecked(VideoPreviewID) &&
    //   videoMenu->isItemChecked(VideoKDEID))
    //    kioThumbList.append("videothumbnail");
    if(previewMenu->isItemChecked(VideoPreviewID))
        kioThumbList.append("videothumbnail");
    return(&kioThumbList);
}

bool UIManager::useMPlayerVideo()
{
    return(false);
    //return(videoMenu->isItemChecked(VideoPreviewID) &&
    //       videoMenu->isItemChecked(VideoMPlayerID));
}

int UIManager::sizeToPixels(int iSize)
{
    switch(iSize){
    case SmallID:
        return(48);
        break;
    case MediumID:
        return(64);
        break;
    case LargeID:
        return(90);
        break;
    case HugeID:
        return(112);
        break;
    default:
        qWarning("Unknown size label in UIManager::sizeToPixels()!");
        break;
    }
    return(90);
}

void UIManager::blockUI(bool blocked)
{
    if(blocked == isBlocked)
        return;
    isBlocked = blocked;
    int i;
    KToolBar *tBar = toolBar("thumbToolBar");
    if(blocked){
        cachedBackEnabled = backDirBtn->isEnabled();
        cachedForwardEnabled = forwardDirBtn->isEnabled();
        cachedUpEnabled = upDirBtn->isEnabled();
        for(i=0; i < 8; ++i){
            if(i != 6)
                tBar->getButton(i)->setEnabled(false);
        }
        dirTree->setEnabled(false);
        fileList->setEnabled(false);
        pathEdit->setEnabled(false);

        fileTb->setEnabled(false);
        menuBar()->setEnabled(false);
    }
    else{
        backDirBtn->setEnabled(cachedBackEnabled);
        forwardDirBtn->setEnabled(cachedForwardEnabled);
        upDirBtn->setEnabled(cachedUpEnabled);
        for(i=3; i < 8; ++i)
            tBar->getButton(i)->setEnabled(true);
        dirTree->setEnabled(true);
        fileList->setEnabled(true);
        pathEdit->setEnabled(true);

        fileTb->setEnabled(true);
        menuBar()->setEnabled(true);
    }
}
