File: SessionTask.cpp

package info (click to toggle)
apper 1.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 9,868 kB
  • sloc: cpp: 14,381; xml: 941; makefile: 15; sh: 4
file content (665 lines) | stat: -rw-r--r-- 21,342 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
/***************************************************************************
 *   Copyright (C) 2009-2011 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 "SessionTask.h"
#include "ui_SessionTask.h"

#include "IntroDialog.h"
#include "InfoWidget.h"
#include "ReviewChanges.h"
#include "ApplicationLauncher.h"

#include <PkStrings.h>
#include <PackageModel.h>
#include <PkTransactionWidget.h>

#include <limits.h>
#include <QtDBus/QDBusConnection>
#include <QTimer>
#include <QStringList>
#include <QFile>
#include <QSignalMapper>
#include <QStringBuilder>
#include <QDialogButtonBox>

//#include <KWindowSystem>
#include <KLocalizedString>
//#include <KGlobalSettings>
#include <QPushButton>
//#include <KGlobal>

#include <QLoggingCategory>

#include <Daemon>

Q_DECLARE_LOGGING_CATEGORY(APPER_SESSION)

using namespace PackageKit;

SessionTask::SessionTask(uint xid, const QString &interaction, const QDBusMessage &message, QWidget *parent) :
    QDialog(parent),
    m_xid(xid),
    m_message(message),
    ui(new Ui::SessionTask)
{
    ui->setupUi(this);
    setAttribute(Qt::WA_DeleteOnClose);

    m_model = new PackageModel(this);

//    connect(KGlobalSettings::self(), SIGNAL(kdisplayPaletteChanged()),
//            this, SLOT(updatePallete()));
    updatePallete();

    setWindowIcon(QIcon::fromTheme(QLatin1String("system-software-install")));
    QPushButton *okButton = ui->buttonBox->button(QDialogButtonBox::Ok);
    okButton->setText(i18n("Continue"));
    okButton->setIcon(QIcon::fromTheme(QLatin1String("go-next")));
    enableButtonOk(false);
    connect(okButton, &QPushButton::clicked, this, &SessionTask::slotContinueClicked);

    QPushButton *cancelButton = ui->buttonBox->button(QDialogButtonBox::Cancel);
    connect(cancelButton, &QPushButton::clicked, this, &SessionTask::slotCancelClicked);



    Daemon::global()->setHints(QLatin1String("locale=") + QLocale::system().name() + QLatin1String(".UTF-8"));

    // Defaults to always
    m_interactions = ConfirmSearch
                   | ConfirmDeps
                   | ConfirmInstall
                   | Progress
                   | Finished
                   | Warning;
    m_timeout = 0;
    parseInteraction(interaction);

    QString cmdline;
    uint pid;
    // TODO as we are running on the session it might
    // be useless to check the PID on the system
    if ((pid = getPidSession()) != UINT_MAX) {
        cmdline = getCmdLine(pid);
    } else if ((pid = getPidSystem()) != UINT_MAX) {
        cmdline = getCmdLine(pid);
    }

    if (!cmdline.isNull()) {
        setExec(cmdline);
    }

    setMinimumSize(QSize(430,280));
//    KConfig config("apper");
//    KConfigGroup configGroup(&config, "SessionInstaller");
//    restoreDialogSize(configGroup);
}

SessionTask::~SessionTask()
{
//    KConfig config("apper");
//    KConfigGroup configGroup(&config, "SessionInstaller");
//    saveDialogSize(configGroup);

    delete ui;
}

void SessionTask::addPackage(Transaction::Info info, const QString &packageID, const QString &summary)
{
    m_model->addSelectedPackage(info, packageID, summary);
}

void SessionTask::searchFinished(PkTransaction::ExitStatus status)
{
    if (m_pkTransaction) {
        // Disconnect so it can be connected to commitFinished latter
        disconnect(m_pkTransaction->transaction(), &PkTransaction::finished, this, &SessionTask::searchFinished);
    }

    if (status == PkTransaction::Success) {
        m_model->finished();
        if (m_model->rowCount() == 0) {
            notFound();
            showCloseButton();
        } else {
            searchSuccess();
        }
    } else if (status == PkTransaction::Cancelled) {
        cancelClicked();
    } else {
        searchFailed();
        showCloseButton();
    }
}

void SessionTask::commitFinished(PkTransaction::ExitStatus status)
{
    if (m_pkTransaction) {
        // Disconnect so it can be connected to something else latter
        disconnect(m_pkTransaction->transaction(), &PkTransaction::finished, this, &SessionTask::searchFinished);
    }

    if (status == PkTransaction::Success) {
        if (!m_removePackages.isEmpty()) {
            removePackages();
        } else {
            commitSuccess();
            showCloseButton();
        }
    } else if (status == PkTransaction::Cancelled) {
        cancelClicked();
    } else {
        commitFailed();
        showCloseButton();
    }
}

void SessionTask::updatePallete()
{
    QPalette pal;
//    pal.setColor(QPalette::Window, KGlobalSettings::activeTitleColor());
//    pal.setColor(QPalette::WindowText, KGlobalSettings::activeTextColor());
    ui->backgroundFrame->setPalette(pal);
}

void SessionTask::setDialog(QDialog *dialog)
{
    // Store the current values
    QWidget *widget = ui->stackedWidget->currentWidget();

    if (qobject_cast<ApplicationLauncher*>(dialog)) {
        // TODO if there is a removal after instalation
        // this will break it, but we don't have
        // this case yet...
        commitSuccess(dialog);
    } else {
        // Set the new ones
        setMainWidget(dialog);
//        setTitle(dialog->windowTitle()); // must come after
        connect(this, &SessionTask::continueClicked, dialog, &QDialog::accept);
//        connect(this, &SessionTask::continueClicked, dia, &QDialog::accept);
//        connect(this, SIGNAL(okClicked()),
//                dialog->mainWidget(), SLOT(deleteLater()));
//        connect(this, SIGNAL(okClicked()),
//                dialog, SLOT(deleteLater()));

        // Make sure we see the last widget and title
        auto mapper = new QSignalMapper(this);
        mapper->setMapping(this, widget);
        connect(this, &SessionTask::continueClicked, mapper, QOverload<>::of(&QSignalMapper::map));
        connect(mapper, QOverload<QWidget*>::of(&QSignalMapper::mapped), this, &SessionTask::setMainWidget);
        enableButtonOk(true);
    }
}

void SessionTask::setMainWidget(QWidget *widget)
{
    if (widget != mainWidget()) {
        ui->stackedWidget->addWidget(widget);
        ui->stackedWidget->setCurrentWidget(widget);
        setTitle(widget->windowTitle());
    }
}

QWidget* SessionTask::mainWidget()
{
    return ui->stackedWidget->currentWidget();
}

void SessionTask::setInfo(const QString &title, const QString &text, const QString &details)
{
    auto info = new InfoWidget(this);
    info->setWindowTitle(title);
    info->setDescription(text);
    info->setDetails(details);
    setMainWidget(info);
    showCloseButton();

    if (qobject_cast<PkTransaction*>(sender())) {
        // if we have a sender this method was caller by PkTransaction
        // be carefull because QSignalMapper from KDialog also calls this method
        sender()->disconnect();
        sendErrorFinished(Failed, text);
    }
}

void SessionTask::setError(const QString &title, const QString &text, const QString &details)
{
    auto info = new InfoWidget(this);
    info->setWindowTitle(title);
    info->setDescription(text);
    info->setIcon(QIcon::fromTheme(QLatin1String("dialog-error")));
    info->setDetails(details);
    setMainWidget(info);
    showCloseButton();

    if (qobject_cast<PkTransaction*>(sender())) {
        // if we have a sender this method was caller by PkTransaction
        // be carefull because QSignalMapper from KDialog also calls this method
        sender()->disconnect();
        sendErrorFinished(Failed, text);
    }
}

void SessionTask::setFinish(const QString &title, const QString &text, QWidget *widget)
{
    auto info = new InfoWidget(this);
    info->setWindowTitle(title);
    info->setDescription(text);
    info->setIcon(QIcon::fromTheme(QLatin1String("dialog-ok-apply")));
    info->addWidget(widget);
    setMainWidget(info);
    showCloseButton();
}

void SessionTask::setTitle(const QString &title)
{
    ui->titleL->setText(title);
}

void SessionTask::setExec(const QString &exec)
{
    if (pathIsTrusted(exec)) {
        // Get from X11 the window title
//        KWindowInfo info = KWindowSystem::windowInfo(m_xid, NET::WMVisibleName);
//        parentTitle = info.visibleName();
    } else {
        parentTitle = exec;
    }
}

bool SessionTask::pathIsTrusted(const QString &exec)
{
    // special case the plugin helper -- it's trusted
    return exec == QLatin1String("/usr/libexec/gst-install-plugins-helper") ||
           exec == QLatin1String("/usr/libexec/pk-gstreamer-install") ||
           exec == QLatin1String("/usr/bin/gstreamer-codec-install") ||
           exec == QLatin1String("/usr/lib/packagekit/pk-gstreamer-install") ||
           exec == QLatin1String("/usr/bin/plasma-desktop") ||
           exec == QLatin1String("/usr/bin/apper");
}

QString SessionTask::getCmdLine(uint pid)
{
    QFile file(QString(QLatin1String("/proc/%1/cmdline")).arg(pid));
    QString line;
    if (file.open(QFile::ReadOnly)) {
        char buf[1024];
        qint64 lineLength = file.readLine(buf, sizeof(buf));
        if (lineLength != -1) {
            // the line is available in buf
            line = QString::fromLocal8Bit(buf);
            if (!line.contains(QLatin1String("(deleted)"))) {
                return line;
            }
        }
    }
    return QString();
}

uint SessionTask::getPidSystem()
{
    QDBusMessage msg;
    msg = QDBusMessage::createMethodCall(QLatin1String("org.freedesktop.DBus"),
                                         QLatin1String("/org/freedesktop/DBus/Bus"),
                                         QLatin1String("org.freedesktop.DBus"),
                                         QLatin1String("GetConnectionUnixProcessID"));
    msg << m_message.service();
    QDBusMessage reply = QDBusConnection::systemBus().call(msg);
    if (reply.type() != QDBusMessage::ReplyMessage) {
        qCWarning(APPER_SESSION) << "Message did not receive a reply";
    }

    if (reply.arguments().size() == 1) {
        return reply.arguments().at(0).toUInt();
    }

    return UINT_MAX;
}

uint SessionTask::getPidSession()
{
    QDBusMessage msg;
    msg = QDBusMessage::createMethodCall(QLatin1String("org.freedesktop.DBus"),
                                         QLatin1String("/org/freedesktop/DBus/Bus"),
                                         QLatin1String("org.freedesktop.DBus"),
                                         QLatin1String("GetConnectionUnixProcessID"));
    msg << m_message.service();
    QDBusMessage reply = QDBusConnection::sessionBus().call(msg);
    if (reply.type() != QDBusMessage::ReplyMessage) {
        qCWarning(APPER_SESSION) << "Message did not receive a reply";
    }

    if (reply.arguments().size() == 1) {
        return reply.arguments().at(0).toUInt();
    }

    return UINT_MAX;
}

void SessionTask::search()
{
    qCDebug(APPER_SESSION) << "virtual method called, falling back to commit()";
    commit();
}

void SessionTask::commit()
{
    qCDebug(APPER_SESSION) << "virtual method called";
    if (m_reviewChanges) {
        QStringList installPackages = m_reviewChanges->model()->selectedPackagesToInstall();
        m_removePackages = m_reviewChanges->model()->selectedPackagesToRemove();

        if (installPackages.isEmpty() && m_removePackages.isEmpty()) {
            setInfo(i18n("There are no packages to Install or Remove"),
                    i18n("This action should not happen"));
            sendErrorFinished(Failed, QLatin1String("to install or remove due to empty lists"));
        } else if (!installPackages.isEmpty()) {
            // Install Packages
            auto transaction = new PkTransaction(this);
            setTransaction(Transaction::RoleInstallPackages, transaction);
            connect(transaction, &PkTransaction::finished, this, &SessionTask::commitFinished, Qt::UniqueConnection);
            transaction->installPackages(installPackages);
        } else {
            // Remove them
            removePackages();
        }
    }
}

void SessionTask::removePackages()
{
    // Remove Packages
    auto transaction = new PkTransaction(this);
    setTransaction(Transaction::RoleRemovePackages, transaction);
    connect(transaction, &PkTransaction::finished, this, &SessionTask::commitFinished, Qt::UniqueConnection);
    transaction->removePackages(m_removePackages);
    m_removePackages.clear();
}

void SessionTask::notFound()
{
    qCDebug(APPER_SESSION) << "virtual method called";
    if (showWarning()) {
        setInfo(i18n("Could not find"),
                i18n("No packages were found that meet the request"));
    }
    sendErrorFinished(NoPackagesFound, QLatin1String("no package found"));
}

void SessionTask::searchFailed()
{
    qCDebug(APPER_SESSION) << "virtual method called";
    setInfo(i18n("Failed to find"),
            i18n("No packages were found that meet the request"));
    sendErrorFinished(Failed, QLatin1String("failed to search"));
}

void SessionTask::searchSuccess()
{
    qCDebug(APPER_SESSION) << "virtual method called";
    enableButtonOk(true);
    m_reviewChanges = new ReviewChanges(m_model, this);
    connect(m_reviewChanges, &ReviewChanges::hasSelectedPackages, this, &SessionTask::enableButtonOk);
    setMainWidget(m_reviewChanges);
}

void SessionTask::commitFailed()
{
    qCDebug(APPER_SESSION) << "virtual method called";
    // This should not be used to display stuff as the transaction should
    // emit error() or info()
//    setInfo(i18n("Failed to commit transaction"),
//            PkStrings::errsearchFailedorMessage(m_pkTransaction->error()));
    sendErrorFinished(Failed, i18n("Transaction did not finish with success"));
}

void SessionTask::commitSuccess(QWidget *widget)
{
    qCDebug(APPER_SESSION) << "virtual method called";
    setFinish(i18n("Task completed"), i18n("All operations were committed successfully"), widget);
    finishTaskOk();
}

void SessionTask::showCloseButton()
{
    ui->buttonBox->setStandardButtons(QDialogButtonBox::Close);
    QPushButton *closeBt = ui->buttonBox->button(QDialogButtonBox::Close);
    closeBt->setDefault(true);
    connect(closeBt, &QPushButton::clicked, this, &SessionTask::accept);
}

void SessionTask::sendErrorFinished(DBusError error, const QString &msg)
{
    QString dbusError;
    switch (error) {
    case Failed:
        dbusError = QLatin1String("org.freedesktop.PackageKit.Failed");
        break;
    case InternalError:
        dbusError = QLatin1String("org.freedesktop.PackageKit.InternalError");
        break;
    case NoPackagesFound:
        dbusError = QLatin1String("org.freedesktop.PackageKit.NoPackagesFound");
        break;
    case Forbidden:
        dbusError = QLatin1String("org.freedesktop.PackageKit.Forbidden");
        break;
    case Cancelled:
        dbusError = QLatin1String("org.freedesktop.PackageKit.Cancelled");
        break;
    }
    QDBusMessage reply = m_message.createErrorReply(dbusError, msg);
    QDBusConnection::sessionBus().send(reply);
}

bool SessionTask::sendMessageFinished(const QDBusMessage &message)
{
//    emit finished();
    return QDBusConnection::sessionBus().send(message);
}

uint SessionTask::parentWId() const
{
    return m_xid;
}

void SessionTask::slotContinueClicked()
{
    if (qobject_cast<IntroDialog*>(mainWidget())) {
        enableButtonOk(false);
        search();
    } else if (qobject_cast<ReviewChanges*>(mainWidget())) {
        enableButtonOk(false);
        commit();
    } else {
//        emit okClicked();
    }
}

void SessionTask::slotCancelClicked()
{
    emit cancelClicked();
    sendErrorFinished(Cancelled, QLatin1String("Aborted by the user"));
    reject();

}

void SessionTask::enableButtonOk(bool enable)
{
    QPushButton *okButton = ui->buttonBox->button(QDialogButtonBox::Ok);
    okButton->setEnabled(enable);
    if (enable) {
        // When enabling the Continue button put focus on it
        okButton->setFocus();
    }
}

void SessionTask::parseInteraction(const QString &interaction)
{
    QStringList interactions = interaction.split(QLatin1Char(','));

    // Enable or disable all options
    if (interactions.contains(QLatin1String("always"))) {
        m_interactions = ConfirmSearch
                       | ConfirmDeps
                       | ConfirmInstall
                       | Progress
                       | Finished
                       | Warning;
    } else if (interactions.contains(QLatin1String("never"))) {
        m_interactions = 0;
    }

    // show custom options
    if (interactions.contains(QLatin1String("show-confirm-search"))) {
        m_interactions |= ConfirmSearch;
    }
    if (interactions.contains(QLatin1String("show-confirm-deps"))) {
        m_interactions |= ConfirmDeps;
    }
    if (interactions.contains(QLatin1String("show-confirm-install"))) {
        m_interactions |= ConfirmInstall;
    }
    if (interactions.contains(QLatin1String("show-progress"))) {
        m_interactions |= Progress;
    }
    if (interactions.contains(QLatin1String("show-finished"))) {
        m_interactions |= Finished;
    }
    if (interactions.contains(QLatin1String("show-warning"))) {
        m_interactions |= Warning;
    }

    // hide custom options
    if (interactions.contains(QLatin1String("hide-confirm-search"))) {
        m_interactions &= ~ConfirmSearch;
    }
    if (interactions.contains(QLatin1String("hide-confirm-deps"))) {
        m_interactions &= ~ConfirmDeps;
    }
    if (interactions.contains(QLatin1String("hide-confirm-install"))) {
        m_interactions &= ~ConfirmInstall;
    }
    if (interactions.contains(QLatin1String("hide-progress"))) {
        m_interactions &= ~Progress;
    }
    if (interactions.contains(QLatin1String("hide-finished"))) {
        m_interactions &= ~Finished;
    }
    if (interactions.contains(QLatin1String("hide-warning"))) {
        m_interactions &= ~Warning;
    }

    int index;
    QRegExp rx(QLatin1String("^timeout=(\\d+)$"));
    index = interactions.indexOf(rx);
    if (index != -1) {
        if (rx.indexIn(interactions.at(index)) != -1) {
            m_timeout = rx.cap(1).toUInt();
        }
    }
}

bool SessionTask::foundPackages() const
{
    return m_model->rowCount();
}

int SessionTask::foundPackagesSize() const
{
    return m_model->rowCount();
}

PackageModel *SessionTask::model() const
{
    return m_model;
}

void SessionTask::setTransaction(Transaction::Role role, PkTransaction *t)
{
    if (m_pkTransaction == 0) {
        m_pkTransaction = new PkTransactionWidget(this);
        m_pkTransaction->hideCancelButton();

        ui->stackedWidget->addWidget(m_pkTransaction);
        connect(m_pkTransaction, &PkTransactionWidget::titleChanged, this, &SessionTask::setTitle);
        connect(this, &SessionTask::cancelClicked, m_pkTransaction, &PkTransactionWidget::cancel);
        connect(m_pkTransaction, &PkTransactionWidget::dialog, this, &SessionTask::setDialog);
        connect(m_pkTransaction, &PkTransactionWidget::sorry, this, &SessionTask::setInfo);
        connect(m_pkTransaction, &PkTransactionWidget::error, this, &SessionTask::setError);
    }
    if (t) {
        m_pkTransaction->setTransaction(t, role);
//        setTitle(m_pkTransaction->title());
    }

    // avoid changing the current widget
    if (mainWidget() != m_pkTransaction) {
        ui->stackedWidget->setCurrentWidget(m_pkTransaction);
    }
}

void SessionTask::finishTaskOk()
{
    sendMessageFinished(m_message.createReply());
}

SessionTask::Interactions SessionTask::interactions() const
{
    return m_interactions;
}

uint SessionTask::timeout() const
{
    return m_timeout;
}

bool SessionTask::showConfirmSearch() const
{
    return m_interactions & ConfirmSearch;
}

bool SessionTask::showConfirmDeps() const
{
    return m_interactions & ConfirmDeps;
}

bool SessionTask::showConfirmInstall() const
{
    return m_interactions & ConfirmInstall;
}

bool SessionTask::showProgress() const
{
    return m_interactions & Progress;
}

bool SessionTask::showFinished() const
{
    return m_interactions & Finished;
}

bool SessionTask::showWarning() const
{
    return m_interactions & Warning;
}

#include "moc_SessionTask.cpp"