freedesktop_portal_desktop.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  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. #include "freedesktop_portal_desktop.h"
  31. #ifdef DBUS_ENABLED
  32. #include "core/crypto/crypto_core.h"
  33. #include "core/error/error_macros.h"
  34. #include "core/os/os.h"
  35. #include "core/string/ustring.h"
  36. #include "core/variant/variant.h"
  37. #ifdef SOWRAP_ENABLED
  38. #include "dbus-so_wrap.h"
  39. #else
  40. #include <dbus/dbus.h>
  41. #endif
  42. #include <unistd.h>
  43. #define BUS_OBJECT_NAME "org.freedesktop.portal.Desktop"
  44. #define BUS_OBJECT_PATH "/org/freedesktop/portal/desktop"
  45. #define BUS_INTERFACE_SETTINGS "org.freedesktop.portal.Settings"
  46. #define BUS_INTERFACE_FILE_CHOOSER "org.freedesktop.portal.FileChooser"
  47. bool FreeDesktopPortalDesktop::try_parse_variant(DBusMessage *p_reply_message, int p_type, void *r_value) {
  48. DBusMessageIter iter[3];
  49. dbus_message_iter_init(p_reply_message, &iter[0]);
  50. if (dbus_message_iter_get_arg_type(&iter[0]) != DBUS_TYPE_VARIANT) {
  51. return false;
  52. }
  53. dbus_message_iter_recurse(&iter[0], &iter[1]);
  54. if (dbus_message_iter_get_arg_type(&iter[1]) != DBUS_TYPE_VARIANT) {
  55. return false;
  56. }
  57. dbus_message_iter_recurse(&iter[1], &iter[2]);
  58. if (dbus_message_iter_get_arg_type(&iter[2]) != p_type) {
  59. return false;
  60. }
  61. dbus_message_iter_get_basic(&iter[2], r_value);
  62. return true;
  63. }
  64. bool FreeDesktopPortalDesktop::read_setting(const char *p_namespace, const char *p_key, int p_type, void *r_value) {
  65. if (unsupported) {
  66. return false;
  67. }
  68. DBusError error;
  69. dbus_error_init(&error);
  70. DBusConnection *bus = dbus_bus_get(DBUS_BUS_SESSION, &error);
  71. if (dbus_error_is_set(&error)) {
  72. if (OS::get_singleton()->is_stdout_verbose()) {
  73. ERR_PRINT(vformat("Error opening D-Bus connection: %s", error.message));
  74. }
  75. dbus_error_free(&error);
  76. unsupported = true;
  77. return false;
  78. }
  79. DBusMessage *message = dbus_message_new_method_call(
  80. BUS_OBJECT_NAME, BUS_OBJECT_PATH, BUS_INTERFACE_SETTINGS,
  81. "Read");
  82. dbus_message_append_args(
  83. message,
  84. DBUS_TYPE_STRING, &p_namespace,
  85. DBUS_TYPE_STRING, &p_key,
  86. DBUS_TYPE_INVALID);
  87. DBusMessage *reply = dbus_connection_send_with_reply_and_block(bus, message, 50, &error);
  88. dbus_message_unref(message);
  89. if (dbus_error_is_set(&error)) {
  90. if (OS::get_singleton()->is_stdout_verbose()) {
  91. ERR_PRINT(vformat("Error on D-Bus communication: %s", error.message));
  92. }
  93. dbus_error_free(&error);
  94. dbus_connection_unref(bus);
  95. return false;
  96. }
  97. bool success = try_parse_variant(reply, p_type, r_value);
  98. dbus_message_unref(reply);
  99. dbus_connection_unref(bus);
  100. return success;
  101. }
  102. uint32_t FreeDesktopPortalDesktop::get_appearance_color_scheme() {
  103. if (unsupported) {
  104. return 0;
  105. }
  106. uint32_t value = 0;
  107. read_setting("org.freedesktop.appearance", "color-scheme", DBUS_TYPE_UINT32, &value);
  108. return value;
  109. }
  110. static const char *cs_empty = "";
  111. void FreeDesktopPortalDesktop::append_dbus_string(DBusMessageIter *p_iter, const String &p_string) {
  112. CharString cs = p_string.utf8();
  113. const char *cs_ptr = cs.ptr();
  114. if (cs_ptr) {
  115. dbus_message_iter_append_basic(p_iter, DBUS_TYPE_STRING, &cs_ptr);
  116. } else {
  117. dbus_message_iter_append_basic(p_iter, DBUS_TYPE_STRING, &cs_empty);
  118. }
  119. }
  120. void FreeDesktopPortalDesktop::append_dbus_dict_options(DBusMessageIter *p_iter, const TypedArray<Dictionary> &p_options, HashMap<String, String> &r_ids) {
  121. DBusMessageIter dict_iter;
  122. DBusMessageIter var_iter;
  123. DBusMessageIter arr_iter;
  124. const char *choices_key = "choices";
  125. dbus_message_iter_open_container(p_iter, DBUS_TYPE_DICT_ENTRY, nullptr, &dict_iter);
  126. dbus_message_iter_append_basic(&dict_iter, DBUS_TYPE_STRING, &choices_key);
  127. dbus_message_iter_open_container(&dict_iter, DBUS_TYPE_VARIANT, "a(ssa(ss)s)", &var_iter);
  128. dbus_message_iter_open_container(&var_iter, DBUS_TYPE_ARRAY, "(ss(ss)s)", &arr_iter);
  129. r_ids.clear();
  130. for (int i = 0; i < p_options.size(); i++) {
  131. const Dictionary &item = p_options[i];
  132. if (!item.has("name") || !item.has("values") || !item.has("default")) {
  133. continue;
  134. }
  135. const String &name = item["name"];
  136. const Vector<String> &options = item["values"];
  137. int default_idx = item["default"];
  138. DBusMessageIter struct_iter;
  139. DBusMessageIter array_iter;
  140. DBusMessageIter array_struct_iter;
  141. dbus_message_iter_open_container(&arr_iter, DBUS_TYPE_STRUCT, nullptr, &struct_iter);
  142. append_dbus_string(&struct_iter, "option_" + itos(i)); // ID.
  143. append_dbus_string(&struct_iter, name); // User visible name.
  144. r_ids["option_" + itos(i)] = name;
  145. dbus_message_iter_open_container(&struct_iter, DBUS_TYPE_ARRAY, "(ss)", &array_iter);
  146. for (int j = 0; j < options.size(); j++) {
  147. dbus_message_iter_open_container(&array_iter, DBUS_TYPE_STRUCT, nullptr, &array_struct_iter);
  148. append_dbus_string(&array_struct_iter, itos(j));
  149. append_dbus_string(&array_struct_iter, options[j]);
  150. dbus_message_iter_close_container(&array_iter, &array_struct_iter);
  151. }
  152. dbus_message_iter_close_container(&struct_iter, &array_iter);
  153. if (options.is_empty()) {
  154. append_dbus_string(&struct_iter, (default_idx) ? "true" : "false"); // Default selection.
  155. } else {
  156. append_dbus_string(&struct_iter, itos(default_idx)); // Default selection.
  157. }
  158. dbus_message_iter_close_container(&arr_iter, &struct_iter);
  159. }
  160. dbus_message_iter_close_container(&var_iter, &arr_iter);
  161. dbus_message_iter_close_container(&dict_iter, &var_iter);
  162. dbus_message_iter_close_container(p_iter, &dict_iter);
  163. }
  164. void FreeDesktopPortalDesktop::append_dbus_dict_filters(DBusMessageIter *p_iter, const Vector<String> &p_filter_names, const Vector<String> &p_filter_exts) {
  165. DBusMessageIter dict_iter;
  166. DBusMessageIter var_iter;
  167. DBusMessageIter arr_iter;
  168. const char *filters_key = "filters";
  169. ERR_FAIL_COND(p_filter_names.size() != p_filter_exts.size());
  170. dbus_message_iter_open_container(p_iter, DBUS_TYPE_DICT_ENTRY, nullptr, &dict_iter);
  171. dbus_message_iter_append_basic(&dict_iter, DBUS_TYPE_STRING, &filters_key);
  172. dbus_message_iter_open_container(&dict_iter, DBUS_TYPE_VARIANT, "a(sa(us))", &var_iter);
  173. dbus_message_iter_open_container(&var_iter, DBUS_TYPE_ARRAY, "(sa(us))", &arr_iter);
  174. for (int i = 0; i < p_filter_names.size(); i++) {
  175. DBusMessageIter struct_iter;
  176. DBusMessageIter array_iter;
  177. DBusMessageIter array_struct_iter;
  178. dbus_message_iter_open_container(&arr_iter, DBUS_TYPE_STRUCT, nullptr, &struct_iter);
  179. append_dbus_string(&struct_iter, p_filter_names[i]);
  180. dbus_message_iter_open_container(&struct_iter, DBUS_TYPE_ARRAY, "(us)", &array_iter);
  181. const String &flt_orig = p_filter_exts[i];
  182. String flt;
  183. for (int j = 0; j < flt_orig.length(); j++) {
  184. if (is_unicode_letter(flt_orig[j])) {
  185. flt += vformat("[%c%c]", String::char_lowercase(flt_orig[j]), String::char_uppercase(flt_orig[j]));
  186. } else {
  187. flt += flt_orig[j];
  188. }
  189. }
  190. int filter_slice_count = flt.get_slice_count(",");
  191. for (int j = 0; j < filter_slice_count; j++) {
  192. dbus_message_iter_open_container(&array_iter, DBUS_TYPE_STRUCT, nullptr, &array_struct_iter);
  193. String str = (flt.get_slice(",", j).strip_edges());
  194. {
  195. const unsigned nil = 0;
  196. dbus_message_iter_append_basic(&array_struct_iter, DBUS_TYPE_UINT32, &nil);
  197. }
  198. append_dbus_string(&array_struct_iter, str);
  199. dbus_message_iter_close_container(&array_iter, &array_struct_iter);
  200. }
  201. dbus_message_iter_close_container(&struct_iter, &array_iter);
  202. dbus_message_iter_close_container(&arr_iter, &struct_iter);
  203. }
  204. dbus_message_iter_close_container(&var_iter, &arr_iter);
  205. dbus_message_iter_close_container(&dict_iter, &var_iter);
  206. dbus_message_iter_close_container(p_iter, &dict_iter);
  207. }
  208. void FreeDesktopPortalDesktop::append_dbus_dict_string(DBusMessageIter *p_iter, const String &p_key, const String &p_value, bool p_as_byte_array) {
  209. DBusMessageIter dict_iter;
  210. DBusMessageIter var_iter;
  211. dbus_message_iter_open_container(p_iter, DBUS_TYPE_DICT_ENTRY, nullptr, &dict_iter);
  212. append_dbus_string(&dict_iter, p_key);
  213. if (p_as_byte_array) {
  214. DBusMessageIter arr_iter;
  215. dbus_message_iter_open_container(&dict_iter, DBUS_TYPE_VARIANT, "ay", &var_iter);
  216. dbus_message_iter_open_container(&var_iter, DBUS_TYPE_ARRAY, "y", &arr_iter);
  217. CharString cs = p_value.utf8();
  218. const char *cs_ptr = cs.get_data();
  219. do {
  220. dbus_message_iter_append_basic(&arr_iter, DBUS_TYPE_BYTE, cs_ptr);
  221. } while (*cs_ptr++);
  222. dbus_message_iter_close_container(&var_iter, &arr_iter);
  223. } else {
  224. dbus_message_iter_open_container(&dict_iter, DBUS_TYPE_VARIANT, "s", &var_iter);
  225. append_dbus_string(&var_iter, p_value);
  226. }
  227. dbus_message_iter_close_container(&dict_iter, &var_iter);
  228. dbus_message_iter_close_container(p_iter, &dict_iter);
  229. }
  230. void FreeDesktopPortalDesktop::append_dbus_dict_bool(DBusMessageIter *p_iter, const String &p_key, bool p_value) {
  231. DBusMessageIter dict_iter;
  232. DBusMessageIter var_iter;
  233. dbus_message_iter_open_container(p_iter, DBUS_TYPE_DICT_ENTRY, nullptr, &dict_iter);
  234. append_dbus_string(&dict_iter, p_key);
  235. dbus_message_iter_open_container(&dict_iter, DBUS_TYPE_VARIANT, "b", &var_iter);
  236. {
  237. int val = p_value;
  238. dbus_message_iter_append_basic(&var_iter, DBUS_TYPE_BOOLEAN, &val);
  239. }
  240. dbus_message_iter_close_container(&dict_iter, &var_iter);
  241. dbus_message_iter_close_container(p_iter, &dict_iter);
  242. }
  243. bool FreeDesktopPortalDesktop::file_chooser_parse_response(DBusMessageIter *p_iter, const Vector<String> &p_names, const HashMap<String, String> &p_ids, bool &r_cancel, Vector<String> &r_urls, int &r_index, Dictionary &r_options) {
  244. ERR_FAIL_COND_V(dbus_message_iter_get_arg_type(p_iter) != DBUS_TYPE_UINT32, false);
  245. dbus_uint32_t resp_code;
  246. dbus_message_iter_get_basic(p_iter, &resp_code);
  247. if (resp_code != 0) {
  248. r_cancel = true;
  249. } else {
  250. r_cancel = false;
  251. ERR_FAIL_COND_V(!dbus_message_iter_next(p_iter), false);
  252. ERR_FAIL_COND_V(dbus_message_iter_get_arg_type(p_iter) != DBUS_TYPE_ARRAY, false);
  253. DBusMessageIter dict_iter;
  254. dbus_message_iter_recurse(p_iter, &dict_iter);
  255. while (dbus_message_iter_get_arg_type(&dict_iter) == DBUS_TYPE_DICT_ENTRY) {
  256. DBusMessageIter iter;
  257. dbus_message_iter_recurse(&dict_iter, &iter);
  258. if (dbus_message_iter_get_arg_type(&iter) == DBUS_TYPE_STRING) {
  259. const char *key;
  260. dbus_message_iter_get_basic(&iter, &key);
  261. dbus_message_iter_next(&iter);
  262. DBusMessageIter var_iter;
  263. dbus_message_iter_recurse(&iter, &var_iter);
  264. if (strcmp(key, "current_filter") == 0) { // (sa(us))
  265. if (dbus_message_iter_get_arg_type(&var_iter) == DBUS_TYPE_STRUCT) {
  266. DBusMessageIter struct_iter;
  267. dbus_message_iter_recurse(&var_iter, &struct_iter);
  268. while (dbus_message_iter_get_arg_type(&struct_iter) == DBUS_TYPE_STRING) {
  269. const char *value;
  270. dbus_message_iter_get_basic(&struct_iter, &value);
  271. String name = String::utf8(value);
  272. r_index = p_names.find(name);
  273. if (!dbus_message_iter_next(&struct_iter)) {
  274. break;
  275. }
  276. }
  277. }
  278. } else if (strcmp(key, "choices") == 0) { // a(ss) {
  279. if (dbus_message_iter_get_arg_type(&var_iter) == DBUS_TYPE_ARRAY) {
  280. DBusMessageIter struct_iter;
  281. dbus_message_iter_recurse(&var_iter, &struct_iter);
  282. while (dbus_message_iter_get_arg_type(&struct_iter) == DBUS_TYPE_STRUCT) {
  283. DBusMessageIter opt_iter;
  284. dbus_message_iter_recurse(&struct_iter, &opt_iter);
  285. const char *opt_key = nullptr;
  286. dbus_message_iter_get_basic(&opt_iter, &opt_key);
  287. String opt_skey = String::utf8(opt_key);
  288. dbus_message_iter_next(&opt_iter);
  289. const char *opt_val = nullptr;
  290. dbus_message_iter_get_basic(&opt_iter, &opt_val);
  291. String opt_sval = String::utf8(opt_val);
  292. if (p_ids.has(opt_skey)) {
  293. opt_skey = p_ids[opt_skey];
  294. if (opt_sval == "true") {
  295. r_options[opt_skey] = true;
  296. } else if (opt_sval == "false") {
  297. r_options[opt_skey] = false;
  298. } else {
  299. r_options[opt_skey] = opt_sval.to_int();
  300. }
  301. }
  302. if (!dbus_message_iter_next(&struct_iter)) {
  303. break;
  304. }
  305. }
  306. }
  307. } else if (strcmp(key, "uris") == 0) { // as
  308. if (dbus_message_iter_get_arg_type(&var_iter) == DBUS_TYPE_ARRAY) {
  309. DBusMessageIter uri_iter;
  310. dbus_message_iter_recurse(&var_iter, &uri_iter);
  311. while (dbus_message_iter_get_arg_type(&uri_iter) == DBUS_TYPE_STRING) {
  312. const char *value;
  313. dbus_message_iter_get_basic(&uri_iter, &value);
  314. r_urls.push_back(String::utf8(value).trim_prefix("file://").uri_decode());
  315. if (!dbus_message_iter_next(&uri_iter)) {
  316. break;
  317. }
  318. }
  319. }
  320. }
  321. }
  322. if (!dbus_message_iter_next(&dict_iter)) {
  323. break;
  324. }
  325. }
  326. }
  327. return true;
  328. }
  329. Error FreeDesktopPortalDesktop::file_dialog_show(DisplayServer::WindowID p_window_id, const String &p_xid, const String &p_title, const String &p_current_directory, const String &p_root, const String &p_filename, DisplayServer::FileDialogMode p_mode, const Vector<String> &p_filters, const TypedArray<Dictionary> &p_options, const Callable &p_callback, bool p_options_in_cb) {
  330. if (unsupported) {
  331. return FAILED;
  332. }
  333. ERR_FAIL_INDEX_V(int(p_mode), DisplayServer::FILE_DIALOG_MODE_SAVE_MAX, FAILED);
  334. ERR_FAIL_NULL_V(monitor_connection, FAILED);
  335. Vector<String> filter_names;
  336. Vector<String> filter_exts;
  337. for (int i = 0; i < p_filters.size(); i++) {
  338. Vector<String> tokens = p_filters[i].split(";");
  339. if (tokens.size() >= 1) {
  340. String flt = tokens[0].strip_edges();
  341. if (!flt.is_empty()) {
  342. if (tokens.size() == 2) {
  343. if (flt == "*.*") {
  344. filter_exts.push_back("*");
  345. } else {
  346. filter_exts.push_back(flt);
  347. }
  348. filter_names.push_back(tokens[1]);
  349. } else {
  350. if (flt == "*.*") {
  351. filter_exts.push_back("*");
  352. filter_names.push_back(RTR("All Files") + " (*.*)");
  353. } else {
  354. filter_exts.push_back(flt);
  355. filter_names.push_back(flt);
  356. }
  357. }
  358. }
  359. }
  360. }
  361. if (filter_names.is_empty()) {
  362. filter_exts.push_back("*");
  363. filter_names.push_back(RTR("All Files") + " (*.*)");
  364. }
  365. DBusError err;
  366. dbus_error_init(&err);
  367. // Open connection and add signal handler.
  368. FileDialogData fd;
  369. fd.callback = p_callback;
  370. fd.prev_focus = p_window_id;
  371. fd.filter_names = filter_names;
  372. fd.opt_in_cb = p_options_in_cb;
  373. CryptoCore::RandomGenerator rng;
  374. ERR_FAIL_COND_V_MSG(rng.init(), FAILED, "Failed to initialize random number generator.");
  375. uint8_t uuid[64];
  376. Error rng_err = rng.get_random_bytes(uuid, 64);
  377. ERR_FAIL_COND_V_MSG(rng_err, rng_err, "Failed to generate unique token.");
  378. String dbus_unique_name = String::utf8(dbus_bus_get_unique_name(monitor_connection));
  379. String token = String::hex_encode_buffer(uuid, 64);
  380. String path = vformat("/org/freedesktop/portal/desktop/request/%s/%s", dbus_unique_name.replace(".", "_").replace(":", ""), token);
  381. fd.path = path;
  382. fd.filter = vformat("type='signal',sender='org.freedesktop.portal.Desktop',path='%s',interface='org.freedesktop.portal.Request',member='Response',destination='%s'", path, dbus_unique_name);
  383. dbus_bus_add_match(monitor_connection, fd.filter.utf8().get_data(), &err);
  384. if (dbus_error_is_set(&err)) {
  385. ERR_PRINT(vformat("Failed to add DBus match: %s", err.message));
  386. dbus_error_free(&err);
  387. return FAILED;
  388. }
  389. // Generate FileChooser message.
  390. const char *method = nullptr;
  391. if (p_mode == DisplayServer::FILE_DIALOG_MODE_SAVE_FILE) {
  392. method = "SaveFile";
  393. } else {
  394. method = "OpenFile";
  395. }
  396. DBusMessage *message = dbus_message_new_method_call(BUS_OBJECT_NAME, BUS_OBJECT_PATH, BUS_INTERFACE_FILE_CHOOSER, method);
  397. {
  398. DBusMessageIter iter;
  399. dbus_message_iter_init_append(message, &iter);
  400. append_dbus_string(&iter, p_xid);
  401. append_dbus_string(&iter, p_title);
  402. DBusMessageIter arr_iter;
  403. dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &arr_iter);
  404. append_dbus_dict_string(&arr_iter, "handle_token", token);
  405. append_dbus_dict_bool(&arr_iter, "multiple", p_mode == DisplayServer::FILE_DIALOG_MODE_OPEN_FILES);
  406. append_dbus_dict_bool(&arr_iter, "directory", p_mode == DisplayServer::FILE_DIALOG_MODE_OPEN_DIR);
  407. append_dbus_dict_filters(&arr_iter, filter_names, filter_exts);
  408. append_dbus_dict_options(&arr_iter, p_options, fd.option_ids);
  409. append_dbus_dict_string(&arr_iter, "current_folder", p_current_directory, true);
  410. if (p_mode == DisplayServer::FILE_DIALOG_MODE_SAVE_FILE) {
  411. append_dbus_dict_string(&arr_iter, "current_name", p_filename);
  412. }
  413. dbus_message_iter_close_container(&iter, &arr_iter);
  414. }
  415. DBusMessage *reply = dbus_connection_send_with_reply_and_block(monitor_connection, message, DBUS_TIMEOUT_INFINITE, &err);
  416. dbus_message_unref(message);
  417. if (!reply || dbus_error_is_set(&err)) {
  418. ERR_PRINT(vformat("Failed to send DBus message: %s", err.message));
  419. dbus_error_free(&err);
  420. dbus_bus_remove_match(monitor_connection, fd.filter.utf8().get_data(), &err);
  421. return FAILED;
  422. }
  423. // Update signal path.
  424. {
  425. DBusMessageIter iter;
  426. if (dbus_message_iter_init(reply, &iter)) {
  427. if (dbus_message_iter_get_arg_type(&iter) == DBUS_TYPE_OBJECT_PATH) {
  428. const char *new_path = nullptr;
  429. dbus_message_iter_get_basic(&iter, &new_path);
  430. if (String::utf8(new_path) != path) {
  431. dbus_bus_remove_match(monitor_connection, fd.filter.utf8().get_data(), &err);
  432. if (dbus_error_is_set(&err)) {
  433. ERR_PRINT(vformat("Failed to remove DBus match: %s", err.message));
  434. dbus_error_free(&err);
  435. return FAILED;
  436. }
  437. fd.filter = String::utf8(new_path);
  438. dbus_bus_add_match(monitor_connection, fd.filter.utf8().get_data(), &err);
  439. if (dbus_error_is_set(&err)) {
  440. ERR_PRINT(vformat("Failed to add DBus match: %s", err.message));
  441. dbus_error_free(&err);
  442. return FAILED;
  443. }
  444. }
  445. }
  446. }
  447. }
  448. dbus_message_unref(reply);
  449. MutexLock lock(file_dialog_mutex);
  450. file_dialogs.push_back(fd);
  451. return OK;
  452. }
  453. void FreeDesktopPortalDesktop::process_file_dialog_callbacks() {
  454. MutexLock lock(file_dialog_mutex);
  455. while (!pending_cbs.is_empty()) {
  456. FileDialogCallback cb = pending_cbs.front()->get();
  457. pending_cbs.pop_front();
  458. if (cb.opt_in_cb) {
  459. Variant ret;
  460. Callable::CallError ce;
  461. const Variant *args[4] = { &cb.status, &cb.files, &cb.index, &cb.options };
  462. cb.callback.callp(args, 4, ret, ce);
  463. if (ce.error != Callable::CallError::CALL_OK) {
  464. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(cb.callback, args, 4, ce)));
  465. }
  466. } else {
  467. Variant ret;
  468. Callable::CallError ce;
  469. const Variant *args[3] = { &cb.status, &cb.files, &cb.index };
  470. cb.callback.callp(args, 3, ret, ce);
  471. if (ce.error != Callable::CallError::CALL_OK) {
  472. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(cb.callback, args, 3, ce)));
  473. }
  474. }
  475. }
  476. }
  477. void FreeDesktopPortalDesktop::_thread_monitor(void *p_ud) {
  478. FreeDesktopPortalDesktop *portal = (FreeDesktopPortalDesktop *)p_ud;
  479. while (!portal->monitor_thread_abort.is_set()) {
  480. if (portal->monitor_connection) {
  481. while (true) {
  482. DBusMessage *msg = dbus_connection_pop_message(portal->monitor_connection);
  483. if (!msg) {
  484. break;
  485. } else if (dbus_message_is_signal(msg, "org.freedesktop.portal.Settings", "SettingChanged")) {
  486. DBusMessageIter iter;
  487. if (dbus_message_iter_init(msg, &iter)) {
  488. const char *value;
  489. dbus_message_iter_get_basic(&iter, &value);
  490. String name_space = String::utf8(value);
  491. dbus_message_iter_next(&iter);
  492. dbus_message_iter_get_basic(&iter, &value);
  493. String key = String::utf8(value);
  494. if (name_space == "org.freedesktop.appearance" && key == "color-scheme") {
  495. callable_mp(portal, &FreeDesktopPortalDesktop::_system_theme_changed_callback).call_deferred();
  496. }
  497. }
  498. } else if (dbus_message_is_signal(msg, "org.freedesktop.portal.Request", "Response")) {
  499. String path = String::utf8(dbus_message_get_path(msg));
  500. MutexLock lock(portal->file_dialog_mutex);
  501. for (int i = 0; i < portal->file_dialogs.size(); i++) {
  502. FreeDesktopPortalDesktop::FileDialogData &fd = portal->file_dialogs.write[i];
  503. if (fd.path == path) {
  504. DBusMessageIter iter;
  505. if (dbus_message_iter_init(msg, &iter)) {
  506. bool cancel = false;
  507. Vector<String> uris;
  508. Dictionary options;
  509. int index = 0;
  510. file_chooser_parse_response(&iter, fd.filter_names, fd.option_ids, cancel, uris, index, options);
  511. if (fd.callback.is_valid()) {
  512. FileDialogCallback cb;
  513. cb.callback = fd.callback;
  514. cb.status = !cancel;
  515. cb.files = uris;
  516. cb.index = index;
  517. cb.options = options;
  518. cb.opt_in_cb = fd.opt_in_cb;
  519. portal->pending_cbs.push_back(cb);
  520. }
  521. if (fd.prev_focus != DisplayServer::INVALID_WINDOW_ID) {
  522. callable_mp(DisplayServer::get_singleton(), &DisplayServer::window_move_to_foreground).call_deferred(fd.prev_focus);
  523. }
  524. }
  525. DBusError err;
  526. dbus_error_init(&err);
  527. dbus_bus_remove_match(portal->monitor_connection, fd.filter.utf8().get_data(), &err);
  528. dbus_error_free(&err);
  529. portal->file_dialogs.remove_at(i);
  530. break;
  531. }
  532. }
  533. }
  534. dbus_message_unref(msg);
  535. }
  536. dbus_connection_read_write(portal->monitor_connection, 0);
  537. }
  538. OS::get_singleton()->delay_usec(50'000);
  539. }
  540. }
  541. void FreeDesktopPortalDesktop::_system_theme_changed_callback() {
  542. if (system_theme_changed.is_valid()) {
  543. Variant ret;
  544. Callable::CallError ce;
  545. system_theme_changed.callp(nullptr, 0, ret, ce);
  546. if (ce.error != Callable::CallError::CALL_OK) {
  547. ERR_PRINT(vformat("Failed to execute system theme changed callback: %s.", Variant::get_callable_error_text(system_theme_changed, nullptr, 0, ce)));
  548. }
  549. }
  550. }
  551. FreeDesktopPortalDesktop::FreeDesktopPortalDesktop() {
  552. #ifdef SOWRAP_ENABLED
  553. #ifdef DEBUG_ENABLED
  554. int dylibloader_verbose = 1;
  555. #else
  556. int dylibloader_verbose = 0;
  557. #endif
  558. unsupported = (initialize_dbus(dylibloader_verbose) != 0);
  559. #else
  560. unsupported = false;
  561. #endif
  562. if (unsupported) {
  563. return;
  564. }
  565. bool ver_ok = false;
  566. int version_major = 0;
  567. int version_minor = 0;
  568. int version_rev = 0;
  569. dbus_get_version(&version_major, &version_minor, &version_rev);
  570. ver_ok = (version_major == 1 && version_minor >= 10) || (version_major > 1); // 1.10.0
  571. print_verbose(vformat("PortalDesktop: DBus %d.%d.%d detected.", version_major, version_minor, version_rev));
  572. if (!ver_ok) {
  573. print_verbose("PortalDesktop: Unsupported DBus library version!");
  574. unsupported = true;
  575. }
  576. DBusError err;
  577. dbus_error_init(&err);
  578. monitor_connection = dbus_bus_get(DBUS_BUS_SESSION, &err);
  579. if (dbus_error_is_set(&err)) {
  580. dbus_error_free(&err);
  581. } else {
  582. theme_path = "type='signal',sender='org.freedesktop.portal.Desktop',interface='org.freedesktop.portal.Settings',member='SettingChanged'";
  583. dbus_bus_add_match(monitor_connection, theme_path.utf8().get_data(), &err);
  584. if (dbus_error_is_set(&err)) {
  585. dbus_error_free(&err);
  586. dbus_connection_unref(monitor_connection);
  587. monitor_connection = nullptr;
  588. }
  589. dbus_connection_read_write(monitor_connection, 0);
  590. }
  591. if (!unsupported) {
  592. monitor_thread_abort.clear();
  593. monitor_thread.start(FreeDesktopPortalDesktop::_thread_monitor, this);
  594. }
  595. }
  596. FreeDesktopPortalDesktop::~FreeDesktopPortalDesktop() {
  597. monitor_thread_abort.set();
  598. if (monitor_thread.is_started()) {
  599. monitor_thread.wait_to_finish();
  600. }
  601. if (monitor_connection) {
  602. DBusError err;
  603. for (FreeDesktopPortalDesktop::FileDialogData &fd : file_dialogs) {
  604. dbus_error_init(&err);
  605. dbus_bus_remove_match(monitor_connection, fd.filter.utf8().get_data(), &err);
  606. dbus_error_free(&err);
  607. }
  608. dbus_error_init(&err);
  609. dbus_bus_remove_match(monitor_connection, theme_path.utf8().get_data(), &err);
  610. dbus_error_free(&err);
  611. dbus_connection_unref(monitor_connection);
  612. }
  613. }
  614. #endif // DBUS_ENABLED