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

Copyright (c) 1996-2001 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 "konsole_mnu.h"
#include <kiconloader.h>
#include <klocale.h>
#include <kglobal.h>
#include <kapplication.h>
#include <krun.h>

#include <stdlib.h>
#include <dirent.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>

#include <qdir.h>
#include <qfileinfo.h>

#include <ksimpleconfig.h>
#include <kstandarddirs.h>

extern "C"
{
    void* init_kickermenu_konsole()
    {
	KGlobal::locale()->insertCatalogue("libkickermenu_konsole");
        return new KonsoleMenuFactory;
    }
}

KonsoleMenu::KonsoleMenu(QWidget *parent, const char *name)
: KPanelMenu("", parent, name)
,m_bookmarksSession(0)
,bookmarkHandler(0)
,bookmarkHandlerSession(0)
,m_menuCreated(false)
{
}

KonsoleMenu::~KonsoleMenu()
{
}

static void insertItemSorted(KPopupMenu *menu, const QIconSet &iconSet, const QString &txt, int id)
{
  const int defaultId = 1; // The id of the 'new' item.
  int index = menu->indexOf(defaultId);
  int count = menu->count();
  if (index >= 0)
  {
     index++; // Skip separator
     while(true)
     {
        index++;
        if (index >= count)
        {
           index = -1; // Insert at end
           break;
        }
        if (menu->text(menu->idAt(index)) > txt)
           break; // Insert before this item
     }
  }
  menu->insertItem(iconSet, txt, id, index);
}


void KonsoleMenu::initialize()
{
    QStringList list = KGlobal::dirs()->findAllResources("data", "konsole/*.desktop", false, true);

    QString defaultShell = locate("data", "konsole/shell.desktop");
    list.prepend(defaultShell);

    int id = 1;

    sessionList.clear();
    for (QStringList::ConstIterator it = list.begin(); it != list.end(); ++it)
    {
        if ((*it == defaultShell) && (id != 1))
           continue;
        KSimpleConfig conf(*it, true /* read only */);
        conf.setDesktopGroup();
        QString text = conf.readEntry("Name");

        // try to locate the binary
        QString exec= conf.readPathEntry("Exec");
        if (exec.startsWith("su -c \'")) {
             exec = exec.mid(7,exec.length()-8);
        }

        exec = KRun::binaryName(exec, false);
        QString pexec = KGlobal::dirs()->findExe(exec);
        if (text.isEmpty() || conf.readEntry("Type") != "KonsoleApplication"
            || ( !exec.isEmpty() && pexec.isEmpty() ) )
        {
            continue;
        }
        insertItemSorted(this, SmallIconSet(conf.readEntry("Icon", "openterm")), text, id++);
        QFileInfo fi(*it);
	sessionList.append(fi.baseName(true));
	
	if (id == 2)
	   insertSeparator();
	
    }
    bookmarkHandlerSession = new KonsoleBookmarkHandler( this, false );
    m_bookmarksSession = bookmarkHandlerSession->menu();
    insertSeparator();
    insertItem(SmallIconSet("keditbookmarks"),
                        i18n("New Session at Bookmark"), m_bookmarksSession);
    connect(m_bookmarksSession,SIGNAL(aboutToShow()),this,SLOT(makeGUI()));
      connect( bookmarkHandlerSession, SIGNAL( openURL( const QString&, const QString& )),
            SLOT( newSession( const QString&, const QString& )));


    screenList.clear();
    QCString screenDir = getenv("SCREENDIR");
    if (screenDir.isEmpty())
        screenDir = QFile::encodeName(QDir::homeDirPath()) + "/.screen/";
    QStringList sessions;
    // Can't use QDir as it doesn't support FIFOs :(
    DIR *dir = opendir(screenDir);
    if (dir)
    {
        struct dirent *entry;
        while ((entry = readdir(dir)))
        {
            QCString path = screenDir + "/" + entry->d_name;
            struct stat st;
            if (stat(path, &st) != 0)
                continue;
            int fd;
            if (S_ISFIFO(st.st_mode) && !(st.st_mode & 0111) && // xbit == attached
                (fd = open(path, O_WRONLY | O_NONBLOCK)) != -1)
            {
                ::close(fd);
                screenList.append(QFile::decodeName(entry->d_name));
                insertItem(SmallIconSet("konsole"),
                    i18n("Screen is a program controlling screens!", "Screen at %1").arg(entry->d_name), id++);
            }
        }
        closedir(dir);
    }
}

void KonsoleMenu::slotExec(int id)
{
    id--;
    if (id >= 0)
    {
        kapp->propagateSessionManager();
        QStringList args;
        if (static_cast<unsigned int>(id) < sessionList.count())
        {
            args << "--type";
            args << sessionList[id];
        }
        else
        {
            args << "-e";
            args << "screen";
            args << "-r";
            args << screenList[id - sessionList.count()];
        }
        KApplication::kdeinitExec("konsole", args);
    }
}

KURL KonsoleMenu::baseURL() const
{
    KURL url;
    /*url.setPath(se->getCwd()+"/");*/
    return url;
}

void KonsoleMenu::makeGUI()
{
    if (m_menuCreated) return;
    disconnect(m_bookmarksSession,SIGNAL(aboutToShow()),this,SLOT(makeGUI()));
    m_menuCreated = true;
}

void KonsoleMenu::newSession(const QString& sURL, const QString& title)
{
    QStringList args;

    KURL url = KURL(sURL);
    if ((url.protocol() == "file") && (url.hasPath())) {
	args << "-T" << title;
        args << "--workdir" << url.path();
        KApplication::kdeinitExec("konsole", args);
        return;
    } else if ((!url.protocol().isEmpty()) && (url.hasHost())) {
        QString protocol = url.protocol();
        QString host = url.host();
	args << "-T" << title;
        args << "-e" << protocol.latin1(); /* argv[0] == command to run. */
        if (url.hasUser()) {
            args << "-l" << url.user().latin1();
        }
        args << host.latin1();
        KApplication::kdeinitExec("konsole", args);
        return;
    }
    /*
     * We can't create a session without a protocol.
     * We should ideally popup a warning, about an invalid bookmark.
     */
}


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

KonsoleMenuFactory::KonsoleMenuFactory(QObject *parent, const char *name)
: KLibFactory(parent, name)
{
    KGlobal::iconLoader()->addAppDir("konsole");
    KGlobal::locale()->insertCatalogue("konsolemenuapplet");
}

QObject* KonsoleMenuFactory::createObject(QObject *parent, const char *name, const char*, const QStringList&)
{
    return new KonsoleMenu((QWidget*)parent, name);
}

#include "konsole_mnu.moc"
