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

Copyright (c) 2000 Bill Nagel
Copyright (c) 2004 Dan Bullok <dan.devel@bullok.com>

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

#include <kapplication.h>
#include <kaboutapplication.h>
#include <kaboutdata.h>
#include <kglobal.h>
#include <klocale.h>
#include <kconfig.h>
#include <kstandarddirs.h>
#include <kurldrag.h>
#include <kdebug.h>


#include <algorithm>
#include <set>
//#include <assert.h>

#include "quicklauncher.h"
#include "quickbutton.h"
#include "quickaddappsmenu.h"
#include "quickbuttongroup.h"

typedef ButtonGroup::iterator ButtonIter;
const ButtonGroup::Index NotFound=ButtonGroup::NotFound;
const ButtonGroup::Index Append=ButtonGroup::Append;

#ifdef DEBUG
   #define DEBUGSTR kdDebug()
#else
   #define DEBUGSTR kndDebug()
#endif

extern "C"
{
   KPanelApplet* init(QWidget *parent, const QString& configFile)
   {
      KGlobal::locale()->insertCatalogue("quicklauncher");
      return new QuickLauncher(configFile, KPanelApplet::Normal,
                               KPanelApplet::About,
                               parent, "quicklauncher");
   }
}

QuickLauncher::QuickLauncher(const QString& configFile, Type type, int actions,
                             QWidget *parent, const char *name)
   : KPanelApplet(configFile, type, actions, parent, name)
{
   DEBUGSTR <<endl<<endl<<endl<<"---------------------------------------------------------------------"<<flush;
   DEBUGSTR << "QuickLauncher::QuickLauncher("<<configFile<<",...)"<<endl<<flush;

   _needsSave=false;
   _needsRefresh=false;
   _refreshEnabled=false;

   _popup=0;
   _appletPopup=0;
   _removeAppsMenu=0;
   _sizePopup=0;

   _dragAccepted=false;
   _dragEnabled=true;

   _buttons=new ButtonGroup;
   _manager=new FlowGridManager;
   _newButtons=0;
   _oldButtons=0;
   _dragButtons=0;

   setBackgroundOrigin(AncestorOrigin);

   loadConfig();

   buildPopupMenu();
   _minPanelDim=(*_iconSizes)[1];
   refreshContents();
   setRefreshEnabled(true);

   setAcceptDrops(true);
   //QToolTip::add(this, i18n("Drop applications here"));
   DEBUGSTR << "    QuickLauncher::QuickLauncher("<<configFile<<",...) END"<<endl<<flush;
}


// X Tooltips are wrong
// X Drag off, then back on loses icon until moved off 1st location
// X Lock/Unlock
//  Drag/drop more than one item at a time
// X set size
// X conserve _space

QuickLauncher::~QuickLauncher()
{
   KGlobal::locale()->removeCatalogue("quicklauncher");
   setCustomMenu(0);
   delete _popup;
   delete _appletPopup;
   delete _removeAppsMenu;
   delete _sizePopup;
   clearTempButtons();
   if (_buttons) {
      _buttons->deleteContents();
      delete _buttons;
   }
}

// Builds, connects _popup menu
void QuickLauncher::buildPopupMenu()
{
   QuickAddAppsMenu *addAppsMenu = new QuickAddAppsMenu(this, this);
   _popup = new QPopupMenu(this);
   _popup->insertItem(i18n("Add Application"), addAppsMenu);

   _sizePopup=new QPopupMenu(this);
   _sizePopup->setCheckable( true );
   _sizePopup->insertItem(i18n("Auto"),SIZE_AUTO);
   _iconSizes=new std::vector<int>();
   _iconSizes->push_back(SIZE_AUTO);
   for (int i=16;i<=32;i+=4) {
      _sizePopup->insertItem(QString(i18n("%1")).arg(i),i);
      _iconSizes->push_back(i);
   }
   connect(_sizePopup,SIGNAL(activated(int)), this, SLOT(setIconDim(int)));


   _appletPopup = new QPopupMenu(this);
   _appletPopup->insertItem(i18n("Add Application"), addAppsMenu);
   _removeAppsMenu = new QPopupMenu(this);
   connect(_removeAppsMenu, SIGNAL(aboutToShow()), SLOT(fillRemoveAppsMenu()));
   connect(_removeAppsMenu, SIGNAL(activated(int)), SLOT(removeApp(int)));
   _appletPopup->insertItem(i18n("Remove Application"), _removeAppsMenu);


   _appletPopup->insertSeparator();
   _appletPopup->setCheckable( true );
   _appletPopup->insertItem(i18n("Set Icon Size"),_sizePopup);
   _conserveMenuItem=_appletPopup->insertItem(i18n("Conserve Space"),this,SLOT(toggleConserveSpace(int)));
   _lockMenuItem=_appletPopup->insertItem(i18n("Lock Drag/Drop"),this,SLOT(toggleLock(int)));
   _appletPopup->insertSeparator();
   _appletPopup->insertItem(i18n("About"), this, SLOT(about()));
   setCustomMenu(_appletPopup);
   updateMenus();
}


