summaryrefslogtreecommitdiffstats
path: root/src/file_chooser_portal.cpp
blob: 7d6eb02aaf9199c260516c84ab0529885cebaa1f (plain)
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
/*******************************************************************************
  XDG desktop portal implementation for TDE
  Copyright © 2024 Mavridis Philippe <mavridisf@gmail.com>

  This program or library 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.1 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, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

  Improvements and feedback are welcome!
*******************************************************************************/

// TQt
#include <tqregexp.h>
#include <tqdbusobjectpath.h>
#include <tqapplication.h>
#include <tqthread.h>

// TDE
#include <tdeio/renamedlg.h>
#include <tdefiledialog.h>
#include <kpushbutton.h>
#include <kdebug.h>

// Portal
#include "file_chooser_portal.h"
#include "file_chooser_portal.moc"

class KMultiFileSaveDialog : public KFileDialog
{
    public:
        KMultiFileSaveDialog(TQString startDir, TQStringList filelist,
                             const char *name, bool modal)
            : KFileDialog(startDir, TQString::null, nullptr, name, modal),
              m_files(filelist)
        {}

        KURL::List urls()
        {
            return m_urls;
        }

    protected slots:
        // The below is a workaround to prevent the dialog from disappearing
        // until we are done handling conflicting files.
        // Don't kick it, it works.
        void done(int) {}
        void actuallyDone(int r) { KFileDialog::done(r); }

        void slotCancel()
        {
            actuallyDone(KFileDialog::Rejected);
        }

        void slotOk()
        {
            KFileDialog::slotOk();
            m_urls.clear();

            // Check if there are conflicting files in the target directory
            // and prompt for action
            TQDir d(selectedURL().path());
            for (TQStringList::Iterator it = m_files.begin(); it != m_files.end(); ++it)
            {
                TQString filename(*it);
                TQFileInfo fi(d, filename);
                KURL url(fi.absFilePath());
                if (fi.exists())
                {
                    TDEIO::RenameDlg rename(nullptr, caption(), TQString::null,
                                            fi.absFilePath(), TDEIO::M_OVERWRITE);
                    int result = rename.exec();

                    switch (result)
                    {
                        case TDEIO::R_RENAME:
                            m_urls << rename.newDestURL();
                            break;
                        case TDEIO::R_OVERWRITE:
                            m_urls << url.url();
                            break;
                        case TDEIO::R_CANCEL:
                        default:
                            actuallyDone(KFileDialog::Rejected);
                            break;
                    }
                }
                else
                {
                    m_urls << url.url();
                }
            }
            actuallyDone(KFileDialog::Accepted);
        }

    private:
        TQStringList m_files;
        KURL::List m_urls;
};

TDEFileChooserPortal::TDEFileChooserPortal(TQT_DBusConnection &connection)
    : m_connection(connection)
{}

TDEFileChooserPortal::~TDEFileChooserPortal()
{}

void TDEFileChooserPortal::OpenFileAsync(int asyncCallId,
                                         const TQT_DBusObjectPath& handle,
                                         const TQString& app_id,
                                         const TQString& parent_window,
                                         const TQString& title,
                                         const TQT_DBusVariantMap &options)
{
    FileDialogOpts opts;

    opts.caption = title;

    if (OPTION_VALID("accept_label", "s"))
        opts.okButtonText = options["accept_label"].value.toString();

    if (OPTION_VALID("directory", "b"))
        opts.directory = options["directory"].value.toBool();

    if (OPTION_VALID("multiple", "b"))
        opts.multiple = options["multiple"].value.toBool();

    if (OPTION_VALID("modal", "b"))
        opts.modal = options["modal"].value.toBool();

    if (OPTION_VALID("filters", "a(sa(us))"))
        opts.filters = parseFilterList(options["filters"], options["current_filter"]);

    opts.windowId = parse_window_id(parent_window);

    // Execute dialog
    execFileDialog(&TDEFileChooserPortal::OpenFileAsyncReply, asyncCallId, opts, handle);
}

