summaryrefslogtreecommitdiff
path: root/raveos-theme/gnome/theme-data/extensions/installed/ShutdownTimer@deminder/dbus-service/action.js
blob: 4b5bf9f4489e5719523fa8f587e62a8c88f4845d (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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
// SPDX-FileCopyrightText: 2023 Deminder <tremminder@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later

import Gio from 'gi://Gio';
import * as Control from './control.js';
import { proxyPromise } from '../modules/util.js';
import { pgettext as C_, gettext as _ } from '../modules/translation.js';
import { logDebug } from '../modules/util.js';

export const ACTIONS = {
  PowerOff: 0,
  Reboot: 1,
  Suspend: 2,
  SuspendThenHibernate: 3,
  Hibernate: 4,
  HybridSleep: 5,
  Halt: 6,
};

export const WAKE_ACTIONS = { wake: 100, 'no-wake': 101 };

/**
 * Get supported actions.
 * In order to show an error when shutdown or reboot are not supported
 * they are always included here. */
export async function* supportedActions() {
  const actionDbus = new Action();
  for await (const action of Object.keys(ACTIONS).map(async a =>
    ['PowerOff', 'Reboot'].includes(a) ||
    (await actionDbus.canShutdownAction(a))
      ? a
      : null
  )) {
    if (action) {
      yield action;
    }
  }
}

export class UnsupportedActionError extends Error {}

export class Action {
  #cancellable = new Gio.Cancellable();
  #cookie = null;

  #loginProxy = proxyPromise(
    'org.freedesktop.login1.Manager',
    Gio.DBus.system,
    'org.freedesktop.login1',
    '/org/freedesktop/login1',
    this.#cancellable
  );

  #screenSaverProxy = proxyPromise(
    'org.gnome.ScreenSaver',
    Gio.DBus.session,
    'org.gnome.ScreenSaver',
    '/org/gnome/ScreenSaver',
    this.#cancellable
  );

  #sessionProxy = proxyPromise(
    'org.gnome.SessionManager',
    Gio.DBus.session,
    'org.gnome.SessionManager',
    '/org/gnome/SessionManager',
    this.#cancellable
  );

  destroy() {
    if (this.#cancellable !== null) {
      this.#cancellable.cancel();
      this.#cancellable = null;
    }
  }

  #poweroffOrReboot(action) {
    return [ACTIONS.PowerOff, ACTIONS.Reboot].includes(ACTIONS[action]);
  }

  /**
   * Perform the shutdown action.
   *
   * @param {string} action the shutdown action
   * @param {boolean} showEndSessionDialog show the end session dialog or directly shutdown
   *
   * @returns {Promise} resolves on action completion
   */
  async shutdownAction(action, showEndSessionDialog) {
    if (!(action in ACTIONS))
      throw new Error(`Unknown shutdown action: ${action}`);
    logDebug('[shutdownAction]', action);

    await this.uninhibitSuspend();

    const screenSaverProxy = await this.#screenSaverProxy;
    const [screenSaverActive] = await screenSaverProxy.GetActiveAsync();
    if (
      showEndSessionDialog &&
      !screenSaverActive &&
      this.#poweroffOrReboot(action)
    ) {
      const sessionProxy = await this.#sessionProxy;
      if (action === 'PowerOff') {
        await sessionProxy.ShutdownAsync();
      } else {
        await sessionProxy.RebootAsync();
      }
    } else {
      const loginProxy = await this.#loginProxy;
      if (await this.canShutdownAction(action)) {
        await loginProxy[`${action}Async`](true);
      } else if (this.#poweroffOrReboot(action)) {
        await Control.shutdown('now', ACTIONS[action] === ACTIONS.Reboot);
      } else {
        throw new UnsupportedActionError();
      }
    }
  }

  /**
   * Check if a shutdown action can be performed (without authentication).
   *
   * @returns {Promise} resolves to `true` if action can be performed, otherwise `false`.
   */
  async canShutdownAction(action) {
    const loginProxy = await this.#loginProxy;
    if (!(action in ACTIONS))
      throw new Error(`Unknown shutdown action: ${action}`);
    const [result] = await loginProxy[`Can${action}Async`]();
    return result === 'yes';
  }

  /**
   * Schedule a wake after some minutes or cancel
   *
   * @param {boolean} wake
   * @param {number} minutes
   */
  async wakeAction(wake, minutes) {
    if (wake) {
      await Control.wake(minutes);
    } else {
      await Control.wakeCancel();
    }
  }

  async inhibitSuspend() {
    if (this.#cookie === null) {
      const sessionProxy = await this.#sessionProxy;
      const [cookie] = await sessionProxy.InhibitAsync(
        'user',
        0,
        'Inhibit by Shutdown Timer (GNOME-Shell extension)',
        /* Suspend flag */ 4
      );
      this.#cookie = cookie;
    }
  }

  async uninhibitSuspend() {
    if (this.#cookie !== null) {
      const sessionProxy = await this.#sessionProxy;
      await sessionProxy.UninhibitAsync(this.#cookie);
      this.#cookie = null;
    }
  }
}

/**
 * Get the translated action label
 *
 * @param action
 */
export function actionLabel(action) {
  return {
    SuspendThenHibernate: _('Suspend then Hibernate'),
    HybridSleep: _('Hybrid Sleep'),
    Hibernate: _('Hibernate'),
    Halt: _('Halt'),
    Suspend: _('Suspend'),
    PowerOff: _('Power Off'),
    Reboot: _('Restart'),
    wake: _('Wake'),
    'no-wake': _('No Wake'),
  }[action];
}

export function untilText(action) {
  return {
    SuspendThenHibernate: C_('untiltext', 'suspend and hibernate'),
    HybridSleep: C_('untiltext', 'hybrid sleep'),
    Hibernate: C_('untiltext', 'hibernate'),
    Halt: C_('untiltext', 'halt'),
    Suspend: C_('untiltext', 'suspend'),
    PowerOff: C_('untiltext', 'shutdown'),
    Reboot: C_('untiltext', 'reboot'),
    wake: C_('untiltext', 'wakeup'),
  }[action];
}

export function mapLegacyAction(action) {
  return action in ACTIONS || ['wake', ''].includes(action)
    ? action
    : {
        poweroff: 'PowerOff',
        shutdown: 'PowerOff',
        reboot: 'Reboot',
        suspend: 'Suspend',
      }[action] ??
        {
          p: 'PowerOff',
          r: 'Reboot',
          s: 'Suspend',
          h: 'SuspendThenHibernate',
        }[action[0].toLowerCase()];
}