diff --git a/add-printer/DevicesModel.cpp b/add-printer/DevicesModel.cpp index 99b6716..639f88c 100644 --- a/add-printer/DevicesModel.cpp +++ b/add-printer/DevicesModel.cpp @@ -1,382 +1,380 @@ /*************************************************************************** * Copyright (C) 2010-2018 by Daniel Nicoletti * * dantti12@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "DevicesModel.h" #include #include #include #include #include #include #include #include DevicesModel::DevicesModel(QObject *parent) : QStandardItemModel(parent), m_request(0), m_rx("[a-z]+://.*") { qDBusRegisterMetaType(); qDBusRegisterMetaType(); m_blacklistedURIs << QLatin1String("hp"); m_blacklistedURIs << QLatin1String("hpfax"); m_blacklistedURIs << QLatin1String("hal"); m_blacklistedURIs << QLatin1String("beh"); m_blacklistedURIs << QLatin1String("scsi"); m_blacklistedURIs << QLatin1String("http"); m_blacklistedURIs << QLatin1String("delete"); // Adds the other device which is meant for manual URI input insertDevice("other", QString(), i18nc("@item", "Manual URI"), QString(), "other", QString()); } void DevicesModel::update() { if (m_request) { return; } // clear the model to don't duplicate items if (rowCount()) { removeRows(1, rowCount() - 1); } m_request = new KCupsRequest; connect(m_request, &KCupsRequest::device, this, &DevicesModel::gotDevice); connect(m_request, &KCupsRequest::finished, this, &DevicesModel::finished); // Get devices with 5 seconds of timeout m_request->getDevices(10); } void DevicesModel::gotDevice(const QString &device_class, const QString &device_id, const QString &device_info, const QString &device_make_and_model, const QString &device_uri, const QString &device_location) { // "direct" qDebug() << device_class; // "MFG:Samsung;CMD:GDI;MDL:SCX-4200 Series;CLS:PRINTER;MODE:PCL;STATUS:IDLE;" qDebug() << device_id; // "Samsung SCX-4200 Series" qDebug() << device_info; // "Samsung SCX-4200 Series" qDebug() << device_make_and_model; // "usb://Samsung/SCX-4200%20Series" qDebug() << device_uri; // "" qDebug() << device_location; if (m_blacklistedURIs.contains(device_uri)) { // ignore black listed uri's return; } // For the protocols, not real devices if (device_id.isEmpty() && device_make_and_model == QLatin1String("Unknown")) { insertDevice(device_class, device_id, device_info, device_make_and_model, device_uri, device_location); } else { // Map the devices so later we try to group them MapSS mapSS; mapSS[KCUPS_DEVICE_CLASS] = device_class; mapSS[KCUPS_DEVICE_ID] = device_id; mapSS[KCUPS_DEVICE_INFO] = device_info; mapSS[KCUPS_DEVICE_MAKE_AND_MODEL] = device_make_and_model; mapSS[KCUPS_DEVICE_LOCATION] = device_location; m_mappedDevices[device_uri] = mapSS; } } void DevicesModel::finished() { bool hasError = m_request->hasError(); if (hasError) { emit errorMessage(i18n("Failed to get a list of devices: '%1'", m_request->errorMsg())); } m_request->deleteLater(); m_request = 0; if (hasError || m_mappedDevices.isEmpty()) { emit loaded(); return; } QDBusMessage message; message = QDBusMessage::createMethodCall(QLatin1String("org.fedoraproject.Config.Printing"), QLatin1String("/org/fedoraproject/Config/Printing"), QLatin1String("org.fedoraproject.Config.Printing"), QLatin1String("GroupPhysicalDevices")); message << qVariantFromValue(m_mappedDevices); QDBusConnection::sessionBus().callWithCallback(message, this, SLOT(getGroupedDevicesSuccess(QDBusMessage)), SLOT(getGroupedDevicesFailed(QDBusError,QDBusMessage))); } void DevicesModel::insertDevice(const QString &device_class, const QString &device_id, const QString &device_info, const QString &device_make_and_model, const QString &device_uri, const QString &device_location, const QStringList &grouped_uris) { QStandardItem *stdItem; stdItem = createItem(device_class, device_id, device_info, device_make_and_model, device_uri, device_location, !grouped_uris.isEmpty()); if (!grouped_uris.isEmpty()) { stdItem->setData(grouped_uris, DeviceUris); } } void DevicesModel::insertDevice(const QString &device_class, const QString &device_id, const QString &device_info, const QString &device_make_and_model, const QString &device_uri, const QString &device_location, const KCupsPrinters &grouped_printers) { QStandardItem *stdItem; stdItem = createItem(device_class, device_id, device_info, device_make_and_model, device_uri, device_location, !grouped_printers.isEmpty()); if (!grouped_printers.isEmpty()) { stdItem->setData(qVariantFromValue(grouped_printers), DeviceUris); } } QStandardItem *DevicesModel::createItem(const QString &device_class, const QString &device_id, const QString &device_info, const QString &device_make_and_model, const QString &device_uri, const QString &device_location, bool grouped) { // "direct" qDebug() << device_class; // "MFG:Samsung;CMD:GDI;MDL:SCX-4200 Series;CLS:PRINTER;MODE:PCL;STATUS:IDLE;" qDebug() << device_id; // "Samsung SCX-4200 Series" qDebug() << device_info; // "Samsung SCX-4200 Series" qDebug() << device_make_and_model; // "usb://Samsung/SCX-4200%20Series" qDebug() << device_uri; // "" qDebug() << device_location; Kind kind; // Store the kind of the device if (device_class == QLatin1String("network")) { if (m_rx.indexIn(device_uri) > -1) { kind = Networked; } else { // other network devices looks like // just "http" kind = OtherNetworked; } } else if (device_class == QLatin1String("other") && device_uri == QLatin1String("other")) { kind = Other; } else { // If device class is not network assume local kind = Local; } QString location; if (device_location.isEmpty() && kind == Local) { location = QHostInfo::localHostName(); } else { location = device_location; } QString text; if (!device_make_and_model.isEmpty() && !grouped && device_make_and_model.compare(QLatin1String("unknown"), Qt::CaseInsensitive)) { text = device_info % QLatin1String(" (") % device_make_and_model % QLatin1Char(')'); } else { text = device_info; } QString toolTip; if (!grouped) { if (device_uri.startsWith(QLatin1String("parallel"))) { toolTip = i18nc("@info:tooltip", "A printer connected to the parallel port"); } else if (device_uri.startsWith(QLatin1String("usb"))) { toolTip = i18nc("@info:tooltip", "A printer connected to a USB port"); } else if (device_uri.startsWith(QLatin1String("bluetooth"))) { toolTip = i18nc("@info:tooltip", "A printer connected via Bluetooth"); } else if (device_uri.startsWith(QLatin1String("hal"))) { toolTip = i18nc("@info:tooltip", "Local printer detected by the " "Hardware Abstraction Layer (HAL)"); } else if (device_uri.startsWith(QLatin1String("hp"))) { toolTip = i18nc("@info:tooltip", "HPLIP software driving a printer, " "or the printer function of a multi-function device"); } else if (device_uri.startsWith(QLatin1String("hpfax"))) { toolTip = i18nc("@info:tooltip", "HPLIP software driving a fax machine, " "or the fax function of a multi-function device"); } else if (device_uri.startsWith(QLatin1String("dnssd")) || device_uri.startsWith(QLatin1String("mdns"))) { toolTip = i18nc("@info:tooltip", "Remote CUPS printer via DNS-SD"); } } auto stdItem = new QStandardItem; stdItem->setText(text); stdItem->setToolTip(toolTip); stdItem->setData(device_class, DeviceClass); stdItem->setData(device_id, DeviceId); stdItem->setData(device_info, DeviceInfo); stdItem->setData(device_uri, DeviceUri); stdItem->setData(device_make_and_model, DeviceMakeAndModel); stdItem->setData(device_location, DeviceLocation); // Find the proper category to our item QStandardItem *catItem; switch (kind) { case Networked: catItem = findCreateCategory(i18nc("@item", "Discovered Network Printers")); catItem->appendRow(stdItem); break; case OtherNetworked: catItem = findCreateCategory(i18nc("@item", "Other Network Printers")); catItem->appendRow(stdItem); break; case Local: catItem = findCreateCategory(i18nc("@item", "Local Printers")); catItem->appendRow(stdItem); break; default: appendRow(stdItem); } return stdItem; } void DevicesModel::getGroupedDevicesSuccess(const QDBusMessage &message) { if (message.type() == QDBusMessage::ReplyMessage && message.arguments().size() == 1) { - QDBusArgument argument; - argument = message.arguments().first().value(); - QList groupeDevices; - groupeDevices = qdbus_cast >(argument); - foreach (const QStringList &list, groupeDevices) { + const auto argument = message.arguments().first().value(); + const auto groupeDevices = qdbus_cast >(argument); + for (const QStringList &list : groupeDevices) { if (list.isEmpty()) { continue; } QString uri = list.first(); MapSS device = m_mappedDevices[uri]; insertDevice(device[KCUPS_DEVICE_CLASS], device[KCUPS_DEVICE_ID], device[KCUPS_DEVICE_INFO], device[KCUPS_DEVICE_MAKE_AND_MODEL], uri, device[KCUPS_DEVICE_LOCATION], list.size() > 1 ? list : QStringList()); } } else { qWarning() << "Unexpected message" << message; groupedDevicesFallback(); } emit loaded(); } void DevicesModel::getGroupedDevicesFailed(const QDBusError &error, const QDBusMessage &message) { qWarning() << error << message; groupedDevicesFallback(); emit errorMessage(i18n("Failed to group devices: '%1'",error.message())); emit loaded(); } void DevicesModel::groupedDevicesFallback() { MapSMapSS::const_iterator i = m_mappedDevices.constBegin(); while (i != m_mappedDevices.constEnd()) { MapSS device = i.value(); insertDevice(device[KCUPS_DEVICE_CLASS], device[KCUPS_DEVICE_ID], device[KCUPS_DEVICE_INFO], device[KCUPS_DEVICE_MAKE_AND_MODEL], i.key(), device[KCUPS_DEVICE_LOCATION]); ++i; } } QStandardItem* DevicesModel::findCreateCategory(const QString &category) { for (int i = 0; i < rowCount(); ++i) { QStandardItem *catItem = item(i); if (catItem->text() == category) { return catItem; } } auto catItem = new QStandardItem(category); QFont font = catItem->font(); font.setBold(true); catItem->setFont(font); catItem->setFlags(Qt::ItemIsEnabled); appendRow(catItem); // Emit the parent so the view expand the item emit parentAdded(indexFromItem(catItem)); return catItem; } diff --git a/add-printer/PageChoosePPD.cpp b/add-printer/PageChoosePPD.cpp index 62e07c3..25160b9 100644 --- a/add-printer/PageChoosePPD.cpp +++ b/add-printer/PageChoosePPD.cpp @@ -1,207 +1,207 @@ /*************************************************************************** * Copyright (C) 2010-2018 by Daniel Nicoletti * * dantti12@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "PageChoosePPD.h" #include "ui_PageChoosePPD.h" #include "DevicesModel.h" #include #include #include #include #include #include #include #include PageChoosePPD::PageChoosePPD(const QVariantHash &args, QWidget *parent) : GenericPage(parent), ui(new Ui::PageChoosePPD), m_isValid(false) { ui->setupUi(this); setAttribute(Qt::WA_DeleteOnClose); // setup default options setWindowTitle(i18nc("@title:window", "Select a Printer to Add")); m_layout = new QStackedLayout; m_layout->setContentsMargins(0, 0, 0, 0); ui->gridLayout->addLayout(m_layout, 1, 3); m_selectMM = new SelectMakeModel(this); connect(m_selectMM, &SelectMakeModel::changed, this, &PageChoosePPD::checkSelected); m_layout->addWidget(m_selectMM); // Setup the busy cursor connect(m_selectMM, &SelectMakeModel::changed, this, &PageChoosePPD::notWorking); if (!args.isEmpty()) { // set our args setValues(args); } } PageChoosePPD::~PageChoosePPD() { removeTempPPD(); delete ui; } void PageChoosePPD::setValues(const QVariantHash &args) { m_args = args; if (args[ADDING_PRINTER].toBool()) { qDebug() << args; working(); removeTempPPD(); QString deviceId = args[KCUPS_DEVICE_ID].toString(); QString make; QString makeAndModel = args[KCUPS_DEVICE_MAKE_AND_MODEL].toString(); QString deviceURI = args[KCUPS_DEVICE_URI].toString(); // If QUrl url(deviceURI % QStringLiteral(".ppd")); if (url.scheme() == QStringLiteral("ipp")) { auto tempFile = new QTemporaryFile; tempFile->setFileTemplate(QStringLiteral("print-manager-XXXXXX.ppd")); tempFile->open(); url.setScheme(QStringLiteral("http")); if (url.port() < 0) { url.setPort(631); } qDebug() << deviceURI << url; KJob *job = KIO::file_copy(url, QUrl::fromLocalFile(tempFile->fileName()), -1, KIO::Overwrite | KIO::HideProgressInfo); job->setProperty("URI", deviceURI); connect(job, &KJob::result, this, &PageChoosePPD::resultJob); } // Get the make from the device id - foreach (const QString &pair, deviceId.split(QLatin1Char(';'))) { + for (const QString &pair : deviceId.split(QLatin1Char(';'))) { if (pair.startsWith(QStringLiteral("MFG:"))) { make = pair.section(QLatin1Char(':'), 1); break; } } if (makeAndModel.isEmpty()) { // Get the model from the device id - foreach (const QString &pair, deviceId.split(QLatin1Char(';'))) { + for (const QString &pair : deviceId.split(QLatin1Char(';'))) { if (pair.startsWith(QStringLiteral("MDL:"))) { // Build the make and model string if (make.isNull()) { makeAndModel = pair.section(QLatin1Char(':'), 1); } else { makeAndModel = make % QLatin1Char(' ') % pair.section(QLatin1Char(':'), 1); } break; } } } // if the device info is empty use the make and model // so we can have a nice name for the new printer on the next page if (!args.contains(KCUPS_DEVICE_INFO) && !makeAndModel.isEmpty()) { m_args[KCUPS_DEVICE_INFO] = makeAndModel; } m_selectMM->setDeviceInfo(deviceId, make, makeAndModel, deviceURI); m_isValid = true; } else { m_isValid = false; } } bool PageChoosePPD::isValid() const { return m_isValid; } QVariantHash PageChoosePPD::values() const { if (!isValid()) { return m_args; } QVariantHash ret = m_args; if (canProceed()) { if (!m_ppdFile.isNull()) { ret[FILENAME] = m_ppdFile; } else if (m_selectMM->isFileSelected()) { ret[FILENAME] = m_selectMM->selectedPPDFileName(); } else { ret[PPD_NAME] = m_selectMM->selectedPPDName(); } } return ret; } bool PageChoosePPD::canProceed() const { // It can proceed if a PPD file (local or not) is provided bool changed = false; bool allow = false; if (m_selectMM->isFileSelected()) { allow = !m_selectMM->selectedPPDFileName().isNull(); } else if (!m_ppdFile.isNull()) { allow = true; } else { allow = !m_selectMM->selectedPPDName().isNull(); } qDebug() << allow; return allow; } void PageChoosePPD::checkSelected() { emit allowProceed(canProceed()); } void PageChoosePPD::selectDefault() { } void PageChoosePPD::resultJob(KJob *job) { if (!job->error() && job->property("URI").toString() == m_args[KCUPS_DEVICE_URI].toString()) { auto fileCopyJob = qobject_cast(job); // Make sure this job is for the current device m_ppdFile = fileCopyJob->destUrl().toLocalFile(); m_isValid = false; emit proceed(); } } void PageChoosePPD::removeTempPPD() { if (!m_ppdFile.isEmpty()) { QFile::remove(m_ppdFile); m_ppdFile.clear(); } } diff --git a/add-printer/PageDestinations.cpp b/add-printer/PageDestinations.cpp index 7dc5754..168acef 100644 --- a/add-printer/PageDestinations.cpp +++ b/add-printer/PageDestinations.cpp @@ -1,400 +1,401 @@ /*************************************************************************** * Copyright (C) 2010-2018 by Daniel Nicoletti * * dantti12@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "PageDestinations.h" #include "ui_PageDestinations.h" #include "DevicesModel.h" #include "ChooseLpd.h" #include "ChooseSamba.h" #include "ChooseSerial.h" #include "ChooseSocket.h" #include "ChooseUri.h" #include #include #include #include #include // system-config-printer --setup-printer='file:/tmp/printout' --devid='MFG:Ricoh;MDL:Aficio SP C820DN' PageDestinations::PageDestinations(const QVariantHash &args, QWidget *parent) : GenericPage(parent), ui(new Ui::PageDestinations), m_chooseLpd(new ChooseLpd(this)), m_chooseSamba(new ChooseSamba(this)), m_chooseSerial(new ChooseSerial(this)), m_chooseSocket(new ChooseSocket(this)), m_chooseUri(new ChooseUri(this)), m_chooseLabel(new QLabel(this)) { ui->setupUi(this); setAttribute(Qt::WA_DeleteOnClose); ui->stackedWidget->addWidget(m_chooseLpd); connect(m_chooseLpd, &ChooseLpd::allowProceed, this, &PageDestinations::allowProceed); connect(m_chooseLpd, &ChooseLpd::startWorking, this, &PageDestinations::working); connect(m_chooseLpd, &ChooseLpd::stopWorking, this, &PageDestinations::notWorking); ui->stackedWidget->addWidget(m_chooseSamba); connect(m_chooseSamba, &ChooseSamba::allowProceed, this, &PageDestinations::allowProceed); connect(m_chooseSamba, &ChooseSamba::startWorking, this, &PageDestinations::working); connect(m_chooseSamba, &ChooseSamba::stopWorking, this, &PageDestinations::notWorking); ui->stackedWidget->addWidget(m_chooseSerial); connect(m_chooseSerial, &ChooseSerial::allowProceed, this, &PageDestinations::allowProceed); connect(m_chooseSerial, &ChooseSerial::startWorking, this, &PageDestinations::working); connect(m_chooseSerial, &ChooseSerial::stopWorking, this, &PageDestinations::notWorking); ui->stackedWidget->addWidget(m_chooseSocket); connect(m_chooseSocket, &ChooseSocket::allowProceed, this, &PageDestinations::allowProceed); connect(m_chooseSocket, &ChooseSocket::startWorking, this, &PageDestinations::working); connect(m_chooseSocket, &ChooseSocket::stopWorking, this, &PageDestinations::notWorking); ui->stackedWidget->addWidget(m_chooseUri); connect(m_chooseUri, &ChooseUri::allowProceed, this, &PageDestinations::allowProceed); connect(m_chooseUri, &ChooseUri::startWorking, this, &PageDestinations::working); connect(m_chooseUri, &ChooseUri::stopWorking, this, &PageDestinations::notWorking); connect(m_chooseUri, &ChooseUri::errorMessage, ui->messageWidget, &KMessageWidget::setText); connect(m_chooseUri, &ChooseUri::errorMessage, ui->messageWidget, &KMessageWidget::animatedShow); connect(m_chooseUri, &ChooseUri::insertDevice, this, &PageDestinations::insertDevice); m_chooseLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); ui->stackedWidget->addWidget(m_chooseLabel); // Hide the message widget ui->messageWidget->setMessageType(KMessageWidget::Error); ui->messageWidget->hide(); // setup default options setWindowTitle(i18nc("@title:window", "Select a Printer to Add")); m_model = new DevicesModel(this); ui->devicesTV->setModel(m_model); ui->devicesTV->setItemDelegate(new NoSelectionRectDelegate(this)); connect(ui->devicesTV->selectionModel(), &QItemSelectionModel::selectionChanged, this, &PageDestinations::deviceChanged); connect(m_model, &DevicesModel::errorMessage, ui->messageWidget, &KMessageWidget::setText); connect(m_model, &DevicesModel::errorMessage, ui->messageWidget, &KMessageWidget::animatedShow); // Expand when a parent is added connect(m_model, &DevicesModel::parentAdded, ui->devicesTV, &QTreeView::expand); // Update the view when the device URI combo box changed connect(ui->connectionsCB, static_cast(&QComboBox::currentIndexChanged), this, &PageDestinations::deviceUriChanged); ui->connectionsGB->setVisible(false); // Setup the busy cursor working(); connect(m_model, &DevicesModel::loaded, this, &PageDestinations::notWorking); if (!args.isEmpty()) { // set our args setValues(args); } } PageDestinations::~PageDestinations() { delete ui; } void PageDestinations::setValues(const QVariantHash &args) { m_args = args; if (args[ADDING_PRINTER].toBool()) { // m_isValid = true; m_model->update(); // m_busySeq->start(); } else { // m_isValid = false; } } bool PageDestinations::isValid() const { return true; } QVariantHash PageDestinations::values() const { QVariantHash ret = m_args; auto page = qobject_cast(ui->stackedWidget->currentWidget()); if (page) { ret = page->values(); } else if (canProceed()) { ret = selectedItemValues(); } return ret; } bool PageDestinations::canProceed() const { bool ret = ui->stackedWidget->currentIndex() != 0; auto page = qobject_cast(ui->stackedWidget->currentWidget()); if (page) { ret = page->canProceed(); } return ret; } void PageDestinations::deviceChanged() { QItemSelectionModel *selection = ui->devicesTV->selectionModel(); if (!selection->selectedIndexes().isEmpty() && selection->selectedIndexes().size() == 1) { QModelIndex index = selection->selectedIndexes().first(); QVariant uris = index.data(DevicesModel::DeviceUris); if (uris.isNull()) { ui->connectionsGB->setVisible(false); } else if (uris.type() == QVariant::StringList) { ui->connectionsCB->clear(); - foreach (const QString &uri, uris.toStringList()) { + for (const QString &uri : uris.toStringList()) { ui->connectionsCB->addItem(uriText(uri), uri); } ui->connectionsGB->setVisible(true); } else { ui->connectionsCB->clear(); - foreach (const KCupsPrinter &printer, uris.value()) { + const auto printers = uris.value(); + for (const KCupsPrinter &printer : printers) { ui->connectionsCB->addItem(printer.name(), qVariantFromValue(printer)); } ui->connectionsGB->setVisible(true); } } else { ui->connectionsGB->setVisible(false); setCurrentPage(0, selectedItemValues()); return; } deviceUriChanged(); } void PageDestinations::deviceUriChanged() { // Get the selected values QVariantHash args = selectedItemValues(); // "beh" is excluded from the list QString deviceUri = args[KCUPS_DEVICE_URI].toString(); qDebug() << deviceUri; if (deviceUri.startsWith(QLatin1String("parallel"))) { m_chooseLabel->setText(i18n("A printer connected to the parallel port.")); setCurrentPage(m_chooseLabel, args); } else if (deviceUri.startsWith(QLatin1String("usb"))) { m_chooseLabel->setText(i18n("A printer connected to a USB port.")); setCurrentPage(m_chooseLabel, args); } else if (deviceUri.startsWith(QLatin1String("bluetooth"))) { m_chooseLabel->setText(i18n("A printer connected via Bluetooth.")); setCurrentPage(m_chooseLabel, args); } else if (deviceUri.startsWith(QLatin1String("hal"))) { m_chooseLabel->setText(i18n("Local printer detected by the " "Hardware Abstraction Layer (HAL).")); setCurrentPage(m_chooseLabel, args); } else if (deviceUri.startsWith(QLatin1String("hp"))) { m_chooseLabel->setText(i18n("HPLIP software driving a printer, " "or the printer function of a multi-function device.")); setCurrentPage(m_chooseLabel, args); } else if (deviceUri.startsWith(QLatin1String("hpfax"))) { m_chooseLabel->setText(i18n("HPLIP software driving a fax machine, " "or the fax function of a multi-function device.")); setCurrentPage(m_chooseLabel, args); } else if (deviceUri.startsWith(QLatin1String("dnssd")) || deviceUri.startsWith(QLatin1String("mdns"))) { // TODO this needs testing... QString text; if (deviceUri.contains(QLatin1String("cups"))) { text = i18n("Remote CUPS printer via DNS-SD"); } else { QString protocol; if (deviceUri.contains(QLatin1String("._ipp"))) { protocol = QLatin1String("IPP"); } else if (deviceUri.contains(QLatin1String("._printer"))) { protocol = QLatin1String("LPD"); } else if (deviceUri.contains(QLatin1String("._pdl-datastream"))) { protocol = QLatin1String("AppSocket/JetDirect"); } if (protocol.isNull()) { text = i18n("Network printer via DNS-SD"); } else { text = i18n("%1 network printer via DNS-SD", protocol); } } m_chooseLabel->setText(text); setCurrentPage(m_chooseLabel, args); } else if (deviceUri.startsWith(QLatin1String("socket"))) { qDebug() << "SOCKET"; setCurrentPage(m_chooseSocket, args); } else if (deviceUri.startsWith(QLatin1String("ipp")) || deviceUri.startsWith(QLatin1String("ipps")) || deviceUri.startsWith(QLatin1String("http")) || deviceUri.startsWith(QLatin1String("https"))) { setCurrentPage(m_chooseUri, args); } else if (deviceUri.startsWith(QLatin1String("lpd"))) { setCurrentPage(m_chooseLpd, args); } else if (deviceUri.startsWith(QLatin1String("scsi"))) { // TODO setCurrentPage(m_chooseUri, args); } else if (deviceUri.startsWith(QLatin1String("serial"))) { setCurrentPage(m_chooseSerial, args); } else if (deviceUri.startsWith(QLatin1String("smb"))) { setCurrentPage(m_chooseSamba, args); } else if (deviceUri.startsWith(QLatin1String("network"))) { setCurrentPage(m_chooseUri, args); } else { setCurrentPage(m_chooseUri, args); } emit allowProceed(canProceed()); } void PageDestinations::insertDevice(const QString &device_class, const QString &device_id, const QString &device_info, const QString &device_make_and_model, const QString &device_uri, const QString &device_location, const KCupsPrinters &grouped_printers) { m_model->insertDevice(device_class, device_id, device_info, device_make_and_model, device_uri, device_location, grouped_printers); } QVariantHash PageDestinations::selectedItemValues() const { QVariantHash ret = m_args; if (!ui->devicesTV->selectionModel()->selectedIndexes().isEmpty() && ui->devicesTV->selectionModel()->selectedIndexes().size() == 1) { QModelIndex index = ui->devicesTV->selectionModel()->selectedIndexes().first(); QVariant uri = index.data(DevicesModel::DeviceUri); QVariant uris = index.data(DevicesModel::DeviceUris); // if the devicesTV holds an item with grouped URIs // get the selected value from the connections combo box if (uris.isNull() || uris.type() == QVariant::StringList) { if (uris.type() == QVariant::StringList) { uri = ui->connectionsCB->itemData(ui->connectionsCB->currentIndex()); } ret[KCUPS_DEVICE_URI] = uri; ret[KCUPS_DEVICE_ID] = index.data(DevicesModel::DeviceId); ret[KCUPS_DEVICE_MAKE_AND_MODEL] = index.data(DevicesModel::DeviceMakeAndModel); ret[KCUPS_DEVICE_INFO] = index.data(DevicesModel::DeviceInfo); ret[KCUPS_DEVICE_LOCATION] = index.data(DevicesModel::DeviceLocation); } else { QVariant aux = ui->connectionsCB->itemData(ui->connectionsCB->currentIndex()); KCupsPrinter printer = aux.value(); QUrl url(uri.toString()); url.setPath(QLatin1String("printers/") % printer.name()); ret[KCUPS_DEVICE_URI] = url.url(); ret[KCUPS_DEVICE_ID] = index.data(DevicesModel::DeviceId); ret[KCUPS_PRINTER_INFO] = printer.info(); qDebug() << KCUPS_PRINTER_INFO << printer.info(); ret[KCUPS_PRINTER_NAME] = printer.name(); ret[KCUPS_DEVICE_LOCATION] = printer.location(); } qDebug() << uri << ret; } return ret; } void PageDestinations::setCurrentPage(QWidget *widget, const QVariantHash &args) { auto page = qobject_cast(widget); if (page) { page->setValues(args); if (ui->stackedWidget->currentWidget() != page) {; ui->stackedWidget->setCurrentWidget(page); } } else if (qobject_cast(widget)) { if (ui->connectionsGB->isVisible() && ui->connectionsCB->currentText() == m_chooseLabel->text()) { // Don't show duplicated text for the user m_chooseLabel->clear(); } if (ui->stackedWidget->currentWidget() != widget) {; ui->stackedWidget->setCurrentWidget(widget); } } else { ui->stackedWidget->setCurrentIndex(0); } } QString PageDestinations::uriText(const QString &uri) const { QString ret; if (uri.startsWith(QLatin1String("parallel"))) { ret = i18n("Parallel Port"); } else if (uri.startsWith(QLatin1String("serial"))) { ret = i18n("Serial Port"); } else if (uri.startsWith(QLatin1String("usb"))) { ret = i18n("USB"); } else if (uri.startsWith(QLatin1String("bluetooth")) ){ ret = i18n("Bluetooth"); } else if (uri.startsWith(QLatin1String("hpfax"))) { ret = i18n("Fax - HP Linux Imaging and Printing (HPLIP)"); } else if (uri.startsWith(QLatin1String("hp"))) { ret = i18n("HP Linux Imaging and Printing (HPLIP)"); } else if (uri.startsWith(QLatin1String("hal"))) { ret = i18n("Hardware Abstraction Layer (HAL)"); } else if (uri.startsWith(QLatin1String("socket"))) { ret = i18n("AppSocket/HP JetDirect"); } else if (uri.startsWith(QLatin1String("lpd"))) { // Check if the queue name is defined QString queue = uri.section(QLatin1Char('/'), -1, -1); if (queue.isEmpty()) { ret = i18n("LPD/LPR queue"); } else { ret = i18n("LPD/LPR queue %1", queue); } } else if (uri.startsWith(QLatin1String("smb"))) { ret = i18n("Windows Printer via SAMBA"); } else if (uri.startsWith(QLatin1String("ipp"))) { // Check if the queue name (fileName) is defined QString queue = uri.section(QLatin1Char('/'), -1, -1); if (queue.isEmpty()) { ret = i18n("IPP"); } else { ret = i18n("IPP %1", queue); } } else if (uri.startsWith(QLatin1String("https"))) { ret = i18n("HTTP"); } else if (uri.startsWith(QLatin1String("dnssd")) || uri.startsWith(QLatin1String("mdns"))) { // TODO this needs testing... QString text; if (uri.contains(QLatin1String("cups"))) { text = i18n("Remote CUPS printer via DNS-SD"); } else { if (uri.contains(QLatin1String("._ipp"))) { ret = i18n("IPP network printer via DNS-SD"); } else if (uri.contains(QLatin1String("._printer"))) { ret = i18n("LPD network printer via DNS-SD"); } else if (uri.contains(QLatin1String("._pdl-datastream"))) { ret = i18n("AppSocket/JetDirect network printer via DNS-SD"); } else { ret = i18n("Network printer via DNS-SD"); } } } else { ret = uri; } return ret; } diff --git a/configure-printer/PrinterBehavior.cpp b/configure-printer/PrinterBehavior.cpp index 0db9e78..6f1ab27 100644 --- a/configure-printer/PrinterBehavior.cpp +++ b/configure-printer/PrinterBehavior.cpp @@ -1,324 +1,327 @@ /*************************************************************************** * Copyright (C) 2010-2018 by Daniel Nicoletti * * dantti12@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "PrinterBehavior.h" #include "ui_PrinterBehavior.h" #include "Debug.h" #include PrinterBehavior::PrinterBehavior(const QString &destName, bool isClass, QWidget *parent) : PrinterPage(parent), ui(new Ui::PrinterBehavior), m_destName(destName), m_isClass(isClass), m_changes(0) { ui->setupUi(this); connect(ui->errorPolicyCB, static_cast(&QComboBox::currentIndexChanged), this, &PrinterBehavior::currentIndexChangedCB); connect(ui->operationPolicyCB, static_cast(&QComboBox::currentIndexChanged), this, &PrinterBehavior::currentIndexChangedCB); connect(ui->startingBannerCB, static_cast(&QComboBox::currentIndexChanged), this, &PrinterBehavior::currentIndexChangedCB); connect(ui->endingBannerCB, static_cast(&QComboBox::currentIndexChanged), this, &PrinterBehavior::currentIndexChangedCB); connect(ui->usersELB, &KEditListWidget::changed, this, &PrinterBehavior::userListChanged); connect(ui->allowRB, &QRadioButton::toggled, this, &PrinterBehavior::userListChanged); } PrinterBehavior::~PrinterBehavior() { delete ui; } void PrinterBehavior::setValues(const KCupsPrinter &printer) { int defaultChoice; ui->errorPolicyCB->clear(); - foreach (const QString &value, printer.errorPolicySupported()) { + const QStringList errorPolicySupported = printer.errorPolicySupported(); + for (const QString &value : errorPolicySupported) { ui->errorPolicyCB->addItem(errorPolicyString(value), value); } QStringList errorPolicy = printer.errorPolicy(); if (!errorPolicy.isEmpty()) { defaultChoice = ui->errorPolicyCB->findData(errorPolicy.first()); ui->errorPolicyCB->setCurrentIndex(defaultChoice); ui->errorPolicyCB->setProperty("defaultChoice", defaultChoice); } ui->operationPolicyCB->clear(); - foreach (const QString &value, printer.opPolicySupported()) { + const QStringList opPolicySupported = printer.opPolicySupported(); + for (const QString &value : opPolicySupported) { ui->operationPolicyCB->addItem(operationPolicyString(value), value); } QStringList operationPolicy = printer.opPolicy(); if (!errorPolicy.isEmpty()) { defaultChoice = ui->operationPolicyCB->findData(operationPolicy.first()); ui->operationPolicyCB->setCurrentIndex(defaultChoice); ui->operationPolicyCB->setProperty("defaultChoice", defaultChoice); } ui->startingBannerCB->clear(); ui->endingBannerCB->clear(); - foreach (const QString &value, printer.jobSheetsSupported()) { + const QStringList jobSheetsSupported = printer.jobSheetsSupported(); + for (const QString &value : jobSheetsSupported) { ui->startingBannerCB->addItem(jobSheetsString(value), value); ui->endingBannerCB->addItem(jobSheetsString(value), value); } QStringList bannerPolicy = printer.jobSheetsDefault(); if (bannerPolicy.size() == 2) { defaultChoice = ui->startingBannerCB->findData(bannerPolicy.at(0)); ui->startingBannerCB->setCurrentIndex(defaultChoice); ui->startingBannerCB->setProperty("defaultChoice", defaultChoice); defaultChoice = ui->endingBannerCB->findData(bannerPolicy.at(1)); ui->endingBannerCB->setCurrentIndex(defaultChoice); ui->endingBannerCB->setProperty("defaultChoice", defaultChoice); } if (!printer.requestingUserNameAllowed().isEmpty()) { QStringList list = printer.requestingUserNameAllowed(); list.sort(); // sort the list here to be able to comapare it later ui->usersELB->setEnabled(true); if (list != ui->usersELB->items()) { ui->usersELB->clear(); ui->usersELB->insertStringList(list); } ui->usersELB->setProperty("defaultList", list); ui->allowRB->setProperty("defaultChoice", true); // Set checked AFTER the default choice was set // otherwise the signal will be emmited // which sets that we have a change ui->allowRB->setChecked(true); } else if (!printer.requestingUserNameDenied().isEmpty()) { QStringList list = printer.requestingUserNameDenied(); list.sort(); // sort the list here to be able to comapare it later ui->usersELB->setEnabled(true); if (list != ui->usersELB->items()) { ui->usersELB->clear(); ui->usersELB->insertStringList(list); } ui->usersELB->setProperty("defaultList", list); ui->allowRB->setProperty("defaultChoice", false); // Set checked AFTER the default choice was set // otherwise the signal will be emmited // which sets that we have a change ui->preventRB->setChecked(true); } // Clear previous changes m_changes = 0; emit changed(false); m_changedValues.clear(); ui->errorPolicyCB->setProperty("different", false); ui->operationPolicyCB->setProperty("different", false); ui->startingBannerCB->setProperty("different", false); ui->endingBannerCB->setProperty("different", false); ui->usersELB->setProperty("different", false); } void PrinterBehavior::userListChanged() { if (ui->usersELB->isEnabled() == false && (ui->allowRB->isChecked() || ui->preventRB->isChecked())) { // this only happen when the list was empty ui-> usersELB->setEnabled(true); } QStringList currentList, defaultList; currentList = ui->usersELB->items(); // sort the list so we can be sure it's different currentList.sort(); defaultList = ui->usersELB->property("defaultList").value(); bool isDifferent = currentList != defaultList; if (isDifferent == false && currentList.isEmpty() == false) { // if the lists are equal and not empty the user might have // changed the Radio Button... if (ui->allowRB->isChecked() != ui->allowRB->property("defaultChoice").toBool()) { isDifferent = true; } } if (isDifferent != ui->usersELB->property("different").toBool()) { // it's different from the last time so add or remove changes isDifferent ? m_changes++ : m_changes--; ui->usersELB->setProperty("different", isDifferent); emit changed(m_changes); } } void PrinterBehavior::currentIndexChangedCB(int index) { auto comboBox = qobject_cast(sender()); bool isDifferent = comboBox->property("defaultChoice").toInt() != index; if (isDifferent != comboBox->property("different").toBool()) { // it's different from the last time so add or remove changes isDifferent ? m_changes++ : m_changes--; comboBox->setProperty("different", isDifferent); emit changed(m_changes); } QString attribute = comboBox->property("AttributeName").toString(); QVariant value; // job-sheets-default has always two values if (attribute == "job-sheets-default") { QStringList values; values << ui->startingBannerCB->itemData(ui->startingBannerCB->currentIndex()).toString(); values << ui->endingBannerCB->itemData(ui->endingBannerCB->currentIndex()).toString(); value = values; } else { value = comboBox->itemData(index).toString(); } // store the new values if (isDifferent) { m_changedValues[attribute] = value; } else { m_changedValues.remove(attribute); } } QString PrinterBehavior::errorPolicyString(const QString &policy) const { // TODO search for others policies of printer-error-policy-supported if (policy == "abort-job") { return i18n("Abort job"); } else if (policy == "retry-current-job") { return i18n("Retry current job"); } else if (policy == "retry-job") { return i18n("Retry job"); } else if (policy == "stop-printer") { return i18n("Stop printer"); } return policy; } QString PrinterBehavior::operationPolicyString(const QString &policy) const { // TODO search for others policies of printer-error-policy-supported if (policy == "authenticated") { return i18n("Authenticated"); } else if (policy == "default") { return i18n("Default"); } return policy; } QString PrinterBehavior::jobSheetsString(const QString &policy) const { // TODO search for others policies of printer-error-policy-supported if (policy == "none") { return i18n("None"); } else if (policy == "classified") { return i18n("Classified"); } else if (policy == "confidential") { return i18n("Confidential"); } else if (policy == "secret") { return i18n("Secret"); } else if (policy == "standard") { return i18n("Standard"); } else if (policy == "topsecret") { return i18n("Topsecret"); } else if (policy == "unclassified") { return i18n("Unclassified"); } return policy; } void PrinterBehavior::save() { if (m_changes) { QVariantHash changedValues = m_changedValues; // since a QStringList might be big we get it here instead // of adding it at edit time. if (ui->usersELB->property("different").toBool()) { QStringList list = ui->usersELB->items(); if (list.isEmpty()) { list << "all"; changedValues[KCUPS_REQUESTING_USER_NAME_ALLOWED] = list; } else { if (ui->allowRB->isChecked()) { changedValues[KCUPS_REQUESTING_USER_NAME_ALLOWED] = list; } else { changedValues[KCUPS_REQUESTING_USER_NAME_DENIED] = list; } } } QPointer request = new KCupsRequest; if (m_isClass) { request->addOrModifyClass(m_destName, changedValues); } else { request->addOrModifyPrinter(m_destName, changedValues); } request->waitTillFinished(); if (request) { if (!request->hasError()) { request->getPrinterAttributes(m_destName, m_isClass, neededValues()); request->waitTillFinished(); if (request && !request->hasError() && !request->printers().isEmpty()){ KCupsPrinter printer = request->printers().first(); setValues(printer); } } request->deleteLater(); } } } void PrinterBehavior::setRemote(bool remote) { ui->errorPolicyCB->setEnabled(!remote); ui->operationPolicyCB->setEnabled(!remote); ui->startingBannerCB->setEnabled(!remote); ui->endingBannerCB->setEnabled(!remote); ui->allowRB->setEnabled(!remote); ui->preventRB->setEnabled(!remote); ui->usersELB->setEnabled(!remote); } bool PrinterBehavior::hasChanges() { return m_changes; } QStringList PrinterBehavior::neededValues() const { QStringList ret; ret << KCUPS_JOB_SHEETS_DEFAULT; ret << KCUPS_JOB_SHEETS_SUPPORTED; ret << KCUPS_PRINTER_ERROR_POLICY; ret << KCUPS_PRINTER_ERROR_POLICY_SUPPORTED; ret << KCUPS_PRINTER_OP_POLICY; ret << KCUPS_PRINTER_OP_POLICY_SUPPORTED; ret << KCUPS_REQUESTING_USER_NAME_ALLOWED; ret << KCUPS_REQUESTING_USER_NAME_DENIED; return ret; } diff --git a/libkcups/ClassListWidget.cpp b/libkcups/ClassListWidget.cpp index 947b436..6a4e846 100644 --- a/libkcups/ClassListWidget.cpp +++ b/libkcups/ClassListWidget.cpp @@ -1,185 +1,185 @@ /*************************************************************************** * Copyright (C) 2010-2018 by Daniel Nicoletti * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "ClassListWidget.h" #include "SelectMakeModel.h" #include "KCupsRequest.h" #include "NoSelectionRectDelegate.h" #include #include #include #include #include ClassListWidget::ClassListWidget(QWidget *parent) : QListView(parent), m_request(0), m_showClasses(false) { KConfigDialogManager::changedMap()->insert("ClassListWidget", SIGNAL(changed(QString))); m_model = new QStandardItemModel(this); setModel(m_model); setItemDelegate(new NoSelectionRectDelegate(this)); // Setup the busy cursor m_busySeq = new KPixmapSequenceOverlayPainter(this); m_busySeq->setSequence(KPixmapSequence("process-working", KIconLoader::SizeSmallMedium)); m_busySeq->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); m_busySeq->setWidget(viewport()); connect(m_model, &QStandardItemModel::dataChanged, this, &ClassListWidget::modelChanged); m_delayedInit.setInterval(0); m_delayedInit.setSingleShot(true); connect(&m_delayedInit, &QTimer::timeout, this, &ClassListWidget::init); m_delayedInit.start(); } ClassListWidget::~ClassListWidget() { } void ClassListWidget::init() { m_busySeq->start(); // Start spining m_model->clear(); QStringList att; att << KCUPS_PRINTER_NAME; att << KCUPS_PRINTER_URI_SUPPORTED; // Get destinations with these masks m_request = new KCupsRequest; connect(m_request, &KCupsRequest::finished, this, &ClassListWidget::loadFinished); if (m_showClasses) { m_request->getPrinters(att); } else { m_request->getPrinters(att, CUPS_PRINTER_CLASS | CUPS_PRINTER_REMOTE | CUPS_PRINTER_IMPLICIT); } } void ClassListWidget::loadFinished(KCupsRequest *request) { // If we have an old request running discard it's result and get a new one if (m_request != request) { request->deleteLater(); return; } m_busySeq->stop(); // Stop spining - KCupsPrinters printers = m_request->printers(); - m_request->deleteLater(); + const KCupsPrinters printers = request->printers(); + request->deleteLater(); m_request = 0; - foreach (const KCupsPrinter &printer, printers) { + for (const KCupsPrinter &printer : printers) { QString destName = printer.name(); if (destName != m_printerName) { auto item = new QStandardItem; item->setText(destName); item->setCheckable(true); item->setEditable(false); item->setData(printer.uriSupported()); updateItemState(item); m_model->appendRow(item); } } modelChanged(); } void ClassListWidget::modelChanged() { QStringList currentMembers = currentSelected(false); m_changed = m_selectedPrinters != currentMembers; emit changed(selectedPrinters()); emit changed(m_changed); } QStringList ClassListWidget::currentSelected(bool uri) const { QStringList currentMembers; for (int i = 0; i < m_model->rowCount(); i++) { QStandardItem *item = m_model->item(i); if (item && item->checkState() == Qt::Checked) { if (uri) { currentMembers << item->data().toString(); } else { currentMembers << item->text(); } } } currentMembers.sort(); return currentMembers; } void ClassListWidget::updateItemState(QStandardItem *item) const { if (m_selectedPrinters.contains(item->text())) { item->setCheckState(Qt::Checked); } else { item->setCheckState(Qt::Unchecked); } } bool ClassListWidget::hasChanges() { return m_changed; } void ClassListWidget::setPrinter(const QString &printer) { if (m_printerName != printer) { m_printerName = printer; m_delayedInit.start(); } } QString ClassListWidget::selectedPrinters() const { return currentSelected(false).join(QLatin1String("|")); } void ClassListWidget::setSelectedPrinters(const QString &selected) { m_selectedPrinters = selected.split(QLatin1Char('|')); m_selectedPrinters.sort(); m_delayedInit.start(); } bool ClassListWidget::showClasses() const { return m_showClasses; } void ClassListWidget::setShowClasses(bool enable) { if (m_showClasses != enable) { m_showClasses = enable; m_delayedInit.start(); } } diff --git a/libkcups/JobModel.cpp b/libkcups/JobModel.cpp index db005e5..6ea7b1e 100644 --- a/libkcups/JobModel.cpp +++ b/libkcups/JobModel.cpp @@ -1,628 +1,628 @@ /*************************************************************************** * Copyright (C) 2010-2018 by Daniel Nicoletti * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "JobModel.h" #include #include #include #include #include #include #include #include #include #include #include #include JobModel::JobModel(QObject *parent) : QStandardItemModel(parent), m_jobRequest(0), m_whichjobs(CUPS_WHICHJOBS_ACTIVE), m_parentId(0) { setHorizontalHeaderItem(ColStatus, new QStandardItem(i18n("Status"))); setHorizontalHeaderItem(ColName, new QStandardItem(i18n("Name"))); setHorizontalHeaderItem(ColUser, new QStandardItem(i18n("User"))); setHorizontalHeaderItem(ColCreated, new QStandardItem(i18n("Created"))); setHorizontalHeaderItem(ColCompleted, new QStandardItem(i18n("Completed"))); setHorizontalHeaderItem(ColPages, new QStandardItem(i18n("Pages"))); setHorizontalHeaderItem(ColProcessed, new QStandardItem(i18n("Processed"))); setHorizontalHeaderItem(ColSize, new QStandardItem(i18n("Size"))); setHorizontalHeaderItem(ColStatusMessage, new QStandardItem(i18n("Status Message"))); setHorizontalHeaderItem(ColPrinter, new QStandardItem(i18n("Printer"))); setHorizontalHeaderItem(ColFromHost, new QStandardItem(i18n("From Hostname"))); // Setup the attributes we want from jobs m_jobAttributes << KCUPS_JOB_ID; m_jobAttributes << KCUPS_JOB_NAME; m_jobAttributes << KCUPS_JOB_K_OCTETS; m_jobAttributes << KCUPS_JOB_K_OCTETS_PROCESSED; m_jobAttributes << KCUPS_JOB_STATE; m_jobAttributes << KCUPS_TIME_AT_COMPLETED; m_jobAttributes << KCUPS_TIME_AT_CREATION; m_jobAttributes << KCUPS_TIME_AT_PROCESSING; m_jobAttributes << KCUPS_JOB_PRINTER_URI; m_jobAttributes << KCUPS_JOB_ORIGINATING_USER_NAME; m_jobAttributes << KCUPS_JOB_ORIGINATING_HOST_NAME; m_jobAttributes << KCUPS_JOB_MEDIA_PROGRESS; m_jobAttributes << KCUPS_JOB_MEDIA_SHEETS; m_jobAttributes << KCUPS_JOB_MEDIA_SHEETS_COMPLETED; m_jobAttributes << KCUPS_JOB_PRINTER_STATE_MESSAGE; m_jobAttributes << KCUPS_JOB_PRESERVED; QHash roles = roleNames(); roles[RoleJobId] = "jobId"; roles[RoleJobState] = "jobState"; roles[RoleJobName] = "jobName"; roles[RoleJobPages] = "jobPages"; roles[RoleJobSize] = "jobSize"; roles[RoleJobOwner] = "jobOwner"; roles[RoleJobCreatedAt] = "jobCreatedAt"; roles[RoleJobIconName] = "jobIconName"; roles[RoleJobCancelEnabled] = "jobCancelEnabled"; roles[RoleJobHoldEnabled] = "jobHoldEnabled"; roles[RoleJobReleaseEnabled] = "jobReleaseEnabled"; roles[RoleJobRestartEnabled] = "jobRestartEnabled"; roles[RoleJobPrinter] = "jobPrinter"; roles[RoleJobOriginatingHostName] = "jobFrom"; setRoleNames(roles); // This is emitted when a job change it's state connect(KCupsConnection::global(), &KCupsConnection::jobState, this, &JobModel::insertUpdateJob); // This is emitted when a job is created connect(KCupsConnection::global(), &KCupsConnection::jobCreated, this, &JobModel::insertUpdateJob); // This is emitted when a job is stopped connect(KCupsConnection::global(), &KCupsConnection::jobStopped, this, &JobModel::insertUpdateJob); // This is emitted when a job has it's config changed connect(KCupsConnection::global(), &KCupsConnection::jobConfigChanged, this, &JobModel::insertUpdateJob); // This is emitted when a job change it's progress connect(KCupsConnection::global(), &KCupsConnection::jobProgress, this, &JobModel::insertUpdateJob); // This is emitted when a printer is removed connect(KCupsConnection::global(), &KCupsConnection::jobCompleted, this, &JobModel::jobCompleted); connect(KCupsConnection::global(), &KCupsConnection::serverAudit, this, &JobModel::getJobs); connect(KCupsConnection::global(), &KCupsConnection::serverStarted, this, &JobModel::getJobs); connect(KCupsConnection::global(), &KCupsConnection::serverStopped, this, &JobModel::getJobs); connect(KCupsConnection::global(), &KCupsConnection::serverRestarted, this, &JobModel::getJobs); } void JobModel::setParentWId(WId parentId) { m_parentId = parentId; } void JobModel::init(const QString &destName) { m_destName = destName; // Get all jobs getJobs(); } void JobModel::hold(const QString &printerName, int jobId) { QPointer request = new KCupsRequest; request->holdJob(printerName, jobId); request->waitTillFinished(); if (request) { request->deleteLater(); } } void JobModel::release(const QString &printerName, int jobId) { QPointer request = new KCupsRequest; request->releaseJob(printerName, jobId); request->waitTillFinished(); if (request) { request->deleteLater(); } } void JobModel::cancel(const QString &printerName, int jobId) { QPointer request = new KCupsRequest; request->cancelJob(printerName, jobId); request->waitTillFinished(); if (request) { request->deleteLater(); } } void JobModel::move(const QString &printerName, int jobId, const QString &toPrinterName) { QPointer request = new KCupsRequest; request->moveJob(printerName, jobId, toPrinterName); request->waitTillFinished(); if (request) { request->deleteLater(); } } void JobModel::getJobs() { if (m_jobRequest) { return; } m_jobRequest = new KCupsRequest; connect(m_jobRequest, &KCupsRequest::finished, this, &JobModel::getJobFinished); m_jobRequest->getJobs(m_destName, false, m_whichjobs, m_jobAttributes); m_processingJob.clear(); } void JobModel::getJobFinished(KCupsRequest *request) { if (request) { if (request->hasError()) { // clear the model after so that the proper widget can be shown clear(); } else { KCupsJobs jobs = request->jobs(); qCDebug(LIBKCUPS) << jobs.size(); for (int i = 0; i < jobs.size(); ++i) { if (jobs.at(i).state() == IPP_JOB_PROCESSING) { m_processingJob = jobs.at(i).name(); } // try to find the job row int job_row = jobRow(jobs.at(i).id()); if (job_row == -1) { // not found, insert new one insertJob(i, jobs.at(i)); } else if (job_row == i) { // update the job updateJob(i, jobs.at(i)); } else { // found at wrong position // take it and insert on the right position QList row = takeRow(job_row); insertRow(i, row); updateJob(i, jobs.at(i)); } } // remove old printers // The above code starts from 0 and make sure // dest == modelIndex(x) and if it's not the // case it either inserts or moves it. // so any item > num_jobs can be safely deleted while (rowCount() > jobs.size()) { removeRow(rowCount() - 1); } } request->deleteLater(); } else { qCWarning(LIBKCUPS) << "Should not be called from a non KCupsRequest class" << sender(); } m_jobRequest = 0; } void JobModel::jobCompleted(const QString &text, const QString &printerUri, const QString &printerName, uint printerState, const QString &printerStateReasons, bool printerIsAcceptingJobs, uint jobId, uint jobState, const QString &jobStateReasons, const QString &jobName, uint jobImpressionsCompleted) { // REALLY? all these parameters just to say foo was deleted?? Q_UNUSED(text) Q_UNUSED(printerUri) Q_UNUSED(printerName) Q_UNUSED(printerState) Q_UNUSED(printerStateReasons) Q_UNUSED(printerIsAcceptingJobs) Q_UNUSED(jobId) Q_UNUSED(jobState) Q_UNUSED(jobStateReasons) Q_UNUSED(jobName) Q_UNUSED(jobImpressionsCompleted) // We grab all jobs again getJobs(); } void JobModel::insertUpdateJob(const QString &text, const QString &printerUri, const QString &printerName, uint printerState, const QString &printerStateReasons, bool printerIsAcceptingJobs, uint jobId, uint jobState, const QString &jobStateReasons, const QString &jobName, uint jobImpressionsCompleted) { // REALLY? all these parameters just to say foo was created?? Q_UNUSED(text) Q_UNUSED(printerUri) Q_UNUSED(printerName) Q_UNUSED(printerState) Q_UNUSED(printerStateReasons) Q_UNUSED(printerIsAcceptingJobs) Q_UNUSED(jobId) Q_UNUSED(jobState) Q_UNUSED(jobStateReasons) Q_UNUSED(jobName) Q_UNUSED(jobImpressionsCompleted) // We grab all jobs again getJobs(); } void JobModel::insertJob(int pos, const KCupsJob &job) { // insert the first column which has the job state and id QList row; ipp_jstate_e jobState = job.state(); auto statusItem = new QStandardItem(jobStatus(jobState)); statusItem->setData(jobState, RoleJobState); statusItem->setData(job.id(), RoleJobId); statusItem->setData(job.name(), RoleJobName); statusItem->setData(job.originatingUserName(), RoleJobOwner); statusItem->setData(job.originatingHostName(), RoleJobOriginatingHostName); QString size = KFormat().formatByteSize(job.size()); statusItem->setData(size, RoleJobSize); QString createdAt = QLocale().toString(job.createdAt()); statusItem->setData(createdAt, RoleJobCreatedAt); // TODO move the update code before the insert and reuse some code... statusItem->setData(KCupsJob::iconName(jobState), RoleJobIconName); statusItem->setData(KCupsJob::cancelEnabled(jobState), RoleJobCancelEnabled); statusItem->setData(KCupsJob::holdEnabled(jobState), RoleJobHoldEnabled); statusItem->setData(KCupsJob::releaseEnabled(jobState), RoleJobReleaseEnabled); statusItem->setData(job.reprintEnabled(), RoleJobRestartEnabled); QString pages = QString::number(job.pages()); if (job.processedPages()) { pages = QString::number(job.processedPages()) % QLatin1Char('/') % QString::number(job.processedPages()); } if (statusItem->data(RoleJobPages) != pages) { statusItem->setData(pages, RoleJobPages); } row << statusItem; for (int i = ColName; i < LastColumn; i++) { // adds all Items to the model row << new QStandardItem; } // insert the whole row insertRow(pos, row); // update the items updateJob(pos, job); } void JobModel::updateJob(int pos, const KCupsJob &job) { // Job Status & internal dataipp_jstate_e ipp_jstate_e jobState = job.state(); if (item(pos, ColStatus)->data(RoleJobState).toInt() != jobState) { item(pos, ColStatus)->setText(jobStatus(jobState)); item(pos, ColStatus)->setData(static_cast(jobState), RoleJobState); item(pos, ColStatus)->setData(KCupsJob::iconName(jobState), RoleJobIconName); item(pos, ColStatus)->setData(KCupsJob::cancelEnabled(jobState), RoleJobCancelEnabled); item(pos, ColStatus)->setData(KCupsJob::holdEnabled(jobState), RoleJobHoldEnabled); item(pos, ColStatus)->setData(KCupsJob::releaseEnabled(jobState), RoleJobReleaseEnabled); item(pos, ColStatus)->setData(job.reprintEnabled(), RoleJobRestartEnabled); } QString pages = QString::number(job.pages()); if (job.processedPages()) { pages = QString::number(job.processedPages()) % QLatin1Char('/') % QString::number(job.processedPages()); } if (item(pos, ColStatus)->data(RoleJobPages) != pages) { item(pos, ColStatus)->setData(pages, RoleJobPages); } // internal dest name & column QString destName = job.printer(); if (item(pos, ColStatus)->data(RoleJobPrinter).toString() != destName) { item(pos, ColStatus)->setData(destName, RoleJobPrinter); // Column job printer Name item(pos, ColPrinter)->setText(destName); } // job name QString jobName = job.name(); if (item(pos, ColName)->text() != jobName) { item(pos, ColStatus)->setData(jobName, RoleJobName); item(pos, ColName)->setText(jobName); } // owner of the job // try to get the full user name QString userString = job.originatingUserName(); KUser user(userString); if (user.isValid() && !user.property(KUser::FullName).toString().isEmpty()) { userString = user.property(KUser::FullName).toString(); } // user name if (item(pos, ColUser)->text() != userString) { item(pos, ColUser)->setText(userString); } // when it was created QDateTime timeAtCreation = job.createdAt(); if (item(pos, ColCreated)->data(Qt::DisplayRole).toDateTime() != timeAtCreation) { item(pos, ColCreated)->setData(timeAtCreation, Qt::DisplayRole); } // when it was completed QDateTime completedAt = job.completedAt(); if (item(pos, ColCompleted)->data(Qt::DisplayRole).toDateTime() != completedAt) { if (!completedAt.isNull()) { item(pos, ColCompleted)->setData(completedAt, Qt::DisplayRole); } else { // Clean the data might happen when the job is restarted item(pos, ColCompleted)->setText(QString()); } } // job pages int completedPages = job.processedPages(); if (item(pos, ColPages)->data(Qt::UserRole) != completedPages) { item(pos, ColPages)->setData(completedPages, Qt::UserRole); item(pos, ColPages)->setText(QString::number(completedPages)); } // when it was precessed QDateTime timeAtProcessing = job.processedAt(); if (item(pos, ColProcessed)->data(Qt::DisplayRole).toDateTime() != timeAtProcessing) { if (!timeAtProcessing.isNull()) { item(pos, ColProcessed)->setData(timeAtProcessing, Qt::DisplayRole); } else { // Clean the data might happen when the job is restarted item(pos, ColCompleted)->setText(QString()); } } int jobSize = job.size(); if (item(pos, ColSize)->data(Qt::UserRole) != jobSize) { item(pos, ColSize)->setData(jobSize, Qt::UserRole); item(pos, ColSize)->setText(KFormat().formatByteSize(jobSize)); } // job printer state message QString stateMessage = job.stateMsg(); if (item(pos, ColStatusMessage)->text() != stateMessage) { item(pos, ColStatusMessage)->setText(stateMessage); } // owner of the job // try to get the full user name QString originatingHostName = job.originatingHostName(); if (item(pos, ColFromHost)->text() != originatingHostName) { item(pos, ColFromHost)->setText(originatingHostName); } } QStringList JobModel::mimeTypes() const { return QStringList("application/x-cupsjobs"); } Qt::DropActions JobModel::supportedDropActions() const { return Qt::MoveAction; } QMimeData* JobModel::mimeData(const QModelIndexList &indexes) const { auto mimeData = new QMimeData(); QByteArray encodedData; QDataStream stream(&encodedData, QIODevice::WriteOnly); - foreach (const QModelIndex &index, indexes) { + for (const QModelIndex &index : indexes) { if (index.isValid() && index.column() == 0) { // serialize the jobId and fromDestName stream << data(index, RoleJobId).toInt() << data(index, RoleJobPrinter).toString() << item(index.row(), ColName)->text(); } } mimeData->setData("application/x-cupsjobs", encodedData); return mimeData; } bool JobModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) { Q_UNUSED(row) Q_UNUSED(column) Q_UNUSED(parent) if (action == Qt::IgnoreAction) { return true; } if (!data->hasFormat("application/x-cupsjobs")) { return false; } QByteArray encodedData = data->data("application/x-cupsjobs"); QDataStream stream(&encodedData, QIODevice::ReadOnly); bool ret = false; while (!stream.atEnd()) { QString fromDestName, displayName; int jobId; // get the jobid and the from dest name stream >> jobId >> fromDestName >> displayName; if (fromDestName == m_destName) { continue; } QPointer request = new KCupsRequest; request->moveJob(fromDestName, jobId, m_destName); request->waitTillFinished(); if (request) { if (request->hasError()) { // failed to move one job // we return here to avoid more password tries KMessageBox::detailedSorryWId(m_parentId, i18n("Failed to move '%1' to '%2'", displayName, m_destName), request->errorMsg(), i18n("Failed")); } request->deleteLater(); ret = !request->hasError(); } } return ret; } KCupsRequest* JobModel::modifyJob(int row, JobAction action, const QString &newDestName, const QModelIndex &parent) { Q_UNUSED(parent) if (row < 0 || row >= rowCount()) { qCWarning(LIBKCUPS) << "Row number is invalid:" << row; return 0; } QStandardItem *job = item(row, ColStatus); int jobId = job->data(RoleJobId).toInt(); QString destName = job->data(RoleJobPrinter).toString(); // ignore some jobs ipp_jstate_t state = static_cast(job->data(RoleJobState).toInt()); if ((state == IPP_JOB_HELD && action == Hold) || (state == IPP_JOB_CANCELED && action == Cancel) || (state != IPP_JOB_HELD && action == Release)) { return 0; } auto request = new KCupsRequest; switch (action) { case Cancel: request->cancelJob(destName, jobId); break; case Hold: request->holdJob(destName, jobId); break; case Release: request->releaseJob(destName, jobId); break; case Reprint: request->restartJob(destName, jobId); break; case Move: request->moveJob(destName, jobId, newDestName); break; default: qCWarning(LIBKCUPS) << "Unknown ACTION called!!!" << action; return 0; } return request; } int JobModel::jobRow(int jobId) { // find the position of the jobId inside the model for (int i = 0; i < rowCount(); i++) { if (jobId == item(i)->data(RoleJobId).toInt()) { return i; } } // -1 if not found return -1; } QString JobModel::jobStatus(ipp_jstate_e job_state) { switch (job_state) { case IPP_JOB_PENDING : return i18n("Pending"); case IPP_JOB_HELD : return i18n("On hold"); case IPP_JOB_PROCESSING : return "-"; case IPP_JOB_STOPPED : return i18n("Stopped"); case IPP_JOB_CANCELED : return i18n("Canceled"); case IPP_JOB_ABORTED : return i18n("Aborted"); case IPP_JOB_COMPLETED : return i18n("Completed"); } return "-"; } void JobModel::clear() { removeRows(0, rowCount()); } void JobModel::setWhichJobs(WhichJobs whichjobs) { switch (whichjobs) { case WhichActive: m_whichjobs = CUPS_WHICHJOBS_ACTIVE; break; case WhichCompleted: m_whichjobs = CUPS_WHICHJOBS_COMPLETED; break; case WhichAll: m_whichjobs = CUPS_WHICHJOBS_ALL; break; } getJobs(); } Qt::ItemFlags JobModel::flags(const QModelIndex &index) const { if (index.isValid()) { ipp_jstate_t state = static_cast(item(index.row(), ColStatus)->data(RoleJobState).toInt()); if (state == IPP_JOB_PENDING || state == IPP_JOB_PROCESSING) { return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled; } } return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled; } QString JobModel::processingJob() const { return m_processingJob; } diff --git a/libkcups/KCupsRequest.cpp b/libkcups/KCupsRequest.cpp index 0d5e2c3..199a2a6 100644 --- a/libkcups/KCupsRequest.cpp +++ b/libkcups/KCupsRequest.cpp @@ -1,674 +1,670 @@ /*************************************************************************** * Copyright (C) 2010-2012 by Daniel Nicoletti * * dantti12@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "KCupsRequest.h" #include "Debug.h" #include "KIppRequest.h" #include "KCupsJob.h" #include "KCupsPrinter.h" #include #include #include #include #define CUPS_DATADIR "/usr/share/cups" KCupsRequest::KCupsRequest(KCupsConnection *connection) : m_connection(connection), m_finished(true), m_error(IPP_OK) { // If no connection was specified use default one if (m_connection == 0) { m_connection = KCupsConnection::global(); } connect(this, &KCupsRequest::finished, &m_loop, &QEventLoop::quit); } QString KCupsRequest::serverError() const { switch (error()) { case IPP_SERVICE_UNAVAILABLE: return i18n("Print service is unavailable"); case IPP_NOT_FOUND : return i18n("Not found"); default : // In this case we don't want to map all enums qCWarning(LIBKCUPS) << "status unrecognised: " << error(); return QString::fromUtf8(ippErrorString(error())); } } void KCupsRequest::getPPDS(const QString &make) { if (m_connection->readyToStart()) { KIppRequest request(CUPS_GET_PPDS, "/"); if (!make.isEmpty()) { request.addString(IPP_TAG_PRINTER, IPP_TAG_TEXT, KCUPS_PPD_MAKE_AND_MODEL, make); } m_ppds = m_connection->request(request, IPP_TAG_PRINTER); setError(httpGetStatus(CUPS_HTTP_DEFAULT), cupsLastError(), QString::fromUtf8(cupsLastErrorString())); setFinished(); } else { invokeMethod("getPPDS", make); } } static void choose_device_cb(const char *device_class, /* I - Class */ const char *device_id, /* I - 1284 device ID */ const char *device_info, /* I - Description */ const char *device_make_and_model, /* I - Make and model */ const char *device_uri, /* I - Device URI */ const char *device_location, /* I - Location */ void *user_data) /* I - Result object */ { /* * Add the device to the array... */ auto request = static_cast(user_data); QMetaObject::invokeMethod(request, "device", Qt::QueuedConnection, Q_ARG(QString, QString::fromUtf8(device_class)), Q_ARG(QString, QString::fromUtf8(device_id)), Q_ARG(QString, QString::fromUtf8(device_info)), Q_ARG(QString, QString::fromUtf8(device_make_and_model)), Q_ARG(QString, QString::fromUtf8(device_uri)), Q_ARG(QString, QString::fromUtf8(device_location))); } void KCupsRequest::getDevices(int timeout) { getDevices(timeout, QStringList(), QStringList()); } void KCupsRequest::getDevices(int timeout, QStringList includeSchemes, QStringList excludeSchemes) { if (m_connection->readyToStart()) { do { const char *include; if (includeSchemes.isEmpty()) { include = CUPS_INCLUDE_ALL; } else { include = includeSchemes.join(QLatin1String(",")).toUtf8(); } const char *exclude; if (excludeSchemes.isEmpty()) { exclude = CUPS_EXCLUDE_NONE; } else { exclude = excludeSchemes.join(QLatin1String(",")).toUtf8(); } // Scan for devices for "timeout" seconds cupsGetDevices(CUPS_HTTP_DEFAULT, timeout, include, exclude, (cups_device_cb_t) choose_device_cb, this); } while (m_connection->retry("/admin/", CUPS_GET_DEVICES)); setError(httpGetStatus(CUPS_HTTP_DEFAULT), cupsLastError(), QString::fromUtf8(cupsLastErrorString())); setFinished(true); } else { invokeMethod("getDevices", timeout, includeSchemes, excludeSchemes); } } // THIS function can get the default server dest through the // "printer-is-default" attribute BUT it does not get user // defined default printer, see cupsGetDefault() on www.cups.org for details void KCupsRequest::getPrinters(QStringList attributes, int mask) { if (m_connection->readyToStart()) { KIppRequest request(CUPS_GET_PRINTERS, "/"); request.addInteger(IPP_TAG_OPERATION, IPP_TAG_ENUM, KCUPS_PRINTER_TYPE, CUPS_PRINTER_LOCAL); if (!attributes.isEmpty()) { request.addStringList(IPP_TAG_OPERATION, IPP_TAG_KEYWORD, KCUPS_REQUESTED_ATTRIBUTES, attributes); } if (mask != -1) { request.addInteger(IPP_TAG_OPERATION, IPP_TAG_ENUM, KCUPS_PRINTER_TYPE_MASK, mask); } - ReturnArguments ret; - ret = m_connection->request(request, IPP_TAG_PRINTER); + const ReturnArguments ret = m_connection->request(request, IPP_TAG_PRINTER); - foreach (const QVariantHash &arguments, ret) { + for (const QVariantHash &arguments : ret) { m_printers << KCupsPrinter(arguments); } setError(httpGetStatus(CUPS_HTTP_DEFAULT), cupsLastError(), QString::fromUtf8(cupsLastErrorString())); setFinished(); } else { invokeMethod("getPrinters", qVariantFromValue(attributes), mask); } } void KCupsRequest::getPrinterAttributes(const QString &printerName, bool isClass, QStringList attributes) { if (m_connection->readyToStart()) { KIppRequest request(IPP_GET_PRINTER_ATTRIBUTES, "/"); request.addPrinterUri(printerName, isClass); request.addInteger(IPP_TAG_OPERATION, IPP_TAG_ENUM, KCUPS_PRINTER_TYPE, CUPS_PRINTER_LOCAL); request.addStringList(IPP_TAG_OPERATION, IPP_TAG_KEYWORD, KCUPS_REQUESTED_ATTRIBUTES, attributes); - ReturnArguments ret; - ret = m_connection->request(request, IPP_TAG_PRINTER); + const ReturnArguments ret = m_connection->request(request, IPP_TAG_PRINTER); - foreach (const QVariantHash &arguments, ret) { + for (const QVariantHash &arguments : ret) { // Inject the printer name back to the arguments hash QVariantHash args = arguments; args[KCUPS_PRINTER_NAME] = printerName; m_printers << KCupsPrinter(args); } setError(httpGetStatus(CUPS_HTTP_DEFAULT), cupsLastError(), QString::fromUtf8(cupsLastErrorString())); setFinished(); } else { invokeMethod("getPrinterAttributes", printerName, isClass, qVariantFromValue(attributes)); } } void KCupsRequest::getJobs(const QString &printerName, bool myJobs, int whichJobs, QStringList attributes) { if (m_connection->readyToStart()) { KIppRequest request(IPP_GET_JOBS, "/"); // printer-uri makes the Name of the Job and owner came blank lol request.addPrinterUri(printerName, false); request.addInteger(IPP_TAG_OPERATION, IPP_TAG_ENUM, KCUPS_PRINTER_TYPE, CUPS_PRINTER_LOCAL); request.addStringList(IPP_TAG_OPERATION, IPP_TAG_KEYWORD, KCUPS_REQUESTED_ATTRIBUTES, attributes); request.addInteger(IPP_TAG_OPERATION, IPP_TAG_ENUM, KCUPS_MY_JOBS, myJobs); if (whichJobs == CUPS_WHICHJOBS_COMPLETED) { request.addString(IPP_TAG_OPERATION, IPP_TAG_KEYWORD, KCUPS_WHICH_JOBS, "completed"); } else if (whichJobs == CUPS_WHICHJOBS_ALL) { request.addString(IPP_TAG_OPERATION, IPP_TAG_KEYWORD, KCUPS_WHICH_JOBS, "all"); } - ReturnArguments ret; - ret = m_connection->request(request, IPP_TAG_JOB); + const ReturnArguments ret = m_connection->request(request, IPP_TAG_JOB); - foreach (const QVariantHash &arguments, ret) { + for (const QVariantHash &arguments : ret) { m_jobs << KCupsJob(arguments); } setError(httpGetStatus(CUPS_HTTP_DEFAULT), cupsLastError(), QString::fromUtf8(cupsLastErrorString())); setFinished(); } else { invokeMethod("getJobs", printerName, myJobs, whichJobs, qVariantFromValue(attributes)); } } void KCupsRequest::getJobAttributes(int jobId, const QString &printerUri, QStringList attributes) { if (m_connection->readyToStart()) { KIppRequest request(IPP_GET_JOB_ATTRIBUTES, "/"); request.addString(IPP_TAG_OPERATION, IPP_TAG_URI, KCUPS_PRINTER_URI, printerUri); request.addInteger(IPP_TAG_OPERATION, IPP_TAG_ENUM, KCUPS_PRINTER_TYPE, CUPS_PRINTER_LOCAL); request.addStringList(IPP_TAG_OPERATION, IPP_TAG_KEYWORD, KCUPS_REQUESTED_ATTRIBUTES, attributes); request.addInteger(IPP_TAG_OPERATION, IPP_TAG_INTEGER, KCUPS_JOB_ID, jobId); - ReturnArguments ret; - ret = m_connection->request(request, IPP_TAG_PRINTER); + const ReturnArguments ret = m_connection->request(request, IPP_TAG_PRINTER); - foreach (const QVariantHash &arguments, ret) { + for (const QVariantHash &arguments : ret) { m_jobs << KCupsJob(arguments); } setError(httpGetStatus(CUPS_HTTP_DEFAULT), cupsLastError(), QString::fromUtf8(cupsLastErrorString())); setFinished(); } else { invokeMethod("getJobAttributes", jobId, printerUri, qVariantFromValue(attributes)); } } void KCupsRequest::getServerSettings() { if (m_connection->readyToStart()) { do { int num_settings; cups_option_t *settings; QVariantHash arguments; int ret = cupsAdminGetServerSettings(CUPS_HTTP_DEFAULT, &num_settings, &settings); for (int i = 0; i < num_settings; ++i) { QString name = QString::fromUtf8(settings[i].name); QString value = QString::fromUtf8(settings[i].value); arguments[name] = value; } cupsFreeOptions(num_settings, settings); if (ret) { setError(HTTP_OK, IPP_OK, QString()); } else { setError(httpGetStatus(CUPS_HTTP_DEFAULT), cupsLastError(), QString::fromUtf8(cupsLastErrorString())); } m_server = KCupsServer(arguments); } while (m_connection->retry("/admin/", -1)); setFinished(); } else { invokeMethod("getServerSettings"); } } void KCupsRequest::getPrinterPPD(const QString &printerName) { if (m_connection->readyToStart()) { do { const char *filename; filename = cupsGetPPD2(CUPS_HTTP_DEFAULT, printerName.toUtf8()); qCDebug(LIBKCUPS) << filename; m_ppdFile = filename; qCDebug(LIBKCUPS) << m_ppdFile; } while (m_connection->retry("/", CUPS_GET_PPD)); setError(httpGetStatus(CUPS_HTTP_DEFAULT), cupsLastError(), QString::fromUtf8(cupsLastErrorString())); setFinished(); } else { invokeMethod("getPrinterPPD", printerName); } } void KCupsRequest::setServerSettings(const KCupsServer &server) { if (m_connection->readyToStart()) { do { QVariantHash args = server.arguments(); int num_settings = 0; cups_option_t *settings; QVariantHash::const_iterator i = args.constBegin(); while (i != args.constEnd()) { num_settings = cupsAddOption(i.key().toUtf8(), i.value().toString().toUtf8(), num_settings, &settings); ++i; } cupsAdminSetServerSettings(CUPS_HTTP_DEFAULT, num_settings, settings); cupsFreeOptions(num_settings, settings); } while (m_connection->retry("/admin/", -1)); setError(httpGetStatus(CUPS_HTTP_DEFAULT), cupsLastError(), QString::fromUtf8(cupsLastErrorString())); setFinished(); } else { invokeMethod("setServerSettings", qVariantFromValue(server)); } } void KCupsRequest::addOrModifyPrinter(const QString &printerName, const QVariantHash &attributes, const QString &filename) { KIppRequest request(CUPS_ADD_MODIFY_PRINTER, "/admin/", filename); request.addPrinterUri(printerName); request.addVariantValues(attributes); process(request); } void KCupsRequest::addOrModifyClass(const QString &printerName, const QVariantHash &attributes) { KIppRequest request(CUPS_ADD_MODIFY_CLASS, "/admin/"); request.addPrinterUri(printerName, true); request.addVariantValues(attributes); process(request); } void KCupsRequest::setShared(const QString &printerName, bool isClass, bool shared) { KIppRequest request(isClass ? CUPS_ADD_MODIFY_CLASS : CUPS_ADD_MODIFY_PRINTER, "/admin/"); request.addPrinterUri(printerName, isClass); request.addBoolean(IPP_TAG_OPERATION, KCUPS_PRINTER_IS_SHARED, shared); process(request); } void KCupsRequest::pausePrinter(const QString &printerName) { KIppRequest request(IPP_PAUSE_PRINTER, "/admin/"); request.addPrinterUri(printerName); process(request); } void KCupsRequest::resumePrinter(const QString &printerName) { KIppRequest request(IPP_RESUME_PRINTER, "/admin/"); request.addPrinterUri(printerName); process(request); } void KCupsRequest::rejectJobs(const QString &printerName) { KIppRequest request(CUPS_REJECT_JOBS, "/admin/"); request.addPrinterUri(printerName); process(request); } void KCupsRequest::acceptJobs(const QString &printerName) { KIppRequest request(CUPS_ACCEPT_JOBS, "/admin/"); request.addPrinterUri(printerName); process(request); } void KCupsRequest::setDefaultPrinter(const QString &printerName) { KIppRequest request(CUPS_SET_DEFAULT, "/admin/"); request.addPrinterUri(printerName); process(request); } void KCupsRequest::deletePrinter(const QString &printerName) { KIppRequest request(CUPS_DELETE_PRINTER, "/admin/"); request.addPrinterUri(printerName); process(request); } void KCupsRequest::printTestPage(const QString &printerName, bool isClass) { QString resource; /* POST resource path */ QString filename; /* Test page filename */ QString datadir; /* CUPS_DATADIR env var */ /* * Locate the test page file... */ datadir = qgetenv("CUPS_DATADIR"); if (datadir.isEmpty()) { datadir = CUPS_DATADIR; } filename = datadir % QLatin1String("/data/testprint"); /* * Point to the printer/class... */ if (isClass) { resource = QLatin1String("/classes/") % printerName; } else { resource = QLatin1String("/printers/") % printerName; } KIppRequest request(IPP_PRINT_JOB, resource.toUtf8(), filename); request.addPrinterUri(printerName); request.addString(IPP_TAG_OPERATION, IPP_TAG_NAME, KCUPS_JOB_NAME, i18n("Test Page")); process(request); } void KCupsRequest::printCommand(const QString &printerName, const QString &command, const QString &title) { if (m_connection->readyToStart()) { do { int job_id; /* Command file job */ char command_file[1024]; /* Command "file" */ http_status_t status; /* Document status */ cups_option_t hold_option; /* job-hold-until option */ /* * Create the CUPS command file... */ snprintf(command_file, sizeof(command_file), "#CUPS-COMMAND\n%s\n", command.toUtf8().data()); /* * Send the command file job... */ hold_option.name = const_cast("job-hold-until"); hold_option.value = const_cast("no-hold"); if ((job_id = cupsCreateJob(CUPS_HTTP_DEFAULT, printerName.toUtf8(), title.toUtf8(), 1, &hold_option)) < 1) { qWarning() << "Unable to send command to printer driver!"; setError(HTTP_OK, IPP_NOT_POSSIBLE, i18n("Unable to send command to printer driver!")); setFinished(); return; } status = cupsStartDocument(CUPS_HTTP_DEFAULT, printerName.toUtf8(), job_id, NULL, CUPS_FORMAT_COMMAND, 1); if (status == HTTP_CONTINUE) { status = cupsWriteRequestData(CUPS_HTTP_DEFAULT, command_file, strlen(command_file)); } if (status == HTTP_CONTINUE) { cupsFinishDocument(CUPS_HTTP_DEFAULT, printerName.toUtf8()); } setError(httpGetStatus(CUPS_HTTP_DEFAULT), cupsLastError(), QString::fromUtf8(cupsLastErrorString())); if (httpGetStatus(CUPS_HTTP_DEFAULT), cupsLastError() >= IPP_REDIRECTION_OTHER_SITE) { qWarning() << "Unable to send command to printer driver!"; cupsCancelJob(printerName.toUtf8(), job_id); setFinished(); return; // Return to avoid a new try } } while (m_connection->retry("/", IPP_CREATE_JOB)); setError(httpGetStatus(CUPS_HTTP_DEFAULT), cupsLastError(), QString::fromUtf8(cupsLastErrorString())); setFinished(); } else { invokeMethod("printCommand", printerName, command, title); } } void KCupsRequest::cancelJob(const QString &printerName, int jobId) { KIppRequest request(IPP_CANCEL_JOB, "/jobs/"); request.addPrinterUri(printerName); request.addInteger(IPP_TAG_OPERATION, IPP_TAG_INTEGER, KCUPS_JOB_ID, jobId); process(request); } void KCupsRequest::holdJob(const QString &printerName, int jobId) { KIppRequest request(IPP_HOLD_JOB, "/jobs/"); request.addPrinterUri(printerName); request.addInteger(IPP_TAG_OPERATION, IPP_TAG_INTEGER, KCUPS_JOB_ID, jobId); process(request); } void KCupsRequest::releaseJob(const QString &printerName, int jobId) { KIppRequest request(IPP_RELEASE_JOB, "/jobs/"); request.addPrinterUri(printerName); request.addInteger(IPP_TAG_OPERATION, IPP_TAG_INTEGER, KCUPS_JOB_ID, jobId); process(request); } void KCupsRequest::restartJob(const QString &printerName, int jobId) { KIppRequest request(IPP_RESTART_JOB, "/jobs/"); request.addPrinterUri(printerName); request.addInteger(IPP_TAG_OPERATION, IPP_TAG_INTEGER, KCUPS_JOB_ID, jobId); process(request); } void KCupsRequest::moveJob(const QString &fromPrinterName, int jobId, const QString &toPrinterName) { if (jobId < -1 || fromPrinterName.isEmpty() || toPrinterName.isEmpty() || jobId == 0) { qWarning() << "Internal error, invalid input data" << jobId << fromPrinterName << toPrinterName; setFinished(); return; } KIppRequest request(CUPS_MOVE_JOB, "/jobs/"); request.addPrinterUri(fromPrinterName); request.addInteger(IPP_TAG_OPERATION, IPP_TAG_INTEGER, KCUPS_JOB_ID, jobId); QString toPrinterUri = KIppRequest::assembleUrif(toPrinterName, false); request.addString(IPP_TAG_OPERATION, IPP_TAG_URI, KCUPS_JOB_PRINTER_URI, toPrinterUri); process(request); } void KCupsRequest::invokeMethod(const char *method, const QVariant &arg1, const QVariant &arg2, const QVariant &arg3, const QVariant &arg4, const QVariant &arg5, const QVariant &arg6, const QVariant &arg7, const QVariant &arg8) { m_error = IPP_OK; m_errorMsg.clear(); m_printers.clear(); m_jobs.clear(); m_ppds.clear(); m_ppdFile.clear(); // If this fails we get into a infinite loop // Do not use global()->thread() which point // to the KCupsConnection parent thread moveToThread(m_connection); m_finished = !QMetaObject::invokeMethod(this, method, Qt::QueuedConnection, QGenericArgument(arg1.typeName(), arg1.data()), QGenericArgument(arg2.typeName(), arg2.data()), QGenericArgument(arg3.typeName(), arg3.data()), QGenericArgument(arg4.typeName(), arg4.data()), QGenericArgument(arg5.typeName(), arg5.data()), QGenericArgument(arg6.typeName(), arg6.data()), QGenericArgument(arg7.typeName(), arg7.data()), QGenericArgument(arg8.typeName(), arg8.data())); if (m_finished) { setError(HTTP_ERROR, IPP_BAD_REQUEST, i18n("Failed to invoke method: %1", method)); setFinished(); } } void KCupsRequest::process(const KIppRequest &request) { if (m_connection->readyToStart()) { m_connection->request(request); setError(httpGetStatus(CUPS_HTTP_DEFAULT), cupsLastError(), QString::fromUtf8(cupsLastErrorString())); setFinished(); } else { invokeMethod("process", qVariantFromValue(request)); } } ReturnArguments KCupsRequest::ppds() const { return m_ppds; } KCupsServer KCupsRequest::serverSettings() const { return m_server; } QString KCupsRequest::printerPPD() const { return m_ppdFile; } KCupsPrinters KCupsRequest::printers() const { return m_printers; } KCupsJobs KCupsRequest::jobs() const { return m_jobs; } void KCupsRequest::waitTillFinished() { if (m_finished) { return; } m_loop.exec(); } bool KCupsRequest::hasError() const { return m_error; } ipp_status_t KCupsRequest::error() const { return m_error; } http_status_t KCupsRequest::httpStatus() const { return m_httpStatus; } QString KCupsRequest::errorMsg() const { return m_errorMsg; } KCupsConnection *KCupsRequest::connection() const { return m_connection; } void KCupsRequest::setError(http_status_t httpStatus, ipp_status_t error, const QString &errorMsg) { m_httpStatus = httpStatus; m_error = error; m_errorMsg = errorMsg; } void KCupsRequest::setFinished(bool delayed) { m_finished = true; if (delayed) { QTimer::singleShot(0, this, [this] () { emit finished(this); }); } else { emit finished(this); } } diff --git a/libkcups/KIppRequest.cpp b/libkcups/KIppRequest.cpp index a80e79d..9a7bd1f 100644 --- a/libkcups/KIppRequest.cpp +++ b/libkcups/KIppRequest.cpp @@ -1,273 +1,274 @@ /*************************************************************************** * Copyright (C) 2010-2013 by Daniel Nicoletti * * dantti12@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "KIppRequest.h" #include "KIppRequest_p.h" #include "Debug.h" #include KIppRequest::KIppRequest() : d_ptr(new KIppRequestPrivate) { } KIppRequest::KIppRequest(const KIppRequest &other) : d_ptr(new KIppRequestPrivate) { *this = other; } KIppRequest::KIppRequest(ipp_op_t operation, const char *resource, const QString &filename) : d_ptr(new KIppRequestPrivate) { Q_D(KIppRequest); d->operation = operation; d->resource = resource; d->filename = filename; // send our user name on the request too addString(IPP_TAG_OPERATION, IPP_TAG_NAME, KCUPS_REQUESTING_USER_NAME, cupsUser()); } KIppRequest::~KIppRequest() { Q_D(KIppRequest); delete d; } ipp_op_t KIppRequest::operation() const { Q_D(const KIppRequest); return d->operation; } QString KIppRequest::resource() const { Q_D(const KIppRequest); return d->resource; } QString KIppRequest::filename() const { Q_D(const KIppRequest); return d->filename; } ipp_t *KIppRequest::sendIppRequest() const { Q_D(const KIppRequest); ipp_t *request = ippNewRequest(d->operation); d->addRawRequestsToIpp(request); if (d->filename.isNull()) { return cupsDoRequest(CUPS_HTTP_DEFAULT, request, d->resource.toUtf8()); } else { return cupsDoFileRequest(CUPS_HTTP_DEFAULT, request, d->resource.toUtf8(), d->filename.toUtf8()); } } void KIppRequest::addString(ipp_tag_t group, ipp_tag_t valueTag, const QString &name, const QString &value) { Q_D(KIppRequest); d->addRequest(group, valueTag, name.toUtf8(), value); } void KIppRequest::addStringList(ipp_tag_t group, ipp_tag_t valueTag, const QString &name, const QStringList &value) { Q_D(KIppRequest); d->addRequest(group, valueTag, name.toUtf8(), value); } void KIppRequest::addInteger(ipp_tag_t group, ipp_tag_t valueTag, const QString &name, int value) { Q_D(KIppRequest); d->addRequest(group, valueTag, name.toUtf8(), value); } void KIppRequest::addBoolean(ipp_tag_t group, const QString &name, bool value) { Q_D(KIppRequest); d->addRequest(group, IPP_TAG_ZERO, name.toUtf8(), value); } void KIppRequest::addVariantValues(const QVariantHash &values) { QVariantHash::ConstIterator i = values.constBegin(); while (i != values.constEnd()) { QString key = i.key(); QVariant value = i.value(); switch (value.type()) { case QVariant::Bool: // Still in use at add-printer/PageAddPrinter.cpp if (key == QLatin1String(KCUPS_PRINTER_IS_ACCEPTING_JOBS)) { addBoolean(IPP_TAG_PRINTER, key, value.toBool()); } else { addBoolean(IPP_TAG_OPERATION, key, value.toBool()); } break; case QVariant::Int: // Still in use at add-printer/PageAddPrinter.cpp if (key == QLatin1String(KCUPS_PRINTER_STATE)) { addInteger(IPP_TAG_PRINTER, IPP_TAG_ENUM, key, value.toInt()); } else { addInteger(IPP_TAG_OPERATION, IPP_TAG_ENUM, key, value.toInt()); } break; case QVariant::String: // Still in use at add-printer/* if (key == QLatin1String(KCUPS_DEVICE_URI)) { // device uri has a different TAG addString(IPP_TAG_PRINTER, IPP_TAG_URI, key, value.toString()); } else if (key == QLatin1String(KCUPS_PRINTER_OP_POLICY) || key == QLatin1String(KCUPS_PRINTER_ERROR_POLICY) || key == QLatin1String("ppd-name")) { // printer-op-policy has a different TAG addString(IPP_TAG_PRINTER, IPP_TAG_NAME, key, value.toString()); } else if (key == QLatin1String(KCUPS_JOB_NAME)) { addString(IPP_TAG_OPERATION, IPP_TAG_NAME, key, value.toString()); } else if (key == QLatin1String(KCUPS_WHICH_JOBS)) { addString(IPP_TAG_OPERATION, IPP_TAG_KEYWORD, key, value.toString()); } else { addString(IPP_TAG_PRINTER, IPP_TAG_TEXT, key, value.toString()); } break; case QVariant::StringList: if (key == QLatin1String(KCUPS_MEMBER_URIS)) { addStringList(IPP_TAG_PRINTER, IPP_TAG_URI, key, value.toStringList()); } else { addStringList(IPP_TAG_PRINTER, IPP_TAG_NAME, key, value.toStringList()); } break; case QVariant::UInt: addInteger(IPP_TAG_OPERATION, IPP_TAG_ENUM, key, value.toInt()); break; default: qCWarning(LIBKCUPS) << "type NOT recognized! This will be ignored:" << key << "values" << i.value(); } ++i; } } void KIppRequest::addPrinterUri(const QString &printerName, bool isClass) { QString uri = assembleUrif(printerName, isClass); addString(IPP_TAG_OPERATION, IPP_TAG_URI, KCUPS_PRINTER_URI, uri); } QString KIppRequest::assembleUrif(const QString &name, bool isClass) { char uri[HTTP_MAX_URI]; // printer URI QString destination; if (isClass) { destination = QLatin1String("/classes/") % name; } else { destination = QLatin1String("/printers/") % name; } httpAssembleURIf(HTTP_URI_CODING_ALL, uri, sizeof(uri), "ipp", cupsUser(), "localhost", ippPort(), destination.toUtf8()); return uri; } KIppRequest &KIppRequest::operator =(const KIppRequest &other) { Q_D(KIppRequest); if (this == &other) return *this; *d = *other.d_ptr; return *this; } void KIppRequestPrivate::addRequest(ipp_tag_t group, ipp_tag_t valueTag, const QString &name, const QVariant &value) { KCupsRawRequest request; request.group = group; request.valueTag = valueTag; request.name = name; request.value = value; rawRequests << request; } void KIppRequestPrivate::addRawRequestsToIpp(ipp_t *ipp) const { // sort the values as CUPS requires it qSort(rawRequests.begin(), rawRequests.end(), rawRequestGroupLessThan); - foreach (const KCupsRawRequest &request, rawRequests) { + const QList &requests = rawRequests; + for (const KCupsRawRequest &request :requests) { switch (request.value.type()) { case QVariant::Bool: ippAddBoolean(ipp, request.group, request.name.toUtf8(), request.value.toBool()); break; case QVariant::Int: case QVariant::UInt: ippAddInteger(ipp, request.group, request.valueTag, request.name.toUtf8(), request.value.toInt()); break; case QVariant::String: ippAddString(ipp, request.group, request.valueTag, request.name.toUtf8(), "utf-8", request.value.toString().toUtf8()); break; case QVariant::StringList: { QStringList list = request.value.toStringList(); QList valuesQByteArrayList; const char **values = qStringListToCharPtrPtr(list, valuesQByteArrayList); ippAddStrings(ipp, request.group, request.valueTag, request.name.toUtf8(), list.size(), "utf-8", values); // ippAddStrings deep copies everything so we can throw away the values. // the QBAList and content is auto discarded when going out of scope. delete [] values; break; } default: qCWarning(LIBKCUPS) << "type NOT recognized! This will be ignored:" << request.name << "values" << request.value; } } } diff --git a/libkcups/PPDModel.cpp b/libkcups/PPDModel.cpp index 73573e1..3d662ad 100644 --- a/libkcups/PPDModel.cpp +++ b/libkcups/PPDModel.cpp @@ -1,128 +1,128 @@ /*************************************************************************** * Copyright (C) 2010-2018 by Daniel Nicoletti * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "PPDModel.h" #include "Debug.h" #include #include PPDModel::PPDModel(QObject *parent) : QStandardItemModel(parent) { } void PPDModel::setPPDs(const QList &ppds, const DriverMatchList &driverMatch) { clear(); QStandardItem *recommended = 0; - foreach (const DriverMatch &driver, driverMatch) { + for (const DriverMatch &driver : driverMatch) { // Find the matched PPD on the PPDs list - foreach (const QVariantHash &ppd, ppds) { + for (const QVariantHash &ppd : ppds) { if (ppd["ppd-name"].toString() == driver.ppd) { // Create the PPD QStandardItem *ppdItem = createPPDItem(ppd, true); if (recommended == 0) { recommended = new QStandardItem; recommended->setText(i18n("Recommended Drivers")); appendRow(recommended); } recommended->appendRow(ppdItem); break; } } } - foreach (const QVariantHash &ppd, ppds) { + for (const QVariantHash &ppd : ppds) { // Find or create the PPD parent (printer Make) QStandardItem *makeItem = findCreateMake(ppd["ppd-make"].toString()); // Create the PPD QStandardItem *ppdItem = createPPDItem(ppd, false); makeItem->appendRow(ppdItem); } } QStandardItem* PPDModel::findCreateMake(const QString &make) { for (int i = 0; i < rowCount(); ++i) { QStandardItem *makeItem = item(i); if (makeItem->text() == make) { return makeItem; } } auto makeItem = new QStandardItem(make); appendRow(makeItem); return makeItem; } Qt::ItemFlags PPDModel::flags(const QModelIndex &index) const { Q_UNUSED(index) return Qt::ItemIsSelectable | Qt::ItemIsEnabled; } void PPDModel::clear() { // Remove all rows from the model removeRows(0, rowCount()); } QStandardItem *PPDModel::createPPDItem(const QVariantHash &ppd, bool recommended) { auto ret = new QStandardItem; QString make = ppd["ppd-make"].toString(); QString makeAndModel = ppd["ppd-make-and-model"].toString(); QString naturalLanguage = ppd["ppd-natural-language"].toString(); QString ppdName = ppd["ppd-name"].toString(); // Set this data before we change the makeAndModel ret->setData(ppdName, PPDName); ret->setData(make, PPDMake); ret->setData(makeAndModel, PPDMakeAndModel); QString text; if (recommended) { text = makeAndModel % QLatin1String(" (") % naturalLanguage % QLatin1Char(')'); } else { // Removes the Make part of the string if (makeAndModel.startsWith(make)) { makeAndModel.remove(0, make.size() + 1); } // Create the PPD text = makeAndModel.trimmed() % QLatin1String(" (") % naturalLanguage % QLatin1Char(')'); } ret->setText(text); return ret; } diff --git a/libkcups/PrinterModel.cpp b/libkcups/PrinterModel.cpp index effd743..35b6053 100644 --- a/libkcups/PrinterModel.cpp +++ b/libkcups/PrinterModel.cpp @@ -1,517 +1,518 @@ /*************************************************************************** * Copyright (C) 2010-2018 by Daniel Nicoletti * * dantti12@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "PrinterModel.h" #include "Debug.h" #include #include #include #include #include #include #include #include #include #include PrinterModel::PrinterModel(QObject *parent) : QStandardItemModel(parent), m_unavailable(true) { m_attributes << KCUPS_PRINTER_NAME; m_attributes << KCUPS_PRINTER_STATE; m_attributes << KCUPS_PRINTER_STATE_MESSAGE; m_attributes << KCUPS_PRINTER_IS_SHARED; m_attributes << KCUPS_PRINTER_IS_ACCEPTING_JOBS; m_attributes << KCUPS_PRINTER_TYPE; m_attributes << KCUPS_PRINTER_LOCATION; m_attributes << KCUPS_PRINTER_INFO; m_attributes << KCUPS_PRINTER_MAKE_AND_MODEL; m_attributes << KCUPS_PRINTER_COMMANDS; m_attributes << KCUPS_MARKER_CHANGE_TIME; m_attributes << KCUPS_MARKER_COLORS; m_attributes << KCUPS_MARKER_LEVELS; m_attributes << KCUPS_MARKER_NAMES; m_attributes << KCUPS_MARKER_TYPES; QHash roles = roleNames(); roles[DestStatus] = "stateMessage"; roles[DestName] = "printerName"; roles[DestState] = "printerState"; roles[DestIsDefault] = "isDefault"; roles[DestIsShared] = "isShared"; roles[DestIsAcceptingJobs] = "isAcceptingJobs"; roles[DestIsPaused] = "isPaused"; roles[DestIsClass] = "isClass"; roles[DestLocation] = "location"; roles[DestDescription] = "info"; roles[DestKind] = "kind"; roles[DestType] = "type"; roles[DestCommands] = "commands"; roles[DestMarkerChangeTime] = "markerChangeTime"; roles[DestMarkers] = "markers"; roles[DestIconName] = "iconName"; roles[DestRemote] = "remote"; setRoleNames(roles); // This is emitted when a printer is added connect(KCupsConnection::global(), &KCupsConnection::printerAdded, this, &PrinterModel::insertUpdatePrinter); // This is emitted when a printer is modified connect(KCupsConnection::global(), &KCupsConnection::printerModified, this, &PrinterModel::insertUpdatePrinter); // This is emitted when a printer has it's state changed connect(KCupsConnection::global(), &KCupsConnection::printerStateChanged, this, &PrinterModel::insertUpdatePrinter); // This is emitted when a printer is stopped connect(KCupsConnection::global(), &KCupsConnection::printerStopped, this, &PrinterModel::insertUpdatePrinter); // This is emitted when a printer is restarted connect(KCupsConnection::global(), &KCupsConnection::printerRestarted, this, &PrinterModel::insertUpdatePrinter); // This is emitted when a printer is shutdown connect(KCupsConnection::global(), &KCupsConnection::printerShutdown, this, &PrinterModel::insertUpdatePrinter); // This is emitted when a printer is removed connect(KCupsConnection::global(), &KCupsConnection::printerDeleted, this, &PrinterModel::printerRemoved); connect(KCupsConnection::global(), &KCupsConnection::serverAudit, this, &PrinterModel::serverChanged); connect(KCupsConnection::global(), &KCupsConnection::serverStarted, this, &PrinterModel::serverChanged); connect(KCupsConnection::global(), &KCupsConnection::serverStopped, this, &PrinterModel::serverChanged); connect(KCupsConnection::global(), &KCupsConnection::serverRestarted, this, &PrinterModel::serverChanged); // Deprecated stuff that works better than the above connect(KCupsConnection::global(), &KCupsConnection::rhPrinterAdded, this, &PrinterModel::insertUpdatePrinterName); connect(KCupsConnection::global(), &KCupsConnection::rhPrinterRemoved, this, &PrinterModel::printerRemovedName); connect(KCupsConnection::global(), &KCupsConnection::rhQueueChanged, this, &PrinterModel::insertUpdatePrinterName); connect(this, &PrinterModel::rowsInserted, this, &PrinterModel::slotCountChanged); connect(this, &PrinterModel::rowsRemoved, this, &PrinterModel::slotCountChanged); connect(this, &PrinterModel::modelReset, this, &PrinterModel::slotCountChanged); update(); } void PrinterModel::getDestsFinished(KCupsRequest *request) { // When there is no printer IPP_NOT_FOUND is returned if (request->hasError() && request->error() != IPP_NOT_FOUND) { // clear the model after so that the proper widget can be shown clear(); emit error(request->error(), request->serverError(), request->errorMsg()); if (request->error() == IPP_SERVICE_UNAVAILABLE && !m_unavailable) { m_unavailable = true; emit serverUnavailableChanged(m_unavailable); } } else { if (m_unavailable) { m_unavailable = false; emit serverUnavailableChanged(m_unavailable); } KCupsPrinters printers = request->printers(); for (int i = 0; i < printers.size(); ++i) { // If there is a printer and it's not the current one add it // as a new destination int dest_row = destRow(printers.at(i).name()); if (dest_row == -1) { // not found, insert new one insertDest(i, printers.at(i)); } else if (dest_row == i) { // update the printer updateDest(item(i), printers.at(i)); } else { // found at wrong position // take it and insert on the right position QList row = takeRow(dest_row); insertRow(i, row); updateDest(item(i), printers.at(i)); } } // remove old printers // The above code starts from 0 and make sure // dest == modelIndex(x) and if it's not the // case it either inserts or moves it. // so any item > num_jobs can be safely deleted while (rowCount() > printers.size()) { removeRow(rowCount() - 1); } emit error(IPP_OK, QString(), QString()); } request->deleteLater(); } void PrinterModel::slotCountChanged() { emit countChanged(rowCount()); } QVariant PrinterModel::headerData(int section, Qt::Orientation orientation, int role) const { if (section == 0 && orientation == Qt::Horizontal && role == Qt::DisplayRole) { return i18n("Printers"); } return QVariant(); } int PrinterModel::count() const { return rowCount(); } bool PrinterModel::serverUnavailable() const { return m_unavailable; } void PrinterModel::pausePrinter(const QString &printerName) { QPointer request = new KCupsRequest; request->pausePrinter(printerName); request->waitTillFinished(); if (request) { request->deleteLater(); } } void PrinterModel::resumePrinter(const QString &printerName) { QPointer request = new KCupsRequest; request->resumePrinter(printerName); request->waitTillFinished(); if (request) { request->deleteLater(); } } void PrinterModel::rejectJobs(const QString &printerName) { QPointer request = new KCupsRequest; request->rejectJobs(printerName); request->waitTillFinished(); if (request) { request->deleteLater(); } } void PrinterModel::acceptJobs(const QString &printerName) { QPointer request = new KCupsRequest; request->acceptJobs(printerName); request->waitTillFinished(); if (request) { request->deleteLater(); } } void PrinterModel::update() { // kcmshell(6331) PrinterModel::update: (QHash(("printer-type", QVariant(int, 75534348) ) ( "marker-names" , QVariant(QStringList, ("Cyan", "Yellow", "Magenta", "Black") ) ) ( "printer-name" , QVariant(QString, "EPSON_Stylus_TX105") ) ( "marker-colors" , QVariant(QStringList, ("#00ffff", "#ffff00", "#ff00ff", "#000000") ) ) ( "printer-location" , QVariant(QString, "Luiz Vitor’s MacBook Pro") ) ( "marker-levels" , QVariant(QList, ) ) ( "marker-types" , QVariant(QStringList, ("inkCartridge", "inkCartridge", "inkCartridge", "inkCartridge") ) ) ( "printer-is-shared" , QVariant(bool, true) ) ( "printer-state-message" , QVariant(QString, "") ) ( "printer-commands" , QVariant(QStringList, ("Clean", "PrintSelfTestPage", "ReportLevels") ) ) ( "marker-change-time" , QVariant(int, 1267903160) ) ( "printer-state" , QVariant(int, 3) ) ( "printer-info" , QVariant(QString, "EPSON Stylus TX105") ) ( "printer-make-and-model" , QVariant(QString, "EPSON TX105 Series") ) ) ) // Get destinations with these attributes auto request = new KCupsRequest; connect(request, &KCupsRequest::finished, this, &PrinterModel::getDestsFinished); request->getPrinters(m_attributes); } void PrinterModel::insertDest(int pos, const KCupsPrinter &printer) { // Create the printer item auto stdItem = new QStandardItem(printer.name()); stdItem->setData(printer.name(), DestName); stdItem->setIcon(printer.icon()); // update the item updateDest(stdItem, printer); // insert the printer Item insertRow(pos, stdItem); } void PrinterModel::updateDest(QStandardItem *destItem, const KCupsPrinter &printer) { // store if the printer is the network default bool isDefault = printer.isDefault(); if (isDefault != destItem->data(DestIsDefault).toBool()) { destItem->setData(isDefault, DestIsDefault); } // store the printer state KCupsPrinter::Status state = printer.state(); if (state != destItem->data(DestState)) { destItem->setData(state, DestState); } qCDebug(LIBKCUPS) << state << printer.name(); // store if the printer is accepting jobs bool accepting = printer.isAcceptingJobs(); if (accepting != destItem->data(DestIsAcceptingJobs)) { destItem->setData(accepting, DestIsAcceptingJobs); } // store the printer status message QString status = destStatus(state, printer.stateMsg(), accepting); if (status != destItem->data(DestStatus)) { destItem->setData(status, DestStatus); } bool paused = (state == KCupsPrinter::Stopped || !accepting); if (paused != destItem->data(DestIsPaused)) { destItem->setData(paused, DestIsPaused); } // store if the printer is shared bool shared = printer.isShared(); if (shared != destItem->data(DestIsShared)) { destItem->setData(shared, DestIsShared); } // store if the printer is a class // the printer-type param is a flag bool isClass = printer.isClass(); if (isClass != destItem->data(DestIsClass)) { destItem->setData(isClass, DestIsClass); } // store if the printer type // the printer-type param is a flag uint printerType = printer.type(); if (printerType != destItem->data(DestType)) { destItem->setData(printerType, DestType); destItem->setData(printerType & CUPS_PRINTER_REMOTE, DestRemote); } // store the printer location QString location = printer.location(); if (location != destItem->data(DestLocation).toString()) { destItem->setData(location, DestLocation); } // store the printer icon name QString iconName = printer.iconName(); if (iconName != destItem->data(DestIconName).toString()) { destItem->setData(iconName, DestIconName); } if (destItem->data(DestName).toString() != destItem->text()){ if (destItem->text() != destItem->data(DestName).toString()){ destItem->setText(destItem->data(DestName).toString()); } } // store the printer description QString description = printer.info(); if (description != destItem->data(DestDescription).toString()){ destItem->setData(description, DestDescription); } // store the printer kind QString kind = printer.makeAndModel(); if (kind != destItem->data(DestKind)) { destItem->setData(kind, DestKind); } // store the printer commands QStringList commands = printer.commands(); if (commands != destItem->data(DestCommands)) { destItem->setData(commands, DestCommands); } int markerChangeTime = printer.markerChangeTime(); if (markerChangeTime != destItem->data(DestMarkerChangeTime)) { destItem->setData(printer.markerChangeTime(), DestMarkerChangeTime); QVariantHash markers; markers["marker-change-time"] = printer.markerChangeTime(); markers["marker-colors"] = printer.argument("marker-colors"); markers["marker-levels"] = printer.argument("marker-levels"); markers["marker-names"] = printer.argument("marker-names"); markers["marker-types"] = printer.argument("marker-types"); destItem->setData(markers, DestMarkers); } } int PrinterModel::destRow(const QString &destName) { // find the position of the jobId inside the model for (int i = 0; i < rowCount(); i++) { if (destName == item(i)->data(DestName).toString()) { return i; } } // -1 if not found return -1; } QString PrinterModel::destStatus(KCupsPrinter::Status state, const QString &message, bool isAcceptingJobs) const { switch (state) { case KCupsPrinter::Idle: if (message.isEmpty()){ return isAcceptingJobs ? i18n("Idle") : i18n("Idle, rejecting jobs"); } else { return isAcceptingJobs ? i18n("Idle - '%1'", message) : i18n("Idle, rejecting jobs - '%1'", message); } case KCupsPrinter::Printing: if (message.isEmpty()){ return i18n("In use"); } else { return i18n("In use - '%1'", message); } case KCupsPrinter::Stopped: if (message.isEmpty()){ return isAcceptingJobs ? i18n("Paused") : i18n("Paused, rejecting jobs"); } else { return isAcceptingJobs ? i18n("Paused - '%1'", message) : i18n("Paused, rejecting jobs - '%1'", message); } default : if (message.isEmpty()){ return i18n("Unknown"); } else { return i18n("Unknown - '%1'", message); } } } void PrinterModel::clear() { removeRows(0, rowCount()); } Qt::ItemFlags PrinterModel::flags(const QModelIndex &index) const { Q_UNUSED(index) return Qt::ItemIsSelectable | Qt::ItemIsEnabled; } void PrinterModel::insertUpdatePrinterName(const QString &printerName) { auto request = new KCupsRequest; connect(request, &KCupsRequest::finished, this, &PrinterModel::insertUpdatePrinterFinished); // TODO how do we know if it's a class if this DBus signal // does not tell us request->getPrinterAttributes(printerName, false, m_attributes); } void PrinterModel::insertUpdatePrinter(const QString &text, const QString &printerUri, const QString &printerName, uint printerState, const QString &printerStateReasons, bool printerIsAcceptingJobs) { Q_UNUSED(text) Q_UNUSED(printerUri) Q_UNUSED(printerState) Q_UNUSED(printerStateReasons) Q_UNUSED(printerIsAcceptingJobs) qCDebug(LIBKCUPS) << text << printerUri << printerName << printerState << printerStateReasons << printerIsAcceptingJobs; insertUpdatePrinterName(printerName); } void PrinterModel::insertUpdatePrinterFinished(KCupsRequest *request) { if (!request->hasError()) { - foreach (const KCupsPrinter &printer, request->printers()) { + const KCupsPrinters printers = request->printers(); + for (const KCupsPrinter &printer : printers) { // If there is a printer and it's not the current one add it // as a new destination int dest_row = destRow(printer.name()); if (dest_row == -1) { // not found, insert new one insertDest(0, printer); } else { // update the printer updateDest(item(dest_row), printer); } } } request->deleteLater(); } void PrinterModel::printerRemovedName(const QString &printerName) { qCDebug(LIBKCUPS) << printerName; // Look for the removed printer int dest_row = destRow(printerName); if (dest_row != -1) { removeRows(dest_row, 1); } } void PrinterModel::printerRemoved(const QString &text, const QString &printerUri, const QString &printerName, uint printerState, const QString &printerStateReasons, bool printerIsAcceptingJobs) { // REALLY? all these parameters just to say foo was deleted?? Q_UNUSED(text) Q_UNUSED(printerUri) Q_UNUSED(printerState) Q_UNUSED(printerStateReasons) Q_UNUSED(printerIsAcceptingJobs) qCDebug(LIBKCUPS) << text << printerUri << printerName << printerState << printerStateReasons << printerIsAcceptingJobs; // Look for the removed printer int dest_row = destRow(printerName); if (dest_row != -1) { removeRows(dest_row, 1); } } void PrinterModel::printerStateChanged(const QString &text, const QString &printerUri, const QString &printerName, uint printerState, const QString &printerStateReasons, bool printerIsAcceptingJobs) { qCDebug(LIBKCUPS) << text << printerUri << printerName << printerState << printerStateReasons << printerIsAcceptingJobs; } void PrinterModel::printerStopped(const QString &text, const QString &printerUri, const QString &printerName, uint printerState, const QString &printerStateReasons, bool printerIsAcceptingJobs) { qCDebug(LIBKCUPS) << text << printerUri << printerName << printerState << printerStateReasons << printerIsAcceptingJobs; } void PrinterModel::printerRestarted(const QString &text, const QString &printerUri, const QString &printerName, uint printerState, const QString &printerStateReasons, bool printerIsAcceptingJobs) { qCDebug(LIBKCUPS) << text << printerUri << printerName << printerState << printerStateReasons << printerIsAcceptingJobs; } void PrinterModel::printerShutdown(const QString &text, const QString &printerUri, const QString &printerName, uint printerState, const QString &printerStateReasons, bool printerIsAcceptingJobs) { qCDebug(LIBKCUPS) << text << printerUri << printerName << printerState << printerStateReasons << printerIsAcceptingJobs; } void PrinterModel::printerModified(const QString &text, const QString &printerUri, const QString &printerName, uint printerState, const QString &printerStateReasons, bool printerIsAcceptingJobs) { qCDebug(LIBKCUPS) << text << printerUri << printerName << printerState << printerStateReasons << printerIsAcceptingJobs; } void PrinterModel::serverChanged(const QString &text) { qCDebug(LIBKCUPS) << text; update(); } diff --git a/libkcups/SelectMakeModel.cpp b/libkcups/SelectMakeModel.cpp index ba72074..ef42c37 100644 --- a/libkcups/SelectMakeModel.cpp +++ b/libkcups/SelectMakeModel.cpp @@ -1,315 +1,316 @@ /*************************************************************************** * Copyright (C) 2010-2018 by Daniel Nicoletti * * dantti12@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "SelectMakeModel.h" #include "ui_SelectMakeModel.h" #include "PPDModel.h" #include "Debug.h" #include "KCupsRequest.h" #include "NoSelectionRectDelegate.h" #include #include #include #include #include #include #include #include // Marshall the MyStructure data into a D-Bus argument QDBusArgument &operator<<(QDBusArgument &argument, const DriverMatch &driverMatch) { argument.beginStructure(); argument << driverMatch.ppd << driverMatch.match; argument.endStructure(); return argument; } // Retrieve the MyStructure data from the D-Bus argument const QDBusArgument &operator>>(const QDBusArgument &argument, DriverMatch &driverMatch) { argument.beginStructure(); argument >> driverMatch.ppd >> driverMatch.match; argument.endStructure(); return argument; } SelectMakeModel::SelectMakeModel(QWidget *parent) : QWidget(parent), ui(new Ui::SelectMakeModel), m_ppdRequest(0), m_gotBestDrivers(false), m_hasRecommended(false) { ui->setupUi(this); // Configure the erro message widget ui->messageWidget->setMessageType(KMessageWidget::Error); ui->messageWidget->hide(); m_sourceModel = new PPDModel(this); ui->makeView->setModel(m_sourceModel); ui->makeView->setItemDelegate(new NoSelectionRectDelegate(this)); // Updates the PPD view to the selected Make connect(ui->makeView->selectionModel(), &QItemSelectionModel::currentChanged, ui->ppdsLV, &QListView::setRootIndex); ui->ppdsLV->setModel(m_sourceModel); ui->ppdsLV->setItemDelegate(new NoSelectionRectDelegate(this)); connect(m_sourceModel, &PPDModel::dataChanged, this, &SelectMakeModel::checkChanged); // Clear the PPD view selection, so the Next/Finish button gets disabled connect(ui->makeView->selectionModel(), &QItemSelectionModel::currentChanged, ui->ppdsLV->selectionModel(), &QItemSelectionModel::clearSelection); // Make sure we update the Next/Finish button if a PPD is selected connect(ui->ppdsLV->selectionModel(), &QItemSelectionModel::selectionChanged, this, &SelectMakeModel::checkChanged); // When the radio button changes the signal must be emitted connect(ui->ppdFileRB, &QRadioButton::toggled, this, &SelectMakeModel::checkChanged); connect(ui->ppdFilePathUrl, &KUrlRequester::textChanged, this, &SelectMakeModel::checkChanged); qDBusRegisterMetaType(); qDBusRegisterMetaType(); } SelectMakeModel::~SelectMakeModel() { delete ui; } void SelectMakeModel::setDeviceInfo(const QString &deviceId, const QString &make, const QString &makeAndModel, const QString &deviceUri) { qCDebug(LIBKCUPS) << "===================================" << deviceId << makeAndModel << deviceUri; m_gotBestDrivers = false; m_hasRecommended = false; m_make = make; m_makeAndModel = makeAndModel; // Get the best drivers QDBusMessage message; message = QDBusMessage::createMethodCall(QLatin1String("org.fedoraproject.Config.Printing"), QLatin1String("/org/fedoraproject/Config/Printing"), QLatin1String("org.fedoraproject.Config.Printing"), QLatin1String("GetBestDrivers")); message << deviceId; message << makeAndModel; message << deviceUri; QDBusConnection::sessionBus().callWithCallback(message, this, SLOT(getBestDriversFinished(QDBusMessage)), SLOT(getBestDriversFailed(QDBusError,QDBusMessage))); if (!m_ppdRequest) { m_ppdRequest = new KCupsRequest; connect(m_ppdRequest, &KCupsRequest::finished, this, &SelectMakeModel::ppdsLoaded); m_ppdRequest->getPPDS(); } } void SelectMakeModel::setMakeModel(const QString &make, const QString &makeAndModel) { if (!m_ppdRequest) { // We won't try to get the best driver // we should be we need more info and testing // TODO m_gotBestDrivers = true; m_hasRecommended = false; m_make = make; m_makeAndModel = makeAndModel; m_ppdRequest = new KCupsRequest; connect(m_ppdRequest, &KCupsRequest::finished, this, &SelectMakeModel::ppdsLoaded); m_ppdRequest->getPPDS(); } else { // TODO test this setModelData(); } } void SelectMakeModel::ppdsLoaded(KCupsRequest *request) { if (request->hasError()) { qCWarning(LIBKCUPS) << "Failed to get PPDs" << request->errorMsg(); ui->messageWidget->setText(i18n("Failed to get a list of drivers: '%1'", request->errorMsg())); ui->messageWidget->animatedShow(); // Force the changed signal to be sent checkChanged(); } else { m_ppds = request->ppds(); // Try to show the PPDs setModelData(); } m_ppdRequest = nullptr; request->deleteLater(); } void SelectMakeModel::checkChanged() { qCDebug(LIBKCUPS); if (isFileSelected()) { emit changed(!selectedPPDFileName().isNull()); } else { // enable or disable the job action buttons if something is selected emit changed(!selectedPPDName().isNull()); selectFirstMake(); } } QString SelectMakeModel::selectedPPDName() const { QItemSelection ppdSelection = ui->ppdsLV->selectionModel()->selection(); if (!isFileSelected() && !ppdSelection.indexes().isEmpty()) { QModelIndex index = ppdSelection.indexes().first(); return index.data(PPDModel::PPDName).toString(); } return QString(); } QString SelectMakeModel::selectedPPDMakeAndModel() const { QItemSelection ppdSelection = ui->ppdsLV->selectionModel()->selection(); if (!isFileSelected() && !ppdSelection.indexes().isEmpty()) { QModelIndex index = ppdSelection.indexes().first(); return index.data(PPDModel::PPDMakeAndModel).toString(); } return QString(); } QString SelectMakeModel::selectedPPDFileName() const { if (isFileSelected()) { QFileInfo file = ui->ppdFilePathUrl->url().toLocalFile(); qCDebug(LIBKCUPS) << ui->ppdFilePathUrl->url().toLocalFile() << file.isFile() << file.filePath(); if (file.isFile()) { return file.filePath(); } } return QString(); } bool SelectMakeModel::isFileSelected() const { qCDebug(LIBKCUPS) << ui->ppdFileRB->isChecked(); return ui->ppdFileRB->isChecked(); } void SelectMakeModel::getBestDriversFinished(const QDBusMessage &message) { if (message.type() == QDBusMessage::ReplyMessage && message.arguments().size() == 1) { QDBusArgument argument = message.arguments().first().value(); - m_driverMatchList = qdbus_cast(argument); + const DriverMatchList driverMatchList = qdbus_cast(argument); + m_driverMatchList = driverMatchList; m_hasRecommended = !m_driverMatchList.isEmpty(); - foreach (const DriverMatch &driverMatch, m_driverMatchList) { + for (const DriverMatch &driverMatch : driverMatchList) { qCDebug(LIBKCUPS) << driverMatch.ppd << driverMatch.match; } } else { qCWarning(LIBKCUPS) << "Unexpected message" << message; } m_gotBestDrivers = true; setModelData(); } void SelectMakeModel::getBestDriversFailed(const QDBusError &error, const QDBusMessage &message) { qCWarning(LIBKCUPS) << "Failed to get best drivers" << error << message; // Show the PPDs anyway m_gotBestDrivers = true; ui->messageWidget->setText(i18n("Failed to search for a recommended driver: '%1'", error.message())); ui->messageWidget->animatedShow(); setModelData(); } void SelectMakeModel::setModelData() { if (!m_ppds.isEmpty() && m_gotBestDrivers) { m_sourceModel->setPPDs(m_ppds, m_driverMatchList); // Pre-select the first Recommended PPD if (m_hasRecommended) { selectRecommendedPPD(); } else if (!m_ppds.isEmpty() && !m_make.isEmpty()) { selectMakeModelPPD(); } // Force changed signal to be emitted checkChanged(); } } void SelectMakeModel::selectFirstMake() { QItemSelection selection; selection = ui->makeView->selectionModel()->selection(); // Make sure the first make is selected if (selection.indexes().isEmpty() && m_sourceModel->rowCount() > 0) { ui->makeView->selectionModel()->setCurrentIndex(m_sourceModel->index(0, 0), QItemSelectionModel::SelectCurrent); } } void SelectMakeModel::selectMakeModelPPD() { - QList makes = m_sourceModel->findItems(m_make); - foreach (QStandardItem *make, makes) { + const QList makes = m_sourceModel->findItems(m_make); + for (QStandardItem *make : makes) { // Check if the item is in this make for (int i = 0; i < make->rowCount(); i++) { if (make->child(i)->data(PPDModel::PPDMakeAndModel).toString() == m_makeAndModel) { ui->makeView->selectionModel()->setCurrentIndex(make->index(), QItemSelectionModel::SelectCurrent); ui->ppdsLV->selectionModel()->setCurrentIndex(make->child(i)->index(), QItemSelectionModel::SelectCurrent); return; } } } // the exact PPD wasn't found try to select just the make if (!makes.isEmpty()) { ui->makeView->selectionModel()->setCurrentIndex(makes.first()->index(), QItemSelectionModel::SelectCurrent); } } void SelectMakeModel::selectRecommendedPPD() { // Force the first make to be selected selectFirstMake(); QItemSelection ppdSelection = ui->ppdsLV->selectionModel()->selection(); if (ppdSelection.indexes().isEmpty()) { QItemSelection makeSelection = ui->makeView->selectionModel()->selection(); QModelIndex parent = makeSelection.indexes().first(); if (parent.isValid()) { ui->ppdsLV->selectionModel()->setCurrentIndex(m_sourceModel->index(0, 0, parent), QItemSelectionModel::SelectCurrent); } } } diff --git a/printqueue/PrintQueue.cpp b/printqueue/PrintQueue.cpp index b1fac74..e8cd948 100644 --- a/printqueue/PrintQueue.cpp +++ b/printqueue/PrintQueue.cpp @@ -1,122 +1,122 @@ /*************************************************************************** * Copyright (C) 2010-2018 by Daniel Nicoletti * * dantti12@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "PrintQueue.h" #include "PrintQueueUi.h" #include #include #include #include #include PrintQueue::PrintQueue(int &argc, char **argv) : QApplication(argc, argv) { } PrintQueue::~PrintQueue() { } void PrintQueue::showQueues(const QStringList &queues, const QString &cwd) { Q_UNUSED(cwd) if (!queues.isEmpty()) { - foreach (const QString & queue, queues) { + for (const QString &queue : queues) { showQueue(queue); } } else { qDebug() << "called with no args"; // If DBus called the ui list won't be empty QTimer::singleShot(500, this, &PrintQueue::removeQueue); } } void PrintQueue::showQueue(const QString &destName) { qDebug() << Q_FUNC_INFO << destName; if (!m_uis.contains(destName)) { // Reserve this since the CUPS call might take a long time m_uis[destName] = 0; QStringList attr; attr << KCUPS_PRINTER_NAME; attr << KCUPS_PRINTER_TYPE; // Get destinations with these attributes QPointer request = new KCupsRequest; request->getPrinters(attr); request->waitTillFinished(); if (!request) { return; } bool found = false; KCupsPrinter printer; KCupsPrinters printers = request->printers(); for (int i = 0; i < printers.size(); i++) { if (printers.at(i).name() == destName) { printer = printers.at(i); found = true; break; } } request->deleteLater(); if (found) { auto ui = new PrintQueueUi(printer); connect(ui, &PrintQueueUi::finished, this, &PrintQueue::removeQueue); ui->show(); m_uis[printer.name()] = ui; } else { // Remove the reservation m_uis.remove(destName); // if no destination was found and we aren't showing // a queue quit the app if (m_uis.isEmpty()) { emit quit(); } return; } } // Check it it's not reserved if (m_uis.value(destName)) { KWindowSystem::forceActiveWindow(m_uis.value(destName)->winId()); } } void PrintQueue::removeQueue() { auto ui = qobject_cast(sender()); if (ui) { m_uis.remove(m_uis.key(ui)); } // if no destination was found and we aren't showing // a queue quit the app if (m_uis.isEmpty()) { quit(); } } diff --git a/printqueue/PrintQueueUi.cpp b/printqueue/PrintQueueUi.cpp index a703560..60b4ed8 100644 --- a/printqueue/PrintQueueUi.cpp +++ b/printqueue/PrintQueueUi.cpp @@ -1,610 +1,613 @@ /*************************************************************************** * Copyright (C) 2010-2018 by Daniel Nicoletti * * dantti12@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "PrintQueueUi.h" #include "ui_PrintQueueUi.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define PRINTER_ICON_SIZE 92 PrintQueueUi::PrintQueueUi(const KCupsPrinter &printer, QWidget *parent) : QDialog(parent), ui(new Ui::PrintQueueUi), m_destName(printer.name()), m_preparingMenu(false), m_printerPaused(false), m_lastState(0) { ui->setupUi(this); // since setupUi needs to setup on the mainWidget() // we need to manually connect the buttons connect(ui->cancelJobPB, &QPushButton::clicked, this, &PrintQueueUi::cancelJob); connect(ui->holdJobPB, &QPushButton::clicked, this, &PrintQueueUi::holdJob); connect(ui->resumeJobPB, &QPushButton::clicked, this, &PrintQueueUi::resumeJob); connect(ui->reprintPB, &QPushButton::clicked, this, &PrintQueueUi::reprintJob); connect(ui->pausePrinterPB, &QPushButton::clicked, this, &PrintQueueUi::pausePrinter); connect(ui->configurePrinterPB, &QPushButton::clicked, this, &PrintQueueUi::configurePrinter); connect(ui->whichJobsCB, static_cast(&QComboBox::currentIndexChanged), this, &PrintQueueUi::whichJobsIndexChanged); // Needed so we have our dialog size saved setAttribute(Qt::WA_DeleteOnClose); setWindowIcon(printer.icon()); if (printer.info().isEmpty()) { m_title = printer.name(); } else { m_title = printer.name() % QLatin1String(" - ") % printer.info(); } setWindowTitle(m_title); setSizeGripEnabled(true); (void) minimumSizeHint(); //Force the dialog to be laid out now layout()->setContentsMargins(0,0,0,0); m_isClass = printer.isClass(); // setup default options ui->jobsView->setCornerWidget(new QWidget); setupButtons(); // loads the standard key icon m_printerIcon = printer.icon().pixmap(PRINTER_ICON_SIZE, PRINTER_ICON_SIZE); ui->iconL->setPixmap(m_printerIcon); m_pauseIcon = KIconLoader::global()->loadIcon("media-playback-pause", KIconLoader::NoGroup, KIconLoader::SizeMedium, KIconLoader::DefaultState, QStringList(), 0, true); ui->printerStatusMsgL->setText(QString()); // setup the jobs model m_model = new JobModel(this); m_model->setParentWId(winId()); m_model->init(printer.name()); connect(m_model, &JobModel::dataChanged, this, &PrintQueueUi::updateButtons); connect(m_model, &JobModel::dataChanged, this, &PrintQueueUi::update); m_proxyModel = new JobSortFilterModel(this); m_proxyModel->setSourceModel(m_model); m_proxyModel->setDynamicSortFilter(true); ui->jobsView->setModel(m_proxyModel); ui->jobsView->setItemDelegate(new NoSelectionRectDelegate(this)); // sort by status column means the jobs will be sorted by the queue order ui->jobsView->sortByColumn(JobModel::ColStatus, Qt::AscendingOrder); connect(ui->jobsView->selectionModel(), &QItemSelectionModel::selectionChanged, this, &PrintQueueUi::updateButtons); connect(ui->jobsView, &QTreeView::customContextMenuRequested, this, &PrintQueueUi::showContextMenu); ui->jobsView->header()->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->jobsView->header(), &QHeaderView::customContextMenuRequested, this, &PrintQueueUi::showHeaderContextMenu); QHeaderView *header = ui->jobsView->header(); header->setResizeMode(QHeaderView::Interactive); header->setStretchLastSection(false); header->setResizeMode(JobModel::ColStatus, QHeaderView::ResizeToContents); header->setResizeMode(JobModel::ColName, QHeaderView::Stretch); header->setResizeMode(JobModel::ColUser, QHeaderView::ResizeToContents); header->setResizeMode(JobModel::ColCreated, QHeaderView::ResizeToContents); header->setResizeMode(JobModel::ColCompleted, QHeaderView::ResizeToContents); header->setResizeMode(JobModel::ColPages, QHeaderView::ResizeToContents); header->setResizeMode(JobModel::ColProcessed, QHeaderView::ResizeToContents); header->setResizeMode(JobModel::ColSize, QHeaderView::ResizeToContents); header->setResizeMode(JobModel::ColStatusMessage, QHeaderView::ResizeToContents); header->setResizeMode(JobModel::ColPrinter, QHeaderView::ResizeToContents); KConfigGroup printQueue(KSharedConfig::openConfig("print-manager"), "PrintQueue"); if (printQueue.hasKey("ColumnState")) { // restore the header state order header->restoreState(printQueue.readEntry("ColumnState", QByteArray())); } else { // Hide some columns ColPrinter header->hideSection(JobModel::ColPrinter); header->hideSection(JobModel::ColUser); header->hideSection(JobModel::ColCompleted); header->hideSection(JobModel::ColSize); header->hideSection(JobModel::ColFromHost); } // This is emitted when a printer is modified connect(KCupsConnection::global(), &KCupsConnection::printerModified, this, &PrintQueueUi::updatePrinter); // This is emitted when a printer has it's state changed connect(KCupsConnection::global(), &KCupsConnection::printerStateChanged, this, &PrintQueueUi::updatePrinter); // This is emitted when a printer is stopped connect(KCupsConnection::global(), &KCupsConnection::printerStopped, this, &PrintQueueUi::updatePrinter); // This is emitted when a printer is restarted connect(KCupsConnection::global(), &KCupsConnection::printerRestarted, this, &PrintQueueUi::updatePrinter); // This is emitted when a printer is shutdown connect(KCupsConnection::global(), &KCupsConnection::printerShutdown, this, &PrintQueueUi::updatePrinter); // This is emitted when a printer is removed connect(KCupsConnection::global(), &KCupsConnection::printerDeleted, this, &PrintQueueUi::updatePrinter); // This is emitted when a printer/queue is changed // Deprecated stuff that works better than the above connect(KCupsConnection::global(), &KCupsConnection::rhPrinterAdded, this, &PrintQueueUi::updatePrinterByName); connect(KCupsConnection::global(), &KCupsConnection::rhPrinterRemoved, this, &PrintQueueUi::updatePrinterByName); connect(KCupsConnection::global(), &KCupsConnection::rhQueueChanged, this, &PrintQueueUi::updatePrinterByName); updatePrinterByName(m_destName); // Restore the dialog size KConfigGroup configGroup(KSharedConfig::openConfig("print-manager"), "PrintQueue"); KWindowConfig::restoreWindowSize(windowHandle(), configGroup); } PrintQueueUi::~PrintQueueUi() { KConfigGroup configGroup(KSharedConfig::openConfig("print-manager"), "PrintQueue"); // save the header state order configGroup.writeEntry("ColumnState", ui->jobsView->header()->saveState()); // Save the dialog size KWindowConfig::saveWindowSize(windowHandle(), configGroup); delete ui; } int PrintQueueUi::columnCount(const QModelIndex &parent) const { if (!parent.isValid()) { return JobModel::LastColumn; } return 0; } void PrintQueueUi::setState(int state, const QString &message) { qDebug() << state << message; if (state != m_lastState || ui->printerStatusMsgL->text() != message) { // save the last state so the ui doesn't need to keep updating if (ui->printerStatusMsgL->text() != message) { ui->printerStatusMsgL->setText(message); } m_lastState = state; QPixmap icon(m_printerIcon); m_printerPaused = false; switch (state) { case KCupsPrinter::Idle: ui->statusL->setText(i18n("Printer ready")); ui->pausePrinterPB->setText(i18n("Pause Printer")); ui->pausePrinterPB->setIcon(QIcon::fromTheme("media-playback-pause")); break; case KCupsPrinter::Printing: if (!m_title.isNull()) { QString jobTitle = m_model->processingJob(); if (jobTitle.isEmpty()) { ui->statusL->setText(i18n("Printing...")); } else { ui->statusL->setText(i18n("Printing '%1'", jobTitle)); } ui->pausePrinterPB->setText(i18n("Pause Printer")); ui->pausePrinterPB->setIcon(QIcon::fromTheme("media-playback-pause")); } break; case KCupsPrinter::Stopped: m_printerPaused = true; ui->statusL->setText(i18n("Printer paused")); ui->pausePrinterPB->setText(i18n("Resume Printer")); ui->pausePrinterPB->setIcon(QIcon::fromTheme("media-playback-start")); // create a paiter to paint the action icon over the key icon { QPainter painter(&icon); // the emblem icon to size 32 int overlaySize = KIconLoader::SizeMedium; QPoint startPoint; // bottom right corner startPoint = QPoint(PRINTER_ICON_SIZE - overlaySize - 2, PRINTER_ICON_SIZE - overlaySize - 2); painter.drawPixmap(startPoint, m_pauseIcon); } break; default : ui->statusL->setText(i18n("Printer state unknown")); break; } // set the printer icon setWindowIcon(icon); } } void PrintQueueUi::showContextMenu(const QPoint &point) { // check if the click was actually over a job if (!ui->jobsView->indexAt(point).isValid() || m_preparingMenu) { return; } m_preparingMenu = true; bool moveTo = false; QItemSelection selection; // we need to map the selection to source to get the real indexes selection = m_proxyModel->mapSelectionToSource(ui->jobsView->selectionModel()->selection()); // if the selection is empty the user clicked on an empty space if (!selection.indexes().isEmpty()) { - foreach (const QModelIndex &index, selection.indexes()) { + const QModelIndexList indexes = selection.indexes(); + for (const QModelIndex &index : indexes) { if (index.column() == 0 && index.flags() & Qt::ItemIsDragEnabled) { // Found a move to item moveTo = true; break; } } // if we can move a job create the menu if (moveTo) { // context menu auto menu = new QMenu(this); // move to menu auto moveToMenu = new QMenu(i18n("Move to"), this); // get printers we can move to QPointer request = new KCupsRequest; QStringList attr; attr << KCUPS_PRINTER_NAME; attr << KCUPS_PRINTER_INFO; request->getPrinters(attr); request->waitTillFinished(); if (!request) { return; } - KCupsPrinters printers = request->printers(); + const KCupsPrinters printers = request->printers(); request->deleteLater(); - foreach (const KCupsPrinter &printer, printers) { + for (const KCupsPrinter &printer : printers) { // If there is a printer and it's not the current one add it // as a new destination if (printer.name() != m_destName) { QAction *action = moveToMenu->addAction(printer.info()); action->setData(printer.name()); } } if (!moveToMenu->isEmpty()) { menu->addMenu(moveToMenu); // show the menu on the right point QAction *action = menu->exec(ui->jobsView->mapToGlobal(point)); if (action) { // move the job modifyJob(JobModel::Move, action->data().toString()); } } } } m_preparingMenu = false; } void PrintQueueUi::showHeaderContextMenu(const QPoint &point) { // Displays a menu containing the header name, and // a check box to indicate if it's being shown auto menu = new QMenu(this); for (int i = 0; i < m_proxyModel->columnCount(); i++) { QAction *action; QString name; name = m_proxyModel->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString(); action = menu->addAction(name); action->setCheckable(true); action->setChecked(!ui->jobsView->header()->isSectionHidden(i)); action->setData(i); } QAction *action = menu->exec(ui->jobsView->header()->mapToGlobal(point)); if (action) { int section = action->data().toInt(); if (action->isChecked()) { ui->jobsView->header()->showSection(section); } else { ui->jobsView->header()->hideSection(section); } } } void PrintQueueUi::updatePrinterByName(const QString &printer) { qDebug() << printer << m_destName; if (printer != m_destName) { // It was another printer that changed return; } QStringList attr; attr << KCUPS_PRINTER_INFO; attr << KCUPS_PRINTER_TYPE; attr << KCUPS_PRINTER_STATE; attr << KCUPS_PRINTER_STATE_MESSAGE; auto request = new KCupsRequest; connect(request, &KCupsRequest::finished, this, &PrintQueueUi::getAttributesFinished); request->getPrinterAttributes(printer, m_isClass, attr); } void PrintQueueUi::updatePrinter(const QString &text, const QString &printerUri, const QString &printerName, uint printerState, const QString &printerStateReasons, bool printerIsAcceptingJobs) { // REALLY? all these parameters just to say foo was added?? Q_UNUSED(text) Q_UNUSED(printerUri) Q_UNUSED(printerState) Q_UNUSED(printerStateReasons) Q_UNUSED(printerIsAcceptingJobs) qDebug() << printerName << printerStateReasons; updatePrinterByName(printerName); } void PrintQueueUi::getAttributesFinished(KCupsRequest *request) { qDebug() << request->hasError() << request->printers().isEmpty(); if (request->hasError() || request->printers().isEmpty()) { // if cups stops we disable our queue setEnabled(false); request->deleteLater(); // DO not delete before using as the request is in another thread return; } else if (isEnabled() == false) { // if cups starts again we enable our queue setEnabled(true); } KCupsPrinter printer = request->printers().first(); // get printer-info if (printer.info().isEmpty()) { m_title = printer.name(); } else { m_title = printer.name() % QLatin1String(" - ") % printer.info(); } // get printer-state setState(printer.state(), printer.stateMsg()); // store if the printer is a class m_isClass = printer.isClass(); request->deleteLater(); update(); } void PrintQueueUi::update() { // Set window title if (m_model->rowCount()) { if (m_destName.isNull()) { setWindowTitle(i18np("All Printers (%1 Job)", "All Printers (%1 Jobs)", m_model->rowCount())); } else { setWindowTitle(i18np("%2 (%1 Job)", "%2 (%1 Jobs)", m_model->rowCount(), m_title)); } } else { setWindowTitle(m_destName.isNull() ? i18n("All Printers") : m_title); } } void PrintQueueUi::updateButtons() { bool cancel, hold, release, reprint; // Set all options to false cancel = hold = release = reprint = false; QItemSelection selection; // we need to map the selection to source to get the real indexes selection = m_proxyModel->mapSelectionToSource(ui->jobsView->selectionModel()->selection()); // enable or disable the job action buttons if something is selected if (!selection.indexes().isEmpty()) { - foreach (const QModelIndex &index, selection.indexes()) { + const QModelIndexList indexes = selection.indexes(); + for (const QModelIndex &index : indexes) { if (index.column() == 0) { switch (static_cast(index.data(JobModel::RoleJobState).toInt())) { case IPP_JOB_CANCELED : case IPP_JOB_COMPLETED : case IPP_JOB_ABORTED : break; case IPP_JOB_HELD : case IPP_JOB_STOPPED : release = true; cancel = true; break; default: cancel = hold = true; break; } if (index.data(JobModel::RoleJobRestartEnabled).toBool()) { reprint = true; } } } } ui->cancelJobPB->setEnabled(cancel); ui->holdJobPB->setEnabled(hold); ui->resumeJobPB->setEnabled(release); ui->reprintPB->setEnabled(reprint); } void PrintQueueUi::modifyJob(int action, const QString &destName) { // get all selected indexes QItemSelection selection; // we need to map the selection to source to get the real indexes selection = m_proxyModel->mapSelectionToSource(ui->jobsView->selectionModel()->selection()); - foreach (const QModelIndex &index, selection.indexes()) { + const QModelIndexList indexes = selection.indexes(); + for (const QModelIndex &index : indexes) { if (index.column() == 0) { KCupsRequest *request; request = m_model->modifyJob(index.row(), static_cast(action), destName); if (!request) { // probably the job already has this state // or this is an unknown action continue; } request->waitTillFinished(); if (request->hasError()) { QString msg, jobName; jobName = m_model->item(index.row(), static_cast(JobModel::ColName))->text(); switch (action) { case JobModel::Cancel: msg = i18n("Failed to cancel '%1'", jobName); break; case JobModel::Hold: msg = i18n("Failed to hold '%1'", jobName); break; case JobModel::Release: msg = i18n("Failed to release '%1'", jobName); break; case JobModel::Reprint: msg = i18n("Failed to reprint '%1'", jobName); break; case JobModel::Move: msg = i18n("Failed to move '%1' to '%2'", jobName, destName); break; } KMessageBox::detailedSorry(this, msg, request->errorMsg(), i18n("Failed")); } request->deleteLater(); } } } void PrintQueueUi::pausePrinter() { // STOP and RESUME printer QPointer request = new KCupsRequest; if (m_printerPaused) { qDebug() << m_destName << "m_printerPaused"; request->resumePrinter(m_destName); } else { qDebug() << m_destName << "NOT m_printerPaused"; request->pausePrinter(m_destName); } request->waitTillFinished(); if (request) { request->deleteLater(); } } void PrintQueueUi::configurePrinter() { QProcess::startDetached("configure-printer", {m_destName}); } void PrintQueueUi::cancelJob() { // CANCEL a job modifyJob(JobModel::Cancel); } void PrintQueueUi::holdJob() { // HOLD a job modifyJob(JobModel::Hold); } void PrintQueueUi::resumeJob() { // RESUME a job modifyJob(JobModel::Release); } void PrintQueueUi::reprintJob() { modifyJob(JobModel::Reprint); } void PrintQueueUi::whichJobsIndexChanged(int index) { switch (index) { case 1: m_model->setWhichJobs(JobModel::WhichCompleted); break; case 2: m_model->setWhichJobs(JobModel::WhichAll); break; default: m_model->setWhichJobs(JobModel::WhichActive); break; } } void PrintQueueUi::setupButtons() { // setup jobs buttons // cancel action ui->cancelJobPB->setIcon(QIcon::fromTheme("dialog-cancel")); // hold job action ui->holdJobPB->setIcon(QIcon::fromTheme("document-open-recent")); // resume job action // TODO we need a new icon ui->resumeJobPB->setIcon(QIcon::fromTheme("media-playback-start")); ui->reprintPB->setIcon(QIcon::fromTheme("view-refresh")); ui->whichJobsCB->setItemIcon(0, QIcon::fromTheme("view-filter")); ui->whichJobsCB->setItemIcon(1, QIcon::fromTheme("view-filter")); ui->whichJobsCB->setItemIcon(2, QIcon::fromTheme("view-filter")); // stop start printer ui->pausePrinterPB->setIcon(QIcon::fromTheme("media-playback-pause")); // configure printer ui->configurePrinterPB->setIcon(QIcon::fromTheme("configure")); } void PrintQueueUi::closeEvent(QCloseEvent *event) { // emits finished signal to be removed the cache emit finished(); QWidget::closeEvent(event); }