filechooser.cpp 22.8 KB
Newer Older
Jan Grulich's avatar
Jan Grulich committed
1
/*
2
 * Copyright © 2016-2018 Red Hat, Inc
Jan Grulich's avatar
Jan Grulich committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors:
 *       Jan Grulich <jgrulich@redhat.com>
 */

#include "filechooser.h"
22
#include "utils.h"
Jan Grulich's avatar
Jan Grulich committed
23

24
#include <QDialogButtonBox>
25
#include <QDBusMetaType>
26
#include <QDBusArgument>
27
#include <QLabel>
Jan Grulich's avatar
Jan Grulich committed
28
#include <QLoggingCategory>
29
#include <QFile>
30
#include <QGridLayout>
31
32
33
#include <QPushButton>
#include <QVBoxLayout>
#include <QUrl>
34
35
#include <QQmlApplicationEngine>

36

Jan Grulich's avatar
Jan Grulich committed
37
#include <KLocalizedString>
38
#include <KFileFilterCombo>
39
#include <KFileWidget>
Jan Grulich's avatar
Jan Grulich committed
40

41
42
#include <mobilefiledialog.h>

Jan Grulich's avatar
Jan Grulich committed
43
Q_LOGGING_CATEGORY(XdgDesktopPortalKdeFileChooser, "xdp-kde-file-chooser")
Jan Grulich's avatar
Jan Grulich committed
44

45
// Keep in sync with qflatpakfiledialog from flatpak-platform-plugin
46
47
48
49
Q_DECLARE_METATYPE(FileChooserPortal::Filter)
Q_DECLARE_METATYPE(FileChooserPortal::Filters)
Q_DECLARE_METATYPE(FileChooserPortal::FilterList)
Q_DECLARE_METATYPE(FileChooserPortal::FilterListList)
50
51
52
53
54
// used for options - choices
Q_DECLARE_METATYPE(FileChooserPortal::Choice)
Q_DECLARE_METATYPE(FileChooserPortal::Choices)
Q_DECLARE_METATYPE(FileChooserPortal::Option)
Q_DECLARE_METATYPE(FileChooserPortal::OptionList)
55

56
QDBusArgument &operator << (QDBusArgument &arg, const FileChooserPortal::Filter &filter)
57
58
59
60
61
62
63
{
    arg.beginStructure();
    arg << filter.type << filter.filterString;
    arg.endStructure();
    return arg;
}

64
const QDBusArgument &operator >> (const QDBusArgument &arg, FileChooserPortal::Filter &filter)
65
66
67
68
69
70
71
72
73
74
75
76
{
    uint type;
    QString filterString;
    arg.beginStructure();
    arg >> type >> filterString;
    filter.type = type;
    filter.filterString = filterString;
    arg.endStructure();

    return arg;
}

77
QDBusArgument &operator << (QDBusArgument &arg, const FileChooserPortal::FilterList &filterList)
78
79
80
81
82
83
84
{
    arg.beginStructure();
    arg << filterList.userVisibleName << filterList.filters;
    arg.endStructure();
    return arg;
}

85
const QDBusArgument &operator >> (const QDBusArgument &arg, FileChooserPortal::FilterList &filterList)
86
87
{
    QString userVisibleName;
88
    FileChooserPortal::Filters filters;
89
90
91
92
93
94
95
96
    arg.beginStructure();
    arg >> userVisibleName >> filters;
    filterList.userVisibleName = userVisibleName;
    filterList.filters = filters;
    arg.endStructure();

    return arg;
}
Jan Grulich's avatar
Jan Grulich committed
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
QDBusArgument &operator << (QDBusArgument &arg, const FileChooserPortal::Choice &choice)
{
    arg.beginStructure();
    arg << choice.id << choice.value;
    arg.endStructure();
    return arg;
}

const QDBusArgument &operator >> (const QDBusArgument &arg, FileChooserPortal::Choice &choice)
{
    QString id;
    QString value;
    arg.beginStructure();
    arg >> id >> value;
    choice.id = id;
    choice.value = value;
    arg.endStructure();
    return arg;
}

