/****************************************************************************
**
** Copyright (C) 2003-2006 Frank Hemer <frank@hemer.org>,
**                         Tilo Riemer <riemer@crossvc.com>
**
**
**----------------------------------------------------------------------------
**
**----------------------------------------------------------------------------
**
** CrossVC is available under two different licenses:
**
** If CrossVC is linked against the GPLed version of Qt 
** CrossVC is released under the terms of GPL also.
**
** If CrossVC is linked against a nonGPLed version of Qt 
** CrossVC is released under the terms of the 
** CrossVC License for non-Unix platforms (CLNU)
**
**
** CrossVC License for non-Unix platforms (CLNU):
**
** Redistribution and use in binary form, without modification, 
** are permitted provided that the following conditions are met:
**
** 1. Redistributions in binary form must reproduce the above copyright
**    notice, this list of conditions and the following disclaimer in the
**    documentation and/or other materials provided with the distribution.
** 2. It is not permitted to distribute the binary package under a name
**    different than CrossVC.
** 3. The name of the authors may not be used to endorse or promote
**    products derived from this software without specific prior written
**    permission.
** 4. The source code is the creative property of the authors.
**    Extensions and development under the terms of the Gnu Public License
**    are limited to the Unix platform. Any distribution or compilation of 
**    the source code against libraries licensed other than gpl requires 
**    the written permission of the authors.
**
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR 
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
** ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY 
** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
** GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**
**
** CrossVC License for Unix platforms:
**
** This program is free software; you can redistribute it and/or modify 
** it under the terms of the GNU General Public License as published by 
** the Free Software Foundation, version 2 of the License.
** This program is distributed in 
** the hope that it will be useful, but WITHOUT ANY WARRANTY; without 
** even the implied warranty of MERCHANTABILITY or FITNESS FOR A 
** PARTICULAR PURPOSE.
**
** See the GNU General Public License version 2 for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software Foundation,
** Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
**
*****************************************************************************/

#include "config.h"

#include <qobjectlist.h>
#include <qmenubar.h>
#include <qregexp.h>
#include <qmessagebox.h>
#include <qradiobutton.h>
#include <qbuttongroup.h>
#include <qpushbutton.h>
#include <qwhatsthis.h>

#include "CustomizeShortcutsDialogImpl.h"
#include "globals.h"
#include "GrabKeyboardImpl.h"

//List
//NoneRButton
//CustomRButton

namespace TMenu {
  Type& operator++(Type& t) {
    switch (t) {
      case PROJECT: return t=DIR;
      case DIR: return t=FILE;
      case FILE: return t=VIEW;
      case VIEW: return t=OPTIONS;
      case OPTIONS: return t=HELP;
      default: return t;
    }
  }
  Type operator++(Type& t,int) {
    Type h = t;
    ++t;
    return h;
  }
};

CustomizeShortcutsDialogImpl::CustomizeShortcutsDialogImpl(const QIconSet &whatsThisIconSet,
							   QMainWindow * parent) 
//  : CustomizeShortcutsDialog(LookAndFeel::g_b0AsParent ? 0 : parent, "ShortCuts", true, 
  : CustomizeShortcutsDialog(parent, "ShortCuts", true, LookAndFeel::g_modalF),
    m_parent(parent) 
{
  m_pWhatsThis->setIconSet(whatsThisIconSet);
#ifdef Q_WS_MAC
  m_pWhatsThis->setMaximumWidth(m_pWhatsThis->height() * 2);
#else
  m_pWhatsThis->setMaximumWidth(m_pWhatsThis->height());
#endif

  keyMap.clear();
  RadioButtonGroup->setEnabled(FALSE);
  fillList();
}

CustomizeShortcutsDialogImpl::~CustomizeShortcutsDialogImpl() {
}

CustomizeShortcutsDialogImpl::ListItem * CustomizeShortcutsDialogImpl::dynamic_cast_listItem(QListViewItem * item) {
  if (item->rtti() == 1000) {
    return (ListItem*)item;
  } else {
    return NULL;
  }
}

void CustomizeShortcutsDialogImpl::showGrabKeyboard() {
  
  if ( !CustomRButton->isChecked()) return;

  ListItem * listItem = dynamic_cast_listItem(List->currentItem());
  int accel = 0;
  if (listItem) accel = listItem->getAccel();

  GrabKeyboardImpl * dlg = new GrabKeyboardImpl(*(m_pWhatsThis->iconSet()), this, accel);

  if (dlg->exec()) {
    QKeySequence ks(dlg->getKeySequence());
    setShortcut(ks);
  }
  delete dlg;

}

