File: devicepreference.cpp

package info (click to toggle)
phonon 4%3A4.12.0-7
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,380 kB
  • sloc: cpp: 15,009; makefile: 35; sh: 30; awk: 22
file content (989 lines) | stat: -rw-r--r-- 36,736 bytes parent folder | download | duplicates (2)
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
980
981
982
983
984
985
986
987
988
989
/*
    Copyright (C) 2006-2008 Matthias Kretz <kretz@kde.org>
    Copyright (C) 2011 Casian Andrei <skeletk13@gmail.com>
    Copyright (C) 2014-2019 Harald Sitter <sitter@kde.org>

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) version 3.

    This library 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "devicepreference.h"

#include <QDialogButtonBox>
#include <QListWidget>
#include <QLabel>
#include <QMessageBox>
#include <QPointer>
#include <QStandardPaths>

#include <phonon/AudioOutput>
#include <phonon/BackendCapabilities>
#include <phonon/MediaObject>
#include <phonon/VideoWidget>
#include <phonon/globalconfig.h>
#include <phonon/phononnamespace.h>

#ifndef METATYPE_QLIST_INT_DEFINED
#define METATYPE_QLIST_INT_DEFINED
// Want this exactly once, see phonondefs_p.h kcm/devicepreference.cpp
Q_DECLARE_METATYPE(QList<int>)
#endif

namespace Phonon {

/*
 * Lists of categories for every device type
 */
static const Category audioOutCategories[] = {
    NoCategory,
    NotificationCategory,
    MusicCategory,
    VideoCategory,
    CommunicationCategory,
    GameCategory,
    AccessibilityCategory,
};

static const CaptureCategory audioCapCategories[] = {
    NoCaptureCategory,
    CommunicationCaptureCategory,
    RecordingCaptureCategory,
    ControlCaptureCategory
};

static const CaptureCategory videoCapCategories[] = {
    NoCaptureCategory,
    CommunicationCaptureCategory,
    RecordingCaptureCategory,
};

static const int audioOutCategoriesCount = sizeof(audioOutCategories) / sizeof(Category);
static const int audioCapCategoriesCount = sizeof(audioCapCategories) / sizeof(CaptureCategory);
static const int videoCapCategoriesCount = sizeof(videoCapCategories) / sizeof(CaptureCategory);

void operator++(Category &c)
{
    c = static_cast<Category>(1 + static_cast<int>(c));
    //Q_ASSERT(c <= LastCategory);
}

class CategoryItem : public QStandardItem {
public:
    CategoryItem(Category cat)
        : QStandardItem(),
          m_cat(cat),
          m_odtype(AudioOutputDeviceType)
    {
        if (cat == NoCategory) {
            setText(QObject::tr("Audio Playback"));
        } else {
            setText(categoryToString(cat));
        }
    }

    CategoryItem(CaptureCategory cat, ObjectDescriptionType t = AudioCaptureDeviceType)
        : QStandardItem(),
          m_capcat(cat),
          m_odtype(t)
    {
        if (cat == NoCaptureCategory) {
            switch(t) {
            case AudioCaptureDeviceType:
                setText(QObject::tr("Audio Recording"));
                break;
            case VideoCaptureDeviceType:
                setText(QObject::tr("Video Recording"));
                break;
            default:
                setText(QObject::tr("Invalid"));
            }
        } else {
            setText(categoryToString(cat));
        }
    }

    int type() const override { return 1001; }
    Category category() const { return m_cat; }
    CaptureCategory captureCategory() const { return m_capcat; }
    ObjectDescriptionType odtype() const { return m_odtype; }

private:
    Category m_cat;
    CaptureCategory m_capcat;
    ObjectDescriptionType m_odtype;
};

/**
 * Need this to change the colors of the ListView if the Palette changed. With CSS set this won't
 * change automatically
 */
void DevicePreference::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    if (e->type() == QEvent::PaletteChange) {
        deviceList->setStyleSheet(deviceList->styleSheet());
    }
}