void TDEFileChooserPortal::SaveFileAsync(int asyncCallId,
                                         const TQT_DBusObjectPath& handle,
                                         const TQString& app_id,
                                         const TQString& parent_window,
                                         const TQString& title,
                                         const TQT_DBusVariantMap &options)
{
    FileDialogOpts opts;

    opts.caption = title;

    if (OPTION_VALID("accept_label", "s"))
        opts.okButtonText = options["accept_label"].value.toString();

    if (OPTION_VALID("directory", "b"))
        opts.directory = options["directory"].value.toBool();

    if (OPTION_VALID("multiple", "b"))
        opts.multiple = options["multiple"].value.toBool();

    if (OPTION_VALID("modal", "b"))
        opts.modal = options["modal"].value.toBool();

    if (OPTION_VALID("filters", "a(sa(us))"))
        opts.filters = parseFilterList(options["filters"], options["current_filter"]);

    if (OPTION_VALID("current_folder", "ay"))
        opts.startDir = bytelist_to_string(options["current_folder"].value.toList().toByteList());

    if (OPTION_VALID("current_name", "s"))
        opts.startName = options["current_name"].value.toString();

    opts.windowId = parse_window_id(parent_window);

    execFileDialog(&TDEFileChooserPortal::SaveFileAsyncReply, asyncCallId, opts, handle);
}

// TODO move some of the dialog handling stuff to execFileDialog()
void TDEFileChooserPortal::SaveFilesAsync(int asyncCallId,
                                          const TQT_DBusObjectPath& handle,
                                          const TQString& app_id,
                                          const TQString& parent_window,
                                          const TQString& title,
                                          const TQMap<TQString, TQT_DBusVariant> &options)
{
    // Get list of files to save
    if (!OPTION_VALID("files", "aay"))
    {
        kdWarning() << "TDEFileChooserPortal::SaveFiles: "
                    << "Invalid or missing files option" << endl;

        SaveFilesAsyncReply(asyncCallId, 0, TQT_DBusVariantMap());
        return;
    }

    TQT_DBusValueList filelist = options["files"].value.toTQValueList();
    TQT_DBusValueList::iterator fi;
    TQStringList files;
    for (fi = filelist.begin(); fi != filelist.end(); ++fi)
    {
        files << bytelist_to_string((*fi).toList().toByteList());
    }

    // Parse options
    FileDialogOpts opts;
    opts.caption = title;

    if (OPTION_VALID("accept_label", "s"))
        opts.okButtonText = options["accept_label"].value.toString();

    if (OPTION_VALID("modal", "b"))
        opts.modal = options["modal"].value.toBool();

    if (OPTION_VALID("current_folder", "ay"))
        opts.startDir = bytelist_to_string(options["current_folder"].value.toList().toByteList());

    // We can't just use execFileDialog because we need to do some special processing
    KMultiFileSaveDialog *dialog = new KMultiFileSaveDialog(opts.startDir, files,
                                                            "xdg-tde-file-chooser",
                                                            opts.modal);

    dialog->setMode(KFile::LocalOnly | KFile::Directory);

    if (!opts.caption.isNull())
        dialog->setPlainCaption(opts.caption);

    if (!opts.okButtonText.isNull())
        dialog->okButton()->setText(opts.okButtonText);

    if (opts.windowId > 0) KWin::setMainWindow(dialog, opts.windowId);

    auto *sender = new DialogResultSender<TDEFileChooserPortal>
            (this, asyncCallId, dialog,
             &TDEFileChooserPortal::prepareSaveFilesReply,
             &TDEFileChooserPortal::SaveFilesAsyncReply);
    dialog->show();
    sender->start();

}

void TDEFileChooserPortal::handleMethodReply(const TQT_DBusMessage &reply)
{
    m_connection.send(reply);
}

bool TDEFileChooserPortal::handleSignalSend(const TQT_DBusMessage& reply) {
    handleMethodReply(reply);
    return true;
}

void TDEFileChooserPortal::execFileDialog(ResultSendCallback<TDEFileChooserPortal> callback,
                                          int asyncCallId,
                                          FileDialogOpts options,
                                          const TQT_DBusObjectPath& handle)
{
    KFileDialog *dialog = new KFileDialog(options.startDir, TQString::null,
                                          nullptr, "xdg-tde-file-chooser",
                                          options.modal);
    uint mode = KFile::LocalOnly;
    if (options.savingMode)
    {
        dialog->setOperationMode(KFileDialog::Saving);
    }
    else {
        mode |= KFile::ExistingOnly;
    }
    dialog->setMode(mode | options.mode());

    if (!options.caption.isNull())
    {
        dialog->setPlainCaption(options.caption);
    }

    if (!options.okButtonText.isNull())
    {
        dialog->okButton()->setText(options.okButtonText);
    }

    if (!options.filters.isNull())
    {
        dialog->setFilter(options.filters);
    }

    dialog->setSelection(options.startName);

    if (options.windowId > 0) KWin::setMainWindow(dialog, options.windowId);

    auto *sender = new DialogResultSender<TDEFileChooserPortal>
        (this, asyncCallId, dialog, &TDEFileChooserPortal::prepareReply, callback);
    dialog->show();
    sender->start();
}

