sensorProxy.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* sensorProxy.js
  2. * Copyright (C) 2024 kosmospredanie, shyzus
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. */
  17. import Gio from 'gi://Gio';
  18. export class SensorProxy {
  19. constructor(rotate_cb) {
  20. this._rotate_cb = rotate_cb;
  21. this._proxy = null;
  22. this._enabled = false;
  23. this._watcher_id = Gio.bus_watch_name(
  24. Gio.BusType.SYSTEM,
  25. 'net.hadess.SensorProxy',
  26. Gio.BusNameWatcherFlags.NONE,
  27. this.appeared.bind(this),
  28. this.vanished.bind(this)
  29. );
  30. }
  31. destroy() {
  32. Gio.bus_unwatch_name(this._watcher_id);
  33. if (this._enabled) this.disable();
  34. this._proxy = null;
  35. }
  36. enable() {
  37. this._enabled = true;
  38. if (this._proxy === null) return;
  39. this._proxy.call_sync('ClaimAccelerometer', null, Gio.DBusCallFlags.NONE, -1, null);
  40. }
  41. disable() {
  42. this._enabled = false;
  43. if (this._proxy === null) return;
  44. this._proxy.call_sync('ReleaseAccelerometer', null, Gio.DBusCallFlags.NONE, -1, null);
  45. }
  46. appeared(_connection, _name, _name_owner) {
  47. this._proxy = Gio.DBusProxy.new_for_bus_sync(
  48. Gio.BusType.SYSTEM, Gio.DBusProxyFlags.NONE, null,
  49. 'net.hadess.SensorProxy', '/net/hadess/SensorProxy', 'net.hadess.SensorProxy',
  50. null);
  51. this._proxy.connect('g-properties-changed', this.properties_changed.bind(this));
  52. if (this._enabled) {
  53. this._proxy.call_sync('ClaimAccelerometer', null, Gio.DBusCallFlags.NONE, -1, null);
  54. }
  55. }
  56. vanished(_connection, _name) {
  57. this._proxy = null;
  58. }
  59. properties_changed(proxy, changed, _invalidated) {
  60. if (!this._enabled) return;
  61. let properties = changed.deep_unpack();
  62. for (let [name, value] of Object.entries(properties)) {
  63. if (name !== 'AccelerometerOrientation') continue;
  64. let target = value.unpack();
  65. this._rotate_cb(target);
  66. }
  67. }
  68. }