Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: cecfac30ac252f0f22ec16fe2a1497d65006d5ec (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
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/*******************************************************************************
 * Copyright (c) 2019 Syntevo and others. All rights reserved.
 * The contents of this file are made available under the terms
 * of the GNU Lesser General Public License (LGPL) Version 2.1 that
 * accompanies this distribution (lgpl-v21.txt).  The LGPL is also
 * available at http://www.gnu.org/licenses/lgpl.html.  If the version
 * of the LGPL at http://www.gnu.org is different to the version of
 * the LGPL accompanying this distribution and there is any conflict
 * between the two license versions, the terms of the LGPL accompanying
 * this distribution shall govern.
 *
 * Contributors:
 *     Syntevo - initial API and implementation
 *******************************************************************************/
package org.eclipse.swt.internal;

import org.eclipse.swt.internal.gtk.OS;

import java.util.ArrayList;

/**
 * Communicates with session manager to receive logoff/shutdown events.
 *
 * GTK also has an implementation (see gtk_application_impl_dbus_startup)
 * However, it requires GtkApplication, and SWT doesn't use that.
 *
 * Current session manager clients can be seen in:
 *   Gnome:
 *     dbus-send --print-reply --dest=org.gnome.SessionManager /org/gnome/SessionManager org.gnome.SessionManager.GetClients
 *   XFCE:
 *     dbus-send --print-reply --dest=org.xfce.SessionManager /org/xfce/SessionManager org.xfce.Session.Manager.ListClients
 *
 * If you know clientObjectPath, you can send Stop signal with:
 *   dbus-send --print-reply --dest=org.gnome.SessionManager /org/gnome/SessionManager/ClientXX org.gnome.SessionManager.Client.Stop
 */
public class SessionManagerDBus {
	public interface IListener {
		/**
		 * Are you ready to exit?
		 *
		 * Time limit imposed by session manager is 1 second.
		 * Final cleanup should happen in stop().
		 * @return false to hint that you're not ready. Session manager can ignore the hint.
		 */
		boolean isReadyToExit();

		/**
		 * Perform final cleanup here.
		 *
		 * Please note that time limit imposed by session manager is 10 seconds.
		 */
		void stop();
	}

	private ArrayList<IListener> listeners = new ArrayList<IListener>();
	private Callback g_signal_callback;
	private long sessionManagerProxy;
	private long clientProxy;
	private String clientObjectPath;
	private boolean isGnome;

	private static int dbusTimeoutMsec = 10000;

	public SessionManagerDBus() {
		// Allow to disable session manager, for example in case it conflicts with
		// session manager connection implemented in application itself.
		boolean isDisabled = System.getProperty("org.eclipse.swt.internal.SessionManagerDBus.disable") != null;
		if (isDisabled) return;

		start();
	}

	public void dispose() {
		stop();
	}

	/**
	 * Subscribes display for session manager events.
	 *
	 * Display will receive SWT.Close and will be able to hint that the session should not end.
	 * Please note that time limit imposed by session manager is 1 second.
	 * Final cleanup should happen at Display.dispose().
	 *
	 * Display will be disposed before session ends, allowing final cleanup to happen.
	 * Please note that time limit imposed by session manager is 10 seconds.
	 */
	public void addListener(IListener listener) {
		listeners.add(listener);
	}

	public void removeListener(IListener listener) {
		listeners.remove(listener);
	}

	private boolean start() {
		if (!connectSessionManager() || !registerClient() || !connectClientSignal()) {
			stop();
			return false;
		}

		return true;
	}

	/**
	 * Un-subscribes from session manager events.
	 *
	 * NOTE: Both Gnome and XFCE will automatically remove client record
	 * when client's process ends, so it's not a big deal if this is not
	 * called at all. See comments for this class to find 'dbus-send'
	 * commands to verify that.
	 */
	private void stop() {
		if ((sessionManagerProxy != 0) && (clientObjectPath != null)) {
			long args = OS.g_variant_new(
					Converter.javaStringToCString("(o)"), //$NON-NLS-1$
					Converter.javaStringToCString(clientObjectPath));

			long [] error = new long [1];
			OS.g_dbus_proxy_call_sync(
					sessionManagerProxy,
					Converter.javaStringToCString("UnregisterClient"), //$NON-NLS-1$
					args,
					OS.G_DBUS_CALL_FLAGS_NONE,
					dbusTimeoutMsec,
					0,
					error);

			if (error[0] != 0) {
				System.err.format(
						"SWT SessionManagerDBus: Failed to UnregisterClient: %s%n",
						extractFreeGError(error[0]));
			}

			clientObjectPath = null;
		}

		if (clientProxy != 0) {
			OS.g_object_unref(clientProxy);
			clientProxy = 0;
		}

		if (sessionManagerProxy != 0) {
			OS.g_object_unref(sessionManagerProxy);
			sessionManagerProxy = 0;
		}

		if (g_signal_callback != null) {
			g_signal_callback.dispose();
			g_signal_callback = null;
		}
	}

	private void sendEndSessionResponse(boolean is_ok, String reason) {
		long args = OS.g_variant_new(
				Converter.javaStringToCString("(bs)"), //$NON-NLS-1$
				is_ok,
				Converter.javaStringToCString(reason));

		long [] error = new long [1];
		OS.g_dbus_proxy_call(
				clientProxy,
				Converter.javaStringToCString("EndSessionResponse"), //$NON-NLS-1$
				args,
				OS.G_DBUS_CALL_FLAGS_NONE,
				dbusTimeoutMsec,
				0,
				0,
				error);

		if (error[0] != 0) {
			System.err.format(
					"SWT SessionManagerDBus: Failed to EndSessionResponse: %s%n",
					extractFreeGError(error[0]));
		}
	}

	private boolean isReadyToExit() {
		boolean isReady = true;

		// Inform everyone even if someone is not ready.
		for (int i = 0; i < listeners.size(); i++) {
			IListener listener = listeners.get(i);
			isReady = isReady && listener.isReadyToExit();
		}

		return isReady;
	}

	private void handleStop() {
		for (int i = 0; i < listeners.size(); i++) {
			IListener listener = listeners.get(i);
			listener.stop();
		}
	}

	/**
	 * Receives events from session manager.
	 *
	 * Docs: https://developer.gnome.org/gio/stable/GDBusProxy.html#GDBusProxy-g-signal
	 * NOTE: Will be called through native callback.
	 * @see this.g_signal_callback
	 * @return Error string in case of error, null if successful.
	 */
	@SuppressWarnings("unused")
	private long g_signal_handler(long proxy, long sender_name, long signal_name, long parameters, long user_data) {
		String signalName = Converter.cCharPtrToJavaString(signal_name, false);

		switch (signalName) {
			case "QueryEndSession": //$NON-NLS-1$
				sendEndSessionResponse(isReadyToExit(), "");
				break;
			case "EndSession": //$NON-NLS-1$
				handleStop();
				// Only respond after we've done, or session can end while we're still working.
				// Even if we don't want the session to end, I don't think sending 'false' here can be of any help.
				sendEndSessionResponse(true, "");
				break;
			case "Stop":
				handleStop();
				break;
		}

		// DBus expects 'void', but to make it easier to use with 'Callback' I return 'long'.
		return 0;
	}

	private static String extractVariantTupleS(long variant) {
		long childVariant = OS.g_variant_get_child_value(variant, 0);
		long childString = OS.g_variant_get_string(childVariant, null);

		String result = Converter.cCharPtrToJavaString(childString, false);

		OS.g_variant_unref(childVariant);
		return result;
	}

	private static String extractFreeGError(long errorPtr) {
		long errorMessageC = OS.g_error_get_message(errorPtr);
		String errorMessageStr = Converter.cCharPtrToJavaString(errorMessageC, false);
		OS.g_error_free(errorPtr);
		return errorMessageStr;
	}

	/**
	 * Creates a connection to the session manager.
	 *
	 * Saves result to member variable when successful.
	 * @return Error string in case of error, null if successful.
	 */
	private String connectSessionManager(String dbusName, String objectPath, String interfaceName) {
		int sessionManagerFlags =
				OS.G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START |
				OS.G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES |
				OS.G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS;

		long [] error = new long [1];
		long proxy = OS.g_dbus_proxy_new_for_bus_sync(
				OS.G_BUS_TYPE_SESSION,
				sessionManagerFlags,
				0,
				Converter.javaStringToCString(dbusName),
				Converter.javaStringToCString(objectPath),
				Converter.javaStringToCString(interfaceName),
				0,
				error);

		// Proxy is usually created even for non-existent service names.
		if (proxy == 0) return extractFreeGError(error[0]);

		// Is the service actually present?
		long owner = OS.g_dbus_proxy_get_name_owner(proxy);
		if (owner == 0) {
			OS.g_object_unref(proxy);
			return "Service not present";
		}
		OS.g_free(owner);

		// Success
		sessionManagerProxy = proxy;
		return null;
	}

	private boolean connectSessionManager() {
		String errorGnome = connectSessionManager(
				"org.gnome.SessionManager",     //$NON-NLS-1$
				"/org/gnome/SessionManager",    //$NON-NLS-1$
				"org.gnome.SessionManager");	//$NON-NLS-1$

		if (errorGnome == null) {
			isGnome = true;
			return true;
		}

		String errorXCFE = connectSessionManager(
				"org.xfce.SessionManager",		//$NON-NLS-1$
				"/org/xfce/SessionManager",		//$NON-NLS-1$
				"org.xfce.Session.Manager");	//$NON-NLS-1$

		if (errorXCFE == null) {
			isGnome = false;
			return true;
		}

		System.err.format(
				"SWT SessionManagerDBus: Failed to connect to SessionManager (gnome: %s, xcfe: %s)%n",
				errorGnome,
				errorXCFE);

		return false;
	}

	/**
	 * Gets the value of 'DESKTOP_AUTOSTART_ID'.
	 *
	 * This environment variable is set by session manager if the
	 * application was auto started (because it is configured to run
	 * automatically for every session). The variable helps session
	 * manager to match autostart settings with actual applications.
	 *
	 * For applications that were not started automatically, the
	 * variable is expected to be absent.
	 *
	 * Once used, 'DESKTOP_AUTOSTART_ID' must not leak into child
	 * processes, or they will fail to 'RegisterClient'.
	 *
	 * NOTE: calling this function twice will give empty ID on
	 * second call. I think this is reasonable. If second object
	 * is created for whatever reason, it's OK to consider it to
	 * be a separate client.
	 */
	private String claimDesktopAutostartID() {
		byte[] DESKTOP_AUTOSTART_ID = Converter.javaStringToCString("DESKTOP_AUTOSTART_ID");	//$NON-NLS-1$

		// NOTE: the returned pointer is not valid after g_unsetenv()
		long valueC = OS.g_getenv(DESKTOP_AUTOSTART_ID);
		if (valueC == 0) return null;
		String result = Converter.cCharPtrToJavaString(valueC, false);

		// Unset value, so it doesn't leak into child processes
		OS.g_unsetenv(DESKTOP_AUTOSTART_ID);

		return result;
	}

	/**
	 * Issues 'RegisterClient' dbus request to register with session manager.
	 *
	 * Saves result to member variable when successful.
	 * @return Error string in case of error, null if successful.
	 */
	private String registerClient(String appID, String clientStartupID) {
		long args = OS.g_variant_new(
				Converter.javaStringToCString("(ss)"),				//$NON-NLS-1$
				Converter.javaStringToCString(appID),
				Converter.javaStringToCString(clientStartupID));

		long [] error = new long [1];
		long clientInfo = OS.g_dbus_proxy_call_sync(
				sessionManagerProxy,
				Converter.javaStringToCString("RegisterClient"),	//$NON-NLS-1$
				args,
				OS.G_DBUS_CALL_FLAGS_NONE,
				dbusTimeoutMsec,
				0,
				error);

		if (clientInfo == 0) return extractFreeGError(error[0]);

		// Success
		clientObjectPath = extractVariantTupleS(clientInfo);
		OS.g_variant_unref(clientInfo);
		return null;
	}

	private boolean registerClient() {
		// This ID doesn't matter much, at least according to what I know.
		// Still, I decided to make it customizable for those who love identity.
		String appID = System.getProperty("org.eclipse.swt.internal.SessionManagerDBus.appID");	//$NON-NLS-1$
		if (appID == null) appID = "org.eclipse.swt.Application";	//$NON-NLS-1$

		// Applications are expected to register using value of
		// 'DESKTOP_AUTOSTART_ID' environment if it's present.
		String desktopAutostartID = claimDesktopAutostartID();
		if (desktopAutostartID != null) {
			String errorText = registerClient(appID, desktopAutostartID);
			if (errorText == null) return true;

			// Bugged launchers use their 'DESKTOP_AUTOSTART_ID', but forget to unset it.
			// This leaks a value that can't be used.
			// The workaround is to retry with empty ID below.
			// This pretends that parent's bug is already fixed.
			boolean parentLeakedID = errorText.startsWith("GDBus.Error:org.gnome.SessionManager.AlreadyRegistered:");	//$NON-NLS-1$
			if (!parentLeakedID) return false;
		}

		// In absence of 'DESKTOP_AUTOSTART_ID' just use empty ID.
		String errorText = registerClient(appID, "");
		if (errorText == null) return true;

		// On XFCE 'RegisterClient' is only available since 4.13.0.
		// Don't print this error since it's expected.
		if (!isGnome && errorText.startsWith("GDBus.Error:org.freedesktop.DBus.Error.UnknownMethod: "))	//$NON-NLS-1$
			return false;

		System.err.format(
				"SWT SessionManagerDBus: Failed to RegisterClient: %s%n",
				errorText);

		return false;
	}

	private boolean connectClientSignal() {
		String dbusName;
		String interfaceName;
		if (isGnome) {
			dbusName      = "org.gnome.SessionManager";					//$NON-NLS-1$
			interfaceName = "org.gnome.SessionManager.ClientPrivate";	//$NON-NLS-1$
		} else {
			dbusName      = "org.xfce.SessionManager";					//$NON-NLS-1$
			interfaceName = "org.xfce.Session.Client";					//$NON-NLS-1$
		}

		long [] error = new long [1];
		clientProxy = OS.g_dbus_proxy_new_for_bus_sync(
				OS.G_BUS_TYPE_SESSION,
				0,
				0,
				Converter.javaStringToCString(dbusName),
				Converter.javaStringToCString(clientObjectPath),
				Converter.javaStringToCString(interfaceName),
				0,
				error);

		if (clientProxy == 0) {
			System.err.format(
					"SWT SessionManagerDBus: Failed to connect to Client: %s%n",
					extractFreeGError(error[0]));
			return false;
		}

		// The rest of the code makes this key call possible
		g_signal_callback = new Callback(this, "g_signal_handler", 5);	//$NON-NLS-1$
		OS.g_signal_connect(
				clientProxy,
				Converter.javaStringToCString("g-signal"),	//$NON-NLS-1$
				g_signal_callback.getAddress(),
				0);

		return true;
	}
}

Back to the top