// Fill the remove apps menu
void QuickLauncher::fillRemoveAppsMenu()
{
   _removeAppsMenu->clear();
   ButtonIter iter(_buttons->begin());
   int i = 0;
   while (iter!=_buttons->end()) {
      QString text = QToolTip::textFor(*iter);
      if (text.isEmpty()) {
         text = (*iter)->url();
         if (text.isEmpty()) {
            text = i18n("Unknown");
         }
      }
      _removeAppsMenu->insertItem((*iter++)->icon(), text, i++);
   }
}


void QuickLauncher::updateMenus()
{  if (_appletPopup) {
      _appletPopup->setItemChecked ( _lockMenuItem, !isDragEnabled() );
      _appletPopup->setItemChecked ( _conserveMenuItem, conserveSpace());
      for (unsigned i=0;i<_iconSizes->size();++i) {
         _sizePopup->setItemChecked((*_iconSizes)[i],(*_iconSizes)[i]==_iconDim);
      }
   }
}


void QuickLauncher::toggleLock(int)
{
   setDragEnabled(!isDragEnabled());
   if (_buttons) {
      _buttons->setEnableDrag(isDragEnabled());
   }
   updateMenus();
   saveConfig();
}

void QuickLauncher::toggleConserveSpace(int)
{
   setConserveSpace(!conserveSpace());
   updateMenus();
   saveConfig();
}


int QuickLauncher::findApp(QuickButton *button)
{  if (_buttons->empty()) return NotFound;
   int pos=_buttons->findValue(button);
   return pos;
}


int QuickLauncher::findApp(QString url)
{  if (_buttons->empty()) return NotFound;
   int pos=_buttons->findDescriptor(url);
   return pos;
}


void QuickLauncher::removeApp(int index)
{  if (_buttons->empty()) return;
   if (!_buttons->isValidIndex(index)) {
      kdWarning() << "    removeApp ("<<index<<") *******WARNING****** index="<<index<<"is out of bounds."<<endl<<flush;  return ;
   }
   DEBUGSTR << "Removing button.  index="<<index<<" url='"<<(*_buttons)[index]->url()<<"'"<<endl<<flush;
   delete (*_buttons)[index];
   _buttons->eraseAt(index);
   refreshContents();
   saveConfig();
}


void QuickLauncher::removeApp(QString url)
{
   int index=findApp(url);
   if (index==NotFound) {
      return;
   }
   removeApp(index);
}


void QuickLauncher::removeApp(QuickButton *button)
{
   int index=findApp(button);
   if (index==NotFound) {
      return;
   }
   removeApp(index);
}


int QuickLauncher::widthForHeight(int h) const
{
   FlowGridManager temp_manager=*_manager;
   temp_manager.setFrameSize(QSize(h,h));
   temp_manager.setOrientation(Qt::Horizontal); // ??? probably not necessary
   if (temp_manager.isValid()) {
      return temp_manager.frameSize().width();
   }
   return _minPanelDim;
}


int QuickLauncher::heightForWidth(int w) const
{
   FlowGridManager temp_manager=*_manager;
   temp_manager.setFrameSize(QSize(w,w));
   temp_manager.setOrientation(Qt::Vertical); // ??? probably not necessary
   if (temp_manager.isValid()) {
      return temp_manager.frameSize().height();
   }
   return _minPanelDim;
}


