utils.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import Gio from 'gi://Gio';
  2. import GLib from 'gi://GLib';
  3. /** Launch the given app
  4. *
  5. * @param {string[]} command
  6. * @returns
  7. */
  8. export function launchApp(command) {
  9. try {
  10. Gio.Subprocess.new(command, Gio.SubprocessFlags.NONE);
  11. return true;
  12. } catch (e) {
  13. console.warn(`Failed launch : ${e}`);
  14. return false;
  15. }
  16. }
  17. /** Load the configuration stored at `name`.
  18. *
  19. * @param {string} name configuration file path
  20. * @param {(a: any) => void} callback a function called when the result is returned
  21. * @param {() => void} errorCallback function called to handle errors
  22. * @returns
  23. */
  24. export function loadConfiguration(name, callback, errorCallback) {
  25. const f = Gio.File.new_for_path(name);
  26. f.load_contents_async(null, (file, res) => {
  27. try {
  28. let r = file?.load_contents_finish(res);
  29. if (!r || !r[0] || !r[1].length) {
  30. errorCallback();
  31. return;
  32. }
  33. const conf = JSON.parse(new TextDecoder().decode(r[1]));
  34. callback(conf);
  35. } catch (e) {
  36. if (e instanceof Gio.IOErrorEnum ||
  37. e.matches?.(Gio.IOErrorEnum, Gio.IOErrorEnum.NOT_FOUND))
  38. errorCallback?.();
  39. else
  40. logError(e);
  41. }
  42. });
  43. }
  44. /** Save the keybinding configuration stored in `obj` in the file `name`.
  45. *
  46. * @param {string} name configuration file name
  47. * @param {object} obj Object to save
  48. */
  49. export function saveConfiguration(name, obj) {
  50. const userPath = GLib.get_user_config_dir();
  51. const parentPath = GLib.build_filenamev([userPath, '/grimble/config']);
  52. const parent = Gio.File.new_for_path(parentPath);
  53. try {
  54. parent.make_directory_with_parents(null);
  55. } catch (e) {
  56. if (e.code !== Gio.IOErrorEnum.EXISTS)
  57. throw e;
  58. }
  59. const path = GLib.build_filenamev([parentPath, `/${name}`]);
  60. const f = Gio.File.new_for_path(path);
  61. try {
  62. f.create(Gio.FileCreateFlags.NONE, null);
  63. } catch (e) {
  64. if (e.code !== Gio.IOErrorEnum.EXISTS)
  65. throw e;
  66. }
  67. const data = new TextEncoder().encode(JSON.stringify(obj));
  68. f.replace_contents_async(data, null, false, Gio.FileCreateFlags.REPLACE_DESTINATION, null, (file, res) => {
  69. try {
  70. file?.replace_contents_finish(res);
  71. } catch (e) {
  72. logError(e);
  73. }
  74. });
  75. }