aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/DBus.js
blob: 9baaea0146ab5414e853339f5252b3aaed507d5f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { sessionBus } from 'dbus-next';
import { isLinux } from '../environment';

export default class DBus {
  bus = null;

  constructor(trayIcon) {
    this.trayIcon = trayIcon;
  }

  start() {
    if (!isLinux || this.bus) return;

    try {
      this.bus = sessionBus();
    } catch {
      // Error connecting to the bus.
      return;
    }

    // HACK Hook onto the MessageBus to track StatusNotifierWatchers
    this.bus._addMatch("type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',path='/org/freedesktop/DBus',member='NameOwnerChanged'");
    const mangled = JSON.stringify({
      path: '/org/freedesktop/DBus',
      interface: 'org.freedesktop.DBus',
      member: 'NameOwnerChanged',
    });
    this.bus._signals.on(mangled, (msg) => {
      const [name, oldOwner, newOwner] = msg.body;
      if (name === 'org.kde.StatusNotifierWatcher' && oldOwner !== newOwner && newOwner !== '') {
        // Leave ample time for the StatusNotifierWatcher to be initialized
        setTimeout(() => {
          this.trayIcon.recreateIfVisible();
        }, 400);
      }
    });
  }

  stop() {
    if (!this.bus) return;

    this.bus.disconnect();
    this.bus = null;
  }
}