joywidget.cpp 13.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/***************************************************************************
 *   Copyright (C) 2003,2012 by Martin Koller                              *
 *   kollix@aon.at                                                         *
 *   This file is part of the KDE Control Center Module for Joysticks      *
 *                                                                         *
 *   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; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   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.                          *
 *                                                                         *
 *   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.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/
#include "joywidget.h"
#include "joydevice.h"
#include "poswidget.h"
#include "caldialog.h"

#include <QTableWidget>
#include <QLabel>
#include <QCheckBox>
#include <QTimer>
#include <QFontMetrics>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QHeaderView>
35 36
#include <QApplication>
#include <QStyle>
37 38

#include <KLocalizedString>
Laurent Montel's avatar
Laurent Montel committed
39 40 41 42
#include <KMessageBox>
#include <KComboBox>
#include <KUrlCompletion>
#include <KMessageWidget>
43 44 45 46 47 48 49 50 51 52 53 54

#include <stdio.h>

//--------------------------------------------------------------
static QString PRESSED = I18N_NOOP("PRESSED");
//--------------------------------------------------------------

class TableWidget : public QTableWidget
{
  public:
    TableWidget(int row, int col) : QTableWidget(row, col) {}

55
    QSize sizeHint() const override
56 57 58 59 60 61 62 63
    {
      return QSize(150, 100);  // return a smaller size than the Qt default(256, 192)
    }
};

//--------------------------------------------------------------

JoyWidget::JoyWidget(QWidget *parent)
64
 : QWidget(parent), idle(nullptr), joydev(nullptr)
65 66
{
  QVBoxLayout *mainVbox = new QVBoxLayout(this);
67 68
  int defaultSpacing = style()->pixelMetric(QStyle::PM_DefaultLayoutSpacing);
  mainVbox->setSpacing(defaultSpacing);
Laurent Montel's avatar
Laurent Montel committed
69
  mainVbox->setContentsMargins(0, 0, 0, 0);
70 71 72 73 74 75 76

  // create area to show an icon + message if no joystick was detected
  {
    messageBox = new KMessageWidget(this);
    messageBox->setMessageType(KMessageWidget::Error);
    messageBox->setCloseButtonVisible(false);
    messageBox->hide();
77
    messageBox->setWordWrap(true);
78 79 80 81 82

    mainVbox->addWidget(messageBox);
  }

  QHBoxLayout *devHbox = new QHBoxLayout;
83
  devHbox->setSpacing(defaultSpacing);
84 85 86 87 88 89 90 91 92 93 94 95
  devHbox->addWidget(new QLabel(i18n("Device:")));
  devHbox->addWidget(device = new KComboBox(true));

  device->setInsertPolicy(QComboBox::NoInsert);
  KUrlCompletion *kc = new KUrlCompletion(KUrlCompletion::FileCompletion);
  device->setCompletionObject(kc);
  device->setAutoDeleteCompletionObject(true);
  connect(device, SIGNAL(activated(QString)), this, SLOT(deviceChanged(QString)));
  connect(device, SIGNAL(returnPressed(QString)), this, SLOT(deviceChanged(QString)));
  devHbox->setStretchFactor(device, 3);

  QHBoxLayout *hbox = new QHBoxLayout;
96
  hbox->setSpacing(defaultSpacing);
97 98 99 100 101

  mainVbox->addLayout(devHbox);
  mainVbox->addLayout(hbox);

  QVBoxLayout *vboxLeft = new QVBoxLayout;
102
  vboxLeft->setSpacing(defaultSpacing);
103 104 105 106
  vboxLeft->addWidget(new QLabel(i18nc("Cue for deflection of the stick", "Position:")));
  vboxLeft->addWidget(xyPos = new PosWidget);

  vboxLeft->addWidget(trace = new QCheckBox(i18n("Show trace")));
107
  connect(trace, &QAbstractButton::toggled, this, &JoyWidget::traceChanged);
108 109

  QVBoxLayout *vboxMid = new QVBoxLayout;
110
  vboxMid->setSpacing(defaultSpacing);
111 112

  QVBoxLayout *vboxRight = new QVBoxLayout;
113
  vboxRight->setSpacing(defaultSpacing);
114 115 116

  // calculate the column width we need
  QFontMetrics fm(font());
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
117
  int colWidth = qMax(fm.horizontalAdvance(PRESSED), fm.horizontalAdvance(QStringLiteral("-32767"))) + 10;  // -32767 largest string
118 119 120 121 122 123 124

  vboxMid->addWidget(new QLabel(i18n("Buttons:")));
  buttonTbl = new TableWidget(0, 1);
  buttonTbl->setSelectionMode(QAbstractItemView::NoSelection);
  buttonTbl->setEditTriggers(QAbstractItemView::NoEditTriggers);
  buttonTbl->setHorizontalHeaderLabels(QStringList(i18n("State")));
  buttonTbl->setSortingEnabled(false);
Laurent Montel's avatar
Laurent Montel committed
125 126
  buttonTbl->horizontalHeader()->setSectionsClickable(false);
  buttonTbl->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
127
  buttonTbl->horizontalHeader()->resizeSection(0, colWidth);
Laurent Montel's avatar
Laurent Montel committed
128
  buttonTbl->verticalHeader()->setSectionsClickable(false);
129 130 131 132 133 134 135 136
  vboxMid->addWidget(buttonTbl);

  vboxRight->addWidget(new QLabel(i18n("Axes:")));
  axesTbl = new TableWidget(0, 1);
  axesTbl->setSelectionMode(QAbstractItemView::NoSelection);
  axesTbl->setEditTriggers(QAbstractItemView::NoEditTriggers);
  axesTbl->setHorizontalHeaderLabels(QStringList(i18n("Value")));
  axesTbl->setSortingEnabled(false);
Laurent Montel's avatar
Laurent Montel committed
137 138
  axesTbl->horizontalHeader()->setSectionsClickable(false);
  axesTbl->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
139
  axesTbl->horizontalHeader()->resizeSection(0, colWidth);
Laurent Montel's avatar
Laurent Montel committed
140
  axesTbl->verticalHeader()->setSectionsClickable(false);
141 142 143 144 145 146 147 148
  vboxRight->addWidget(axesTbl);

  hbox->addLayout(vboxLeft);
  hbox->addLayout(vboxMid);
  hbox->addLayout(vboxRight);

  // calibrate button
  calibrate = new QPushButton(i18n("Calibrate"));
149
  connect(calibrate, &QAbstractButton::clicked, this, &JoyWidget::calibrateDevice);
150 151 152 153 154 155 156
  calibrate->setEnabled(false);

  vboxLeft->addStretch();
  vboxLeft->addWidget(calibrate);

  // set up a timer for idle processing of joystick events
  idle = new QTimer(this);
157
  connect(idle, &QTimer::timeout, this, &JoyWidget::checkDevice);
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202

  // check which devicefiles we have
  init();
}

//--------------------------------------------------------------

JoyWidget::~JoyWidget()
{
  delete joydev;
}

//--------------------------------------------------------------

void JoyWidget::init()
{
  // check which devicefiles we have
  int i;
  bool first = true;
  char dev[30];

  device->clear();
  buttonTbl->setRowCount(0);
  axesTbl->setRowCount(0);

  for (i = 0; i < 5; i++)  // check the first 5 devices
  {
    sprintf(dev, "/dev/js%d", i);  // first look in /dev
    JoyDevice *joy = new JoyDevice(dev);

    if ( joy->open() != JoyDevice::SUCCESS )
    {
      delete joy;
      sprintf(dev, "/dev/input/js%d", i);  // then look in /dev/input
      joy = new JoyDevice(dev);

      if ( joy->open() != JoyDevice::SUCCESS )
      {
        delete joy;
        continue;    // try next number
      }
    }

    // we found one

203
    device->addItem(QStringLiteral("%1 (%2)").arg(joy->text()).arg(joy->device()));
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218

    // display values for first device
    if ( first )
    {
      showDeviceProps(joy);  // this sets the joy object into this->joydev
      first = false;
    }
    else
      delete joy;
  }

  /* KDE 4: Remove this check(and i18n) when all KCM wrappers properly test modules */
  if ( device->count() == 0 )
  {
    messageBox->show();
219
    messageBox->setText(QStringLiteral("<qt>%1</qt>").arg(
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
      i18n("No joystick device automatically found on this computer.<br />"
           "Checks were done in /dev/js[0-4] and /dev/input/js[0-4]<br />"
           "If you know that there is one attached, please enter the correct device file.")));
  }
}

