summaryrefslogtreecommitdiffstats
path: root/src/dialog.cpp
blob: 3eeaf7ebf207f7a5faceb6f1f11308f4b9357b25 (plain) (blame)
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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
#include "dialog.h"
#include "config.h"

#include <QMessageBox>
#include <QDebug>
#include <QRegExp>
#include <QFile>
#include <QProcess>
#include <QTimer>
#include <QDesktopWidget>
#include <QDateTime>
#include <QTemporaryFile>
#include <QUrlQuery>

#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>

#include "ui_dialog.h"
#include "sessiontreeitem.h"
#include "globals.h"
#include "vsession.h"
#include "userconfig.h"
#include "filedownloader.h"
#include "windowmanager.h"

static bool isProcessRunning(const QString &binary);

QDialog* Dialog::instance = nullptr;

static QDomDocument toDomDocument(const QString& what, const QByteArray& data, const QString& backupFile, const QString& mandatoryChild);

Dialog::Dialog(QWidget *parent)
    : QDialog(parent), ui(new Ui::Dialog) {

    instance = this;
    model_[TAB_NATIVE] = new SessionTreeModel(parent);
    model_[TAB_RECENT_COURSES] = new SessionTreeModel(parent, true);
    model_[TAB_ALL_VMS] = new SessionTreeModel(parent);
    userInteracted_ = false;
    genericExpandedOnce_ = false;
    autoQuit_ = g_autoQuitSeconds;

    ui->setupUi(this);

    tabs_[TAB_NATIVE] = ui->tabButtonLocal;
    tabs_[TAB_RECENT_COURSES] = ui->tabButtonMyClasses;
    tabs_[TAB_ALL_VMS] = ui->tabButtonAllClasses;

    strings_[STR_LOADING] = QCoreApplication::instance()->translate("Dialog", "Loading...");
    strings_[STR_URL_ERROR] = QCoreApplication::instance()->translate("Dialog", "URL Error");
    strings_[STR_NO_ITEMS] = QCoreApplication::instance()->translate("Dialog", "No Items");

    // Re-center dialog every second to account for resolution changes
    QRect desktopRect = QApplication::desktop()->availableGeometry(this);
    oldCenter_ = desktopRect.center();
    centerTimer_ = new QTimer(this);
    connect(centerTimer_, &QTimer::timeout, this, &Dialog::onCenterTimer);
    centerTimer_->start(1000);

    ui->treeView->setFocusProxy(ui->filterEdit);
    // ui->filterEdit->installEventFilter(this);
    QCoreApplication::instance()->installEventFilter(this);

    if (!UserConfig::isNewsHelpOpen()) {
        ui->helpBox->hide();
        ui->newsBox->hide();
    }
    ui->lblAutoQuit->hide();

    this->addStatusString(STR_LOADING);

    /*
     * TODO: why connect signal/slot when no item was loaded yet?
     * TODO: Change "TODO" in the above line to "QUESTION", as it's just that
    QObject::connect(ui->treeView->selectionModel(), SIGNAL(currentChanged ( const QModelIndex&, const QModelIndex&)),
            this, SLOT(treeView_selectionChanged(const QModelIndex&, const QModelIndex&)));
    */

    ui->PVS_checkbox->setVisible(Config::isSet(Config::PVS));
    ui->PVS_checkbox->setChecked(Config::isSet(Config::PVS_CHECKED));

    ui->chkNoScreenSaver->setVisible(Config::isSet(Config::ALLOW_SCREENSAVER_DISABLE));

    activeTab_ = -1;
    if (Config::isSet(Config::EXAM_MODE)) {
        ui->tabButtonLocal->setEnabled(false);
        this->onTabButtonChanged(TAB_ALL_VMS);
        /* modify the pvs checkbox */
        ui->PVS_checkbox->setText(tr("join PVS(limited)"));
        ui->PVS_checkbox->setEnabled(false);
        ui->PVS_checkbox->setChecked(true);

    } else {
        this->onTabButtonChanged(TAB_NATIVE);
    }

    ui->chkAdminEdit->setVisible(Config::isSet(Config::ALLOW_VM_EDIT));
    ui->chkAdminEdit->setEnabled(false);
    ui->chkAdminCopy->setVisible(Config::isSet(Config::ALLOW_VM_EDIT));
    ui->chkAdminCopy->setEnabled(false);

	ui->btnScreenSetup->setVisible(isProcessRunning("beamergui"));
	if (QApplication::screens().size() > 1) {
		QFont copy = ui->btnScreenSetup->font();
		copy.setBold(true);
		ui->btnScreenSetup->setFont(copy);
	}

    // TODO: Implement bug report dialog :)
    ui->buttonBugReport->setEnabled(false);
    QObject::connect(SessionsIconHolder::get(), &SessionsIconHolder::iconDownloaded,
            this, &Dialog::iconDownloaded);

    QObject::connect(ui->chkAdminCopy, &QCheckBox::toggled, [this](bool checked) {
        if (checked) {
            ui->chkAdminEdit->setChecked(false);
        }
    });
    QObject::connect(ui->chkAdminEdit, &QCheckBox::toggled, [this](bool checked) {
        if (checked) {
            ui->chkAdminCopy->setChecked(false);
        }
    });
}

