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

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 <qtooltip.h>
#include <qcursor.h>

#include <kglobal.h>
#include <kconfig.h>
#include <kstddirs.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kpropsdlg.h>
#include <krun.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <kdesktopfile.h>
#include <kapp.h>
#include <kiconeffect.h>

#include "panelbutton.h"
#include "panelbutton.moc"
#include "servicemenu.h"
#include "dialogs.h"

#include <kipc.h>

PanelButton::PanelButton( QWidget * parent, const char *name)
  : PanelButtonBase( parent, name )
{
  connect(kapp, SIGNAL(iconChanged(int)), SLOT(slotIconChanged(int)));
  kapp->addKipcEventMask(KIPC::IconChanged);
}

void PanelButton::slotIconChanged(int /*group*/)
{
  resizeEvent(0L);
}

void PanelButton::setPosition(Position p)
{
  pos = p;

  if (pos == Bottom)
    setArrowDirection(Top);
  else if (pos == Top)
    setArrowDirection(Bottom);
  else if (pos == Left)
    setArrowDirection(Right);
  else
    setArrowDirection(Left);
}

QPoint PanelButton::getPopupPosition(QPopupMenu *menu)
{
  if(position() == Bottom)
    return(mapToGlobal(QPoint(0, 0-menu->height())));
  else if(position() == Top)
    return(mapToGlobal(QPoint(0, height())));
  else if(position() == Right)
    return(mapToGlobal(QPoint(0-menu->width(), 0)));
  else
    return(mapToGlobal(QPoint(width(), 0)));
}

PanelURLButton::PanelURLButton(const QString &url, QWidget *parent,
                               const char *name)
  : PanelButton(parent, name)
{
  configure();
  urlStr = url;
  KURL u(url);
  local = u.isLocalFile();
  connect(this, SIGNAL(clicked()), SLOT(slotExec()));
  setAcceptDrops(true);
}

void PanelURLButton::configure()
{
  PanelButton::configure();

  KConfig *config = KGlobal::config();
  config->setGroup("buttons");

  QString tile = QString::null;
  if(config->readBoolEntry("EnableTileBackground", false))
    {
      config->setGroup("button_tiles");
      if(config->readBoolEntry("EnableURLTiles", true))
        tile = config->readEntry("URLTile", QString::null);
    }
  setTile(tile);
}

void PanelURLButton::dragEnterEvent(QDragEnterEvent *ev)
{
  ev->accept(QUriDrag::canDecode(ev));
}

void PanelURLButton::dropEvent(QDropEvent *ev)
{
  kapp->propagateSessionManager();
  QStrList fileList;
  QStringList execList;
  if(QUriDrag::decode(ev, fileList)){
    QStrListIterator it(fileList);
    for(;it.current(); ++it)
      execList.append(it.current());
    KURL url(urlStr);
    if(!execList.isEmpty() && KDesktopFile::isDesktopFile(url.path())){
      KApplication::startServiceByDesktopPath(url.path(), execList);
    }
  }
}

void PanelURLButton::resizeEvent(QResizeEvent*e)
{
  PanelButtonBase::resizeEvent(e);

  setIcon(KURL(urlStr));
}

void PanelURLButton::slotExec()
{
  KIconEffect::visualActivate(this, rect());
  kapp->propagateSessionManager();
  new KRun(urlStr, 0, local);
}

void PanelURLButton::updateURL()
{
    if (pDlg->kurl().path() != urlStr)
      urlStr = pDlg->kurl().path();

    pDlg = 0L;
    resizeEvent(0);
}

void PanelURLButton::properties()
{
  if (local)
    if (!QFile::exists(KURL(urlStr).path())) {
       KMessageBox::error( 0L, i18n("The file %1 doesn't exist").arg(urlStr) );
       return;
    }
    
  pDlg = new KPropertiesDialog(urlStr); // will delete itself
  connect(pDlg, SIGNAL(applied()), SLOT(updateURL()));
}

PanelBrowserButton::PanelBrowserButton(const QString &startDir, QWidget *parent,
                                       const char *name)
  : PanelButton(parent, name)
{
  configure();
  setDrawArrow(true);
  topMenu = new PanelBrowserMenu(startDir);
  // pressed() and NOT clicked() (Matthias)
  connect(this, SIGNAL(pressed()), SLOT(slotExecMenu()));
}