int QuickLauncher::dimension() const
{  if (orientation()==Qt::Vertical)
      return size().width();
   return size().height();
}

void QuickLauncher::addApp(QString url)
{  addApp(url,Append);
}

void QuickLauncher::addApp(QString url, int index)
{  DEBUGSTR << endl <<"About to add: url='"<<url<<"' index="<<index<<endl<<flush;
   QuickButton *newButton;
   if (!_buttons->isValidInsertIndex(index)) {
      kdWarning() << "    *******WARNING****** index="<<index<<"is out of bounds."<<endl<<flush;
      index=_buttons->lastIndex();
   }
   int old=findApp(QuickURL(url).url());
   if (old!=NotFound) {
      if (index==old) return;
      if (index>old) index--;
      newButton=(*_buttons)[old];
      _buttons->eraseAt(old);
   } else {
      newButton=new QuickButton(url, this);
   }
   _buttons->insertAt(index,newButton);
   DEBUGSTR << "Added: url='"<<url<<"' index="<<index<<endl<<endl<<flush;
   refreshContents();
   saveConfig();
}

void QuickLauncher::addAppBefore(QString url,QString sender)
{  if (sender.isNull() ) { addApp(url,Append);}
   int pos=findApp(sender);
   if (pos<0) { pos=Append;}
   DEBUGSTR << "QuickLauncher::addAppBefore("<<url<<","<<sender<<"):  pos="<<pos<<endl<<flush;
   addApp(url,pos);
}


void QuickLauncher::about()
{
   KAboutData about("quicklauncher", I18N_NOOP("Quick Launcher"), "2.0",
                    I18N_NOOP("A simple application launcher"), KAboutData::License_GPL_V2, "(C) 2000 Bill Nagel\n(C) 2004 Dan Bullok");
   KAboutApplication a(&about, this);
   a.exec();
}


void QuickLauncher::mousePressEvent(QMouseEvent *e)
{
   if (e->button() == RightButton)
      _popup->popup(e->globalPos());
}


void QuickLauncher::resizeEvent(QResizeEvent*)
{
   refreshContents();
}


void QuickLauncher::_showButtons()
{  return; // remove this to use  -  it's slow enough to make drag/drop really... drag.
   std::set<QuickButton *> all;
   all.insert(_buttons->begin(),_buttons->end());
   if (_newButtons!=0) all.insert(_newButtons->begin(),_newButtons->end());
   if (_oldButtons!=0) all.insert(_oldButtons->begin(),_oldButtons->end());
   if (_dragButtons!=0) all.insert(_dragButtons->begin(),_dragButtons->end());

   DEBUGSTR<<"_buttons:"<<endl<<flush;
   std::set<QuickButton *>::iterator iter=all.begin();
   while (iter !=all.end()) {
      DEBUGSTR<<"    "<<((_buttons->findValue(*iter)>=0)? "B ":"  ")<<((_dragButtons!=0) && (_dragButtons->findValue(*iter)>=0)? "D ":"  ")<<((_newButtons!=0) && (_newButtons->findValue(*iter)>=0)? "N ":"  ")<<((_oldButtons!=0)&& (_oldButtons->findValue(*iter)>=0)? "O ":"  ")<<(void*)(*iter)<<" "<<(*iter)->menuId()<<endl<<flush;
      ++iter;
   }
}

void QuickLauncher::dragEnterEvent(QDragEnterEvent *e)
{
   DEBUGSTR << "QuickLauncher::dragEnterEvent(pos="<<e->pos()<<" type="<<e->type()<<")"<<endl<<flush;
   _dragAccepted=false;
   KURL::List kurlList;
   if (!isDragEnabled() || !KURLDrag::decode(e, kurlList)) { e->accept(false); return;}

   if (kurlList.size()<=0) {
      e->accept(false); return;
   }
   QStringList urlList=kurlList.toStringList();
   _dragButtons=new ButtonGroup;
   _oldButtons=new ButtonGroup(*_buttons);

   QStringList::const_iterator iter=urlList.begin();
   QString url;
   while (iter!=urlList.end()) {
      url=QuickURL(*iter).url();
      DEBUGSTR << "    Drag Object='"<<url<<"'"<<endl<<flush;
      int pos=_buttons->findDescriptor(url);
      if (pos!=NotFound) {
         // if it's already in _buttons, take it out
         _dragButtons->push_back(_buttons->takeFrom(pos));
      } else {
         // otherwise, create a new one
         _dragButtons->push_back(new QuickButton(url,this));
      }
      ++iter;
   }
   if (_dragButtons->size()>0) {
      //make sure we can drag at least one button.
      _dragAccepted=true;
      _newButtons=new ButtonGroup(*_buttons);
      _dropPos=NotFound;
      e->accept(true);
      return;
   }
   e->accept(false);
   clearTempButtons();
}