Dialog::~Dialog() {
    instance = nullptr;
    delete ui;
}

void Dialog::changeEvent(QEvent *e) {
    QDialog::changeEvent(e);
    if (e->type() == QEvent::LanguageChange) {
        ui->retranslateUi(this);
    }
}

void Dialog::on_treeView_doubleClicked(const QModelIndex& index)
{
    userInteracted_ = true;
    // this method gets called when a Session has been selected to start

    SessionTreeItem* item =
                    static_cast<SessionTreeItem*>(index.internalPointer());

    if (item == nullptr)
            return; // do nothing if cast failed

    const Session* s(item->session());
    if (s == nullptr) // no valid session has been selected, do nothing
            return;

    // Check preconditions. The method might show error messages and return false
    if (!s->prepareRun())
        return;

    bool adminMode = false;

    if (anyEditModeRequested() && s->canEdit()) {
        auto mode = s->editModeTypes();
        adminMode = true;
        if (ui->chkAdminEdit->isChecked() && ui->chkAdminEdit->isEnabled()) {
            setenv("VMCHOOSER_ADMIN_TYPE", "EDIT", 1);
        } else {
            setenv("VMCHOOSER_ADMIN_TYPE", "COPY", 1);
        }
        if (Config::isSet(Config::COW_TOKEN)) {
            setenv("VMCHOOSER_ADMIN_TOKEN", Config::get(Config::COW_TOKEN).toLocal8Bit().constData(), 1);
        }
    }

    WindowManager::stopOwnInstance(true);

    // These two are up here in case run-virt cares...
    if (Config::isSet(Config::PVS)) {
        if (ui->PVS_checkbox->isChecked()) {
            setenv("PVS_AUTO_CONNECT", "TRUE", 1);
        } else {
            setenv("PVS_AUTO_CONNECT", "FALSE", 1);
        }
    }

    if (anyEditModeRequested() && Config::isSet(Config::ALLOW_VM_EDIT)) {
        adminMode = true;
    }

    if (adminMode) {
        setenv("VMCHOOSER_ADMIN_MODE", "TRUE", 1);
    } else {
        setenv("VMCHOOSER_ADMIN_MODE", "FALSE", 1);
    }

    if (ui->chkNoScreenSaver->isChecked()) {
        setenv("VMCHOOSER_DISABLE_SCREENSAVER", "TRUE", 1);
    } else {
        setenv("VMCHOOSER_DISABLE_SCREENSAVER", "FALSE", 1);
    }

    UserConfig::addLastSession(s->uuid().isEmpty() ? s->shortDescription() : s->uuid());
    UserConfig::setLastTab(activeTab_);
    UserConfig::setNewsHelpOpen(!ui->helpBox->isHidden());
    UserConfig::sync();

    qint64 scriptPid = 0;
    if (QFile::exists(SESSION_START_SCRIPT)) {
        // Companion script
        setenv("SESSION_NAME", s->shortDescription().toLocal8Bit().constData(), 1);
        setenv("SESSION_UUID", s->uuid().toLocal8Bit().constData(), 1);
        setenv("SESSION_CMD", s->execCommand().toLocal8Bit().constData(), 1);
        if (s->type() == Session::VSESSION) {
           setenv("SESSION_TYPE", "VSESSION", 1);
        } else if (s->type() == Session::XSESSION) {
           setenv("SESSION_TYPE", "XSESSION", 1);
        }
        if (!QProcess::startDetached(SESSION_START_SCRIPT, QStringList(), QStringLiteral("/"), &scriptPid)) {
            scriptPid = 0;
        }
    }

    // Run session
    s->run();
    // Should not return on success
    if (scriptPid > 0) {
        ::kill(pid_t(scriptPid), SIGTERM);
    }
    QMessageBox::critical(
                this, tr("vmchooser"),
                tr("Vmchooser failed to run the selected session!"));
    QApplication::instance()->quit();
}

bool Dialog::anyEditModeRequested() const
{
    return (ui->chkAdminEdit->isEnabled() && ui->chkAdminEdit->isChecked())
            || (ui->chkAdminCopy->isEnabled() && ui->chkAdminCopy->isChecked());
}