DevicePreference::DevicePreference(QWidget *parent)
    : QWidget(parent),
      m_headerModel(0, 1, nullptr),
      m_media(nullptr), m_audioOutput(nullptr), m_videoWidget(nullptr)
{
    setupUi(this);

    // Setup the buttons
    testPlaybackButton->setIcon(QIcon::fromTheme(QStringLiteral("media-playback-start")));
    testPlaybackButton->setEnabled(false);
    testPlaybackButton->setToolTip(tr("Test the selected device"));
    deferButton->setIcon(QIcon::fromTheme(QStringLiteral("go-down")));
    preferButton->setIcon(QIcon::fromTheme(QStringLiteral("go-up")));

    // Configure the device list
    deviceList->setDragDropMode(QAbstractItemView::InternalMove);
    deviceList->setStyleSheet(QStringLiteral("QTreeView {"
                                      "background-color: palette(base);"
                                      "background-image: url(:/phononsettings/listview-background.png);"
                                      "background-position: bottom left;"
                                      "background-attachment: fixed;"
                                      "background-repeat: no-repeat;"
                                      "background-clip: padding;"
                                      "}"));
    deviceList->setAlternatingRowColors(false);

    // The root item for the categories
    QStandardItem *parentItem = m_categoryModel.invisibleRootItem();

    // Audio Output Parent
    QStandardItem *aOutputItem = new CategoryItem(NoCategory);
    m_audioOutputModel[NoCategory] = new AudioOutputDeviceModel(this);
    aOutputItem->setEditable(false);
    aOutputItem->setToolTip(tr("Defines the default ordering of devices which can be overridden by individual categories."));
    parentItem->appendRow(aOutputItem);

    // Audio Capture Parent
    QStandardItem *aCaptureItem = new CategoryItem(NoCaptureCategory, AudioCaptureDeviceType);
    m_audioCaptureModel[NoCaptureCategory] = new AudioCaptureDeviceModel(this);
    aCaptureItem->setEditable(false);
    aCaptureItem->setToolTip(tr("Defines the default ordering of devices which can be overridden by individual categories."));
    parentItem->appendRow(aCaptureItem);

    // Video Capture Parent
    QStandardItem *vCaptureItem = new CategoryItem(NoCaptureCategory, VideoCaptureDeviceType);
    m_videoCaptureModel[NoCaptureCategory] = new VideoCaptureDeviceModel(this);
    vCaptureItem->setEditable(false);
    vCaptureItem->setToolTip(tr("Defines the default ordering of devices which can be overridden by individual categories."));
    parentItem->appendRow(vCaptureItem);

    // Audio Output Children
    parentItem = aOutputItem;
    for (int i = 1; i < audioOutCategoriesCount; ++i) { // i == 1 to skip NoCategory
        m_audioOutputModel[audioOutCategories[i]] = new AudioOutputDeviceModel(this);
        QStandardItem *item = new CategoryItem(audioOutCategories[i]);
        item->setEditable(false);
        parentItem->appendRow(item);
    }

    // Audio Capture Children
    parentItem = aCaptureItem;
    for (int i = 1; i < audioCapCategoriesCount; ++i) { // i == 1 to skip NoCategory
        m_audioCaptureModel[audioCapCategories[i]] = new AudioCaptureDeviceModel(this);
        QStandardItem *item = new CategoryItem(audioCapCategories[i], AudioCaptureDeviceType);
        item->setEditable(false);
        parentItem->appendRow(item);
    }

    // Video Capture Children
    parentItem = vCaptureItem;
    for (int i = 1; i < videoCapCategoriesCount; ++i) { // i == 1 to skip NoCategory
        m_videoCaptureModel[videoCapCategories[i]] = new VideoCaptureDeviceModel(this);
        QStandardItem *item = new CategoryItem(videoCapCategories[i], VideoCaptureDeviceType);
        item->setEditable(false);
        parentItem->appendRow(item);
    }

    // Configure the category tree
    categoryTree->setModel(&m_categoryModel);
    if (categoryTree->header()) {
        categoryTree->header()->hide();
    }
    categoryTree->expandAll();

    connect(categoryTree->selectionModel(), SIGNAL(currentChanged(const QModelIndex &,const QModelIndex &)),
            SLOT(updateDeviceList()));

    // Connect all model data change signals to the changed slot
    for (int i = -1; i <= LastCategory; ++i) {
        connect(m_audioOutputModel[i], SIGNAL(rowsInserted(QModelIndex, int, int)), this, SIGNAL(changed()));
        connect(m_audioOutputModel[i], SIGNAL(rowsRemoved(QModelIndex, int, int)), this, SIGNAL(changed()));
        connect(m_audioOutputModel[i], SIGNAL(layoutChanged()), this, SIGNAL(changed()));
        connect(m_audioOutputModel[i], SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SIGNAL(changed()));
        if (m_audioCaptureModel.contains(i)) {
            connect(m_audioCaptureModel[i], SIGNAL(rowsInserted(QModelIndex, int, int)), this, SIGNAL(changed()));
            connect(m_audioCaptureModel[i], SIGNAL(rowsRemoved(QModelIndex , int, int)), this, SIGNAL(changed()));
            connect(m_audioCaptureModel[i], SIGNAL(layoutChanged()), this, SIGNAL(changed()));
            connect(m_audioCaptureModel[i], SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SIGNAL(changed()));
        }
        if (m_videoCaptureModel.contains(i)) {
            connect(m_videoCaptureModel[i], SIGNAL(rowsInserted(QModelIndex, int, int)), this, SIGNAL(changed()));
            connect(m_videoCaptureModel[i], SIGNAL(rowsRemoved(QModelIndex, int, int)), this, SIGNAL(changed()));
            connect(m_videoCaptureModel[i], SIGNAL(layoutChanged()), this, SIGNAL(changed()));
            connect(m_videoCaptureModel[i], SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SIGNAL(changed()));
        }
    }

    connect(showAdvancedDevicesCheckBox, &QCheckBox::stateChanged, this, &DevicePreference::changed);

    // Connect the signals from Phonon that notify changes in the device lists
    connect(BackendCapabilities::notifier(), SIGNAL(availableAudioOutputDevicesChanged()), SLOT(updateAudioOutputDevices()));
    connect(BackendCapabilities::notifier(), SIGNAL(availableAudioCaptureDevicesChanged()), SLOT(updateAudioCaptureDevices()));
    connect(BackendCapabilities::notifier(), SIGNAL(availableVideoCaptureDevicesChanged()), SLOT(updateVideoCaptureDevices()));
    connect(BackendCapabilities::notifier(), SIGNAL(capabilitiesChanged()), SLOT(updateAudioOutputDevices()));
    connect(BackendCapabilities::notifier(), SIGNAL(capabilitiesChanged()), SLOT(updateAudioCaptureDevices()));
    connect(BackendCapabilities::notifier(), SIGNAL(capabilitiesChanged()), SLOT(updateVideoCaptureDevices()));

    if (!categoryTree->currentIndex().isValid()) {
        categoryTree->setCurrentIndex(m_categoryModel.index(1, 0, m_categoryModel.index(0, 0)));
    }
}

