1/**************************************************************************/
2/* freedesktop_portal_desktop.cpp */
3/**************************************************************************/
4/* This file is part of: */
5/* GODOT ENGINE */
6/* https://godotengine.org */
7/**************************************************************************/
8/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10/* */
11/* Permission is hereby granted, free of charge, to any person obtaining */
12/* a copy of this software and associated documentation files (the */
13/* "Software"), to deal in the Software without restriction, including */
14/* without limitation the rights to use, copy, modify, merge, publish, */
15/* distribute, sublicense, and/or sell copies of the Software, and to */
16/* permit persons to whom the Software is furnished to do so, subject to */
17/* the following conditions: */
18/* */
19/* The above copyright notice and this permission notice shall be */
20/* included in all copies or substantial portions of the Software. */
21/* */
22/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29/**************************************************************************/
30
31#include "freedesktop_portal_desktop.h"
32
33#ifdef DBUS_ENABLED
34
35#include "core/crypto/crypto_core.h"
36#include "core/error/error_macros.h"
37#include "core/os/os.h"
38#include "core/string/ustring.h"
39#include "core/variant/variant.h"
40
41#ifdef SOWRAP_ENABLED
42#include "dbus-so_wrap.h"
43#else
44#include <dbus/dbus.h>
45#endif
46
47#include <unistd.h>
48
49#define BUS_OBJECT_NAME "org.freedesktop.portal.Desktop"
50#define BUS_OBJECT_PATH "/org/freedesktop/portal/desktop"
51
52#define BUS_INTERFACE_SETTINGS "org.freedesktop.portal.Settings"
53#define BUS_INTERFACE_FILE_CHOOSER "org.freedesktop.portal.FileChooser"
54
55bool FreeDesktopPortalDesktop::try_parse_variant(DBusMessage *p_reply_message, int p_type, void *r_value) {
56 DBusMessageIter iter[3];
57
58 dbus_message_iter_init(p_reply_message, &iter[0]);
59 if (dbus_message_iter_get_arg_type(&iter[0]) != DBUS_TYPE_VARIANT) {
60 return false;
61 }
62
63 dbus_message_iter_recurse(&iter[0], &iter[1]);
64 if (dbus_message_iter_get_arg_type(&iter[1]) != DBUS_TYPE_VARIANT) {
65 return false;
66 }
67
68 dbus_message_iter_recurse(&iter[1], &iter[2]);
69 if (dbus_message_iter_get_arg_type(&iter[2]) != p_type) {
70 return false;
71 }
72
73 dbus_message_iter_get_basic(&iter[2], r_value);
74 return true;
75}
76
77bool FreeDesktopPortalDesktop::read_setting(const char *p_namespace, const char *p_key, int p_type, void *r_value) {
78 if (unsupported) {
79 return false;
80 }
81
82 DBusError error;
83 dbus_error_init(&error);
84
85 DBusConnection *bus = dbus_bus_get(DBUS_BUS_SESSION, &error);
86 if (dbus_error_is_set(&error)) {
87 if (OS::get_singleton()->is_stdout_verbose()) {
88 ERR_PRINT(vformat("Error opening D-Bus connection: %s", error.message));
89 }
90 dbus_error_free(&error);
91 unsupported = true;
92 return false;
93 }
94
95 DBusMessage *message = dbus_message_new_method_call(
96 BUS_OBJECT_NAME, BUS_OBJECT_PATH, BUS_INTERFACE_SETTINGS,
97 "Read");
98 dbus_message_append_args(
99 message,
100 DBUS_TYPE_STRING, &p_namespace,
101 DBUS_TYPE_STRING, &p_key,
102 DBUS_TYPE_INVALID);
103
104 DBusMessage *reply = dbus_connection_send_with_reply_and_block(bus, message, 50, &error);
105 dbus_message_unref(message);
106 if (dbus_error_is_set(&error)) {
107 if (OS::get_singleton()->is_stdout_verbose()) {
108 ERR_PRINT(vformat("Error on D-Bus communication: %s", error.message));
109 }
110 dbus_error_free(&error);
111 dbus_connection_unref(bus);
112 return false;
113 }
114
115 bool success = try_parse_variant(reply, p_type, r_value);
116
117 dbus_message_unref(reply);
118 dbus_connection_unref(bus);
119
120 return success;
121}
122
123uint32_t FreeDesktopPortalDesktop::get_appearance_color_scheme() {
124 if (unsupported) {
125 return 0;
126 }
127
128 uint32_t value = 0;
129 read_setting("org.freedesktop.appearance", "color-scheme", DBUS_TYPE_UINT32, &value);
130 return value;
131}
132
133static const char *cs_empty = "";
134
135void FreeDesktopPortalDesktop::append_dbus_string(DBusMessageIter *p_iter, const String &p_string) {
136 CharString cs = p_string.utf8();
137 const char *cs_ptr = cs.ptr();
138 if (cs_ptr) {
139 dbus_message_iter_append_basic(p_iter, DBUS_TYPE_STRING, &cs_ptr);
140 } else {
141 dbus_message_iter_append_basic(p_iter, DBUS_TYPE_STRING, &cs_empty);
142 }
143}
144
145void FreeDesktopPortalDesktop::append_dbus_dict_filters(DBusMessageIter *p_iter, const Vector<String> &p_filters) {
146 DBusMessageIter dict_iter;
147 DBusMessageIter var_iter;
148 DBusMessageIter arr_iter;
149 const char *filters_key = "filters";
150
151 dbus_message_iter_open_container(p_iter, DBUS_TYPE_DICT_ENTRY, nullptr, &dict_iter);
152 dbus_message_iter_append_basic(&dict_iter, DBUS_TYPE_STRING, &filters_key);
153 dbus_message_iter_open_container(&dict_iter, DBUS_TYPE_VARIANT, "a(sa(us))", &var_iter);
154 dbus_message_iter_open_container(&var_iter, DBUS_TYPE_ARRAY, "(sa(us))", &arr_iter);
155 for (int i = 0; i < p_filters.size(); i++) {
156 Vector<String> tokens = p_filters[i].split(";");
157 if (tokens.size() == 2) {
158 DBusMessageIter struct_iter;
159 DBusMessageIter array_iter;
160 DBusMessageIter array_struct_iter;
161 dbus_message_iter_open_container(&arr_iter, DBUS_TYPE_STRUCT, nullptr, &struct_iter);
162 append_dbus_string(&struct_iter, tokens[0]);
163
164 dbus_message_iter_open_container(&struct_iter, DBUS_TYPE_ARRAY, "(us)", &array_iter);
165 dbus_message_iter_open_container(&array_iter, DBUS_TYPE_STRUCT, nullptr, &array_struct_iter);
166 {
167 const unsigned nil = 0;
168 dbus_message_iter_append_basic(&array_struct_iter, DBUS_TYPE_UINT32, &nil);
169 }
170 append_dbus_string(&array_struct_iter, tokens[1]);
171 dbus_message_iter_close_container(&array_iter, &array_struct_iter);
172 dbus_message_iter_close_container(&struct_iter, &array_iter);
173 dbus_message_iter_close_container(&arr_iter, &struct_iter);
174 }
175 }
176 dbus_message_iter_close_container(&var_iter, &arr_iter);
177 dbus_message_iter_close_container(&dict_iter, &var_iter);
178 dbus_message_iter_close_container(p_iter, &dict_iter);
179}
180
181void FreeDesktopPortalDesktop::append_dbus_dict_string(DBusMessageIter *p_iter, const String &p_key, const String &p_value, bool p_as_byte_array) {
182 DBusMessageIter dict_iter;
183 DBusMessageIter var_iter;
184 dbus_message_iter_open_container(p_iter, DBUS_TYPE_DICT_ENTRY, nullptr, &dict_iter);
185 append_dbus_string(&dict_iter, p_key);
186
187 if (p_as_byte_array) {
188 DBusMessageIter arr_iter;
189 dbus_message_iter_open_container(&dict_iter, DBUS_TYPE_VARIANT, "ay", &var_iter);
190 dbus_message_iter_open_container(&var_iter, DBUS_TYPE_ARRAY, "y", &arr_iter);
191 CharString cs = p_value.utf8();
192 const char *cs_ptr = cs.get_data();
193 do {
194 dbus_message_iter_append_basic(&arr_iter, DBUS_TYPE_BYTE, cs_ptr);
195 } while (*cs_ptr++);
196 dbus_message_iter_close_container(&var_iter, &arr_iter);
197 } else {
198 dbus_message_iter_open_container(&dict_iter, DBUS_TYPE_VARIANT, "s", &var_iter);
199 append_dbus_string(&var_iter, p_value);
200 }
201
202 dbus_message_iter_close_container(&dict_iter, &var_iter);
203 dbus_message_iter_close_container(p_iter, &dict_iter);
204}
205
206void FreeDesktopPortalDesktop::append_dbus_dict_bool(DBusMessageIter *p_iter, const String &p_key, bool p_value) {
207 DBusMessageIter dict_iter;
208 DBusMessageIter var_iter;
209 dbus_message_iter_open_container(p_iter, DBUS_TYPE_DICT_ENTRY, nullptr, &dict_iter);
210 append_dbus_string(&dict_iter, p_key);
211
212 dbus_message_iter_open_container(&dict_iter, DBUS_TYPE_VARIANT, "b", &var_iter);
213 {
214 int val = p_value;
215 dbus_message_iter_append_basic(&var_iter, DBUS_TYPE_BOOLEAN, &val);
216 }
217
218 dbus_message_iter_close_container(&dict_iter, &var_iter);
219 dbus_message_iter_close_container(p_iter, &dict_iter);
220}
221
222bool FreeDesktopPortalDesktop::file_chooser_parse_response(DBusMessageIter *p_iter, bool &r_cancel, Vector<String> &r_urls) {
223 ERR_FAIL_COND_V(dbus_message_iter_get_arg_type(p_iter) != DBUS_TYPE_UINT32, false);
224
225 dbus_uint32_t resp_code;
226 dbus_message_iter_get_basic(p_iter, &resp_code);
227 if (resp_code != 0) {
228 r_cancel = true;
229 } else {
230 r_cancel = false;
231 ERR_FAIL_COND_V(!dbus_message_iter_next(p_iter), false);
232 ERR_FAIL_COND_V(dbus_message_iter_get_arg_type(p_iter) != DBUS_TYPE_ARRAY, false);
233
234 DBusMessageIter dict_iter;
235 dbus_message_iter_recurse(p_iter, &dict_iter);
236 while (dbus_message_iter_get_arg_type(&dict_iter) == DBUS_TYPE_DICT_ENTRY) {
237 DBusMessageIter iter;
238 dbus_message_iter_recurse(&dict_iter, &iter);
239 if (dbus_message_iter_get_arg_type(&iter) == DBUS_TYPE_STRING) {
240 const char *key;
241 dbus_message_iter_get_basic(&iter, &key);
242 dbus_message_iter_next(&iter);
243
244 DBusMessageIter var_iter;
245 dbus_message_iter_recurse(&iter, &var_iter);
246 if (strcmp(key, "uris") == 0) {
247 if (dbus_message_iter_get_arg_type(&var_iter) == DBUS_TYPE_ARRAY) {
248 DBusMessageIter uri_iter;
249 dbus_message_iter_recurse(&var_iter, &uri_iter);
250 while (dbus_message_iter_get_arg_type(&uri_iter) == DBUS_TYPE_STRING) {
251 const char *value;
252 dbus_message_iter_get_basic(&uri_iter, &value);
253 r_urls.push_back(String::utf8(value).trim_prefix("file://").uri_decode());
254 if (!dbus_message_iter_next(&uri_iter)) {
255 break;
256 }
257 }
258 }
259 }
260 }
261 if (!dbus_message_iter_next(&dict_iter)) {
262 break;
263 }
264 }
265 }
266 return true;
267}
268
269Error FreeDesktopPortalDesktop::file_dialog_show(const String &p_xid, const String &p_title, const String &p_current_directory, const String &p_filename, DisplayServer::FileDialogMode p_mode, const Vector<String> &p_filters, const Callable &p_callback) {
270 if (unsupported) {
271 return FAILED;
272 }
273
274 DBusError err;
275 dbus_error_init(&err);
276
277 // Open connection and add signal handler.
278 FileDialogData fd;
279 fd.callback = p_callback;
280
281 CryptoCore::RandomGenerator rng;
282 ERR_FAIL_COND_V_MSG(rng.init(), FAILED, "Failed to initialize random number generator.");
283 uint8_t uuid[64];
284 Error rng_err = rng.get_random_bytes(uuid, 64);
285 ERR_FAIL_COND_V_MSG(rng_err, rng_err, "Failed to generate unique token.");
286
287 fd.connection = dbus_bus_get(DBUS_BUS_SESSION, &err);
288 if (dbus_error_is_set(&err)) {
289 ERR_PRINT(vformat("Failed to open DBus connection: %s", err.message));
290 dbus_error_free(&err);
291 unsupported = true;
292 return FAILED;
293 }
294
295 String dbus_unique_name = String::utf8(dbus_bus_get_unique_name(fd.connection));
296 String token = String::hex_encode_buffer(uuid, 64);
297 String path = vformat("/org/freedesktop/portal/desktop/request/%s/%s", dbus_unique_name.replace(".", "_").replace(":", ""), token);
298
299 fd.path = vformat("type='signal',sender='org.freedesktop.portal.Desktop',path='%s',interface='org.freedesktop.portal.Request',member='Response',destination='%s'", path, dbus_unique_name);
300 dbus_bus_add_match(fd.connection, fd.path.utf8().get_data(), &err);
301 if (dbus_error_is_set(&err)) {
302 ERR_PRINT(vformat("Failed to add DBus match: %s", err.message));
303 dbus_error_free(&err);
304 dbus_connection_unref(fd.connection);
305 return FAILED;
306 }
307
308 // Generate FileChooser message.
309 const char *method = nullptr;
310 switch (p_mode) {
311 case DisplayServer::FILE_DIALOG_MODE_SAVE_FILE: {
312 method = "SaveFile";
313 } break;
314 case DisplayServer::FILE_DIALOG_MODE_OPEN_ANY:
315 case DisplayServer::FILE_DIALOG_MODE_OPEN_FILE:
316 case DisplayServer::FILE_DIALOG_MODE_OPEN_DIR:
317 case DisplayServer::FILE_DIALOG_MODE_OPEN_FILES: {
318 method = "OpenFile";
319 } break;
320 }
321
322 DBusMessage *message = dbus_message_new_method_call(BUS_OBJECT_NAME, BUS_OBJECT_PATH, BUS_INTERFACE_FILE_CHOOSER, method);
323 {
324 DBusMessageIter iter;
325 dbus_message_iter_init_append(message, &iter);
326
327 append_dbus_string(&iter, p_xid);
328 append_dbus_string(&iter, p_title);
329
330 DBusMessageIter arr_iter;
331 dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &arr_iter);
332
333 append_dbus_dict_string(&arr_iter, "handle_token", token);
334 append_dbus_dict_bool(&arr_iter, "multiple", p_mode == DisplayServer::FILE_DIALOG_MODE_OPEN_FILES);
335 append_dbus_dict_bool(&arr_iter, "directory", p_mode == DisplayServer::FILE_DIALOG_MODE_OPEN_DIR);
336 append_dbus_dict_filters(&arr_iter, p_filters);
337 append_dbus_dict_string(&arr_iter, "current_folder", p_current_directory, true);
338 if (p_mode == DisplayServer::FILE_DIALOG_MODE_SAVE_FILE) {
339 append_dbus_dict_string(&arr_iter, "current_name", p_filename);
340 }
341
342 dbus_message_iter_close_container(&iter, &arr_iter);
343 }
344
345 DBusMessage *reply = dbus_connection_send_with_reply_and_block(fd.connection, message, DBUS_TIMEOUT_INFINITE, &err);
346 dbus_message_unref(message);
347
348 if (!reply || dbus_error_is_set(&err)) {
349 ERR_PRINT(vformat("Failed to send DBus message: %s", err.message));
350 dbus_error_free(&err);
351 dbus_bus_remove_match(fd.connection, fd.path.utf8().get_data(), &err);
352 dbus_connection_unref(fd.connection);
353 return FAILED;
354 }
355
356 // Update signal path.
357 {
358 DBusMessageIter iter;
359 if (dbus_message_iter_init(reply, &iter)) {
360 if (dbus_message_iter_get_arg_type(&iter) == DBUS_TYPE_OBJECT_PATH) {
361 const char *new_path = nullptr;
362 dbus_message_iter_get_basic(&iter, &new_path);
363 if (String::utf8(new_path) != path) {
364 dbus_bus_remove_match(fd.connection, fd.path.utf8().get_data(), &err);
365 if (dbus_error_is_set(&err)) {
366 ERR_PRINT(vformat("Failed to remove DBus match: %s", err.message));
367 dbus_error_free(&err);
368 dbus_connection_unref(fd.connection);
369 return FAILED;
370 }
371 fd.path = String::utf8(new_path);
372 dbus_bus_add_match(fd.connection, fd.path.utf8().get_data(), &err);
373 if (dbus_error_is_set(&err)) {
374 ERR_PRINT(vformat("Failed to add DBus match: %s", err.message));
375 dbus_error_free(&err);
376 dbus_connection_unref(fd.connection);
377 return FAILED;
378 }
379 }
380 }
381 }
382 }
383 dbus_message_unref(reply);
384
385 MutexLock lock(file_dialog_mutex);
386 file_dialogs.push_back(fd);
387
388 return OK;
389}
390
391void FreeDesktopPortalDesktop::_thread_file_dialog_monitor(void *p_ud) {
392 FreeDesktopPortalDesktop *portal = (FreeDesktopPortalDesktop *)p_ud;
393
394 while (!portal->file_dialog_thread_abort.is_set()) {
395 {
396 MutexLock lock(portal->file_dialog_mutex);
397 for (int i = portal->file_dialogs.size() - 1; i >= 0; i--) {
398 bool remove = false;
399 {
400 FreeDesktopPortalDesktop::FileDialogData &fd = portal->file_dialogs.write[i];
401 if (fd.connection) {
402 while (true) {
403 DBusMessage *msg = dbus_connection_pop_message(fd.connection);
404 if (!msg) {
405 break;
406 } else if (dbus_message_is_signal(msg, "org.freedesktop.portal.Request", "Response")) {
407 DBusMessageIter iter;
408 if (dbus_message_iter_init(msg, &iter)) {
409 bool cancel = false;
410 Vector<String> uris;
411 file_chooser_parse_response(&iter, cancel, uris);
412
413 if (fd.callback.is_valid()) {
414 Variant v_status = !cancel;
415 Variant v_files = uris;
416 Variant *v_args[2] = { &v_status, &v_files };
417 fd.callback.call_deferredp((const Variant **)&v_args, 2);
418 }
419 }
420 dbus_message_unref(msg);
421
422 DBusError err;
423 dbus_error_init(&err);
424 dbus_bus_remove_match(fd.connection, fd.path.utf8().get_data(), &err);
425 dbus_error_free(&err);
426 dbus_connection_unref(fd.connection);
427 remove = true;
428 break;
429 }
430 dbus_message_unref(msg);
431 }
432 dbus_connection_read_write(fd.connection, 0);
433 }
434 }
435 if (remove) {
436 portal->file_dialogs.remove_at(i);
437 }
438 }
439 }
440 usleep(50000);
441 }
442}
443
444FreeDesktopPortalDesktop::FreeDesktopPortalDesktop() {
445#ifdef SOWRAP_ENABLED
446#ifdef DEBUG_ENABLED
447 int dylibloader_verbose = 1;
448#else
449 int dylibloader_verbose = 0;
450#endif
451 unsupported = (initialize_dbus(dylibloader_verbose) != 0);
452#else
453 unsupported = false;
454#endif
455
456 if (unsupported) {
457 return;
458 }
459
460 bool ver_ok = false;
461 int version_major = 0;
462 int version_minor = 0;
463 int version_rev = 0;
464 dbus_get_version(&version_major, &version_minor, &version_rev);
465 ver_ok = (version_major == 1 && version_minor >= 10) || (version_major > 1); // 1.10.0
466 print_verbose(vformat("PortalDesktop: DBus %d.%d.%d detected.", version_major, version_minor, version_rev));
467 if (!ver_ok) {
468 print_verbose("PortalDesktop: Unsupported DBus library version!");
469 unsupported = true;
470 }
471
472 if (!unsupported) {
473 file_dialog_thread_abort.clear();
474 file_dialog_thread.start(FreeDesktopPortalDesktop::_thread_file_dialog_monitor, this);
475 }
476}
477
478FreeDesktopPortalDesktop::~FreeDesktopPortalDesktop() {
479 file_dialog_thread_abort.set();
480 if (file_dialog_thread.is_started()) {
481 file_dialog_thread.wait_to_finish();
482 }
483 for (FreeDesktopPortalDesktop::FileDialogData &fd : file_dialogs) {
484 if (fd.connection) {
485 DBusError err;
486 dbus_error_init(&err);
487 dbus_bus_remove_match(fd.connection, fd.path.utf8().get_data(), &err);
488 dbus_error_free(&err);
489 dbus_connection_unref(fd.connection);
490 }
491 }
492}
493
494#endif // DBUS_ENABLED
495