void Dialog::on_treeView_expanded(const QModelIndex& index) {
    if (activeTab_ != TAB_ALL_VMS)
        return;
    SessionTreeItem* item =
                    static_cast<SessionTreeItem*>(index.internalPointer());
    if (item->session() == nullptr && item->sectionType() != SECTION_FOR_LOCATION) {
        genericExpandedOnce_ = true;
    }
}

void Dialog::addItems(const QList<Session*>& entries, int tab) {
    if (tab < 0 || tab >= TAB_COUNT)
        return; // Invalid index
    if (Config::isSet(Config::EXAM_MODE) && tab == TAB_NATIVE)
        return; // Exam mode -- keep native sessions empty
    ui->treeView->blockSignals(true);
    if (tab != TAB_RECENT_COURSES) {
        // If tab is not the recent courses tab, check the list for any recent sessions
        auto prev = UserConfig::getLastSessions();
        if (!prev.isEmpty()) {
            QList<Session*> matches;
            for (auto it : entries) {
                if ((!it->uuid().isEmpty() && prev.contains(it->uuid()))
                        || prev.contains(it->shortDescription())) {
                    matches.append(it);
                }
            }
            if (!matches.isEmpty()) {
                addItems(matches, TAB_RECENT_COURSES);
                ui->treeView->blockSignals(true);
            }
        }
        for (auto it : entries) {
            // Also check for validity
            it->checkCanRun();
        }
    }
    this->model_[tab]->addItems(entries);
    tabs_[tab]->setEnabled(this->model_[tab]->rowCount() != 0);
    if (tab == activeTab_) {
        setListModel(this->model_[tab]);
    }
    ui->treeView->blockSignals(false);
    model_[tab]->updateView();
    if (!ui->filterEdit->text().isEmpty()) {
        on_filterEdit_textChanged();
    }
    if (tab != TAB_RECENT_COURSES) {
        selectPreviousSession();
    }
}

void Dialog::addStatusString(const int status) {
    if (status < 0 || status >= STR__MAX)
        return;
    this->model_[TAB_RECENT_COURSES]->addLabelItem(strings_[status]);
    this->model_[TAB_ALL_VMS]->addLabelItem(strings_[status]);
    tabs_[TAB_RECENT_COURSES]->setEnabled(this->model_[TAB_RECENT_COURSES]->rowCount() > 1);
    tabs_[TAB_ALL_VMS]->setEnabled(this->model_[TAB_ALL_VMS]->rowCount() > 1);
    model_[TAB_RECENT_COURSES]->updateView();
    model_[TAB_ALL_VMS]->updateView();
}

void Dialog::removeStatusString(const int status) {
    if (status < 0 || status >= STR__MAX)
        return;
    this->model_[TAB_RECENT_COURSES]->removeItem(strings_[status]);
    this->model_[TAB_ALL_VMS]->removeItem(strings_[status]);
    tabs_[TAB_RECENT_COURSES]->setEnabled(this->model_[TAB_RECENT_COURSES]->rowCount() > 1);
    tabs_[TAB_ALL_VMS]->setEnabled(this->model_[TAB_RECENT_COURSES]->rowCount() > 1);
    model_[TAB_RECENT_COURSES]->updateView();
    model_[TAB_ALL_VMS]->updateView();
}

void Dialog::on_pushButtonAbort_clicked() {
    close();
}

void Dialog::on_pushButtonStart_clicked() {
    userInteracted_ = true;
    this->on_treeView_doubleClicked(ui->treeView->selectionModel()->currentIndex());
}

void Dialog::on_btnScreenSetup_clicked() {
	QProcess::startDetached("beamergui", QStringList("-w"));
}