DevicePreference::~DevicePreference()
{
    // Ensure that the video widget is destroyed, if it remains active
    delete m_videoWidget;
}

void DevicePreference::updateDeviceList()
{
    // Temporarily disconnect the device list selection model
    if (deviceList->selectionModel()) {
        disconnect(deviceList->selectionModel(),
                   SIGNAL(currentRowChanged(const QModelIndex &,const QModelIndex &)),
                   this, SLOT(updateButtonsEnabled()));
    }

    // Get the current selected category item
    QStandardItem *currentItem = m_categoryModel.itemFromIndex(categoryTree->currentIndex());
    if (currentItem && currentItem->type() == 1001) {
        CategoryItem *catItem = static_cast<CategoryItem *>(currentItem);
        bool cap = catItem->odtype() != AudioOutputDeviceType;
        const Category cat = catItem->category();
        const CaptureCategory capcat = catItem->captureCategory();

        // Update the device list, by setting it's model to the one for the corresponding category
        switch (catItem->odtype()) {
        case AudioOutputDeviceType:
            deviceList->setModel(m_audioOutputModel[cat]);
            break;
        case AudioCaptureDeviceType:
            deviceList->setModel(m_audioCaptureModel[capcat]);
            break;
        case VideoCaptureDeviceType:
            deviceList->setModel(m_videoCaptureModel[capcat]);
            break;
        default: ;
        }

        // Update the header
        if (cap ? capcat == NoCaptureCategory : cat == NoCategory) {
            switch (catItem->odtype()) {
            case AudioOutputDeviceType:
                m_headerModel.setHeaderData(0, Qt::Horizontal, tr("Default Audio Playback Device Preference"), Qt::DisplayRole);
                break;
            case AudioCaptureDeviceType:
                m_headerModel.setHeaderData(0, Qt::Horizontal, tr("Default Audio Recording Device Preference"), Qt::DisplayRole);
                break;
            case VideoCaptureDeviceType:
                m_headerModel.setHeaderData(0, Qt::Horizontal, tr("Default Video Recording Device Preference"), Qt::DisplayRole);
                break;
            default: ;
            }
        } else {
            switch (catItem->odtype()) {
            case AudioOutputDeviceType:
                m_headerModel.setHeaderData(0, Qt::Horizontal, tr("Audio Playback Device Preference for the '%1' Category").arg(
                                                                    categoryToString(cat)), Qt::DisplayRole);
                break;
            case AudioCaptureDeviceType:
                m_headerModel.setHeaderData(0, Qt::Horizontal, tr("Audio Recording Device Preference for the '%1' Category").arg(
                                                                    categoryToString(capcat)), Qt::DisplayRole);
                break;
            case VideoCaptureDeviceType:
                m_headerModel.setHeaderData(0, Qt::Horizontal, tr("Video Recording Device Preference for the '%1' Category ").arg(
                                                                    categoryToString(capcat)), Qt::DisplayRole);
                break;
            default: ;
            }
        }
    } else {
        // No valid category selected
        m_headerModel.setHeaderData(0, Qt::Horizontal, QString(), Qt::DisplayRole);
        deviceList->setModel(nullptr);
    }

    // Update the header, the buttons enabled state
    deviceList->header()->setModel(&m_headerModel);
    updateButtonsEnabled();

    // Reconnect the device list selection model
    if (deviceList->selectionModel()) {
        connect(deviceList->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex &,const QModelIndex &)),
                this, SLOT(updateButtonsEnabled()));
    }

    deviceList->resizeColumnToContents(0);
}