void QuickLauncher::dragMoveEvent(QDragMoveEvent *e)
{
   if (!_dragAccepted) {
      kdWarning() << "QuickLauncher::dragMoveEvent: Drag is not accepted."<<_dragAccepted<<endl<<flush;
      e->accept(false);
      return;
   }

   _showButtons();
   e->accept(true);
   int pos=_manager->indexNearest(e->pos());
   if (pos==_dropPos) return;// Already been inserted here, no need to update

   if (_newButtons->isValidInsertIndex(pos));{
      mergeButtons(pos);
      _dropPos=pos;
   }
   _showButtons();
   refreshContents();
}


void QuickLauncher::dragLeaveEvent(QDragLeaveEvent *e)
{
   DEBUGSTR << "QuickLauncher::dragLeaveEvent(type="<<e->type()<<")"<<endl<<flush;
   if (!_dragAccepted) return;

   _showButtons();

   // No drop.  Return to starting state.
   std::swap(_buttons,_oldButtons);
   clearTempButtons();

   _showButtons();

   refreshContents();
   saveConfig();
}


void QuickLauncher::dropEvent(QDropEvent *e)
{
   DEBUGSTR << "QuickLauncher::dropEvent(pos="<<e->pos()<<" type="<<e->type()<<")"<<endl<<flush;
   if (!_dragAccepted) { e->accept(false); return;}

   _showButtons();

   clearTempButtons();
   _showButtons();
   refreshContents();
   saveConfig();
}

// insert dragbuttons at index in _newButtons.  Put result in _buttons
void QuickLauncher::mergeButtons(int index)
{
   if (!_newButtons->isValidInsertIndex(index))
      index=_newButtons->size();

   _buttons->clear();
   (*_buttons)=(*_newButtons);
   _buttons->insertAt(index,*_dragButtons);
   refreshContents();
}

void QuickLauncher::clearTempButtons()
{  std::set<QuickButton *> allButtons;
   //put all the _buttons in a set (removes duplicates automatically
   if (_newButtons) allButtons.insert(_newButtons->begin(),_newButtons->end());
   if (_oldButtons) allButtons.insert(_oldButtons->begin(),_oldButtons->end());
   if (_dragButtons) allButtons.insert(_dragButtons->begin(),_dragButtons->end());
   //delete temp ButtonGroups
   delete _newButtons; _newButtons=0;
   delete _oldButtons; _oldButtons=0;
   delete _dragButtons; _dragButtons=0;
   //if an element allButtons is NOT in _buttons (the ones we keep), delete it
   std::set<QuickButton *>::iterator iter=allButtons.begin();
   while (iter!=allButtons.end()) {
      if (findApp(*iter)==NotFound)
         delete *iter;
      ++iter;
   }
   _dragAccepted=false;
   _dropPos=NotFound;
}

