diff --git a/autotests/kcolorbuttontest.cpp b/autotests/kcolorbuttontest.cpp
index b3bd029..22d8d9d 100644
--- a/autotests/kcolorbuttontest.cpp
+++ b/autotests/kcolorbuttontest.cpp
@@ -1,143 +1,143 @@
/*
Copyright 2013 Albert Astals Cid
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "kcolorbuttontest.h"
#include
#include
#include
#include
#include
QTEST_MAIN(KColorButtonTest)
static void workaround()
{
// Workaround for Qt-5.1 bug, which assumes GTK if there's no running desktop.
// (and apparently QTest::qWaitForWindowExposed doesn't work for GTK native dialogs)
qputenv("XDG_CURRENT_DESKTOP", "KDE");
// TODO: it means this test will always fail with native dialogs, though.
// But we can't set QColorDialog::DontUseNativeDialog from here...
}
Q_CONSTRUCTOR_FUNCTION(workaround)
void KColorButtonTest::initTestCase()
{
black40Colors.setHsv(-1, 0, 0);
}
void KColorButtonTest::testChangeAndCancel()
{
KColorButton colorButton(Qt::red);
colorButton.show();
QVERIFY(QTest::qWaitForWindowExposed(&colorButton));
QTest::mouseClick(&colorButton, Qt::LeftButton);
QColorDialog *dialog = colorButton.findChild();
- QVERIFY(dialog != NULL);
+ QVERIFY(dialog != nullptr);
QVERIFY(QTest::qWaitForWindowExposed(dialog));
#pragma message("port to QColorDialog")
#if 0
KColorCells *cells = dialog->findChild();
QVERIFY(cells != NULL);
QTest::mouseClick(cells->viewport(), Qt::LeftButton, 0, QPoint(1, 1));
QCOMPARE(dialog->color(), black40Colors);
dialog->reject();
QCOMPARE(colorButton.color(), QColor(Qt::red));
#endif
}
void KColorButtonTest::testDoubleClickChange()
{
KColorButton colorButton(Qt::red);
colorButton.show();
QVERIFY(QTest::qWaitForWindowExposed(&colorButton));
QTest::mouseClick(&colorButton, Qt::LeftButton);
QColorDialog *dialog = colorButton.findChild();
if (!dialog) {
qWarning() << "No QColorDialog was found! topLevelWidgets=" << QApplication::topLevelWidgets() << "children of colorbutton=" << colorButton.children();
}
- QVERIFY(dialog != NULL);
+ QVERIFY(dialog != nullptr);
QVERIFY(QTest::qWaitForWindowExposed(dialog));
#pragma message("port to QColorDialog")
#if 0
KColorCells *cells = dialog->findChild();
QVERIFY(cells != NULL);
QTest::mouseDClick(cells->viewport(), Qt::LeftButton, 0, QPoint(1, 1));
QCOMPARE(colorButton.color(), black40Colors);
#endif
}
void KColorButtonTest::testOkChange()
{
KColorButton colorButton(Qt::red);
colorButton.show();
QVERIFY(QTest::qWaitForWindowExposed(&colorButton));
QTest::mouseClick(&colorButton, Qt::LeftButton);
QColorDialog *dialog = colorButton.findChild();
- QVERIFY(dialog != NULL);
+ QVERIFY(dialog != nullptr);
QVERIFY(QTest::qWaitForWindowExposed(dialog));
#pragma message("port to QColorDialog")
#if 0
KColorCells *cells = dialog->findChild();
QVERIFY(cells != NULL);
QTest::mouseClick(cells->viewport(), Qt::LeftButton, 0, QPoint(1, 1));
QCOMPARE(dialog->color(), black40Colors);
QSignalSpy okClickedSpy(dialog, SIGNAL(okClicked()));
const QDialogButtonBox *buttonBox = dialog->findChild();
const QList buttons = buttonBox->buttons();
foreach (QAbstractButton *button, buttons) {
if (buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole) {
QTest::mouseClick(button, Qt::LeftButton);
break;
}
}
QCOMPARE(okClickedSpy.count(), 1);
QCOMPARE(colorButton.color(), black40Colors);
#endif
}
void KColorButtonTest::testRecentColorsPick()
{
KColorButton colorButton(Qt::red);
colorButton.show();
QVERIFY(QTest::qWaitForWindowExposed(&colorButton));
QTest::mouseClick(&colorButton, Qt::LeftButton);
QColorDialog *dialog = colorButton.findChild();
- QVERIFY(dialog != NULL);
+ QVERIFY(dialog != nullptr);
QVERIFY(QTest::qWaitForWindowExposed(dialog));
#pragma message("port to QColorDialog")
#if 0
QComboBox *combo = dialog->findChild();
combo->setFocus();
QTest::keyPress(combo, Qt::Key_Up);
QTest::keyPress(combo, Qt::Key_Up);
KColorCells *cells = dialog->findChild();
QVERIFY(cells != NULL);
QTest::mouseMove(cells->viewport(), QPoint(1, 1));
QTest::mouseClick(cells->viewport(), Qt::LeftButton, 0, QPoint(30, 1));
const QColor color = dialog->color();
dialog->accept();
QCOMPARE(colorButton.color(), color);
#endif
}
diff --git a/autotests/kdatecomboboxtest.cpp b/autotests/kdatecomboboxtest.cpp
index 07bb16c..434eaa5 100644
--- a/autotests/kdatecomboboxtest.cpp
+++ b/autotests/kdatecomboboxtest.cpp
@@ -1,163 +1,163 @@
/*
Copyright 2011 John Layt
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "kdatecomboboxtest.h"
#include
#include
#include
#include "kdatecombobox.h"
QTEST_MAIN(KDateComboBoxTest)
void KDateComboBoxTest::testDefaults()
{
- m_combo = new KDateComboBox(0);
+ m_combo = new KDateComboBox(nullptr);
QCOMPARE(m_combo->date(), QDate::currentDate());
// Missing support in QLocale;
//QCOMPARE(m_combo->minimumDate(), KLocale::global()->calendar()->earliestValidDate());
//QCOMPARE(m_combo->maximumDate(), KLocale::global()->calendar()->latestValidDate());
QCOMPARE(m_combo->isValid(), true);
QCOMPARE(m_combo->isNull(), false);
QCOMPARE(m_combo->options(), KDateComboBox::EditDate | KDateComboBox::SelectDate | KDateComboBox::DatePicker | KDateComboBox::DateKeywords);
QCOMPARE(m_combo->displayFormat(), QLocale::ShortFormat);
delete m_combo;
}
void KDateComboBoxTest::testValidNull()
{
- m_combo = new KDateComboBox(0);
+ m_combo = new KDateComboBox(nullptr);
QCOMPARE(m_combo->isValid(), true);
QCOMPARE(m_combo->isNull(), false);
m_combo->setDate(QDate());
QCOMPARE(m_combo->isValid(), false);
QCOMPARE(m_combo->isNull(), true);
m_combo->setDate(QDate(2000, 1, 1));
m_combo->lineEdit()->setText(QStringLiteral("invalid"));
QCOMPARE(m_combo->isValid(), false);
QCOMPARE(m_combo->isNull(), false);
delete m_combo;
}
void KDateComboBoxTest::testDateRange()
{
- m_combo = new KDateComboBox(0);
+ m_combo = new KDateComboBox(nullptr);
m_combo->setDate(QDate(2000, 1, 1));
// Missing support in QLocale;
//QCOMPARE(m_combo->minimumDate(), KLocale::global()->calendar()->earliestValidDate());
//QCOMPARE(m_combo->maximumDate(), KLocale::global()->calendar()->latestValidDate());
QCOMPARE(m_combo->isValid(), true);
m_combo->setDateRange(QDate(2001, 1, 1), QDate(2002, 1, 1));
QCOMPARE(m_combo->minimumDate(), QDate(2001, 1, 1));
QCOMPARE(m_combo->maximumDate(), QDate(2002, 1, 1));
QCOMPARE(m_combo->isValid(), false);
m_combo->setDate(QDate(2003, 1, 1));
QCOMPARE(m_combo->isValid(), false);
m_combo->setDate(QDate(2001, 6, 1));
QCOMPARE(m_combo->isValid(), true);
m_combo->setDate(QDate(2001, 1, 1));
QCOMPARE(m_combo->isValid(), true);
m_combo->setDate(QDate(2002, 1, 1));
QCOMPARE(m_combo->isValid(), true);
m_combo->setDate(QDate(2000, 12, 31));
QCOMPARE(m_combo->isValid(), false);
m_combo->setDate(QDate(2002, 1, 2));
QCOMPARE(m_combo->isValid(), false);
m_combo->setDateRange(QDate(1995, 1, 1), QDate(1990, 1, 1));
QCOMPARE(m_combo->minimumDate(), QDate(2001, 1, 1));
QCOMPARE(m_combo->maximumDate(), QDate(2002, 1, 1));
m_combo->setMinimumDate(QDate(2000, 1, 1));
QCOMPARE(m_combo->minimumDate(), QDate(2000, 1, 1));
QCOMPARE(m_combo->maximumDate(), QDate(2002, 1, 1));
m_combo->setMaximumDate(QDate(2003, 1, 1));
QCOMPARE(m_combo->minimumDate(), QDate(2000, 1, 1));
QCOMPARE(m_combo->maximumDate(), QDate(2003, 1, 1));
m_combo->resetDateRange();
QVERIFY(!m_combo->minimumDate().isValid());
QVERIFY(!m_combo->maximumDate().isValid());
// Check functioning when the minimum or maximum date is not already set
m_combo->setMinimumDate(QDate(2000, 1, 1));
QCOMPARE(m_combo->minimumDate(), QDate(2000, 1, 1));
QVERIFY(!m_combo->maximumDate().isValid());
m_combo->resetMinimumDate();
QVERIFY(!m_combo->minimumDate().isValid());
QVERIFY(!m_combo->maximumDate().isValid());
m_combo->setMaximumDate(QDate(2003, 1, 1));
QVERIFY(!m_combo->minimumDate().isValid());
QCOMPARE(m_combo->maximumDate(), QDate(2003, 1, 1));
m_combo->resetMaximumDate();
QVERIFY(!m_combo->minimumDate().isValid());
QVERIFY(!m_combo->maximumDate().isValid());
delete m_combo;
}
void KDateComboBoxTest::testDateList()
{
- m_combo = new KDateComboBox(0);
+ m_combo = new KDateComboBox(nullptr);
QMap map;
// Test default map
QCOMPARE(m_combo->dateMap(), map);
// Test basic map
map.clear();
map.insert(QDate(2000, 1, 1), QStringLiteral("New Years Day"));
map.insert(QDate(2000, 1, 2), QString());
map.insert(QDate(2000, 1, 3), QStringLiteral("separator"));
map.insert(QDate(), QStringLiteral("No Date"));
m_combo->setDateMap(map);
QCOMPARE(m_combo->dateMap(), map);
delete m_combo;
}
void KDateComboBoxTest::testOptions()
{
- m_combo = new KDateComboBox(0);
+ m_combo = new KDateComboBox(nullptr);
KDateComboBox::Options options = KDateComboBox::EditDate | KDateComboBox::SelectDate | KDateComboBox::DatePicker | KDateComboBox::DateKeywords;
QCOMPARE(m_combo->options(), options);
options = KDateComboBox::EditDate | KDateComboBox::WarnOnInvalid;
m_combo->setOptions(options);
QCOMPARE(m_combo->options(), options);
delete m_combo;
}
void KDateComboBoxTest::testDisplayFormat()
{
- m_combo = new KDateComboBox(0);
+ m_combo = new KDateComboBox(nullptr);
QLocale::FormatType format = QLocale::ShortFormat;
QCOMPARE(m_combo->displayFormat(), format);
format = QLocale::NarrowFormat;
m_combo->setDisplayFormat(format);
QCOMPARE(m_combo->displayFormat(), format);
delete m_combo;
}
diff --git a/autotests/kdatetimeedittest.cpp b/autotests/kdatetimeedittest.cpp
index a8b0b1f..3e6b050 100644
--- a/autotests/kdatetimeedittest.cpp
+++ b/autotests/kdatetimeedittest.cpp
@@ -1,257 +1,257 @@
/*
Copyright 2011 John Layt
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "kdatetimeedittest.h"
#include
#include
#include
#include
#include
#include "kdatetimeedit.h"
#include "kdatecombobox.h"
QTEST_MAIN(KDateTimeEditTest)
void KDateTimeEditTest::testDefaults()
{
- m_edit = new KDateTimeEdit(0);
+ m_edit = new KDateTimeEdit(nullptr);
QCOMPARE(m_edit->dateTime(), QDateTime(QDate::currentDate(), QTime(0, 0, 0)));
QCOMPARE(m_edit->date(), QDate::currentDate());
QCOMPARE(m_edit->time(), QTime(0, 0, 0));
// Missing support in QLocale
//QCOMPARE(m_edit->minimumDateTime(), KDateTime(KLocale::global()->calendar()->earliestValidDate(), QTime(0, 0, 0)));
//QCOMPARE(m_edit->maximumDateTime(), KDateTime(KLocale::global()->calendar()->latestValidDate(), QTime(23, 59, 59, 999)));
QCOMPARE(m_edit->isValid(), true);
QCOMPARE(m_edit->isNull(), false);
QCOMPARE(m_edit->options(), KDateTimeEdit::ShowDate | KDateTimeEdit::EditDate | KDateTimeEdit::SelectDate | KDateTimeEdit::DatePicker | KDateTimeEdit::DateKeywords | KDateTimeEdit::ShowTime | KDateTimeEdit::EditTime | KDateTimeEdit::SelectTime);
QCOMPARE(m_edit->dateDisplayFormat(), QLocale::ShortFormat);
QCOMPARE(m_edit->timeListInterval(), 15);
QCOMPARE(m_edit->timeDisplayFormat(), QLocale::ShortFormat);
delete m_edit;
}
void KDateTimeEditTest::testValidNull()
{
- m_edit = new KDateTimeEdit(0);
+ m_edit = new KDateTimeEdit(nullptr);
QCOMPARE(m_edit->isValid(), true);
QCOMPARE(m_edit->isNull(), false);
m_edit->setDateTime(QDateTime());
QCOMPARE(m_edit->isValid(), false);
QCOMPARE(m_edit->isNull(), true);
delete m_edit;
}
void KDateTimeEditTest::testDateTimeRange()
{
- m_edit = new KDateTimeEdit(0);
+ m_edit = new KDateTimeEdit(nullptr);
m_edit->setDateTime(QDateTime(QDate(2000, 1, 1), QTime(12, 0, 0)));
// Missing support in QLocale
//QCOMPARE(m_edit->minimumDateTime(), KDateTime(KLocale::global()->calendar()->earliestValidDate(), QTime(0, 0, 0)));
//QCOMPARE(m_edit->maximumDateTime(), KDateTime(KLocale::global()->calendar()->latestValidDate(), QTime(23, 59, 59, 999)));
QCOMPARE(m_edit->isValid(), true);
m_edit->setDateTimeRange(QDateTime(QDate(2001, 1, 1), QTime(10, 0, 0)),
QDateTime(QDate(2002, 1, 1), QTime(20, 0, 0)));
QCOMPARE(m_edit->minimumDateTime(), QDateTime(QDate(2001, 1, 1), QTime(10, 0, 0)));
QCOMPARE(m_edit->maximumDateTime(), QDateTime(QDate(2002, 1, 1), QTime(20, 0, 0)));
QCOMPARE(m_edit->isValid(), false);
m_edit->setDateTime(QDateTime(QDate(2001, 1, 1), QTime(9, 59, 59, 999)));
QCOMPARE(m_edit->isValid(), false);
m_edit->setDateTime(QDateTime(QDate(2001, 1, 1), QTime(10, 0, 0)));
QCOMPARE(m_edit->isValid(), true);
m_edit->setDateTime(QDateTime(QDate(2002, 1, 1), QTime(20, 0, 0, 1)));
QCOMPARE(m_edit->isValid(), false);
m_edit->setDateTime(QDateTime(QDate(2002, 1, 1), QTime(20, 0, 0, 0)));
QCOMPARE(m_edit->isValid(), true);
m_edit->setDateTimeRange(QDateTime(QDate(1995, 1, 1), QTime(10, 0, 0)),
QDateTime(QDate(1990, 1, 1), QTime(20, 0, 0)));
QCOMPARE(m_edit->minimumDateTime(), QDateTime(QDate(2001, 1, 1), QTime(10, 0, 0)));
QCOMPARE(m_edit->maximumDateTime(), QDateTime(QDate(2002, 1, 1), QTime(20, 0, 0)));
m_edit->setMinimumDateTime(QDateTime(QDate(2000, 1, 1), QTime(0, 0, 0)));
QCOMPARE(m_edit->minimumDateTime(), QDateTime(QDate(2000, 1, 1), QTime(0, 0, 0)));
QCOMPARE(m_edit->maximumDateTime(), QDateTime(QDate(2002, 1, 1), QTime(20, 0, 0)));
m_edit->setMaximumDateTime(QDateTime(QDate(2003, 1, 1), QTime(0, 0, 0)));
QCOMPARE(m_edit->minimumDateTime(), QDateTime(QDate(2000, 1, 1), QTime(0, 0, 0)));
QCOMPARE(m_edit->maximumDateTime(), QDateTime(QDate(2003, 1, 1), QTime(0, 0, 0)));
delete m_edit;
}
void KDateTimeEditTest::testDateList()
{
- m_edit = new KDateTimeEdit(0);
+ m_edit = new KDateTimeEdit(nullptr);
QMap map;
// KDateTimeEditTest default map
QCOMPARE(m_edit->dateMap(), map);
// KDateTimeEditTest basic map
map.clear();
map.insert(QDate(2000, 1, 1), QStringLiteral("New Years Day"));
map.insert(QDate(2000, 1, 2), QString());
map.insert(QDate(2000, 1, 3), QStringLiteral("separator"));
map.insert(QDate(), QStringLiteral("No Date"));
m_edit->setDateMap(map);
QCOMPARE(m_edit->dateMap(), map);
delete m_edit;
}
void KDateTimeEditTest::testOptions()
{
- m_edit = new KDateTimeEdit(0);
+ m_edit = new KDateTimeEdit(nullptr);
KDateTimeEdit::Options options = KDateTimeEdit::ShowDate | KDateTimeEdit::EditDate | KDateTimeEdit::SelectDate | KDateTimeEdit::DatePicker | KDateTimeEdit::DateKeywords | KDateTimeEdit::ShowTime | KDateTimeEdit::EditTime | KDateTimeEdit::SelectTime;
QCOMPARE(m_edit->options(), options);
options = KDateTimeEdit::EditDate | KDateTimeEdit::WarnOnInvalid;
m_edit->setOptions(options);
QCOMPARE(m_edit->options(), options);
delete m_edit;
}
void KDateTimeEditTest::testDateDisplayFormat()
{
- m_edit = new KDateTimeEdit(0);
+ m_edit = new KDateTimeEdit(nullptr);
QLocale::FormatType format = QLocale::ShortFormat;
QCOMPARE(m_edit->dateDisplayFormat(), format);
format = QLocale::NarrowFormat;
m_edit->setDateDisplayFormat(format);
QCOMPARE(m_edit->dateDisplayFormat(), format);
delete m_edit;
}
void KDateTimeEditTest::testTimeListInterval()
{
m_edit = new KDateTimeEdit();
QCOMPARE(m_edit->timeListInterval(), 15);
m_edit-> setTimeListInterval(60);
QCOMPARE(m_edit->timeListInterval(), 60);
delete m_edit;
}
void KDateTimeEditTest::testTimeList()
{
m_edit = new KDateTimeEdit();
QList list;
// KDateTimeEditTest default list
QTime thisTime = QTime(0, 0, 0);
for (int i = 0; i < 1440; i = i + 15) {
list << thisTime.addSecs(i * 60);
}
list << QTime(23, 59, 59, 999);
QCOMPARE(m_edit->timeList(), list);
// KDateTimeEditTest basic list
list.clear();
list << QTime(3, 0, 0) << QTime(15, 16, 17);
m_edit->setTimeList(list);
QCOMPARE(m_edit->timeList(), list);
delete m_edit;
}
void KDateTimeEditTest::testTimeDisplayFormat()
{
m_edit = new KDateTimeEdit();
QLocale::FormatType format = QLocale::ShortFormat;
QCOMPARE(m_edit->timeDisplayFormat(), format);
format = QLocale::NarrowFormat;
m_edit->setTimeDisplayFormat(format);
QCOMPARE(m_edit->timeDisplayFormat(), format);
delete m_edit;
}
void KDateTimeEditTest::testCalendarSystem()
{
m_edit = new KDateTimeEdit();
QList calendars;
calendars << QLocale();
QCOMPARE(m_edit->locale(), QLocale());
QCOMPARE(m_edit->calendarLocalesList(), calendars);
m_edit->setLocale(QLocale(QLocale::Hebrew));
QCOMPARE(m_edit->locale(), QLocale(QLocale::Hebrew));
calendars.clear();
calendars.append(QLocale(QLocale::Hebrew));
calendars.append(QLocale(QLocale::Chinese));
m_edit->setCalendarLocalesList(calendars);
QCOMPARE(m_edit->calendarLocalesList(), calendars);
delete m_edit;
}
void KDateTimeEditTest::testTimeSpec()
{
m_edit = new KDateTimeEdit();
QCOMPARE(m_edit->timeZone(), QDateTime::currentDateTime().timeZone());
QList zones;
foreach (const QByteArray &zoneId, QTimeZone::availableTimeZoneIds()) {
zones << QTimeZone(zoneId);
}
QCOMPARE(m_edit->timeZones(), zones);
QTimeZone zone(3600);
m_edit->setTimeZone(zone);
QCOMPARE(m_edit->timeZone(), zone);
zones << zone;
m_edit->setTimeZones(zones);
QCOMPARE(m_edit->timeZones(), zones);
delete m_edit;
}
template
static T findVisibleChild(QWidget *parent)
{
foreach (T child, parent->findChildren()) {
if (child->isVisible()) {
return child;
}
}
- return 0;
+ return nullptr;
}
void KDateTimeEditTest::testDateMenu()
{
m_edit = new KDateTimeEdit();
KDateTimeEdit::Options options = KDateTimeEdit::ShowDate | KDateTimeEdit::EditDate | KDateTimeEdit::SelectDate | KDateTimeEdit::DatePicker | KDateTimeEdit::DateKeywords;
m_edit->setOptions(options);
m_edit->setDate(QDate(2002, 1, 1));
m_edit->show();
QComboBox *combo = findVisibleChild(m_edit);
QVERIFY(combo);
combo->showPopup();
QMenu *menu = findVisibleChild(combo);
QVERIFY(menu);
QAction *nextMonthAction = menu->actions().at(3);
QCOMPARE(nextMonthAction->text(), KDateComboBox::tr("Next Month", "@option next month"));
nextMonthAction->trigger();
QCOMPARE(m_edit->date(), QDate::currentDate().addMonths(1));
}
diff --git a/autotests/kdualactiontest.cpp b/autotests/kdualactiontest.cpp
index ead2c9b..02a1d91 100644
--- a/autotests/kdualactiontest.cpp
+++ b/autotests/kdualactiontest.cpp
@@ -1,129 +1,129 @@
/* This file is part of the KDE libraries
*
* Copyright (c) 2010 Aurélien Gâteau
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include
#include
#include "kguiitem.h"
static const QString INACTIVE_TEXT = QStringLiteral("Show Foo");
static const QString ACTIVE_TEXT = QStringLiteral("Hide Foo");
class KDualActionTest : public QObject
{
Q_OBJECT
private Q_SLOTS:
void initTestCase()
{
qRegisterMetaType("QAction*");
}
void testSetGuiItem()
{
- KDualAction action(0);
+ KDualAction action(nullptr);
action.setInactiveGuiItem(KGuiItem(INACTIVE_TEXT));
action.setActiveGuiItem(KGuiItem(ACTIVE_TEXT));
QCOMPARE(action.inactiveText(), INACTIVE_TEXT);
QCOMPARE(action.activeText(), ACTIVE_TEXT);
QCOMPARE(action.text(), INACTIVE_TEXT);
}
void testSetIconForStates()
{
QIcon icon(QPixmap(16, 16));
QVERIFY(!icon.isNull());
- KDualAction action(0);
+ KDualAction action(nullptr);
QVERIFY(action.inactiveIcon().isNull());
QVERIFY(action.activeIcon().isNull());
action.setIconForStates(icon);
QCOMPARE(action.inactiveIcon(), icon);
QCOMPARE(action.activeIcon(), icon);
}
void testSetActive()
{
- KDualAction action(INACTIVE_TEXT, ACTIVE_TEXT, 0);
+ KDualAction action(INACTIVE_TEXT, ACTIVE_TEXT, nullptr);
QVERIFY(!action.isActive());
QCOMPARE(action.text(), INACTIVE_TEXT);
QSignalSpy activeChangedSpy(&action, SIGNAL(activeChanged(bool)));
QSignalSpy activeChangedByUserSpy(&action, SIGNAL(activeChangedByUser(bool)));
action.setActive(true);
QVERIFY(action.isActive());
QCOMPARE(action.text(), ACTIVE_TEXT);
QCOMPARE(activeChangedSpy.count(), 1);
QCOMPARE(activeChangedSpy.takeFirst().at(0).toBool(), true);
QCOMPARE(activeChangedByUserSpy.count(), 0);
action.setActive(false);
QVERIFY(!action.isActive());
QCOMPARE(action.text(), INACTIVE_TEXT);
QCOMPARE(activeChangedSpy.count(), 1);
QCOMPARE(activeChangedSpy.takeFirst().at(0).toBool(), false);
QCOMPARE(activeChangedByUserSpy.count(), 0);
}
void testTrigger()
{
- KDualAction action(INACTIVE_TEXT, ACTIVE_TEXT, 0);
+ KDualAction action(INACTIVE_TEXT, ACTIVE_TEXT, nullptr);
QVERIFY(!action.isActive());
QCOMPARE(action.text(), INACTIVE_TEXT);
QSignalSpy activeChangedSpy(&action, SIGNAL(activeChanged(bool)));
QSignalSpy activeChangedByUserSpy(&action, SIGNAL(activeChangedByUser(bool)));
action.trigger();
QVERIFY(action.isActive());
QCOMPARE(action.text(), ACTIVE_TEXT);
QCOMPARE(activeChangedSpy.count(), 1);
QCOMPARE(activeChangedSpy.takeFirst().at(0).toBool(), true);
QCOMPARE(activeChangedByUserSpy.count(), 1);
QCOMPARE(activeChangedByUserSpy.takeFirst().at(0).toBool(), true);
action.trigger();
QVERIFY(!action.isActive());
QCOMPARE(action.text(), INACTIVE_TEXT);
QCOMPARE(activeChangedSpy.count(), 1);
QCOMPARE(activeChangedSpy.takeFirst().at(0).toBool(), false);
QCOMPARE(activeChangedByUserSpy.count(), 1);
QCOMPARE(activeChangedByUserSpy.takeFirst().at(0).toBool(), false);
// Turn off autoToggle, nothing should happen
action.setAutoToggle(false);
action.trigger();
QVERIFY(!action.isActive());
QCOMPARE(action.text(), INACTIVE_TEXT);
QCOMPARE(activeChangedSpy.count(), 0);
QCOMPARE(activeChangedByUserSpy.count(), 0);
// Turn on autoToggle, action should change
action.setAutoToggle(true);
action.trigger();
QCOMPARE(action.text(), ACTIVE_TEXT);
QCOMPARE(activeChangedSpy.count(), 1);
QCOMPARE(activeChangedSpy.takeFirst().at(0).toBool(), true);
QCOMPARE(activeChangedByUserSpy.count(), 1);
QCOMPARE(activeChangedByUserSpy.takeFirst().at(0).toBool(), true);
}
};
QTEST_MAIN(KDualActionTest)
#include "kdualactiontest.moc"
diff --git a/autotests/kselectaction_unittest.cpp b/autotests/kselectaction_unittest.cpp
index 9cc1e83..7cd6301 100644
--- a/autotests/kselectaction_unittest.cpp
+++ b/autotests/kselectaction_unittest.cpp
@@ -1,329 +1,329 @@
/* This file is part of the KDE libraries
Copyright (c) 2009 Daniel Calviño Sánchez
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "kselectaction_unittest.h"
#include
#include
#include
#include
#include
QTEST_MAIN(KSelectAction_UnitTest)
void KSelectAction_UnitTest::testSetToolTipBeforeRequestingComboBoxWidget()
{
- KSelectAction selectAction(QStringLiteral("selectAction"), 0);
+ KSelectAction selectAction(QStringLiteral("selectAction"), nullptr);
selectAction.setToolBarMode(KSelectAction::ComboBoxMode);
selectAction.setToolTip(QStringLiteral("Test"));
selectAction.setEnabled(false); // also test disabling the action
QWidget parent;
QWidget *widget = selectAction.requestWidget(&parent);
QVERIFY(widget);
QComboBox *comboBox = qobject_cast(widget);
QVERIFY(comboBox);
QCOMPARE(comboBox->toolTip(), QStringLiteral("Test"));
QCOMPARE(comboBox->isEnabled(), false);
}
void KSelectAction_UnitTest::testSetToolTipAfterRequestingComboBoxWidget()
{
- KSelectAction selectAction(QStringLiteral("selectAction"), 0);
+ KSelectAction selectAction(QStringLiteral("selectAction"), nullptr);
selectAction.setToolBarMode(KSelectAction::ComboBoxMode);
QWidget parent;
QWidget *widget = selectAction.requestWidget(&parent);
selectAction.setToolTip(QStringLiteral("Test"));
selectAction.setEnabled(false); // also test disabling the action
QVERIFY(widget);
QComboBox *comboBox = qobject_cast(widget);
QVERIFY(comboBox);
QCOMPARE(comboBox->toolTip(), QStringLiteral("Test"));
QCOMPARE(comboBox->isEnabled(), false);
}
void KSelectAction_UnitTest::testSetToolTipBeforeRequestingToolButtonWidget()
{
- KSelectAction selectAction(QStringLiteral("selectAction"), 0);
+ KSelectAction selectAction(QStringLiteral("selectAction"), nullptr);
selectAction.setToolBarMode(KSelectAction::MenuMode);
selectAction.setToolTip(QStringLiteral("Test"));
QToolBar toolBar;
//Don't use requestWidget, as it needs a releaseWidget when used in MenuMode
//(in ComboBoxMode the widget is released automatically when it is
//destroyed). When the action is added to the QToolBar, it requests and
//releases the widget as needed.
toolBar.addAction(&selectAction);
QWidget *widget = toolBar.widgetForAction(&selectAction);
QVERIFY(widget);
QToolButton *toolButton = qobject_cast(widget);
QVERIFY(toolButton);
QCOMPARE(toolButton->toolTip(), QStringLiteral("Test"));
}
void KSelectAction_UnitTest::testSetToolTipAfterRequestingToolButtonWidget()
{
- KSelectAction selectAction(QStringLiteral("selectAction"), 0);
+ KSelectAction selectAction(QStringLiteral("selectAction"), nullptr);
selectAction.setToolBarMode(KSelectAction::MenuMode);
QToolBar toolBar;
//Don't use requestWidget, as it needs a releaseWidget when used in MenuMode
//(in ComboBoxMode the widget is released automatically when it is
//destroyed). When the action is added to the QToolBar, it requests and
//releases the widget as needed.
toolBar.addAction(&selectAction);
QWidget *widget = toolBar.widgetForAction(&selectAction);
selectAction.setToolTip(QStringLiteral("Test"));
QVERIFY(widget);
QToolButton *toolButton = qobject_cast(widget);
QVERIFY(toolButton);
QCOMPARE(toolButton->toolTip(), QStringLiteral("Test"));
}
void KSelectAction_UnitTest::testSetWhatsThisBeforeRequestingComboBoxWidget()
{
- KSelectAction selectAction(QStringLiteral("selectAction"), 0);
+ KSelectAction selectAction(QStringLiteral("selectAction"), nullptr);
selectAction.setToolBarMode(KSelectAction::ComboBoxMode);
selectAction.setWhatsThis(QStringLiteral("Test"));
QWidget parent;
QWidget *widget = selectAction.requestWidget(&parent);
QVERIFY(widget);
QComboBox *comboBox = qobject_cast(widget);
QVERIFY(comboBox);
QCOMPARE(comboBox->whatsThis(), QStringLiteral("Test"));
}
void KSelectAction_UnitTest::testSetWhatsThisAfterRequestingComboBoxWidget()
{
- KSelectAction selectAction(QStringLiteral("selectAction"), 0);
+ KSelectAction selectAction(QStringLiteral("selectAction"), nullptr);
selectAction.setToolBarMode(KSelectAction::ComboBoxMode);
QWidget parent;
QWidget *widget = selectAction.requestWidget(&parent);
selectAction.setWhatsThis(QStringLiteral("Test"));
QVERIFY(widget);
QComboBox *comboBox = qobject_cast(widget);
QVERIFY(comboBox);
QCOMPARE(comboBox->whatsThis(), QStringLiteral("Test"));
}
void KSelectAction_UnitTest::testSetWhatsThisBeforeRequestingToolButtonWidget()
{
- KSelectAction selectAction(QStringLiteral("selectAction"), 0);
+ KSelectAction selectAction(QStringLiteral("selectAction"), nullptr);
selectAction.setToolBarMode(KSelectAction::MenuMode);
selectAction.setWhatsThis(QStringLiteral("Test"));
QToolBar toolBar;
//Don't use requestWidget, as it needs a releaseWidget when used in MenuMode
//(in ComboBoxMode the widget is released automatically when it is
//destroyed). When the action is added to the QToolBar, it requests and
//releases the widget as needed.
toolBar.addAction(&selectAction);
QWidget *widget = toolBar.widgetForAction(&selectAction);
QVERIFY(widget);
QToolButton *toolButton = qobject_cast(widget);
QVERIFY(toolButton);
QCOMPARE(toolButton->whatsThis(), QStringLiteral("Test"));
}
void KSelectAction_UnitTest::testSetWhatsThisAfterRequestingToolButtonWidget()
{
- KSelectAction selectAction(QStringLiteral("selectAction"), 0);
+ KSelectAction selectAction(QStringLiteral("selectAction"), nullptr);
selectAction.setToolBarMode(KSelectAction::MenuMode);
QToolBar toolBar;
//Don't use requestWidget, as it needs a releaseWidget when used in MenuMode
//(in ComboBoxMode the widget is released automatically when it is
//destroyed). When the action is added to the QToolBar, it requests and
//releases the widget as needed.
toolBar.addAction(&selectAction);
QWidget *widget = toolBar.widgetForAction(&selectAction);
selectAction.setWhatsThis(QStringLiteral("Test"));
QVERIFY(widget);
QToolButton *toolButton = qobject_cast(widget);
QVERIFY(toolButton);
QCOMPARE(toolButton->whatsThis(), QStringLiteral("Test"));
}
void KSelectAction_UnitTest::testChildActionStateChangeComboMode()
{
- KSelectAction selectAction(QStringLiteral("selectAction"), 0);
+ KSelectAction selectAction(QStringLiteral("selectAction"), nullptr);
selectAction.setToolBarMode(KSelectAction::ComboBoxMode);
QWidget parent;
QWidget *widget = selectAction.requestWidget(&parent);
QComboBox *comboBox = qobject_cast(widget);
QVERIFY(comboBox);
const QString itemText = QStringLiteral("foo");
QAction *childAction = selectAction.addAction(itemText);
QCOMPARE(comboBox->itemText(0), itemText);
childAction->setEnabled(false);
// There's no API for item-is-enabled, need to go via the internal model like kselectaction does...
QStandardItemModel *model = qobject_cast(comboBox->model());
QVERIFY(model);
QVERIFY(!model->item(0)->isEnabled());
// Now remove the action
selectAction.removeAction(childAction);
QCOMPARE(comboBox->count(), 0);
}
void KSelectAction_UnitTest::testRequestWidgetComboBoxModeWidgetParent()
{
- KSelectAction selectAction(QStringLiteral("selectAction"), 0);
+ KSelectAction selectAction(QStringLiteral("selectAction"), nullptr);
selectAction.setToolBarMode(KSelectAction::ComboBoxMode);
QToolBar toolBar;
toolBar.addAction(&selectAction);
QWidget *widget = toolBar.widgetForAction(&selectAction);
QVERIFY(widget);
QComboBox *comboBox = qobject_cast(widget);
QVERIFY(comboBox);
QVERIFY(!comboBox->isEnabled());
}
void KSelectAction_UnitTest::testRequestWidgetComboBoxModeWidgetParentSeveralActions()
{
- KSelectAction selectAction(QStringLiteral("selectAction"), 0);
+ KSelectAction selectAction(QStringLiteral("selectAction"), nullptr);
selectAction.setToolBarMode(KSelectAction::ComboBoxMode);
selectAction.addAction(new QAction(QStringLiteral("action1"), &selectAction));
selectAction.addAction(new QAction(QStringLiteral("action2"), &selectAction));
selectAction.addAction(new QAction(QStringLiteral("action3"), &selectAction));
QToolBar toolBar;
toolBar.addAction(&selectAction);
QWidget *widget = toolBar.widgetForAction(&selectAction);
QVERIFY(widget);
QComboBox *comboBox = qobject_cast(widget);
QVERIFY(comboBox);
QVERIFY(comboBox->isEnabled());
}
void KSelectAction_UnitTest::testRequestWidgetMenuModeWidgetParent()
{
- KSelectAction selectAction(QStringLiteral("selectAction"), 0);
+ KSelectAction selectAction(QStringLiteral("selectAction"), nullptr);
selectAction.setToolBarMode(KSelectAction::MenuMode);
QToolBar toolBar;
toolBar.addAction(&selectAction);
QWidget *widget = toolBar.widgetForAction(&selectAction);
QVERIFY(widget);
QToolButton *toolButton = qobject_cast(widget);
QVERIFY(toolButton);
QVERIFY(!toolButton->isEnabled());
QVERIFY(toolButton->autoRaise());
QCOMPARE((int)toolButton->focusPolicy(), (int)Qt::NoFocus);
QCOMPARE(toolButton->defaultAction(), (QAction *)&selectAction);
QCOMPARE(toolButton->actions().count(), 1);
QCOMPARE(toolButton->actions().at(0)->text(), QStringLiteral("selectAction"));
}
void KSelectAction_UnitTest::testRequestWidgetMenuModeWidgetParentSeveralActions()
{
- KSelectAction selectAction(QStringLiteral("selectAction"), 0);
+ KSelectAction selectAction(QStringLiteral("selectAction"), nullptr);
selectAction.setToolBarMode(KSelectAction::MenuMode);
selectAction.addAction(new QAction(QStringLiteral("action1"), &selectAction));
selectAction.addAction(new QAction(QStringLiteral("action2"), &selectAction));
selectAction.addAction(new QAction(QStringLiteral("action3"), &selectAction));
QToolBar toolBar;
toolBar.addAction(&selectAction);
QWidget *widget = toolBar.widgetForAction(&selectAction);
QVERIFY(widget);
QToolButton *toolButton = qobject_cast(widget);
QVERIFY(toolButton);
QVERIFY(toolButton->isEnabled());
QVERIFY(toolButton->autoRaise());
QCOMPARE((int)toolButton->focusPolicy(), (int)Qt::NoFocus);
QCOMPARE(toolButton->defaultAction(), (QAction *)&selectAction);
QCOMPARE(toolButton->actions().count(), 4);
QCOMPARE(toolButton->actions().at(0)->text(), QStringLiteral("selectAction"));
QCOMPARE(toolButton->actions().at(1)->text(), QStringLiteral("action1"));
QCOMPARE(toolButton->actions().at(2)->text(), QStringLiteral("action2"));
QCOMPARE(toolButton->actions().at(3)->text(), QStringLiteral("action3"));
}
void KSelectAction_UnitTest::testRequestWidgetMenuModeWidgetParentAddActions()
{
- KSelectAction selectAction(QStringLiteral("selectAction"), 0);
+ KSelectAction selectAction(QStringLiteral("selectAction"), nullptr);
selectAction.setToolBarMode(KSelectAction::MenuMode);
QToolBar toolBar;
toolBar.addAction(&selectAction);
QWidget *widget = toolBar.widgetForAction(&selectAction);
QVERIFY(widget);
QVERIFY(!widget->isEnabled());
selectAction.addAction(new QAction(QStringLiteral("action1"), &selectAction));
selectAction.addAction(new QAction(QStringLiteral("action2"), &selectAction));
selectAction.addAction(new QAction(QStringLiteral("action3"), &selectAction));
QVERIFY(widget->isEnabled());
QCOMPARE(widget->actions().count(), 4);
QCOMPARE(widget->actions().at(0)->text(), QStringLiteral("selectAction"));
QCOMPARE(widget->actions().at(1)->text(), QStringLiteral("action1"));
QCOMPARE(widget->actions().at(2)->text(), QStringLiteral("action2"));
QCOMPARE(widget->actions().at(3)->text(), QStringLiteral("action3"));
}
void KSelectAction_UnitTest::testRequestWidgetMenuModeWidgetParentRemoveActions()
{
- KSelectAction selectAction(QStringLiteral("selectAction"), 0);
+ KSelectAction selectAction(QStringLiteral("selectAction"), nullptr);
selectAction.setToolBarMode(KSelectAction::MenuMode);
QToolBar toolBar;
toolBar.addAction(&selectAction);
QWidget *widget = toolBar.widgetForAction(&selectAction);
QVERIFY(widget);
QAction *action1 = new QAction(QStringLiteral("action1"), &selectAction);
selectAction.addAction(action1);
QAction *action2 = new QAction(QStringLiteral("action2"), &selectAction);
selectAction.addAction(action2);
QAction *action3 = new QAction(QStringLiteral("action3"), &selectAction);
selectAction.addAction(action3);
delete selectAction.removeAction(action1);
delete selectAction.removeAction(action2);
delete selectAction.removeAction(action3);
QVERIFY(!widget->isEnabled());
QCOMPARE(widget->actions().count(), 1);
QCOMPARE(widget->actions().at(0)->text(), QStringLiteral("selectAction"));
}
diff --git a/autotests/ksplittercollapserbuttontest.h b/autotests/ksplittercollapserbuttontest.h
index 4c64b79..8f23621 100644
--- a/autotests/ksplittercollapserbuttontest.h
+++ b/autotests/ksplittercollapserbuttontest.h
@@ -1,58 +1,58 @@
/*
Copyright (c) 2014 Montel Laurent
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) version 3, or any
later version accepted by the membership of KDE e.V. (or its
successor approved by the membership of KDE e.V.), which shall
act as a proxy defined in Section 6 of version 3 of the license.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this program. If not, see .
*/
#ifndef KSPLITTERCOLLAPSERBUTTONTEST_H
#define KSPLITTERCOLLAPSERBUTTONTEST_H
#include
class QSplitter;
class QTextEdit;
class TestSplitter : public QWidget
{
Q_OBJECT
public:
- explicit TestSplitter(QWidget *parent = 0);
+ explicit TestSplitter(QWidget *parent = nullptr);
QSplitter *splitter;
QTextEdit *edit1;
QTextEdit *edit2;
};
class KSplitterCollapserButtonTest : public QObject
{
Q_OBJECT
public:
- explicit KSplitterCollapserButtonTest(QObject *parent = 0);
+ explicit KSplitterCollapserButtonTest(QObject *parent = nullptr);
~KSplitterCollapserButtonTest();
private Q_SLOTS:
void shouldHaveDefaultValue();
void shouldCollapseWhenClickOnButton();
void shouldRestoreCorrectPosition();
void shouldRestoreCorrectPositionForFirstWidget();
void shouldTestVerticalSplitterFirstWidget();
void shouldTestVerticalSplitterSecondWidget();
void shouldBeVisible_data();
void shouldBeVisible();
void shouldBeVisibleWhenMovingHandle_data();
void shouldBeVisibleWhenMovingHandle();
};
#endif // KSPLITTERCOLLAPSERBUTTONTEST_H
diff --git a/autotests/ktimecomboboxtest.cpp b/autotests/ktimecomboboxtest.cpp
index f0cd3f4..b01b14b 100644
--- a/autotests/ktimecomboboxtest.cpp
+++ b/autotests/ktimecomboboxtest.cpp
@@ -1,186 +1,186 @@
/*
Copyright 2011 John Layt
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "ktimecomboboxtest.h"
#include
#include
#include
#include
QTEST_MAIN(KTimeComboBoxTest)
void KTimeComboBoxTest::testDefaults()
{
m_combo = new KTimeComboBox();
QCOMPARE(m_combo->time(), QTime(0, 0, 0, 0));
QCOMPARE(m_combo->minimumTime(), QTime(0, 0, 0, 0));
QCOMPARE(m_combo->maximumTime(), QTime(23, 59, 59, 999));
QCOMPARE(m_combo->isValid(), true);
QCOMPARE(m_combo->options(), KTimeComboBox::EditTime | KTimeComboBox::SelectTime);
QCOMPARE(m_combo->timeListInterval(), 15);
QCOMPARE(m_combo->displayFormat(), QLocale::ShortFormat);
delete m_combo;
}
void KTimeComboBoxTest::testValidNull()
{
- m_combo = new KTimeComboBox(0);
+ m_combo = new KTimeComboBox(nullptr);
QCOMPARE(m_combo->isValid(), true);
QCOMPARE(m_combo->isNull(), false);
m_combo->setTime(QTime());
QCOMPARE(m_combo->isValid(), false);
QCOMPARE(m_combo->isNull(), true);
m_combo->setTime(QTime(0, 0, 0));
m_combo->lineEdit()->setText(QStringLiteral("99:99"));
QCOMPARE(m_combo->isValid(), false);
QCOMPARE(m_combo->isNull(), false);
delete m_combo;
}
void KTimeComboBoxTest::testTimeRange()
{
m_combo = new KTimeComboBox();
m_combo->setTime(QTime(2, 0, 0, 0));
QCOMPARE(m_combo->minimumTime(), QTime(0, 0, 0, 0));
QCOMPARE(m_combo->maximumTime(), QTime(23, 59, 59, 999));
QCOMPARE(m_combo->isValid(), true);
m_combo->setTimeRange(QTime(3, 0, 0, 0), QTime(22, 0, 0, 0));
QCOMPARE(m_combo->minimumTime(), QTime(3, 0, 0, 0));
QCOMPARE(m_combo->maximumTime(), QTime(22, 0, 0, 0));
QCOMPARE(m_combo->isValid(), false);
m_combo->setTime(QTime(23, 0, 0, 0));
QCOMPARE(m_combo->isValid(), false);
m_combo->setTime(QTime(12, 0, 0, 0));
QCOMPARE(m_combo->isValid(), true);
m_combo->setTime(QTime(3, 0, 0, 0));
QCOMPARE(m_combo->isValid(), true);
m_combo->setTime(QTime(22, 0, 0, 0));
QCOMPARE(m_combo->isValid(), true);
m_combo->setTime(QTime(2, 59, 59, 999));
QCOMPARE(m_combo->isValid(), false);
m_combo->setTime(QTime(22, 1, 0, 0));
QCOMPARE(m_combo->isValid(), false);
m_combo->setTimeRange(QTime(15, 0, 0, 0), QTime(5, 0, 0, 0));
QCOMPARE(m_combo->minimumTime(), QTime(3, 0, 0, 0));
QCOMPARE(m_combo->maximumTime(), QTime(22, 0, 0, 0));
m_combo->setMinimumTime(QTime(2, 0, 0, 0));
QCOMPARE(m_combo->minimumTime(), QTime(2, 0, 0, 0));
QCOMPARE(m_combo->maximumTime(), QTime(22, 0, 0, 0));
m_combo->setMaximumTime(QTime(21, 0, 0, 0));
QCOMPARE(m_combo->minimumTime(), QTime(2, 0, 0, 0));
QCOMPARE(m_combo->maximumTime(), QTime(21, 0, 0, 0));
delete m_combo;
}
void KTimeComboBoxTest::testTimeListInterval()
{
m_combo = new KTimeComboBox();
QCOMPARE(m_combo->timeListInterval(), 15);
m_combo-> setTimeListInterval(60);
QCOMPARE(m_combo->timeListInterval(), 60);
m_combo-> setTimeListInterval(7);
QCOMPARE(m_combo->timeListInterval(), 60);
m_combo-> setTimeListInterval(720);
QCOMPARE(m_combo->timeListInterval(), 720);
QList list;
list << QTime(0, 0, 0) << QTime(12, 0, 0) << QTime(23, 59, 59, 999);
QCOMPARE(m_combo->timeList(), list);
m_combo->setTimeRange(QTime(4, 0, 0, 0), QTime(5, 0, 0, 0));
m_combo-> setTimeListInterval(30);
list.clear();
list << QTime(4, 0, 0) << QTime(4, 30, 0) << QTime(5, 0, 0, 0);
QCOMPARE(m_combo->timeList(), list);
m_combo->setTimeRange(QTime(4, 0, 0, 0), QTime(4, 59, 0, 0));
m_combo-> setTimeListInterval(30);
list.clear();
list << QTime(4, 0, 0) << QTime(4, 30, 0) << QTime(4, 59, 0, 0);
QCOMPARE(m_combo->timeList(), list);
delete m_combo;
}
void KTimeComboBoxTest::testTimeList()
{
m_combo = new KTimeComboBox();
QList list;
// Test default list
QTime thisTime = QTime(0, 0, 0);
for (int i = 0; i < 1440; i = i + 15) {
list << thisTime.addSecs(i * 60);
}
list << QTime(23, 59, 59, 999);
QCOMPARE(m_combo->timeList(), list);
// Test basic list
list.clear();
list << QTime(3, 0, 0) << QTime(15, 16, 17);
m_combo->setTimeList(list);
QCOMPARE(m_combo->timeList(), list);
QCOMPARE(m_combo->minimumTime(), QTime(3, 0, 0));
QCOMPARE(m_combo->maximumTime(), QTime(15, 16, 17));
// Test sort input times
list.clear();
list << QTime(17, 16, 15) << QTime(4, 0, 0);
m_combo->setTimeList(list);
qSort(list);
QCOMPARE(m_combo->timeList(), list);
QCOMPARE(m_combo->minimumTime(), QTime(4, 0, 0));
QCOMPARE(m_combo->maximumTime(), QTime(17, 16, 15));
// Test ignore null QTime
list.clear();
list << QTime(3, 0, 0) << QTime(15, 16, 17) << QTime();
m_combo->setTimeList(list);
list.takeLast();
QCOMPARE(m_combo->timeList(), list);
QCOMPARE(m_combo->minimumTime(), QTime(3, 0, 0));
QCOMPARE(m_combo->maximumTime(), QTime(15, 16, 17));
delete m_combo;
}
void KTimeComboBoxTest::testOptions()
{
m_combo = new KTimeComboBox();
KTimeComboBox::Options options = KTimeComboBox::EditTime | KTimeComboBox::SelectTime;
QCOMPARE(m_combo->options(), options);
options = KTimeComboBox::EditTime | KTimeComboBox::WarnOnInvalid;
m_combo->setOptions(options);
QCOMPARE(m_combo->options(), options);
delete m_combo;
}
void KTimeComboBoxTest::testDisplayFormat()
{
m_combo = new KTimeComboBox();
QLocale::FormatType format = QLocale::ShortFormat;
QCOMPARE(m_combo->displayFormat(), format);
format = QLocale::NarrowFormat;
m_combo->setDisplayFormat(format);
QCOMPARE(m_combo->displayFormat(), format);
delete m_combo;
}
diff --git a/src/fonthelpers_p.h b/src/fonthelpers_p.h
index 0a1aa13..7782ef4 100644
--- a/src/fonthelpers_p.h
+++ b/src/fonthelpers_p.h
@@ -1,68 +1,68 @@
/*
Requires the Qt widget libraries, available at no cost at
http://www.troll.no
Copyright (C) 2008 Chusslove Illich
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef FONTHELPERS_P_H
#define FONTHELPERS_P_H
// i18n-related helpers for fonts, common to KFont* widgets.
#include
#include
#include
/**
* @internal
*
* Split the compound raw font name into family and foundry.
*
* @param name the raw font name reported by Qt
* @param family the storage for family name
* @param foundry the storage for foundry name
*/
void splitFontString(const QString &name,
- QString *family, QString *foundry = NULL);
+ QString *family, QString *foundry = nullptr);
/**
* @internal
*
* Translate the font name for the user.
* Primarily for generic fonts like Serif, Sans-Serif, etc.
*
* @param name the raw font name reported by Qt
* @return translated font name
*/
QString translateFontName(const QString &name);
/**
* @internal
*
* Compose locale-aware sorted list of translated font names,
* with generic fonts handled in a special way.
* The mapping of translated to raw names can be reported too if required.
*
* @param names raw font names as reported by Qt
* @param trToRawNames storage for mapping of translated to raw names
* @return sorted list of translated font names
*/
QStringList translateFontNameList(const QStringList &names,
- QHash *trToRawNames = NULL);
+ QHash *trToRawNames = nullptr);
# endif
diff --git a/src/kacceleratormanager.cpp b/src/kacceleratormanager.cpp
index 0579d46..9a396ba 100644
--- a/src/kacceleratormanager.cpp
+++ b/src/kacceleratormanager.cpp
@@ -1,834 +1,834 @@
/* This file is part of the KDE project
Copyright (C) 2002 Matthias Hölzer-Klüpfel
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "kacceleratormanager.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "kacceleratormanager_p.h"
#include "loggingcategory.h"
/*********************************************************************
class Item - helper class containing widget information
This class stores information about the widgets the need accelerators,
as well as about their relationship.
*********************************************************************/
bool KAcceleratorManagerPrivate::programmers_mode = false;
QString KAcceleratorManagerPrivate::changed_string;
QString KAcceleratorManagerPrivate::added_string;
QString KAcceleratorManagerPrivate::removed_string;
QMap KAcceleratorManagerPrivate::ignored_widgets;
QStringList KAcceleratorManagerPrivate::standardNames;
void KAcceleratorManagerPrivate::addStandardActionNames(const QStringList &list)
{
standardNames.append(list);
}
bool KAcceleratorManagerPrivate::standardName(const QString &str)
{
return standardNames.contains(str);
}
KAcceleratorManagerPrivate::Item::~Item()
{
if (m_children)
while (!m_children->isEmpty()) {
delete m_children->takeFirst();
}
delete m_children;
}
void KAcceleratorManagerPrivate::Item::addChild(Item *item)
{
if (!m_children) {
m_children = new ItemList;
}
m_children->append(item);
}
void KAcceleratorManagerPrivate::manage(QWidget *widget)
{
if (!widget) {
qCDebug(KWidgetsAddonsLog) << "null pointer given to manage";
return;
}
if (KAcceleratorManagerPrivate::ignored_widgets.contains(widget)) {
return;
}
if (qobject_cast(widget)) {
// create a popup accel manager that can deal with dynamic menus
KPopupAccelManager::manage(static_cast(widget));
return;
}
Item *root = new Item;
manageWidget(widget, root);
QString used;
calculateAccelerators(root, used);
delete root;
}
void KAcceleratorManagerPrivate::calculateAccelerators(Item *item, QString &used)
{
if (!item->m_children) {
return;
}
// collect the contents
KAccelStringList contents;
Q_FOREACH (Item *it, *item->m_children) {
contents << it->m_content;
}
// find the right accelerators
KAccelManagerAlgorithm::findAccelerators(contents, used);
// write them back into the widgets
int cnt = -1;
Q_FOREACH (Item *it, *item->m_children) {
cnt++;
QDockWidget *dock = qobject_cast(it->m_widget);
if (dock) {
if (checkChange(contents[cnt])) {
dock->setWindowTitle(contents[cnt].accelerated());
}
continue;
}
QTabBar *tabBar = qobject_cast(it->m_widget);
if (tabBar) {
if (checkChange(contents[cnt])) {
tabBar->setTabText(it->m_index, contents[cnt].accelerated());
}
continue;
}
QMenuBar *menuBar = qobject_cast(it->m_widget);
if (menuBar) {
if (it->m_index >= 0) {
QAction *maction = menuBar->actions()[it->m_index];
if (maction) {
checkChange(contents[cnt]);
maction->setText(contents[cnt].accelerated());
}
continue;
}
}
// we possibly reserved an accel, but we won't set it as it looks silly
QGroupBox *groupBox = qobject_cast(it->m_widget);
if (groupBox && !groupBox->isCheckable()) {
continue;
}
int tprop = it->m_widget->metaObject()->indexOfProperty("text");
if (tprop != -1) {
if (checkChange(contents[cnt])) {
it->m_widget->setProperty("text", contents[cnt].accelerated());
}
} else {
tprop = it->m_widget->metaObject()->indexOfProperty("title");
if (tprop != -1 && checkChange(contents[cnt])) {
it->m_widget->setProperty("title", contents[cnt].accelerated());
}
}
}
// calculate the accelerators for the children
Q_FOREACH (Item *it, *item->m_children) {
if (it->m_widget && it->m_widget->isVisibleTo(item->m_widget)) {
calculateAccelerators(it, used);
}
}
}
void KAcceleratorManagerPrivate::traverseChildren(QWidget *widget, Item *item)
{
QList childList = widget->findChildren();
Q_FOREACH (QWidget *w, childList) {
// Ignore unless we have the direct parent
if (qobject_cast(w->parent()) != widget) {
continue;
}
- if (!w->isVisibleTo(widget) || (w->isTopLevel() && qobject_cast(w) == NULL)) {
+ if (!w->isVisibleTo(widget) || (w->isTopLevel() && qobject_cast(w) == nullptr)) {
continue;
}
if (KAcceleratorManagerPrivate::ignored_widgets.contains(w)) {
continue;
}
manageWidget(w, item);
}
}
void KAcceleratorManagerPrivate::manageWidget(QWidget *w, Item *item)
{
// first treat the special cases
QTabBar *tabBar = qobject_cast(w);
if (tabBar) {
manageTabBar(tabBar, item);
return;
}
QStackedWidget *wds = qobject_cast(w);
if (wds) {
QWidgetStackAccelManager::manage(wds);
// return;
}
QDockWidget *dock = qobject_cast(w);
if (dock) {
//QWidgetStackAccelManager::manage( wds );
manageDockWidget(dock, item);
}
QMenu *popupMenu = qobject_cast(w);
if (popupMenu) {
// create a popup accel manager that can deal with dynamic menus
KPopupAccelManager::manage(popupMenu);
return;
}
QStackedWidget *wdst = qobject_cast(w);
if (wdst) {
QWidgetStackAccelManager::manage(wdst);
// return;
}
QMenuBar *menuBar = qobject_cast(w);
if (menuBar) {
manageMenuBar(menuBar, item);
return;
}
if (qobject_cast(w) || qobject_cast(w) ||
w->inherits("Q3TextEdit") ||
qobject_cast(w) ||
qobject_cast(w) || w->inherits("KMultiTabBar") ||
w->inherits("qdesigner_internal::TextPropertyEditor")) {
return;
}
if (w->inherits("KUrlRequester")) {
traverseChildren(w, item);
return;
}
// now treat 'ordinary' widgets
QLabel *label = qobject_cast(w);
if (label) {
if (!label->buddy()) {
return;
} else {
if (label->textFormat() == Qt::RichText ||
(label->textFormat() == Qt::AutoText &&
Qt::mightBeRichText(label->text()))) {
return;
}
}
}
if (w->focusPolicy() != Qt::NoFocus || label || qobject_cast(w) || qobject_cast(w)) {
QString content;
QVariant variant;
int tprop = w->metaObject()->indexOfProperty("text");
if (tprop != -1) {
QMetaProperty p = w->metaObject()->property(tprop);
if (p.isValid() && p.isWritable()) {
variant = p.read(w);
} else {
tprop = -1;
}
}
if (tprop == -1) {
tprop = w->metaObject()->indexOfProperty("title");
if (tprop != -1) {
QMetaProperty p = w->metaObject()->property(tprop);
if (p.isValid() && p.isWritable()) {
variant = p.read(w);
}
}
}
if (variant.isValid()) {
content = variant.toString();
}
if (!content.isEmpty()) {
Item *i = new Item;
i->m_widget = w;
// put some more weight on the usual action elements
int weight = KAccelManagerAlgorithm::DEFAULT_WEIGHT;
if (qobject_cast(w) || qobject_cast(w) || qobject_cast(w) || qobject_cast(w)) {
weight = KAccelManagerAlgorithm::ACTION_ELEMENT_WEIGHT;
}
// don't put weight on non-checkable group boxes,
// as usually the contents are more important
QGroupBox *groupBox = qobject_cast(w);
if (groupBox) {
if (groupBox->isCheckable()) {
weight = KAccelManagerAlgorithm::CHECKABLE_GROUP_BOX_WEIGHT;
} else {
weight = KAccelManagerAlgorithm::GROUP_BOX_WEIGHT;
}
}
i->m_content = KAccelString(content, weight);
item->addChild(i);
}
}
traverseChildren(w, item);
}
void KAcceleratorManagerPrivate::manageTabBar(QTabBar *bar, Item *item)
{
// ignore QTabBar for QDockWidgets, because QDockWidget on its title change
// also updates its tabbar entry, so on the next run of KCheckAccelerators
// this looks like a conflict and triggers a new reset of the shortcuts -> endless loop
QWidget *parentWidget = bar->parentWidget();
if (parentWidget) {
QMainWindow *mainWindow = qobject_cast(parentWidget);
// TODO: find better hints that this is a QTabBar for QDockWidgets
if (mainWindow) { // && (mainWindow->layout()->indexOf(bar) != -1)) QMainWindowLayout lacks proper support
return;
}
}
for (int i = 0; i < bar->count(); i++) {
QString content = bar->tabText(i);
if (content.isEmpty()) {
continue;
}
Item *it = new Item;
item->addChild(it);
it->m_widget = bar;
it->m_index = i;
it->m_content = KAccelString(content);
}
}
void KAcceleratorManagerPrivate::manageDockWidget(QDockWidget *dock, Item *item)
{
// As of Qt 4.4.3 setting a shortcut to a QDockWidget has no effect,
// because a QDockWidget does not grab it, even while displaying an underscore
// in the title for the given shortcut letter.
// Still it is useful to set the shortcut, because if QDockWidgets are tabbed,
// the tab automatically gets the same text as the QDockWidget title, including the shortcut.
// And for the QTabBar the shortcut does work, it gets grabbed as usual.
// Having the QDockWidget without a shortcut and resetting the tab text with a title including
// the shortcut does not work, the tab text is instantly reverted to the QDockWidget title
// (see also manageTabBar()).
// All in all QDockWidgets and shortcuts are a little broken for now.
QString content = dock->windowTitle();
if (content.isEmpty()) {
return;
}
Item *it = new Item;
item->addChild(it);
it->m_widget = dock;
it->m_content = KAccelString(content, KAccelManagerAlgorithm::STANDARD_ACCEL);
}
void KAcceleratorManagerPrivate::manageMenuBar(QMenuBar *mbar, Item *item)
{
QAction *maction;
QString s;
for (int i = 0; i < mbar->actions().count(); ++i) {
maction = mbar->actions()[i];
if (!maction) {
continue;
}
// nothing to do for separators
if (maction->isSeparator()) {
continue;
}
s = maction->text();
if (!s.isEmpty()) {
Item *it = new Item;
item->addChild(it);
it->m_content =
KAccelString(s,
// menu titles are important, so raise the weight
KAccelManagerAlgorithm::MENU_TITLE_WEIGHT);
it->m_widget = mbar;
it->m_index = i;
}
// have a look at the popup as well, if present
if (maction->menu()) {
KPopupAccelManager::manage(maction->menu());
}
}
}
/*********************************************************************
class KAcceleratorManager - main entry point
This class is just here to provide a clean public API...
*********************************************************************/
void KAcceleratorManager::manage(QWidget *widget, bool programmers_mode)
{
KAcceleratorManagerPrivate::changed_string.clear();
KAcceleratorManagerPrivate::added_string.clear();
KAcceleratorManagerPrivate::removed_string.clear();
KAcceleratorManagerPrivate::programmers_mode = programmers_mode;
KAcceleratorManagerPrivate::manage(widget);
}
void KAcceleratorManager::last_manage(QString &added, QString &changed, QString &removed)
{
added = KAcceleratorManagerPrivate::added_string;
changed = KAcceleratorManagerPrivate::changed_string;
removed = KAcceleratorManagerPrivate::removed_string;
}
/*********************************************************************
class KAccelString - a string with weighted characters
*********************************************************************/
KAccelString::KAccelString(const QString &input, int initialWeight)
: m_pureText(input), m_weight()
{
m_orig_accel = m_pureText.indexOf(QStringLiteral("(!)&"));
if (m_orig_accel != -1) {
m_pureText.remove(m_orig_accel, 4);
}
m_orig_accel = m_pureText.indexOf(QStringLiteral("(&&)"));
if (m_orig_accel != -1) {
m_pureText.replace(m_orig_accel, 4, QStringLiteral("&"));
}
m_origText = m_pureText;
if (m_pureText.contains(QLatin1Char('\t'))) {
m_pureText = m_pureText.left(m_pureText.indexOf(QLatin1Char('\t')));
}
m_orig_accel = m_accel = stripAccelerator(m_pureText);
if (initialWeight == -1) {
initialWeight = KAccelManagerAlgorithm::DEFAULT_WEIGHT;
}
calculateWeights(initialWeight);
// dump();
}
QString KAccelString::accelerated() const
{
QString result = m_origText;
if (result.isEmpty()) {
return result;
}
if (KAcceleratorManagerPrivate::programmers_mode) {
if (m_accel != m_orig_accel) {
int oa = m_orig_accel;
if (m_accel >= 0) {
result.insert(m_accel, QStringLiteral("(!)&"));
if (m_accel < m_orig_accel) {
oa += 4;
}
}
if (m_orig_accel >= 0) {
result.replace(oa, 1, QStringLiteral("(&&)"));
}
}
} else {
if (m_accel >= 0 && m_orig_accel != m_accel) {
if (m_orig_accel != -1) {
result.remove(m_orig_accel, 1);
}
result.insert(m_accel, QStringLiteral("&"));
}
}
return result;
}
QChar KAccelString::accelerator() const
{
if ((m_accel < 0) || (m_accel > (int)m_pureText.length())) {
return QChar();
}
return m_pureText[m_accel].toLower();
}
void KAccelString::calculateWeights(int initialWeight)
{
m_weight.resize(m_pureText.length());
int pos = 0;
bool start_character = true;
while (pos < m_pureText.length()) {
QChar c = m_pureText[pos];
int weight = initialWeight + 1;
// add special weight to first character
if (pos == 0) {
weight += KAccelManagerAlgorithm::FIRST_CHARACTER_EXTRA_WEIGHT;
}
// add weight to word beginnings
if (start_character) {
weight += KAccelManagerAlgorithm::WORD_BEGINNING_EXTRA_WEIGHT;
start_character = false;
}
// add decreasing weight to left characters
if (pos < 50) {
weight += (50 - pos);
}
// try to preserve the wanted accelarators
if ((int)pos == accel()) {
weight += KAccelManagerAlgorithm::WANTED_ACCEL_EXTRA_WEIGHT;
// qCDebug(KWidgetsAddonsLog) << "wanted " << m_pureText << " " << KAcceleratorManagerPrivate::standardName(m_origText);
if (KAcceleratorManagerPrivate::standardName(m_origText)) {
weight += KAccelManagerAlgorithm::STANDARD_ACCEL;
}
}
// skip non typeable characters
if (!c.isLetterOrNumber()) {
weight = 0;
start_character = true;
}
m_weight[pos] = weight;
++pos;
}
}
int KAccelString::stripAccelerator(QString &text)
{
// Note: this code is derived from QAccel::shortcutKey
int p = 0;
while (p >= 0) {
p = text.indexOf(QLatin1Char('&'), p) + 1;
if (p <= 0 || p >= (int)text.length()) {
break;
}
if (text[p] != QLatin1Char('&')) {
QChar c = text[p];
if (c.isPrint()) {
text.remove(p - 1, 1);
return p - 1;
}
}
p++;
}
return -1;
}
int KAccelString::maxWeight(int &index, const QString &used) const
{
int max = 0;
index = -1;
for (int pos = 0; pos < m_pureText.length(); ++pos)
if (used.indexOf(m_pureText[pos], 0, Qt::CaseInsensitive) == -1 && m_pureText[pos].toLatin1() != 0)
if (m_weight[pos] > max) {
max = m_weight[pos];
index = pos;
}
return max;
}
void KAccelString::dump()
{
QString s;
for (int i = 0; i < m_weight.count(); ++i) {
s += QStringLiteral("%1(%2) ").arg(pure()[i]).arg(m_weight[i]);
}
qCDebug(KWidgetsAddonsLog) << "s " << s;
}
/*********************************************************************
findAccelerators - the algorithm determining the new accelerators
The algorithm is very crude:
* each character in each widget text is assigned a weight
* the character with the highest weight over all is picked
* that widget is removed from the list
* the weights are recalculated
* the process is repeated until no more accelerators can be found
The algorithm has some advantages:
* it favors 'nice' accelerators (first characters in a word, etc.)
* it is quite fast, O(N²)
* it is easy to understand :-)
The disadvantages:
* it does not try to find as many accelerators as possible
TODO:
* The result is always correct, but not necessarily optimal. Perhaps
it would be a good idea to add another algorithm with higher complexity
that gets used when this one fails, i.e. leaves widgets without
accelerators.
* The weights probably need some tweaking so they make more sense.
*********************************************************************/
void KAccelManagerAlgorithm::findAccelerators(KAccelStringList &result, QString &used)
{
KAccelStringList accel_strings = result;
// initially remove all accelerators
for (KAccelStringList::Iterator it = result.begin(); it != result.end(); ++it) {
(*it).setAccel(-1);
}
// pick the highest bids
for (int cnt = 0; cnt < accel_strings.count(); ++cnt) {
int max = 0, index = -1, accel = -1;
// find maximum weight
for (int i = 0; i < accel_strings.count(); ++i) {
int a;
int m = accel_strings[i].maxWeight(a, used);
if (m > max) {
max = m;
index = i;
accel = a;
}
}
// stop if no more accelerators can be found
if (index < 0) {
return;
}
// insert the accelerator
if (accel >= 0) {
result[index].setAccel(accel);
used.append(result[index].accelerator());
}
// make sure we don't visit this one again
accel_strings[index] = KAccelString();
}
}
/*********************************************************************
class KPopupAccelManager - managing QPopupMenu widgets dynamically
*********************************************************************/
KPopupAccelManager::KPopupAccelManager(QMenu *popup)
: QObject(popup), m_popup(popup), m_count(-1)
{
aboutToShow(); // do one check and then connect to show
connect(popup, &QMenu::aboutToShow, this, &KPopupAccelManager::aboutToShow);
}
void KPopupAccelManager::aboutToShow()
{
// Note: we try to be smart and avoid recalculating the accelerators
// whenever possible. Unfortunately, there is no way to know if an
// item has been added or removed, so we can not do much more than
// to compare the items each time the menu is shown :-(
if (m_count != (int)m_popup->actions().count()) {
findMenuEntries(m_entries);
calculateAccelerators();
m_count = m_popup->actions().count();
} else {
KAccelStringList entries;
findMenuEntries(entries);
if (entries != m_entries) {
m_entries = entries;
calculateAccelerators();
}
}
}
void KPopupAccelManager::calculateAccelerators()
{
// find the new accelerators
QString used;
KAccelManagerAlgorithm::findAccelerators(m_entries, used);
// change the menu entries
setMenuEntries(m_entries);
}
void KPopupAccelManager::findMenuEntries(KAccelStringList &list)
{
QString s;
list.clear();
// read out the menu entries
Q_FOREACH (QAction *maction, m_popup->actions()) {
if (maction->isSeparator()) {
continue;
}
s = maction->text();
// in full menus, look at entries with global accelerators last
int weight = 50;
if (s.contains(QLatin1Char('\t'))) {
weight = 0;
}
list.append(KAccelString(s, weight));
// have a look at the popup as well, if present
if (maction->menu()) {
KPopupAccelManager::manage(maction->menu());
}
}
}
void KPopupAccelManager::setMenuEntries(const KAccelStringList &list)
{
uint cnt = 0;
Q_FOREACH (QAction *maction, m_popup->actions()) {
if (maction->isSeparator()) {
continue;
}
if (KAcceleratorManagerPrivate::checkChange(list[cnt])) {
maction->setText(list[cnt].accelerated());
}
cnt++;
}
}
void KPopupAccelManager::manage(QMenu *popup)
{
// don't add more than one manager to a popup
- if (popup->findChild(QString()) == 0) {
+ if (popup->findChild(QString()) == nullptr) {
new KPopupAccelManager(popup);
}
}
void QWidgetStackAccelManager::manage(QStackedWidget *stack)
{
- if (stack->findChild(QString()) == 0) {
+ if (stack->findChild(QString()) == nullptr) {
new QWidgetStackAccelManager(stack);
}
}
QWidgetStackAccelManager::QWidgetStackAccelManager(QStackedWidget *stack)
: QObject(stack), m_stack(stack)
{
currentChanged(stack->currentIndex()); // do one check and then connect to show
connect(stack, &QStackedWidget::currentChanged, this, &QWidgetStackAccelManager::currentChanged);
}
bool QWidgetStackAccelManager::eventFilter(QObject *watched, QEvent *e)
{
if (e->type() == QEvent::Show && qApp->activeWindow()) {
KAcceleratorManager::manage(qApp->activeWindow());
watched->removeEventFilter(this);
}
return false;
}
void QWidgetStackAccelManager::currentChanged(int child)
{
if (child < 0 || child >= static_cast(parent())->count()) {
// NOTE: QStackedWidget emits currentChanged(-1) when it is emptied
return;
}
static_cast(parent())->widget(child)->installEventFilter(this);
}
void KAcceleratorManager::setNoAccel(QWidget *widget)
{
KAcceleratorManagerPrivate::ignored_widgets[widget] = 1;
}
void KAcceleratorManager::addStandardActionNames(const QStringList &names)
{
KAcceleratorManagerPrivate::addStandardActionNames(names);
}
#include "moc_kacceleratormanager_p.cpp"
diff --git a/src/kacceleratormanager_p.h b/src/kacceleratormanager_p.h
index 3d98d61..9a1eb4f 100644
--- a/src/kacceleratormanager_p.h
+++ b/src/kacceleratormanager_p.h
@@ -1,274 +1,274 @@
/* This file is part of the KDE project
Copyright (C) 2002 Matthias H�zer-Klpfel
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef KACCELERATORMANAGER_PRIVATE_H
#define KACCELERATORMANAGER_PRIVATE_H
#include
#include
#include
class QStackedWidget;
class QMenuBar;
class QTabBar;
class QDockWidget;
/**
* A string class handling accelerators.
*
* This class contains a string and knowledge about accelerators.
* It keeps a list weights, telling how valuable each character
* would be as an accelerator.
*
* @author Matthias H�zer-Klpfel
*/
class KAccelString
{
public:
KAccelString() : m_pureText(), m_accel(-1) {}
explicit KAccelString(const QString &input, int initalWeight = -1);
void calculateWeights(int initialWeight);
const QString &pure() const
{
return m_pureText;
}
QString accelerated() const;
int accel() const
{
return m_accel;
}
void setAccel(int accel)
{
m_accel = accel;
}
int originalAccel() const
{
return m_orig_accel;
}
QString originalText() const
{
return m_origText;
}
QChar accelerator() const;
int maxWeight(int &index, const QString &used) const;
bool operator == (const KAccelString &c) const
{
return m_pureText == c.m_pureText && m_accel == c.m_accel && m_orig_accel == c.m_orig_accel;
}
private:
int stripAccelerator(QString &input);
void dump();
QString m_pureText, m_origText;
int m_accel, m_orig_accel;
QVector m_weight;
};
typedef QList KAccelStringList;
/**
* This class encapsulates the algorithm finding the 'best'
* distribution of accelerators in a hierarchy of widgets.
*
* @author Matthias H�zer-Klpfel
*/
class KAccelManagerAlgorithm
{
public:
enum {
// Default control weight
DEFAULT_WEIGHT = 50,
// Additional weight for first character in string
FIRST_CHARACTER_EXTRA_WEIGHT = 50,
// Additional weight for the beginning of a word
WORD_BEGINNING_EXTRA_WEIGHT = 50,
// Additional weight for the dialog buttons (large, we basically never want these reassigned)
DIALOG_BUTTON_EXTRA_WEIGHT = 300,
// Additional weight for a 'wanted' accelerator
WANTED_ACCEL_EXTRA_WEIGHT = 150,
// Default weight for an 'action' widget (ie, pushbuttons)
ACTION_ELEMENT_WEIGHT = 50,
// Default weight for group boxes (lowest priority)
GROUP_BOX_WEIGHT = -2000,
// Default weight for checkable group boxes (low priority)
CHECKABLE_GROUP_BOX_WEIGHT = 20,
// Default weight for menu titles
MENU_TITLE_WEIGHT = 250,
// Additional weight for KDE standard accelerators
STANDARD_ACCEL = 300
};
static void findAccelerators(KAccelStringList &result, QString &used);
};
/**
* This class manages a popup menu. It will notice if entries have been
* added or changed, and will recalculate the accelerators accordingly.
*
* This is necessary for dynamic menus like for example in kicker.
*
* @author Matthias H�zer-Klpfel
*/
class KPopupAccelManager : public QObject
{
Q_OBJECT
public:
static void manage(QMenu *popup);
protected:
KPopupAccelManager(QMenu *popup);
private Q_SLOTS:
void aboutToShow();
private:
void calculateAccelerators();
void findMenuEntries(KAccelStringList &list);
void setMenuEntries(const KAccelStringList &list);
QMenu *m_popup;
KAccelStringList m_entries;
int m_count;
};
class QWidgetStackAccelManager : public QObject
{
Q_OBJECT
public:
static void manage(QStackedWidget *popup);
protected:
QWidgetStackAccelManager(QStackedWidget *popup);
private Q_SLOTS:
void currentChanged(int child);
bool eventFilter(QObject *watched, QEvent *e) Q_DECL_OVERRIDE;
private:
void calculateAccelerators();
QStackedWidget *m_stack;
KAccelStringList m_entries;
};
/*********************************************************************
class KAcceleratorManagerPrivate - internal helper class
This class does all the work to find accelerators for a hierarchy of
widgets.
*********************************************************************/
class KAcceleratorManagerPrivate
{
public:
static void manage(QWidget *widget);
static bool programmers_mode;
static void addStandardActionNames(const QStringList &strList);
static bool standardName(const QString &str);
static bool checkChange(const KAccelString &as)
{
QString t2 = as.accelerated();
QString t1 = as.originalText();
if (t1 != t2) {
if (as.accel() == -1) {
removed_string += QLatin1String("") + t1.toHtmlEscaped() + QLatin1String(" |
");
} else if (as.originalAccel() == -1) {
added_string += QLatin1String("") + t2.toHtmlEscaped() + QLatin1String(" |
");
} else {
changed_string += QLatin1String("") + t1.toHtmlEscaped() + QLatin1String(" | ");
changed_string += QLatin1String("") + t2.toHtmlEscaped() + QLatin1String(" |
");
}
return true;
}
return false;
}
static QString changed_string;
static QString added_string;
static QString removed_string;
static QMap ignored_widgets;
static QStringList standardNames;
private:
class Item;
public:
typedef QList- ItemList;
private:
static void traverseChildren(QWidget *widget, Item *item);
static void manageWidget(QWidget *widget, Item *item);
static void manageMenuBar(QMenuBar *mbar, Item *item);
static void manageTabBar(QTabBar *bar, Item *item);
static void manageDockWidget(QDockWidget *dock, Item *item);
static void calculateAccelerators(Item *item, QString &used);
class Item
{
public:
- Item() : m_widget(0), m_children(0), m_index(-1) {}
+ Item() : m_widget(nullptr), m_children(nullptr), m_index(-1) {}
~Item();
void addChild(Item *item);
QWidget *m_widget;
KAccelString m_content;
ItemList *m_children;
int m_index;
};
};
#endif // KACCELERATORMANAGER_PRIVATE_H
diff --git a/src/kactionselector.h b/src/kactionselector.h
index 41b7061..c0c4510 100644
--- a/src/kactionselector.h
+++ b/src/kactionselector.h
@@ -1,354 +1,354 @@
/* This file is part of the KDE project
Copyright (C) 2002 Anders Lund
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef _KACTION_SELECTOR_H_
#define _KACTION_SELECTOR_H_
#include
#include
class QListWidget;
class QListWidgetItem;
class QKeyEvent;
class QEvent;
class QIcon;
class KActionSelectorPrivate;
/**
@short A widget for selecting and arranging actions/objects
This widget allows the user to select from a set of objects and arrange
the order of the selected ones using two list boxes labeled "Available"
and "Used" with horizontal arrows in between to move selected objects between
the two, and vertical arrows on the right to arrange the order of the selected
objects.
The widget moves objects to the other listbox when doubleclicked if
the property moveOnDoubleClick is set to true (default). See moveOnDoubleClick()
and setMoveOnDoubleClick().
The user control the widget using the keyboard if enabled (default),
see keyboardEnabled.
Note that this may conflict with keyboard selection in the selected list box,
if you set that to anything else than QListWidget::Single (which is the default).
To use it, simply construct an instance and then add items to the two listboxes,
available through lbAvailable() and lbSelected(). Whenever you want, you can retrieve
the selected options using QListWidget methods on lbSelected().
This way, you can use your own QListWidgetItem class, allowing you to easily
store object data in those.
When an item is moved to a listbox, it is placed below the current item
of that listbox.
Standard arrow icons are used, but you can use icons of your own choice if desired,
see setButtonIcon(). It is also possible to set tooltips and whatsthis help
for the buttons. See setButtonTooltip() and setButtonWhatsThis().
To set whatsthis or tooltips for the listboxes, access them through
availableListWidget() and selectedListWidget().
All the moving buttons are automatically set enabled as expected.
Signals are sent each time an item is moved, allowing you to follow the
users actions if you need to. See addedToSelection(), removedFromSelection(),
movedUp() and movedDown()
\image html kactionselector.png "KDE Action Selector"
@author Anders Lund
*/
class KWIDGETSADDONS_EXPORT KActionSelector : public QWidget
{
Q_OBJECT
Q_PROPERTY(bool moveOnDoubleClick READ moveOnDoubleClick WRITE setMoveOnDoubleClick)
Q_PROPERTY(bool keyboardEnabled READ keyboardEnabled WRITE setKeyboardEnabled)
Q_PROPERTY(QString availableLabel READ availableLabel WRITE setAvailableLabel)
Q_PROPERTY(QString selectedLabel READ selectedLabel WRITE setSelectedLabel)
Q_PROPERTY(InsertionPolicy availableInsertionPolicy READ availableInsertionPolicy WRITE setAvailableInsertionPolicy)
Q_PROPERTY(InsertionPolicy selectedInsertionPolicy READ selectedInsertionPolicy WRITE setSelectedInsertionPolicy)
Q_PROPERTY(bool showUpDownButtons READ showUpDownButtons WRITE setShowUpDownButtons)
public:
- explicit KActionSelector(QWidget *parent = 0);
+ explicit KActionSelector(QWidget *parent = nullptr);
~KActionSelector();
/**
@return The QListWidget holding the available actions
*/
QListWidget *availableListWidget() const;
/**
@return The QListWidget holding the selected actions
*/
QListWidget *selectedListWidget() const;
/**
This enum identifies the moving buttons
*/
enum MoveButton {
ButtonAdd,
ButtonRemove,
ButtonUp,
ButtonDown
};
Q_ENUM(MoveButton)
/**
This enum defines policies for where to insert moved items in a listbox.
The following policies are currently defined:
@li BelowCurrent - The item is inserted below the listbox'
currentItem() or at the end if there is no current item.
@li Sorted - The listbox is sort()ed after one or more items are inserted.
@li AtTop - The item is inserted at index 0 in the listbox.
@li AtBottom - The item is inserted at the end of the listbox.
@sa availableInsertionPolicy(), setAvailableInsertionPolicy(),
selectedInsertionPolicy(), setSelectedInsertionPolicy().
*/
enum InsertionPolicy {
BelowCurrent,
Sorted,
AtTop,
AtBottom
};
Q_ENUM(InsertionPolicy)
/**
@return Whether moveOnDoubleClcik is enabled.
If enabled, an item in any listbox will be moved to the other one whenever
double-clicked.
This feature is enabled by default.
@sa setMoveOnDoubleClick()
*/
bool moveOnDoubleClick() const;
/**
Sets moveOnDoubleClick to @p enable
@sa moveOnDoubleClick()
*/
void setMoveOnDoubleClick(bool enable);
/**
@return Whether keyboard control is enabled.
When Keyboard control is enabled, the widget will react to
the following keyboard actions:
@li CTRL + Right - simulate clicking the add button
@li CTRL + Left - simulate clicking the remove button
@li CTRL + Up - simulate clicking the up button
@li CTRL + Down - simulate clicking the down button
Additionally, pressing RETURN or ENTER on one of the list boxes
will cause the current item of that listbox to be moved to the other
listbox.
The keyboard actions are enabled by default.
@sa setKeyboardEnabled()
*/
bool keyboardEnabled() const;
/**
Sets the keyboard enabled depending on @p enable.
@sa keyboardEnabled()
*/
void setKeyboardEnabled(bool enable);
/**
@return The text of the label for the available items listbox.
*/
QString availableLabel() const;
/**
Sets the label for the available items listbox to @p text.
Note that this label has the listbox as its @e buddy, so that
if you have a single ampersand in the text, the following character
will become the accelerator to focus the listbox.
*/
void setAvailableLabel(const QString &text);
/**
@return the label of the selected items listbox.
*/
QString selectedLabel() const;
/**
Sets the label for the selected items listbox to @p text.
Note that this label has the listbox as its @e buddy, so that
if you have a single ampersand in the text, the following character
will become the accelerator to focus the listbox.
*/
void setSelectedLabel(const QString &text);
/**
@return The current insertion policy for the available listbox.
The default policy for the available listbox is Sorted.
See also InsertionPolicy, setAvailableInsertionPolicy().
*/
InsertionPolicy availableInsertionPolicy() const;
/**
Sets the insertion policy for the available listbox.
See also InsertionPolicy, availableInsertionPolicy().
*/
void setAvailableInsertionPolicy(InsertionPolicy policy);
/**
@return The current insertion policy for the selected listbox.
The default policy for the selected listbox is BelowCurrent.
See also InsertionPolicy, setSelectedInsertionPolicy().
*/
InsertionPolicy selectedInsertionPolicy() const;
/**
Sets the insertion policy for the selected listbox.
See also InsertionPolicy, selectedInsertionPolicy().
*/
void setSelectedInsertionPolicy(InsertionPolicy policy);
/**
@return whether the Up and Down buttons should be displayed.
*/
bool showUpDownButtons() const;
/**
Sets whether the Up and Down buttons should be displayed
according to @p show
*/
void setShowUpDownButtons(bool show);
/**
Sets the pixmap of the button @p button to @p icon.
It calls SmallIconSet(pm) to generate the icon set.
*/
void setButtonIcon(const QString &icon, MoveButton button);
/**
Sets the iconset for button @p button to @p iconset.
You can use this method to set a custom icon set. Either
created by QIconSet, or use the application instance of
KIconLoader (recommended).
*/
void setButtonIconSet(const QIcon &iconset, MoveButton button);
/**
Sets the tooltip for the button @p button to @p tip.
*/
void setButtonTooltip(const QString &tip, MoveButton button);
/**
Sets the whatsthis help for button @p button to @p text.
*/
void setButtonWhatsThis(const QString &text, MoveButton button);
Q_SIGNALS:
/**
Emitted when an item is moved to the "selected" listbox.
*/
void added(QListWidgetItem *item);
/**
Emitted when an item is moved out of the "selected" listbox.
*/
void removed(QListWidgetItem *item);
/**
Emitted when an item is moved upwards in the "selected" listbox.
*/
void movedUp(QListWidgetItem *item);
/**
Emitted when an item is moved downwards in the "selected" listbox.
*/
void movedDown(QListWidgetItem *item);
/**
Emitted when an item is moved to the "selected" listbox.
*/
// void addedToSelection( QListWidgetItem *item );
public Q_SLOTS:
/**
Sets the enabled state of all moving buttons to reflect the current
options.
Be sure to call this if you add or removes items to either listbox after the
widget is shown
*/
void setButtonsEnabled();
protected:
/**
Reimplemented for internal reasons.
*/
void keyPressEvent(QKeyEvent *) Q_DECL_OVERRIDE;
/**
Reimplemented for internal reasons.
*/
bool eventFilter(QObject *, QEvent *) Q_DECL_OVERRIDE;
private:
/**
Move selected item from available box to the selected box
*/
Q_PRIVATE_SLOT(d, void buttonAddClicked())
/**
Move selected item from selected box to available box
*/
Q_PRIVATE_SLOT(d, void buttonRemoveClicked())
/**
Move selected item in selected box upwards
*/
Q_PRIVATE_SLOT(d, void buttonUpClicked())
/**
Move seleted item in selected box downwards
*/
Q_PRIVATE_SLOT(d, void buttonDownClicked())
/**
Moves the item @p item to the other listbox if moveOnDoubleClick is enabled.
*/
Q_PRIVATE_SLOT(d, void itemDoubleClicked(QListWidgetItem *item))
/**
connected to both list boxes to set the buttons enabled
*/
Q_PRIVATE_SLOT(d, void slotCurrentChanged(QListWidgetItem *))
private:
/** @private
Private data storage
*/
friend class KActionSelectorPrivate;
KActionSelectorPrivate *const d;
Q_DISABLE_COPY(KActionSelector)
};
#endif // _KACTION_SELECTOR_H_
diff --git a/src/kanimatedbutton.cpp b/src/kanimatedbutton.cpp
index 76b8ba7..1ccfe29 100644
--- a/src/kanimatedbutton.cpp
+++ b/src/kanimatedbutton.cpp
@@ -1,203 +1,203 @@
/* This file is part of the KDE libraries
Copyright (C) 2000 Kurt Granroth
Copyright (C) 2006 Hamish Rodda
Copyright (C) 2008 Pino Toscano
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include
#include
#include
#include
#include
#include
#include
class KAnimatedButtonPrivate
{
public:
KAnimatedButtonPrivate(KAnimatedButton *qq)
- : q(qq), movie(0)
+ : q(qq), movie(nullptr)
{
}
void updateIcons();
void updateCurrentIcon();
void _k_movieFrameChanged(int number);
void _k_movieFinished();
void _k_timerUpdate();
KAnimatedButton *q;
QMovie *movie;
int frames;
int current_frame;
QPixmap pixmap;
QTimer timer;
QString icon_path;
QVector framesCache; // We keep copies of each frame so that
// the icon code can properly cache them in QPixmapCache,
// and not fill it up with dead copies
};
KAnimatedButton::KAnimatedButton(QWidget *parent)
: QToolButton(parent), d(new KAnimatedButtonPrivate(this))
{
connect(&d->timer, SIGNAL(timeout()), this, SLOT(_k_timerUpdate()));
}
KAnimatedButton::~KAnimatedButton()
{
d->timer.stop();
qDeleteAll(d->framesCache);
delete d->movie;
delete d;
}
void KAnimatedButton::start()
{
if (d->movie) {
d->movie->start();
} else {
d->current_frame = 0;
d->timer.start(50);
}
}
void KAnimatedButton::stop()
{
if (d->movie) {
d->movie->stop();
d->movie->jumpToFrame(0);
d->_k_movieFrameChanged(0);
} else {
d->current_frame = 0;
d->timer.stop();
d->updateCurrentIcon();
}
}
void KAnimatedButton::setAnimationPath(const QString &path)
{
if (d->icon_path == path) {
return;
}
d->timer.stop();
d->icon_path = path;
d->updateIcons();
}
QString KAnimatedButton::animationPath() const
{
return d->icon_path;
}
void KAnimatedButtonPrivate::_k_timerUpdate()
{
if (!q->isVisible()) {
return;
}
current_frame++;
if (current_frame == frames) {
current_frame = 0;
}
updateCurrentIcon();
}
void KAnimatedButtonPrivate::updateCurrentIcon()
{
if (pixmap.isNull()) {
return;
}
QPixmap *frame = framesCache[current_frame];
if (!frame) {
const int icon_size = qMin(pixmap.width(), pixmap.height());
const int row_size = pixmap.width() / icon_size;
const int row = current_frame / row_size;
const int column = current_frame % row_size;
frame = new QPixmap(icon_size, icon_size);
frame->fill(Qt::transparent);
QPainter p(frame);
p.drawPixmap(QPoint(0, 0), pixmap, QRect(column * icon_size, row * icon_size, icon_size, icon_size));
p.end();
framesCache[current_frame] = frame;
}
q->setIcon(QIcon(*frame));
}
void KAnimatedButtonPrivate::_k_movieFrameChanged(int number)
{
Q_UNUSED(number);
q->setIcon(QIcon(movie->currentPixmap()));
}
void KAnimatedButtonPrivate::_k_movieFinished()
{
// if not running, make it loop
if (movie->state() == QMovie::NotRunning) {
movie->start();
}
}
void KAnimatedButtonPrivate::updateIcons()
{
pixmap = QPixmap();
- QMovie *newMovie = 0;
+ QMovie *newMovie = nullptr;
QImageReader reader(icon_path);
if (QMovie::supportedFormats().contains(reader.format())) {
newMovie = new QMovie(icon_path);
frames = 0;
newMovie->setCacheMode(QMovie::CacheAll);
QObject::connect(newMovie, SIGNAL(frameChanged(int)), q, SLOT(_k_movieFrameChanged(int)));
QObject::connect(newMovie, SIGNAL(finished()), q, SLOT(_k_movieFinished()));
} else {
const QPixmap pix(icon_path);
if (pix.isNull()) {
return;
}
const int icon_size = qMin(pix.width(), pix.height());
if ((pix.height() % icon_size != 0) || (pix.width() % icon_size != 0)) {
return;
}
frames = (pix.height() / icon_size) * (pix.width() / icon_size);
pixmap = pix;
}
current_frame = 0;
qDeleteAll(framesCache);
- framesCache.fill(0);
+ framesCache.fill(nullptr);
framesCache.resize(frames);
delete movie;
movie = newMovie;
if (movie) {
movie->jumpToFrame(0);
_k_movieFrameChanged(0);
} else {
updateCurrentIcon();
}
}
#include "moc_kanimatedbutton.cpp"
diff --git a/src/kanimatedbutton.h b/src/kanimatedbutton.h
index 9d9e0e8..106657f 100644
--- a/src/kanimatedbutton.h
+++ b/src/kanimatedbutton.h
@@ -1,87 +1,87 @@
/* This file is part of the KDE libraries
Copyright (C) 2000 Kurt Granroth
Copyright (C) 2006 Hamish Rodda
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef KANIMATEDBUTTON_H
#define KANIMATEDBUTTON_H
#include
#include
/**
* @short An extended version of QToolButton which can display an animation.
*
* This widget extends QToolButton with the ability to display an animation.
* All you need to do is pass along a path to a file containing an animation,
* it can be anything supported by QMovie, or a picture containing all the
* frames of the animation next to each other (each frame being assumed of
* having the same size).
*
* @author Kurt Granroth
*/
class KWIDGETSADDONS_EXPORT KAnimatedButton : public QToolButton
{
Q_OBJECT
Q_PROPERTY(QString animationPath READ animationPath WRITE setAnimationPath)
public:
/**
* Construct an animated tool button.
*
* @param parent The parent widget
*/
- explicit KAnimatedButton(QWidget *parent = 0);
+ explicit KAnimatedButton(QWidget *parent = nullptr);
/**
* Destructor
*/
virtual ~KAnimatedButton();
/**
* Returns the path used to load the animation
*/
QString animationPath() const;
/**
* Sets the path to the file which contains the animation to load.
*
* @param path The path of the file containing the animation
*/
void setAnimationPath(const QString &path);
public Q_SLOTS:
/**
* Starts the animation from frame 1
*/
void start();
/**
* Stops the animation. This will also reset the widget to frame 1.
*/
void stop();
private:
class KAnimatedButtonPrivate *const d;
Q_PRIVATE_SLOT(d, void _k_movieFrameChanged(int))
Q_PRIVATE_SLOT(d, void _k_movieFinished())
Q_PRIVATE_SLOT(d, void _k_timerUpdate())
Q_DISABLE_COPY(KAnimatedButton)
};
#endif // KANIMATEDBUTTON_H
diff --git a/src/kassistantdialog.h b/src/kassistantdialog.h
index 529f5cd..62f41c2 100644
--- a/src/kassistantdialog.h
+++ b/src/kassistantdialog.h
@@ -1,154 +1,154 @@
/* This file is part of the KDE libraries
Copyright (C) 2006 Olivier Goffart
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef KASSISTANTDIALOG_H
#define KASSISTANTDIALOG_H
#include
#include
/**
* This class provides a framework for assistant dialogs.
*
* An assistant dialog consists of a sequence of pages.
* Its purpose is to guide the user (assist) through a process step by step.
* Assistant dialogs are useful for complex or infrequently occurring tasks
* that people may find difficult to learn or do.
* Sometimes a task requires too many input fields to fit them on a single dialog.
*
* Create and populate dialog pages that inherit from QWidget and add them
* to the assistant dialog using addPage().
*
* The functions next() and back() are virtual and may be reimplemented to
* override the default actions of the next and back buttons.
*
* \image html kassistantdialog.png "KDE Assistant Dialog"
*
* @author Olivier Goffart
*/
class KWIDGETSADDONS_EXPORT KAssistantDialog : public KPageDialog
{
Q_OBJECT
public:
/**
* Construct a new assistant dialog with @p parent as parent.
* @param parent is the parent of the widget.
* @flags the window flags to give to the assistant dialog. The
* default of zero is usually what you want.
*/
- explicit KAssistantDialog(QWidget *parent = 0, Qt::WindowFlags flags = 0);
+ explicit KAssistantDialog(QWidget *parent = nullptr, Qt::WindowFlags flags = nullptr);
virtual ~KAssistantDialog();
/**
* Specify if the content of the page is valid, and if the next button may be enabled on this page.
* By default all pages are valid.
*
* This will disable or enable the next button on the specified page
*
* @param page the page on which the next button will be enabled/disable
* @param enable if true the next button will be enabled, if false it will be disabled
*/
void setValid(KPageWidgetItem *page, bool enable);
/**
* return if a page is valid
* @see setValid
* @param page the page to check the validity of
*/
bool isValid(KPageWidgetItem *page) const;
/**
* Specify whether a page is appropriate.
*
* A page is considered inappropriate if it should not be shown due to
* the contents of other pages making it inappropriate.
*
* A page which is inappropriate will not be shown.
*
* The last page in an assistant dialog should always be appropriate
* @param page the page to set as appropriate
* @param appropriate flag indicating the appropriateness of the page.
* If @p appropriate is true, then @p page is appropriate and will be
* shown in the assistant dialog. If false, @p page will not be shown.
*/
void setAppropriate(KPageWidgetItem *page, bool appropriate);
/**
* Check if a page is appropriate for use in the assistant dialog.
* @param page is the page to check the appropriateness of.
* @return true if @p page is appropriate, false if it is not
*/
bool isAppropriate(KPageWidgetItem *page) const;
/**
* @returns the next button
*/
QPushButton* nextButton() const;
/**
* @returns the finish button
*/
QPushButton* backButton() const;
/**
* @returns the finish button
*/
QPushButton* finishButton() const;
public Q_SLOTS:
/**
* Called when the user clicks the Back button.
*
* This function will show the preceding relevant page in the sequence.
* Do nothing if the current page is the first page in the sequence.
*/
virtual void back();
/**
* Called when the user clicks the Next/Finish button.
*
* This function will show the next relevant page in the sequence.
* If the current page is the last page, it will call accept()
*/
virtual void next();
protected:
/**
* Construct an assistant dialog from a single widget.
* @param widget the widget to construct the dialog with
* @param parent the parent of the assistant dialog
* @flags the window flags to use when creating the widget. The default
* of zero is usually fine.
*
* Calls the KPageDialog(KPageWidget *widget, QWidget *parent, Qt::WindowFlags flags) constructor
*/
- explicit KAssistantDialog(KPageWidget *widget, QWidget *parent = 0, Qt::WindowFlags flags = 0);
+ explicit KAssistantDialog(KPageWidget *widget, QWidget *parent = nullptr, Qt::WindowFlags flags = nullptr);
void showEvent(QShowEvent *event) Q_DECL_OVERRIDE;
private:
class Private;
Private *const d;
Q_PRIVATE_SLOT(d, void _k_slotUpdateButtons())
Q_DISABLE_COPY(KAssistantDialog)
};
#endif
diff --git a/src/kcapacitybar.h b/src/kcapacitybar.h
index 6ebd35e..2e5ed9a 100644
--- a/src/kcapacitybar.h
+++ b/src/kcapacitybar.h
@@ -1,236 +1,236 @@
/*
* This file is part of the KDE project
* Copyright (C) 2008 Rafael Fernández López
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef KCAPACITYBAR_H
#define KCAPACITYBAR_H
#include
#include
class QPaintEvent;
/**
* @brief This widget shows a bar which is filled to show the level of usage of
* a certain device.
*
* This widget represents a bar which goal is to show the level of usage of a
* device. Its look is similar to a progress bar, but different, because this
* widget does not want to give a notion of progress.
*
* @since 4.2
*
* \image html kcapacitybar.png "KDE Capacity Bar"
*
* @author Rafael Fernández López
*/
class KWIDGETSADDONS_EXPORT KCapacityBar
: public QWidget
{
Q_OBJECT
Q_PROPERTY(int value READ value WRITE setValue)
Q_PROPERTY(QString text READ text WRITE setText)
Q_PROPERTY(DrawTextMode drawTextMode READ drawTextMode WRITE setDrawTextMode)
Q_PROPERTY(bool fillFullBlocks READ fillFullBlocks WRITE setFillFullBlocks)
Q_PROPERTY(bool continuous READ continuous WRITE setContinuous)
Q_PROPERTY(int barHeight READ barHeight WRITE setBarHeight)
Q_PROPERTY(Qt::Alignment horizontalTextAlignment READ horizontalTextAlignment
WRITE setHorizontalTextAlignment)
public:
enum DrawTextMode {
DrawTextInline = 0, ///< If any text set, draw it into the capacity bar
DrawTextOutline ///< If any text set, draw it out of the capacity bar
};
Q_ENUM(DrawTextMode)
/**
* Constructs a capacity bar with DrawTextOutline as draw text mode.
* @param parent The parent of the widget.
* @since 5.24
*/
explicit KCapacityBar(QWidget *parent = Q_NULLPTR);
/**
* Capacity bar constructor.
*
* @param drawTextMode If any text set, whether to draw it into the capacity bar
* or not.
* @param parent The parent of the widget.
*/
- explicit KCapacityBar(DrawTextMode drawTextMode, QWidget *parent = 0);
+ explicit KCapacityBar(DrawTextMode drawTextMode, QWidget *parent = nullptr);
~KCapacityBar();
/**
* Capacity bar fill value.
*
* @param value This parameter can take values from 0 to 100.
*
* @note Its value is 0 by default.
*/
void setValue(int value);
/**
* @return The fill value of the capacity bar.
*/
int value() const;
/**
* Sets the text for the capacity bar.
*
* @param text The text that the capacity bar will show.
*
* @note This is an empty string by default.
*/
void setText(const QString &text);
/**
* @return The text that the capacity bar will show.
*/
QString text() const;
/**
* When the capacity bar is non-continuous, sets whether the last block
* shown should be drawn full or can be cut off (depending on the capacity
* bar width, and the value set on it).
*
* @param fillFullBlocks If true, the last block drawn will be fully filled,
* on other case, the last block drawn could be cut off.
*
* @note This method is only relevant if the capacity bar is in
* non-continuous mode.
*
* @note Its value is true by default.
*
* @see setContinuous, continuous
*/
void setFillFullBlocks(bool fillFullBlocks);
/**
* @return Whether the last block shown can be cut off when necessary.
*/
bool fillFullBlocks() const;
/**
* Sets whether the fill of the capacity bar should be continuous or in
* block mode.
*
* @param continuous If true, the fill of the capacity bar is done in a
* continuous way. In other case, the fill is done with
* separated blocks.
*
* @note Its value is true by default.
*/
void setContinuous(bool continuous);
/**
* @return Whether the fill of the capacity bar should be continuous or
* block-based.
*/
bool continuous() const;
/**
* Sets the height (in pixels) of the bar.
*
* @param barHeight The preferred height (in pixels) of the capacity bar.
*
* @note If you set a certain text and the capacity bar is in inline mode,
* the height of the bar will be the maximum of the font height and
* this value.
*
* @note If you set a certain text and the capacity bar is in outline mode,
* the height of the whole capacity bar will be bigger than this
* value. Take in count the height of this widget is got from adding
* the bar height, the font metrics height and a small separator
* between the bar and the outline text.
*
* @note Its value is 12 pixels by default.
*/
void setBarHeight(int barHeight);
/**
* @return The preferred height of the capacity bar.
*/
int barHeight() const;
/**
* If the capacity bar is in outline text mode, draw the text with
* @p textAlignment alignment.
*
* @param textAlignment Sets the horizontal alignment for the text if
* the capacity bar is in outline text mode.
*
* @note If @p textAlignemt contains vertical alignment flags, they will be
* ignored.
*
* @note If the capacity bar is in inline text mode, the text is always
* centered, and both vertical and horizontal flags set through this
* method are ignored.
*
* @note Its value is centered by default.
*/
void setHorizontalTextAlignment(Qt::Alignment textAlignment);
/**
* @return The horizontal alignment for the text that will be drawn.
*/
Qt::Alignment horizontalTextAlignment() const;
/**
* Set the way text is drawn if any is set
*
* @param drawTextMode If any text set, whether to draw it into the capacity bar
* or not.
*/
void setDrawTextMode(DrawTextMode mode);
/**
* The way text is drawn, inside the capacity bar or outside of it
*/
DrawTextMode drawTextMode() const;
/**
* This method allows you to draw the widget, directly, for example on
* item delegates. You only need the painter object and the rect where
* this widget should be drawn.
*/
void drawCapacityBar(QPainter *p, const QRect &rect) const;
// Reimplemented from QWidget
QSize minimumSizeHint() const Q_DECL_OVERRIDE;
protected:
// Reimplemented from QWidget
void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE;
// Reimplemented from QWidget
void changeEvent(QEvent *event) Q_DECL_OVERRIDE;
private:
/**
* @internal
*/
class Private;
Private *const d;
};
#endif
diff --git a/src/kcharselect.cpp b/src/kcharselect.cpp
index d0bc5b3..cee6efc 100644
--- a/src/kcharselect.cpp
+++ b/src/kcharselect.cpp
@@ -1,1100 +1,1100 @@
/* This file is part of the KDE libraries
Copyright (C) 1999 Reginald Stadlbauer
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "kcharselect.h"
#include "kcharselect_p.h"
#include "loggingcategory.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
Q_GLOBAL_STATIC(KCharSelectData, s_data)
class KCharSelectTablePrivate
{
public:
- KCharSelectTablePrivate(KCharSelectTable *q): q(q), model(0)
+ KCharSelectTablePrivate(KCharSelectTable *q): q(q), model(nullptr)
{}
KCharSelectTable *q;
QFont font;
KCharSelectItemModel *model;
QVector chars;
uint chr;
void _k_resizeCells();
void _k_doubleClicked(const QModelIndex &index);
void _k_slotSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected);
};
class KCharSelect::KCharSelectPrivate
{
public:
struct HistoryItem {
uint c;
bool fromSearch;
QString searchString;
};
enum { MaxHistoryItems = 100 };
KCharSelectPrivate(KCharSelect *q)
: q(q)
- , searchLine(0)
+ , searchLine(nullptr)
, searchMode(false)
, historyEnabled(false)
, allPlanesEnabled(false)
, inHistory(0)
- , actionParent(0)
+ , actionParent(nullptr)
{
}
QString tr(const char *str)
{
return KCharSelect::tr(str);
}
KCharSelect *q;
QToolButton *backButton;
QToolButton *forwardButton;
QLineEdit *searchLine;
QFontComboBox *fontCombo;
QSpinBox *fontSizeSpinBox;
QComboBox *sectionCombo;
QComboBox *blockCombo;
KCharSelectTable *charTable;
QTextBrowser *detailBrowser;
bool searchMode; //a search is active
bool historyEnabled;
bool allPlanesEnabled;
int inHistory; //index of current char in history
QList history;
QObject *actionParent;
QString createLinks(QString s);
void historyAdd(uint c, bool fromSearch, const QString &searchString);
void showFromHistory(int index);
void updateBackForwardButtons();
void _k_activateSearchLine();
void _k_back();
void _k_forward();
void _k_fontSelected();
void _k_charSelected(uint c);
void _k_updateCurrentChar(uint c);
void _k_slotUpdateUnicode(uint c);
void _k_sectionSelected(int index);
void _k_blockSelected(int index);
void _k_searchEditChanged();
void _k_search();
void _k_linkClicked(QUrl url);
};
/******************************************************************/
/* Class: KCharSelectTable */
/******************************************************************/
KCharSelectTable::KCharSelectTable(QWidget *parent, const QFont &_font)
: QTableView(parent), d(new KCharSelectTablePrivate(this))
{
d->font = _font;
setTabKeyNavigation(false);
setSelectionMode(QAbstractItemView::SingleSelection);
QPalette _palette;
_palette.setColor(backgroundRole(), palette().color(QPalette::Base));
setPalette(_palette);
verticalHeader()->setVisible(false);
verticalHeader()->setSectionResizeMode(QHeaderView::Custom);
horizontalHeader()->setVisible(false);
horizontalHeader()->setSectionResizeMode(QHeaderView::Custom);
setFocusPolicy(Qt::StrongFocus);
setDragEnabled(true);
setAcceptDrops(true);
setDropIndicatorShown(false);
setDragDropMode(QAbstractItemView::DragDrop);
connect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(_k_doubleClicked(QModelIndex)));
d->_k_resizeCells();
}
KCharSelectTable::~KCharSelectTable()
{
delete d;
}
void KCharSelectTable::setFont(const QFont &_font)
{
QTableView::setFont(_font);
d->font = _font;
if (d->model) {
d->model->setFont(_font);
}
d->_k_resizeCells();
}
uint KCharSelectTable::chr()
{
return d->chr;
}
QFont KCharSelectTable::font() const
{
return d->font;
}
QVector KCharSelectTable::displayedChars() const
{
return d->chars;
}
void KCharSelectTable::setChar(uint c)
{
int pos = d->chars.indexOf(c);
if (pos != -1) {
setCurrentIndex(model()->index(pos / model()->columnCount(), pos % model()->columnCount()));
}
}
void KCharSelectTable::setContents(const QVector &chars)
{
d->chars = chars;
KCharSelectItemModel *m = d->model;
d->model = new KCharSelectItemModel(chars, d->font, this);
setModel(d->model);
d->_k_resizeCells();
QItemSelectionModel *selectionModel = new QItemSelectionModel(d->model);
setSelectionModel(selectionModel);
setSelectionBehavior(QAbstractItemView::SelectItems);
setSelectionMode(QAbstractItemView::SingleSelection);
connect(selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(_k_slotSelectionChanged(QItemSelection,QItemSelection)));
connect(d->model, &KCharSelectItemModel::showCharRequested, this, &KCharSelectTable::showCharRequested);
delete m; // this should hopefully delete aold selection models too, since it is the parent of them (didn't track, if there are setParent calls somewhere. Check that (jowenn)
}
void KCharSelectTable::scrollTo(const QModelIndex &index, ScrollHint hint)
{
// this prevents horizontal scrolling when selecting a character in the last column
if (index.isValid() && index.column() != 0) {
QTableView::scrollTo(d->model->index(index.row(), 0), hint);
} else {
QTableView::scrollTo(index, hint);
}
}
void KCharSelectTablePrivate::_k_slotSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
Q_UNUSED(deselected);
if (!model || selected.indexes().isEmpty()) {
return;
}
QVariant temp = model->data(selected.indexes().at(0), KCharSelectItemModel::CharacterRole);
if (temp.type() != QVariant::UInt) {
return;
}
uint c = temp.toUInt();
chr = c;
emit q->focusItemChanged(c);
}
void KCharSelectTable::resizeEvent(QResizeEvent *e)
{
QTableView::resizeEvent(e);
if (e->size().width() != e->oldSize().width()) {
d->_k_resizeCells();
}
}
void KCharSelectTablePrivate::_k_resizeCells()
{
KCharSelectItemModel *model = static_cast(q->model());
if (!model) return;
const int viewportWidth = q->viewport()->size().width();
QFontMetrics fontMetrics(font);
// Determine the max width of the displayed characters
// fontMetrics.maxWidth() doesn't help because of font fallbacks
// (testcase: Malayalam characters)
int maxCharWidth = 0;
const QVector chars = model->chars();
for (int i = 0; i < chars.size(); ++i) {
uint thisChar = chars.at(i);
if(s_data()->isPrint(thisChar)) {
maxCharWidth = qMax(maxCharWidth, fontMetrics.boundingRect(QString::fromUcs4(&thisChar, 1)).width());
}
}
// Avoid too narrow cells
maxCharWidth = qMax(maxCharWidth, 2 * fontMetrics.xHeight());
maxCharWidth = qMax(maxCharWidth, fontMetrics.height());
// Add the necessary padding, trying to match the delegate
- const int textMargin = q->style()->pixelMetric(QStyle::PM_FocusFrameHMargin, 0, q) + 1;
+ const int textMargin = q->style()->pixelMetric(QStyle::PM_FocusFrameHMargin, nullptr, q) + 1;
maxCharWidth += 2 * textMargin;
const int columns = qMax(1, viewportWidth / maxCharWidth);
model->setColumnCount(columns);
const uint oldChar = q->chr();
const int new_w = viewportWidth / columns;
const int rows = model->rowCount();
q->setUpdatesEnabled(false);
QHeaderView *hHeader = q->horizontalHeader();
const int spaceLeft = viewportWidth - new_w * columns;
for (int i = 0; i <= columns; ++i) {
if (i < spaceLeft) {
hHeader->resizeSection(i, new_w + 1);
} else {
hHeader->resizeSection(i, new_w);
}
}
QHeaderView *vHeader = q->verticalHeader();
#ifdef Q_OS_WIN
int new_h = fontMetrics.lineSpacing() + 1;
#else
int new_h = fontMetrics.xHeight() * 3;
#endif
const int fontHeight = fontMetrics.height();
if (new_h < 5 || new_h < 4 + fontHeight) {
new_h = qMax(5, 4 + fontHeight);
}
for (int i = 0; i < rows; ++i) {
vHeader->resizeSection(i, new_h);
}
q->setUpdatesEnabled(true);
q->setChar(oldChar);
}
void KCharSelectTablePrivate::_k_doubleClicked(const QModelIndex &index)
{
uint c = model->data(index, KCharSelectItemModel::CharacterRole).toUInt();
if (s_data()->isPrint(c)) {
emit q->activated(c);
}
}
void KCharSelectTable::keyPressEvent(QKeyEvent *e)
{
if (d->model) {
switch (e->key()) {
case Qt::Key_Space:
emit activated(QChar::Space);
return;
case Qt::Key_Enter:
case Qt::Key_Return: {
if (!currentIndex().isValid()) {
return;
}
uint c = d->model->data(currentIndex(), KCharSelectItemModel::CharacterRole).toUInt();
if (s_data()->isPrint(c)) {
emit activated(c);
}
return;
}
default:
break;
}
}
QTableView::keyPressEvent(e);
}
/******************************************************************/
/* Class: KCharSelect */
/******************************************************************/
#ifndef KWIDGETSADDONS_NO_DEPRECATED
KCharSelect::KCharSelect(QWidget *parent, const Controls controls)
: QWidget(parent), d(new KCharSelectPrivate(this))
{
- initWidget(controls, NULL);
+ initWidget(controls, nullptr);
}
#endif
KCharSelect::KCharSelect(
QWidget *parent
, QObject *actionParent
, const Controls controls)
: QWidget(parent), d(new KCharSelectPrivate(this))
{
initWidget(controls, actionParent);
}
void attachToActionParent(QAction *action, QObject *actionParent, const QList &shortcuts)
{
if (!action || !actionParent) {
return;
}
action->setParent(actionParent);
if (actionParent->inherits("KActionCollection")) {
QMetaObject::invokeMethod(actionParent, "addAction", Q_ARG(QString, action->objectName()), Q_ARG(QAction *, action));
QMetaObject::invokeMethod(actionParent, "setDefaultShortcuts", Q_ARG(QAction *, action), Q_ARG(QList, shortcuts));
} else {
action->setShortcuts(shortcuts);
}
}
void KCharSelect::initWidget(const Controls controls, QObject *actionParent)
{
d->actionParent = actionParent;
QVBoxLayout *mainLayout = new QVBoxLayout(this);
mainLayout->setMargin(0);
if (SearchLine & controls) {
QHBoxLayout *searchLayout = new QHBoxLayout();
mainLayout->addLayout(searchLayout);
d->searchLine = new QLineEdit(this);
searchLayout->addWidget(d->searchLine);
d->searchLine->setPlaceholderText(tr("Enter a search term or character here"));
d->searchLine->setClearButtonEnabled(true);
d->searchLine->setToolTip(tr("Enter a search term or character here"));
QAction *findAction = new QAction(this);
connect(findAction, SIGNAL(triggered(bool)), this, SLOT(_k_activateSearchLine()));
findAction->setObjectName(QStringLiteral("edit_find"));
findAction->setText(tr("&Find..."));
findAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-find")));
attachToActionParent(findAction, actionParent, QKeySequence::keyBindings(QKeySequence::Find));
connect(d->searchLine, SIGNAL(textChanged(QString)), this, SLOT(_k_searchEditChanged()));
connect(d->searchLine, SIGNAL(returnPressed()), this, SLOT(_k_search()));
}
if ((SearchLine & controls) && ((FontCombo & controls) || (FontSize & controls) || (BlockCombos & controls))) {
QFrame *line = new QFrame(this);
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);
mainLayout->addWidget(line);
}
QHBoxLayout *comboLayout = new QHBoxLayout();
d->backButton = new QToolButton(this);
comboLayout->addWidget(d->backButton);
d->backButton->setEnabled(false);
d->backButton->setText(tr("Previous in History", "Goes to previous character"));
d->backButton->setIcon(QIcon::fromTheme(QStringLiteral("go-previous")));
d->backButton->setToolTip(tr("Previous Character in History"));
d->forwardButton = new QToolButton(this);
comboLayout->addWidget(d->forwardButton);
d->forwardButton->setEnabled(false);
d->forwardButton->setText(tr("Next in History", "Goes to next character"));
d->forwardButton->setIcon(QIcon::fromTheme(QStringLiteral("go-next")));
d->forwardButton->setToolTip(tr("Next Character in History"));
QAction *backAction = new QAction(this);
connect(backAction, &QAction::triggered, d->backButton, &QAbstractButton::animateClick);
backAction->setObjectName(QStringLiteral("go_back"));
backAction->setText(tr("&Back", "go back"));
backAction->setIcon(QIcon::fromTheme(QStringLiteral("go-previous")));
attachToActionParent(backAction, actionParent, QKeySequence::keyBindings(QKeySequence::Back));
QAction *forwardAction = new QAction(this);
connect(forwardAction, &QAction::triggered, d->forwardButton, &QAbstractButton::animateClick);
forwardAction->setObjectName(QStringLiteral("go_forward"));
forwardAction->setText(tr("&Forward", "go forward"));
forwardAction->setIcon(QIcon::fromTheme(QStringLiteral("go-next")));
attachToActionParent(forwardAction, actionParent, QKeySequence::keyBindings(QKeySequence::Forward));
if (QApplication::isRightToLeft()) { // swap the back/forward icons
QIcon tmp = backAction->icon();
backAction->setIcon(forwardAction->icon());
forwardAction->setIcon(tmp);
}
connect(d->backButton, SIGNAL(clicked()), this, SLOT(_k_back()));
connect(d->forwardButton, SIGNAL(clicked()), this, SLOT(_k_forward()));
d->sectionCombo = new QComboBox(this);
d->sectionCombo->setToolTip(tr("Select a category"));
comboLayout->addWidget(d->sectionCombo);
d->blockCombo = new QComboBox(this);
d->blockCombo->setToolTip(tr("Select a block to be displayed"));
d->blockCombo->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
comboLayout->addWidget(d->blockCombo, 1);
d->sectionCombo->addItems(s_data()->sectionList());
d->blockCombo->setMinimumWidth(QFontMetrics(QWidget::font()).averageCharWidth() * 25);
connect(d->sectionCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(_k_sectionSelected(int)));
connect(d->blockCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(_k_blockSelected(int)));
d->fontCombo = new QFontComboBox(this);
comboLayout->addWidget(d->fontCombo);
d->fontCombo->setEditable(true);
d->fontCombo->resize(d->fontCombo->sizeHint());
d->fontCombo->setToolTip(tr("Set font"));
d->fontSizeSpinBox = new QSpinBox(this);
comboLayout->addWidget(d->fontSizeSpinBox);
d->fontSizeSpinBox->setValue(QWidget::font().pointSize());
d->fontSizeSpinBox->setRange(1, 400);
d->fontSizeSpinBox->setSingleStep(1);
d->fontSizeSpinBox->setToolTip(tr("Set font size"));
connect(d->fontCombo, SIGNAL(currentIndexChanged(QString)), this, SLOT(_k_fontSelected()));
connect(d->fontSizeSpinBox, SIGNAL(valueChanged(int)), this, SLOT(_k_fontSelected()));
if ((HistoryButtons & controls) || (FontCombo & controls) || (FontSize & controls) || (BlockCombos & controls)) {
mainLayout->addLayout(comboLayout);
}
if (!(HistoryButtons & controls)) {
d->backButton->hide();
d->forwardButton->hide();
}
if (!(FontCombo & controls)) {
d->fontCombo->hide();
}
if (!(FontSize & controls)) {
d->fontSizeSpinBox->hide();
}
if (!(BlockCombos & controls)) {
d->sectionCombo->hide();
d->blockCombo->hide();
}
QSplitter *splitter = new QSplitter(this);
if ((CharacterTable & controls) || (DetailBrowser & controls)) {
mainLayout->addWidget(splitter);
} else {
splitter->hide();
}
d->charTable = new KCharSelectTable(this, QFont());
if (CharacterTable & controls) {
splitter->addWidget(d->charTable);
d->charTable->setFocus(Qt::OtherFocusReason);
} else {
d->charTable->hide();
}
const QSize sz(200, 200);
d->charTable->resize(sz);
d->charTable->setMinimumSize(sz);
d->charTable->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setCurrentFont(QFont());
connect(d->charTable, SIGNAL(focusItemChanged(uint)), this, SLOT(_k_updateCurrentChar(uint)));
connect(d->charTable, SIGNAL(activated(uint)), this, SLOT(_k_charSelected(uint)));
connect(d->charTable, SIGNAL(showCharRequested(uint)), this, SLOT(setCurrentCodePoint(uint)));
d->detailBrowser = new QTextBrowser(this);
if (DetailBrowser & controls) {
splitter->addWidget(d->detailBrowser);
} else {
d->detailBrowser->hide();
}
d->detailBrowser->setOpenLinks(false);
connect(d->detailBrowser, SIGNAL(anchorClicked(QUrl)), this, SLOT(_k_linkClicked(QUrl)));
setFocusPolicy(Qt::StrongFocus);
setFocusProxy(d->charTable);
d->_k_sectionSelected(0);
d->_k_blockSelected(0);
setCurrentCodePoint(QChar::Null);
d->historyEnabled = true;
}
KCharSelect::~KCharSelect()
{
delete d;
}
QSize KCharSelect::sizeHint() const
{
return QWidget::sizeHint();
}
void KCharSelect::setCurrentFont(const QFont &_font)
{
d->fontCombo->setCurrentFont(_font);
d->fontSizeSpinBox->setValue(_font.pointSize());
d->_k_fontSelected();
}
void KCharSelect::setAllPlanesEnabled(bool all)
{
d->allPlanesEnabled = all;
}
bool KCharSelect::allPlanesEnabled() const
{
return d->allPlanesEnabled;
}
QChar KCharSelect::currentChar() const
{
if (d->allPlanesEnabled) {
qFatal("You must use KCharSelect::currentCodePoint instead of KCharSelect::currentChar");
}
return QChar(d->charTable->chr());
}
uint KCharSelect::currentCodePoint() const
{
return d->charTable->chr();
}
QFont KCharSelect::currentFont() const
{
return d->charTable->font();
}
QList KCharSelect::displayedChars() const
{
if (d->allPlanesEnabled) {
qFatal("You must use KCharSelect::displayedCodePoints instead of KCharSelect::displayedChars");
}
QList result;
foreach (uint c, d->charTable->displayedChars()) {
result.append(QChar(c));
}
return result;
}
QVector KCharSelect::displayedCodePoints() const
{
return d->charTable->displayedChars();
}
void KCharSelect::setCurrentChar(const QChar &c)
{
if (d->allPlanesEnabled) {
qCritical("You should use KCharSelect::setCurrentCodePoint instead of KCharSelect::setCurrentChar");
}
setCurrentCodePoint(c.unicode());
}
void KCharSelect::setCurrentCodePoint(uint c)
{
if (!d->allPlanesEnabled && QChar::requiresSurrogates(c)) {
qCritical("You must setAllPlanesEnabled(true) to use non-BMP characters");
c = QChar::ReplacementCharacter;
}
if (c > QChar::LastValidCodePoint) {
qCWarning(KWidgetsAddonsLog, "Code point outside Unicode range");
c = QChar::LastValidCodePoint;
}
bool oldHistoryEnabled = d->historyEnabled;
d->historyEnabled = false;
int block = s_data()->blockIndex(c);
int section = s_data()->sectionIndex(block);
d->sectionCombo->setCurrentIndex(section);
int index = d->blockCombo->findData(block);
if (index != -1) {
d->blockCombo->setCurrentIndex(index);
}
d->historyEnabled = oldHistoryEnabled;
d->charTable->setChar(c);
}
void KCharSelect::KCharSelectPrivate::historyAdd(uint c, bool fromSearch, const QString &searchString)
{
//qCDebug(KWidgetsAddonsLog) << "about to add char" << c << "fromSearch" << fromSearch << "searchString" << searchString;
if (!historyEnabled) {
return;
}
if (!history.isEmpty() && c == history.last().c) {
//avoid duplicates
return;
}
//behave like a web browser, i.e. if user goes back from B to A then clicks C, B is forgotten
while (!history.isEmpty() && inHistory != history.count() - 1) {
history.removeLast();
}
while (history.size() >= MaxHistoryItems) {
history.removeFirst();
}
HistoryItem item;
item.c = c;
item.fromSearch = fromSearch;
item.searchString = searchString;
history.append(item);
inHistory = history.count() - 1;
updateBackForwardButtons();
}
void KCharSelect::KCharSelectPrivate::showFromHistory(int index)
{
Q_ASSERT(index >= 0 && index < history.count());
Q_ASSERT(index != inHistory);
inHistory = index;
updateBackForwardButtons();
const HistoryItem &item = history[index];
//qCDebug(KWidgetsAddonsLog) << "index" << index << "char" << item.c << "fromSearch" << item.fromSearch
// << "searchString" << item.searchString;
//avoid adding an item from history into history again
bool oldHistoryEnabled = historyEnabled;
historyEnabled = false;
if (item.fromSearch) {
if (searchLine->text() != item.searchString) {
searchLine->setText(item.searchString);
_k_search();
}
charTable->setChar(item.c);
} else {
searchLine->clear();
q->setCurrentCodePoint(item.c);
}
historyEnabled = oldHistoryEnabled;
}
void KCharSelect::KCharSelectPrivate::updateBackForwardButtons()
{
backButton->setEnabled(inHistory > 0);
forwardButton->setEnabled(inHistory < history.count() - 1);
}
void KCharSelect::KCharSelectPrivate::_k_activateSearchLine()
{
searchLine->setFocus();
searchLine->selectAll();
}
void KCharSelect::KCharSelectPrivate::_k_back()
{
Q_ASSERT(inHistory > 0);
showFromHistory(inHistory - 1);
}
void KCharSelect::KCharSelectPrivate::_k_forward()
{
Q_ASSERT(inHistory + 1 < history.count());
showFromHistory(inHistory + 1);
}
void KCharSelect::KCharSelectPrivate::_k_fontSelected()
{
QFont font = fontCombo->currentFont();
font.setPointSize(fontSizeSpinBox->value());
charTable->setFont(font);
emit q->currentFontChanged(font);
}
void KCharSelect::KCharSelectPrivate::_k_charSelected(uint c)
{
if (!allPlanesEnabled) {
emit q->charSelected(QChar(c));
}
emit q->codePointSelected(c);
}
void KCharSelect::KCharSelectPrivate::_k_updateCurrentChar(uint c)
{
if (!allPlanesEnabled) {
emit q->currentCharChanged(QChar(c));
}
emit q->currentCodePointChanged(c);
if (searchMode) {
//we are in search mode. make the two comboboxes show the section & block for this character.
//(when we are not in search mode the current character always belongs to the current section & block.)
int block = s_data()->blockIndex(c);
int section = s_data()->sectionIndex(block);
sectionCombo->setCurrentIndex(section);
int index = blockCombo->findData(block);
if (index != -1) {
blockCombo->setCurrentIndex(index);
}
}
if (searchLine) {
historyAdd(c, searchMode, searchLine->text());
}
_k_slotUpdateUnicode(c);
}
void KCharSelect::KCharSelectPrivate::_k_slotUpdateUnicode(uint c)
{
QString html = QStringLiteral("
") + tr("Character:") + QLatin1Char(' ') + s_data()->display(c, charTable->font()) + QLatin1Char(' ') +
s_data()->formatCode(c) + QStringLiteral("
");
QString name = s_data()->name(c);
if (!name.isEmpty()) {
//is name ever empty?
should always be there...
html += tr("Name: ") + name.toHtmlEscaped() + QStringLiteral("
");
}
QStringList aliases = s_data()->aliases(c);
QStringList notes = s_data()->notes(c);
QVector seeAlso = s_data()->seeAlso(c);
QStringList equivalents = s_data()->equivalents(c);
QStringList approxEquivalents = s_data()->approximateEquivalents(c);
if (!(aliases.isEmpty() && notes.isEmpty() && seeAlso.isEmpty() && equivalents.isEmpty() && approxEquivalents.isEmpty())) {
html += QStringLiteral("") + tr("Annotations and Cross References") + QStringLiteral("
");
}
if (!aliases.isEmpty()) {
html += QStringLiteral("") + tr("Alias names:") + QStringLiteral("
");
foreach (const QString &alias, aliases) {
html += QStringLiteral("- ") + alias.toHtmlEscaped() + QStringLiteral("
");
}
html += QStringLiteral("
");
}
if (!notes.isEmpty()) {
html += QStringLiteral("") + tr("Notes:") + QStringLiteral("
");
foreach (const QString ¬e, notes) {
html += QStringLiteral("- ") + createLinks(note.toHtmlEscaped()) + QStringLiteral("
");
}
html += QStringLiteral("
");
}
if (!seeAlso.isEmpty()) {
html += QStringLiteral("") + tr("See also:") + QStringLiteral("
");
}
if (!equivalents.isEmpty()) {
html += QStringLiteral("") + tr("Equivalents:") + QStringLiteral("
");
foreach (const QString &equivalent, equivalents) {
html += QStringLiteral("- ") + createLinks(equivalent.toHtmlEscaped()) + QStringLiteral("
");
}
html += QStringLiteral("
");
}
if (!approxEquivalents.isEmpty()) {
html += QStringLiteral("") + tr("Approximate equivalents:") + QStringLiteral("
");
foreach (const QString &approxEquivalent, approxEquivalents) {
html += QStringLiteral("- ") + createLinks(approxEquivalent.toHtmlEscaped()) + QStringLiteral("
");
}
html += QStringLiteral("
");
}
QStringList unihan = s_data()->unihanInfo(c);
if (unihan.count() == 7) {
html += QStringLiteral("") + tr("CJK Ideograph Information") + QStringLiteral("
");
bool newline = true;
if (!unihan[0].isEmpty()) {
html += tr("Definition in English: ") + unihan[0];
newline = false;
}
if (!unihan[2].isEmpty()) {
if (!newline) {
html += QStringLiteral("
");
}
html += tr("Mandarin Pronunciation: ") + unihan[2];
newline = false;
}
if (!unihan[1].isEmpty()) {
if (!newline) {
html += QStringLiteral("
");
}
html += tr("Cantonese Pronunciation: ") + unihan[1];
newline = false;
}
if (!unihan[6].isEmpty()) {
if (!newline) {
html += QStringLiteral("
");
}
html += tr("Japanese On Pronunciation: ") + unihan[6];
newline = false;
}
if (!unihan[5].isEmpty()) {
if (!newline) {
html += QStringLiteral("
");
}
html += tr("Japanese Kun Pronunciation: ") + unihan[5];
newline = false;
}
if (!unihan[3].isEmpty()) {
if (!newline) {
html += QStringLiteral("
");
}
html += tr("Tang Pronunciation: ") + unihan[3];
newline = false;
}
if (!unihan[4].isEmpty()) {
if (!newline) {
html += QStringLiteral("
");
}
html += tr("Korean Pronunciation: ") + unihan[4];
newline = false;
}
html += QStringLiteral("
");
}
html += QStringLiteral("") + tr("General Character Properties") + QStringLiteral("
");
html += tr("Block: ") + s_data()->block(c) + QStringLiteral("
");
html += tr("Unicode category: ") + s_data()->categoryText(s_data()->category(c)) + QStringLiteral("
");
QByteArray utf8 = QString::fromUcs4(&c, 1).toUtf8();
html += QStringLiteral("") + tr("Various Useful Representations") + QStringLiteral("
");
html += tr("UTF-8:");
foreach (unsigned char c, utf8) {
html += QLatin1Char(' ') + s_data()->formatCode(c, 2, QStringLiteral("0x"));
}
html += QStringLiteral("
") + tr("UTF-16: ");
if (QChar::requiresSurrogates(c)) {
html += s_data()->formatCode(QChar::highSurrogate(c), 4, QStringLiteral("0x"));
html += QLatin1Char(' ') + s_data->formatCode(QChar::lowSurrogate(c), 4, QStringLiteral("0x"));
} else {
html += s_data()->formatCode(c, 4, QStringLiteral("0x"));
}
html += QStringLiteral("
") + tr("C octal escaped UTF-8: ");
foreach (unsigned char c, utf8) {
html += s_data()->formatCode(c, 3, QStringLiteral("\\"), 8);
}
html += QStringLiteral("
") + tr("XML decimal entity:") + QStringLiteral(" &#") + QString::number(c) + QStringLiteral(";
");
detailBrowser->setHtml(html);
}
QString KCharSelect::KCharSelectPrivate::createLinks(QString s)
{
QRegExp rx(QStringLiteral("\\b([\\dABCDEF]{4,5})\\b"));
QStringList chars;
int pos = 0;
while ((pos = rx.indexIn(s, pos)) != -1) {
chars << rx.cap(1);
pos += rx.matchedLength();
}
QSet chars2 = QSet::fromList(chars);
foreach (const QString &c, chars2) {
- int unicode = c.toInt(0, 16);
+ int unicode = c.toInt(nullptr, 16);
if (!allPlanesEnabled && QChar::requiresSurrogates(unicode)) {
continue;
}
QString link = QStringLiteral("");
if (s_data()->isPrint(unicode)) {
link += QStringLiteral("") + QString::number(unicode) + QStringLiteral("; ");
}
link += QStringLiteral("U+") + c + QLatin1Char(' ');
link += s_data()->name(unicode).toHtmlEscaped() + QStringLiteral("");
s.replace(c, link);
}
return s;
}
void KCharSelect::KCharSelectPrivate::_k_sectionSelected(int index)
{
blockCombo->clear();
QVector blocks = s_data()->sectionContents(index);
foreach (int block, blocks) {
if (!allPlanesEnabled) {
const QVector contents = s_data()->blockContents(block);
if (!contents.isEmpty() && QChar::requiresSurrogates(contents.at(0))) {
continue;
}
}
blockCombo->addItem(s_data()->blockName(block), QVariant(block));
}
blockCombo->setCurrentIndex(0);
}
void KCharSelect::KCharSelectPrivate::_k_blockSelected(int index)
{
if (index == -1) {
//the combo box has been cleared and is about to be filled again (because the section has changed)
return;
}
if (searchMode) {
//we are in search mode, so don't fill the table with this block.
return;
}
int block = blockCombo->itemData(index).toInt();
const QVector contents = s_data()->blockContents(block);
charTable->setContents(contents);
emit q->displayedCharsChanged();
charTable->setChar(contents[0]);
}
void KCharSelect::KCharSelectPrivate::_k_searchEditChanged()
{
if (searchLine->text().isEmpty()) {
sectionCombo->setEnabled(true);
blockCombo->setEnabled(true);
//upon leaving search mode, keep the same character selected
searchMode = false;
uint c = charTable->chr();
bool oldHistoryEnabled = historyEnabled;
historyEnabled = false;
_k_blockSelected(blockCombo->currentIndex());
historyEnabled = oldHistoryEnabled;
q->setCurrentCodePoint(c);
} else {
sectionCombo->setEnabled(false);
blockCombo->setEnabled(false);
int length = searchLine->text().length();
if (length >= 3) {
_k_search();
}
}
}
void KCharSelect::KCharSelectPrivate::_k_search()
{
if (searchLine->text().isEmpty()) {
return;
}
searchMode = true;
QVector contents = s_data()->find(searchLine->text());
if (!allPlanesEnabled) {
QVector::iterator it = contents.begin();
while (it != contents.end()) {
if (QChar::requiresSurrogates(*it)) {
it = contents.erase(it);
} else {
++it;
}
}
}
charTable->setContents(contents);
emit q->displayedCharsChanged();
if (!contents.isEmpty()) {
charTable->setChar(contents[0]);
}
}
void KCharSelect::KCharSelectPrivate::_k_linkClicked(QUrl url)
{
QString hex = url.toString();
if (hex.size() > 6) {
return;
}
- int unicode = hex.toInt(0, 16);
+ int unicode = hex.toInt(nullptr, 16);
if (unicode > QChar::LastValidCodePoint) {
return;
}
searchLine->clear();
q->setCurrentCodePoint(unicode);
}
////
QVariant KCharSelectItemModel::data(const QModelIndex &index, int role) const
{
int pos = m_columns * (index.row()) + index.column();
if (!index.isValid() || pos < 0 || pos >= m_chars.size()
|| index.row() < 0 || index.column() < 0) {
if (role == Qt::BackgroundColorRole) {
return QVariant(qApp->palette().color(QPalette::Button));
}
return QVariant();
}
uint c = m_chars[pos];
if (role == Qt::ToolTipRole) {
QString result = s_data()->display(c, m_font) + QStringLiteral("
") + s_data()->name(c).toHtmlEscaped() + QStringLiteral("
") +
tr("Unicode code point:") + QLatin1Char(' ') + s_data()->formatCode(c) + QStringLiteral("
") +
tr("In decimal", "Character") + QLatin1Char(' ') + QString::number(c);
return QVariant(result);
} else if (role == Qt::TextAlignmentRole) {
return QVariant(Qt::AlignHCenter | Qt::AlignVCenter);
} else if (role == Qt::DisplayRole) {
if (s_data()->isPrint(c)) {
return QVariant(QString::fromUcs4(&c, 1));
}
return QVariant();
} else if (role == Qt::BackgroundColorRole) {
QFontMetrics fm = QFontMetrics(m_font);
if (fm.inFontUcs4(c) && s_data()->isPrint(c)) {
return QVariant(qApp->palette().color(QPalette::Base));
} else {
return QVariant(qApp->palette().color(QPalette::Button));
}
} else if (role == Qt::FontRole) {
return QVariant(m_font);
} else if (role == CharacterRole) {
return QVariant(c);
}
return QVariant();
}
bool KCharSelectItemModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
{
Q_UNUSED(row)
Q_UNUSED(parent)
if (action == Qt::IgnoreAction) {
return true;
}
if (!data->hasText()) {
return false;
}
if (column > 0) {
return false;
}
QString text = data->text();
if (text.isEmpty()) {
return false;
}
emit showCharRequested(text.toUcs4().at(0));
return true;
}
void KCharSelectItemModel::setColumnCount(int columns)
{
emit layoutAboutToBeChanged();
m_columns = columns;
emit layoutChanged();
}
#include "moc_kcharselect.cpp"
#include "moc_kcharselect_p.cpp"
diff --git a/src/kcharselect_p.h b/src/kcharselect_p.h
index 466c1c7..cf4b743 100644
--- a/src/kcharselect_p.h
+++ b/src/kcharselect_p.h
@@ -1,188 +1,188 @@
/* This file is part of the KDE libraries
Copyright (C) 2005 Joseph Wenninger
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef KCHARSELECT_P_H
#define KCHARSELECT_P_H
#include
#include
#include
#include
#include "kcharselectdata_p.h"
class KCharSelectTablePrivate;
/**
* @short Character selection table
*
* A table widget which displays the characters of a font. Internally
* used by KCharSelect. See the KCharSelect documentation for further
* details.
*
* @author Reginald Stadlbauer
* @author Daniel Laidig
*/
class KCharSelectTable : public QTableView
{
Q_OBJECT
public:
/**
* Constructor. Using @p _font, draw a table of chars.
* @sa setContents
*/
KCharSelectTable(QWidget *parent, const QFont &_font);
~KCharSelectTable();
void resizeEvent(QResizeEvent *) Q_DECL_OVERRIDE;
/** Set the font to be displayed to @p _font . */
void setFont(const QFont &_font);
/** Set the highlighted character to @p c . */
void setChar(uint c);
/** Set the contents of the table to @p chars . */
void setContents(const QVector &chars);
/** @return Currently highlighted character. */
uint chr();
/**
* Returns the currently displayed font.
*/
QFont font() const;
/**
* Returns a list of currently displayed characters.
*/
QVector displayedChars() const;
/**
* Reimplemented.
*/
virtual void scrollTo(const QModelIndex &index, ScrollHint hint = EnsureVisible) Q_DECL_OVERRIDE;
protected:
/**
* Reimplemented.
*/
virtual void keyPressEvent(QKeyEvent *e) Q_DECL_OVERRIDE;
Q_SIGNALS:
/** Emitted to indicate that character @p c is activated (such as by double-clicking it). */
void activated(uint c);
void focusItemChanged(uint c);
void showCharRequested(uint c);
private:
Q_PRIVATE_SLOT(d, void _k_slotSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected))
Q_PRIVATE_SLOT(d, void _k_resizeCells())
Q_PRIVATE_SLOT(d, void _k_doubleClicked(const QModelIndex &index))
private:
friend class KCharSelectTablePrivate;
KCharSelectTablePrivate *const d;
Q_DISABLE_COPY(KCharSelectTable)
};
// NO D-Pointer needed, private internal class, no public API
class KCharSelectItemModel: public QAbstractTableModel
{
Q_OBJECT
public:
KCharSelectItemModel(QVector chars, const QFont &font, QObject *parent): QAbstractTableModel(parent), m_chars(chars), m_font(font)
{
if (chars.count()) {
m_columns = chars.count();
} else {
m_columns = 1;
}
}
enum internalRoles {CharacterRole = Qt::UserRole};
int rowCount(const QModelIndex & = QModelIndex()) const Q_DECL_OVERRIDE
{
if (m_chars.count() % m_columns == 0) {
return m_chars.count() / m_columns;
} else {
return m_chars.count() / m_columns + 1;
}
}
int columnCount(const QModelIndex & = QModelIndex()) const Q_DECL_OVERRIDE
{
return m_columns;
}
void setFont(const QFont &font)
{
beginResetModel();
m_font = font;
endResetModel();
}
Qt::ItemFlags flags(const QModelIndex &index) const Q_DECL_OVERRIDE
{
int pos = m_columns * (index.row()) + index.column();
if (pos >= m_chars.size() || index.row() < 0 || index.column() < 0) {
return Qt::ItemIsDropEnabled;
}
return (Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | Qt::ItemIsSelectable | Qt::ItemIsEnabled);
}
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE;
QMimeData *mimeData(const QModelIndexList &indexes) const Q_DECL_OVERRIDE
{
if (indexes.size() != 1) {
- return 0;
+ return nullptr;
}
QMimeData *mimeData = new QMimeData();
uint character = data(indexes[0], CharacterRole).toUInt();
mimeData->setText(QString::fromUcs4(&character, 1));
return mimeData;
}
Qt::DropActions supportedDropActions() const Q_DECL_OVERRIDE
{
return Qt::CopyAction;
}
QStringList mimeTypes() const Q_DECL_OVERRIDE
{
QStringList types;
types << QStringLiteral("text/plain");
return types;
}
bool dropMimeData(const QMimeData *data, Qt::DropAction action,
int row, int column, const QModelIndex &parent) Q_DECL_OVERRIDE;
void setColumnCount(int columns);
QVector chars() const { return m_chars; }
private:
QVector m_chars;
QFont m_font;
int m_columns;
Q_SIGNALS:
void showCharRequested(uint c);
};
#endif // KCHARSELECT_P_H
diff --git a/src/kcharselectdata.cpp b/src/kcharselectdata.cpp
index 92c1c79..724a374 100644
--- a/src/kcharselectdata.cpp
+++ b/src/kcharselectdata.cpp
@@ -1,1027 +1,1027 @@
/* This file is part of the KDE libraries
Copyright (C) 2007 Daniel Laidig
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "kcharselectdata_p.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
/* constants for hangul (de)composition, see UAX #15 */
#define SBase 0xAC00
#define LBase 0x1100
#define VBase 0x1161
#define TBase 0x11A7
#define LCount 19
#define VCount 21
#define TCount 28
#define NCount (VCount * TCount)
#define SCount (LCount * NCount)
class RunIndexCreation : public QFutureInterface, public QRunnable
{
public:
RunIndexCreation(KCharSelectData *data, const QByteArray &dataFile)
: m_data(data), m_dataFile(dataFile)
{
}
QFuture start()
{
setRunnable(this);
reportStarted();
QFuture f = this->future();
QThreadPool::globalInstance()->start(this);
return f;
}
void run() Q_DECL_OVERRIDE
{
Index index = m_data->createIndex(m_dataFile);
reportResult(index);
reportFinished();
}
private:
KCharSelectData *m_data;
QByteArray m_dataFile;
};
static const char JAMO_L_TABLE[][4] = {
"G", "GG", "N", "D", "DD", "R", "M", "B", "BB",
"S", "SS", "", "J", "JJ", "C", "K", "T", "P", "H"
};
static const char JAMO_V_TABLE[][4] = {
"A", "AE", "YA", "YAE", "EO", "E", "YEO", "YE", "O",
"WA", "WAE", "OE", "YO", "U", "WEO", "WE", "WI",
"YU", "EU", "YI", "I"
};
static const char JAMO_T_TABLE[][4] = {
"", "G", "GG", "GS", "N", "NJ", "NH", "D", "L", "LG", "LM",
"LB", "LS", "LT", "LP", "LH", "M", "B", "BS",
"S", "SS", "NG", "J", "C", "K", "T", "P", "H"
};
bool KCharSelectData::openDataFile()
{
if (!dataFile.isEmpty()) {
return true;
} else {
QFile file(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("kf5/kcharselect/kcharselect-data")));
if (!file.open(QIODevice::ReadOnly)) {
return false;
}
dataFile = file.readAll();
file.close();
if (dataFile.size() < 40) {
dataFile.clear();
return false;
}
const uchar *data = reinterpret_cast(dataFile.constData());
const quint32 offsetBegin = qFromLittleEndian(data + 20);
const quint32 offsetEnd = qFromLittleEndian(data + 24);
uint blocks = (offsetEnd - offsetBegin) / 4;
if (blocks <= 167) { // maximum possible number of blocks in BMP
// no remapping
remapType = -1;
} else if (blocks == 174) {
// remapping introduced in 5.25
remapType = 0;
} else {
// unknown remapping, abort
dataFile.clear();
return false;
}
futureIndex = (new RunIndexCreation(this, dataFile))->start();
return true;
}
}
// Temporary remapping code points <-> 16 bit database codes
// See kcharselect-generate-datafile.py for details
quint16 KCharSelectData::mapCodePointToDataBase(uint code) const
{
if (remapType == 0) {
if (code >= 0xE000 && code <= 0xEFFF) {
return 0xFFFF;
}
if (code >= 0xF000 && code <= 0xFFFF) {
return code - 0x1000;
}
if (code >= 0x1F000 && code <= 0x1FFFF) {
return code - 0x10000;
}
}
if (code >= 0x10000) {
return 0xFFFF;
}
return code;
}
uint KCharSelectData::mapDataBaseToCodePoint(quint16 code) const
{
if (remapType == 0) {
if (code >= 0xE000 && code <= 0xEFFF) {
return code + 0x1000;
}
if (code >= 0xF000 && code <= 0xFFFF) {
return code + 0x10000;
}
}
return code;
}
quint32 KCharSelectData::getDetailIndex(uint c) const
{
const uchar *data = reinterpret_cast(dataFile.constData());
// Convert from little-endian, so that this code works on PPC too.
// http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=482286
const quint32 offsetBegin = qFromLittleEndian(data + 12);
const quint32 offsetEnd = qFromLittleEndian(data + 16);
int min = 0;
int mid;
int max = ((offsetEnd - offsetBegin) / 27) - 1;
quint16 unicode = mapCodePointToDataBase(c);
if (unicode == 0xFFFF) {
return 0;
}
static quint16 most_recent_searched;
static quint32 most_recent_result;
if (unicode == most_recent_searched) {
return most_recent_result;
}
most_recent_searched = unicode;
while (max >= min) {
mid = (min + max) / 2;
const quint16 midUnicode = qFromLittleEndian(data + offsetBegin + mid * 27);
if (unicode > midUnicode) {
min = mid + 1;
} else if (unicode < midUnicode) {
max = mid - 1;
} else {
most_recent_result = offsetBegin + mid * 27;
return most_recent_result;
}
}
most_recent_result = 0;
return 0;
}
QString KCharSelectData::formatCode(uint code, int length, const QString &prefix, int base)
{
QString s = QString::number(code, base).toUpper();
while (s.size() < length) {
s.prepend(QLatin1Char('0'));
}
s.prepend(prefix);
return s;
}
QVector KCharSelectData::blockContents(int block)
{
if (!openDataFile()) {
return QVector();
}
const uchar *data = reinterpret_cast(dataFile.constData());
const quint32 offsetBegin = qFromLittleEndian(data + 20);
const quint32 offsetEnd = qFromLittleEndian(data + 24);
int max = ((offsetEnd - offsetBegin) / 4) - 1;
QVector res;
if (block > max) {
return res;
}
quint16 unicodeBegin = qFromLittleEndian(data + offsetBegin + block * 4);
quint16 unicodeEnd = qFromLittleEndian(data + offsetBegin + block * 4 + 2);
while (unicodeBegin < unicodeEnd) {
res.append(mapDataBaseToCodePoint(unicodeBegin));
unicodeBegin++;
}
res.append(mapDataBaseToCodePoint(unicodeBegin)); // Be carefull when unicodeEnd==0xffff
return res;
}
QVector KCharSelectData::sectionContents(int section)
{
if (!openDataFile()) {
return QVector();
}
const uchar *data = reinterpret_cast(dataFile.constData());
const quint32 offsetBegin = qFromLittleEndian(data + 28);
const quint32 offsetEnd = qFromLittleEndian(data + 32);
int max = ((offsetEnd - offsetBegin) / 4) - 1;
QVector res;
if (section > max) {
return res;
}
for (int i = 0; i <= max; i++) {
const quint16 currSection = qFromLittleEndian(data + offsetBegin + i * 4);
if (currSection == section) {
res.append(qFromLittleEndian(data + offsetBegin + i * 4 + 2));
}
}
return res;
}
QStringList KCharSelectData::sectionList()
{
if (!openDataFile()) {
return QStringList();
}
const uchar *udata = reinterpret_cast(dataFile.constData());
const quint32 stringBegin = qFromLittleEndian(udata + 24);
const quint32 stringEnd = qFromLittleEndian(udata + 28);
const char *data = dataFile.constData();
QStringList list;
quint32 i = stringBegin;
while (i < stringEnd) {
list.append(QCoreApplication::translate("KCharSelectData", data + i, "KCharSelect section name"));
i += strlen(data + i) + 1;
}
return list;
}
QString KCharSelectData::block(uint c)
{
return blockName(blockIndex(c));
}
QString KCharSelectData::section(uint c)
{
return sectionName(sectionIndex(blockIndex(c)));
}
QString KCharSelectData::name(uint c)
{
if (!openDataFile()) {
return QString();
}
if ((c & 0xFFFE) == 0xFFFE || (c >= 0xFDD0 && c <= 0xFDEF)) {
return QCoreApplication::translate("KCharSelectData", "");
} else if ((c >= 0x3400 && c <= 0x4DBF)
|| (c >= 0x4E00 && c <= 0x9FFF)
|| (c >= 0x20000 && c <= 0x2F7FF)) {
return QStringLiteral("CJK UNIFIED IDEOGRAPH-") + formatCode(c, 4, QString());
} else if (c >= 0xAC00 && c <= 0xD7AF) {
/* compute hangul syllable name as per UAX #15 */
int SIndex = c - SBase;
int LIndex, VIndex, TIndex;
if (SIndex < 0 || SIndex >= SCount) {
return QString();
}
LIndex = SIndex / NCount;
VIndex = (SIndex % NCount) / TCount;
TIndex = SIndex % TCount;
return QLatin1String("HANGUL SYLLABLE ") + QLatin1String(JAMO_L_TABLE[LIndex])
+ QLatin1String(JAMO_V_TABLE[VIndex]) + QLatin1String(JAMO_T_TABLE[TIndex]);
} else if (c >= 0xD800 && c <= 0xDB7F) {
return QCoreApplication::translate("KCharSelectData", "");
} else if (c >= 0xDB80 && c <= 0xDBFF) {
return QCoreApplication::translate("KCharSelectData", "");
} else if (c >= 0xDC00 && c <= 0xDFFF) {
return QCoreApplication::translate("KCharSelectData", "");
} else if ((c >= 0xE000 && c <= 0xF8FF) || c >= 0xF0000) {
return QCoreApplication::translate("KCharSelectData", "");
} else if ((c >= 0xF900 && c <= 0xFAFF) || (c >= 0x2F800 && c <= 0x2FFFF)) {
return QStringLiteral("CJK COMPATIBILITY IDEOGRAPH-") + formatCode(c, 4, QString());
}
quint16 unicode = mapCodePointToDataBase(c);
if (unicode == 0xFFFF) {
return QStringLiteral("NON-BMP-CHARACTER-") + formatCode(c, 4, QString());
} else {
const uchar *data = reinterpret_cast(dataFile.constData());
const quint32 offsetBegin = qFromLittleEndian(data + 4);
const quint32 offsetEnd = qFromLittleEndian(data + 8);
int min = 0;
int mid;
int max = ((offsetEnd - offsetBegin) / 6) - 1;
QString s;
while (max >= min) {
mid = (min + max) / 2;
const quint16 midUnicode = qFromLittleEndian(data + offsetBegin + mid * 6);
if (unicode > midUnicode) {
min = mid + 1;
} else if (unicode < midUnicode) {
max = mid - 1;
} else {
quint32 offset = qFromLittleEndian(data + offsetBegin + mid * 6 + 2);
s = QString::fromUtf8(dataFile.constData() + offset + 1);
break;
}
}
if (s.isNull()) {
return QCoreApplication::translate("KCharSelectData", "");
} else {
return s;
}
}
}
int KCharSelectData::blockIndex(uint c)
{
if (!openDataFile()) {
return 0;
}
const uchar *data = reinterpret_cast(dataFile.constData());
const quint32 offsetBegin = qFromLittleEndian(data + 20);
const quint32 offsetEnd = qFromLittleEndian(data + 24);
const quint16 unicode = mapCodePointToDataBase(c);
if (unicode == 0xFFFF) {
return 0;
}
int max = ((offsetEnd - offsetBegin) / 4) - 1;
int i = 0;
while (unicode > qFromLittleEndian(data + offsetBegin + i * 4 + 2) && i < max) {
i++;
}
return i;
}
int KCharSelectData::sectionIndex(int block)
{
if (!openDataFile()) {
return 0;
}
const uchar *data = reinterpret_cast(dataFile.constData());
const quint32 offsetBegin = qFromLittleEndian(data + 28);
const quint32 offsetEnd = qFromLittleEndian(data + 32);
int max = ((offsetEnd - offsetBegin) / 4) - 1;
for (int i = 0; i <= max; i++) {
if (qFromLittleEndian(data + offsetBegin + i * 4 + 2) == block) {
return qFromLittleEndian(data + offsetBegin + i * 4);
}
}
return 0;
}
QString KCharSelectData::blockName(int index)
{
if (!openDataFile()) {
return QString();
}
const uchar *udata = reinterpret_cast(dataFile.constData());
const quint32 stringBegin = qFromLittleEndian(udata + 16);
const quint32 stringEnd = qFromLittleEndian(udata + 20);
quint32 i = stringBegin;
int currIndex = 0;
const char *data = dataFile.constData();
while (i < stringEnd && currIndex < index) {
i += strlen(data + i) + 1;
currIndex++;
}
return QCoreApplication::translate("KCharSelectData", data + i, "KCharselect unicode block name");
}
QString KCharSelectData::sectionName(int index)
{
if (!openDataFile()) {
return QString();
}
const uchar *udata = reinterpret_cast(dataFile.constData());
const quint32 stringBegin = qFromLittleEndian(udata + 24);
const quint32 stringEnd = qFromLittleEndian(udata + 28);
quint32 i = stringBegin;
int currIndex = 0;
const char *data = dataFile.constData();
while (i < stringEnd && currIndex < index) {
i += strlen(data + i) + 1;
currIndex++;
}
return QCoreApplication::translate("KCharSelectData", data + i, "KCharselect unicode section name");
}
QStringList KCharSelectData::aliases(uint c)
{
if (!openDataFile()) {
return QStringList();
}
const uchar *udata = reinterpret_cast(dataFile.constData());
const int detailIndex = getDetailIndex(c);
if (detailIndex == 0) {
return QStringList();
}
const quint8 count = * (quint8 *)(udata + detailIndex + 6);
quint32 offset = qFromLittleEndian(udata + detailIndex + 2);
QStringList aliases;
const char *data = dataFile.constData();
for (int i = 0; i < count; i++) {
aliases.append(QString::fromUtf8(data + offset));
offset += strlen(data + offset) + 1;
}
return aliases;
}
QStringList KCharSelectData::notes(uint c)
{
if (!openDataFile()) {
return QStringList();
}
const int detailIndex = getDetailIndex(c);
if (detailIndex == 0) {
return QStringList();
}
const uchar *udata = reinterpret_cast(dataFile.constData());
const quint8 count = * (quint8 *)(udata + detailIndex + 11);
quint32 offset = qFromLittleEndian(udata + detailIndex + 7);
QStringList notes;
const char *data = dataFile.constData();
for (int i = 0; i < count; i++) {
notes.append(QString::fromUtf8(data + offset));
offset += strlen(data + offset) + 1;
}
return notes;
}
QVector KCharSelectData::seeAlso(uint c)
{
if (!openDataFile()) {
return QVector();
}
const int detailIndex = getDetailIndex(c);
if (detailIndex == 0) {
return QVector();
}
const uchar *udata = reinterpret_cast(dataFile.constData());
const quint8 count = * (quint8 *)(udata + detailIndex + 26);
quint32 offset = qFromLittleEndian(udata + detailIndex + 22);
QVector seeAlso;
for (int i = 0; i < count; i++) {
seeAlso.append(mapDataBaseToCodePoint(qFromLittleEndian (udata + offset)));
offset += 2;
}
return seeAlso;
}
QStringList KCharSelectData::equivalents(uint c)
{
if (!openDataFile()) {
return QStringList();
}
const int detailIndex = getDetailIndex(c);
if (detailIndex == 0) {
return QStringList();
}
const uchar *udata = reinterpret_cast(dataFile.constData());
const quint8 count = * (quint8 *)(udata + detailIndex + 21);
quint32 offset = qFromLittleEndian(udata + detailIndex + 17);
QStringList equivalents;
const char *data = dataFile.constData();
for (int i = 0; i < count; i++) {
equivalents.append(QString::fromUtf8(data + offset));
offset += strlen(data + offset) + 1;
}
return equivalents;
}
QStringList KCharSelectData::approximateEquivalents(uint c)
{
if (!openDataFile()) {
return QStringList();
}
const int detailIndex = getDetailIndex(c);
if (detailIndex == 0) {
return QStringList();
}
const uchar *udata = reinterpret_cast(dataFile.constData());
const quint8 count = * (quint8 *)(udata + detailIndex + 16);
quint32 offset = qFromLittleEndian(udata + detailIndex + 12);
QStringList approxEquivalents;
const char *data = dataFile.constData();
for (int i = 0; i < count; i++) {
approxEquivalents.append(QString::fromUtf8(data + offset));
offset += strlen(data + offset) + 1;
}
return approxEquivalents;
}
QStringList KCharSelectData::unihanInfo(uint c)
{
if (!openDataFile()) {
return QStringList();
}
quint16 unicode = mapCodePointToDataBase(c);
if (unicode == 0xFFFF) {
return QStringList();
}
const char *data = dataFile.constData();
const uchar *udata = reinterpret_cast(data);
const quint32 offsetBegin = qFromLittleEndian(udata + 36);
const quint32 offsetEnd = dataFile.size();
int min = 0;
int mid;
int max = ((offsetEnd - offsetBegin) / 30) - 1;
while (max >= min) {
mid = (min + max) / 2;
const quint16 midUnicode = qFromLittleEndian(udata + offsetBegin + mid * 30);
if (unicode > midUnicode) {
min = mid + 1;
} else if (unicode < midUnicode) {
max = mid - 1;
} else {
QStringList res;
for (int i = 0; i < 7; i++) {
quint32 offset = qFromLittleEndian(udata + offsetBegin + mid * 30 + 2 + i * 4);
if (offset != 0) {
res.append(QString::fromUtf8(data + offset));
} else {
res.append(QString());
}
}
return res;
}
}
return QStringList();
}
QChar::Category KCharSelectData::category(uint c)
{
if (!openDataFile()) {
return QChar::category(c);
}
ushort unicode = mapCodePointToDataBase(c);
if (unicode == 0xFFFF) {
return QChar::category(c);
}
const uchar *data = reinterpret_cast(dataFile.constData());
const quint32 offsetBegin = qFromLittleEndian(data + 4);
const quint32 offsetEnd = qFromLittleEndian(data + 8);
int min = 0;
int mid;
int max = ((offsetEnd - offsetBegin) / 6) - 1;
QString s;
while (max >= min) {
mid = (min + max) / 2;
const quint16 midUnicode = qFromLittleEndian(data + offsetBegin + mid * 6);
if (unicode > midUnicode) {
min = mid + 1;
} else if (unicode < midUnicode) {
max = mid - 1;
} else {
quint32 offset = qFromLittleEndian(data + offsetBegin + mid * 6 + 2);
uchar categoryCode = *(data + offset);
Q_ASSERT(categoryCode > 0);
categoryCode--; /* Qt5 changed QChar::Category enum to start from 0 instead of 1
See QtBase commit d17c76feee9eece4 */
return QChar::Category(categoryCode);
}
}
return QChar::category(c);
}
bool KCharSelectData::isPrint(uint c)
{
QChar::Category cat = category(c);
return !(cat == QChar::Other_Control || cat == QChar::Other_NotAssigned);
}
bool KCharSelectData::isDisplayable(uint c)
{
// Qt internally uses U+FDD0 and U+FDD1 to mark the beginning and the end of frames.
// They should be seen as non-printable characters, as trying to display them leads
// to a crash caused by a Qt "noBlockInString" assertion.
if (c == 0xFDD0 || c == 0xFDD1) {
return false;
}
return !isIgnorable(c) && isPrint(c);
}
bool KCharSelectData::isIgnorable(uint c)
{
/*
* According to the Unicode standard, Default Ignorable Code Points
* should be ignored unless explicitly supported. For example, U+202E
* RIGHT-TO-LEFT-OVERRIDE ir printable according to Qt, but displaying
* it gives the undesired effect of all text being turned RTL. We do not
* have a way to "explicitly" support it, so we will treat it as
* non-printable.
*
* There is a list of these on
* http://unicode.org/Public/UNIDATA/DerivedCoreProperties.txt under the
* property Default_Ignorable_Code_Point.
*/
//NOTE: not very nice to hardcode these here; is it worth it to modify
// the binary data file to hold them?
return c == 0x00AD || c == 0x034F || c == 0x115F || c == 0x1160 ||
c == 0x17B4 || c == 0x17B5 || (c >= 0x180B && c <= 0x180D) ||
(c >= 0x200B && c <= 0x200F) || (c >= 0x202A && c <= 0x202E) ||
(c >= 0x2060 && c <= 0x206F) || c == 0x3164 ||
(c >= 0xFE00 && c <= 0xFE0F) || c == 0xFEFF || c == 0xFFA0 ||
(c >= 0xFFF0 && c <= 0xFFF8);
}
bool KCharSelectData::isCombining(uint c)
{
return section(c) == QCoreApplication::translate("KCharSelectData", "Combining Diacritics", "KCharSelect section name");
//FIXME: this is an imperfect test. There are many combining characters
// that are outside of this section. See Grapheme_Extend in
// http://www.unicode.org/Public/UNIDATA/DerivedCoreProperties.txt
}
QString KCharSelectData::display(uint c, const QFont &font)
{
if (!isDisplayable(c)) {
return QStringLiteral("") + QCoreApplication::translate("KCharSelectData", "Non-printable") + QStringLiteral("");
} else {
QString s = QStringLiteral("");
if (isCombining(c)) {
s += displayCombining(c);
} else {
s += QStringLiteral("") + QString::number(c) + QLatin1Char(';');
}
s += QStringLiteral("");
return s;
}
}
QString KCharSelectData::displayCombining(uint c)
{
/*
* The purpose of this is to make it easier to see how a combining
* character affects the text around it.
* The initial plan was to use U+25CC DOTTED CIRCLE for this purpose,
* as seen in pdfs from Unicode, but there seem to be a lot of alignment
* problems with that.
*
* Eventually, it would be nice to determine whether the character
* combines to the left or to the right, etc.
*/
QString s = QStringLiteral(" ") + QString::number(c) + QStringLiteral("; ") +
QStringLiteral(" (ab") + QString::number(c) + QStringLiteral(";c)");
return s;
}
QString KCharSelectData::categoryText(QChar::Category category)
{
switch (category) {
case QChar::Other_Control: return QCoreApplication::translate("KCharSelectData", "Other, Control");
case QChar::Other_Format: return QCoreApplication::translate("KCharSelectData", "Other, Format");
case QChar::Other_NotAssigned: return QCoreApplication::translate("KCharSelectData", "Other, Not Assigned");
case QChar::Other_PrivateUse: return QCoreApplication::translate("KCharSelectData", "Other, Private Use");
case QChar::Other_Surrogate: return QCoreApplication::translate("KCharSelectData", "Other, Surrogate");
case QChar::Letter_Lowercase: return QCoreApplication::translate("KCharSelectData", "Letter, Lowercase");
case QChar::Letter_Modifier: return QCoreApplication::translate("KCharSelectData", "Letter, Modifier");
case QChar::Letter_Other: return QCoreApplication::translate("KCharSelectData", "Letter, Other");
case QChar::Letter_Titlecase: return QCoreApplication::translate("KCharSelectData", "Letter, Titlecase");
case QChar::Letter_Uppercase: return QCoreApplication::translate("KCharSelectData", "Letter, Uppercase");
case QChar::Mark_SpacingCombining: return QCoreApplication::translate("KCharSelectData", "Mark, Spacing Combining");
case QChar::Mark_Enclosing: return QCoreApplication::translate("KCharSelectData", "Mark, Enclosing");
case QChar::Mark_NonSpacing: return QCoreApplication::translate("KCharSelectData", "Mark, Non-Spacing");
case QChar::Number_DecimalDigit: return QCoreApplication::translate("KCharSelectData", "Number, Decimal Digit");
case QChar::Number_Letter: return QCoreApplication::translate("KCharSelectData", "Number, Letter");
case QChar::Number_Other: return QCoreApplication::translate("KCharSelectData", "Number, Other");
case QChar::Punctuation_Connector: return QCoreApplication::translate("KCharSelectData", "Punctuation, Connector");
case QChar::Punctuation_Dash: return QCoreApplication::translate("KCharSelectData", "Punctuation, Dash");
case QChar::Punctuation_Close: return QCoreApplication::translate("KCharSelectData", "Punctuation, Close");
case QChar::Punctuation_FinalQuote: return QCoreApplication::translate("KCharSelectData", "Punctuation, Final Quote");
case QChar::Punctuation_InitialQuote: return QCoreApplication::translate("KCharSelectData", "Punctuation, Initial Quote");
case QChar::Punctuation_Other: return QCoreApplication::translate("KCharSelectData", "Punctuation, Other");
case QChar::Punctuation_Open: return QCoreApplication::translate("KCharSelectData", "Punctuation, Open");
case QChar::Symbol_Currency: return QCoreApplication::translate("KCharSelectData", "Symbol, Currency");
case QChar::Symbol_Modifier: return QCoreApplication::translate("KCharSelectData", "Symbol, Modifier");
case QChar::Symbol_Math: return QCoreApplication::translate("KCharSelectData", "Symbol, Math");
case QChar::Symbol_Other: return QCoreApplication::translate("KCharSelectData", "Symbol, Other");
case QChar::Separator_Line: return QCoreApplication::translate("KCharSelectData", "Separator, Line");
case QChar::Separator_Paragraph: return QCoreApplication::translate("KCharSelectData", "Separator, Paragraph");
case QChar::Separator_Space: return QCoreApplication::translate("KCharSelectData", "Separator, Space");
default: return QCoreApplication::translate("KCharSelectData", "Unknown");
}
}
QVector KCharSelectData::find(const QString &needle)
{
QSet result;
QVector returnRes;
QString simplified = needle.simplified();
QStringList searchStrings;
QRegularExpression octalExp(QStringLiteral("^\\\\[0-7][0-7\\\\]*$"));
QRegularExpressionMatch match = octalExp.match(simplified);
if (match.hasMatch()) {
// search for C octal escaped UTF-8
QByteArray utf8;
int byte = -1;
for (int i = 0; i <= simplified.length(); ++i) {
int c = simplified.at(i).unicode();
if (c >= '0' && c <= '7') {
byte = 8 * byte + c - '0';
} else if (byte == -1) {
byte = 0;
} else if (byte >= 0x00 && byte <= 0xFF) {
utf8.append((char) byte);
byte = 0;
}
}
simplified = QString::fromUtf8(utf8);
}
if (simplified.length() <= 2) {
QVector ucs4 = simplified.toUcs4();
if (ucs4.size() == 1) {
// search for hex representation of the character
searchStrings = QStringList(formatCode(ucs4.at(0)));
}
} else {
searchStrings = splitString(simplified);
}
if (searchStrings.count() == 0) {
return returnRes;
}
QRegularExpression hexExp(QStringLiteral("^(|u\\+|U\\+|0x|0X)([A-Fa-f0-9]{4,5})$"));
foreach (const QString &s, searchStrings) {
QRegularExpressionMatch match = hexExp.match(s);
if (match.hasMatch()) {
- returnRes.append(match.captured(2).toInt(0, 16));
+ returnRes.append(match.captured(2).toInt(nullptr, 16));
// search for "1234" instead of "0x1234"
if (s.length() == 6 || s.length() == 7) {
searchStrings[searchStrings.indexOf(s)] = match.captured(2);
}
}
// try to parse string as decimal number
bool ok;
int unicode = s.toInt(&ok);
if (ok && unicode >= 0 && unicode <= QChar::LastValidCodePoint) {
returnRes.append(unicode);
}
}
bool firstSubString = true;
foreach (const QString &s, searchStrings) {
QSet partResult = getMatchingChars(s.toLower());
if (firstSubString) {
result = partResult;
firstSubString = false;
} else {
result = result.intersect(partResult);
}
}
// remove results found by matching the code point to prevent duplicate results
// while letting these characters stay at the beginning
foreach (uint c, returnRes) {
result.remove(c);
}
QVector sortedResult;
sortedResult.reserve(result.count());
QSet::const_iterator it = result.begin();
const QSet::const_iterator end = result.end();
for ( ; it != end ; ++it ) {
sortedResult.append(*it);
}
qSort(sortedResult);
returnRes += sortedResult;
return returnRes;
}
QSet KCharSelectData::getMatchingChars(const QString &s)
{
if (dataFile.isEmpty()) {
return QSet();
}
futureIndex.waitForFinished();
const Index index = futureIndex;
Index::const_iterator pos = index.lowerBound(s);
QSet result;
while (pos != index.constEnd() && pos.key().startsWith(s)) {
foreach (quint16 c, pos.value()) {
result.insert(mapDataBaseToCodePoint(c));
}
++pos;
}
return result;
}
QStringList KCharSelectData::splitString(const QString &s)
{
QStringList result;
int start = 0;
int end = 0;
int length = s.length();
while (end < length) {
while (end < length && (s[end].isLetterOrNumber() || s[end] == QLatin1Char('+'))) {
end++;
}
if (start != end) {
result.append(s.mid(start, end - start));
}
start = end;
while (end < length && !(s[end].isLetterOrNumber() || s[end] == QLatin1Char('+'))) {
end++;
start++;
}
}
return result;
}
void KCharSelectData::appendToIndex(Index *index, quint16 unicode, const QString &s)
{
const QStringList strings = splitString(s);
foreach (const QString &s, strings) {
(*index)[s.toLower()].append(unicode);
}
}
Index KCharSelectData::createIndex(const QByteArray &dataFile)
{
Index i;
// character names
const uchar *udata = reinterpret_cast(dataFile.constData());
const char *data = dataFile.constData();
const quint32 nameOffsetBegin = qFromLittleEndian(udata + 4);
const quint32 nameOffsetEnd = qFromLittleEndian(udata + 8);
int max = ((nameOffsetEnd - nameOffsetBegin) / 6) - 1;
for (int pos = 0; pos <= max; pos++) {
const quint16 unicode = qFromLittleEndian(udata + nameOffsetBegin + pos * 6);
quint32 offset = qFromLittleEndian(udata + nameOffsetBegin + pos * 6 + 2);
appendToIndex(&i, unicode, QString::fromUtf8(data + offset + 1));
}
// details
const quint32 detailsOffsetBegin = qFromLittleEndian(udata + 12);
const quint32 detailsOffsetEnd = qFromLittleEndian(udata + 16);
max = ((detailsOffsetEnd - detailsOffsetBegin) / 27) - 1;
for (int pos = 0; pos <= max; pos++) {
const quint16 unicode = qFromLittleEndian(udata + detailsOffsetBegin + pos * 27);
// aliases
const quint8 aliasCount = * (quint8 *)(udata + detailsOffsetBegin + pos * 27 + 6);
quint32 aliasOffset = qFromLittleEndian(udata + detailsOffsetBegin + pos * 27 + 2);
for (int j = 0; j < aliasCount; j++) {
appendToIndex(&i, unicode, QString::fromUtf8(data + aliasOffset));
aliasOffset += strlen(data + aliasOffset) + 1;
}
// notes
const quint8 notesCount = * (quint8 *)(udata + detailsOffsetBegin + pos * 27 + 11);
quint32 notesOffset = qFromLittleEndian(udata + detailsOffsetBegin + pos * 27 + 7);
for (int j = 0; j < notesCount; j++) {
appendToIndex(&i, unicode, QString::fromUtf8(data + notesOffset));
notesOffset += strlen(data + notesOffset) + 1;
}
// approximate equivalents
const quint8 apprCount = * (quint8 *)(udata + detailsOffsetBegin + pos * 27 + 16);
quint32 apprOffset = qFromLittleEndian(udata + detailsOffsetBegin + pos * 27 + 12);
for (int j = 0; j < apprCount; j++) {
appendToIndex(&i, unicode, QString::fromUtf8(data + apprOffset));
apprOffset += strlen(data + apprOffset) + 1;
}
// equivalents
const quint8 equivCount = * (quint8 *)(udata + detailsOffsetBegin + pos * 27 + 21);
quint32 equivOffset = qFromLittleEndian(udata + detailsOffsetBegin + pos * 27 + 17);
for (int j = 0; j < equivCount; j++) {
appendToIndex(&i, unicode, QString::fromUtf8(data + equivOffset));
equivOffset += strlen(data + equivOffset) + 1;
}
// see also - convert to string (hex)
const quint8 seeAlsoCount = * (quint8 *)(udata + detailsOffsetBegin + pos * 27 + 26);
quint32 seeAlsoOffset = qFromLittleEndian(udata + detailsOffsetBegin + pos * 27 + 22);
for (int j = 0; j < seeAlsoCount; j++) {
quint16 seeAlso = qFromLittleEndian (udata + seeAlsoOffset);
appendToIndex(&i, unicode, formatCode(seeAlso, 4, QString()));
equivOffset += strlen(data + equivOffset) + 1;
}
}
// unihan data
// temporary disabled due to the huge amount of data
// const quint32 unihanOffsetBegin = qFromLittleEndian(udata+36);
// const quint32 unihanOffsetEnd = dataFile.size();
// max = ((unihanOffsetEnd - unihanOffsetBegin) / 30) - 1;
//
// for (int pos = 0; pos <= max; pos++) {
// const quint16 unicode = qFromLittleEndian(udata + unihanOffsetBegin + pos*30);
// for(int j = 0; j < 7; j++) {
// quint32 offset = qFromLittleEndian(udata + unihanOffsetBegin + pos*30 + 2 + j*4);
// if(offset != 0) {
// appendToIndex(&i, unicode, QString::fromUtf8(data + offset));
// }
// }
// }
return i;
}
diff --git a/src/kcollapsiblegroupbox.h b/src/kcollapsiblegroupbox.h
index 1567a3b..f4eb8b8 100644
--- a/src/kcollapsiblegroupbox.h
+++ b/src/kcollapsiblegroupbox.h
@@ -1,120 +1,120 @@
/*
* This file is part of the KDE project
* Copyright (C) 2015 David Edmundson
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef KCOLLAPSIBLEGROUPBOX_H
#define KCOLLAPSIBLEGROUPBOX_H
#include
#include
class KCollapsibleGroupBoxPrivate;
/**
* @class KCollapsibleGroupBox
*
* A groupbox featuring a clickable header and arrow indicator that can be
* expanded and collapsed to reveal the contents.
*
* When expanded, the widget will resize to fit the sizeHint of child items.
*
* @since 5.16
*/
class KWIDGETSADDONS_EXPORT KCollapsibleGroupBox : public QWidget
{
Q_OBJECT
Q_PROPERTY(QString title READ title WRITE setTitle NOTIFY titleChanged)
Q_PROPERTY(bool expanded READ isExpanded WRITE setExpanded NOTIFY expandedChanged)
public:
- explicit KCollapsibleGroupBox(QWidget *parent = 0);
+ explicit KCollapsibleGroupBox(QWidget *parent = nullptr);
virtual ~KCollapsibleGroupBox();
/**
* Set the title that will be permanently shown at the top of the collapsing box
* Mnemonics are supported
*/
void setTitle(const QString &title);
/**
* The title
*/
QString title() const;
/**
* Set whether contents are shown
*
* The default is false until the user clicks
*/
void setExpanded(bool expanded);
/**
* Whether contents are shown
* During animations, this will reflect the target state at the end of the animation
*/
bool isExpanded() const;
QSize sizeHint() const Q_DECL_OVERRIDE;
QSize minimumSizeHint() const Q_DECL_OVERRIDE;
public Q_SLOTS:
/**
* Expands if collapsed and vice versa
*/
void toggle();
/**
* Equivalent to setExpanded(true)
*/
void expand();
/**
* Equivalent to setExpanded(false)
*/
void collapse();
Q_SIGNALS:
/**
* Emitted when the title is changed
*/
void titleChanged();
/**
* Emitted when the widget expands or collapsed
*/
void expandedChanged();
protected:
void paintEvent(QPaintEvent*) Q_DECL_OVERRIDE;
bool event(QEvent*) Q_DECL_OVERRIDE;
void mousePressEvent(QMouseEvent*) Q_DECL_OVERRIDE;
void mouseMoveEvent(QMouseEvent*) Q_DECL_OVERRIDE;
void leaveEvent(QEvent*) Q_DECL_OVERRIDE;
void keyPressEvent(QKeyEvent*) Q_DECL_OVERRIDE;
void resizeEvent(QResizeEvent*) Q_DECL_OVERRIDE;
private:
KCollapsibleGroupBoxPrivate *const d;
Q_DISABLE_COPY(KCollapsibleGroupBox)
};
#endif
diff --git a/src/kcolorbutton.cpp b/src/kcolorbutton.cpp
index 3db3c6a..e5cb5e7 100644
--- a/src/kcolorbutton.cpp
+++ b/src/kcolorbutton.cpp
@@ -1,335 +1,335 @@
/* This file is part of the KDE libraries
Copyright (C) 1997 Martin Jones (mjones@kde.org)
Copyright (C) 1999 Cristian Tibirna (ctibirna@kde.org)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "kcolorbutton.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
class KColorButton::KColorButtonPrivate
{
public:
KColorButtonPrivate(KColorButton *q);
void _k_chooseColor();
void _k_colorChosen();
KColorButton *q;
QColor m_defaultColor;
bool m_bdefaultColor : 1;
bool m_alphaChannel : 1;
QColor col;
QPoint mPos;
QPointer dialogPtr;
void initStyleOption(QStyleOptionButton *opt) const;
};
/////////////////////////////////////////////////////////////////////
// Functions duplicated from KColorMimeData
// Should be kept in sync
void _k_populateMimeData(QMimeData *mimeData, const QColor &color)
{
mimeData->setColorData(color);
mimeData->setText(color.name());
}
bool _k_canDecode(const QMimeData *mimeData)
{
if (mimeData->hasColor()) {
return true;
}
if (mimeData->hasText()) {
const QString colorName = mimeData->text();
if ((colorName.length() >= 4) && (colorName[0] == QLatin1Char('#'))) {
return true;
}
}
return false;
}
QColor _k_fromMimeData(const QMimeData *mimeData)
{
if (mimeData->hasColor()) {
return mimeData->colorData().value();
}
if (_k_canDecode(mimeData)) {
return QColor(mimeData->text());
}
return QColor();
}
QDrag *_k_createDrag(const QColor &color, QObject *dragsource)
{
QDrag *drag = new QDrag(dragsource);
QMimeData *mime = new QMimeData;
_k_populateMimeData(mime, color);
drag->setMimeData(mime);
QPixmap colorpix(25, 20);
colorpix.fill(color);
QPainter p(&colorpix);
p.setPen(Qt::black);
p.drawRect(0, 0, 24, 19);
p.end();
drag->setPixmap(colorpix);
drag->setHotSpot(QPoint(-5, -7));
return drag;
}
/////////////////////////////////////////////////////////////////////
KColorButton::KColorButtonPrivate::KColorButtonPrivate(KColorButton *q)
: q(q)
{
m_bdefaultColor = false;
m_alphaChannel = false;
q->setAcceptDrops(true);
connect(q, SIGNAL(clicked()), q, SLOT(_k_chooseColor()));
}
KColorButton::KColorButton(QWidget *parent)
: QPushButton(parent)
, d(new KColorButtonPrivate(this))
{
}
KColorButton::KColorButton(const QColor &c, QWidget *parent)
: QPushButton(parent)
, d(new KColorButtonPrivate(this))
{
d->col = c;
}
KColorButton::KColorButton(const QColor &c, const QColor &defaultColor, QWidget *parent)
: QPushButton(parent)
, d(new KColorButtonPrivate(this))
{
d->col = c;
setDefaultColor(defaultColor);
}
KColorButton::~KColorButton()
{
delete d;
}
QColor KColorButton::color() const
{
return d->col;
}
void KColorButton::setColor(const QColor &c)
{
if (d->col != c) {
d->col = c;
update();
emit changed(d->col);
}
}
void KColorButton::setAlphaChannelEnabled(bool alpha)
{
d->m_alphaChannel = alpha;
}
bool KColorButton::isAlphaChannelEnabled() const
{
return d->m_alphaChannel;
}
QColor KColorButton::defaultColor() const
{
return d->m_defaultColor;
}
void KColorButton::setDefaultColor(const QColor &c)
{
d->m_bdefaultColor = c.isValid();
d->m_defaultColor = c;
}
void KColorButton::KColorButtonPrivate::initStyleOption(QStyleOptionButton *opt) const
{
opt->initFrom(q);
opt->state |= q->isDown() ? QStyle::State_Sunken : QStyle::State_Raised;
opt->features = QStyleOptionButton::None;
if (q->isDefault()) {
opt->features |= QStyleOptionButton::DefaultButton;
}
opt->text.clear();
opt->icon = QIcon();
}
void KColorButton::paintEvent(QPaintEvent *)
{
QPainter painter(this);
QStyle *style = QWidget::style();
//First, we need to draw the bevel.
QStyleOptionButton butOpt;
d->initStyleOption(&butOpt);
style->drawControl(QStyle::CE_PushButtonBevel, &butOpt, &painter, this);
//OK, now we can muck around with drawing out pretty little color box
//First, sort out where it goes
QRect labelRect = style->subElementRect(QStyle::SE_PushButtonContents,
&butOpt, this);
int shift = style->pixelMetric(QStyle::PM_ButtonMargin, &butOpt, this) / 2;
labelRect.adjust(shift, shift, -shift, -shift);
int x, y, w, h;
labelRect.getRect(&x, &y, &w, &h);
if (isChecked() || isDown()) {
x += style->pixelMetric(QStyle::PM_ButtonShiftHorizontal, &butOpt, this);
y += style->pixelMetric(QStyle::PM_ButtonShiftVertical, &butOpt, this);
}
QColor fillCol = isEnabled() ? d->col : palette().color(backgroundRole());
- qDrawShadePanel(&painter, x, y, w, h, palette(), true, 1, NULL);
+ qDrawShadePanel(&painter, x, y, w, h, palette(), true, 1, nullptr);
if (fillCol.isValid()) {
const QRect rect(x + 1, y + 1, w - 2, h - 2);
if (fillCol.alpha() < 255) {
QPixmap chessboardPattern(16, 16);
QPainter patternPainter(&chessboardPattern);
patternPainter.fillRect(0, 0, 8, 8, Qt::black);
patternPainter.fillRect(8, 8, 8, 8, Qt::black);
patternPainter.fillRect(0, 8, 8, 8, Qt::white);
patternPainter.fillRect(8, 0, 8, 8, Qt::white);
patternPainter.end();
painter.fillRect(rect, QBrush(chessboardPattern));
}
painter.fillRect(rect, fillCol);
}
if (hasFocus()) {
QRect focusRect = style->subElementRect(QStyle::SE_PushButtonFocusRect, &butOpt, this);
QStyleOptionFocusRect focusOpt;
focusOpt.init(this);
focusOpt.rect = focusRect;
focusOpt.backgroundColor = palette().background().color();
style->drawPrimitive(QStyle::PE_FrameFocusRect, &focusOpt, &painter, this);
}
}
QSize KColorButton::sizeHint() const
{
QStyleOptionButton opt;
d->initStyleOption(&opt);
return style()->sizeFromContents(QStyle::CT_PushButton, &opt, QSize(40, 15), this).
expandedTo(QApplication::globalStrut());
}
QSize KColorButton::minimumSizeHint() const
{
QStyleOptionButton opt;
d->initStyleOption(&opt);
return style()->sizeFromContents(QStyle::CT_PushButton, &opt, QSize(3, 3), this).
expandedTo(QApplication::globalStrut());
}
void KColorButton::dragEnterEvent(QDragEnterEvent *event)
{
event->setAccepted(_k_canDecode(event->mimeData()) && isEnabled());
}
void KColorButton::dropEvent(QDropEvent *event)
{
QColor c = _k_fromMimeData(event->mimeData());
if (c.isValid()) {
setColor(c);
}
}
void KColorButton::keyPressEvent(QKeyEvent *e)
{
int key = e->key() | e->modifiers();
if (QKeySequence::keyBindings(QKeySequence::Copy).contains(key)) {
QMimeData *mime = new QMimeData;
_k_populateMimeData(mime, color());
QApplication::clipboard()->setMimeData(mime, QClipboard::Clipboard);
} else if (QKeySequence::keyBindings(QKeySequence::Paste).contains(key)) {
QColor color = _k_fromMimeData(QApplication::clipboard()->mimeData(QClipboard::Clipboard));
setColor(color);
} else {
QPushButton::keyPressEvent(e);
}
}
void KColorButton::mousePressEvent(QMouseEvent *e)
{
d->mPos = e->pos();
QPushButton::mousePressEvent(e);
}
void KColorButton::mouseMoveEvent(QMouseEvent *e)
{
if ((e->buttons() & Qt::LeftButton) &&
(e->pos() - d->mPos).manhattanLength() > QApplication::startDragDistance()) {
_k_createDrag(color(), this)->start();
setDown(false);
}
}
void KColorButton::KColorButtonPrivate::_k_chooseColor()
{
QColorDialog *dialog = dialogPtr.data();
if (dialog) {
dialog->show();
dialog->raise();
dialog->activateWindow();
return;
}
dialog = new QColorDialog(q);
dialog->setCurrentColor(q->color());
dialog->setOption(QColorDialog::ShowAlphaChannel, m_alphaChannel);
dialog->setAttribute(Qt::WA_DeleteOnClose);
connect(dialog, SIGNAL(accepted()), q, SLOT(_k_colorChosen()));
dialogPtr = dialog;
dialog->show();
}
void KColorButton::KColorButtonPrivate::_k_colorChosen()
{
QColorDialog *dialog = dialogPtr.data();
if (!dialog) {
return;
}
if (dialog->selectedColor().isValid()) {
q->setColor(dialog->selectedColor());
} else if (m_bdefaultColor) {
q->setColor(m_defaultColor);
}
}
#include "moc_kcolorbutton.cpp"
diff --git a/src/kcolorbutton.h b/src/kcolorbutton.h
index 93902ba..6232e9a 100644
--- a/src/kcolorbutton.h
+++ b/src/kcolorbutton.h
@@ -1,123 +1,123 @@
/* This file is part of the KDE libraries
Copyright (C) 1997 Martin Jones (mjones@kde.org)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef KCOLORBUTTON_H
#define KCOLORBUTTON_H
#include
#include
class KColorButtonPrivate;
/**
* @short A pushbutton to display or allow user selection of a color.
*
* This widget can be used to display or allow user selection of a color.
*
* @see QColorDialog
*
* \image html kcolorbutton.png "KDE Color Button"
*/
class KWIDGETSADDONS_EXPORT KColorButton : public QPushButton
{
Q_OBJECT
Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY changed USER true)
Q_PROPERTY(QColor defaultColor READ defaultColor WRITE setDefaultColor)
Q_PROPERTY(bool alphaChannelEnabled READ isAlphaChannelEnabled WRITE setAlphaChannelEnabled)
public:
/**
* Creates a color button.
*/
- explicit KColorButton(QWidget *parent = 0);
+ explicit KColorButton(QWidget *parent = nullptr);
/**
* Creates a color button with an initial color @p c.
*/
- explicit KColorButton(const QColor &c, QWidget *parent = 0);
+ explicit KColorButton(const QColor &c, QWidget *parent = nullptr);
/**
* Creates a color button with an initial color @p c and default color @p defaultColor.
*/
- KColorButton(const QColor &c, const QColor &defaultColor, QWidget *parent = 0);
+ KColorButton(const QColor &c, const QColor &defaultColor, QWidget *parent = nullptr);
virtual ~KColorButton();
/**
* Returns the currently chosen color.
*/
QColor color() const;
/**
* Sets the current color to @p c.
*/
void setColor(const QColor &c);
/**
* When set to true, allow the user to change the alpha component
* of the color. The default value is false.
* @since 4.5
*/
void setAlphaChannelEnabled(bool alpha);
/**
* Returns true if the user is allowed to change the alpha component.
* @since 4.5
*/
bool isAlphaChannelEnabled() const;
/**
* Returns the default color or an invalid color
* if no default color is set.
*/
QColor defaultColor() const;
/**
* Sets the default color to @p c.
*/
void setDefaultColor(const QColor &c);
QSize sizeHint() const Q_DECL_OVERRIDE;
QSize minimumSizeHint() const Q_DECL_OVERRIDE;
Q_SIGNALS:
/**
* Emitted when the color of the widget
* is changed, either with setColor() or via user selection.
*/
void changed(const QColor &newColor);
protected:
void paintEvent(QPaintEvent *pe) Q_DECL_OVERRIDE;
void dragEnterEvent(QDragEnterEvent *) Q_DECL_OVERRIDE;
void dropEvent(QDropEvent *) Q_DECL_OVERRIDE;
void mousePressEvent(QMouseEvent *e) Q_DECL_OVERRIDE;
void mouseMoveEvent(QMouseEvent *e) Q_DECL_OVERRIDE;
void keyPressEvent(QKeyEvent *e) Q_DECL_OVERRIDE;
private:
class KColorButtonPrivate;
KColorButtonPrivate *const d;
Q_PRIVATE_SLOT(d, void _k_chooseColor())
Q_PRIVATE_SLOT(d, void _k_colorChosen())
};
#endif
diff --git a/src/kcolorcombo.cpp b/src/kcolorcombo.cpp
index 92bf403..91bff87 100644
--- a/src/kcolorcombo.cpp
+++ b/src/kcolorcombo.cpp
@@ -1,354 +1,354 @@
/* This file is part of the KDE libraries
Copyright (C) 1997 Martin Jones (mjones@kde.org)
Copyright (C) 2007 Pino Toscano (pino@kde.org)
Copyright (c) 2007 David Jarvie (software@astrojar.org.uk)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "kcolorcombo.h"
#include
#include
#include
#include
class KColorComboDelegate : public QAbstractItemDelegate
{
public:
enum ItemRoles {
ColorRole = Qt::UserRole + 1
};
enum LayoutMetrics {
FrameMargin = 3
};
- KColorComboDelegate(QObject *parent = 0);
+ KColorComboDelegate(QObject *parent = nullptr);
virtual ~KColorComboDelegate();
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
};
static QBrush k_colorcombodelegate_brush(const QModelIndex &index, int role)
{
QBrush brush;
QVariant v = index.data(role);
if (v.type() == QVariant::Brush) {
brush = v.value();
} else if (v.type() == QVariant::Color) {
brush = QBrush(v.value());
}
return brush;
}
KColorComboDelegate::KColorComboDelegate(QObject *parent)
: QAbstractItemDelegate(parent)
{
}
KColorComboDelegate::~KColorComboDelegate()
{
}
void KColorComboDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
// background
QColor innercolor(Qt::white);
bool isSelected = (option.state & QStyle::State_Selected);
bool paletteBrush = (k_colorcombodelegate_brush(index, Qt::BackgroundRole).style() == Qt::NoBrush);
if (isSelected) {
innercolor = option.palette.color(QPalette::Highlight);
} else {
innercolor = option.palette.color(QPalette::Base);
}
// highlight selected item
QStyleOptionViewItem opt(option);
opt.showDecorationSelected = true;
QStyle *style = opt.widget ? opt.widget->style() : QApplication::style();
style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, opt.widget);
QRect innerrect = option.rect.adjusted(FrameMargin, FrameMargin, -FrameMargin, -FrameMargin);
// inner color
QVariant cv = index.data(ColorRole);
if (cv.type() == QVariant::Color) {
QColor tmpcolor = cv.value();
if (tmpcolor.isValid()) {
innercolor = tmpcolor;
paletteBrush = false;
painter->setPen(Qt::transparent);
painter->setBrush(innercolor);
QPainter::RenderHints tmpHint = painter->renderHints();
painter->setRenderHint(QPainter::Antialiasing);
painter->drawRoundedRect(innerrect, 2, 2);
painter->setRenderHints(tmpHint);
painter->setBrush(Qt::NoBrush);
}
}
// text
QVariant tv = index.data(Qt::DisplayRole);
if (tv.type() == QVariant::String) {
QString text = tv.toString();
QColor textColor;
if (paletteBrush) {
if (isSelected) {
textColor = option.palette.color(QPalette::HighlightedText);
} else {
textColor = option.palette.color(QPalette::Text);
}
} else {
int unused, v;
innercolor.getHsv(&unused, &unused, &v);
if (v > 128) {
textColor = Qt::black;
} else {
textColor = Qt::white;
}
}
painter->setPen(textColor);
painter->drawText(innerrect.adjusted(1, 1, -1, -1), text);
}
}
QSize KColorComboDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
Q_UNUSED(index)
// the width does not matter, as the view will always use the maximum width available
return QSize(100, option.fontMetrics.height() + 2 * FrameMargin);
}
static const uchar standardPalette[][4] = {
{ 255, 255, 255 }, // white
{ 192, 192, 192 }, // light gray
{ 160, 160, 160 }, // gray
{ 128, 128, 128 }, // dark gray
{ 0, 0, 0 }, // black
{ 255, 128, 128 }, //light red
{ 255, 192, 128 }, //light orange
{ 255, 255, 128 }, //light yellow
{ 128, 255, 128 }, //light green
{ 128, 255, 255 }, //cyan blue
{ 128, 128, 255 }, //light blue
{ 255, 128, 255 }, //light violet
{ 255, 0, 0 }, //red
{ 255, 128, 0 }, //orange
{ 255, 255, 0 }, //yellow
{ 0, 255, 0 }, //green
{ 0, 255, 255 }, //light blue
{ 0, 0, 255 }, //blue
{ 255, 0, 255 }, //violet
{ 128, 0, 0 }, //dark red
{ 128, 64, 0 }, //dark orange
{ 128, 128, 0 }, //dark yellow
{ 0, 128, 0 }, //dark green
{ 0, 128, 128 }, //dark light blue
{ 0, 0, 128 }, //dark blue
{ 128, 0, 128 } //dark violet
};
#define STANDARD_PALETTE_SIZE (int(sizeof(standardPalette) / sizeof(*standardPalette)))
static inline QColor standardColor(int i)
{
const uchar *entry = standardPalette[i];
return QColor(entry[0], entry[1], entry[2]);
}
class KColorComboPrivate
{
public:
KColorComboPrivate(KColorCombo *qq);
void addColors();
void setCustomColor(const QColor &color, bool lookupInPresets = true);
// slots
void _k_slotActivated(int index);
void _k_slotHighlighted(int index);
KColorCombo *q;
QList colorList;
QColor customColor;
QColor internalcolor;
};
KColorComboPrivate::KColorComboPrivate(KColorCombo *qq)
: q(qq), customColor(Qt::white)
{
}
void KColorComboPrivate::setCustomColor(const QColor &color, bool lookupInPresets)
{
if (lookupInPresets) {
if (colorList.isEmpty()) {
for (int i = 0; i < STANDARD_PALETTE_SIZE; ++i) {
if (standardColor(i) == color) {
q->setCurrentIndex(i + 1);
internalcolor = color;
return;
}
}
} else {
int i = colorList.indexOf(color);
if (i >= 0) {
q->setCurrentIndex(i + 1);
internalcolor = color;
return;
}
}
}
internalcolor = color;
customColor = color;
q->setItemData(0, customColor, KColorComboDelegate::ColorRole);
}
KColorCombo::KColorCombo(QWidget *parent)
: QComboBox(parent), d(new KColorComboPrivate(this))
{
setItemDelegate(new KColorComboDelegate(this));
d->addColors();
connect(this, SIGNAL(activated(int)), SLOT(_k_slotActivated(int)));
connect(this, SIGNAL(highlighted(int)), SLOT(_k_slotHighlighted(int)));
// select the white color
setCurrentIndex(1);
d->_k_slotActivated(1);
setMaxVisibleItems(13);
}
KColorCombo::~KColorCombo()
{
delete d;
}
void KColorCombo::setColors(const QList &colors)
{
clear();
d->colorList = colors;
d->addColors();
}
QList KColorCombo::colors() const
{
if (d->colorList.isEmpty()) {
QList list;
for (int i = 0; i < STANDARD_PALETTE_SIZE; ++i) {
list += standardColor(i);
}
return list;
} else {
return d->colorList;
}
}
void KColorCombo::setColor(const QColor &col)
{
if (!col.isValid()) {
return;
}
if (count() == 0) {
d->addColors();
}
d->setCustomColor(col, true);
}
QColor KColorCombo::color() const
{
return d->internalcolor;
}
bool KColorCombo::isCustomColor() const
{
return d->internalcolor == d->customColor;
}
void KColorCombo::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
QStylePainter painter(this);
painter.setPen(palette().color(QPalette::Text));
QStyleOptionComboBox opt;
initStyleOption(&opt);
painter.drawComplexControl(QStyle::CC_ComboBox, opt);
QRect frame = style()->subControlRect(QStyle::CC_ComboBox, &opt, QStyle::SC_ComboBoxEditField, this);
painter.setRenderHint(QPainter::Antialiasing);
painter.setPen(Qt::transparent);
painter.setBrush(QBrush(d->internalcolor));
painter.drawRoundedRect(frame.adjusted(1, 1, -1, -1), 2, 2);
}
void KColorCombo::showEmptyList()
{
clear();
}
void KColorComboPrivate::_k_slotActivated(int index)
{
if (index == 0) {
QColor c = QColorDialog::getColor(customColor, q);
if (c.isValid()) {
customColor = c;
setCustomColor(customColor, false);
}
} else if (colorList.isEmpty()) {
internalcolor = standardColor(index - 1);
} else {
internalcolor = colorList[index - 1];
}
emit q->activated(internalcolor);
}
void KColorComboPrivate::_k_slotHighlighted(int index)
{
if (index == 0) {
internalcolor = customColor;
} else if (colorList.isEmpty()) {
internalcolor = standardColor(index - 1);
} else {
internalcolor = colorList[index - 1];
}
emit q->highlighted(internalcolor);
}
void KColorComboPrivate::addColors()
{
q->addItem(KColorCombo::tr("Custom...", "Custom color"));
if (colorList.isEmpty()) {
for (int i = 0; i < STANDARD_PALETTE_SIZE; ++i) {
q->addItem(QString());
q->setItemData(i + 1, standardColor(i), KColorComboDelegate::ColorRole);
}
} else {
for (int i = 0, count = colorList.count(); i < count; ++i) {
q->addItem(QString());
q->setItemData(i + 1, colorList[i], KColorComboDelegate::ColorRole);
}
}
}
#include "moc_kcolorcombo.cpp"
diff --git a/src/kcolorcombo.h b/src/kcolorcombo.h
index 98fb0eb..e437e87 100644
--- a/src/kcolorcombo.h
+++ b/src/kcolorcombo.h
@@ -1,115 +1,115 @@
/* This file is part of the KDE libraries
Copyright (C) 1997 Martin Jones (mjones@kde.org)
Copyright (c) 2007 David Jarvie (software@astrojar.org.uk)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
//-----------------------------------------------------------------------------
// KDE color selection combo box
// layout management added Oct 1997 by Mario Weilguni
//
#ifndef KCOLORCOMBO_H
#define KCOLORCOMBO_H
#include
#include
#include
class KColorComboPrivate;
/**
* Combobox for colors.
*
* The combobox provides some preset colors to be selected, and an entry to
* select a custom color using a color dialog.
*
* \image html kcolorcombo.png "KDE Color Combo Box"
*/
class KWIDGETSADDONS_EXPORT KColorCombo : public QComboBox
{
Q_OBJECT
Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY activated USER true)
Q_PROPERTY(QList colors READ colors WRITE setColors)
public:
/**
* Constructs a color combo box.
*/
- explicit KColorCombo(QWidget *parent = 0);
+ explicit KColorCombo(QWidget *parent = nullptr);
~KColorCombo();
/**
* Selects the color @p col.
*/
void setColor(const QColor &col);
/**
* Returns the currently selected color.
**/
QColor color() const;
/**
* Find whether the currently selected color is a custom color selected
* using a color dialog.
**/
bool isCustomColor() const;
/**
* Set a custom list of colors to choose from, in place of the standard
* list.
* @param cols list of colors. If empty, the selection list reverts to
* the standard list.
**/
void setColors(const QList &colors);
/**
* Return the list of colors available for selection.
* @return list of colors
**/
QList colors() const;
/**
* Clear the color list and don't show it, till the next setColor() call
**/
void showEmptyList();
Q_SIGNALS:
/**
* Emitted when a new color box has been selected.
*/
void activated(const QColor &col);
/**
* Emitted when a new item has been highlighted.
*/
void highlighted(const QColor &col);
protected:
void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE;
private:
friend class KColorComboPrivate;
KColorComboPrivate *const d;
Q_DISABLE_COPY(KColorCombo)
Q_PRIVATE_SLOT(d, void _k_slotActivated(int))
Q_PRIVATE_SLOT(d, void _k_slotHighlighted(int))
};
#endif // KCOLORCOMBO_H
diff --git a/src/kcolumnresizer.h b/src/kcolumnresizer.h
index 6855f57..83aeb6d 100644
--- a/src/kcolumnresizer.h
+++ b/src/kcolumnresizer.h
@@ -1,126 +1,126 @@
/* This file is part of the KDE frameworks
*
* Copyright (c) 2014 Aurélien Gâteau
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#ifndef KCOLUMNRESIZER_H
#define KCOLUMNRESIZER_H
#include
#include
#include
class QEvent;
class QGridLayout;
class QLayout;
class QWidget;
class KColumnResizerPrivate;
/**
* @short Maintains consistent column sizes across layouts
*
* KColumnResizer is a helper class which can force columns of different layouts
* to keep the same width. It is useful to keep label columns consistent.
*
* It works with QGridLayout and QFormLayout.
*
* @image html kcolumnresizer.png "left: without KColumnResizer - right: with KColumnResizer"
*
* Here is a typical example:
*
* @code
* void Window::createWidgets()
* {
* QVBoxLayout *layout = new QVBoxLayout(this);
*
* QGroupBox *box1 = new QGroupBox();
* // Fill box1
* // ...
* layout->addWidget(box1);
*
* QGroupBox *box2 = new QGroupBox();
* // Fill box2
* // ...
* layout->addWidget(box2);
*
* KColumnResizer *resizer = new KColumnResizer(this);
* resizer->addWidgetsFromLayout(box1->layout(), 0);
* resizer->addWidgetsFromLayout(box2->layout(), 0);
* }
* @endcode
*
* In this example box1 and box2 children can be organized using QGridLayout or
* QFormLayout, resizer will ensure the first columns of the two QGroupBox stay
* the same width.
*
* @author Aurélien Gâteau
*
* @since 5.1
*/
class KWIDGETSADDONS_EXPORT KColumnResizer : public QObject
{
Q_OBJECT
public:
/**
* Constructs a KColumnResizer.
*/
- explicit KColumnResizer(QObject *parent = 0);
+ explicit KColumnResizer(QObject *parent = nullptr);
~KColumnResizer();
/**
* Add all widgets from @p layout which are in column @p column to the list
* of widgets to manage.
*
* @param layout The layout containing the widgets to add. KColumnResizer
* supports QGridLayout and QFormLayout.
* @param column The column number which contains the widgets. If layout is
* a QFormLayout, column should not be higher than QFormLayout::SpanningRole
*/
void addWidgetsFromLayout(QLayout *layout, int column = 0);
/**
* Add a single widget to the list of widgets whose width is monitored.
*
* It is more common to use addWidgetsFromLayout(), but adding single
* widgets can be useful if you want to keep a single button the same width
* as a column in a layout.
*
* @param widget The widget to add
*/
void addWidget(QWidget *widget);
/**
* Remove a widget previously added by addWidget or addWidgetsFromLayout.
*
* @param widget The widget to remove
*/
void removeWidget(QWidget *widget);
protected:
bool eventFilter(QObject *, QEvent *event) Q_DECL_OVERRIDE;
private:
KColumnResizerPrivate *const d;
Q_DISABLE_COPY(KColumnResizer)
Q_PRIVATE_SLOT(d, void updateWidth())
};
#endif /* KCOLUMNRESIZER_H */
diff --git a/src/kcursor.cpp b/src/kcursor.cpp
index 22bff24..41fea34 100644
--- a/src/kcursor.cpp
+++ b/src/kcursor.cpp
@@ -1,274 +1,274 @@
/* This file is part of the KDE libraries
Copyright (C) 1998 Kurt Granroth (granroth@kde.org)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "kcursor.h"
#include "kcursor_p.h"
#include
#include
#include
#include
#include
#include
void KCursor::setAutoHideCursor(QWidget *w, bool enable,
bool customEventFilter)
{
KCursorPrivate::self()->setAutoHideCursor(w, enable, customEventFilter);
}
void KCursor::autoHideEventFilter(QObject *o, QEvent *e)
{
KCursorPrivate::self()->eventFilter(o, e);
}
void KCursor::setHideCursorDelay(int ms)
{
KCursorPrivate::self()->hideCursorDelay = ms;
}
int KCursor::hideCursorDelay()
{
return KCursorPrivate::self()->hideCursorDelay;
}
// **************************************************************************
KCursorPrivateAutoHideEventFilter::KCursorPrivateAutoHideEventFilter(QWidget *widget)
: m_widget(widget)
, m_wasMouseTracking(m_widget->hasMouseTracking())
, m_isCursorHidden(false)
, m_isOwnCursor(false)
{
mouseWidget()->setMouseTracking(true);
connect(&m_autoHideTimer, &QTimer::timeout,
this, &KCursorPrivateAutoHideEventFilter::hideCursor);
}
KCursorPrivateAutoHideEventFilter::~KCursorPrivateAutoHideEventFilter()
{
- if (m_widget != NULL) {
+ if (m_widget != nullptr) {
mouseWidget()->setMouseTracking(m_wasMouseTracking);
}
}
void KCursorPrivateAutoHideEventFilter::resetWidget()
{
- m_widget = NULL;
+ m_widget = nullptr;
}
void KCursorPrivateAutoHideEventFilter::hideCursor()
{
m_autoHideTimer.stop();
if (m_isCursorHidden) {
return;
}
m_isCursorHidden = true;
QWidget *w = mouseWidget();
m_isOwnCursor = w->testAttribute(Qt::WA_SetCursor);
if (m_isOwnCursor) {
m_oldCursor = w->cursor();
}
w->setCursor(QCursor(Qt::BlankCursor));
}
void KCursorPrivateAutoHideEventFilter::unhideCursor()
{
m_autoHideTimer.stop();
if (!m_isCursorHidden) {
return;
}
m_isCursorHidden = false;
QWidget *w = mouseWidget();
if (w->cursor().shape() != Qt::BlankCursor) { // someone messed with the cursor already
return;
}
if (m_isOwnCursor) {
w->setCursor(m_oldCursor);
} else {
w->unsetCursor();
}
}
// The widget which gets mouse events, and that shows the cursor
// (that is the viewport, for a QAbstractScrollArea)
QWidget *KCursorPrivateAutoHideEventFilter::mouseWidget() const
{
QWidget *w = m_widget;
// Is w a QAbstractScrollArea ? Call setCursor on the viewport in that case.
QAbstractScrollArea *sv = qobject_cast(w);
if (sv) {
w = sv->viewport();
}
return w;
}
bool KCursorPrivateAutoHideEventFilter::eventFilter(QObject *o, QEvent *e)
{
Q_UNUSED(o);
// o is m_widget or its viewport
//Q_ASSERT( o == m_widget );
switch (e->type()) {
case QEvent::Leave:
case QEvent::FocusOut:
case QEvent::WindowDeactivate:
unhideCursor();
break;
case QEvent::KeyPress:
case QEvent::ShortcutOverride:
hideCursor();
break;
case QEvent::Enter:
case QEvent::FocusIn:
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
case QEvent::MouseButtonDblClick:
case QEvent::MouseMove:
case QEvent::Show:
case QEvent::Hide:
case QEvent::Wheel:
unhideCursor();
if (m_widget->hasFocus()) {
m_autoHideTimer.setSingleShot(true);
m_autoHideTimer.start(KCursorPrivate::self()->hideCursorDelay);
}
break;
default:
break;
}
return false;
}
-KCursorPrivate *KCursorPrivate::s_self = 0L;
+KCursorPrivate *KCursorPrivate::s_self = nullptr;
KCursorPrivate *KCursorPrivate::self()
{
if (!s_self) {
s_self = new KCursorPrivate;
}
// WABA: Don't delete KCursorPrivate, it serves no real purpose.
// Even worse it causes crashes because it seems to get deleted
// during ~QApplication and ~QApplication doesn't seem to like it
// when we delete a QCursor. No idea if that is a bug itself.
return s_self;
}
KCursorPrivate::KCursorPrivate()
{
hideCursorDelay = 5000; // 5s default value
enabled = true;
}
KCursorPrivate::~KCursorPrivate()
{
}
void KCursorPrivate::setAutoHideCursor(QWidget *w, bool enable, bool customEventFilter)
{
if (!w || !enabled) {
return;
}
- QWidget *viewport = 0;
+ QWidget *viewport = nullptr;
QAbstractScrollArea *sv = qobject_cast(w);
if (sv) {
viewport = sv->viewport();
}
if (enable) {
if (m_eventFilters.contains(w)) {
return;
}
KCursorPrivateAutoHideEventFilter *filter = new KCursorPrivateAutoHideEventFilter(w);
m_eventFilters.insert(w, filter);
if (viewport) {
m_eventFilters.insert(viewport, filter);
connect(viewport, &QObject::destroyed, this, &KCursorPrivate::slotViewportDestroyed);
}
if (!customEventFilter) {
w->installEventFilter(filter); // for key events
if (viewport) {
viewport->installEventFilter(filter); // for mouse events
}
}
connect(w, &QObject::destroyed,
this, &KCursorPrivate::slotWidgetDestroyed);
} else {
KCursorPrivateAutoHideEventFilter *filter = m_eventFilters.take(w);
- if (filter == 0) {
+ if (filter == nullptr) {
return;
}
w->removeEventFilter(filter);
if (viewport) {
m_eventFilters.remove(viewport);
disconnect(viewport, &QObject::destroyed, this, &KCursorPrivate::slotViewportDestroyed);
viewport->removeEventFilter(filter);
}
delete filter;
disconnect(w, &QObject::destroyed,
this, &KCursorPrivate::slotWidgetDestroyed);
}
}
bool KCursorPrivate::eventFilter(QObject *o, QEvent *e)
{
if (!enabled || e->type() == QEvent::ChildAdded) {
return false;
}
KCursorPrivateAutoHideEventFilter *filter = m_eventFilters.value(o);
- Q_ASSERT(filter != 0);
- if (filter == 0) {
+ Q_ASSERT(filter != nullptr);
+ if (filter == nullptr) {
return false;
}
return filter->eventFilter(o, e);
}
void KCursorPrivate::slotViewportDestroyed(QObject *o)
{
m_eventFilters.remove(o);
}
void KCursorPrivate::slotWidgetDestroyed(QObject *o)
{
KCursorPrivateAutoHideEventFilter *filter = m_eventFilters.take(o);
- Q_ASSERT(filter != 0);
+ Q_ASSERT(filter != nullptr);
filter->resetWidget(); // so that dtor doesn't access it
delete filter;
}
#include "moc_kcursor_p.cpp"
diff --git a/src/kdatecombobox.h b/src/kdatecombobox.h
index 3979600..b2c042a 100644
--- a/src/kdatecombobox.h
+++ b/src/kdatecombobox.h
@@ -1,311 +1,311 @@
/*
Copyright 2011 John Layt
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef KDATECOMBOBOX_H
#define KDATECOMBOBOX_H
#include
#include
#include
class KDateComboBoxPrivate;
class KWIDGETSADDONS_EXPORT KDateComboBox : public QComboBox
{
Q_OBJECT
Q_PROPERTY(QDate date READ date WRITE setDate NOTIFY dateChanged USER true)
Q_PROPERTY(QDate minimumDate READ minimumDate WRITE setMinimumDate RESET resetMinimumDate)
Q_PROPERTY(QDate maximumDate READ maximumDate WRITE setMaximumDate RESET resetMaximumDate)
Q_PROPERTY(Options options READ options WRITE setOptions)
public:
/**
* Options provided by the widget
* @see options()
* @see setOptions()
*/
enum Option {
EditDate = 0x0001, /**< Allow the user to manually edit the date in the combo line edit */
SelectDate = 0x0002, /**< Allow the user to select the date from a drop-down menu */
DatePicker = 0x0004, /**< Show a date picker in the drop-down */
DateKeywords = 0x0008, /**< Show date keywords in the drop-down */
WarnOnInvalid = 0x0010 /**< Show a warning on focus out if the date is invalid */
};
Q_DECLARE_FLAGS(Options, Option)
Q_FLAG(Options)
/**
* Create a new KDateComboBox widget
*
* By default the EditDate, SelectDate, DatePicker and DateKeywords options
* are enabled, the ShortDate format is used and the date is set to the
* current date.
*/
- explicit KDateComboBox(QWidget *parent = 0);
+ explicit KDateComboBox(QWidget *parent = nullptr);
/**
* Destroy the widget
*/
virtual ~KDateComboBox();
/**
* Return the currently selected date
*
* @return the currently selected date
*/
QDate date() const;
/**
* Return if the current user input is valid
*
* If the user input is null then it is not valid
*
* @see isNull()
* @return if the current user input is valid
*/
bool isValid() const;
/**
* Return if the current user input is null
*
* @see isValid()
* @return if the current user input is null
*/
bool isNull() const;
/**
* Return the currently set widget options
*
* @return the currently set widget options
*/
Options options() const;
/**
* Return the currently set date display format
*
* By default this is the Short Format
*
* @return the currently set date format
*/
QLocale::FormatType displayFormat() const;
/**
* Return the current minimum date
*
* @return the current minimum date
*/
QDate minimumDate() const;
/**
* Return the current maximum date
*
* @return the current maximum date
*/
QDate maximumDate() const;
/**
* Return the map of dates listed in the drop-down and their displayed
* string forms.
*
* @see setDateMap()
* @return the select date map
*/
QMap dateMap() const;
Q_SIGNALS:
/**
* Signal if the date has been manually entered or selected by the user.
*
* The returned date may be invalid.
*
* @param date the new date
*/
void dateEntered(const QDate &date);
/**
* Signal if the date has been changed either manually by the user
* or programatically.
*
* The returned date may be invalid.
*
* @param date the new date
*/
void dateChanged(const QDate &date);
/**
* Signal if the date is being manually edited by the user.
*
* The returned date may be invalid.
*
* @param date the new date
*/
void dateEdited(const QDate &date);
public Q_SLOTS:
/**
* Set the currently selected date
*
* You can set an invalid date or a date outside the valid range, validity
* checking is only done via isValid().
*
* @param date the new date
*/
void setDate(const QDate &date);
/**
* Set the new widget options
*
* @param options the new widget options
*/
void setOptions(Options options);
/**
* Sets the date format to display.
*
* By default is the Short Format.
*
* @param format the date format to use
*/
void setDisplayFormat(QLocale::FormatType format);
/**
* Set the valid date range to be applied by isValid().
*
* Both dates must be valid and the minimum date must be less than or equal
* to the maximum date, otherwise the date range will not be set.
*
* @param minDate the minimum date
* @param maxDate the maximum date
* @param minWarnMsg the minimum warning message
* @param maxWarnMsg the maximum warning message
*/
void setDateRange(const QDate &minDate,
const QDate &maxDate,
const QString &minWarnMsg = QString(),
const QString &maxWarnMsg = QString());
/**
* Reset the minimum and maximum date to the default values.
* @see setDateRange()
*/
void resetDateRange();
/**
* Set the minimum allowed date.
*
* If the date is invalid, or greater than current maximum,
* then the minimum will not be set.
*
* @see minimumDate()
* @see maximumDate()
* @see setMaximumDate()
* @see setDateRange()
* @param minDate the minimum date
* @param minWarnMsg the minimum warning message
*/
void setMinimumDate(const QDate &minTime, const QString &minWarnMsg = QString());
/**
* Reset the minimum date to the default.
*
* The default is to have no minimum date.
*/
void resetMinimumDate();
/**
* Set the maximum allowed date.
*
* If the date is invalid, or less than current minimum,
* then the maximum will not be set.
*
* @see minimumDate()
* @see maximumDate()
* @see setMaximumDate()
* @see setDateRange()
* @param maxDate the maximum date
* @param maxWarnMsg the maximum warning message
*/
void setMaximumDate(const QDate &maxDate, const QString &maxWarnMsg = QString());
/**
* Reset the maximum date to the default
*
* The default is to have no maximum date.
*/
void resetMaximumDate();
/**
* Set the list of dates able to be selected from the drop-down and the
* string form to display for those dates, e.g. "2010-01-01" and "Yesterday".
*
* Any invalid or duplicate dates will be used, the list will NOT be
* sorted, and the minimum and maximum date will not be affected.
*
* The @p dateMap is keyed by the date to be listed and the value is the
* string to be displayed. If you want the date to be displayed in the
* default date format then the string should be null. If you want a
* separator to be displayed then set the string to "separator".
*
* @see dateMap()
* @param dateMap the map of dates able to be selected
*/
void setDateMap(QMap dateMap);
protected:
bool eventFilter(QObject *object, QEvent *event) Q_DECL_OVERRIDE;
void showPopup() Q_DECL_OVERRIDE;
void hidePopup() Q_DECL_OVERRIDE;
void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE;
void keyPressEvent(QKeyEvent *event) Q_DECL_OVERRIDE;
void focusInEvent(QFocusEvent *event) Q_DECL_OVERRIDE;
void focusOutEvent(QFocusEvent *event) Q_DECL_OVERRIDE;
void resizeEvent(QResizeEvent *event) Q_DECL_OVERRIDE;
/**
* Assign the date for the widget.
*
* Virtual to allow sub-classes to apply extra validation rules.
*
* @param date the new date
*/
virtual void assignDate(const QDate &date);
private:
friend class KDateComboBoxPrivate;
KDateComboBoxPrivate *const d;
Q_PRIVATE_SLOT(d, void clickDate())
Q_PRIVATE_SLOT(d, void selectDate(QAction *))
Q_PRIVATE_SLOT(d, void editDate(const QString &))
Q_PRIVATE_SLOT(d, void enterDate(const QDate &))
Q_PRIVATE_SLOT(d, void parseDate())
};
Q_DECLARE_OPERATORS_FOR_FLAGS(KDateComboBox::Options)
#endif // KDATECOMBOBOX_H
diff --git a/src/kdatepicker.cpp b/src/kdatepicker.cpp
index 712cb9b..6196fa8 100644
--- a/src/kdatepicker.cpp
+++ b/src/kdatepicker.cpp
@@ -1,657 +1,657 @@
/* -*- C++ -*-
This file is part of the KDE libraries
Copyright (C) 1997 Tim D. Gilman (tdgilman@best.org)
(C) 1998-2001 Mirko Boehm (mirko@kde.org)
(C) 2007 John Layt
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "kdatepicker.h"
#include "kdatepicker_p.h"
#include "kdatetable_p.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "moc_kdatepicker.cpp"
#include "moc_kdatepicker_p.cpp"
class DatePickerValidator : public QValidator
{
public:
DatePickerValidator(KDatePicker *parent)
: QValidator(parent), picker(parent) {}
State validate(QString &text, int &) const Q_DECL_OVERRIDE
{
QLocale::FormatType formats[] = { QLocale::LongFormat, QLocale::ShortFormat, QLocale::NarrowFormat };
QLocale locale = picker->locale();
for (int i = 0; i < 3; i++) {
QDate tmp = locale.toDate(text, formats[i]);
if (tmp.isValid()) {
return Acceptable;
}
}
return QValidator::Intermediate;
}
private:
KDatePicker *picker;
};
// Week numbers are defined by ISO 8601
// See http://www.merlyn.demon.co.uk/weekinfo.htm for details
KDatePickerPrivateYearSelector::KDatePickerPrivateYearSelector(
const QDate ¤tDate, QWidget *parent)
: QLineEdit(parent), val(new QIntValidator(this)), result(0)
{
oldDate = currentDate;
setFont(QFontDatabase::systemFont(QFontDatabase::GeneralFont));
setFrame(false);
// TODO: Find a way to get that from QLocale
//val->setRange( calendar->year( calendar->earliestValidDate() ),
// calendar->year( calendar->latestValidDate() ) );
setValidator(val);
connect(this, &QLineEdit::returnPressed, this, &KDatePickerPrivateYearSelector::yearEnteredSlot);
}
void KDatePickerPrivateYearSelector::yearEnteredSlot()
{
bool ok;
int newYear;
// check if entered value is a number
newYear = text().toInt(&ok);
if (!ok) {
QApplication::beep();
return;
}
// check if new year will lead to a valid date
if (QDate(newYear, oldDate.month(), oldDate.day()).isValid()) {
result = newYear;
emit(closeMe(1));
} else {
QApplication::beep();
}
}
int KDatePickerPrivateYearSelector::year()
{
return result;
}
void KDatePickerPrivateYearSelector::setYear(int year)
{
setText(QString::number(year));
}
class KDatePicker::KDatePickerPrivate
{
public:
KDatePickerPrivate(KDatePicker *q) :
- q(q), closeButton(0L), selectWeek(0L), todayButton(0), navigationLayout(0)
+ q(q), closeButton(nullptr), selectWeek(nullptr), todayButton(nullptr), navigationLayout(nullptr)
{
}
void fillWeeksCombo();
QDate validDateInYearMonth(int year, int month);
/// the date table
KDatePicker *q;
QToolButton *closeButton;
QComboBox *selectWeek;
QToolButton *todayButton;
QBoxLayout *navigationLayout;
/// the year forward button
QToolButton *yearForward;
/// the year backward button
QToolButton *yearBackward;
/// the month forward button
QToolButton *monthForward;
/// the month backward button
QToolButton *monthBackward;
/// the button for selecting the month directly
QToolButton *selectMonth;
/// the button for selecting the year directly
QToolButton *selectYear;
/// the line edit to enter the date directly
QLineEdit *line;
/// the validator for the line edit:
DatePickerValidator *val;
/// the date table
KDateTable *table;
/// the widest month string in pixels:
QSize maxMonthRect;
/// the font size for the widget
int fontsize;
};
void KDatePicker::KDatePickerPrivate::fillWeeksCombo()
{
// every year can have a different number of weeks
// it could be that we had 53,1..52 and now 1..53 which is the same number but different
// so always fill with new values
// We show all week numbers for all weeks between first day of year to last day of year
// This of course can be a list like 53,1,2..52
const QDate thisDate = q->date();
const int thisYear = thisDate.year();
QDate day(thisDate.year(), 1, 1);
const QDate lastDayOfYear = QDate(thisDate.year() + 1, 1, 1).addDays(-1);
selectWeek->clear();
// Starting from the first day in the year, loop through the year a week at a time
// adding an entry to the week combo for each week in the year
for (; day.isValid() && day <= lastDayOfYear; day = day.addDays(7)) {
// Get the ISO week number for the current day and what year that week is in
// e.g. 1st day of this year may fall in week 53 of previous year
int weekYear = thisYear;
const int week = day.weekNumber(&weekYear);
QString weekString = tr("Week %1").arg(QString::number(week));
// show that this is a week from a different year
if (weekYear != thisYear) {
weekString += QLatin1Char('*');
}
// when the week is selected, go to the same weekday as the one
// that is currently selected in the date table
QDate targetDate = day.addDays(thisDate.dayOfWeek() - day.dayOfWeek());
selectWeek->addItem(weekString, targetDate);
// make sure that the week of the lastDayOfYear is always inserted: in Chinese calendar
// system, this is not always the case
if (day < lastDayOfYear &&
day.daysTo(lastDayOfYear) < 7 &&
lastDayOfYear.weekNumber() != day.weekNumber()) {
day = lastDayOfYear.addDays(-7);
}
}
}
QDate KDatePicker::KDatePickerPrivate::validDateInYearMonth(int year, int month)
{
QDate newDate;
// Try to create a valid date in this year and month
// First try the first of the month, then try last of month
if (QDate(year, month, 1).isValid()) {
newDate = QDate(year, month, 1);
} else if (QDate(year, month + 1, 1).isValid()) {
newDate = QDate(year, month + 1, 1).addDays(-1);
} else {
newDate = QDate::fromJulianDay(0);
}
return newDate;
}
KDatePicker::KDatePicker(QWidget *parent) : QFrame(parent), d(new KDatePickerPrivate(this))
{
initWidget(QDate::currentDate());
}
KDatePicker::KDatePicker(const QDate &date_, QWidget *parent)
: QFrame(parent), d(new KDatePickerPrivate(this))
{
initWidget(date_);
}
void KDatePicker::initWidget(const QDate &date_)
{
const int spacingHint = style()->pixelMetric(QStyle::PM_DefaultLayoutSpacing);
QBoxLayout *topLayout = new QVBoxLayout(this);
topLayout->setSpacing(0);
topLayout->setMargin(0);
d->navigationLayout = new QHBoxLayout();
d->navigationLayout->setSpacing(0);
d->navigationLayout->setMargin(0);
topLayout->addLayout(d->navigationLayout);
d->navigationLayout->addStretch();
d->yearBackward = new QToolButton(this);
d->yearBackward->setAutoRaise(true);
d->navigationLayout->addWidget(d->yearBackward);
d->monthBackward = new QToolButton(this);
d->monthBackward ->setAutoRaise(true);
d->navigationLayout->addWidget(d->monthBackward);
d->navigationLayout->addSpacing(spacingHint);
d->selectMonth = new QToolButton(this);
d->selectMonth ->setAutoRaise(true);
d->navigationLayout->addWidget(d->selectMonth);
d->selectYear = new QToolButton(this);
d->selectYear->setCheckable(true);
d->selectYear->setAutoRaise(true);
d->navigationLayout->addWidget(d->selectYear);
d->navigationLayout->addSpacing(spacingHint);
d->monthForward = new QToolButton(this);
d->monthForward ->setAutoRaise(true);
d->navigationLayout->addWidget(d->monthForward);
d->yearForward = new QToolButton(this);
d->yearForward ->setAutoRaise(true);
d->navigationLayout->addWidget(d->yearForward);
d->navigationLayout->addStretch();
d->line = new QLineEdit(this);
d->val = new DatePickerValidator(this);
d->table = new KDateTable(this);
setFocusProxy(d->table);
d->fontsize = QFontDatabase::systemFont(QFontDatabase::GeneralFont).pointSize();
if (d->fontsize == -1) {
d->fontsize = QFontInfo(QFontDatabase::systemFont(QFontDatabase::GeneralFont)).pointSize();
}
d->fontsize++; // Make a little bigger
d->selectWeek = new QComboBox(this); // read only week selection
d->selectWeek->setFocusPolicy(Qt::NoFocus);
d->todayButton = new QToolButton(this);
d->todayButton->setIcon(QIcon::fromTheme(QStringLiteral("go-jump-today")));
d->yearForward->setToolTip(tr("Next year"));
d->yearBackward->setToolTip(tr("Previous year"));
d->monthForward->setToolTip(tr("Next month"));
d->monthBackward->setToolTip(tr("Previous month"));
d->selectWeek->setToolTip(tr("Select a week"));
d->selectMonth->setToolTip(tr("Select a month"));
d->selectYear->setToolTip(tr("Select a year"));
d->todayButton->setToolTip(tr("Select the current day"));
// -----
setFontSize(d->fontsize);
d->line->setValidator(d->val);
d->line->installEventFilter(this);
if (QApplication::isRightToLeft()) {
d->yearForward->setIcon(QIcon::fromTheme(QStringLiteral("arrow-left-double")));
d->yearBackward->setIcon(QIcon::fromTheme(QStringLiteral("arrow-right-double")));
d->monthForward->setIcon(QIcon::fromTheme(QStringLiteral("arrow-left")));
d->monthBackward->setIcon(QIcon::fromTheme(QStringLiteral("arrow-right")));
} else {
d->yearForward->setIcon(QIcon::fromTheme(QStringLiteral("arrow-right-double")));
d->yearBackward->setIcon(QIcon::fromTheme(QStringLiteral("arrow-left-double")));
d->monthForward->setIcon(QIcon::fromTheme(QStringLiteral("arrow-right")));
d->monthBackward->setIcon(QIcon::fromTheme(QStringLiteral("arrow-left")));
}
connect(d->table, SIGNAL(dateChanged(QDate)), SLOT(dateChangedSlot(QDate)));
connect(d->table, &KDateTable::tableClicked, this, &KDatePicker::tableClickedSlot);
connect(d->monthForward, &QAbstractButton::clicked, this, &KDatePicker::monthForwardClicked);
connect(d->monthBackward, &QAbstractButton::clicked, this, &KDatePicker::monthBackwardClicked);
connect(d->yearForward, &QAbstractButton::clicked, this, &KDatePicker::yearForwardClicked);
connect(d->yearBackward, &QAbstractButton::clicked, this, &KDatePicker::yearBackwardClicked);
connect(d->selectWeek, SIGNAL(activated(int)), SLOT(weekSelected(int)));
connect(d->todayButton, &QAbstractButton::clicked, this, &KDatePicker::todayButtonClicked);
connect(d->selectMonth, &QAbstractButton::clicked, this, &KDatePicker::selectMonthClicked);
connect(d->selectYear, &QAbstractButton::toggled, this, &KDatePicker::selectYearClicked);
connect(d->line, &QLineEdit::returnPressed, this, &KDatePicker::lineEnterPressed);
topLayout->addWidget(d->table);
QBoxLayout *bottomLayout = new QHBoxLayout();
bottomLayout->setMargin(0);
bottomLayout->setSpacing(0);
topLayout->addLayout(bottomLayout);
bottomLayout->addWidget(d->todayButton);
bottomLayout->addWidget(d->line);
bottomLayout->addWidget(d->selectWeek);
d->table->setDate(date_);
dateChangedSlot(date_); // needed because table emits changed only when newDate != oldDate
}
KDatePicker::~KDatePicker()
{
delete d;
}
bool KDatePicker::eventFilter(QObject *o, QEvent *e)
{
if (e->type() == QEvent::KeyPress) {
QKeyEvent *k = (QKeyEvent *)e;
if ((k->key() == Qt::Key_PageUp) ||
(k->key() == Qt::Key_PageDown) ||
(k->key() == Qt::Key_Up) ||
(k->key() == Qt::Key_Down)) {
QApplication::sendEvent(d->table, e);
d->table->setFocus();
return true; // eat event
}
}
return QFrame::eventFilter(o, e);
}
void KDatePicker::resizeEvent(QResizeEvent *e)
{
QWidget::resizeEvent(e);
}
void KDatePicker::dateChangedSlot(const QDate &date_)
{
d->line->setText(locale().toString(date_, QLocale::ShortFormat));
d->selectMonth->setText(locale().standaloneMonthName(date_.month(), QLocale::LongFormat));
d->fillWeeksCombo();
// calculate the item num in the week combo box; normalize selected day so as if 1.1. is the first day of the week
QDate firstDay(date_.year(), 1, 1);
// If we cannot successfully create the 1st of the year, this can only mean that
// the 1st is before the earliest valid date in the current calendar system, so use
// the earliestValidDate as the first day.
// In particular covers the case of Gregorian where 1/1/-4713 is not a valid QDate
d->selectWeek->setCurrentIndex((date_.dayOfYear() + firstDay.dayOfWeek() - 2) / 7);
d->selectYear->setText(QString::number(date_.year()).rightJustified(4, QLatin1Char('0')));
emit(dateChanged(date_));
}
void KDatePicker::tableClickedSlot()
{
emit(dateSelected(date()));
emit(tableClicked());
}
const QDate &KDatePicker::date() const
{
return d->table->date();
}
bool KDatePicker::setDate(const QDate &date_)
{
// the table setDate does validity checking for us
// this also emits dateChanged() which then calls our dateChangedSlot()
return d->table->setDate(date_);
}
void KDatePicker::monthForwardClicked()
{
if (! setDate(date().addMonths(1))) {
QApplication::beep();
}
d->table->setFocus();
}
void KDatePicker::monthBackwardClicked()
{
if (! setDate(date().addMonths(-1))) {
QApplication::beep();
}
d->table->setFocus();
}
void KDatePicker::yearForwardClicked()
{
if (! setDate(d->table->date().addYears(1))) {
QApplication::beep();
}
d->table->setFocus();
}
void KDatePicker::yearBackwardClicked()
{
if (! setDate(d->table->date().addYears(-1))) {
QApplication::beep();
}
d->table->setFocus();
}
void KDatePicker::weekSelected(int index)
{
QDate targetDay = d->selectWeek->itemData(index).toDateTime().date();
if (! setDate(targetDay)) {
QApplication::beep();
}
d->table->setFocus();
}
void KDatePicker::selectMonthClicked()
{
QDate thisDate(date());
d->table->setFocus();
QMenu popup(d->selectMonth);
// Populate the pick list with all the month names, this may change by year
// JPL do we need to do somethng here for months that fall outside valid range?
const int monthsInYear = QDate(thisDate.year() + 1, 1, 1).addDays(-1).month();
for (int m = 1; m <= monthsInYear; m++) {
popup.addAction(locale().standaloneMonthName(m))->setData(m);
}
QAction *item = popup.actions()[ thisDate.month() - 1 ];
// if this happens the above should already given an assertion
if (item) {
popup.setActiveAction(item);
}
// cancelled
- if ((item = popup.exec(d->selectMonth->mapToGlobal(QPoint(0, 0)), item)) == 0) {
+ if ((item = popup.exec(d->selectMonth->mapToGlobal(QPoint(0, 0)), item)) == nullptr) {
return;
}
// We need to create a valid date in the month selected so we can find out how many days are
// in the month.
QDate newDate(thisDate.year(), item->data().toInt(), 1);
// If we have succeeded in creating a date in the new month, then try to create the new date,
// checking we don't set a day after the last day of the month
newDate.setDate(newDate.year(), newDate.month(), qMin(thisDate.day(), newDate.daysInMonth()));
// Set the date, if it's invalid in any way then alert user and don't update
if (! setDate(newDate)) {
QApplication::beep();
}
}
void KDatePicker::selectYearClicked()
{
if (!d->selectYear->isChecked()) {
return;
}
QDate thisDate(date());
KPopupFrame *popup = new KPopupFrame(this);
KDatePickerPrivateYearSelector *picker = new KDatePickerPrivateYearSelector(date(), popup);
picker->resize(picker->sizeHint());
picker->setYear(thisDate.year());
picker->selectAll();
popup->setMainWidget(picker);
connect(picker, SIGNAL(closeMe(int)), popup, SLOT(close(int)));
picker->setFocus();
if (popup->exec(d->selectYear->mapToGlobal(QPoint(0, d->selectMonth->height())))) {
// We need to create a valid date in the year/month selected so we can find out how many
// days are in the month.
QDate newDate(picker->year(), thisDate.month(), 1);
// If we have succeeded in creating a date in the new month, then try to create the new
// date, checking we don't set a day after the last day of the month
newDate = QDate(newDate.year(), newDate.month(), qMin(thisDate.day(), newDate.daysInMonth()));
// Set the date, if it's invalid in any way then alert user and don't update
if (! setDate(newDate)) {
QApplication::beep();
}
}
delete popup;
d->selectYear->setChecked(false);
}
void KDatePicker::uncheckYearSelector()
{
d->selectYear->setChecked(false);
d->selectYear->update();
}
void KDatePicker::changeEvent(QEvent *event)
{
if (event && event->type() == QEvent::EnabledChange) {
if (isEnabled()) {
d->table->setFocus();
}
}
}
KDateTable *KDatePicker::dateTable() const
{
return d->table;
}
void KDatePicker::lineEnterPressed()
{
QDate newDate = QDate::fromString(d->line->text(), locale().dateFormat());
if (newDate.isValid()) {
emit(dateEntered(newDate));
setDate(newDate);
d->table->setFocus();
} else {
QApplication::beep();
}
}
void KDatePicker::todayButtonClicked()
{
setDate(QDate::currentDate());
d->table->setFocus();
}
QSize KDatePicker::sizeHint() const
{
return QWidget::sizeHint();
}
void KDatePicker::setFontSize(int s)
{
QWidget *const buttons[] = {
d->selectMonth,
d->selectYear,
};
const int NoOfButtons = sizeof(buttons) / sizeof(buttons[0]);
int count;
QFont font;
QRect r;
// -----
d->fontsize = s;
for (count = 0; count < NoOfButtons; ++count) {
font = buttons[count]->font();
font.setPointSize(s);
buttons[count]->setFont(font);
}
d->table->setFontSize(s);
QFontMetrics metrics(d->selectMonth->fontMetrics());
QString longestMonth;
for (int i = 1;; ++i) {
QString str = locale().standaloneMonthName(i, QLocale::LongFormat);
if (str.isNull()) {
break;
}
r = metrics.boundingRect(str);
if (r.width() > d->maxMonthRect.width()) {
d->maxMonthRect.setWidth(r.width());
longestMonth = str;
}
if (r.height() > d->maxMonthRect.height()) {
d->maxMonthRect.setHeight(r.height());
}
}
QStyleOptionToolButton opt;
opt.initFrom(d->selectMonth);
opt.text = longestMonth;
// stolen from QToolButton
QSize textSize = metrics.size(Qt::TextShowMnemonic, longestMonth);
textSize.setWidth(textSize.width() + metrics.width(QLatin1Char(' ')) * 2);
int w = textSize.width();
int h = textSize.height();
opt.rect.setHeight(h); // PM_MenuButtonIndicator depends on the height
QSize metricBound = style()->sizeFromContents(
QStyle::CT_ToolButton, &opt, QSize(w, h), d->selectMonth
).expandedTo(QApplication::globalStrut());
d->selectMonth->setMinimumSize(metricBound);
}
int KDatePicker::fontSize() const
{
return d->fontsize;
}
void KDatePicker::setCloseButton(bool enable)
{
- if (enable == (d->closeButton != 0L)) {
+ if (enable == (d->closeButton != nullptr)) {
return;
}
if (enable) {
d->closeButton = new QToolButton(this);
d->closeButton->setAutoRaise(true);
const int spacingHint = style()->pixelMetric(QStyle::PM_DefaultLayoutSpacing);
d->navigationLayout->addSpacing(spacingHint);
d->navigationLayout->addWidget(d->closeButton);
d->closeButton->setToolTip(tr("Close", "@action:button"));
d->closeButton->setIcon(QIcon::fromTheme(QStringLiteral("window-close")));
connect(d->closeButton, &QAbstractButton::clicked,
topLevelWidget(), &QWidget::close);
} else {
delete d->closeButton;
- d->closeButton = 0L;
+ d->closeButton = nullptr;
}
updateGeometry();
}
bool KDatePicker::hasCloseButton() const
{
return (d->closeButton);
}
diff --git a/src/kdatepicker.h b/src/kdatepicker.h
index 4511f8f..f53b2a3 100644
--- a/src/kdatepicker.h
+++ b/src/kdatepicker.h
@@ -1,183 +1,183 @@
/* -*- C++ -*-
This file is part of the KDE libraries
Copyright (C) 1997 Tim D. Gilman (tdgilman@best.org)
(C) 1998-2001 Mirko Boehm (mirko@kde.org)
(C) 2007 John Layt
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef KDATEPICKER_H
#define KDATEPICKER_H
#include
#include
#include
class QLineEdit;
class KDateTable;
/**
* @short A date selection widget.
*
* Provides a widget for calendar date input.
*
* Different from the
* previous versions, it now emits two types of signals, either
* dateSelected() or dateEntered() (see documentation for both
* signals).
*
* A line edit has been added in the newer versions to allow the user
* to select a date directly by entering numbers like 19990101
* or 990101.
*
* \image html kdatepicker.png "KDE Date Widget"
*
* @author Tim Gilman, Mirko Boehm
*
**/
class KWIDGETSADDONS_EXPORT KDatePicker: public QFrame
{
Q_OBJECT
Q_PROPERTY(QDate date READ date WRITE setDate NOTIFY dateChanged USER true)
Q_PROPERTY(bool closeButton READ hasCloseButton WRITE setCloseButton)
Q_PROPERTY(int fontSize READ fontSize WRITE setFontSize)
public:
/**
* The constructor. The current date will be displayed initially.
**/
- explicit KDatePicker(QWidget *parent = 0);
+ explicit KDatePicker(QWidget *parent = nullptr);
/**
* The constructor. The given date will be displayed initially.
**/
- explicit KDatePicker(const QDate &dt, QWidget *parent = 0);
+ explicit KDatePicker(const QDate &dt, QWidget *parent = nullptr);
/**
* The destructor.
**/
virtual ~KDatePicker();
/** The size hint for date pickers. The size hint recommends the
* minimum size of the widget so that all elements may be placed
* without clipping. This sometimes looks ugly, so when using the
* size hint, try adding 28 to each of the reported numbers of
* pixels.
**/
QSize sizeHint() const Q_DECL_OVERRIDE;
/**
* Sets the date.
*
* @returns @p false and does not change anything if the date given is invalid.
**/
bool setDate(const QDate &date);
/**
* @returns the selected date.
*/
const QDate &date() const;
/**
* @returns the KDateTable widget child of this KDatePicker
* widget.
*/
/**
* Sets the font size of the widgets elements.
**/
void setFontSize(int);
/**
* Returns the font size of the widget elements.
*/
int fontSize() const;
/**
* By calling this method with @p enable = true, KDatePicker will show
* a little close-button in the upper button-row. Clicking the
* close-button will cause the KDatePicker's topLevelWidget()'s close()
* method being called. This is mostly useful for toplevel datepickers
* without a window manager decoration.
* @see hasCloseButton
*/
void setCloseButton(bool enable);
/**
* @returns true if a KDatePicker shows a close-button.
* @see setCloseButton
*/
bool hasCloseButton() const;
protected:
/// to catch move keyEvents when QLineEdit has keyFocus
bool eventFilter(QObject *o, QEvent *e) Q_DECL_OVERRIDE;
/// the resize event
void resizeEvent(QResizeEvent *) Q_DECL_OVERRIDE;
void changeEvent(QEvent *event) Q_DECL_OVERRIDE;
protected Q_SLOTS:
void dateChangedSlot(const QDate &date);
void tableClickedSlot();
void monthForwardClicked();
void monthBackwardClicked();
void yearForwardClicked();
void yearBackwardClicked();
void selectMonthClicked();
void selectYearClicked();
void uncheckYearSelector();
void lineEnterPressed();
void todayButtonClicked();
void weekSelected(int);
Q_SIGNALS:
/** This signal is emitted each time the selected date is changed.
* Usually, this does not mean that the date has been entered,
* since the date also changes, for example, when another month is
* selected.
* @see dateSelected
*/
void dateChanged(const QDate &date);
/** This signal is emitted each time a day has been selected by
* clicking on the table (hitting a day in the current month). It
* has the same meaning as dateSelected() in older versions of
* KDatePicker.
*/
void dateSelected(const QDate &date);
/** This signal is emitted when enter is pressed and a VALID date
* has been entered before into the line edit. Connect to both
* dateEntered() and dateSelected() to receive all events where the
* user really enters a date.
*/
void dateEntered(const QDate &date);
/** This signal is emitted when the day has been selected by
* clicking on it in the table.
*/
void tableClicked();
private:
KDateTable *dateTable() const;
void initWidget(const QDate &date);
class KDatePickerPrivate;
friend class KDatePickerPrivate;
KDatePickerPrivate *const d;
};
#endif // KDATEPICKER_H
diff --git a/src/kdatepicker_p.h b/src/kdatepicker_p.h
index 2f071d3..7645f83 100644
--- a/src/kdatepicker_p.h
+++ b/src/kdatepicker_p.h
@@ -1,59 +1,59 @@
/* -*- C++ -*-
This file is part of the KDE libraries
Copyright (C) 1997 Tim D. Gilman (tdgilman@best.org)
(C) 1998-2001 Mirko Boehm (mirko@kde.org)
(C) 1998-2001 Mirko Boehm (john@layt.net)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef KDATEPICKER_P_H
#define KDATEPICKER_P_H
#include
#include
#include
/** Year selection widget.
* @internal
* @author Tim Gilman, Mirko Boehm, John Layt
*/
class KDatePickerPrivateYearSelector : public QLineEdit
{
Q_OBJECT
public:
- KDatePickerPrivateYearSelector(const QDate ¤tDate, QWidget *parent = 0);
+ KDatePickerPrivateYearSelector(const QDate ¤tDate, QWidget *parent = nullptr);
int year();
void setYear(int year);
public Q_SLOTS:
void yearEnteredSlot();
Q_SIGNALS:
void closeMe(int);
protected:
QIntValidator *val;
int result;
private:
QDate oldDate;
Q_DISABLE_COPY(KDatePickerPrivateYearSelector)
};
#endif // KDATEPICKER_P_H
diff --git a/src/kdatetable_p.h b/src/kdatetable_p.h
index a371426..5dd32d6 100644
--- a/src/kdatetable_p.h
+++ b/src/kdatetable_p.h
@@ -1,193 +1,193 @@
/* -*- C++ -*-
This file is part of the KDE libraries
Copyright (C) 1997 Tim D. Gilman (tdgilman@best.org)
(C) 1998-2001 Mirko Boehm (mirko@kde.org)
(C) 2007 John Layt
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef KDATETABLE_H
#define KDATETABLE_H
#include
#include
class QMenu;
/**
* Date selection table.
* This is a support class for the KDatePicker class. It just
* draws the calendar table without titles, but could theoretically
* be used as a standalone.
*
* When a date is selected by the user, it emits a signal:
* dateSelected(QDate)
*
* \image html kdatetable.png "KDE Date Selection Table"
*
* @internal
* @author Tim Gilman, Mirko Boehm
*/
class KDateTable : public QWidget
{
Q_OBJECT
Q_PROPERTY(QDate date READ date WRITE setDate)
Q_PROPERTY(bool popupMenu READ popupMenuEnabled WRITE setPopupMenuEnabled)
public:
/**
* The constructor.
*/
- explicit KDateTable(QWidget *parent = 0);
+ explicit KDateTable(QWidget *parent = nullptr);
/**
* The constructor.
*/
- explicit KDateTable(const QDate &, QWidget *parent = 0);
+ explicit KDateTable(const QDate &, QWidget *parent = nullptr);
/**
* The destructor.
*/
~KDateTable();
/**
* Returns a recommended size for the widget.
* To save some time, the size of the largest used cell content is
* calculated in each paintCell() call, since all calculations have
* to be done there anyway. The size is stored in maxCell. The
* sizeHint() simply returns a multiple of maxCell.
*/
QSize sizeHint() const Q_DECL_OVERRIDE;
/**
* Set the font size of the date table.
*/
void setFontSize(int size);
/**
* Select and display this date.
*/
bool setDate(const QDate &date);
// KDE5 remove the const & from the returned QDate
/**
* @returns the selected date.
*/
const QDate &date() const;
/**
* Enables a popup menu when right clicking on a date.
*
* When it's enabled, this object emits a aboutToShowContextMenu signal
* where you can fill in the menu items.
*/
void setPopupMenuEnabled(bool enable);
/**
* Returns if the popup menu is enabled or not
*/
bool popupMenuEnabled() const;
enum BackgroundMode { NoBgMode = 0, RectangleMode, CircleMode };
/**
* Makes a given date be painted with a given foregroundColor, and background
* (a rectangle, or a circle/ellipse) in a given color.
*/
void setCustomDatePainting(const QDate &date, const QColor &fgColor,
BackgroundMode bgMode = NoBgMode, const QColor &bgColor = QColor());
/**
* Unsets the custom painting of a date so that the date is painted as usual.
*/
void unsetCustomDatePainting(const QDate &date);
protected:
/**
* calculate the position of the cell in the matrix for the given date.
* The result is the 0-based index.
*/
virtual int posFromDate(const QDate &date);
/**
* calculate the date that is displayed at a given cell in the matrix. pos is the
* 0-based index in the matrix. Inverse function to posForDate().
*/
virtual QDate dateFromPos(int pos);
void paintEvent(QPaintEvent *e) Q_DECL_OVERRIDE;
/**
* React on mouse clicks that select a date.
*/
void mousePressEvent(QMouseEvent *e) Q_DECL_OVERRIDE;
void wheelEvent(QWheelEvent *e) Q_DECL_OVERRIDE;
void keyPressEvent(QKeyEvent *e) Q_DECL_OVERRIDE;
void focusInEvent(QFocusEvent *e) Q_DECL_OVERRIDE;
void focusOutEvent(QFocusEvent *e) Q_DECL_OVERRIDE;
/**
* Cell highlight on mouse hovering
*/
bool event(QEvent *e) Q_DECL_OVERRIDE;
Q_SIGNALS:
/**
* The selected date changed.
*/
void dateChanged(const QDate &date);
/**
* This function behaves essentially like the one above.
* The selected date changed.
* @param cur The current date
* @param old The date before the date was changed
*/
void dateChanged(const QDate &cur, const QDate &old);
/**
* A date has been selected by clicking on the table.
*/
void tableClicked();
/**
* A popup menu for a given date is about to be shown (as when the user
* right clicks on that date and the popup menu is enabled). Connect
* the slot where you fill the menu to this signal.
*/
void aboutToShowContextMenu(QMenu *menu, const QDate &date);
private:
Q_PRIVATE_SLOT(d, void nextMonth())
Q_PRIVATE_SLOT(d, void previousMonth())
Q_PRIVATE_SLOT(d, void beginningOfMonth())
Q_PRIVATE_SLOT(d, void endOfMonth())
Q_PRIVATE_SLOT(d, void beginningOfWeek())
Q_PRIVATE_SLOT(d, void endOfWeek())
private:
class KDateTablePrivate;
friend class KDateTablePrivate;
KDateTablePrivate *const d;
void initWidget(const QDate &date);
void initAccels();
void paintCell(QPainter *painter, int row, int col);
Q_DISABLE_COPY(KDateTable)
};
#endif // KDATETABLE_H
diff --git a/src/kdatetimeedit.h b/src/kdatetimeedit.h
index 6e809cc..a989806 100644
--- a/src/kdatetimeedit.h
+++ b/src/kdatetimeedit.h
@@ -1,600 +1,600 @@
/*
Copyright 2011 John Layt
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef KDATETIMEEDIT_H
#define KDATETIMEEDIT_H
#include
#include
#include
#include
class KDateTimeEditPrivate;
class KWIDGETSADDONS_EXPORT KDateTimeEdit : public QWidget
{
Q_OBJECT
Q_PROPERTY(QDate date READ date WRITE setDate NOTIFY dateChanged USER true)
Q_PROPERTY(QTime time READ time WRITE setTime NOTIFY timeChanged USER true)
Q_PROPERTY(int timeListInterval READ timeListInterval WRITE setTimeListInterval)
Q_PROPERTY(Options options READ options WRITE setOptions)
public:
/**
* Options provided by the widget
* @see options
* @see setOptions
*/
enum Option {
ShowCalendar = 0x00001, /**< If the Calendar System edit is displayed */
ShowDate = 0x00002, /**< If the Date is displayed */
ShowTime = 0x00004, /**< If the Time is displayed */
ShowTimeZone = 0x00008, /**< If the Time Zone is displayed */
//EditCalendar = 0x00010, /**< Allow the user to manually edit the calendar */
EditDate = 0x00020, /**< Allow the user to manually edit the date */
EditTime = 0x00040, /**< Allow the user to manually edit the time */
//EditTimeZone = 0x00080, /**< Allow the user to manually edit the time zone */
SelectCalendar = 0x00100, /**< Allow the user to select a calendar */
SelectDate = 0x00200, /**< Allow the user to select a date */
SelectTime = 0x00400, /**< Allow the user to select a time */
SelectTimeZone = 0x00800, /**< Allow the user to select a time zone */
DatePicker = 0x01000, /**< Show a date picker */
DateKeywords = 0x02000, /**< Show date keywords */
ForceTime = 0x04000, /**< The entered time can only be a selected time */
WarnOnInvalid = 0x08000 /**< Show a warning on focus out if the date or time is invalid */
};
Q_DECLARE_FLAGS(Options, Option)
Q_FLAG(Options)
/**
* Create a new KDateTimeEdit widget
*/
- explicit KDateTimeEdit(QWidget *parent = 0);
+ explicit KDateTimeEdit(QWidget *parent = nullptr);
/**
* Destroy the widget
*/
virtual ~KDateTimeEdit();
/**
* Return the currently set widget options
*
* @return the currently set widget options
*/
Options options() const;
/**
* Return the currently selected date, time and time zone
*
* @return the currently selected date, time and time zone
*/
QDateTime dateTime() const;
/**
* Return the currently selected date
*
* @return the currently selected date
*/
QDate date() const;
/**
* Return the currently selected time
*
* @return the currently selected time
*/
QTime time() const;
/**
* Return the currently selected time zone
*
* @return the currently selected time zone
*/
QTimeZone timeZone() const;
/**
* Returns the list of Calendar Systems displayed.
*
* @param calendars the list of calendar systems to display
*/
QList calendarLocalesList() const;
/**
* Return the current minimum date and time
*
* @return the current minimum date and time
*/
QDateTime minimumDateTime() const;
/**
* Return the current maximum date and time
*
* @return the current maximum date and time
*/
QDateTime maximumDateTime() const;
/**
* Return the currently set date display format
*
* By default this is the Short Format
*
* @return the currently set date format
*/
QLocale::FormatType dateDisplayFormat() const;
/**
* Return the map of dates listed in the drop-down and their displayed
* string forms.
*
* @see setDateMap()
* @return the select date map
*/
QMap dateMap() const;
/**
* Return the currently set time format
*
* By default this is the Short Format
*
* @return the currently set time format
*/
QLocale::FormatType timeDisplayFormat() const;
/**
* Return the time list interval able to be selected
*
* @return the select time intervals in minutes
*/
int timeListInterval() const;
/**
* Return the list of times able to be selected in the drop-down.
*
* @see setTimeList()
* @see timeListInterval()
* @see setTimeListInterval()
* @return the select time list
*/
QList timeList() const;
/**
* Return the list of time zones able to be selected
*
* @param zones the time zones to display
*/
QList timeZones() const;
/**
* Return if the current user input is valid
*
* If the user input is null then it is not valid
*
* @see isNull()
* @return if the current user input is valid
*/
bool isValid() const;
/**
* Return if the current user input is null
*
* @see isValid()
* @return if the current user input is null
*/
bool isNull() const;
/**
* Return if the current user input date is valid
*
* If the user input date is null then it is not valid
*
* @see isNullDate()
* @return if the current user input date is valid
*/
bool isValidDate() const;
/**
* Return if the current user input date is null
*
* @see isValidDate()
* @return if the current user input date is null
*/
bool isNullDate() const;
/**
* Return if the current user input time is valid
*
* If the user input time is null then it is not valid
*
* @see isNullTime()
* @return if the current user input time is valid
*/
bool isValidTime() const;
/**
* Return if the current user input time is null
*
* @see isValidTime()
* @return if the current user input time is null
*/
bool isNullTime() const;
Q_SIGNALS:
/**
* Signal if the date or time has been manually entered by the user.
*
* The returned date and time may be invalid.
*
* @param dateTime the new date, time and time zone
*/
void dateTimeEntered(const QDateTime &dateTime);
/**
* Signal if the date or time has been changed either manually by the user
* or programatically.
*
* The returned date and time may be invalid.
*
* @param dateTime the new date, time and time zone
*/
void dateTimeChanged(const QDateTime &dateTime);
/**
* Signal if the date or time is being manually edited by the user.
*
* The returned date and time may be invalid.
*
* @param dateTime the new date, time and time zone
*/
void dateTimeEdited(const QDateTime &dateTime);
/**
* Signal if the Calendar Locale has been manually entered by the user.
*
* @param calendarLocale the new calendar locale
*/
void calendarEntered(const QLocale &calendarLocale);
/**
* Signal if the Calendar Locale has been changed either manually by the user
* or programatically.
*
* @param calendarLocale the new calendar locale
*/
void calendarChanged(const QLocale &calendarLocale);
/**
* Signal if the date has been manually entered by the user.
*
* The returned date may be invalid.
*
* @param date the new date
*/
void dateEntered(const QDate &date);
/**
* Signal if the date has been changed either manually by the user
* or programatically.
*
* The returned date may be invalid.
*
* @param date the new date
*/
void dateChanged(const QDate &date);
/**
* Signal if the date is being manually edited by the user.
*
* The returned date may be invalid.
*
* @param date the new date
*/
void dateEdited(const QDate &date);
/**
* Signal if the time has been manually entered by the user.
*
* The returned time may be invalid.
*
* @param time the new time
*/
void timeEntered(const QTime &time);
/**
* Signal if the time has been changed either manually by the user
* or programatically.
*
* The returned time may be invalid.
*
* @param time the new time
*/
void timeChanged(const QTime &time);
/**
* Signal if the time is being manually edited by the user.
*
* The returned time may be invalid.
*
* @param time the new time
*/
void timeEdited(const QTime &time);
/**
* Signal if the time zone has been changed manually by the user.
*
* @param timeZone the new time zone
*/
void timeZoneEntered(const QTimeZone &zone);
/**
* Signal if the time zone has been changed either manually by the user
* or programatically.
*
* @param timeZone the new time zone
*/
void timeZoneChanged(const QTimeZone &zone);
public Q_SLOTS:
/**
* Set the new widget options
*
* @param options the new widget options
*/
void setOptions(Options options);
/**
* Set the currently selected date, time and time zone
*
* @param dateTime the new date, time and time zone
*/
void setDateTime(const QDateTime &dateTime);
/**
* Set the currently selected date
*
* @param date the new date
*/
void setDate(const QDate &date);
/**
* Set the currently selected time
*
* @param time the new time
*/
void setTime(const QTime &time);
/**
* Set the current time zone
*
* @param zone the new zone
*/
void setTimeZone(const QTimeZone &zone);
/**
* Set the minimum and maximum date and time range
*
* To enable range checking provide two valid dates.
* To disable range checking provide two invalid dates, or call
* clearDateRange;
*
* @param minDateTime the minimum date and time
* @param maxDateTime the maximum date and time
* @param minWarnMsg the minimum warning message
* @param maxWarnMsg the maximum warning message
*/
void setDateTimeRange(const QDateTime &minDateTime,
const QDateTime &maxDateTime,
const QString &minWarnMsg = QString(),
const QString &maxWarnMsg = QString());
/**
* Reset the minimum and maximum date and time to the default
*/
void resetDateTimeRange();
/**
* Set the minimum allowed date.
*
* If the date is invalid, or more than current maximum,
* then the minimum will not be set.
*
* @see setMaximumDateTime()
* @see setDateRange()
* @param maxDate the minimum date
* @param maxWarnMsg the minimum warning message
*/
void setMinimumDateTime(const QDateTime &minDateTime, const QString &minWarnMsg = QString());
/**
* Reset the minimum date and time to the default
*/
void resetMinimumDateTime();
/**
* Set the maximum allowed date.
*
* If the date is invalid, or less than current minimum,
* then the maximum will not be set.
*
* @see setMinimumDateTime()
* @see setDateRange()
* @param maxDate the maximum date
* @param maxWarnMsg the maximum warning message
*/
void setMaximumDateTime(const QDateTime &maxDateTime, const QString &maxWarnMsg = QString());
/**
* Reset the minimum date and time to the default
*/
void resetMaximumDateTime();
/**
* Sets the date format to display.
*
* By default is the Short Format.
*
* @param format the date format to use
*/
void setDateDisplayFormat(QLocale::FormatType format);
/**
* Set the list of Calendar Locales to display.
*
* @param calendarLocales the list of calendar locales to display
*/
void setCalendarLocalesList(const QList &calendarLocales);
/**
* Set the list of dates able to be selected from the drop-down and the
* string form to display for those dates, e.g. "2010-01-01" and "Yesterday".
*
* Any invalid or duplicate dates will be used, the list will NOT be
* sorted, and the minimum and maximum date will not be affected.
*
* The @p dateMap is keyed by the date to be listed and the value is the
* string to be displayed. If you want the date to be displayed in the
* default date format then the string should be null. If you want a
* separator to be displayed then set the string to "separator".
*
* @see dateMap()
* @param dateMap the map of dates able to be selected
*/
void setDateMap(QMap dateMap);
/**
* Sets the time format to display.
*
* By default is the Short Format.
*
* @param format the time format to use
*/
void setTimeDisplayFormat(QLocale::FormatType formatOptions);
/**
* Set the interval between times able to be selected from the drop-down.
*
* The combo drop-down will be populated with times every @param minutes
* apart, starting from the minimumTime() and ending at maximumTime().
*
* If the ForceInterval option is set then any time manually typed into the
* combo line edit will be forced to the nearest interval.
*
* This interval must be an exact divisor of the valid time range hours.
* For example with the default 24 hour range @p interval must divide 1440
* minutes exactly, meaning 1, 6 and 90 are valid but 7, 31 and 91 are not.
*
* Setting the time list interval will override any time list previously set
* via setTimeList().
*
* @see timeListInterval()
* @param minutes the time list interval to display
*/
void setTimeListInterval(int minutes);
/**
* Set the list of times able to be selected from the drop-down.
*
* Setting the time list will override any time interval previously set via
* setTimeListInterval().
*
* Any invalid or duplicate times will be ignored, and the list will be
* sorted.
*
* The minimum and maximum time will automatically be set to the earliest
* and latest value in the list.
*
* @see timeList()
* @param timeList the list of times able to be selected
* @param minWarnMsg the minimum warning message
* @param maxWarnMsg the maximum warning message
*/
void setTimeList(QList timeList,
const QString &minWarnMsg = QString(),
const QString &maxWarnMsg = QString());
/**
* Set the time zones able to be selected
*
* @param zones the time zones to display
*/
void setTimeZones(const QList &zones);
protected:
bool eventFilter(QObject *object, QEvent *event) Q_DECL_OVERRIDE;
void focusInEvent(QFocusEvent *event) Q_DECL_OVERRIDE;
void focusOutEvent(QFocusEvent *event) Q_DECL_OVERRIDE;
void resizeEvent(QResizeEvent *event) Q_DECL_OVERRIDE;
/**
* Assign the date, time and time zone for the widget.
*
* Virtual to allow sub-classes to apply extra validation rules,
* but reimplementations must call the parent method at the end.
*
* @param datetime the new date and time
*/
virtual void assignDateTime(const QDateTime &dateTime);
/**
* Assign the date for the widget.
*
* Virtual to allow sub-classes to apply extra validation rules,
* but reimplementations must call the parent method at the end.
*
* @param date the new date
*/
virtual void assignDate(const QDate &date);
/**
* Assign the time for the widget.
*
* Virtual to allow sub-classes to apply extra validation rules,
* but reimplementations must call the parent method at the end.
*
* @param time the new time
*/
virtual void assignTime(const QTime &time);
/**
* Assign the time zone for the widget.
*
* Virtual to allow sub-classes to apply extra validation rules,
* but reimplementations must call the parent method at the end.
*
* @param zone the new time zone
*/
void assignTimeZone(const QTimeZone &zone);
private:
friend class KDateTimeEditPrivate;
KDateTimeEditPrivate *const d;
Q_PRIVATE_SLOT(d, void selectCalendar(int))
Q_PRIVATE_SLOT(d, void enterCalendar(const QLocale &))
Q_PRIVATE_SLOT(d, void selectTimeZone(int))
Q_PRIVATE_SLOT(d, void enterTimeZone(const QByteArray &))
};
Q_DECLARE_OPERATORS_FOR_FLAGS(KDateTimeEdit::Options)
#endif // KDATETIMEEDIT_H
diff --git a/src/kdragwidgetdecorator.cpp b/src/kdragwidgetdecorator.cpp
index 5e18fd9..9ff121b 100644
--- a/src/kdragwidgetdecorator.cpp
+++ b/src/kdragwidgetdecorator.cpp
@@ -1,108 +1,108 @@
/* This file is part of the KDE libraries
Copyright (C) 2000 Carsten Pfeiffer
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "kdragwidgetdecorator.h"
#include
#include
#include
#include
class KDragWidgetDecoratorBasePrivate
{
public:
KDragWidgetDecoratorBasePrivate()
: dragEnabled(true),
- decoratedWidget(0)
+ decoratedWidget(nullptr)
{
}
bool dragEnabled;
QWidget *decoratedWidget;
QPoint startPos;
};
KDragWidgetDecoratorBase::KDragWidgetDecoratorBase(QWidget *parent)
: QObject(parent),
d(new KDragWidgetDecoratorBasePrivate)
{
parent->installEventFilter(this);
d->decoratedWidget = parent;
}
KDragWidgetDecoratorBase::~KDragWidgetDecoratorBase()
{
delete d;
}
bool KDragWidgetDecoratorBase::isDragEnabled() const
{
return d->dragEnabled;
}
void KDragWidgetDecoratorBase::setDragEnabled(bool enable)
{
d->dragEnabled = enable;
}
bool KDragWidgetDecoratorBase::eventFilter(QObject *watched, QEvent *event)
{
Q_UNUSED(watched) // except in Q_ASSERT
Q_ASSERT(watched == d->decoratedWidget);
if (!d->dragEnabled) {
return false;
}
if (event->type() == QEvent::MouseButtonPress) {
QMouseEvent *e = static_cast(event);
d->startPos = e->pos();
} else if (event->type() == QEvent::MouseMove) {
QMouseEvent *e = static_cast(event);
if ((e->buttons() & Qt::LeftButton) &&
(e->pos() - d->startPos).manhattanLength() >
QApplication::startDragDistance()) {
startDrag();
d->decoratedWidget->setProperty("down", false);
return true;
}
}
return false;
}
QWidget *KDragWidgetDecoratorBase::decoratedWidget() const
{
return d->decoratedWidget;
}
QDrag *KDragWidgetDecoratorBase::dragObject()
{
- return 0;
+ return nullptr;
}
void KDragWidgetDecoratorBase::startDrag()
{
QDrag *drag = dragObject();
if (drag) {
drag->exec(Qt::CopyAction);
}
}
diff --git a/src/kdragwidgetdecorator.h b/src/kdragwidgetdecorator.h
index 620823f..c923c91 100644
--- a/src/kdragwidgetdecorator.h
+++ b/src/kdragwidgetdecorator.h
@@ -1,148 +1,148 @@
/* This file is part of the KDE libraries
Copyright (C) 2000 Carsten Pfeiffer
Copyright (C) 2012 Kevin Ottens
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef KDRAGWIDGETDECORATOR_H
#define KDRAGWIDGETDECORATOR_H
#include
#include
class QDrag;
class KDragWidgetDecoratorBasePrivate;
/**
* @brief A decorator which adds drag-support to widgets
*
* This is a decorator using an event filter to implement drag-support
* in widgets.
* You must override the virtual method dragObject() to specify the
* QDrag to be used.
*
* @author Carsten Pfeiffer
*/
class KWIDGETSADDONS_EXPORT KDragWidgetDecoratorBase : public QObject
{
Q_OBJECT
Q_PROPERTY(bool isDragEnabled READ isDragEnabled WRITE setDragEnabled)
public:
/**
* Default constructor.
*/
- explicit KDragWidgetDecoratorBase(QWidget *parent = 0);
+ explicit KDragWidgetDecoratorBase(QWidget *parent = nullptr);
/**
* Destructs the decorator.
*/
~KDragWidgetDecoratorBase();
/**
* Enables/disables drag-support. Default is enabled.
*/
void setDragEnabled(bool enable);
/**
* @returns if drag support is enabled or not.
*/
bool isDragEnabled() const;
protected:
/**
* @return the widget this decorator is attached to
*/
QWidget *decoratedWidget() const;
/**
* Reimplement this and return the QDrag object that should be used
* for the drag. Remember to give it "decoratedWidget()" as parent.
*
* Default implementation returns 0, so that no drag is initiated.
*/
virtual QDrag *dragObject();
/**
* Reimplemented to add drag-support
*/
bool eventFilter(QObject *watched, QEvent *event) Q_DECL_OVERRIDE;
/**
* Starts a drag (Copy by default) using dragObject()
*/
virtual void startDrag();
private:
KDragWidgetDecoratorBasePrivate *const d;
};
/**
* @brief A decorator which adds drag-support to widgets
*
* This is a decorator using an event filter to implement drag-support
* in widgets.
* You must set the dragObjectFactory to specify the QDrag to be used.
*
* @author Kevin Ottens
*/
template
class KDragWidgetDecorator : public KDragWidgetDecoratorBase
{
public:
typedef QDrag *(*DragObjectFactory)(Widget *);
KDragWidgetDecorator(Widget *parent = 0)
: KDragWidgetDecoratorBase(parent), m_factory(0) {}
/**
* @return the QDrag factory used by this decorator
*/
DragObjectFactory dragObjectFactory() const
{
return m_factory;
}
/**
* Set a factory to be used by this decorator
*
* @param factory the new QDrag factory to use
*/
void setDragObjectFactory(DragObjectFactory factory)
{
m_factory = factory;
}
private:
/**
* Reimplemented to use the QDrag factory
*/
QDrag *dragObject() Q_DECL_OVERRIDE
{
if (m_factory) {
Widget *w = static_cast(decoratedWidget());
return m_factory(w);
} else {
return KDragWidgetDecoratorBase::dragObject();
}
}
DragObjectFactory m_factory;
};
#endif // KDRAGWIDGETDECORATOR_H
diff --git a/src/keditlistwidget.cpp b/src/keditlistwidget.cpp
index 9669127..14b31c7 100644
--- a/src/keditlistwidget.cpp
+++ b/src/keditlistwidget.cpp
@@ -1,653 +1,653 @@
/* This file is part of the KDE libraries
Copyright (C) 2000 David Faure , Alexander Neundorf
(C) 2000, 2002 Carsten Pfeiffer
(C) 2010 Sebastian Trueg
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "keditlistwidget.h"
#include
#include
#include
#include
#include