DialogResult TDEFileChooserPortal::prepareReply(TQDialog *dlg)
{
    KFileDialog *fd = static_cast<KFileDialog*>(dlg);
    KURL::List urllist = fd->selectedURLs();

    DialogResult res;
    TQT_DBusDataList urls = kurl_list_to_datalist(urllist);
    TQT_DBusVariant var = TQT_DBusData::fromList(urls).getAsVariantData().toVariant();
    res.results.insert("uris", var);
    res.response = urllist.isEmpty() ? 1 : 0;
    return res;
}

// Special treatment for SaveFiles()
// TODO revise this and possibly merge with prepareReply()
DialogResult TDEFileChooserPortal::prepareSaveFilesReply(TQDialog *dlg)
{
    DialogResult res;
    if (dlg->result() == TQDialog::Accepted)
    {
        KMultiFileSaveDialog *fd = static_cast<KMultiFileSaveDialog*>(dlg);

        TQT_DBusDataList urls = kurl_list_to_datalist(fd->urls());
        TQT_DBusVariant var = TQT_DBusData::fromList(urls).getAsVariantData().toVariant();

        res.response = 0;
        res.results.insert("uris", var);
    }
    else res.response = 1;

    return res;
}

TQString TDEFileChooserPortal::parseFilter(const TQT_DBusData data)
{
    TQStringList patternList;

    TQT_DBusValueList filterData = data.toStruct();

    TQString label = filterData[0].toString();
    TQT_DBusValueList patterns = filterData[1].toTQValueList();

    TQT_DBusValueList::iterator fp;
    for (fp = patterns.begin(); fp != patterns.end(); ++fp)
    {
        TQT_DBusValueList patternData = (*fp).toStruct();
        bool isMime = (patternData[0].toUInt32() == 1);
        if (isMime) {
            // KFileDialog cannot handle both a mime and a simple
            // extension filter, so in case we get a mimetype,
            // we just get the associated extensions from the
            // MIME system
            TQString mime = patternData[1].toString();
            patternList += KMimeType::mimeType(mime)->patterns();
        }
        else {
            TQString patternString = patternData[1].toString();

            // Regex patterns like *.[hH][tT][mM][lL] are unnecessary for us
            // and causes a problem with the save dialog's extension autoselection
            TQString finalPattern = patternString;
            if (TQRegExp("[*.](?:[[](?:[A-Za-z]{2})[]])+").search(patternString) != -1)
            {
                finalPattern = "*.";
                int pos = patternString.find('[');
                while (pos != -1)
                {
                    finalPattern += patternString[pos + 1];
                    pos = patternString.find('[', patternString.find(']', pos));
                }
            }
            patternList += finalPattern;
        }
    }

    TQString patternString = patternList.join(" ");

    return TQString("%1|%2 (%3)").arg(patternString, label, patternString);
}

TQString TDEFileChooserPortal::parseFilterList(const TQT_DBusVariant filterData,
                                               const TQT_DBusVariant currentFilterData)
{
    TQStringList filterList;
    TQT_DBusValueList filters = filterData.value.toTQValueList();
    if (filters.count() > 0) {
        TQT_DBusValueList::iterator f;
        for (f = filters.begin(); f != filters.end(); ++f)
                filterList += parseFilter((*f));
    }

    if (check_variant(currentFilterData, "(sa(us))"))
    {
        TQString currentFilter = parseFilter(currentFilterData.value);
        if (filterList.contains(currentFilter))
        {
            // We have no way to affect the filter selection of the dialog,
            // so we just move the current filter to the top of the list
            // to get it selected automatically
            filterList.remove(currentFilter);
            filterList.prepend(currentFilter);
        }
    }

    return filterList.join("\n");
}

// kate: replace-tabs true; tab-width 4; indent-width 4;