void DevicePreference::updateAudioCaptureDevices()
{
    const QList<AudioCaptureDevice> list = availableAudioCaptureDevices();
    QHash<int, AudioCaptureDevice> hash;
    foreach (const AudioCaptureDevice &dev, list) {
        hash.insert(dev.index(), dev);
    }

    for (int catIndex = 0; catIndex < audioCapCategoriesCount; ++ catIndex) {
        const int i = audioCapCategories[catIndex];
        AudioCaptureDeviceModel *model = m_audioCaptureModel.value(i);
        Q_ASSERT(model);

        QHash<int, AudioCaptureDevice> hashCopy(hash);
        QList<AudioCaptureDevice> orderedList;

        if (model->rowCount() > 0) {
            QList<int> order = model->tupleIndexOrder();
            foreach (int idx, order) {
                if (hashCopy.contains(idx)) {
                    orderedList << hashCopy.take(idx);
                }
            }

            if (hashCopy.size() > 1) {
                // keep the order of the original list
                foreach (const AudioCaptureDevice &dev, list) {
                    if (hashCopy.contains(dev.index())) {
                        orderedList << hashCopy.take(dev.index());
                    }
                }
            } else if (hashCopy.size() == 1) {
                orderedList += hashCopy.values();
            }

            model->setModelData(orderedList);
        } else {
            model->setModelData(list);
        }
    }

    deviceList->resizeColumnToContents(0);
}

void DevicePreference::updateVideoCaptureDevices()
{
    const QList<VideoCaptureDevice> list = availableVideoCaptureDevices();
    QHash<int, VideoCaptureDevice> hash;
    foreach (const VideoCaptureDevice &dev, list) {
        hash.insert(dev.index(), dev);
    }

    for (int catIndex = 0; catIndex < videoCapCategoriesCount; ++ catIndex) {
        const int i = videoCapCategories[catIndex];
        VideoCaptureDeviceModel *model = m_videoCaptureModel.value(i);
        Q_ASSERT(model);

        QHash<int, VideoCaptureDevice> hashCopy(hash);
        QList<VideoCaptureDevice> orderedList;

        if (model->rowCount() > 0) {
            QList<int> order = model->tupleIndexOrder();
            foreach (int idx, order) {
                if (hashCopy.contains(idx)) {
                    orderedList << hashCopy.take(idx);
                }
            }

            if (hashCopy.size() > 1) {
                // keep the order of the original list
                foreach (const VideoCaptureDevice &dev, list) {
                    if (hashCopy.contains(dev.index())) {
                        orderedList << hashCopy.take(dev.index());
                    }
                }
            } else if (hashCopy.size() == 1) {
                orderedList += hashCopy.values();
            }

            model->setModelData(orderedList);
        } else {
            model->setModelData(list);
        }
    }

    deviceList->resizeColumnToContents(0);
}

void DevicePreference::updateAudioOutputDevices()
{
    const QList<AudioOutputDevice> list = availableAudioOutputDevices();
    QHash<int, AudioOutputDevice> hash;
    foreach (const AudioOutputDevice &dev, list) {
        hash.insert(dev.index(), dev);
    }

    for (int catIndex = 0; catIndex < audioOutCategoriesCount; ++ catIndex) {
        const int i = audioOutCategories[catIndex];
        AudioOutputDeviceModel *model = m_audioOutputModel.value(i);
        Q_ASSERT(model);

        QHash<int, AudioOutputDevice> hashCopy(hash);
        QList<AudioOutputDevice> orderedList;

        if (model->rowCount() > 0) {
            QList<int> order = model->tupleIndexOrder();
            foreach (int idx, order) {
                if (hashCopy.contains(idx)) {
                    orderedList << hashCopy.take(idx);
                }
            }

            if (hashCopy.size() > 1) {
                // keep the order of the original list
                foreach (const AudioOutputDevice &dev, list) {
                    if (hashCopy.contains(dev.index())) {
                        orderedList << hashCopy.take(dev.index());
                    }
                }
            } else if (hashCopy.size() == 1) {
                orderedList += hashCopy.values();
            }

            model->setModelData(orderedList);
        } else {
            model->setModelData(list);
        }
    }

    deviceList->resizeColumnToContents(0);
}

