index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // SPDX-FileCopyrightText: GSConnect Developers https://github.com/GSConnect
  2. //
  3. // SPDX-License-Identifier: GPL-2.0-or-later
  4. import * as atspi from './atspi.js';
  5. import * as clipboard from './clipboard.js';
  6. import * as contacts from './contacts.js';
  7. import * as input from './input.js';
  8. import * as mpris from './mpris.js';
  9. import * as notification from './notification.js';
  10. import * as pulseaudio from './pulseaudio.js';
  11. import * as session from './session.js';
  12. import * as sound from './sound.js';
  13. import * as upower from './upower.js';
  14. import * as ydotool from './ydotool.js';
  15. export const functionOverrides = {};
  16. const components = {
  17. atspi,
  18. clipboard,
  19. contacts,
  20. input,
  21. mpris,
  22. notification,
  23. pulseaudio,
  24. session,
  25. sound,
  26. upower,
  27. ydotool,
  28. };
  29. /*
  30. * Singleton Tracker
  31. */
  32. const Default = new Map();
  33. /**
  34. * Acquire a reference to a component. Calls to this function should always be
  35. * followed by a call to `release()`.
  36. *
  37. * @param {string} name - The module name
  38. * @returns {*} The default instance of a component
  39. */
  40. export function acquire(name) {
  41. if (functionOverrides.acquire)
  42. return functionOverrides.acquire(name);
  43. let component;
  44. try {
  45. let info = Default.get(name);
  46. if (info === undefined) {
  47. const module = components[name];
  48. info = {
  49. instance: new module.default(),
  50. refcount: 0,
  51. };
  52. Default.set(name, info);
  53. }
  54. info.refcount++;
  55. component = info.instance;
  56. } catch (e) {
  57. debug(e, name);
  58. }
  59. return component;
  60. }
  61. /**
  62. * Release a reference on a component. If the caller was the last reference
  63. * holder, the component will be freed.
  64. *
  65. * @param {string} name - The module name
  66. * @returns {null} A %null value, useful for overriding a traced variable
  67. */
  68. export function release(name) {
  69. if (functionOverrides.release)
  70. return functionOverrides.release(name);
  71. try {
  72. const info = Default.get(name);
  73. if (info.refcount === 1) {
  74. info.instance.destroy();
  75. Default.delete(name);
  76. }
  77. info.refcount--;
  78. } catch (e) {
  79. debug(e, name);
  80. }
  81. return null;
  82. }