freedesktop_portal_desktop.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  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, const Vector<String> &p_filter_mimes) {
  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. ERR_FAIL_COND(p_filter_names.size() != p_filter_mimes.size());
  171. dbus_message_iter_open_container(p_iter, DBUS_TYPE_DICT_ENTRY, nullptr, &dict_iter);
  172. dbus_message_iter_append_basic(&dict_iter, DBUS_TYPE_STRING, &filters_key);
  173. dbus_message_iter_open_container(&dict_iter, DBUS_TYPE_VARIANT, "a(sa(us))", &var_iter);
  174. dbus_message_iter_open_container(&var_iter, DBUS_TYPE_ARRAY, "(sa(us))", &arr_iter);
  175. for (int i = 0; i < p_filter_names.size(); i++) {
  176. DBusMessageIter struct_iter;
  177. DBusMessageIter array_iter;
  178. DBusMessageIter array_struct_iter;
  179. dbus_message_iter_open_container(&arr_iter, DBUS_TYPE_STRUCT, nullptr, &struct_iter);
  180. append_dbus_string(&struct_iter, p_filter_names[i]);
  181. dbus_message_iter_open_container(&struct_iter, DBUS_TYPE_ARRAY, "(us)", &array_iter);
  182. const String &flt_orig = p_filter_exts[i];
  183. String flt;
  184. for (int j = 0; j < flt_orig.length(); j++) {
  185. if (is_unicode_letter(flt_orig[j])) {
  186. flt += vformat("[%c%c]", String::char_lowercase(flt_orig[j]), String::char_uppercase(flt_orig[j]));
  187. } else {
  188. flt += flt_orig[j];
  189. }
  190. }
  191. int filter_slice_count = flt.get_slice_count(",");
  192. for (int j = 0; j < filter_slice_count; j++) {
  193. dbus_message_iter_open_container(&array_iter, DBUS_TYPE_STRUCT, nullptr, &array_struct_iter);
  194. String str = (flt.get_slice(",", j).strip_edges());
  195. {
  196. const unsigned flt_type = 0;
  197. dbus_message_iter_append_basic(&array_struct_iter, DBUS_TYPE_UINT32, &flt_type);
  198. }
  199. append_dbus_string(&array_struct_iter, str);
  200. dbus_message_iter_close_container(&array_iter, &array_struct_iter);
  201. }
  202. const String &mime = p_filter_mimes[i];
  203. filter_slice_count = mime.get_slice_count(",");
  204. for (int j = 0; j < filter_slice_count; j++) {
  205. dbus_message_iter_open_container(&array_iter, DBUS_TYPE_STRUCT, nullptr, &array_struct_iter);
  206. String str = mime.get_slicec(',', j).strip_edges();
  207. {
  208. const unsigned flt_type = 1;
  209. dbus_message_iter_append_basic(&array_struct_iter, DBUS_TYPE_UINT32, &flt_type);
  210. }
  211. append_dbus_string(&array_struct_iter, str);
  212. dbus_message_iter_close_container(&array_iter, &array_struct_iter);
  213. }
  214. dbus_message_iter_close_container(&struct_iter, &array_iter);
  215. dbus_message_iter_close_container(&arr_iter, &struct_iter);
  216. }
  217. dbus_message_iter_close_container(&var_iter, &arr_iter);
  218. dbus_message_iter_close_container(&dict_iter, &var_iter);
  219. dbus_message_iter_close_container(p_iter, &dict_iter);
  220. }
  221. void FreeDesktopPortalDesktop::append_dbus_dict_string(DBusMessageIter *p_iter, const String &p_key, const String &p_value, bool p_as_byte_array) {
  222. DBusMessageIter dict_iter;
  223. DBusMessageIter var_iter;
  224. dbus_message_iter_open_container(p_iter, DBUS_TYPE_DICT_ENTRY, nullptr, &dict_iter);
  225. append_dbus_string(&dict_iter, p_key);
  226. if (p_as_byte_array) {
  227. DBusMessageIter arr_iter;
  228. dbus_message_iter_open_container(&dict_iter, DBUS_TYPE_VARIANT, "ay", &var_iter);
  229. dbus_message_iter_open_container(&var_iter, DBUS_TYPE_ARRAY, "y", &arr_iter);
  230. CharString cs = p_value.utf8();
  231. const char *cs_ptr = cs.get_data();
  232. do {
  233. dbus_message_iter_append_basic(&arr_iter, DBUS_TYPE_BYTE, cs_ptr);
  234. } while (*cs_ptr++);
  235. dbus_message_iter_close_container(&var_iter, &arr_iter);
  236. } else {
  237. dbus_message_iter_open_container(&dict_iter, DBUS_TYPE_VARIANT, "s", &var_iter);
  238. append_dbus_string(&var_iter, p_value);
  239. }
  240. dbus_message_iter_close_container(&dict_iter, &var_iter);
  241. dbus_message_iter_close_container(p_iter, &dict_iter);
  242. }
  243. void FreeDesktopPortalDesktop::append_dbus_dict_bool(DBusMessageIter *p_iter, const String &p_key, bool p_value) {
  244. DBusMessageIter dict_iter;
  245. DBusMessageIter var_iter;
  246. dbus_message_iter_open_container(p_iter, DBUS_TYPE_DICT_ENTRY, nullptr, &dict_iter);
  247. append_dbus_string(&dict_iter, p_key);
  248. dbus_message_iter_open_container(&dict_iter, DBUS_TYPE_VARIANT, "b", &var_iter);
  249. {
  250. int val = p_value;
  251. dbus_message_iter_append_basic(&var_iter, DBUS_TYPE_BOOLEAN, &val);
  252. }
  253. dbus_message_iter_close_container(&dict_iter, &var_iter);
  254. dbus_message_iter_close_container(p_iter, &dict_iter);
  255. }
  256. 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) {
  257. ERR_FAIL_COND_V(dbus_message_iter_get_arg_type(p_iter) != DBUS_TYPE_UINT32, false);
  258. dbus_uint32_t resp_code;
  259. dbus_message_iter_get_basic(p_iter, &resp_code);
  260. if (resp_code != 0) {
  261. r_cancel = true;
  262. } else {
  263. r_cancel = false;
  264. ERR_FAIL_COND_V(!dbus_message_iter_next(p_iter), false);
  265. ERR_FAIL_COND_V(dbus_message_iter_get_arg_type(p_iter) != DBUS_TYPE_ARRAY, false);
  266. DBusMessageIter dict_iter;
  267. dbus_message_iter_recurse(p_iter, &dict_iter);
  268. while (dbus_message_iter_get_arg_type(&dict_iter) == DBUS_TYPE_DICT_ENTRY) {
  269. DBusMessageIter iter;
  270. dbus_message_iter_recurse(&dict_iter, &iter);
  271. if (dbus_message_iter_get_arg_type(&iter) == DBUS_TYPE_STRING) {
  272. const char *key;
  273. dbus_message_iter_get_basic(&iter, &key);
  274. dbus_message_iter_next(&iter);
  275. DBusMessageIter var_iter;
  276. dbus_message_iter_recurse(&iter, &var_iter);
  277. if (strcmp(key, "current_filter") == 0) { // (sa(us))
  278. if (dbus_message_iter_get_arg_type(&var_iter) == DBUS_TYPE_STRUCT) {
  279. DBusMessageIter struct_iter;
  280. dbus_message_iter_recurse(&var_iter, &struct_iter);
  281. while (dbus_message_iter_get_arg_type(&struct_iter) == DBUS_TYPE_STRING) {
  282. const char *value;
  283. dbus_message_iter_get_basic(&struct_iter, &value);
  284. String name = String::utf8(value);
  285. r_index = p_names.find(name);
  286. if (!dbus_message_iter_next(&struct_iter)) {
  287. break;
  288. }
  289. }
  290. }
  291. } else if (strcmp(key, "choices") == 0) { // a(ss) {
  292. if (dbus_message_iter_get_arg_type(&var_iter) == DBUS_TYPE_ARRAY) {
  293. DBusMessageIter struct_iter;
  294. dbus_message_iter_recurse(&var_iter, &struct_iter);
  295. while (dbus_message_iter_get_arg_type(&struct_iter) == DBUS_TYPE_STRUCT) {
  296. DBusMessageIter opt_iter;
  297. dbus_message_iter_recurse(&struct_iter, &opt_iter);
  298. const char *opt_key = nullptr;
  299. dbus_message_iter_get_basic(&opt_iter, &opt_key);
  300. String opt_skey = String::utf8(opt_key);
  301. dbus_message_iter_next(&opt_iter);
  302. const char *opt_val = nullptr;
  303. dbus_message_iter_get_basic(&opt_iter, &opt_val);
  304. String opt_sval = String::utf8(opt_val);
  305. if (p_ids.has(opt_skey)) {
  306. opt_skey = p_ids[opt_skey];
  307. if (opt_sval == "true") {
  308. r_options[opt_skey] = true;
  309. } else if (opt_sval == "false") {
  310. r_options[opt_skey] = false;
  311. } else {
  312. r_options[opt_skey] = opt_sval.to_int();
  313. }
  314. }
  315. if (!dbus_message_iter_next(&struct_iter)) {
  316. break;
  317. }
  318. }
  319. }
  320. } else if (strcmp(key, "uris") == 0) { // as
  321. if (dbus_message_iter_get_arg_type(&var_iter) == DBUS_TYPE_ARRAY) {
  322. DBusMessageIter uri_iter;
  323. dbus_message_iter_recurse(&var_iter, &uri_iter);
  324. while (dbus_message_iter_get_arg_type(&uri_iter) == DBUS_TYPE_STRING) {
  325. const char *value;
  326. dbus_message_iter_get_basic(&uri_iter, &value);
  327. r_urls.push_back(String::utf8(value).trim_prefix("file://").uri_decode());
  328. if (!dbus_message_iter_next(&uri_iter)) {
  329. break;
  330. }
  331. }
  332. }
  333. }
  334. }
  335. if (!dbus_message_iter_next(&dict_iter)) {
  336. break;
  337. }
  338. }
  339. }
  340. return true;
  341. }
  342. 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) {
  343. if (unsupported) {
  344. return FAILED;
  345. }
  346. ERR_FAIL_INDEX_V(int(p_mode), DisplayServer::FILE_DIALOG_MODE_SAVE_MAX, FAILED);
  347. ERR_FAIL_NULL_V(monitor_connection, FAILED);
  348. Vector<String> filter_names;
  349. Vector<String> filter_exts;
  350. Vector<String> filter_mimes;
  351. for (int i = 0; i < p_filters.size(); i++) {
  352. Vector<String> tokens = p_filters[i].split(";");
  353. if (tokens.size() >= 1) {
  354. String flt = tokens[0].strip_edges();
  355. String mime = (tokens.size() >= 2) ? tokens[2].strip_edges() : String();
  356. if (!flt.is_empty() || !mime.is_empty()) {
  357. if (tokens.size() >= 2) {
  358. if (flt == "*.*") {
  359. filter_exts.push_back("*");
  360. } else {
  361. filter_exts.push_back(flt);
  362. }
  363. filter_mimes.push_back(mime);
  364. filter_names.push_back(tokens[1]);
  365. } else {
  366. if (flt == "*.*") {
  367. filter_exts.push_back("*");
  368. filter_names.push_back(RTR("All Files") + " (*.*)");
  369. } else {
  370. filter_exts.push_back(flt);
  371. filter_names.push_back(flt);
  372. }
  373. filter_mimes.push_back(mime);
  374. }
  375. }
  376. }
  377. }
  378. if (filter_names.is_empty()) {
  379. filter_exts.push_back("*");
  380. filter_mimes.push_back("");
  381. filter_names.push_back(RTR("All Files") + " (*.*)");
  382. }
  383. DBusError err;
  384. dbus_error_init(&err);
  385. // Open connection and add signal handler.
  386. FileDialogData fd;
  387. fd.callback = p_callback;
  388. fd.prev_focus = p_window_id;
  389. fd.filter_names = filter_names;
  390. fd.opt_in_cb = p_options_in_cb;
  391. CryptoCore::RandomGenerator rng;
  392. ERR_FAIL_COND_V_MSG(rng.init(), FAILED, "Failed to initialize random number generator.");
  393. uint8_t uuid[64];
  394. Error rng_err = rng.get_random_bytes(uuid, 64);
  395. ERR_FAIL_COND_V_MSG(rng_err, rng_err, "Failed to generate unique token.");
  396. String dbus_unique_name = String::utf8(dbus_bus_get_unique_name(monitor_connection));
  397. String token = String::hex_encode_buffer(uuid, 64);
  398. String path = vformat("/org/freedesktop/portal/desktop/request/%s/%s", dbus_unique_name.replace(".", "_").replace(":", ""), token);
  399. fd.path = path;
  400. 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);
  401. dbus_bus_add_match(monitor_connection, fd.filter.utf8().get_data(), &err);
  402. if (dbus_error_is_set(&err)) {
  403. ERR_PRINT(vformat("Failed to add DBus match: %s", err.message));
  404. dbus_error_free(&err);
  405. return FAILED;
  406. }
  407. // Generate FileChooser message.
  408. const char *method = nullptr;
  409. if (p_mode == DisplayServer::FILE_DIALOG_MODE_SAVE_FILE) {
  410. method = "SaveFile";
  411. } else {
  412. method = "OpenFile";
  413. }
  414. DBusMessage *message = dbus_message_new_method_call(BUS_OBJECT_NAME, BUS_OBJECT_PATH, BUS_INTERFACE_FILE_CHOOSER, method);
  415. {
  416. DBusMessageIter iter;
  417. dbus_message_iter_init_append(message, &iter);
  418. append_dbus_string(&iter, p_xid);
  419. append_dbus_string(&iter, p_title);
  420. DBusMessageIter arr_iter;
  421. dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &arr_iter);
  422. append_dbus_dict_string(&arr_iter, "handle_token", token);
  423. append_dbus_dict_bool(&arr_iter, "multiple", p_mode == DisplayServer::FILE_DIALOG_MODE_OPEN_FILES);
  424. append_dbus_dict_bool(&arr_iter, "directory", p_mode == DisplayServer::FILE_DIALOG_MODE_OPEN_DIR);
  425. append_dbus_dict_filters(&arr_iter, filter_names, filter_exts, filter_mimes);
  426. append_dbus_dict_options(&arr_iter, p_options, fd.option_ids);
  427. append_dbus_dict_string(&arr_iter, "current_folder", p_current_directory, true);
  428. if (p_mode == DisplayServer::FILE_DIALOG_MODE_SAVE_FILE) {
  429. append_dbus_dict_string(&arr_iter, "current_name", p_filename);
  430. }
  431. dbus_message_iter_close_container(&iter, &arr_iter);
  432. }
  433. DBusMessage *reply = dbus_connection_send_with_reply_and_block(monitor_connection, message, DBUS_TIMEOUT_INFINITE, &err);
  434. dbus_message_unref(message);
  435. if (!reply || dbus_error_is_set(&err)) {
  436. ERR_PRINT(vformat("Failed to send DBus message: %s", err.message));
  437. dbus_error_free(&err);
  438. dbus_bus_remove_match(monitor_connection, fd.filter.utf8().get_data(), &err);
  439. return FAILED;
  440. }
  441. // Update signal path.
  442. {
  443. DBusMessageIter iter;
  444. if (dbus_message_iter_init(reply, &iter)) {
  445. if (dbus_message_iter_get_arg_type(&iter) == DBUS_TYPE_OBJECT_PATH) {
  446. const char *new_path = nullptr;
  447. dbus_message_iter_get_basic(&iter, &new_path);
  448. if (String::utf8(new_path) != path) {
  449. dbus_bus_remove_match(monitor_connection, fd.filter.utf8().get_data(), &err);
  450. if (dbus_error_is_set(&err)) {
  451. ERR_PRINT(vformat("Failed to remove DBus match: %s", err.message));
  452. dbus_error_free(&err);
  453. return FAILED;
  454. }
  455. fd.filter = String::utf8(new_path);
  456. dbus_bus_add_match(monitor_connection, fd.filter.utf8().get_data(), &err);
  457. if (dbus_error_is_set(&err)) {
  458. ERR_PRINT(vformat("Failed to add DBus match: %s", err.message));
  459. dbus_error_free(&err);
  460. return FAILED;
  461. }
  462. }
  463. }
  464. }
  465. }
  466. dbus_message_unref(reply);
  467. MutexLock lock(file_dialog_mutex);
  468. file_dialogs.push_back(fd);
  469. return OK;
  470. }
  471. void FreeDesktopPortalDesktop::process_file_dialog_callbacks() {
  472. MutexLock lock(file_dialog_mutex);
  473. while (!pending_cbs.is_empty()) {
  474. FileDialogCallback cb = pending_cbs.front()->get();
  475. pending_cbs.pop_front();
  476. if (cb.opt_in_cb) {
  477. Variant ret;
  478. Callable::CallError ce;
  479. const Variant *args[4] = { &cb.status, &cb.files, &cb.index, &cb.options };
  480. cb.callback.callp(args, 4, ret, ce);
  481. if (ce.error != Callable::CallError::CALL_OK) {
  482. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(cb.callback, args, 4, ce)));
  483. }
  484. } else {
  485. Variant ret;
  486. Callable::CallError ce;
  487. const Variant *args[3] = { &cb.status, &cb.files, &cb.index };
  488. cb.callback.callp(args, 3, ret, ce);
  489. if (ce.error != Callable::CallError::CALL_OK) {
  490. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(cb.callback, args, 3, ce)));
  491. }
  492. }
  493. }
  494. }
  495. void FreeDesktopPortalDesktop::_thread_monitor(void *p_ud) {
  496. FreeDesktopPortalDesktop *portal = (FreeDesktopPortalDesktop *)p_ud;
  497. while (!portal->monitor_thread_abort.is_set()) {
  498. if (portal->monitor_connection) {
  499. while (true) {
  500. DBusMessage *msg = dbus_connection_pop_message(portal->monitor_connection);
  501. if (!msg) {
  502. break;
  503. } else if (dbus_message_is_signal(msg, "org.freedesktop.portal.Settings", "SettingChanged")) {
  504. DBusMessageIter iter;
  505. if (dbus_message_iter_init(msg, &iter)) {
  506. const char *value;
  507. dbus_message_iter_get_basic(&iter, &value);
  508. String name_space = String::utf8(value);
  509. dbus_message_iter_next(&iter);
  510. dbus_message_iter_get_basic(&iter, &value);
  511. String key = String::utf8(value);
  512. if (name_space == "org.freedesktop.appearance" && key == "color-scheme") {
  513. callable_mp(portal, &FreeDesktopPortalDesktop::_system_theme_changed_callback).call_deferred();
  514. }
  515. }
  516. } else if (dbus_message_is_signal(msg, "org.freedesktop.portal.Request", "Response")) {
  517. String path = String::utf8(dbus_message_get_path(msg));
  518. MutexLock lock(portal->file_dialog_mutex);
  519. for (int i = 0; i < portal->file_dialogs.size(); i++) {
  520. FreeDesktopPortalDesktop::FileDialogData &fd = portal->file_dialogs.write[i];
  521. if (fd.path == path) {
  522. DBusMessageIter iter;
  523. if (dbus_message_iter_init(msg, &iter)) {
  524. bool cancel = false;
  525. Vector<String> uris;
  526. Dictionary options;
  527. int index = 0;
  528. file_chooser_parse_response(&iter, fd.filter_names, fd.option_ids, cancel, uris, index, options);
  529. if (fd.callback.is_valid()) {
  530. FileDialogCallback cb;
  531. cb.callback = fd.callback;
  532. cb.status = !cancel;
  533. cb.files = uris;
  534. cb.index = index;
  535. cb.options = options;
  536. cb.opt_in_cb = fd.opt_in_cb;
  537. portal->pending_cbs.push_back(cb);
  538. }
  539. if (fd.prev_focus != DisplayServer::INVALID_WINDOW_ID) {
  540. callable_mp(DisplayServer::get_singleton(), &DisplayServer::window_move_to_foreground).call_deferred(fd.prev_focus);
  541. }
  542. }
  543. DBusError err;
  544. dbus_error_init(&err);
  545. dbus_bus_remove_match(portal->monitor_connection, fd.filter.utf8().get_data(), &err);
  546. dbus_error_free(&err);
  547. portal->file_dialogs.remove_at(i);
  548. break;
  549. }
  550. }
  551. }
  552. dbus_message_unref(msg);
  553. }
  554. dbus_connection_read_write(portal->monitor_connection, 0);
  555. }
  556. OS::get_singleton()->delay_usec(50'000);
  557. }
  558. }
  559. void FreeDesktopPortalDesktop::_system_theme_changed_callback() {
  560. if (system_theme_changed.is_valid()) {
  561. Variant ret;
  562. Callable::CallError ce;
  563. system_theme_changed.callp(nullptr, 0, ret, ce);
  564. if (ce.error != Callable::CallError::CALL_OK) {
  565. ERR_PRINT(vformat("Failed to execute system theme changed callback: %s.", Variant::get_callable_error_text(system_theme_changed, nullptr, 0, ce)));
  566. }
  567. }
  568. }
  569. FreeDesktopPortalDesktop::FreeDesktopPortalDesktop() {
  570. #ifdef SOWRAP_ENABLED
  571. #ifdef DEBUG_ENABLED
  572. int dylibloader_verbose = 1;
  573. #else
  574. int dylibloader_verbose = 0;
  575. #endif
  576. unsupported = (initialize_dbus(dylibloader_verbose) != 0);
  577. #else
  578. unsupported = false;
  579. #endif
  580. if (unsupported) {
  581. return;
  582. }
  583. bool ver_ok = false;
  584. int version_major = 0;
  585. int version_minor = 0;
  586. int version_rev = 0;
  587. dbus_get_version(&version_major, &version_minor, &version_rev);
  588. ver_ok = (version_major == 1 && version_minor >= 10) || (version_major > 1); // 1.10.0
  589. print_verbose(vformat("PortalDesktop: DBus %d.%d.%d detected.", version_major, version_minor, version_rev));
  590. if (!ver_ok) {
  591. print_verbose("PortalDesktop: Unsupported DBus library version!");
  592. unsupported = true;
  593. }
  594. DBusError err;
  595. dbus_error_init(&err);
  596. monitor_connection = dbus_bus_get(DBUS_BUS_SESSION, &err);
  597. if (dbus_error_is_set(&err)) {
  598. dbus_error_free(&err);
  599. } else {
  600. theme_path = "type='signal',sender='org.freedesktop.portal.Desktop',interface='org.freedesktop.portal.Settings',member='SettingChanged'";
  601. dbus_bus_add_match(monitor_connection, theme_path.utf8().get_data(), &err);
  602. if (dbus_error_is_set(&err)) {
  603. dbus_error_free(&err);
  604. dbus_connection_unref(monitor_connection);
  605. monitor_connection = nullptr;
  606. }
  607. dbus_connection_read_write(monitor_connection, 0);
  608. }
  609. if (!unsupported) {
  610. monitor_thread_abort.clear();
  611. monitor_thread.start(FreeDesktopPortalDesktop::_thread_monitor, this);
  612. }
  613. }
  614. FreeDesktopPortalDesktop::~FreeDesktopPortalDesktop() {
  615. monitor_thread_abort.set();
  616. if (monitor_thread.is_started()) {
  617. monitor_thread.wait_to_finish();
  618. }
  619. if (monitor_connection) {
  620. DBusError err;
  621. for (FreeDesktopPortalDesktop::FileDialogData &fd : file_dialogs) {
  622. dbus_error_init(&err);
  623. dbus_bus_remove_match(monitor_connection, fd.filter.utf8().get_data(), &err);
  624. dbus_error_free(&err);
  625. }
  626. dbus_error_init(&err);
  627. dbus_bus_remove_match(monitor_connection, theme_path.utf8().get_data(), &err);
  628. dbus_error_free(&err);
  629. dbus_connection_unref(monitor_connection);
  630. }
  631. }
  632. #endif // DBUS_ENABLED