QList<AudioOutputDevice> DevicePreference::availableAudioOutputDevices() const
{
    return BackendCapabilities::availableAudioOutputDevices();
}

QList<AudioCaptureDevice> DevicePreference::availableAudioCaptureDevices() const
{
#ifndef PHONON_NO_AUDIOCAPTURE
    return BackendCapabilities::availableAudioCaptureDevices();
#else
    return QList<AudioCaptureDevice>();
#endif
}

QList<VideoCaptureDevice> DevicePreference::availableVideoCaptureDevices() const
{
#ifndef PHONON_NO_VIDEOCAPTURE
    return BackendCapabilities::availableVideoCaptureDevices();
#else
    return QList<VideoCaptureDevice>();
#endif
}

void DevicePreference::load()
{
    showAdvancedDevicesCheckBox->setChecked(!GlobalConfig().hideAdvancedDevices());
    loadCategoryDevices();
}

void DevicePreference::loadCategoryDevices()
{
    // "Load" the settings from the backend.
    for (int i = 0; i < audioOutCategoriesCount; ++ i) {
        const Category cat = audioOutCategories[i];
        QList<AudioOutputDevice> list;
        const QList<int> deviceIndexes = GlobalConfig().audioOutputDeviceListFor(cat);
        foreach (int i, deviceIndexes) {
            list.append(AudioOutputDevice::fromIndex(i));
        }

        m_audioOutputModel[cat]->setModelData(list);
    }

#ifndef PHONON_NO_AUDIOCAPTURE
    for (int i = 0; i < audioCapCategoriesCount; ++ i) {
        const CaptureCategory cat = audioCapCategories[i];
        QList<AudioCaptureDevice> list;
        const QList<int> deviceIndexes = GlobalConfig().audioCaptureDeviceListFor(cat);
        foreach (int i, deviceIndexes) {
            list.append(AudioCaptureDevice::fromIndex(i));
        }

        m_audioCaptureModel[cat]->setModelData(list);
    }
#endif

#ifndef PHONON_NO_VIDEOCAPTURE
    for (int i = 0; i < videoCapCategoriesCount; ++ i) {
        const CaptureCategory cat = videoCapCategories[i];
        QList<VideoCaptureDevice> list;
        const QList<int> deviceIndexes = GlobalConfig().videoCaptureDeviceListFor(cat);
        foreach (int i, deviceIndexes) {
            list.append(VideoCaptureDevice::fromIndex(i));
        }

        m_videoCaptureModel[cat]->setModelData(list);
    }
#endif

    deviceList->resizeColumnToContents(0);
}

void DevicePreference::save()
{
    for (int i = 0; i < audioOutCategoriesCount; ++i) {
        const Category cat = audioOutCategories[i];
        Q_ASSERT(m_audioOutputModel.value(cat));
        const QList<int> order = m_audioOutputModel.value(cat)->tupleIndexOrder();
        GlobalConfig().setAudioOutputDeviceListFor(cat, order);
    }

#ifndef PHONON_NO_AUDIOCAPTURE
    for (int i = 0; i < audioCapCategoriesCount; ++i) {
        const CaptureCategory cat = audioCapCategories[i];
        Q_ASSERT(m_audioCaptureModel.value(cat));
        const QList<int> order = m_audioCaptureModel.value(cat)->tupleIndexOrder();
        GlobalConfig().setAudioCaptureDeviceListFor(cat, order);
    }
#endif

#ifndef PHONON_NO_VIDEOCAPTURE
    for (int i = 0; i < videoCapCategoriesCount; ++i) {
        const CaptureCategory cat = videoCapCategories[i];
        Q_ASSERT(m_videoCaptureModel.value(cat));
        const QList<int> order = m_videoCaptureModel.value(cat)->tupleIndexOrder();
        GlobalConfig().setVideoCaptureDeviceListFor(cat, order);
    }
#endif
}