//--------------------------------------------------------------

void JoyWidget::traceChanged(bool state)
{
  xyPos->showTrace(state);
}

//--------------------------------------------------------------

void JoyWidget::restoreCurrDev()
{
  if ( !joydev )  // no device open
  {
239
    device->setEditText(QLatin1String(""));
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
    calibrate->setEnabled(false);
  }
  else
  {
    // try to find the current open device in the combobox list
    int index = device->findText(joydev->device(), Qt::MatchContains);

    if ( index == -1 )  // the current open device is one the user entered (not in the list)
      device->setEditText(joydev->device());
    else
      device->setEditText(device->itemText(index));
  }
}

//--------------------------------------------------------------

void JoyWidget::deviceChanged(const QString &dev)
{
  // find "/dev" in given string
  int start, stop;
  QString devName;

262
  if ( (start = dev.indexOf(QLatin1String("/dev"))) == -1 )
263 264 265 266 267 268 269 270 271 272
  {
    KMessageBox::sorry(this,
      i18n("The given device name is invalid (does not contain /dev).\n"
           "Please select a device from the list or\n"
           "enter a device file, like /dev/js0."), i18n("Unknown Device"));

    restoreCurrDev();
    return;
  }

273
  if ( (stop = dev.indexOf(QLatin1Char(')'), start)) != -1 )  // seems to be text selected from our list
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
    devName = dev.mid(start, stop - start);
  else
    devName = dev.mid(start);

  if ( joydev && (devName == joydev->device()) ) return;  // user selected the current device; ignore it

  JoyDevice *joy = new JoyDevice(devName);
  JoyDevice::ErrorCode ret = joy->open();

  if ( ret != JoyDevice::SUCCESS )
  {
    KMessageBox::error(this, joy->errText(ret), i18n("Device Error"));

    delete joy;
    restoreCurrDev();
    return;
  }

  showDeviceProps(joy);
}