bool Dialog::selectSession(const QString& name, int preferredTab) {
    QModelIndex root(ui->treeView->rootIndex());

    int bestTab = -1;
    int matchLevel = 0;
    int boost;
    QModelIndex bestIndex;
    for (int tab = TAB_COUNT - 1; tab >= 0; --tab) {
        boost = (tab == preferredTab);
        for (int i = 0; i < model_[tab]->rowCount(root); ++i) {
            QModelIndex section(model_[tab]->index(i, 0, root));
            if (!section.isValid())
                continue;
            for (int j = 0; j < model_[tab]->rowCount(section); ++j) {
                QModelIndex index(model_[tab]->index(j, 0, section));
                if (!index.isValid())
                    continue;
                SessionTreeItem* item = static_cast<SessionTreeItem*>(index.internalPointer());
                const Session* s = item->session();
                if (s == nullptr) {
                    continue;
                }
                if ((!s->uuid().isEmpty() && s->uuid() == name) || s->shortDescription() == name) {
                    bestTab = tab;
                    bestIndex = index;
                    matchLevel = 5 + boost;
                    break; // Break inner, keep checking other tabs
                }
                if (matchLevel < 3 + boost && s->shortDescription().startsWith(name)) {
                    bestTab = tab;
                    bestIndex = index;
                    matchLevel = 3 + boost;
                }
                if (matchLevel < 1 + boost && name.length() > 3 && s->shortDescription().contains(name)) {
                    bestTab = tab;
                    bestIndex = index;
                    matchLevel = 1 + boost;
                }
            }
        }
    }

    if (bestTab != -1) {
        // change the tab
        qDebug() << "Best tab is" << bestTab;
        onTabButtonChanged(bestTab);
        // set selection
        ui->treeView->selectionModel()->clearSelection();
        ui->treeView->selectionModel()->clear();
        ui->treeView->selectionModel()->select(bestIndex, QItemSelectionModel::Select);
        ui->treeView->selectionModel()->setCurrentIndex(bestIndex, QItemSelectionModel::Select);
        ui->treeView->scrollTo(bestIndex);
        return true;
    }

    return false;
}

void Dialog::selectPreviousSession() {
    if (userInteracted_) {
        qDebug() << "Not selecting previous session as user interacted or session was already selected";
        return;
    }
    int lastTab = UserConfig::getLastTab();

    if (Config::isSet(Config::FORCE_DEFAULT_TAB)) {
        // Force specific tab preselect
        lastTab = Config::get(Config::DEFAULT_TAB).toInt();
    }

    // Command line default session takes precedence
    QString lastSession = Config::get(Config::DEFAULT_SESSION);
    if (lastSession.isEmpty() && !Config::isSet(Config::FORCE_DEFAULT_TAB)) {
        // If no cmdline, use user's last session if we don't force a tab via cmdline
        auto list = UserConfig::getLastSessions();
        if (!list.isEmpty()) {
            lastSession = list.back();
        }
    }
    if (!lastSession.isEmpty()) {
        qDebug() << "Trying to select last session: " << lastSession;
        ui->treeView->clearSelection();
        if (selectSession(lastSession, lastTab)) {
            qDebug() << "Success";
            userInteracted_ = true;
            return;
        }
    }
    // could not find last session, change to last used tab
    if (lastTab >= 0 && lastTab < TAB_COUNT) {
        qDebug() << "Trying to select last tab " << lastTab;
        this->onTabButtonChanged(lastTab);
    } else if (Config::isSet(Config::DEFAULT_TAB)) {
        int defaultTab = Config::get(Config::DEFAULT_TAB).toInt();
        qDebug() << "Selected default tab " << defaultTab;
        // Select default tab
        this->onTabButtonChanged(defaultTab);
    }
}

void Dialog::startSession(const QString& name) {
    autoStartEntry_ = name;
}

void Dialog::setTheme() {
    QString backgroundColor, imageLeft, imageRight, backgroundStyle;
    QString themePathBase, themePathIni, themePathImgLeft, themePathImgRight;

    if (!Config::isSet(Config::THEME))
        return;

    QString theme(Config::get(Config::THEME));
    if (theme.startsWith(QStringLiteral("/"))) {
        themePathBase = theme + QStringLiteral("/");
    } else {
        themePathBase = QStringLiteral("%1/%2/").arg(VMCHOOSER_THEME_BASE).arg(theme);
    }
    themePathIni = themePathBase + theme + QStringLiteral(".ini");

    if (!QFile::exists(themePathIni)) {
        qDebug() << "Theme config" << themePathIni << "does not exist";
        return;
    }

    QSettings themeSettings(themePathIni, QSettings::IniFormat);
    themeSettings.setIniCodec("UTF-8");
    backgroundColor = themeSettings.value("background-color").toString();
    backgroundStyle = themeSettings.value("background").toString();
    imageLeft = themeSettings.value("image-left").toString();
    imageRight = themeSettings.value("image-right").toString();

    themePathImgLeft = themePathBase + imageLeft;
    themePathImgRight = themePathBase + imageRight;

    QPixmap imgLeft(themePathImgLeft);
    QPixmap imgRight(themePathImgRight);
    ui->label_l->setPixmap(imgLeft);
    ui->label_r->setPixmap(imgRight);
    ui->label_l->setMinimumSize(imgLeft.size());
    ui->label_r->setMinimumSize(imgRight.size());
    if (!backgroundStyle.isEmpty()) {
        qDebug() << "Setting background to" << (backgroundStyle);
        ui->headerBg->setStyleSheet(QStringLiteral("#headerBg { %1 }").arg(backgroundStyle));
    } else {
        backgroundColor = QStringLiteral("background:") + backgroundColor;
        ui->headerBg->setStyleSheet(backgroundColor);
    }
}