void PanelBrowserButton::configure()
{
  PanelButton::configure();

  KConfig *config = KGlobal::config();
  config->setGroup("buttons");

  QString tile = QString::null;
  if(config->readBoolEntry("EnableTileBackground", false))
    {
      config->setGroup("button_tiles");
      if(config->readBoolEntry("EnableBrowserTiles", true))
        tile = config->readEntry("BrowserTile", QString::null);
    }
  setTile(tile);
}

void PanelBrowserButton::resizeEvent(QResizeEvent* e)
{
  PanelButtonBase::resizeEvent(e);

  QString dirFile(topMenu->path()+"/.directory");
  QString iconFile;
  if(QFile::exists(dirFile)){
    KSimpleConfig config(dirFile);
    config.setDesktopGroup();
    iconFile = config.readEntry("Icon", "folder");
  }
  if(iconFile.isEmpty())
    iconFile = "folder";

  setIcon(iconFile, "folder");
}

void PanelBrowserButton::slotExecMenu()
{
  topMenu->initialize();
  topMenu->exec(getPopupPosition(topMenu));
  setDown( FALSE );
}


void PanelBrowserButton::properties()
{
  KMessageBox::sorry(this, i18n("Properties for QuickBrowser not implemented!"),
                     i18n("Apology from mosfet"));
}

PanelKButton::PanelKButton(QWidget *parent, const char *name)
  :PanelButton(parent, name)
{
  configure();
  setDrawArrow(true);
  QToolTip::add(this, i18n("KDE Application Menu"));
  topMenu = new PanelKMenu();
  // pressed() and NOT clicked() (Matthias)
  connect(this, SIGNAL(pressed()), SLOT(slotExecMenu()));
  // client menu stuff
  menuMgr = new KickerMenuManager( topMenu, this, "kickerMenuManager" );
  connect(menuMgr, SIGNAL(popupKMenu(int, int)), this,
          SLOT(slotExecMenuAt(int, int)));
}

void PanelKButton::configure()
{
  PanelButton::configure();

  KConfig *config = KGlobal::config();
  config->setGroup("buttons");

  QString tile = QString::null;
  if(config->readBoolEntry("EnableTileBackground", false))
    {
      config->setGroup("button_tiles");
      if(config->readBoolEntry("EnableKMenuTiles", true))
        tile = config->readEntry("KMenuTile", QString::null);
    }
  setTile(tile);
}

void PanelKButton::resizeEvent(QResizeEvent*e)
{
  PanelButtonBase::resizeEvent(e);

  setIcon("go", "unknown");
}

void PanelKButton::slotExecMenu()
{
  topMenu->initialize();
  topMenu->exec(getPopupPosition(topMenu));
  setDown( FALSE );
}

void PanelKButton::slotExecMenuAt(int x, int y)
{
  topMenu->initialize();
  topMenu->exec(QPoint(x, y));
}

void PanelKButton::properties()
{
  KMessageBox::sorry(this, i18n("Properties for K Menu not implemented!"),
                     i18n("Apology from mosfet"));
}

// Non-KDE application
PanelExeButton::PanelExeButton(const QString &filePath, const QString &icon,
                               const QString &cmdLine, bool inTerm,
                               QWidget *parent, const char *name)
  : PanelButton(parent, name)
{
  configure();
  pathStr = filePath;
  iconStr = icon;
  cmdStr = cmdLine;
  term = inTerm;

  connect(this, SIGNAL(clicked()), SLOT(slotExec()));
}

void PanelExeButton::configure()
{
  PanelButton::configure();

  KConfig *config = KGlobal::config();
  config->setGroup("buttons");

  QString tile = QString::null;
  if(config->readBoolEntry("EnableTileBackground", false))
    {
      config->setGroup("button_tiles");
      if(config->readBoolEntry("EnableExeTiles", true))
        tile = config->readEntry("ExeTile", QString::null);
    }
  setTile(tile);
}

PanelExeButton::PanelExeButton(const QString &configData, QWidget *parent,
                               const char *name)
  : PanelButton(parent, name)
{
  term = (configData[0] ==  '1') ? true : false;
  pathStr= configData.mid(1);
  int index = pathStr.find("::mossie::");
  pathStr.truncate(index);
  iconStr=configData.mid(index+11);
  int index2 = iconStr.find("::mossie::");
  iconStr.truncate(index2);
  cmdStr =configData.mid(index+11+index2+10);
  warning("term %d, path %s, icon %s, cmd %s", term, pathStr.latin1(),
          iconStr.latin1(), cmdStr.latin1());
  
  connect(this, SIGNAL(clicked()), SLOT(slotExec()));
  setAcceptDrops(true);
}