QDBusArgument &operator << (QDBusArgument &arg, const FileChooserPortal::Option &option)
{
    arg.beginStructure();
    arg << option.id << option.label << option.choices << option.initialChoiceId;
    arg.endStructure();
    return arg;
}

const QDBusArgument &operator >> (const QDBusArgument &arg, FileChooserPortal::Option &option)
{
    QString id;
    QString label;
    FileChooserPortal::Choices choices;
    QString initialChoiceId;
    arg.beginStructure();
    arg >> id >> label >> choices >> initialChoiceId;
    option.id = id;
    option.label = label;
    option.choices = choices;
    option.initialChoiceId = initialChoiceId;
    arg.endStructure();
    return arg;
}

142
143
144
145
146
147
148
149
150
151
FileDialog::FileDialog(QDialog *parent, Qt::WindowFlags flags)
    : QDialog(parent, flags)
    , m_fileWidget(new KFileWidget(QUrl(), this))
{
    setLayout(new QVBoxLayout);
    layout()->addWidget(m_fileWidget);

    m_buttons = new QDialogButtonBox(this);
    m_buttons->addButton(m_fileWidget->okButton(), QDialogButtonBox::AcceptRole);
    m_buttons->addButton(m_fileWidget->cancelButton(), QDialogButtonBox::RejectRole);
Laurent Montel's avatar
Laurent Montel committed
152
153
154
155
156
    connect(m_buttons, &QDialogButtonBox::rejected, m_fileWidget, &KFileWidget::slotCancel);
    connect(m_fileWidget->okButton(), &QAbstractButton::clicked, m_fileWidget, &KFileWidget::slotOk);
    connect(m_fileWidget, &KFileWidget::accepted, m_fileWidget, &KFileWidget::accept);
    connect(m_fileWidget, &KFileWidget::accepted, this, &QDialog::accept);
    connect(m_fileWidget->cancelButton(), &QAbstractButton::clicked, this, &QDialog::reject);
157
158
159
160
161
162
163
    layout()->addWidget(m_buttons);
}

FileDialog::~FileDialog()
{
}

164
165
FileChooserPortal::FileChooserPortal(QObject *parent)
    : QDBusAbstractAdaptor(parent)
166
    , m_mobileFileDialog(nullptr)
Jan Grulich's avatar
Jan Grulich committed
167
{
168
169
170
171
    qDBusRegisterMetaType<Filter>();
    qDBusRegisterMetaType<Filters>();
    qDBusRegisterMetaType<FilterList>();
    qDBusRegisterMetaType<FilterListList>();
172
173
174
175
    qDBusRegisterMetaType<Choice>();
    qDBusRegisterMetaType<Choices>();
    qDBusRegisterMetaType<Option>();
    qDBusRegisterMetaType<OptionList>();
Jan Grulich's avatar
Jan Grulich committed
176
177
}

178
FileChooserPortal::~FileChooserPortal()
Jan Grulich's avatar
Jan Grulich committed
179
180
181
{
}

