/***************************************************************************
 *   Copyright (C) 2007 by Anistratov Oleg                                 *
 *   ower86@gmail.com                                                      *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License version 2        *
 *   as published by the Free Software Foundation;                         *
 *                                                                         *
 *   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 for more details.                          *
 *                                                                         *
 ***************************************************************************/
#include "shortcutbutton.h"

ShortcutButton::ShortcutButton(QWidget *parent)
 : QPushButton(parent)
{
  setText(tr("Input Shortcut"));
}


ShortcutButton::~ShortcutButton()
{
}

void ShortcutButton::keyPressEvent(QKeyEvent* ev)
{
  if(ev->isAutoRepeat())
    return;

  setShortcutText(ev);

  if(/*ev->modifiers() &&*/ validKey(ev->key()))
  {
    emit sequenceAccepted(QKeySequence(ev->modifiers() + validKey(ev->key())));
    setText(tr("Input Shortcut"));
    releaseKeyboard();
  }
}

void ShortcutButton::keyReleaseEvent(QKeyEvent* ev)
{
  setShortcutText(ev);
}

int ShortcutButton::validKey(int key)
{
  if(key < 0 || key == Qt::Key_unknown)
    return 0;

  switch(key)
  {
    case Qt::Key_Shift   :
    case Qt::Key_Control :
    case Qt::Key_Alt     :
    case Qt::Key_Meta    :
    case Qt::Key_AltGr   :
    return 0;
  }

  return key;
}

void ShortcutButton::setShortcutText(QKeyEvent* ev)
{
  QString seq = QKeySequence(ev->modifiers() + validKey(ev->key())).toString();

  if(!seq.isEmpty())
    setText(seq);
  else
    setText(tr("Input Shortcut"));
}