void Dialog::onCenterTimer() {
    // center dialog on primary screen
    if (isVisible()) {
        QRect desktopRect = QApplication::desktop()->availableGeometry(this);
        QPoint center = desktopRect.center();
        if (center != oldCenter_) {
            if (g_fullscreen)
                this->resize(desktopRect.width(), desktopRect.height());
            this->move(center.x() - this->width() / 2, center.y() - this->height() / 2);
            oldCenter_ = center;
        }
    }
    // Handle auto-quit timeout
    if (autoQuit_ > 0) {
        autoQuit_--;
        if (autoQuit_ == 0) {
            QCoreApplication::instance()->exit(0);
        } else if (autoQuit_ < 60) {
            ui->lblAutoQuit->setText(tr("Auto logout in %1").arg(autoQuit_));
            ui->lblAutoQuit->show();
        } else if (!ui->lblAutoQuit->isHidden()) {
            ui->lblAutoQuit->hide();
        }
    }
}

/**
 * Download lecture list, news and help
 */
void Dialog::downloadData() {
    QUrl listUrl(Config::isSet(Config::URL_LIST)
                 ? Config::get(Config::URL_LIST)
                 : Config::get(Config::URL_BASE).append("/list"));
    QUrlQuery listQuery(listUrl);

    bool cache = true;
    const QString& locationIds = Config::get(Config::LOCATIONS);
    const QString& cowToken = Config::get(Config::COW_TOKEN);
    if (!locationIds.isEmpty()) {
        listQuery.addQueryItem("locations", locationIds);
    }
    if (!cowToken.isEmpty()) {
        // Don't cache lecture list containing edit mode annotations
        listQuery.addQueryItem("cow-user", cowToken);
        cache = false;
    }
    if (Config::isSet(Config::EXAM_MODE)) {
        listQuery.addQueryItem("exams", "exam-mode");
    }
    listUrl.setQuery(listQuery);
    //
    // Download lecture XML
    FileDownloader::download(listUrl, [cache, this](QNetworkReply::NetworkError err, const QByteArray& data) {
        QList<Session*> sessions;
        QDomDocument doc = toDomDocument(QStringLiteral("lecture list"), data, cache ? TEMP_PATH_XML_LIST : QString(),
                QStringLiteral("settings"));
        sessions = VSession::loadFromXmlDocument(doc);

        QString errMsg = doc.firstChildElement(QStringLiteral("settings"))
                    .firstChildElement(QStringLiteral("error")).text();

        if (!errMsg.isEmpty()) {
            ui->filterEdit->setText(errMsg);
        }

        this->removeStatusString(STR_LOADING);
        if (sessions.isEmpty()) {
            if (err == QNetworkReply::NoError) {
                this->addStatusString(STR_NO_ITEMS);
            } else {
                this->addStatusString(STR_URL_ERROR);
            }
        } else {
            qSort(sessions.begin(), sessions.end(), sessionComparator);
            this->addItems(sessions, TAB_ALL_VMS);
            bool showEdit = false; // Only show edit button if at least one lecture is editable
            for (QList<Session*>::const_iterator it = sessions.begin(); it != sessions.end(); ++it) {
                if ((**it).canEdit()) {
                    showEdit = true;
                    break;
                }
            }
            if (showEdit) {
                ui->chkAdminEdit->setVisible(true);
                ui->chkAdminCopy->setVisible(true);
            }
        }

        checkAutostart();

        // select last-session
        selectPreviousSession();
        userInteracted_ = true;
    });
    //
    // News
    FileDownloader::download(QUrl(Config::isSet(Config::URL_NEWS)
                                  ? Config::get(Config::URL_NEWS)
                                  : Config::get(Config::URL_BASE).append("/news")), [this](QNetworkReply::NetworkError err, const QByteArray& data) {
        QDomDocument doc = toDomDocument(QStringLiteral("news"), data, TEMP_PATH_NEWS, QStringLiteral("news"));
        QDomElement newsNode = doc.firstChildElement("news");
        QDomElement timeNode = newsNode.firstChildElement("date");
        QDomElement infoNode = newsNode.firstChildElement("info");
        QDomElement headlineNode = newsNode.firstChildElement("headline");
        QDateTime timestamp;
        timestamp.setTime_t(timeNode.text().toUInt());

        if (timeNode.isNull() || infoNode.isNull()) {
            qDebug() << "Could not load news. Network:" << err;
            ui->newsTextBrowser->setText(QCoreApplication::instance()->translate("Dialog", "Could not get news. (//news/date or //news/info missing)"));
        } else {
            // format and print news
            ui->newsTextBrowser->setText(QString("<p style='font-size:16px; margin-bottom: 2px;'>" + headlineNode.text() + "</p> <small>"
                    + timestamp.toString(Qt::SystemLocaleShortDate) + "</small><p>"
                    + infoNode.text() + "</p>"));
        }

        if (ui->helpBox->isHidden()
                && (UserConfig::getLastNewsTime() < timestamp.toTime_t() || UserConfig::getLastNewsTime() > QDateTime::currentMSecsSinceEpoch() / 1000)) {
            // show news if not seen before
            on_helpNewsButton_clicked();
        }

        // update ini
        UserConfig::setLastNewsTime(timestamp.toTime_t());
    });
    //
    // Download help
    FileDownloader::download(QUrl(Config::isSet(Config::URL_HELP)
                                  ? Config::get(Config::URL_HELP)
                                  : Config::get(Config::URL_BASE).append("/help")), [this](QNetworkReply::NetworkError err, const QByteArray& data) {
        QDomDocument doc = toDomDocument(QStringLiteral("help"), data, TEMP_PATH_HELP, QStringLiteral("news"));
        QDomElement helpTextNode = doc.firstChildElement("news").firstChildElement("info");
        if (helpTextNode.isNull()) {
            qDebug() << "Could not load help. Network:" << err;
            ui->helpTextBrowser->setText(QCoreApplication::instance()->translate("Dialog", "Could not get help (XML has no //news/info)"));
        } else {
            ui->helpTextBrowser->setText(helpTextNode.text());
        }
    });
    //
}