void DevicePreference::defaults()
{
    {
        const QList<AudioOutputDevice> list = availableAudioOutputDevices();
        for (int i = 0; i < audioOutCategoriesCount; ++i) {
            m_audioOutputModel[audioOutCategories[i]]->setModelData(list);
        }
    }
    {
        const QList<AudioCaptureDevice> list = availableAudioCaptureDevices();
        for (int i = 0; i < audioCapCategoriesCount; ++i) {
            m_audioCaptureModel[audioCapCategories[i]]->setModelData(list);
        }
    }
    {
        const QList<VideoCaptureDevice> list = availableVideoCaptureDevices();
        for (int i = 0; i < videoCapCategoriesCount; ++i) {
            m_videoCaptureModel[videoCapCategories[i]]->setModelData(list);
        }
    }

    /*
     * Save this list (that contains even hidden devices) to GlobaConfig, and then
     * load them back. All devices that should be hidden will be hidden
     */
    save();
    loadCategoryDevices();

    deviceList->resizeColumnToContents(0);
}

void DevicePreference::pulseAudioEnabled()
{
    showAdvancedDevicesContainer->removeItem(showAdvancedDevicesSpacer);
    delete showAdvancedDevicesSpacer;
    showAdvancedDevicesCheckBox->setVisible(false);
}

void DevicePreference::on_preferButton_clicked()
{
    QAbstractItemModel *model = deviceList->model();
    {
        AudioOutputDeviceModel *deviceModel = dynamic_cast<AudioOutputDeviceModel *>(model);
        if (deviceModel) {
            deviceModel->moveUp(deviceList->currentIndex());
            updateButtonsEnabled();
            emit changed();
        }
    }
    {
        AudioCaptureDeviceModel *deviceModel = dynamic_cast<AudioCaptureDeviceModel *>(model);
        if (deviceModel) {
            deviceModel->moveUp(deviceList->currentIndex());
            updateButtonsEnabled();
            emit changed();
        }
    }
    {
        VideoCaptureDeviceModel *deviceModel = dynamic_cast<VideoCaptureDeviceModel *>(model);
        if (deviceModel) {
            deviceModel->moveUp(deviceList->currentIndex());
            updateButtonsEnabled();
            emit changed();
        }
    }
}

void DevicePreference::on_deferButton_clicked()
{
    QAbstractItemModel *model = deviceList->model();
    {
        AudioOutputDeviceModel *deviceModel = dynamic_cast<AudioOutputDeviceModel *>(model);
        if (deviceModel) {
            deviceModel->moveDown(deviceList->currentIndex());
            updateButtonsEnabled();
            emit changed();
        }
    }
    {
        AudioCaptureDeviceModel *deviceModel = dynamic_cast<AudioCaptureDeviceModel *>(model);
        if (deviceModel) {
            deviceModel->moveDown(deviceList->currentIndex());
            updateButtonsEnabled();
            emit changed();
        }
    }
    {
        VideoCaptureDeviceModel *deviceModel = dynamic_cast<VideoCaptureDeviceModel *>(model);
        if (deviceModel) {
            deviceModel->moveDown(deviceList->currentIndex());
            updateButtonsEnabled();
            emit changed();
        }
    }
}

DevicePreference::DeviceType DevicePreference::shownModelType() const
{
    const QStandardItem *item = m_categoryModel.itemFromIndex(categoryTree->currentIndex());
    if (!item)
        return dtInvalidDevice;
    Q_ASSERT(item->type() == 1001);

    const CategoryItem *catItem = static_cast<const CategoryItem *>(item);
    if (!catItem)
        return dtInvalidDevice;

    switch (catItem->odtype()) {
    case AudioOutputDeviceType:
        return dtAudioOutput;
    case AudioCaptureDeviceType:
        return dtAudioCapture;
    case VideoCaptureDeviceType:
        return dtVideoCapture;
    default:
        return dtInvalidDevice;
    }
}

