/*****************************************************************

Copyright (c) 1996-2000 the kicker authors. See file AUTHORS.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

******************************************************************/

#include <qlabel.h>
#include <qlayout.h>
#include <qfileinfo.h>

#include <kbuttonbox.h>
#include <kseparator.h>
#include <klocale.h>
#include <kiconloader.h>

#include <kmimetype.h>
#include <kfiledialog.h>
#include <kmessagebox.h>
#include <qdir.h>
#include <qfileinfo.h>
#include <kstandarddirs.h>

#include <kdebug.h>

#include "exe_dlg.h"

PanelExeDialog::PanelExeDialog(const QString &path, const QString &pixmap,
                               const QString &cmd, bool inTerm,
                               QWidget *parent, const char *name)
    : QDialog(parent, name, true)
{
    setCaption(i18n("Non-KDE Application Configuration"));
    QFileInfo fi(path);

    QLabel *fileLbl = new QLabel(i18n("Executable: "), this);
    m_exe = new KLineEdit( path, this );
    fillCompletion();
    connect(m_exe, SIGNAL(textChanged(const QString &)),
           this, SLOT(slotTextChanged(const QString &)));
    connect(m_exe, SIGNAL(returnPressed()),
           this, SLOT(slotReturnPressed()));

    QLabel *clLbl = new QLabel(i18n("Optional command line arguments:"), this);
    clEdit = new KLineEdit( cmd, this );

    termBtn = new QCheckBox(i18n("Run in terminal"), this);
    termBtn->setChecked(inTerm);
    iconBtn = new KIconButton(this);
    iconBtn->setIconType(KIcon::Panel, KIcon::Application);
    KButtonBox *bbox = new KButtonBox(this);
    bbox->addStretch(1);
    QButton *btn = bbox->addButton(i18n("Select &File..."));
    connect(btn, SIGNAL(clicked()), this, SLOT(slotSelect()));
    btn = bbox->addButton(KStdGuiItem::ok());
    connect(btn, SIGNAL(clicked()), this, SLOT(accept()));
    btn = bbox->addButton(KStdGuiItem::cancel());
    connect(btn, SIGNAL(clicked()), this, SLOT(reject()));
    bbox->layout();

    m_pixmap = pixmap;
    updateIcon();

    QGridLayout *layout = new QGridLayout(this, 11, 3, 4);
    layout->addMultiCellWidget(fileLbl, 0, 0, 0, 2);
    layout->setRowSpacing(1, 10);
    layout->addMultiCellWidget(new KSeparator(QFrame::HLine, this), 2, 2, 0, 2);
    layout->addMultiCellWidget(iconBtn, 3, 5, 2, 2);
    layout->addMultiCellWidget(fileLbl, 3, 3, 0, 1);
    layout->addMultiCellWidget(m_exe, 4, 4, 0, 1);
    layout->addMultiCellWidget(clLbl, 5, 5, 0, 1);
    layout->addMultiCellWidget(clEdit, 6, 6, 0, 1);
    layout->addMultiCellWidget(termBtn, 7, 7, 0, 1);
    layout->setRowSpacing(8, 10);
    layout->addMultiCellWidget(new KSeparator(QFrame::HLine, this), 9, 9, 0, 2);
    layout->addMultiCellWidget(bbox, 10, 10, 0, 2);
    layout->setRowStretch(9, 1);
    layout->setColStretch(0, 1);
    layout->activate();
    // leave decent space for the commandline
    resize(sizeHint().width() > 300 ? sizeHint().width() : 300,
           sizeHint().height());
}

void PanelExeDialog::updateIcon()
{
    if(!m_pixmap.isEmpty())
        iconBtn->setIcon(m_pixmap);
}

void PanelExeDialog::fillCompletion()
{
    KCompletion *comp = m_exe->completionObject();
    QStringList exePaths = KStandardDirs::systemPaths();

    for (QStringList::ConstIterator it = exePaths.begin(); it != exePaths.end(); it++)
    {
        QDir d( (*it) );
        d.setFilter( QDir::Files | QDir::Executable );

        const QFileInfoList *list = d.entryInfoList();
        if (!list)
            continue;

        QFileInfoListIterator it2( *list );
        QFileInfo *fi;

        while ( (fi = it2.current()) != 0 ) {
            m_partialPath2full.insert(fi->fileName(), fi->filePath(), false);
            comp->addItem(fi->fileName());
            comp->addItem(fi->filePath());
            ++it2;
        }
    }
}

void PanelExeDialog::slotTextChanged(const QString &str)
{
    QString exeLocation = str;
    QMap<QString, QString>::iterator it = m_partialPath2full.find(str);

    if (it != m_partialPath2full.end())
        exeLocation = it.data();
    KMimeType::pixmapForURL(KURL( exeLocation ), 0, KIcon::Panel, 0, KIcon::DefaultState, &m_pixmap);
    updateIcon();
}

void PanelExeDialog::slotReturnPressed()
{
    if (m_partialPath2full.contains(m_exe->text()))
        m_exe->setText(m_partialPath2full[m_exe->text()]);
}

void PanelExeDialog::slotSelect()
{
    QString exec = KFileDialog::getOpenFileName(QString::null, QString::null,
						                        0,i18n("Select Executable"));
    if ( exec.isEmpty() )
        return;

    QFileInfo fi(exec);
    while(!fi.isExecutable())
    {
        if(KMessageBox::warningYesNo(0, i18n("The selected file is not executable.\n"
                                             "Do you want to select another file?"))
                == KMessageBox::Yes)
        {
            exec = KFileDialog::getOpenFileName(QString::null, QString::null, 0,
                                                i18n("Select Executable"));
            if ( exec.isEmpty() )
                return;
            fi.setFile(exec);
        }
        else
            return;
	}

    m_exe->setText(exec);
    KMimeType::pixmapForURL(KURL( exec ), 0, KIcon::Panel, 0, KIcon::DefaultState, &m_pixmap);
    updateIcon();
}

#include "exe_dlg.moc"