void Dialog::mousePressEvent(QMouseEvent * event) {
    QDialog::mousePressEvent(event);
    userInteracted_ = true;
}

void Dialog::setAdminChecks(int mode)
{
    ui->chkAdminEdit->setEnabled((mode & Session::EDIT_TYPE_EDIT) != 0);
    ui->chkAdminCopy->setEnabled((mode & Session::EDIT_TYPE_COPY) != 0);
}

void Dialog::treeView_selectionChanged(const QModelIndex& current, const QModelIndex&) {
    SessionTreeItem* item = static_cast<SessionTreeItem*>(current.internalPointer());
    if (item == nullptr) {
        setAdminChecks(0);
        return;
    }

    const Session* s(item->session());
    if (!s) {
        qDebug() << "invalid selection";
        // no valid session has been selected, do nothing
        setAdminChecks(0);
        return;
    }

    QString description;
    if (s->type() == Session::VSESSION) {
        const VSession* vs = reinterpret_cast<const VSession*>(s);

        ui->label_creator->setText(vs->getAttribute("creator", "param"));
        ui->label_creator->setToolTip(vs->getAttribute("creator", "param"));

        ui->label_os->setText(vs->getAttribute("os_name", "param"));
        ui->label_os->setToolTip(vs->getAttribute("os_name", "param"));

        ui->label_platform->setText(vs->getAttribute("virtualizer_name", "param"));
        ui->label_platform->setToolTip(vs->getAttribute("virtualizer_name", "param"));

        // If ALLOW_EDIT is false, we still might have editable sessions if the list meta data says so
        if (Config::isSet(Config::ALLOW_VM_EDIT)) {
            setAdminChecks(255);
        } else {
            setAdminChecks(s->editModeTypes());
        }

        if (vs->keywords().length() > 0) {
            description = "\n\nKeywords: ";
            for (int i = 0; i < vs->keywords().length(); ++i) {
                description += vs->keywords()[i] + ", ";
            }
        }
    } else {
        ui->label_creator->setText("");
        ui->label_creator->setToolTip("");
        ui->label_os->setText(QCoreApplication::instance()->translate("Dialog", "Native Linux"));
        ui->label_platform->setText("Linux");
        ui->label_platform->setToolTip("");
        setAdminChecks(0);
    }
    ui->label_name->setText(s->shortDescription());
    ui->label_name->setToolTip(s->shortDescription());
    ui->textBrowser->setPlainText(s->description() + description);
}

void Dialog::on_tabButtonLocal_clicked() {
    userInteracted_ = true;
    onTabButtonChanged(TAB_NATIVE);
}

void Dialog::on_tabButtonMyClasses_clicked() {
    userInteracted_ = true;
    onTabButtonChanged(TAB_RECENT_COURSES);
}

void Dialog::on_tabButtonAllClasses_clicked() {
    userInteracted_ = true;
    onTabButtonChanged(TAB_ALL_VMS);
}

