diff --git a/libkcups/JobModel.cpp b/libkcups/JobModel.cpp index 2807fd7..9a460c2 100644 --- a/libkcups/JobModel.cpp +++ b/libkcups/JobModel.cpp @@ -1,630 +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 JobModel::JobModel(QObject *parent) : QStandardItemModel(parent) { 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 = QStringList{ - KCUPS_JOB_ID, - KCUPS_JOB_NAME, - KCUPS_JOB_K_OCTETS, - KCUPS_JOB_K_OCTETS_PROCESSED, - KCUPS_JOB_STATE, - KCUPS_TIME_AT_COMPLETED, - KCUPS_TIME_AT_CREATION, - KCUPS_TIME_AT_PROCESSING, - KCUPS_JOB_PRINTER_URI, - KCUPS_JOB_ORIGINATING_USER_NAME, - KCUPS_JOB_ORIGINATING_HOST_NAME, - KCUPS_JOB_MEDIA_PROGRESS, - KCUPS_JOB_MEDIA_SHEETS, - KCUPS_JOB_MEDIA_SHEETS_COMPLETED, - KCUPS_JOB_PRINTER_STATE_MESSAGE, - KCUPS_JOB_PRESERVED - }; - m_roles = QStandardItemModel::roleNames(); m_roles[RoleJobId] = "jobId"; m_roles[RoleJobState] = "jobState"; m_roles[RoleJobName] = "jobName"; m_roles[RoleJobPages] = "jobPages"; m_roles[RoleJobSize] = "jobSize"; m_roles[RoleJobOwner] = "jobOwner"; m_roles[RoleJobCreatedAt] = "jobCreatedAt"; m_roles[RoleJobIconName] = "jobIconName"; m_roles[RoleJobCancelEnabled] = "jobCancelEnabled"; m_roles[RoleJobHoldEnabled] = "jobHoldEnabled"; m_roles[RoleJobReleaseEnabled] = "jobReleaseEnabled"; m_roles[RoleJobRestartEnabled] = "jobRestartEnabled"; m_roles[RoleJobPrinter] = "jobPrinter"; m_roles[RoleJobOriginatingHostName] = "jobFrom"; // 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); + const static QStringList attrs({ + KCUPS_JOB_ID, + KCUPS_JOB_NAME, + KCUPS_JOB_K_OCTETS, + KCUPS_JOB_K_OCTETS_PROCESSED, + KCUPS_JOB_STATE, + KCUPS_TIME_AT_COMPLETED, + KCUPS_TIME_AT_CREATION, + KCUPS_TIME_AT_PROCESSING, + KCUPS_JOB_PRINTER_URI, + KCUPS_JOB_ORIGINATING_USER_NAME, + KCUPS_JOB_ORIGINATING_HOST_NAME, + KCUPS_JOB_MEDIA_PROGRESS, + KCUPS_JOB_MEDIA_SHEETS, + KCUPS_JOB_MEDIA_SHEETS_COMPLETED, + KCUPS_JOB_PRINTER_STATE_MESSAGE, + KCUPS_JOB_PRESERVED + }); + m_jobRequest->getJobs(m_destName, false, m_whichjobs, attrs); 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 { const 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 { QStringLiteral("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); 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(QLatin1String("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(QLatin1String("application/x-cupsjobs"))) { return false; } QByteArray encodedData = data->data(QLatin1String("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; } QHash JobModel::roleNames() const { return m_roles; } 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 QLatin1String("-"); 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 QLatin1String("-"); } 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; } #include "moc_JobModel.cpp" diff --git a/libkcups/JobModel.h b/libkcups/JobModel.h index 467ce79..1984a4a 100644 --- a/libkcups/JobModel.h +++ b/libkcups/JobModel.h @@ -1,151 +1,150 @@ /*************************************************************************** * Copyright (C) 2010 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. * ***************************************************************************/ #ifndef JOB_MODEL_H #define JOB_MODEL_H #include #include class KCupsJob; class KCupsRequest; class Q_DECL_EXPORT JobModel : public QStandardItemModel { Q_OBJECT Q_ENUMS(JobAction) Q_ENUMS(Role) Q_ENUMS(WhichJobs) public: enum Role { RoleJobId = Qt::UserRole + 2, RoleJobState, RoleJobName, RoleJobPages, RoleJobSize, RoleJobOwner, RoleJobCreatedAt, RoleJobIconName, RoleJobCancelEnabled, RoleJobHoldEnabled, RoleJobReleaseEnabled, RoleJobRestartEnabled, RoleJobPrinter, RoleJobOriginatingHostName }; enum JobAction { Cancel, Hold, Release, Move, Reprint }; enum WhichJobs { WhichAll, WhichActive, WhichCompleted }; enum Columns { ColStatus = 0, ColName, ColUser, ColCreated, ColCompleted, ColPages, ColProcessed, ColSize, ColStatusMessage, ColPrinter, ColFromHost, LastColumn }; explicit JobModel(QObject *parent = 0); void setParentWId(WId parentId); Q_INVOKABLE void init(const QString &destName = QString()); Q_INVOKABLE void hold(const QString &printerName, int jobId); Q_INVOKABLE void release(const QString &printerName, int jobId); Q_INVOKABLE void cancel(const QString &printerName, int jobId); Q_INVOKABLE void move(const QString &printerName, int jobId, const QString &toPrinterName); QString processingJob() const; Qt::ItemFlags flags(const QModelIndex &index) const Q_DECL_OVERRIDE; QStringList mimeTypes() const Q_DECL_OVERRIDE; Qt::DropActions supportedDropActions() const Q_DECL_OVERRIDE; QMimeData* mimeData(const QModelIndexList &indexes) const Q_DECL_OVERRIDE; bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) Q_DECL_OVERRIDE; virtual QHash roleNames() const override; Q_INVOKABLE void setWhichJobs(WhichJobs whichjobs); KCupsRequest* modifyJob(int row, JobAction action, const QString &newDestName = QString(), const QModelIndex &parent = QModelIndex()); private slots: void getJobs(); void getJobFinished(KCupsRequest *request); void 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); void 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); private: int jobRow(int jobId); void insertJob(int pos, const KCupsJob &job); void updateJob(int pos, const KCupsJob &job); QString jobStatus(ipp_jstate_e job_state); void clear(); KCupsRequest *m_jobRequest = nullptr; QString m_destName; QString m_processingJob; QHash m_roles; int m_whichjobs = CUPS_WHICHJOBS_ACTIVE; WId m_parentId = 0; - QStringList m_jobAttributes; }; #endif // JOB_MODEL_H diff --git a/libkcups/PrinterModel.cpp b/libkcups/PrinterModel.cpp index abca8e6..d7ed42d 100644 --- a/libkcups/PrinterModel.cpp +++ b/libkcups/PrinterModel.cpp @@ -1,527 +1,526 @@ /*************************************************************************** * 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 +const static QStringList attrs(QStringList{ + KCUPS_PRINTER_NAME, + KCUPS_PRINTER_STATE, + KCUPS_PRINTER_STATE_MESSAGE, + KCUPS_PRINTER_IS_SHARED, + KCUPS_PRINTER_IS_ACCEPTING_JOBS, + KCUPS_PRINTER_TYPE, + KCUPS_PRINTER_LOCATION, + KCUPS_PRINTER_INFO, + KCUPS_PRINTER_MAKE_AND_MODEL, + KCUPS_PRINTER_COMMANDS, + KCUPS_MARKER_CHANGE_TIME, + KCUPS_MARKER_COLORS, + KCUPS_MARKER_LEVELS, + KCUPS_MARKER_NAMES, + KCUPS_MARKER_TYPES + }); + PrinterModel::PrinterModel(QObject *parent) : - QStandardItemModel(parent), - m_unavailable(true) + QStandardItemModel(parent) { - m_attributes = QStringList{ - KCUPS_PRINTER_NAME, - KCUPS_PRINTER_STATE, - KCUPS_PRINTER_STATE_MESSAGE, - KCUPS_PRINTER_IS_SHARED, - KCUPS_PRINTER_IS_ACCEPTING_JOBS, - KCUPS_PRINTER_TYPE, - KCUPS_PRINTER_LOCATION, - KCUPS_PRINTER_INFO, - KCUPS_PRINTER_MAKE_AND_MODEL, - KCUPS_PRINTER_COMMANDS, - KCUPS_MARKER_CHANGE_TIME, - KCUPS_MARKER_COLORS, - KCUPS_MARKER_LEVELS, - KCUPS_MARKER_NAMES, - KCUPS_MARKER_TYPES - }; - m_roles = QStandardItemModel::roleNames(); m_roles[DestStatus] = "stateMessage"; m_roles[DestName] = "printerName"; m_roles[DestState] = "printerState"; m_roles[DestIsDefault] = "isDefault"; m_roles[DestIsShared] = "isShared"; m_roles[DestIsAcceptingJobs] = "isAcceptingJobs"; m_roles[DestIsPaused] = "isPaused"; m_roles[DestIsClass] = "isClass"; m_roles[DestLocation] = "location"; m_roles[DestDescription] = "info"; m_roles[DestKind] = "kind"; m_roles[DestType] = "type"; m_roles[DestCommands] = "commands"; m_roles[DestMarkerChangeTime] = "markerChangeTime"; m_roles[DestMarkers] = "markers"; m_roles[DestIconName] = "iconName"; m_roles[DestRemote] = "remote"; // 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); } const 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; } QHash PrinterModel::roleNames() const { return m_roles; } 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); + request->getPrinters(attrs); } 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); const QVariantHash markers{ {KCUPS_MARKER_CHANGE_TIME, printer.markerChangeTime()}, {KCUPS_MARKER_COLORS, printer.argument(KCUPS_MARKER_COLORS)}, {KCUPS_MARKER_LEVELS, printer.argument(KCUPS_MARKER_LEVELS)}, {KCUPS_MARKER_NAMES, printer.argument(KCUPS_MARKER_NAMES)}, {KCUPS_MARKER_TYPES, printer.argument(KCUPS_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); + request->getPrinterAttributes(printerName, false, attrs); } 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()) { 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(); } #include "moc_PrinterModel.cpp" diff --git a/libkcups/PrinterModel.h b/libkcups/PrinterModel.h index d222bb1..be05419 100644 --- a/libkcups/PrinterModel.h +++ b/libkcups/PrinterModel.h @@ -1,121 +1,120 @@ /*************************************************************************** * 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. * ***************************************************************************/ #ifndef PRINTER_MODEL_H #define PRINTER_MODEL_H #include #include #include class KCupsRequest; class Q_DECL_EXPORT PrinterModel : public QStandardItemModel { Q_OBJECT Q_ENUMS(JobAction) Q_ENUMS(Role) Q_PROPERTY(int count READ count NOTIFY countChanged) Q_PROPERTY(bool serverUnavailable READ serverUnavailable NOTIFY serverUnavailableChanged) public: enum Role { DestStatus = Qt::UserRole, DestState, DestName, DestIsDefault, DestIsShared, DestIsAcceptingJobs, DestIsPaused, DestIsClass, DestLocation, DestDescription, DestKind, DestType, DestCommands, DestMarkerChangeTime, DestMarkers, DestIconName, DestRemote }; enum JobAction { Cancel, Hold, Release, Move }; explicit PrinterModel(QObject *parent = 0); Qt::ItemFlags flags(const QModelIndex &index) const Q_DECL_OVERRIDE; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE; int count() const; bool serverUnavailable() const; virtual QHash roleNames() const override; Q_INVOKABLE void pausePrinter(const QString &printerName); Q_INVOKABLE void resumePrinter(const QString &printerName); Q_INVOKABLE void rejectJobs(const QString &printerName); Q_INVOKABLE void acceptJobs(const QString &printerName); public slots: void update(); void getDestsFinished(KCupsRequest *request); void slotCountChanged(); signals: void countChanged(int count); void serverUnavailableChanged(bool unavailable); void error(int lastError, const QString &errorTitle, const QString &errorMsg); private slots: void insertUpdatePrinterName(const QString &printerName); void insertUpdatePrinter(const QString &text, const QString &printerUri, const QString &printerName, uint printerState, const QString &printerStateReasons, bool printerIsAcceptingJobs); void insertUpdatePrinterFinished(KCupsRequest *request); void printerRemovedName(const QString &printerName); void printerRemoved(const QString &text, const QString &printerUri, const QString &printerName, uint printerState, const QString &printerStateReasons, bool printerIsAcceptingJobs); void printerStateChanged(const QString &text, const QString &printerUri, const QString &printerName, uint printerState, const QString &printerStateReasons, bool printerIsAcceptingJobs); void printerStopped(const QString &text, const QString &printerUri, const QString &printerName, uint printerState, const QString &printerStateReasons, bool printerIsAcceptingJobs); void printerRestarted(const QString &text, const QString &printerUri, const QString &printerName, uint printerState, const QString &printerStateReasons, bool printerIsAcceptingJobs); void printerShutdown(const QString &text, const QString &printerUri, const QString &printerName, uint printerState, const QString &printerStateReasons, bool printerIsAcceptingJobs); void printerModified(const QString &text, const QString &printerUri, const QString &printerName, uint printerState, const QString &printerStateReasons, bool printerIsAcceptingJobs); void serverChanged(const QString &text); private: WId m_parentId; - QStringList m_attributes; QHash m_roles; - bool m_unavailable; + bool m_unavailable = true; int destRow(const QString &destName); void insertDest(int pos, const KCupsPrinter &printer); void updateDest(QStandardItem *item, const KCupsPrinter &printer); QString destStatus(KCupsPrinter::Status state, const QString &message, bool isAcceptingJobs) const; void clear(); }; #endif // PRINTER_MODEL_H