182
uint FileChooserPortal::OpenFile(const QDBusObjectPath &handle,
Jan Grulich's avatar
Jan Grulich committed
183
184
185
186
187
188
189
190
191
192
193
194
195
196
                           const QString &app_id,
                           const QString &parent_window,
                           const QString &title,
                           const QVariantMap &options,
                           QVariantMap &results)
{
    Q_UNUSED(app_id);

    qCDebug(XdgDesktopPortalKdeFileChooser) << "OpenFile called with parameters:";
    qCDebug(XdgDesktopPortalKdeFileChooser) << "    handle: " << handle.path();
    qCDebug(XdgDesktopPortalKdeFileChooser) << "    parent_window: " << parent_window;
    qCDebug(XdgDesktopPortalKdeFileChooser) << "    title: " << title;
    qCDebug(XdgDesktopPortalKdeFileChooser) << "    options: " << options;

197
    bool directory = false;
Jan Grulich's avatar
Jan Grulich committed
198
199
    bool modalDialog = true;
    bool multipleFiles = false;
200
201
    QStringList nameFilters;
    QStringList mimeTypeFilters;
202
203
    // mapping between filter strings and actual filters
    QMap<QString, FilterList> allFilters;
204

205
    const QString acceptLabel = ExtractAcceptLabel(options);
Jan Grulich's avatar
Jan Grulich committed
206

Laurent Montel's avatar
Laurent Montel committed
207
208
    if (options.contains(QStringLiteral("modal"))) {
        modalDialog = options.value(QStringLiteral("modal")).toBool();
Jan Grulich's avatar
Jan Grulich committed
209
210
    }

Laurent Montel's avatar
Laurent Montel committed
211
212
    if (options.contains(QStringLiteral("multiple"))) {
        multipleFiles = options.value(QStringLiteral("multiple")).toBool();
213
214
    }

215
216
217
218
    if (options.contains(QStringLiteral("directory"))) {
        directory = options.value(QStringLiteral("directory")).toBool();
    }

219
    ExtractFilters(options, nameFilters, mimeTypeFilters, allFilters);
Jan Grulich's avatar
Jan Grulich committed
220

221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
    if (options.contains(QStringLiteral("current_filter"))) {
        FilterList filterList = qdbus_cast<FilterList>(options.value(QStringLiteral("current_filter")));
        if (filterList.filters.size() == 1) {
            // make the relevant entry the first one in the list of filters,
            // since that is the one that gets preselected by KFileWidget
            Filter filterStruct = filterList.filters.at(0);
            if (filterStruct.type == 0) {
                QString nameFilter = QStringLiteral("%1|%2").arg(filterStruct.filterString).arg(filterList.userVisibleName);
                nameFilters.removeAll(nameFilter);
                nameFilters.push_front(nameFilter);
            } else {
                mimeTypeFilters.removeAll(filterStruct.filterString);
                mimeTypeFilters.push_front(filterStruct.filterString);
            }
        } else {
            qCDebug(XdgDesktopPortalKdeFileChooser) << "Ignoring 'current_filter' parameter with 0 or multiple filters specified.";
        }
    }

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
    if (isMobile()) {
        if (!m_mobileFileDialog) {
            qCDebug(XdgDesktopPortalKdeFileChooser) << "Creating file dialog";
            m_mobileFileDialog = new MobileFileDialog(this);
        }

        m_mobileFileDialog->setTitle(title);

        // Always true when we are opening a file
        m_mobileFileDialog->setSelectExisting(true);

        m_mobileFileDialog->setSelectFolder(directory);

        // currentName: not implemented

        if (!acceptLabel.isEmpty()) {
            m_mobileFileDialog->setAcceptLabel(acceptLabel);
        }

        if (!nameFilters.isEmpty()) {
            m_mobileFileDialog->setNameFilters(nameFilters);
        }

        if (!mimeTypeFilters.isEmpty()) {
            m_mobileFileDialog->setMimeTypeFilters(mimeTypeFilters);
        }

        uint retCode = m_mobileFileDialog->exec();

        results.insert(QStringLiteral("uris"), m_mobileFileDialog->results());

        return retCode;
    }

    // for handling of options - choices
    QScopedPointer<QWidget> optionsWidget;
    // to store IDs for choices along with corresponding comboboxes/checkboxes
    QMap<QString, QCheckBox*> checkboxes;
    QMap<QString, QComboBox*> comboboxes;

280
281
282
283
284
    if (options.contains(QStringLiteral("choices"))) {
        OptionList optionList = qdbus_cast<OptionList>(options.value(QStringLiteral("choices")));
        optionsWidget.reset(CreateChoiceControls(optionList, checkboxes, comboboxes));
    }

285
    QScopedPointer<FileDialog, QScopedPointerDeleteLater> fileDialog(new FileDialog());
286
    Utils::setParentWindow(fileDialog.data(), parent_window);
Jan Grulich's avatar
Jan Grulich committed
287
288
    fileDialog->setWindowTitle(title);
    fileDialog->setModal(modalDialog);
289
290
    KFile::Mode mode = directory ? KFile::Mode::Directory : multipleFiles ? KFile::Mode::Files : KFile::Mode::File;
    fileDialog->m_fileWidget->setMode(mode | KFile::Mode::ExistingOnly);
291
    fileDialog->m_fileWidget->okButton()->setText(!acceptLabel.isEmpty() ? acceptLabel : i18n("Open"));
Jan Grulich's avatar
Jan Grulich committed
292

293

294
    bool bMimeFilters = false;
295
    if (!mimeTypeFilters.isEmpty()) {
296
        fileDialog->m_fileWidget->setMimeFilter(mimeTypeFilters);
297
298
299
        bMimeFilters = true;
    } else if (!nameFilters.isEmpty()) {
        fileDialog->m_fileWidget->setFilter(nameFilters.join(QLatin1Char('\n')));
300
301
    }

302
303
304
305
    if (optionsWidget) {
        fileDialog->m_fileWidget->setCustomWidget(QStringLiteral(""), optionsWidget.get());
    }

Jan Grulich's avatar
Jan Grulich committed
306
307
    if (fileDialog->exec() == QDialog::Accepted) {
        QStringList files;
308
        for (const QString &filename : fileDialog->m_fileWidget->selectedFiles()) {
309
310
            QUrl url = QUrl::fromLocalFile(filename);
            files << url.toDisplayString();
Jan Grulich's avatar
Jan Grulich committed
311
        }
312
313
314
315
316
317

        if (files.isEmpty()) {
            qCDebug(XdgDesktopPortalKdeFileChooser) << "Failed to open file: no local file selected";
            return 2;
        }

Laurent Montel's avatar
Laurent Montel committed
318
        results.insert(QStringLiteral("uris"), files);
319
        results.insert(QStringLiteral("writable"), true);
320
321
322
323
324
325

        if (optionsWidget) {
            QVariant choices = EvaluateSelectedChoices(checkboxes, comboboxes);
            results.insert(QStringLiteral("choices"), choices);
        }

326
327
328
329
330
331
332
333
334
335
336
        // try to map current filter back to one of the predefined ones
        QString selectedFilter;
        if (bMimeFilters) {
            selectedFilter = fileDialog->m_fileWidget->currentMimeFilter();
        } else {
            selectedFilter = fileDialog->m_fileWidget->filterWidget()->currentText();
        }
        if (allFilters.contains(selectedFilter)) {
            results.insert(QStringLiteral("current_filter"), QVariant::fromValue<FilterList>(allFilters.value(selectedFilter)));
        }

Jan Grulich's avatar
Jan Grulich committed
337
338
339
340
341
342
        return 0;
    }

    return 1;
}