void DevicePreference::on_applyPreferencesButton_clicked()
{
    const QModelIndex idx = categoryTree->currentIndex();
    const QStandardItem *item = m_categoryModel.itemFromIndex(idx);
    if (!item)
        return;
    Q_ASSERT(item->type() == 1001);

    const CategoryItem *catItem = static_cast<const CategoryItem *>(item);

    QList<AudioOutputDevice> aoPreferredList;
    QList<AudioCaptureDevice> acPreferredList;
    QList<VideoCaptureDevice> vcPreferredList;
    const Category *categoryList = nullptr;
    const CaptureCategory *capCategoryList = nullptr;
    int categoryListCount;
    int catIndex;
    bool cap = false;

    switch (catItem->odtype()) {
    case AudioOutputDeviceType:
        aoPreferredList = m_audioOutputModel.value(catItem->category())->modelData();
        categoryList = audioOutCategories;
        categoryListCount = audioOutCategoriesCount;
        cap = false;
        break;

    case AudioCaptureDeviceType:
        acPreferredList = m_audioCaptureModel.value(catItem->captureCategory())->modelData();
        capCategoryList = audioCapCategories;
        categoryListCount = audioCapCategoriesCount;
        cap = true;
        break;

    case VideoCaptureDeviceType:
        vcPreferredList = m_videoCaptureModel.value(catItem->captureCategory())->modelData();
        capCategoryList = videoCapCategories;
        categoryListCount = videoCapCategoriesCount;
        cap = true;
        break;

    default:
        return;
    }

    QPointer<QDialog> dialog = new QDialog(this);

    QLabel *label = new QLabel(dialog);
    label->setText(tr("Apply the currently shown device preference list to the following other "
                        "audio playback categories:"));
    label->setWordWrap(true);

    QListWidget *list = new QListWidget(dialog);

    for (catIndex = 0; catIndex < categoryListCount; catIndex ++) {
        Category cat = cap ? NoCategory : categoryList[catIndex];
        CaptureCategory capcat = cap ? capCategoryList[catIndex] : NoCaptureCategory;

        QListWidgetItem *item = nullptr;
        if (cap) {
            if (capcat == NoCaptureCategory) {
                item = new QListWidgetItem(tr("Default/Unspecified Category"), list, capcat);
            } else {
                item = new QListWidgetItem(categoryToString(capcat), list, capcat);
            }
        } else {
            if (cat == NoCategory) {
                item = new QListWidgetItem(tr("Default/Unspecified Category"), list, cat);
            } else {
                item = new QListWidgetItem(categoryToString(cat), list, cat);
            }
        }

        item->setCheckState(Qt::Checked);
        if (cat == catItem->category()) {
            item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
        }
    }

    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok
                                                       | QDialogButtonBox::Cancel, dialog);
    connect(buttonBox, &QDialogButtonBox::accepted, dialog.data(), &QDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, dialog.data(), &QDialog::reject);

    QVBoxLayout *layout = new QVBoxLayout(dialog);
    layout->addWidget(label);
    layout->addWidget(list);
    layout->addWidget(buttonBox);

    switch (dialog->exec()) {
    case QDialog::Accepted:
        for (catIndex = 0; catIndex < categoryListCount; catIndex ++) {
            Category cat = cap ? NoCategory : categoryList[catIndex];
            CaptureCategory capcat = cap ? capCategoryList[catIndex] : NoCaptureCategory;

            if (cap ? capcat != catItem->captureCategory() : cat != catItem->category()) {
                QListWidgetItem *item = list->item(catIndex);
                Q_ASSERT(item->type() == cap ? (int) capcat : (int) cat);
                if (item->checkState() == Qt::Checked) {
                    switch (catItem->odtype()) {
                    case AudioOutputDeviceType:
                        m_audioOutputModel.value(cat)->setModelData(aoPreferredList);
                        break;

                    case AudioCaptureDeviceType:
                        m_audioCaptureModel.value(capcat)->setModelData(acPreferredList);
                        break;

                    case VideoCaptureDeviceType:
                        m_videoCaptureModel.value(capcat)->setModelData(vcPreferredList);
                        break;

                    default: ;
                    }
                }
            }
        }

        emit changed();
        break;

    case QDialog::Rejected:
        // nothing to do
        break;
    }

    delete dialog;
}

void DevicePreference::on_showAdvancedDevicesCheckBox_toggled()
{
    // In order to get the right list from the backend, we need to update the settings now
    // before calling availableAudio{Output,Capture}Devices()
    GlobalConfig().setHideAdvancedDevices(!showAdvancedDevicesCheckBox->isChecked());
    loadCategoryDevices();
}