//--------------------------------------------------------------

void JoyWidget::showDeviceProps(JoyDevice *joy)
{
  joydev = joy;

  buttonTbl->setRowCount(joydev->numButtons());

  axesTbl->setRowCount(joydev->numAxes());
  if ( joydev->numAxes() >= 2 )
  {
    axesTbl->setVerticalHeaderItem(0, new QTableWidgetItem(i18n("1(x)")));
    axesTbl->setVerticalHeaderItem(1, new QTableWidgetItem(i18n("2(y)")));
  }

  calibrate->setEnabled(true);
  idle->start(0);

  // make both tables use the same space for header; this looks nicer
  // TODO: Don't know how to do this in Qt4; the following does no longer work
  // Probably by setting a sizeHint for every single header item ?
  /*
  buttonTbl->verticalHeader()->setFixedWidth(qMax(buttonTbl->verticalHeader()->width(),
                                                    axesTbl->verticalHeader()->width()));
  axesTbl->verticalHeader()->setFixedWidth(buttonTbl->verticalHeader()->width());
  */
}

//--------------------------------------------------------------

void JoyWidget::checkDevice()
{
  if ( !joydev ) return;  // no open device yet

  JoyDevice::EventType type;
  int number, value;

  if ( !joydev->getEvent(type, number, value) )
    return;

  if ( type == JoyDevice::BUTTON )
  {
    if ( ! buttonTbl->item(number, 0) )
      buttonTbl->setItem(number, 0, new QTableWidgetItem());

    if ( value == 0 )  // button release
341
      buttonTbl->item(number, 0)->setText(QStringLiteral("-"));
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
    else
      buttonTbl->item(number, 0)->setText(PRESSED);
  }

  if ( type == JoyDevice::AXIS )
  {
    if ( number == 0 ) // x-axis
      xyPos->changeX(value);

    if ( number == 1 ) // y-axis
      xyPos->changeY(value);

    if ( ! axesTbl->item(number, 0) )
      axesTbl->setItem(number, 0, new QTableWidgetItem());

357
    axesTbl->item(number, 0)->setText(QStringLiteral("%1").arg(int(value)));
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
  }
}

//--------------------------------------------------------------

void JoyWidget::calibrateDevice()
{
  if ( !joydev ) return;  // just to be save

  JoyDevice::ErrorCode ret = joydev->initCalibration();

  if ( ret != JoyDevice::SUCCESS )
  {
    KMessageBox::error(this, joydev->errText(ret), i18n("Communication Error"));
    return;
  }

  if ( KMessageBox::messageBox(this, KMessageBox::Information,
        i18n("<qt>Calibration is about to check the precision.<br /><br />"
             "<b>Please move all axes to their center position and then "
             "do not touch the joystick anymore.</b><br /><br />"
             "Click OK to start the calibration.</qt>"),
        i18n("Calibration"),
        KStandardGuiItem::ok(), KStandardGuiItem::cancel()) != KMessageBox::Ok )
    return;

  idle->stop();  // stop the joystick event getting; this must be done inside the calibrate dialog

  CalDialog dlg(this, joydev);
  dlg.calibrate();

  // user canceled somewhere during calibration, therefore the device is in a bad state
  if ( dlg.result() == QDialog::Rejected )
    joydev->restoreCorr();

  idle->start(0);  // continue with event getting
}

//--------------------------------------------------------------

void JoyWidget::resetCalibration()
{
  if ( !joydev ) return;  // just to be save

  JoyDevice::ErrorCode ret = joydev->restoreCorr();

  if ( ret != JoyDevice::SUCCESS )
  {
    KMessageBox::error(this, joydev->errText(ret), i18n("Communication Error"));
  }
  else
  {
    KMessageBox::information(this,
      i18n("Restored all calibration values for joystick device %1.", joydev->device()),
      i18n("Calibration Success"));
  }
}

//--------------------------------------------------------------