diff --git a/CMakeLists.txt b/CMakeLists.txt index b5a514832..90c533867 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,27 +1,27 @@ cmake_minimum_required(VERSION 2.8.12) project(KDialog) # ECM setup find_package(ECM 1.7.0 CONFIG REQUIRED) set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH}) include(FeatureSummary) include(KDEInstallDirs) include(KDECMakeSettings) include(KDEFrameworkCompilerSettings NO_POLICY_SCOPE) # Build dependencies -find_package(KF5 REQUIRED COMPONENTS KDELibs4Support KIO) +find_package(KF5 REQUIRED COMPONENTS KDELibs4Support KIO DBusAddons) find_package(Qt5DBus CONFIG) find_package(X11) if(X11_FOUND) set(HAVE_X11 1) endif() add_definitions(-DQT_NO_URL_CAST_FROM_STRING) add_subdirectory(src) feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index eae0b71b4..8fe698f9b 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,28 +1,51 @@ configure_file(config-kdialog.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config-kdialog.h) set(kdialog_SRCS kdialog.cpp widgets.cpp + utils.cpp klistboxdialog.cpp - progressdialog.cpp) - -qt5_add_dbus_adaptor( kdialog_SRCS org.kde.kdialog.ProgressDialog.xml progressdialog.h KProgressDialog ) +) add_executable(kdialog ${kdialog_SRCS}) -# Need libkfile due to the code that adjusts the geometry of the KDirSelectDialog target_link_libraries(kdialog KF5::KIOWidgets KF5::KDELibs4Support ) if(Qt5DBus_FOUND) target_link_libraries(kdialog Qt5::DBus) endif() if (HAVE_X11) target_link_libraries(kdialog ${X11_X11_LIB}) endif() install(TARGETS kdialog ${KF5_INSTALL_TARGETS_DEFAULT_ARGS}) install(FILES org.kde.kdialog.ProgressDialog.xml DESTINATION ${KDE_INSTALL_DBUSINTERFACEDIR}) + +################################################################################ + +set(kdialog_progress_helper_SRCS + kdialog_progress_helper.cpp + utils.cpp + progressdialog.cpp +) + +qt5_add_dbus_adaptor(kdialog_progress_helper_SRCS org.kde.kdialog.ProgressDialog.xml progressdialog.h ProgressDialog) + +add_executable(kdialog_progress_helper ${kdialog_progress_helper_SRCS}) + +target_link_libraries(kdialog_progress_helper + KF5::DBusAddons + Qt5::Widgets + KF5::KDELibs4Support +) + +if (HAVE_X11) + target_link_libraries(kdialog_progress_helper ${X11_X11_LIB}) +endif() + +install(TARGETS kdialog_progress_helper ${KF5_INSTALL_TARGETS_DEFAULT_ARGS}) + diff --git a/src/kdialog.cpp b/src/kdialog.cpp index b63e51b74..c7b5bdbb5 100644 --- a/src/kdialog.cpp +++ b/src/kdialog.cpp @@ -1,973 +1,971 @@ // // Copyright (C) 1998 Matthias Hoelzer // Copyright (C) 2002, 2016 David Faure // Copyright (C) 2005 Brad Hards // Copyright (C) 2008 by Dmitry Suzdalev // Copyright (C) 2011 Kai Uwe Broulik // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the7 implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // #include "config-kdialog.h" #include "widgets.h" +#include "utils.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include -#include #include #include #include +#include +#include #include +#include #include -#include #include -#if defined HAVE_X11 && !defined K_WS_QTONLY +#if defined HAVE_X11 #include #include #endif #include "config-kdialog.h" #ifdef Qt5DBus_FOUND #include #include #endif #ifdef Q_WS_WIN #include #endif #include #include #include using namespace std; // this class hooks into the eventloop and outputs the id // of shown dialogs or makes the dialog transient for other winids. // Will destroy itself on app exit. class WinIdEmbedder: public QObject { public: WinIdEmbedder(bool printID, WId winId): QObject(qApp), print(printID), id(winId) { if (qApp) qApp->installEventFilter(this); } protected: bool eventFilter(QObject *o, QEvent *e) Q_DECL_OVERRIDE; private: bool print; WId id; }; bool WinIdEmbedder::eventFilter(QObject *o, QEvent *e) { if (e->type() == QEvent::Show && o->isWidgetType() && o->inherits("QDialog")) { QWidget *w = static_cast(o); if (print) cout << "winId: " << w->winId() << endl; if (id) KWindowSystem::setMainWindow(w, id); deleteLater(); // WinIdEmbedder is not needed anymore after the first dialog was shown return false; } return QObject::eventFilter(o, e); } /** * Display a passive notification popup using the D-Bus interface, if possible. * @return true if the notification was successfully sent, false otherwise. */ static bool sendVisualNotification(const QString &text, const QString &title, const QString &icon, int timeout) { #ifdef Qt5DBus_FOUND const QString dbusServiceName = "org.freedesktop.Notifications"; const QString dbusInterfaceName = "org.freedesktop.Notifications"; const QString dbusPath = "/org/freedesktop/Notifications"; // check if service already exists on plugin instantiation QDBusConnectionInterface* interface = QDBusConnection::sessionBus().interface(); if (!interface || !interface->isServiceRegistered(dbusServiceName)) { //kDebug() << dbusServiceName << "D-Bus service not registered"; return false; } if (timeout == 0) timeout = 10 * 1000; QDBusMessage m = QDBusMessage::createMethodCall(dbusServiceName, dbusPath, dbusInterfaceName, "Notify"); QList args; args.append("kdialog"); // app_name args.append(0U); // replaces_id args.append(icon); // app_icon args.append(title); // summary args.append(text); // body args.append(QStringList()); // actions - unused for plain passive popups args.append(QVariantMap()); // hints - unused atm args.append(timeout); // expire timout m.setArguments(args); QDBusMessage replyMsg = QDBusConnection::sessionBus().call(m); if(replyMsg.type() == QDBusMessage::ReplyMessage) { if (!replyMsg.arguments().isEmpty()) { return true; } // Not displaying any error messages as this is optional for kdialog // and KPassivePopup is a perfectly valid fallback. //else { // kDebug() << "Error: received reply with no arguments."; //} } else if (replyMsg.type() == QDBusMessage::ErrorMessage) { //kDebug() << "Error: failed to send D-Bus message"; //kDebug() << replyMsg; } else { //kDebug() << "Unexpected reply type"; } #endif return false; } static void outputStringList(const QStringList &list, bool separateOutput) { if ( separateOutput) { for ( QStringList::ConstIterator it = list.constBegin(); it != list.constEnd(); ++it ) { cout << (*it).toLocal8Bit().data() << endl; } } else { for ( QStringList::ConstIterator it = list.constBegin(); it != list.constEnd(); ++it ) { cout << (*it).toLocal8Bit().data() << " "; } cout << endl; } } static void outputStringList(const QList &list, bool separateOutput) { if ( separateOutput) { for ( auto it = list.constBegin(); it != list.constEnd(); ++it ) { cout << (*it).toDisplayString().toLocal8Bit().data() << endl; } } else { for ( auto it = list.constBegin(); it != list.constEnd(); ++it ) { cout << (*it).toDisplayString().toLocal8Bit().data() << " "; } cout << endl; } } static KGuiItem configuredYes(const QString &text) { return KGuiItem( text, "dialog-ok" ); } static KGuiItem configuredNo(const QString &text) { return KGuiItem( text, "process-stop" ); } static KGuiItem configuredCancel(const QString &text) { return KGuiItem( text, "dialog-cancel" ); } static KGuiItem configuredContinue(const QString &text) { return KGuiItem( text, "arrow-right" ); } int main(int argc, char *argv[]) { // Bug 373677: Qt removes various arguments it treats internally (such as title and icon) from args // and applies them to the first Qt::Window, while here we only show dialogs // so we need to store them before we even create our QApplication QStringList rawArgs; for (int i = 0; i < argc; ++i) { rawArgs << QString::fromLocal8Bit(argv[i]); } KLocalizedString::setApplicationDomain("kdialog"); QApplication app(argc, argv); // enable high dpi support app.setAttribute(Qt::AA_UseHighDpiPixmaps, true); KAboutData aboutData( "kdialog", i18n("KDialog"), "1.0", i18n( "KDialog can be used to show nice dialog boxes from shell scripts" ), KAboutLicense::GPL, i18n("(C) 2000, Nick Thompson")); aboutData.addAuthor(i18n("David Faure"), i18n("Current maintainer"),"faure@kde.org"); aboutData.addAuthor(i18n("Brad Hards"), QString(), "bradh@frogmouth.net"); aboutData.addAuthor(i18n("Nick Thompson"),QString(), 0/*"nickthompson@lucent.com" bounces*/); aboutData.addAuthor(i18n("Matthias Hölzer"),QString(),"hoelzer@kde.org"); aboutData.addAuthor(i18n("David Gümbel"),QString(),"david.guembel@gmx.net"); aboutData.addAuthor(i18n("Richard Moore"),QString(),"rich@kde.org"); aboutData.addAuthor(i18n("Dawit Alemayehu"),QString(),"adawit@kde.org"); aboutData.addAuthor(i18n("Kai Uwe Broulik"),QString(),"kde@privat.broulik.de"); QApplication::setWindowIcon(QIcon::fromTheme("system-run")); QCommandLineParser parser; KAboutData::setApplicationData(aboutData); parser.addVersionOption(); parser.addHelpOption(); aboutData.setupCommandLine(&parser); parser.addOption(QCommandLineOption(QStringList() << QLatin1String("yesno"), i18n("Question message box with yes/no buttons"), QLatin1String("text"))); parser.addOption(QCommandLineOption(QStringList() << QLatin1String("yesnocancel"), i18n("Question message box with yes/no/cancel buttons"), QLatin1String("text"))); parser.addOption(QCommandLineOption(QStringList() << QLatin1String("warningyesno"), i18n("Warning message box with yes/no buttons"), QLatin1String("text"))); parser.addOption(QCommandLineOption(QStringList() << QLatin1String("warningcontinuecancel"), i18n("Warning message box with continue/cancel buttons"), QLatin1String("text"))); parser.addOption(QCommandLineOption(QStringList() << QLatin1String("warningyesnocancel"), i18n("Warning message box with yes/no/cancel buttons"), QLatin1String("text"))); parser.addOption(QCommandLineOption(QStringList() << QLatin1String("yes-label"), i18n("Use text as Yes button label"), QLatin1String("text"))); parser.addOption(QCommandLineOption(QStringList() << QLatin1String("no-label"), i18n("Use text as No button label"), QLatin1String("text"))); parser.addOption(QCommandLineOption(QStringList() << QLatin1String("cancel-label"), i18n("Use text as Cancel button label"), QLatin1String("text"))); parser.addOption(QCommandLineOption(QStringList() << QLatin1String("continue-label"), i18n("Use text as Continue button label"), QLatin1String("text"))); parser.addOption(QCommandLineOption(QStringList() << QLatin1String("sorry"), i18n("'Sorry' message box"), QLatin1String("text"))); parser.addOption(QCommandLineOption(QStringList() << QLatin1String("detailedsorry"), i18n("'Sorry' message box with expandable Details field"), QLatin1String("text> {xX}][{+-}{+-}]"), QLatin1String("geometry"))); parser.addPositionalArgument(QLatin1String("[arg]"), i18n("Arguments - depending on main option")); parser.process(rawArgs); aboutData.processCommandLine(&parser); // execute kdialog command const QStringList args = parser.positionalArguments(); - QString title; - bool separateOutput = false; - bool printWId = parser.isSet("print-winid"); + const QString title = parser.value("title"); + const bool separateOutput = parser.isSet("separate-output"); + const bool printWId = parser.isSet("print-winid"); QString defaultEntry; - - // --title text - if (parser.isSet("title")) { - title = parser.value("title"); - } - - // --separate-output - if (parser.isSet("separate-output")) - { - separateOutput = true; - } + const QString geometry = parser.value("geometry"); + Utils::setGeometry(geometry); WId winid = 0; bool attach = parser.isSet("attach"); if(attach) { #ifdef Q_WS_WIN winid = reinterpret_cast(parser.value("attach").toLong(&attach, 0)); //C style parsing. If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used. #else winid = parser.value("attach").toLong(&attach, 0); //C style parsing. If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used. #endif } else if(parser.isSet("embed")) { /* KDialog originally used --embed for attaching the dialog box. However this is misleading and so we changed to --attach. * For consistancy, we silently map --embed to --attach */ attach = true; #ifdef Q_WS_WIN winid = reinterpret_cast(parser.value("embed").toLong(&attach, 0)); //C style parsing. If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used. #else winid = parser.value("embed").toLong(&attach, 0); //C style parsing. If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used. #endif } if (printWId || attach) { (void)new WinIdEmbedder(printWId, winid); } // button labels // Initialize with default labels KGuiItem yesButton = KStandardGuiItem::yes(); KGuiItem noButton = KStandardGuiItem::no(); KGuiItem cancelButton = KStandardGuiItem::cancel(); KGuiItem continueButton = KStandardGuiItem::cont(); // Customize the asked labels if (parser.isSet("yes-label")) { yesButton = configuredYes( parser.value("yes-label") ); } if (parser.isSet("no-label")) { noButton = configuredNo( parser.value("no-label") ); } if (parser.isSet("cancel-label")) { cancelButton = configuredCancel( parser.value("cancel-label") ); } if (parser.isSet("continue-label")) { continueButton = configuredContinue( parser.value("continue-label") ); } // --yesno and other message boxes KMessageBox::DialogType type = static_cast(0); QByteArray option; if (parser.isSet("yesno")) { option = "yesno"; type = KMessageBox::QuestionYesNo; } else if (parser.isSet("yesnocancel")) { option = "yesnocancel"; type = KMessageBox::QuestionYesNoCancel; } else if (parser.isSet("warningyesno")) { option = "warningyesno"; type = KMessageBox::WarningYesNo; } else if (parser.isSet("warningcontinuecancel")) { option = "warningcontinuecancel"; type = KMessageBox::WarningContinueCancel; } else if (parser.isSet("warningyesnocancel")) { option = "warningyesnocancel"; type = KMessageBox::WarningYesNoCancel; } else if (parser.isSet("sorry")) { option = "sorry"; type = KMessageBox::Sorry; } else if (parser.isSet("detailedsorry")) { option = "detailedsorry"; } else if (parser.isSet("error")) { option = "error"; type = KMessageBox::Error; } else if (parser.isSet("detailederror")) { option = "detailederror"; } else if (parser.isSet("msgbox")) { option = "msgbox"; type = KMessageBox::Information; } if ( !option.isEmpty() ) { KConfig* dontagaincfg = NULL; // --dontagain QString dontagain; // QString() if (parser.isSet("dontagain")) { QString value = parser.value("dontagain"); QStringList values = value.split( ':', QString::SkipEmptyParts ); if( values.count() == 2 ) { dontagaincfg = new KConfig( values[ 0 ] ); KMessageBox::setDontShowAgainConfig( dontagaincfg ); dontagain = values[ 1 ]; } else qDebug( "Incorrect --dontagain!" ); } int ret = 0; - QString text = Widgets::parseString(parser.value(option)); + QString text = Utils::parseString(parser.value(option)); QString details; if (args.count() == 1) { - details = Widgets::parseString(args.at(0)); + details = Utils::parseString(args.at(0)); } if ( type == KMessageBox::WarningContinueCancel ) { ret = KMessageBox::messageBox( 0, type, text, title, continueButton, noButton, cancelButton, dontagain ); } else if (option == "detailedsorry") { KMessageBox::detailedSorry( 0, text, details, title ); } else if (option == "detailederror") { KMessageBox::detailedError( 0, text, details, title ); } else { ret = KMessageBox::messageBox( 0, type, text, title, yesButton, noButton, cancelButton, dontagain ); } delete dontagaincfg; // ret is 1 for Ok, 2 for Cancel, 3 for Yes, 4 for No and 5 for Continue. // We want to return 0 for ok, yes and continue, 1 for no and 2 for cancel return (ret == KMessageBox::Ok || ret == KMessageBox::Yes || ret == KMessageBox::Continue) ? 0 : ( ret == KMessageBox::No ? 1 : 2 ); } // --inputbox text [init] if (parser.isSet("inputbox")) { QString result; QString init; if (args.count() > 0) { init = args.at(0); } const bool retcode = Widgets::inputBox(0, title, parser.value("inputbox"), init, result); cout << result.toLocal8Bit().data() << endl; return retcode ? 0 : 1; } // --password text if (parser.isSet("password")) { QString result; const bool retcode = Widgets::passwordBox(0, title, parser.value("password"), result); cout << qPrintable(result) << endl; return retcode ? 0 : 1; } // --passivepopup if (parser.isSet("passivepopup")) { int timeout = 0; if (args.count() > 0) { timeout = 1000 * args.at(0).toInt(); } if (timeout < 0) { timeout = -1; } // Use --icon parameter for passivepopup as well QString icon; if (parser.isSet("icon")) { icon = parser.value("icon"); } else { icon = "dialog-information"; // Use generic (i)-icon if none specified } // try to use more stylish notifications - if (sendVisualNotification(Widgets::parseString(parser.value("passivepopup")), title, icon, timeout)) + if (sendVisualNotification(Utils::parseString(parser.value("passivepopup")), title, icon, timeout)) return 0; // ...did not work, use KPassivePopup as fallback // parse timeout time again, so it does not auto-close the fallback (timer cannot handle -1 time) if (args.count() > 0) { timeout = 1000 * args.at(0).toInt(); } if (timeout <= 0) { timeout = 10*1000; // 10 seconds should be a decent time for auto-closing (you can override this using a parameter) } QPixmap passiveicon; if (parser.isSet("icon")) { // Only show icon if explicitly requested passiveicon = KIconLoader::global()->loadIcon(icon, KIconLoader::Dialog); } KPassivePopup *popup = KPassivePopup::message( KPassivePopup::Boxed, // style title, - Widgets::parseString(parser.value("passivepopup")), + Utils::parseString(parser.value("passivepopup")), passiveicon, (QWidget*)0UL, // parent timeout ); KDialog::centerOnScreen( popup ); QTimer *timer = new QTimer(); QObject::connect( timer, SIGNAL(timeout()), qApp, SLOT(quit()) ); QObject::connect( popup, SIGNAL(clicked()), qApp, SLOT(quit()) ); timer->setSingleShot( true ); timer->start( timeout ); #ifdef HAVE_X11 - QString geometry; - if (parser.isSet("geometry")) - geometry = parser.value("geometry"); - if ( !geometry.isEmpty()) { + if ( !geometry.isEmpty()) { int x, y; int w, h; - int m = XParseGeometry( geometry.toLatin1().constData(), &x, &y, (unsigned int*)&w, (unsigned int*)&h); + int m = XParseGeometry( geometry.toLatin1().constData(), &x, &y, (unsigned int*)&w, (unsigned int*)&h); if ( (m & XNegative) ) - x = QApplication::desktop()->width() + x - w; + x = QApplication::desktop()->width() + x - w; if ( (m & YNegative) ) - y = QApplication::desktop()->height() + y - h; + y = QApplication::desktop()->height() + y - h; popup->setAnchor( QPoint(x, y) ); } #endif - qApp->exec(); + qApp->exec(); return 0; - } + } // --textbox file [width] [height] if (parser.isSet("textbox")) { int w = 0; int h = 0; if (args.count() == 2) { w = args.at(0).toInt(); h = args.at(1).toInt(); } return Widgets::textBox(0, w, h, title, parser.value("textbox")); } // --textinputbox file [width] [height] if (parser.isSet("textinputbox")) { int w = 400; int h = 200; if (args.count() >= 3) { w = args.at(1).toInt(); h = args.at(2).toInt(); } QString init; if (args.count() >= 1) { - init = Widgets::parseString(args.at(0)); + init = Utils::parseString(args.at(0)); } QString result; - int ret = Widgets::textInputBox(0, w, h, title, Widgets::parseString(parser.value("textinputbox")), init, result); + int ret = Widgets::textInputBox(0, w, h, title, Utils::parseString(parser.value("textinputbox")), init, result); cout << qPrintable(result) << endl; return ret; } // --combobox item [item] ..." if (parser.isSet("combobox")) { QStringList list; if (args.count() >= 1) { for (int i = 0; i < args.count(); i++) { list.append(args.at(i)); } - const QString text = Widgets::parseString(parser.value("combobox")); + const QString text = Utils::parseString(parser.value("combobox")); if (parser.isSet("default")) { defaultEntry = parser.value("default"); } QString result; const bool retcode = Widgets::comboBox(0, title, text, list, defaultEntry, result); cout << result.toLocal8Bit().data() << endl; return retcode ? 0 : 1; } return -1; } // --menu text [tag item] [tag item] ... if (parser.isSet("menu")) { QStringList list; if (args.count() >= 2) { for (int i = 0; i < args.count(); i++) { list.append(args.at(i)); } - const QString text = Widgets::parseString(parser.value("menu")); + const QString text = Utils::parseString(parser.value("menu")); if (parser.isSet("default")) { defaultEntry = parser.value("default"); } QString result; const bool retcode = Widgets::listBox(0, title, text, list, defaultEntry, result); if (1 == retcode) { // OK was selected cout << result.toLocal8Bit().data() << endl; } return retcode ? 0 : 1; } return -1; } // --checklist text [tag item status] [tag item status] ... if (parser.isSet("checklist")) { QStringList list; if (args.count() >= 3) { for (int i = 0; i < args.count(); i++) { list.append(args.at(i)); } - const QString text = Widgets::parseString(parser.value("checklist")); + const QString text = Utils::parseString(parser.value("checklist")); QStringList result; const bool retcode = Widgets::checkList(0, title, text, list, separateOutput, result); for (int i=0; i= 3) { for (int i = 0; i < args.count(); i++) { list.append(args.at(i)); } - const QString text = Widgets::parseString(parser.value("radiolist")); + const QString text = Utils::parseString(parser.value("radiolist")); QString result; const bool retcode = Widgets::radioBox(0, title, text, list, result); cout << result.toLocal8Bit().data() << endl; return retcode ? 0 : 1; } return -1; } // getopenfilename [startDir] [filter] if (parser.isSet("getopenfilename")) { QString startDir = args.count() > 0 ? args.at(0) : QString(); const QUrl startUrl = QUrl::fromUserInput(startDir); QString filter; if (args.count() > 1) { - filter = Widgets::parseString(args.at(1)); + filter = Utils::parseString(args.at(1)); } KFileDialog dlg( startUrl, filter, 0 ); dlg.setOperationMode( KFileDialog::Opening ); if (parser.isSet("multiple")) { dlg.setMode(KFile::Files | KFile::LocalOnly); } else { dlg.setMode(KFile::File | KFile::LocalOnly); } - Widgets::handleXGeometry(&dlg); + Utils::handleXGeometry(&dlg); dlg.setWindowTitle(title.isEmpty() ? i18nc("@title:window", "Open") : title); dlg.exec(); if (parser.isSet("multiple")) { const QStringList result = dlg.selectedFiles(); if ( !result.isEmpty() ) { outputStringList( result, separateOutput ); return 0; } } else { const QString result = dlg.selectedFile(); if (!result.isEmpty()) { cout << result.toLocal8Bit().data() << endl; return 0; } } return 1; // canceled } // getsaveurl [startDir] [filter] // getsavefilename [startDir] [filter] if ( (parser.isSet("getsavefilename") ) || (parser.isSet("getsaveurl") ) ) { QString startDir = args.count() > 0 ? args.at(0) : QString(); QString filter; const QUrl startUrl = QUrl::fromUserInput(startDir); if (args.count() > 1) { - filter = Widgets::parseString(args.at(1)); + filter = Utils::parseString(args.at(1)); } // copied from KFileDialog::getSaveFileName(), so we can add geometry bool specialDir = startDir.startsWith(QLatin1Char(':')); if ( !specialDir ) { KFileItem kfi(startUrl); specialDir = kfi.isDir(); } KFileDialog dlg( specialDir ? startUrl : QUrl(), filter, 0 ); if ( !specialDir ) dlg.setSelection( startDir ); dlg.setOperationMode( KFileDialog::Saving ); - Widgets::handleXGeometry(&dlg); + Utils::handleXGeometry(&dlg); dlg.setWindowTitle(title.isEmpty() ? i18nc("@title:window", "Save As") : title); dlg.exec(); if ( parser.isSet("getsaveurl") ) { const QUrl result = dlg.selectedUrl(); if ( result.isValid()) { cout << result.url().toLocal8Bit().data() << endl; return 0; } } else { // getsavefilename const QString result = dlg.selectedFile(); if (!result.isEmpty()) { KRecentDocument::add(QUrl::fromLocalFile(result)); cout << result.toLocal8Bit().data() << endl; return 0; } } return 1; // canceled } // getexistingdirectory [startDir] if (parser.isSet("getexistingdirectory")) { QString startDir = args.count() > 0 ? args.at(0) : QString(); const QUrl startUrl = QUrl::fromUserInput(startDir); QString result; #ifdef Q_WS_WIN result = QFileDialog::getExistingDirectory( 0, title, startDir, QFileDialog::DontResolveSymlinks | QFileDialog::ShowDirsOnly); #else QUrl url; KDirSelectDialog myDialog( startUrl, true, 0 ); - Widgets::handleXGeometry(&myDialog); + Utils::handleXGeometry(&myDialog); if ( !title.isEmpty() ) myDialog.setWindowTitle( title ); if ( myDialog.exec() == QDialog::Accepted ) url = myDialog.url(); if ( url.isValid() ) result = url.path(); #endif if (!result.isEmpty()) { cout << result.toLocal8Bit().data() << endl; return 0; } return 1; // canceled } // getopenurl [startDir] [filter] if (parser.isSet("getopenurl")) { QString startDir = args.count() > 0 ? args.at(0) : QString(); const QUrl startUrl = QUrl::fromUserInput(startDir); QString filter; if (args.count() > 1) { - filter = Widgets::parseString(args.at(1)); + filter = Utils::parseString(args.at(1)); } KFileDialog dlg( startUrl, filter, 0 ); dlg.setOperationMode( KFileDialog::Opening ); if (parser.isSet("multiple")) { dlg.setMode(KFile::Files); } else { dlg.setMode(KFile::File); } - Widgets::handleXGeometry(&dlg); + Utils::handleXGeometry(&dlg); dlg.setWindowTitle(title.isEmpty() ? i18nc("@title:window", "Open") : title); dlg.exec(); if (parser.isSet("multiple")) { const QList result = dlg.selectedUrls(); if ( !result.isEmpty() ) { outputStringList( result, separateOutput ); return 0; } } else { const QUrl result = dlg.selectedUrl(); if (!result.isEmpty()) { cout << result.url().toLocal8Bit().data() << endl; return 0; } } return 1; // canceled } // geticon [group] [context] if (parser.isSet("geticon")) { QString groupStr, contextStr; groupStr = parser.value("geticon"); if (args.count() >= 1) { contextStr = args.at(0); } const KIconLoader::Group group = ( groupStr == QLatin1String( "Desktop" ) ) ? KIconLoader::Desktop : ( groupStr == QLatin1String( "Toolbar" ) ) ? KIconLoader::Toolbar : ( groupStr == QLatin1String( "MainToolbar" ) ) ? KIconLoader::MainToolbar : ( groupStr == QLatin1String( "Small" ) ) ? KIconLoader::Small : ( groupStr == QLatin1String( "Panel" ) ) ? KIconLoader::Panel : ( groupStr == QLatin1String( "Dialog" ) ) ? KIconLoader::Dialog : ( groupStr == QLatin1String( "User" ) ) ? KIconLoader::User : /* else */ KIconLoader::NoGroup; const KIconLoader::Context context = ( contextStr == QLatin1String( "Action" ) ) ? KIconLoader::Action : ( contextStr == QLatin1String( "Application" ) ) ? KIconLoader::Application : ( contextStr == QLatin1String( "Device" ) ) ? KIconLoader::Device : ( contextStr == QLatin1String( "FileSystem" ) ) ? KIconLoader::FileSystem : ( contextStr == QLatin1String( "MimeType" ) ) ? KIconLoader::MimeType : ( contextStr == QLatin1String( "Animation" ) ) ? KIconLoader::Animation : ( contextStr == QLatin1String( "Category" ) ) ? KIconLoader::Category : ( contextStr == QLatin1String( "Emblem" ) ) ? KIconLoader::Emblem : ( contextStr == QLatin1String( "Emote" ) ) ? KIconLoader::Emote : ( contextStr == QLatin1String( "International" ) ) ? KIconLoader::International : ( contextStr == QLatin1String( "Place" ) ) ? KIconLoader::Place : ( contextStr == QLatin1String( "StatusIcon" ) ) ? KIconLoader::StatusIcon : // begin: KDE3 compatibility (useful?) ( contextStr == QLatin1String( "Devices" ) ) ? KIconLoader::Device : ( contextStr == QLatin1String( "MimeTypes" ) ) ? KIconLoader::MimeType : ( contextStr == QLatin1String( "FileSystems" ) ) ? KIconLoader::FileSystem : ( contextStr == QLatin1String( "Applications" ) ) ? KIconLoader::Application : ( contextStr == QLatin1String( "Actions" ) ) ? KIconLoader::Action : // end: KDE3 compatibility /* else */ KIconLoader::Any; KIconDialog dlg((QWidget*)Q_NULLPTR); dlg.setup( group, context); dlg.setIconSize(KIconLoader::SizeHuge); if (!title.isEmpty()) dlg.setWindowTitle(title); - Widgets::handleXGeometry(&dlg); + Utils::handleXGeometry(&dlg); const QString result = dlg.openDialog(); if (!result.isEmpty()) { cout << result.toLocal8Bit().data() << endl; return 0; } return 1; // canceled } // --progressbar text totalsteps if (parser.isSet("progressbar")) { - cout << "org.kde.kdialog-" << getpid() << " /ProgressDialog" << endl; - if (fork()) - _exit(0); - close(1); - - int totalsteps = 100; - const QString text = Widgets::parseString(parser.value("progressbar")); - - if (args.count() == 1) - totalsteps = args.at(0).toInt(); - - return Widgets::progressBar(0, title, text, totalsteps) ? 1 : 0; + const QString text = Utils::parseString(parser.value("progressbar")); + + QProcess process; + QStringList arguments; + arguments << QStringLiteral("--progressbar"); + arguments << text; + arguments << QStringLiteral("--title"); + arguments << title; + if (args.count() == 1) { + arguments << args.at(0); + } + qint64 pid = 0; + if (process.startDetached("kdialog_progress_helper", arguments, QString(), &pid)) { + const QString serviceName = QStringLiteral("org.kde.kdialog-") + QString::number(pid); + std::cout << serviceName.toLatin1().constData() << " /ProgressDialog" << std::endl << std::flush; + return 0; + } + qWarning() << "Error starting kdialog_progress_helper"; + return 1; } // --getcolor if (parser.isSet("getcolor")) { KColorDialog dlg((QWidget*)0L, true); if (parser.isSet("default")) { defaultEntry = parser.value("default"); dlg.setColor(defaultEntry); } else { QColor color = KColorMimeData::fromMimeData(QApplication::clipboard()->mimeData(QClipboard::Clipboard)); if (color.isValid()) { dlg.setColor(color); } } - Widgets::handleXGeometry(&dlg); + Utils::handleXGeometry(&dlg); dlg.setWindowTitle(title.isEmpty() ? i18nc("@title:window", "Choose Color") : title); if (dlg.exec() == KColorDialog::Accepted) { QString result; QRegularExpressionMatch match; if (dlg.color().isValid() && parser.isSet("format")) { bool found = false; QString format = parser.value("format"); format.remove(QChar('*')); // stripped out * for safety QList pattern_pool; pattern_pool << QRegularExpression("(%#?[-+]?\\d*\\.?\\d*(?:ll|hh|l|h)?[diouxX])") << QRegularExpression("(%#?[-+]?\\d*\\.?\\d*[l]?[efgEFG])"); for (int i = 0; i < pattern_pool.size(); i++) { QRegularExpressionMatchIterator itor = pattern_pool.at(i).globalMatch(format); QRegularExpressionMatch match; int match_count = 0; while (itor.hasNext()) { match = itor.next(); if (match.hasMatch()) { match_count++; } } // currently only handle RGB, when alpha is ready, should hit 4 if (3 == match_count) { found = true; if (match.captured(0).contains(QRegularExpression("[diouxX]"))) { result = QString::asprintf(format.toUtf8().constData(), dlg.color().red(), dlg.color().green(), dlg.color().blue()); } else { result = QString::asprintf(format.toUtf8().constData(), dlg.color().redF(), dlg.color().greenF(), dlg.color().blueF()); } break; } } if (false == found) { cout << "Invalid format pattern"; } } else { result = dlg.color().name(); } cout << result.toLocal8Bit().data() << endl; return 0; } return 1; // cancelled } if (parser.isSet("slider")) { int miniValue = 0; int maxValue = 0; int step = 0; - const QString text = Widgets::parseString(parser.value("slider")); + const QString text = Utils::parseString(parser.value("slider")); if (args.count() == 3) { miniValue = args.at(0).toInt(); maxValue = args.at( 1 ).toInt(); step = args.at( 2 ).toInt(); } int result = 0; const bool returnCode = Widgets::slider(0, title, text, miniValue, maxValue, step, result); if ( returnCode ) cout << result << endl; return returnCode; } if (parser.isSet("calendar")) { - const QString text = Widgets::parseString(parser.value("calendar")); + const QString text = Utils::parseString(parser.value("calendar")); QDate result; const bool returnCode = Widgets::calendar(0, title, text, result); if ( returnCode ) cout << result.toString().toLocal8Bit().data() << endl; return returnCode; } parser.showHelp(); return -2; // NOTREACHED } diff --git a/src/kdialog_progress_helper.cpp b/src/kdialog_progress_helper.cpp new file mode 100644 index 000000000..a851cb002 --- /dev/null +++ b/src/kdialog_progress_helper.cpp @@ -0,0 +1,57 @@ +// Copyright (C) 2017 David Faure +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the7 implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// + +#include +#include +#include +#include +#include +#include "progressdialog.h" +#include "utils.h" + +int main(int argc, char **argv) +{ + QStringList rawArgs; + for (int i = 0; i < argc; ++i) { + rawArgs << QString::fromLocal8Bit(argv[i]); + } + + KLocalizedString::setApplicationDomain("kdialog"); + + QApplication app(argc, argv); + app.setApplicationName("kdialog"); + app.setOrganizationDomain("kde.org"); + KDBusService dbusService(KDBusService::Multiple); + + QCommandLineParser parser; + parser.addOption(QCommandLineOption(QStringList() << QLatin1String("progressbar"), i18n("Progress bar dialog, returns a D-Bus reference for communication"), QLatin1String("text"))); + parser.addOption(QCommandLineOption(QStringList() << QLatin1String("title"), i18n("Dialog title"), QLatin1String("text"))); + parser.addPositionalArgument(QLatin1String("[arg]"), i18n("Arguments - depending on main option")); + parser.process(rawArgs); + + const QStringList args = parser.positionalArguments(); + + const QString text = Utils::parseString(parser.value("progressbar")); + const QString title = parser.value("title"); + + int totalsteps = 100; + if (args.count() == 1) + totalsteps = args.at(0).toInt(); + + ProgressDialog dlg(0, title, text, totalsteps); + return dlg.exec() ? 0 : 1; +} diff --git a/src/progressdialog.cpp b/src/progressdialog.cpp index 187d23b9a..1f425dd48 100644 --- a/src/progressdialog.cpp +++ b/src/progressdialog.cpp @@ -1,95 +1,39 @@ // // Copyright (C) 2004-2005 Stephan Binner // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the7 implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // #include "progressdialog.h" -#include "kdebug.h" -#include "widgets.h" -#include -#include "progressdialogadaptor.h" +#include "utils.h" +#include "progressdialogadaptor.h" +#include ProgressDialog::ProgressDialog(QWidget* parent, const QString& caption, const QString& text, int totalSteps) - : KProgressDialog(parent, caption, text, 0) + : QProgressDialog(parent) { + setWindowTitle(caption); + setLabelText(text); (void)new ProgressDialogAdaptor( this ); QDBusConnection::sessionBus().registerObject( QLatin1String("/ProgressDialog"), this ); setAutoClose( false ); - progressBar()->setMaximum( totalSteps ); - showCancelButton( false ); - Widgets::handleXGeometry(this); + setMaximum( totalSteps ); + Utils::handleXGeometry(this); } -void ProgressDialog::setMaximum( int totalSteps ) +void ProgressDialog::showCancelButton(bool show) { - progressBar()->setMaximum( totalSteps ); - if ( progressBar()->value()>=totalSteps ) - showCancelButton( false ); + setCancelButtonText(show ? i18n("Cancel") : QString()); } - -int ProgressDialog::maximum() const -{ - return progressBar()->maximum(); -} - -void ProgressDialog::setValue( int progress ) -{ - progressBar()->setValue( progress ); - if (progress>=maximum() ) - showCancelButton( false ); -} - -int ProgressDialog::value() const -{ - return progressBar()->value(); -} - -void ProgressDialog::setLabelText(const QString& label) -{ - KProgressDialog::setLabelText( label ); -} - -void ProgressDialog::showCancelButton( bool show ) -{ - setAllowCancel( false ); - KProgressDialog::showCancelButton( show ); -} - -bool ProgressDialog::wasCancelled() const -{ - return KProgressDialog::wasCancelled(); -} - -void ProgressDialog::ignoreCancel() -{ - KProgressDialog::ignoreCancel(); -} - -void ProgressDialog::setAutoClose( bool close ) -{ - KProgressDialog::setAutoClose( close ); -} - -bool ProgressDialog::autoClose() const -{ - return KProgressDialog::autoClose(); -} - -void ProgressDialog::close() -{ - slotButtonClicked(KDialog::Close); -} - diff --git a/src/progressdialog.h b/src/progressdialog.h index bac64298f..84a7580ff 100644 --- a/src/progressdialog.h +++ b/src/progressdialog.h @@ -1,53 +1,37 @@ // // Copyright (C) 2004-2005 Stephan Binner // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the7 implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // #ifndef PROGRESSDIALOG_H #define PROGRESSDIALOG_H -#include -class ProgressDialog : public KProgressDialog +#include + +class ProgressDialog : public QProgressDialog { Q_OBJECT - Q_PROPERTY(int value READ value WRITE setValue) - Q_PROPERTY(int maximum READ maximum WRITE setMaximum) - Q_PROPERTY(bool autoClose READ autoClose WRITE setAutoClose) public: - explicit ProgressDialog(QWidget* parent = 0, - const QString& caption = QString(), + explicit ProgressDialog(QWidget* parent = Q_NULLPTR, + const QString& caption = QString(), const QString& text = QString(), int totalSteps = 100); - - void setMaximum( int ); - int maximum() const; - - void setValue( int ); - int value() const; - - void setLabelText(const QString&); - - void showCancelButton(bool show); - bool wasCancelled() const; - void ignoreCancel(); - void setAutoClose( bool ); - bool autoClose() const; - - void close(); + void showCancelButton(bool show); + bool wasCancelled() const { return wasCanceled(); } }; #endif // PROGRESSDIALOG_H diff --git a/src/utils.cpp b/src/utils.cpp new file mode 100644 index 000000000..631ae348c --- /dev/null +++ b/src/utils.cpp @@ -0,0 +1,85 @@ +// Copyright (C) 2017 David Faure +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the7 implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// + +#include "utils.h" +#include +#include +#include +#include "config-kdialog.h" + +#if defined HAVE_X11 && ! defined K_WS_QTONLY +#include +#include +#endif + +static QString xGeometry; + +void Utils::setGeometry(const QString &geometry) +{ + xGeometry = geometry; +} + +void Utils::handleXGeometry(QWidget * dlg) +{ +#ifdef HAVE_X11 + if ( !xGeometry.isEmpty()) { + int x, y; + int w, h; + int m = XParseGeometry( xGeometry.toLatin1().constData(), &x, &y, (unsigned int*)&w, (unsigned int*)&h); + if ( (m & XNegative) ) + x = QApplication::desktop()->width() + x - w; + if ( (m & YNegative) ) + y = QApplication::desktop()->height() + y - h; + dlg->setGeometry(x, y, w, h); + qDebug() << "x: " << x << " y: " << y << " w: " << w << " h: " << h; + } +#endif +} + +QString Utils::parseString(const QString &str) +{ + QString ret; + ret.reserve(str.size()); + bool escaped = false; + for (int i = 0; i < str.size(); i++) { + QChar c = str.at(i); + if (escaped) { + escaped = false; + if (c == '\\') { + ret += c; + } else if (c == 'n') { + ret += '\n'; + } else { + qWarning() << qPrintable(QString::fromLatin1("Unrecognized escape sequence \\%1").arg(c)); + ret += '\\'; + ret += c; + } + } else { + if (c == '\\') { + escaped = true; + } else { + ret += c; + } + } + } + if (escaped) { + qWarning() << "Unterminated escape sequence"; + ret += '\\'; + } + return ret; +} + diff --git a/src/utils.h b/src/utils.h new file mode 100644 index 000000000..487860f0b --- /dev/null +++ b/src/utils.h @@ -0,0 +1,31 @@ +// Copyright (C) 2017 David Faure +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the7 implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// + +#ifndef UTILS_P_H +#define UTILS_P_H + +#include +class QWidget; + +namespace Utils +{ + void setGeometry(const QString &geometry); + void handleXGeometry(QWidget * dlg); + QString parseString(const QString &str); +} + +#endif diff --git a/src/widgets.cpp b/src/widgets.cpp index 38ee0cb99..78ecf0a9e 100644 --- a/src/widgets.cpp +++ b/src/widgets.cpp @@ -1,405 +1,336 @@ // // Copyright (C) 1998 Matthias Hoelzer // Copyright (C) 2002-2005 David Faure // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the7 implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // Own #include "config-kdialog.h" #include "widgets.h" +#include "utils.h" // Qt #include #include #include #include #include // KDE -#include #include #include #include #include #include #include #include #include #include // Local #include "klistboxdialog.h" #include "progressdialog.h" -#if defined HAVE_X11 && ! defined K_WS_QTONLY -#include -#include -#endif - -void Widgets::handleXGeometry(QWidget * dlg) -{ -#ifdef HAVE_X11 - QString geometry; - KCmdLineArgs *args = KCmdLineArgs::parsedArgs("kde"); - if (args && args->isSet("geometry")) - geometry = args->getOption("geometry"); - if ( !geometry.isEmpty()) { - int x, y; - int w, h; - int m = XParseGeometry( geometry.toLatin1().constData(), &x, &y, (unsigned int*)&w, (unsigned int*)&h); - if ( (m & XNegative) ) - x = KApplication::desktop()->width() + x - w; - if ( (m & YNegative) ) - y = KApplication::desktop()->height() + y - h; - dlg->setGeometry(x, y, w, h); - kDebug() << "x: " << x << " y: " << y << " w: " << w << " h: " << h; - } -#endif -} - bool Widgets::inputBox(QWidget *parent, const QString& title, const QString& text, const QString& init, QString &result) { bool ok; const QString str = KInputDialog::getText( title, text, init, &ok, parent, 0, 0, QString() ); if ( ok ) result = str; return ok; } bool Widgets::passwordBox(QWidget *parent, const QString& title, const QString& text, QString &result) { KPasswordDialog dlg( parent ); kapp->setTopWidget( &dlg ); dlg.setWindowTitle(title); dlg.setPrompt(text); - handleXGeometry(&dlg); + Utils::handleXGeometry(&dlg); bool retcode = (dlg.exec() == QDialog::Accepted); if ( retcode ) result = dlg.password(); return retcode; } int Widgets::textBox(QWidget *parent, int width, int height, const QString& title, const QString& file) { // KTextBox dlg(parent, 0, true, width, height, file); KDialog dlg( parent ); dlg.setWindowTitle( title ); dlg.setButtons( KDialog::Ok ); dlg.setModal( true ); kapp->setTopWidget( &dlg ); KVBox* vbox = new KVBox(&dlg); dlg.setMainWidget(vbox); KTextEdit *edit = new KTextEdit( vbox ); edit->setReadOnly(true); edit->setFocus(); if (file == QLatin1String("-")) { QTextStream s(stdin, QIODevice::ReadOnly); while (!s.atEnd()) edit->append(s.readLine()); } else { QFile f(file); if (!f.open(QIODevice::ReadOnly)) { kError() << i18n("kdialog: could not open file %1", file) << endl; return -1; } QTextStream s(&f); while (!s.atEnd()) edit->append(s.readLine()); } edit->setTextCursor(QTextCursor(edit->document())); if ( width > 0 && height > 0 ) dlg.setInitialSize( QSize( width, height ) ); - handleXGeometry(&dlg); + Utils::handleXGeometry(&dlg); dlg.setWindowTitle(title); return (dlg.exec() == KDialog::Accepted) ? 0 : 1; } int Widgets::textInputBox(QWidget *parent, int width, int height, const QString& title, const QString& text, const QString& init, QString &result) { // KTextBox dlg(parent, 0, true, width, height, file); KDialog dlg( parent ); dlg.setWindowTitle( title ); dlg.setButtons( KDialog::Ok ); dlg.setModal( true ); kapp->setTopWidget( &dlg ); KVBox* vbox = new KVBox(&dlg); dlg.setMainWidget(vbox); if( !text.isEmpty() ) { QLabel *label = new QLabel(vbox); label->setText(text); } KTextEdit *edit = new KTextEdit( vbox ); edit->setReadOnly(false); edit->setFocus(); edit->insertPlainText( init ); if ( width > 0 && height > 0 ) dlg.setInitialSize( QSize( width, height ) ); - handleXGeometry(&dlg); + Utils::handleXGeometry(&dlg); dlg.setWindowTitle(title); const int returnDialogCode = dlg.exec(); result = edit->toPlainText(); return (returnDialogCode == KDialog::Accepted ? 0 : 1); } bool Widgets::comboBox(QWidget *parent, const QString& title, const QString& text, const QStringList& args, const QString& defaultEntry, QString &result) { KDialog dlg( parent ); kapp->setTopWidget( &dlg ); dlg.setWindowTitle( title ); dlg.setButtons( KDialog::Ok|KDialog::Cancel ); dlg.setModal( true ); dlg.setDefaultButton( KDialog::Ok ); KVBox* vbox = new KVBox( &dlg ); dlg.setMainWidget( vbox ); QLabel label (vbox); label.setText (text); KComboBox combo (vbox); combo.insertItems (0, args); combo.setCurrentIndex( combo.findText( defaultEntry ) ); combo.setFocus(); - handleXGeometry(&dlg); + Utils::handleXGeometry(&dlg); bool retcode = (dlg.exec() == QDialog::Accepted); if (retcode) result = combo.currentText(); return retcode; } bool Widgets::listBox(QWidget *parent, const QString& title, const QString& text, const QStringList& args, const QString& defaultEntry, QString &result) { KListBoxDialog box(text,parent); kapp->setTopWidget( &box ); box.setWindowTitle(title); for (int i = 0; i+1setTopWidget( &box ); box.setWindowTitle(title); for (int i=0; i+2setSelected( args[i+2] == QLatin1String("on") ); } - handleXGeometry(&box); + Utils::handleXGeometry(&box); const bool retcode = (box.exec() == QDialog::Accepted); if ( retcode ) { if (separateOutput) { for (int i=0; iisSelected()) result.append(tags[i]); } else { for (int i=0; iisSelected()) rs += QLatin1String("\"") + tags[i] + QLatin1String("\" "); result.append(rs); } } return retcode; } bool Widgets::radioBox(QWidget *parent, const QString& title, const QString& text, const QStringList& args, QString &result) { QStringList entries, tags; KListBoxDialog box(text,parent); QListWidget &table = box.getTable(); kapp->setTopWidget( &box ); box.setWindowTitle(title); for (int i=0; i+2setTopWidget( &dlg ); - dlg.setWindowTitle( title ); - handleXGeometry(&dlg); - dlg.exec(); - return dlg.wasCancelled(); -} - - bool Widgets::slider( QWidget *parent, const QString& title, const QString& text, int minValue, int maxValue, int step, int &result ) { KDialog dlg( parent ); kapp->setTopWidget( &dlg ); dlg.setWindowTitle( title ); dlg.setButtons( KDialog::Ok|KDialog::Cancel ); dlg.setModal( true ); dlg.setDefaultButton( KDialog::Ok ); KVBox* vbox = new KVBox( &dlg ); dlg.setMainWidget( vbox ); QLabel label (vbox); label.setText (text); QSlider slider (vbox); slider.setMinimum( minValue ); slider.setMaximum( maxValue ); slider.setSingleStep( step ); slider.setTickPosition ( QSlider::TicksAbove ); slider.setOrientation( Qt::Horizontal ); slider.setFocus(); - handleXGeometry(&dlg); + Utils::handleXGeometry(&dlg); const bool retcode = (dlg.exec() == QDialog::Accepted); if (retcode) result = slider.value(); return retcode; } bool Widgets::calendar( QWidget *parent, const QString &title, const QString &text, QDate & result ) { KDialog dlg( parent ); kapp->setTopWidget( &dlg ); dlg.setWindowTitle( title ); dlg.setButtons( KDialog::Ok|KDialog::Cancel ); dlg.setModal( true ); dlg.setDefaultButton( KDialog::Ok ); KVBox* vbox = new KVBox( &dlg ); dlg.setMainWidget( vbox ); QLabel label (vbox); label.setText (text); KDatePicker dateWidget( vbox ); dateWidget.setFocus(); - handleXGeometry(&dlg); + Utils::handleXGeometry(&dlg); const bool retcode = (dlg.exec() == QDialog::Accepted); if (retcode) result = dateWidget.date(); return retcode; } -QString Widgets::parseString(const QString &str) -{ - QString ret; - ret.reserve(str.size()); - bool escaped = false; - for (int i = 0; i < str.size(); i++) { - QChar c = str.at(i); - if (escaped) { - escaped = false; - if (c == '\\') { - ret += c; - } else if (c == 'n') { - ret += '\n'; - } else { - kWarning() << qPrintable(QString::fromLatin1("Unrecognized escape sequence \\%1").arg(c)); - ret += '\\'; - ret += c; - } - } else { - if (c == '\\') { - escaped = true; - } else { - ret += c; - } - } - } - if (escaped) { - kWarning() << "Unterminated escape sequence"; - ret += '\\'; - } - return ret; -} diff --git a/src/widgets.h b/src/widgets.h index dd3539562..f90e0fb27 100644 --- a/src/widgets.h +++ b/src/widgets.h @@ -1,48 +1,42 @@ // // Copyright (C) 1998 Matthias Hoelzer // Copyright (C) 2002-2005 David Faure // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the7 implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // #ifndef WIDGETS_H #define WIDGETS_H #include -#include #include #include namespace Widgets { bool inputBox(QWidget *parent, const QString& title, const QString& text, const QString& init, QString &result); bool passwordBox(QWidget *parent, const QString& title, const QString& text, QString &result); int textBox(QWidget *parent, int width, int height, const QString& title, const QString& file); int textInputBox(QWidget *parent, int width, int height, const QString& title, const QString& text, const QString& init, QString &result); bool listBox(QWidget *parent, const QString& title, const QString& text, const QStringList& args, const QString &defaultEntry, QString &result); bool checkList(QWidget *parent, const QString& title, const QString& text, const QStringList& args, bool separateOutput, QStringList &result); bool radioBox(QWidget *parent, const QString& title, const QString& text, const QStringList& args, QString &result); bool comboBox(QWidget *parent, const QString& title, const QString& text, const QStringList& args, const QString& defaultEntry, QString &result); - bool progressBar(QWidget *parent, const QString& title, const QString& text, int totalSteps); bool slider( QWidget *parent, const QString& title, const QString& test, int minValue, int maxValue, int step, int &result ); bool calendar( QWidget *parent, const QString &title, const QString &text, QDate & result ); - - void handleXGeometry(QWidget * dlg); - - QString parseString(const QString &str); } #endif