void DevicePreference::on_testPlaybackButton_toggled(bool down)
{
    if (down) {
        QModelIndex idx = deviceList->currentIndex();
        if (!idx.isValid()) {
            return;
        }

        // Shouldn't happen, but better to be on the safe side
        if (m_testingType != dtInvalidDevice) {
            delete m_media;
            m_media = nullptr;
            delete m_audioOutput;
            m_audioOutput = nullptr;
            delete m_videoWidget;
            m_videoWidget = nullptr;
        }

        // Setup the Phonon objects according to the testing type
        m_testingType = shownModelType();
        switch (m_testingType) {
        case dtAudioOutput: {
            // Create an audio output with the selected device
            m_media = new MediaObject(this);
            const AudioOutputDeviceModel *model = static_cast<const AudioOutputDeviceModel *>(idx.model());
            const AudioOutputDevice &device = model->modelData(idx);
            m_audioOutput = new AudioOutput(this);
            if (!m_audioOutput->setOutputDevice(device)) {
                QMessageBox::critical(this, tr("Failed to set the selected audio output device"),  tr("Failed to set the selected audio output device"));
                break;
            }

            // Just to be very sure that nothing messes our test sound up
            m_audioOutput->setVolume(1.0);
            m_audioOutput->setMuted(false);

            createPath(m_media, m_audioOutput);
            static QUrl testUrl = QUrl::fromLocalFile(QStandardPaths::locate(
                                                          QStandardPaths::GenericDataLocation,
                                                          QStringLiteral("sounds/Oxygen-Sys-Log-In.ogg")));
            m_media->setCurrentSource(testUrl);
            connect(m_media, &MediaObject::finished, testPlaybackButton, &QToolButton::toggle);

            break;
        }

#ifndef PHONON_NO_AUDIOCAPTURE
        case dtAudioCapture: {
            // Create a media object and an audio output
            m_media = new MediaObject(this);
            m_audioOutput = new AudioOutput(NoCategory, this);

            // Just to be very sure that nothing messes our test sound up
            m_audioOutput->setVolume(1.0);
            m_audioOutput->setMuted(false);

            // Try to create a path
            if (!createPath(m_media, m_audioOutput).isValid()) {
                QMessageBox::critical(this, tr("Your backend may not support audio recording"), tr("Your backend may not support audio recording"));
                break;
            }

            // Determine the selected device
            const AudioCaptureDeviceModel *model = static_cast<const AudioCaptureDeviceModel *>(idx.model());
            const AudioCaptureDevice &device = model->modelData(idx);
            m_media->setCurrentSource(device);

            break;
        }
#endif

#ifndef PHONON_NO_VIDEOCAPTURE
        case dtVideoCapture: {
            // Create a media object and a video output
            m_media = new MediaObject(this);
            m_videoWidget = new VideoWidget(nullptr);

            // Try to create a path
            if (!createPath(m_media, m_videoWidget).isValid()) {
                QMessageBox::critical(this, tr("Your backend may not support video recording"), tr("Your backend may not support video recording"));
                break;
            }

            // Determine the selected device
            const VideoCaptureDeviceModel *model = static_cast<const VideoCaptureDeviceModel *>(idx.model());
            const VideoCaptureDevice &device = model->modelData(idx);
            m_media->setCurrentSource(device);

            // Set up the testing video widget
            m_videoWidget->setWindowTitle(tr("Testing %1").arg(device.name()));
            m_videoWidget->setWindowFlags(Qt::WindowStaysOnTopHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint);
            if (device.property("icon").canConvert(QVariant::String))
                m_videoWidget->setWindowIcon(QIcon::fromTheme(device.property("icon").toString()));
            m_videoWidget->move(QCursor::pos() - QPoint(250, 295));
            m_videoWidget->resize(320, 240);
            m_videoWidget->show();

            break;
        }
#endif

        default:
            return;
        }

        m_media->play();
    } else {
        // Uninitialize the Phonon objects according to the testing type
        switch (m_testingType) {
        case dtAudioOutput:
            disconnect(m_media, &MediaObject::finished, testPlaybackButton, &QToolButton::toggle);
            delete m_media;
            delete m_audioOutput;
            break;

        case dtAudioCapture:
            delete m_media;
            delete m_audioOutput;
            break;

        case dtVideoCapture:
            delete m_media;
            delete m_videoWidget;
            break;

        default:
            return;
        }

        m_media = nullptr;
        m_videoWidget = nullptr;
        m_audioOutput = nullptr;
        m_testingType = dtInvalidDevice;
    }
}

void DevicePreference::updateButtonsEnabled()
{
    if (deviceList->model()) {
        QModelIndex idx = deviceList->currentIndex();
        preferButton->setEnabled(idx.isValid() && idx.row() > 0);
        deferButton->setEnabled(idx.isValid() && idx.row() < deviceList->model()->rowCount() - 1);
        testPlaybackButton->setEnabled(idx.isValid() && (idx.flags() & Qt::ItemIsEnabled));
    } else {
        preferButton->setEnabled(false);
        deferButton->setEnabled(false);
        testPlaybackButton->setEnabled(false);
    }
}

} // Phonon namespace

#include "moc_devicepreference.cpp"