343
uint FileChooserPortal::SaveFile(const QDBusObjectPath &handle,
Jan Grulich's avatar
Jan Grulich committed
344
345
346
347
348
349
350
351
352
353
354
355
356
357
                           const QString &app_id,
                           const QString &parent_window,
                           const QString &title,
                           const QVariantMap &options,
                           QVariantMap &results)
{
    Q_UNUSED(app_id);

    qCDebug(XdgDesktopPortalKdeFileChooser) << "SaveFile called with parameters:";
    qCDebug(XdgDesktopPortalKdeFileChooser) << "    handle: " << handle.path();
    qCDebug(XdgDesktopPortalKdeFileChooser) << "    parent_window: " << parent_window;
    qCDebug(XdgDesktopPortalKdeFileChooser) << "    title: " << title;
    qCDebug(XdgDesktopPortalKdeFileChooser) << "    options: " << options;

358
    bool modalDialog = true;
Jan Grulich's avatar
Jan Grulich committed
359
360
361
    QString currentName;
    QString currentFolder;
    QString currentFile;
362
363
    QStringList nameFilters;
    QStringList mimeTypeFilters;
364
365
    // mapping between filter strings and actual filters
    QMap<QString, FilterList> allFilters;
Jan Grulich's avatar
Jan Grulich committed
366

Laurent Montel's avatar
Laurent Montel committed
367
368
    if (options.contains(QStringLiteral("modal"))) {
        modalDialog = options.value(QStringLiteral("modal")).toBool();
Jan Grulich's avatar
Jan Grulich committed
369
370
    }

371
    const QString acceptLabel = ExtractAcceptLabel(options);
Jan Grulich's avatar
Jan Grulich committed
372

Laurent Montel's avatar
Laurent Montel committed
373
374
    if (options.contains(QStringLiteral("current_name"))) {
        currentName = options.value(QStringLiteral("current_name")).toString();
Jan Grulich's avatar
Jan Grulich committed
375
376
    }

Laurent Montel's avatar
Laurent Montel committed
377
    if (options.contains(QStringLiteral("current_folder"))) {
378
        currentFolder = QFile::decodeName(options.value(QStringLiteral("current_folder")).toByteArray());
Jan Grulich's avatar
Jan Grulich committed
379
380
    }

Laurent Montel's avatar
Laurent Montel committed
381
    if (options.contains(QStringLiteral("current_file"))) {
382
        currentFile = QFile::decodeName(options.value(QStringLiteral("current_file")).toByteArray());
Jan Grulich's avatar
Jan Grulich committed
383
384
    }

385
    ExtractFilters(options, nameFilters, mimeTypeFilters, allFilters);
386

387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
    if (options.contains(QStringLiteral("current_filter"))) {
        FilterList filterList = qdbus_cast<FilterList>(options.value(QStringLiteral("current_filter")));
        if (filterList.filters.size() == 1) {
            // make the relevant entry the first one in the list of filters,
            // since that is the one that gets preselected by KFileWidget
            Filter filterStruct = filterList.filters.at(0);
            if (filterStruct.type == 0) {
                QString nameFilter = QStringLiteral("%1|%2").arg(filterStruct.filterString).arg(filterList.userVisibleName);
                nameFilters.removeAll(nameFilter);
                nameFilters.push_front(nameFilter);
            } else {
                mimeTypeFilters.removeAll(filterStruct.filterString);
                mimeTypeFilters.push_front(filterStruct.filterString);
            }
        } else {
            qCDebug(XdgDesktopPortalKdeFileChooser) << "Ignoring 'current_filter' parameter with 0 or multiple filters specified.";
        }
    }

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
    if (isMobile()) {
        if (!m_mobileFileDialog) {
            qCDebug(XdgDesktopPortalKdeFileChooser) << "Creating file dialog";
            m_mobileFileDialog = new MobileFileDialog(this);
        }

        m_mobileFileDialog->setTitle(title);

        // Always false when we are saving a file
        m_mobileFileDialog->setSelectExisting(false);

        if (!currentFolder.isEmpty()) {
            m_mobileFileDialog->setFolder(currentFolder);
        }

        if (!currentFile.isEmpty()) {
            m_mobileFileDialog->setCurrentFile(currentFile);
        }

        // currentName: not implemented

        if (!acceptLabel.isEmpty()) {
            m_mobileFileDialog->setAcceptLabel(acceptLabel);
        }

        if (!nameFilters.isEmpty()) {
            m_mobileFileDialog->setNameFilters(nameFilters);
        }

        if (!mimeTypeFilters.isEmpty()) {
            m_mobileFileDialog->setMimeTypeFilters(mimeTypeFilters);
        }

        uint retCode = m_mobileFileDialog->exec();

        results.insert(QStringLiteral("uris"), m_mobileFileDialog->results());

        return retCode;
    }

    // for handling of options - choices
    QScopedPointer<QWidget> optionsWidget;
    // to store IDs for choices along with corresponding comboboxes/checkboxes
    QMap<QString, QCheckBox*> checkboxes;
    QMap<QString, QComboBox*> comboboxes;

452
453
454
455
456
    if (options.contains(QStringLiteral("choices"))) {
        OptionList optionList = qdbus_cast<OptionList>(options.value(QStringLiteral("choices")));
        optionsWidget.reset(CreateChoiceControls(optionList, checkboxes, comboboxes));
    }

457
    QScopedPointer<FileDialog, QScopedPointerDeleteLater> fileDialog(new FileDialog());
458
    Utils::setParentWindow(fileDialog.data(), parent_window);
Jan Grulich's avatar
Jan Grulich committed
459
460
    fileDialog->setWindowTitle(title);
    fileDialog->setModal(modalDialog);
461
    fileDialog->m_fileWidget->setOperationMode(KFileWidget::Saving);
462
    fileDialog->m_fileWidget->setConfirmOverwrite(true);
Jan Grulich's avatar
Jan Grulich committed
463
464

    if (!currentFolder.isEmpty()) {
465
        fileDialog->m_fileWidget->setUrl(QUrl::fromLocalFile(currentFolder));
Jan Grulich's avatar
Jan Grulich committed
466
467
468
    }

    if (!currentFile.isEmpty()) {
469
        fileDialog->m_fileWidget->setSelectedUrl(QUrl::fromLocalFile(currentFile));
Jan Grulich's avatar
Jan Grulich committed
470
471
    }

472
    if (!currentName.isEmpty()) {
473
474
        const QUrl url = fileDialog->m_fileWidget->baseUrl();
        fileDialog->m_fileWidget->setSelectedUrl(QUrl::fromLocalFile(QStringLiteral("%1/%2").arg(url.toDisplayString(QUrl::StripTrailingSlash), currentName)));
475
476
    }

Jan Grulich's avatar
Jan Grulich committed
477
    if (!acceptLabel.isEmpty()) {
478
        fileDialog->m_fileWidget->okButton()->setText(acceptLabel);
Jan Grulich's avatar
Jan Grulich committed
479
480
    }

481
    bool bMimeFilters = false;
482
    if (!mimeTypeFilters.isEmpty()) {
483
        fileDialog->m_fileWidget->setMimeFilter(mimeTypeFilters);
484
485
486
        bMimeFilters = true;
    } else if (!nameFilters.isEmpty()) {
        fileDialog->m_fileWidget->setFilter(nameFilters.join(QLatin1Char('\n')));
487
488
    }

489
490
491
492
    if (optionsWidget) {
        fileDialog->m_fileWidget->setCustomWidget(optionsWidget.get());
    }

Jan Grulich's avatar
Jan Grulich committed
493
494
    if (fileDialog->exec() == QDialog::Accepted) {
        QStringList files;
495
496
        QUrl url = QUrl::fromLocalFile(fileDialog->m_fileWidget->selectedFile());
        files << url.toDisplayString();
Laurent Montel's avatar
Laurent Montel committed
497
        results.insert(QStringLiteral("uris"), files);
498
499
500
501
502
503

        if (optionsWidget) {
            QVariant choices = EvaluateSelectedChoices(checkboxes, comboboxes);
            results.insert(QStringLiteral("choices"), choices);
        }

504
505
506
507
508
509
510
511
512
513
514
        // try to map current filter back to one of the predefined ones
        QString selectedFilter;
        if (bMimeFilters) {
            selectedFilter = fileDialog->m_fileWidget->currentMimeFilter();
        } else {
            selectedFilter = fileDialog->m_fileWidget->filterWidget()->currentText();
        }
        if (allFilters.contains(selectedFilter)) {
            results.insert(QStringLiteral("current_filter"), QVariant::fromValue<FilterList>(allFilters.value(selectedFilter)));
        }

Jan Grulich's avatar
Jan Grulich committed
515
516
517
518
519
520
        return 0;
    }

    return 1;
}

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
QWidget* FileChooserPortal::CreateChoiceControls(const FileChooserPortal::OptionList &optionList,
                                                 QMap<QString, QCheckBox *> &checkboxes,
                                                 QMap<QString, QComboBox *> &comboboxes)
{
    if (optionList.empty()) {
        return nullptr;
    }

    QWidget* optionsWidget = new QWidget;
    QGridLayout* layout = new QGridLayout(optionsWidget);
    // set stretch for (unused) column 2 so controls only take the space they actually need
    layout->setColumnStretch(2, 1);
    optionsWidget->setLayout(layout);

    for (const Option& option : optionList) {
        const int nextRow = layout->rowCount();
        // empty list of choices -> boolean choice according to the spec
        if (option.choices.empty()) {
            QCheckBox* checkbox = new QCheckBox(option.label, optionsWidget);
            checkbox->setChecked(option.initialChoiceId == QStringLiteral("true"));
            layout->addWidget(checkbox, nextRow, 1);
            checkboxes.insert(option.id, checkbox);
        } else {
            QComboBox* combobox = new QComboBox(optionsWidget);
            for (const Choice& choice : option.choices) {
                combobox->addItem(choice.value, choice.id);
                // select this entry if initialChoiceId matches
                if (choice.id == option.initialChoiceId) {
                    combobox->setCurrentIndex(combobox->count() - 1);
                }
            }
            QString labelText = option.label;
            if (!labelText.endsWith(QChar::fromLatin1(':'))) {
                labelText += QChar::fromLatin1(':');
            }
            QLabel* label = new QLabel(labelText, optionsWidget);
            label->setBuddy(combobox);
            layout->addWidget(label, nextRow, 0, Qt::AlignRight);
            layout->addWidget(combobox, nextRow, 1);
            comboboxes.insert(option.id, combobox);
        }
    }

    return optionsWidget;
}