void Dialog::onTabButtonChanged(int tab) {
    if (tab < 0 || tab >= TAB_COUNT) {
        // no valid button
        return;
    }
    // Block this so it won't trigger the expand signal while refilling, which would
    // interfere with LOCATION_EXCLUSIVE mode
    ui->treeView->blockSignals(true);

    // give focus to treeView
    if (!ui->treeView->hasFocus()) {
        ui->treeView->setFocus();
    }

    // Update pressed status of buttons
    for (int i = 0; i < TAB_COUNT; ++i) {
        tabs_[i]->setChecked(tab == i);
    }

    // clear filter if necessary
    if (activeTab_ != tab) {
        this->ui->filterEdit->setText("");
    }

    // load the new list
    setListModel(model_[tab]);
    this->activeTab_ = tab;

    ui->treeView->blockSignals(false);
    /* get the first element ad select it */
    selectFirstElement();

}

void Dialog::on_filterEdit_textEdited() {
    userInteracted_ = true;
}

void Dialog::on_filterEdit_textChanged() {
    if (activeTab_ < 0 || activeTab_ >= TAB_COUNT) return;
    SessionTreeModel *newModel = nullptr;

    // filter the current model
    if (!ui->filterEdit->text().isEmpty() && ui->filterEdit->text().replace(" ", "").length() > 2) {
        if (model_[activeTab_] != nullptr) {
            newModel = new SessionTreeModel(this);
            newModel->addItems(this->model_[activeTab_]->lookForItem(ui->filterEdit->text()));
        }
    }
    if (newModel == nullptr) {
        newModel = model_[activeTab_];
    }
    if (newModel != nullptr) {
        setListModel(newModel);
    }
}

void Dialog::setListModel(SessionTreeModel *model) {
    QAbstractItemModel *old = nullptr;
    if (ui->treeView->model() == model_[TAB_NATIVE] || ui->treeView->model() == model_[TAB_RECENT_COURSES] || ui->treeView->model() == model_[TAB_ALL_VMS]) {
        // A default model is currently being set; don't delete it
    } else {
        // Remember currently set model so we can delete it after setting the new one
        old = ui->treeView->model();
    }
    // Disconnect current model
    QObject::disconnect(ui->treeView->selectionModel(), &QItemSelectionModel::currentChanged,
            this, &Dialog::treeView_selectionChanged);
    ui->treeView->setModel(model);
    ui->treeView->expandAll();
    if (!genericExpandedOnce_ && g_forLocationHandling == LOCATION_EXCLUSIVE && model->rowCount() > 1) {
        QModelIndex index = model->getSection(SECTION_GENERIC);
        if (index.isValid()) {
            ui->treeView->collapse(index);
        }
        index = model->getSection(SECTION_TEMPLATES);
        if (index.isValid()) {
            ui->treeView->collapse(index);
        }
    }
    if (old != nullptr) {
        old->deleteLater();
    }

    // reconnect the treeModel
    QObject::connect(ui->treeView->selectionModel(), &QItemSelectionModel::currentChanged,
            this, &Dialog::treeView_selectionChanged);

    // select the first element, if no element is selected
    if (ui->treeView->selectionModel()->selectedRows().count() == 0) {
        //ui->treeView->selectionModel()->setCurrentIndex(ui->treeView->model()->index(0, 0, ui->treeView->rootIndex()), QItemSelectionModel::Select);
        ui->treeView->selectionModel()->select(ui->treeView->model()->index(0, 0, ui->treeView->rootIndex()), QItemSelectionModel::Select);
    }
}

void Dialog::on_helpNewsButton_clicked() {
    if (!ui->helpBox->isHidden()) {
        ui->helpBox->hide();
        ui->newsBox->hide();
    } else {
        ui->helpBox->show();
        ui->newsBox->show();
    }
}

void Dialog::keyPressEvent(QKeyEvent* event) {
    switch(event->key()) {
    case Qt::Key_Return:
        event->accept();
        this->on_pushButtonStart_clicked();
        break;
    case Qt::Key_Escape:
        event->accept();
        this->on_pushButtonAbort_clicked();
        break;
    default:
        QDialog::keyPressEvent(event);
        break;
    }
}

void Dialog::iconDownloaded(const QUrl& url, const QIcon&) {
    qDebug() << "Icon downloaded... (" << url << ")";
    // TODO: Check which model(s) contain an entry with this icon
    model_[TAB_RECENT_COURSES]->updateView();
    model_[TAB_ALL_VMS]->updateView();
}

void Dialog::on_leftKey() {
    int i = activeTab_;
    do {
        i = (i - 1 + TAB_COUNT) % TAB_COUNT;
    } while (!tabs_[i]->isEnabled() && i != activeTab_);
    onTabButtonChanged(i);
}