void PanelExeButton::dragEnterEvent(QDragEnterEvent *ev)
{
  ev->accept(QUriDrag::canDecode(ev));
}

void PanelExeButton::dropEvent(QDropEvent *ev)
{
  QStrList fileList;
  QStringList blah;
  QString execStr;
  if(QUriDrag::decode(ev, fileList)){
    QStrListIterator it(fileList);
    for(;it.current(); ++it){
      KURL url(it.current());
      if(KDesktopFile::isDesktopFile(url.path())){
        KDesktopFile deskFile(url.path());
        deskFile.setDesktopGroup();
        execStr += deskFile.readURL() + " ";
      }
      else
        execStr += url.path() + " ";
    }
    bool result;
    kapp->propagateSessionManager();
    if(term){
      KConfig *config = KGlobal::config();
      config->setGroup("misc");
      QString termStr = config->readEntry("Terminal", "konsole");
      result = KRun::run(termStr + " -e " + pathStr + " " +
                         cmdStr + " " + execStr, blah);

    }
    else
      result = KRun::run(pathStr + " " + cmdStr + " " + execStr, blah);

    if(!result)
      KMessageBox::error(this, i18n("Cannot execute non-KDE application!"),
                         i18n("Kicker Error!"));
  }
}

void PanelExeButton::resizeEvent(QResizeEvent*e)
{
  PanelButtonBase::resizeEvent(e);
  setIcon(iconStr, "exec");
}

QString PanelExeButton::configData()
{
  QString data;
  data.sprintf("%d%s::mossie::%s::mossie::%s", term, pathStr.latin1(),
               iconStr.latin1(), cmdStr.latin1());
  return data;
}

void PanelExeButton::slotExec()
{
  KIconEffect::visualActivate(this, rect());
  QStringList blah;
  bool result;
  kapp->propagateSessionManager();
  if(term){
    KConfig *config = KGlobal::config();
    config->setGroup("misc");
    QString termStr = config->readEntry("Terminal", "konsole");
    result = KRun::run(termStr + " -e " + pathStr + " " + cmdStr, blah);
  }
  else
    result = KRun::run(pathStr + " " + cmdStr, blah);
  if(!result)
    KMessageBox::error(this, i18n("Cannot execute non-KDE application!"),
                       i18n("Kicker Error!"));
}

void PanelExeButton::properties()
{
  PanelExeDialog dlg(pathStr, iconStr, cmdStr, term, this);
  if(dlg.exec() == QDialog::Accepted){
    // KIconloader returns a full path, we only want name
    QFileInfo iconfi(dlg.icon());
    iconStr = iconfi.baseName();
    cmdStr = dlg.commandLine();
    term = dlg.useTerminal();
    setIcon(iconStr, "exec");
    emit requestSave();
  }
}

PanelWindowListButton::PanelWindowListButton(QWidget *parent, const char *name)
  : PanelButton(parent, name)
{
  configure();
  setDrawArrow(true);
  topMenu = new PanelWindowListMenu();
  connect(this, SIGNAL(pressed()), SLOT(slotExecMenu()));
}

void PanelWindowListButton::configure()
{
  PanelButton::configure();

  KConfig *config = KGlobal::config();
  config->setGroup("buttons");

  QString tile = QString::null;
  if(config->readBoolEntry("EnableTileBackground", false))
    {
      config->setGroup("button_tiles");
      if(config->readBoolEntry("EnableBrowserTiles", true))
        tile = config->readEntry("BrowserTile", QString::null);
    }
  setTile(tile);
}

void PanelWindowListButton::resizeEvent(QResizeEvent* e)
{
  PanelButtonBase::resizeEvent(e);
  setIcon("window_list", "unknown");
}

void PanelWindowListButton::slotExecMenu()
{
  topMenu->init();
  topMenu->exec(getPopupPosition(topMenu));
  setDown( FALSE );
}

void PanelWindowListButton::properties()
{
  KMessageBox::sorry(this, i18n("Properties for WindowList not implemented!"));
}