QVariant FileChooserPortal::EvaluateSelectedChoices(const QMap<QString, QCheckBox*>& checkboxes,
                                                    const QMap<QString, QComboBox*>& comboboxes)
{
    Choices selectedChoices;
    for (const QString& id : checkboxes.keys()) {
        Choice choice;
        choice.id = id;
        choice.value = checkboxes.value(id)->isChecked() ? QStringLiteral("true") : QStringLiteral("false");
        selectedChoices << choice;
    }
    for (const QString& id : comboboxes.keys()) {
        Choice choice;
        choice.id = id;
        choice.value = comboboxes.value(id)->currentData().toString();
        selectedChoices << choice;
    }

    return QVariant::fromValue<Choices>(selectedChoices);
}
586

587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
QString FileChooserPortal::ExtractAcceptLabel(const QVariantMap &options)
{
    QString acceptLabel;
    if (options.contains(QStringLiteral("accept_label"))) {
        acceptLabel = options.value(QStringLiteral("accept_label")).toString();
        // 'accept_label' allows mnemonic underlines, but Qt uses '&' character, so replace/escape accordingly
        // to keep literal '&'s and transform mnemonic underlines to the Qt equivalent using '&' for mnemonic
        acceptLabel.replace(QChar::fromLatin1('&'), QStringLiteral("&&"));
        const int mnemonic_pos = acceptLabel.indexOf(QChar::fromLatin1('_'));
        if (mnemonic_pos != -1) {
            acceptLabel.replace(mnemonic_pos, 1, QChar::fromLatin1('&'));
        }
    }
    return acceptLabel;
}

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
void FileChooserPortal::ExtractFilters(const QVariantMap &options, QStringList &nameFilters,
                                       QStringList &mimeTypeFilters, QMap<QString, FilterList> &allFilters)
{
    if (options.contains(QStringLiteral("filters"))) {
        FilterListList filterListList = qdbus_cast<FilterListList>(options.value(QStringLiteral("filters")));
        for (const FilterList &filterList : filterListList) {
            QStringList filterStrings;
            for (const Filter &filterStruct : filterList.filters) {
                if (filterStruct.type == 0) {
                    filterStrings << filterStruct.filterString;
                } else {
                    mimeTypeFilters << filterStruct.filterString;
                    allFilters[filterStruct.filterString] = filterList;
                }
            }

            if (!filterStrings.isEmpty()) {
                const QString filterString = filterStrings.join(QLatin1Char(' '));
                const QString nameFilter = QStringLiteral("%1|%2").arg(filterString, filterList.userVisibleName);
                nameFilters << nameFilter;
                allFilters[filterList.userVisibleName] = filterList;
            }
        }
    }
}
628
629
630
631
632
633

bool FileChooserPortal::isMobile() const
{
    QByteArray mobile = qgetenv("QT_QUICK_CONTROLS_MOBILE");
    return mobile == "true" || mobile == "1";
}