void Dialog::on_rightKey() {
    int i = activeTab_;
    do {
        i = (i + 1) % TAB_COUNT;
    } while (!tabs_[i]->isEnabled() && i != activeTab_);
    onTabButtonChanged(i);
}

/* when the user presses the space key, the current selection in the treeview
 * should be collapsed/expanded. */
void Dialog::on_spaceKey() {
    QModelIndex index = ui->treeView->selectionModel()->currentIndex();
    if (ui->treeView->isExpanded(index)) {
        ui->treeView->collapse(index);
    } else {
        ui->treeView->expand(index);
    }
}

void Dialog::selectFirstElement() {
    QModelIndex root(ui->treeView->rootIndex());
    QModelIndex section(model_[activeTab_]->index(0, 0, root));
    QModelIndex newIndex = QModelIndex(model_[activeTab_]->index(0, 0, section));

    ui->treeView->selectionModel()->setCurrentIndex(newIndex, QItemSelectionModel::Select);

    ui->treeView->setFocus();
}

/* install this filter to the filterEdit to listen for arrow keys */
bool Dialog::eventFilter(QObject*, QEvent *event) {
    if (event->type() == QEvent::KeyPress) {
        autoQuit_ = g_autoQuitSeconds;
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        bool fortv = false;
        if (keyEvent->key() == Qt::Key_Right) {
            on_rightKey();
            fortv = true;
        }
        if (keyEvent->key() == Qt::Key_Left) {
            on_leftKey();
            fortv = true;
        }
        if (keyEvent->key() == Qt::Key_Up) {
            ui->treeView->cursorUp();
            fortv = true;
        }
        if (keyEvent->key() == Qt::Key_Down) {
            ui->treeView->cursorDown();
            fortv = true;
        }
        if (fortv) {
            ui->treeView->setFocus();
            return true;
        }
    } else if (event->type() == QEvent::MouseMove) {
        autoQuit_ = g_autoQuitSeconds;
    }
    return false;
}
void Dialog::checkAutostart() {
    if (!autoStartEntry_.isEmpty()) {
        if (this->selectSession(autoStartEntry_)) {
            this->on_treeView_doubleClicked(ui->treeView->selectionModel()->currentIndex());
        } else {
            QMessageBox::critical(this, "Autostart", QString::fromUtf8("Konnte %1 nicht starten.").arg(autoStartEntry_));
        }
        autoStartEntry_.clear();
        return;
    }
}

void Dialog::showEvent(QShowEvent *e)
{
    QDialog::showEvent(e);
    // Make sure a window manager is running, so any modals or other popups work properly
    QTimer::singleShot(10, []() {
        WindowManager::ensureRunning();
    });
}

QDialog* Dialog::getInstance()
{
    return instance;
}

static bool isProcessRunning(const QString &binary)
{
	bool full = binary.contains('/');
	QDir proc("/proc");
	for (auto entry : proc.entryInfoList(QStringList(), QDir::NoDotAndDotDot | QDir::AllDirs)) {
		if (!entry.isReadable())
			continue;
		QDir dest = QDir(entry.filePath() + "/exe");
		if (!dest.isReadable())
			continue;
		QString wurst = dest.canonicalPath();
		if (wurst.isEmpty())
			continue;
		if (full && wurst == binary)
			return true;
		if (!full && wurst.mid(wurst.lastIndexOf('/') + 1) == binary)
			return true;
	}
	return false;
}

static QDomDocument toDomDocument(const QString& what, const QByteArray& data, const QString& backupFile, const QString& mandatoryChild)
{
    QDomDocument doc;
    if (!data.isEmpty()) {
        if (!doc.setContent(data)) {
            qDebug() << "Downloaded" << what << "XML contains errors.";
        }
    } else {
        qDebug() << "No content downloaded for" << what;
    }
    // No backup file given, just return what we got
    if (backupFile.isEmpty())
        return doc;

    QFile backup(backupFile);
    if (doc.isNull() || !doc.hasChildNodes()) {
        if (backup.open(QFile::ReadOnly)) {
            if (!doc.setContent(&backup)) {
                qDebug() << "Could not load" << what << "backup.";
            }
        }
    }
    if (doc.isNull() || !doc.hasChildNodes())
        return QDomDocument(); // Above methods failed
    if (doc.firstChildElement(mandatoryChild).isNull()) {
        qDebug() << "Downloaded" << what << "xml doesn't contain mandatory root node" << mandatoryChild;
        return QDomDocument();
    }
    if (!backup.isOpen()) {
        // If it were already open we'd have read the backup, so no need to write it out again...
        if (!backup.open(QFile::WriteOnly)) {
            qDebug() << "Cannot open" << what << "backup file" << backupFile << "for writing";
        } else {
            backup.write(data);
        }
    }
    return doc;
}