void QuickLauncher::refreshContents()
{
   int idim,
      d=dimension();
   // determine button size
   if (_iconDim==SIZE_AUTO) {
      if (d<18) {
         idim=std::min(16,d);
      } else if (d<64) {
         idim=16;
      } else if (d<80) {
         idim=20;
      } else if (d<122) {
         idim=24;
      } else {
         idim=28;
      }
   } else {
      idim=std::min(_iconDim,d);
   }
   _space=std::max((idim/8)-1,0);
   _border=_space;
   _buttonSize=QSize(idim,idim);
   _manager->setOrientation(orientation());
   _manager->setNumItems(_buttons->size());
   _manager->setFrameSize(size());
   _manager->setItemSize(_buttonSize);
   _manager->setSpaceSize(QSize(_space,_space));
   _manager->setBorderSize(QSize(_border,_border));
   if (!_refreshEnabled) {
      _needsRefresh=true; return;
   }
   if (!_manager->isValid()) {
      kdDebug()<<endl<<"******WARNING******    Layout is invalid."<<endl<<flush;
      _manager->dump();
      return;
   }


   unsigned index;
   QPoint pos;
   setUpdatesEnabled(false);
   _buttons->setUpdatesEnabled(false);
   for (index=0;index<_buttons->size();index++) {
      pos=_manager->pos(index);
      (*_buttons)[index]->resize(_manager->itemSize());
      (*_buttons)[index]->move(pos.x(),pos.y());
      (*_buttons)[index]->setDragging(false);
      (*_buttons)[index]->setEnableDrag(isDragEnabled());
   }
   if (_newButtons) _newButtons->setDragging(false);
   if (_dragButtons) _dragButtons->setDragging(true);
   _buttons->show();
   setUpdatesEnabled(true);
   update();
   _buttons->setUpdatesEnabled(true);
   updateGeometry();
   emit updateLayout();
}


void QuickLauncher::setDragEnabled(bool enable)
{  _dragEnabled=enable;
   updateMenus();

}

void QuickLauncher::setConserveSpace(bool conserve_space)
{
   _manager->setConserveSpace(conserve_space);
   if (conserve_space)
      _manager->setSlack(FlowGridManager::SpaceSlack,FlowGridManager::SpaceSlack);
   else
      _manager->setSlack(FlowGridManager::ItemSlack,FlowGridManager::ItemSlack);
   updateMenus();
   refreshContents();
}


void QuickLauncher::setIconDim(int idim)
{
   _iconDim=idim;
   updateMenus();
   refreshContents();
   saveConfig();
}


void QuickLauncher::loadConfig()
{
   DEBUGSTR << "QuickLauncher::loadConfig()"<<endl<<flush;
   KConfig *c = config();
   c->setGroup("General");
   _iconDim=c->readNumEntry("IconDim",0);
   setConserveSpace(c->readBoolEntry("ConserveSpace",true));
   setDragEnabled(c->readBoolEntry("DragEnabled",true));
   DEBUGSTR << "    IconDim="<<_iconDim<<endl<<flush;
   DEBUGSTR << "    ConserveSpace="<<(_manager->conserveSpace())<<endl<<flush;
   DEBUGSTR << "    DragEnabled="<<isDragEnabled()<<endl<<flush;
   if (c->hasKey("Buttons")){
      QStringList urls = c->readListEntry("Buttons");
      QStringList::Iterator iter(urls.begin());
      while (iter != urls.end()) {
         DEBUGSTR << "    "<<(*iter)<<endl<<flush;
         addApp(*iter++);
      }
   } else {
      addApp("kde-Home.desktop");
      addApp("kde-konsole.desktop");
      addApp("kde-KControl.desktop");
      addApp("kde-Help.desktop");
      addApp("kde-kwrite.desktop");
   }
}

void QuickLauncher::saveConfig()
{
   if (!_refreshEnabled) {
      _needsSave=true; return;
   }
   DEBUGSTR << "QuickLauncher::saveConfig()"<<endl<<flush;
   KConfig *c = config();
   c->setGroup("General");
   QStringList urls;
   ButtonIter iter=_buttons->begin();
   while (iter!=_buttons->end()) {
      DEBUGSTR << "    "<<(*iter)->menuId()<<endl<<flush;
      urls.append((*iter++)->menuId());
   }
   c->writeEntry("Buttons", urls);
   c->writeEntry("IconDim",_iconDim);
   c->writeEntry("ConserveSpace",_manager->conserveSpace());
   c->writeEntry("DragEnabled",isDragEnabled());
   c->sync();
   DEBUGSTR << "    IconDim="<<_iconDim<<endl<<flush;
   DEBUGSTR << "    ConserveSpace="<<(_manager->conserveSpace())<<endl<<flush;
   DEBUGSTR << "    DragEnabled="<<isDragEnabled()<<endl<<flush;
}


void QuickLauncher::setRefreshEnabled(bool enable)
{  _refreshEnabled=enable;
   if (_refreshEnabled) {
      if (_needsSave) {
         saveConfig();
      }
      if (_needsRefresh) {
         refreshContents();
      }
   }
}
#include "quicklauncher.moc"

