summaryrefslogtreecommitdiff
path: root/extension.js
blob: b08d77be285c584301cc2dddfee7a991c8ebdf45 (plain)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
// Copyright 2018 Bartosz Jaroszewski
// SPDX-License-Identifier: GPL-2.0-or-later
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

const Main = imports.ui.main;
const GLib = imports.gi.GLib;

const ExtensionUtils = imports.misc.extensionUtils;
const Me = ExtensionUtils.getCurrentExtension();
const UiExtension = Me.imports.ui;
const Bluetooth = Me.imports.bluetooth;
const Utils = Me.imports.utils;
const Settings = Me.imports.settings.Settings;


class BluetoothQuickConnect {
    constructor(bluetooth, settings) {
        this._logger = new Utils.Logger(settings);
        this._logger.info('Initializing extension');
        this._menu = bluetooth._item.menu;
        this._proxy = bluetooth._proxy;
        this._controller = new Bluetooth.BluetoothController();
        this._settings = settings

        this._items = {};
    }

    enable() {
        this._logger.info('Enabling extension');
        this._controller.enable();
        this._refresh();
        this._connectControllerSignals();
        this._connectIdleMonitor();
        this._connectMenuSignals();
    }

    _connectMenuSignals() {
        this._connectSignal(this._menu, 'open-state-changed', (menu, isOpen) => {
            this._logger.info(`Menu toggled: ${isOpen}`);
            if (isOpen)
                this._disconnectIdleMonitor()
            else
                this._connectIdleMonitor();

            if (isOpen && this._settings.isAutoPowerOnEnabled() && this._proxy.BluetoothAirplaneMode) {
                this._logger.info('Disabling airplane mode');
                this._proxy.BluetoothAirplaneMode = false;
            }
        });
    }

    disable() {
        this._logger.info('Disabling extension');
        this._destroy();
    }

    test() {
        try {
            this._logger.info('Testing bluetoothctl');
            GLib.spawn_command_line_sync("bluetoothctl --version");
            this._logger.info('Test succeeded');
        } catch (error) {
            Main.notifyError(_('Bluetooth quick connect'), _(`Error trying to execute "bluetoothctl"`));
            this._logger.info('Test failed');
        }
    }

    _connectControllerSignals() {
        this._logger.info('Connecting bluetooth controller signals');

        this._connectSignal(this._controller, 'device-inserted', (ctrl, device) => {
            this._logger.info(`Device inserted event: ${device.name}`);
            this._addMenuItem(device);
        });
        this._connectSignal(this._controller, 'device-changed', (ctrl, device) => {
            this._logger.info(`Device changed event: ${device.name}`);
            if (device.isDefault)
                this._refresh();
            else
                this._syncMenuItem(device);
        });
        this._connectSignal(this._controller, 'device-deleted', () => {
            this._logger.info(`Device deleted event`);
            this._refresh();
        });

        this._connectSignal(Main.sessionMode, 'updated', () => {
            this._refresh()
        });
    }

    _syncMenuItem(device) {
        this._logger.info(`Synchronizing device menu item: ${device.name}`);
        let item = this._items[device.mac] || this._addMenuItem(device);
        item.sync(device);
    }

    _addMenuItem(device) {
        this._logger.info(`Adding device menu item: ${device.name}`);
        let menuItem = new UiExtension.PopupBluetoothDeviceMenuItem(
            device,
            {
                showRefreshButton: this._settings.isShowRefreshButtonEnabled(),
                closeMenuOnAction: !this._settings.isKeepMenuOnToggleEnabled()
            }
        );
        this._items[device.mac] = menuItem;
        this._menu.addMenuItem(menuItem, 1);

        return menuItem;
    }

    _connectIdleMonitor() {
        if (this._idleMonitorId) return;

        this._logger.info('Connecting idle monitor');

        this._idleMonitorId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, this._settings.autoPowerOffCheckingInterval() * 1000, () => {
            if (this._settings.isAutoPowerOffEnabled() && this._controller.getConnectedDevices().length === 0)
                this._proxy.BluetoothAirplaneMode = true;

            return true;
        });
    }

    _disconnectIdleMonitor() {
        if (!this._idleMonitorId) return;

        this._logger.info('Disconnecting idle monitor');

        GLib.Source.remove(this._idleMonitorId);
        this._idleMonitorId = null;
    }

    _connectSignal(subject, signal_name, method) {
        let signal_id = subject.connect(signal_name, method);
        this._signals.push({
            subject: subject,
            signal_id: signal_id
        });
    }

    _refresh() {
        this._removeDevicesFromMenu();
        this._addDevicesToMenu();

        this._logger.info('Refreshing devices list');
    }

    _addDevicesToMenu() {
        this._controller.getDevices().forEach((device) => {
            this._addMenuItem(device);
        });
    }

    _removeDevicesFromMenu() {
        Object.values(this._items).forEach((item) => {
            item.destroy();
        });

        this._items = {};
    }

    _destroy() {
        this._disconnectSignals();
        this._removeDevicesFromMenu();
        this._disconnectIdleMonitor();
        if (this._controller)
            this._controller.destroy();
    }
}

Utils.addSignalsHelperMethods(BluetoothQuickConnect.prototype);


let bluetoothQuickConnect = null;

function init() {
    let bluetooth = Main.panel.statusArea.aggregateMenu._bluetooth;
    let settings = new Settings();
    bluetoothQuickConnect = new BluetoothQuickConnect(bluetooth, settings);
}

function enable() {
    bluetoothQuickConnect.test();
    bluetoothQuickConnect.enable();
}

function disable() {
    bluetoothQuickConnect.disable();
}