void CustomizeShortcutsDialogImpl::applyClicked() {
  KEYBOARDSHORTCUTS = "";
  QValueList<int> values = keyMap.values();
  MenuItem * item = MenuItem::first();
  while (item) {
    if ( values.contains(item->getInstanceNum()) ) {
      QMap<int,int>::Iterator it;
      for ( it = keyMap.begin(); it != keyMap.end(); ++it ) {
	if (it.data() == item->getInstanceNum()) {
	  MenuItem::setAccel(item,it.key());
	  KEYBOARDSHORTCUTS += QString::number(it.data())+","+QString::number(it.key())+":";
	  break;
	}
      }
    } else {
      MenuItem::setAccel(item,0);
    }
    item = item->nextItem();
  }
}

void CustomizeShortcutsDialogImpl::selected(QListViewItem * item) {

  RadioButtonGroup->setEnabled(item->isSelected());
  if (!item->isSelected()) NoneRButton->setChecked(TRUE);

  ListItem * listItem = dynamic_cast_listItem(item);
  if (listItem) {
    int accel = listItem->getAccel();
    if (accel==0) NoneRButton->setChecked(TRUE);
    else CustomRButton->setChecked(TRUE);
    QKeySequence ks(accel);
    emit setText(QString(ks));
  } else emit setText("");
  EditButton->setEnabled(CustomRButton->isChecked());
}

void CustomizeShortcutsDialogImpl::customizable(int a) {
  EditButton->setEnabled(a == 1);
}

void CustomizeShortcutsDialogImpl::resetAccel() {
  ListItem * listItem = dynamic_cast_listItem(List->currentItem());
  if (listItem && (listItem->getAccel() != 0) ) {
    QKeySequence seq(0);
    setShortcut(seq);
  }
}

void CustomizeShortcutsDialogImpl::fillList() {

  QMenuBar * menuBar = m_parent->menuBar();
  int index = 0;
  int id = -1;
  QListViewItem * rootItem = NULL;
  TMenu::Type type = TMenu::PROJECT; 
  while ( (id = menuBar->idAt(index++)) > -1) {
    QMenuItem * topItem = menuBar->findItem(id);
    if (topItem) {
      QString txt = topItem->text();
      txt.replace( QRegExp("&"),"");
      rootItem = new QListViewItem(List,txt);
      rootItem->setSelectable(FALSE);

      MenuItem * item = MenuItem::first();
      while (item) {
	if ( (item->menu() & type) && item->slot() ) {
	  int accel = item->accel();
	  QString txt = item->caption();
	  MenuItem * parent = item->getParent();
	  while (parent) {
	    txt = parent->caption()+" "+txt;
	    parent = parent->getParent();
	  }
	  new ListItem(rootItem,txt,QString(QKeySequence(accel)),item );
	  if (accel != 0) {
	    keyMap.insert(accel,item->getInstanceNum());
	  }
	}
	item = item->nextItem();
      }
    }
    type++;
  }

}

void CustomizeShortcutsDialogImpl::setShortcut(QKeySequence& sequence) {
   ListItem * listItem = dynamic_cast_listItem(List->currentItem());
   if (listItem) {
      QMap<int,int>::iterator it;
      it = keyMap.find(sequence);
      if ( it!=keyMap.end()) {
         
         QString top = "";
         bool done = FALSE;
         QListViewItem * topItem = List->firstChild();
         do {
            QListViewItem * child = topItem->firstChild();
            while (!done && child) {
               if (child->text(1) == QString(sequence)) {
                  top = topItem->text(0) + " | ";
                  done = TRUE;
               }
               child = child->nextSibling();
            }
         } while ( !done && (topItem=topItem->nextSibling()));
         
         QMessageBox::warning(this,tr("Can't use key shortcut"),
         tr("This shortcut is already in use by:")
         +"\n'"+top+MenuItem::getInstance(it.data())->caption()+"'",
         QMessageBox::Cancel,QMessageBox::NoButton);
         
      } else {
         emit setText(QString(sequence));
         listItem->setText(1,QString(sequence));
         int instance = listItem->getMenuItem()->getInstanceNum();
         keyMap.remove(listItem->getAccel());
         if ((int)sequence != 0) {
            keyMap.insert(sequence,instance);
         }
         listItem->setAccel(sequence);
      }
   }
}

void CustomizeShortcutsDialogImpl::accept() {
  applyClicked();
  CustomizeShortcutsDialog::accept();
}

void CustomizeShortcutsDialogImpl::enterWhatsThisMode()
{
   QWhatsThis::enterWhatsThisMode();
}

