Debian Codegraph @

tools/main.vala

raw
1 /* vim:set et sts=4 sw=4:
2 *
3 * ibus - The Input Bus
4 *
5 * Copyright(c) 2013 Peng Huang <[email protected]>
6 * Copyright(c) 2015-2025 Takao Fujiwara <[email protected]>
7 *
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
21 * USA
22 */
23
24 private const string IBUS_SCHEMAS_GENERAL = "org.freedesktop.ibus.general";
25 private const string IBUS_SCHEMAS_GENERAL_HOTKEY =
26 "org.freedesktop.ibus.general.hotkey";
27 private const string IBUS_SCHEMAS_PANEL = "org.freedesktop.ibus.panel";
28 private const string IBUS_SCHEMAS_PANEL_EMOJI =
29 "org.freedesktop.ibus.panel.emoji";
30 private const string SYSTEMD_SESSION_GNOME_FILE =
31 "org.freedesktop.IBus.session.GNOME.service";
32
33 #if IBUS_WAYLAND
34 bool is_wayland_session = false;
35 #endif
36 bool name_only = false;
37 /* system() exists as a public API. */
38 bool is_system = false;
39 string cache_file = null;
40 string engine_id = null;
41 bool verbose = false;
42 string daemon_type = null;
43 string systemd_service_file = null;
44 GLib.MainLoop loop = null;
45
46
47 class EngineList {
48 public IBus.EngineDesc[] data = {};
49 }
50
51
52 private bool is_kde(bool verbose) {
53 unowned string? desktop = Environment.get_variable("XDG_CURRENT_DESKTOP");
54 if (desktop == "KDE")
55 return true;
56 if (desktop == null || desktop == "(null)")
57 desktop = Environment.get_variable("XDG_SESSION_DESKTOP");
58 if (desktop == "plasma" || desktop == "KDE-wayland")
59 return true;
60 if (desktop == null) {
61 if (verbose) {
62 stderr.printf("XDG_CURRENT_DESKTOP is not exported in your " +
63 "desktop session.\n");
64 }
65 } else if (verbose) {
66 stderr.printf("Your desktop session \"%s\" is not KDE\n.", desktop);
67 }
68 return false;
69 }
70
71
72 IBus.Bus? get_bus() {
73 var bus = new IBus.Bus();
74 if (!bus.is_connected ())
75 return null;
76 return bus;
77 }
78
79
80 private void
81 name_appeared_handler(GLib.DBusConnection connection,
82 string name,
83 string name_owner) {
84 if (verbose)
85 stderr.printf("NameAquired %s:%s\n", name, name_owner);
86 loop.quit();
87 loop = null;
88 }
89
90
91 private void
92 kde_virtual_keyboard_avail_cb(GLib.DBusConnection connection,
93 string? sender_name,
94 string object_path,
95 string interface_name,
96 string signal_name,
97 GLib.Variant parameters)
98 {
99 if (verbose) {
100 stderr.printf("%s.%s %s returned.\n",
101 interface_name, signal_name, object_path);
102 }
103 loop.quit();
104 loop = null;
105 }
106
107
108 GLib.DBusConnection? get_session_bus(bool verbose) {
109 loop = new GLib.MainLoop();
110 assert(loop != null);
111 GLib.Bus.watch_name (GLib.BusType.SESSION,
112 DBus.SERVICE_DBUS,
113 GLib.BusNameWatcherFlags.NONE,
114 name_appeared_handler,
115 null);
116 GLib.DBusConnection? connection = null;
117 GLib.Bus.get.begin(GLib.BusType.SESSION, null,
118 (obj, res) => {
119 try {
120 connection = GLib.Bus.get.end(res);
121 if (verbose)
122 stderr.printf("The session bus is generated.\n");
123 } catch(GLib.IOError e) {
124 if (verbose)
125 stderr.printf("The session bus error: %s\n", e.message);
126 if (loop != null) {
127 loop.quit();
128 loop = null;
129 }
130 }
131 });
132 loop.run();
133 if (connection.is_closed()) {
134 if (verbose)
135 stderr.printf("The session bus is closed.\n");
136 return null;
137 }
138 return connection;
139 }
140
141
142 string?
143 get_ibus_systemd_object_path(GLib.DBusConnection connection,
144 bool verbose) {
145 string object_path = null;
146 assert(systemd_service_file != null);
147 try {
148 var variant = connection.call_sync (
149 "org.freedesktop.systemd1",
150 "/org/freedesktop/systemd1",
151 "org.freedesktop.systemd1.Manager",
152 "GetUnit",
153 new GLib.Variant("(s)", systemd_service_file),
154 new GLib.VariantType("(o)"),
155 GLib.DBusCallFlags.NONE,
156 -1,
157 null);
158 variant.get("(o)", ref object_path);
159 if (verbose) {
160 stderr.printf("Succeed to get an object path \"%s\" for IBus " +
161 "systemd service file \"%s\".\n",
162 object_path, systemd_service_file);
163 }
164 return object_path;
165 } catch (GLib.Error e) {
166 if (verbose) {
167 stderr.printf("IBus systemd service file \"%s\" is not installed " +
168 "in your system: %s\n",
169 systemd_service_file, e.message);
170 }
171 }
172 return null;
173 }
174
175
176 bool
177 is_running_daemon_via_systemd(GLib.DBusConnection connection,
178 string object_path,
179 bool verbose) {
180 string? state = null;
181 try {
182 while (true) {
183 var variant = connection.call_sync (
184 "org.freedesktop.systemd1",
185 object_path,
186 "org.freedesktop.DBus.Properties",
187 "Get",
188 new GLib.Variant("(ss)",
189 "org.freedesktop.systemd1.Unit",
190 "ActiveState"),
191 new GLib.VariantType("(v)"),
192 GLib.DBusCallFlags.NONE,
193 -1,
194 null);
195 GLib.Variant child = null;
196 variant.get("(v)", ref child);
197 state = child.dup_string();
198 if (verbose) {
199 stderr.printf("systemd state is \"%s\" for an object " +
200 "path \"%s\".\n", state, object_path);
201 }
202 if (state != "activating")
203 break;
204 Posix.sleep(1);
205 }
206 } catch (GLib.Error e) {
207 if (verbose)
208 stderr.printf("%s\n", e.message);
209 return false;
210 }
211 if (state == "active")
212 return true;
213 return false;
214 }
215
216
217 #if IBUS_WAYLAND
218 void registry_global_cb(void *data,
219 Wl.Registry wl_registry,
220 uint32 name,
221 string @interface,
222 uint32 version) {
223 if (verbose) {
224 stderr.printf("Wl.RegistryListenerGlobal name: %3u interface: %s " +
225 "version: %u.\n", name, interface, version);
226 }
227 if (interface == "zwp_input_method_manager_v2") {
228 is_wayland_session = true;
229 } else if (interface == "zwp_input_method_v1") {
230 stderr.printf("Wayland input-method protocol version 1 does not " +
231 "work with the forked application.\n");
232 is_wayland_session = true;
233 }
234 }
235
236
237 void registry_global_remove_cb(void *data,
238 Wl.Registry wl_registry,
239 uint32 name) {
240 }
241
242
243 bool check_wayland_protocols() {
244 var display = new Wl.Display.connect(null);
245 if (display == null)
246 return false;
247 var registry = display.get_registry();
248 var listener = Wl.RegistryListener() {
249 global = registry_global_cb,
250 global_remove = registry_global_remove_cb
251 };
252 registry.add_listener (listener, null);
253 display.roundtrip();
254 return true;
255 }
256
257
258 bool start_daemon_in_wayland(bool restart,
259 string[] _argv) {
260
261 check_wayland_protocols();
262 if (!is_wayland_session) {
263 if (verbose)
264 stderr.printf("Cannot find the Wayland input-method protocol.\n");
265 return false;
266 }
267
268 var bus = get_bus();
269 if (restart) {
270 if (bus == null) {
271 stderr.printf(_("Can't connect to IBus.\n"));
272 return false;
273 }
274 bus.exit(false);
275 if (verbose) {
276 stderr.printf("Succeed to exit ibus-daemon with an IBus API " +
277 "directly.\n");
278 }
279 bus = null;
280 Posix.sleep(3);
281 } else if (bus != null) {
282 stderr.printf("%s\n".printf(_("IBus is running.")));
283 Posix.exit(Posix.EXIT_FAILURE);
284 return true;
285 }
286
287 string cmd = Config.LIBEXECDIR + "/ibus-ui-gtk3";
288 var file = File.new_for_path(cmd);
289 if (!file.query_exists())
290 cmd = "../ui/gtk3/ibus-ui-gtk3";
291
292 string daemon_args = "--xim --panel disable";
293 if (_argv.length > 1)
294 daemon_args = string.joinv(" ", _argv[1:]);
295 string[] argv = { cmd };
296 argv += "--enable-wayland-im";
297 argv += "--exec-daemon";
298 argv += "--daemon-args";
299 argv += "%s".printf(daemon_args);
300 if (verbose)
301 argv += "--verbose";
302
303 string[] env = Environ.get();
304
305 try {
306 // Non-blocking
307 Process.spawn_async(null, argv, env,
308 SpawnFlags.SEARCH_PATH,
309 null, null);
310 } catch (SpawnError e) {
311 stderr.printf("%s\n", e.message);
312 Posix.exit(Posix.EXIT_FAILURE);
313 return true;
314 }
315 if (verbose) {
316 stderr.printf("Succeed to %s ibus-daemon with a Wayland " +
317 "input-method version 2.\n",
318 restart ? "restart" : "start");
319 }
320 return true;
321 }
322 #endif
323
324
325 bool
326 start_daemon_with_dbus_systemd(GLib.DBusConnection connection,
327 bool restart,
328 bool verbose) {
329 string object_path = null;
330 string method = "StartUnit";
331 assert(systemd_service_file != null);
332 if (restart)
333 method = "RestartUnit";
334 try {
335 var variant = connection.call_sync (
336 "org.freedesktop.systemd1",
337 "/org/freedesktop/systemd1",
338 "org.freedesktop.systemd1.Manager",
339 method,
340 new GLib.Variant("(ss)", systemd_service_file, "fail"),
341 new GLib.VariantType("(o)"),
342 GLib.DBusCallFlags.NONE,
343 -1,
344 null);
345 variant.get("(o)", ref object_path);
346 if (verbose) {
347 stderr.printf("Succeed to restart IBus daemon via IBus systemd " +
348 "service file \"%s\": \"%s\"\n",
349 systemd_service_file, object_path);
350 }
351 return true;
352 } catch (GLib.Error e) {
353 if (verbose) {
354 stderr.printf("Failed to %s IBus daemon via IBus systemd " +
355 "service file \"%s\": %s\n",
356 restart ? "restart" : "start",
357 systemd_service_file, e.message);
358 }
359 }
360 return false;
361 }
362
363
364 bool
365 operate_daemon_with_dbus_kde_real(GLib.DBusConnection connection,
366 bool verbose) {
367 loop = new GLib.MainLoop();
368 assert(loop != null);
369 uint subscripion_id = connection.signal_subscribe(
370 null,
371 "org.kde.kwin.VirtualKeyboard",
372 "availableChanged",
373 "/VirtualKeyboard",
374 null,
375 DBusSignalFlags.NONE,
376 kde_virtual_keyboard_avail_cb);
377
378 string wayland_values = "InputMethod";
379 var bytes = new GLib.VariantBuilder(new GLib.VariantType("ay"));
380 for (int i = 0; i < wayland_values.length; i++) {
381 bytes.add("y", wayland_values.get(i));
382 }
383 var bytes2 = new GLib.VariantBuilder(new GLib.VariantType("aay"));
384 bytes2.add("ay", bytes);
385 var array = new GLib.VariantBuilder(new GLib.VariantType("a{saay}"));
386 array.add("{saay}", "Wayland", bytes2);
387 try {
388 if (!connection.emit_signal(null,
389 "/kwinrc",
390 "org.kde.kconfig.notify",
391 "ConfigChanged",
392 new GLib.Variant("(a{saay})", array))) {
393 if (verbose)
394 stderr.printf("Failed to emit a KDE D-Bus signal.\n");
395 connection.signal_unsubscribe(subscripion_id);
396 if (loop != null) {
397 loop.quit();
398 loop = null;
399 }
400 return false;
401 }
402 } catch (GLib.Error e) {
403 stderr.printf("%s\n", e.message);
404 connection.signal_unsubscribe(subscripion_id);
405 if (loop != null) {
406 loop.quit();
407 loop = null;
408 }
409 return false;
410 }
411 // Wait for "/VirtualKeyboard" on "org.kde.kwin.VirtualKeyboard" signal
412 // so that "/kwinrc" on "org.kde.kconfig.notify" signal is reached to
413 // kwin.
414 loop.run();
415 connection.signal_unsubscribe(subscripion_id);
416 return true;
417 }
418
419
420 bool
421 operate_daemon_with_dbus_kde(GLib.DBusConnection connection,
422 bool start,
423 bool verbose) {
424 if (start) {
425 return operate_daemon_with_dbus_kde_real(connection, verbose);
426 }
427 // Wait for the KeyRelease of Return key.
428 var source = new GLib.TimeoutSource.seconds(1);
429 source.attach();
430 uint id = source.get_id();
431 bool retval = false;
432 source.set_callback(() => {
433 retval = operate_daemon_with_dbus_kde_real(connection, verbose);
434 id = 0;
435 return GLib.Source.REMOVE;
436 });
437 while (id > 0)
438 GLib.MainContext.default().iteration(true);
439 return retval;
440 }
441
442
443 int list_engine(string[] argv) {
444 const OptionEntry[] options = {
445 { "name-only", 0, 0, OptionArg.NONE, out name_only,
446 N_("List engine name only"), null },
447 { null }
448 };
449
450 var option = new OptionContext();
451 option.add_main_entries(options, Config.GETTEXT_PACKAGE);
452
453 try {
454 option.parse(ref argv);
455 } catch (OptionError e) {
456 stderr.printf("%s\n", e.message);
457 return Posix.EXIT_FAILURE;
458 }
459
460 var bus = get_bus();
461 if (bus == null) {
462 stderr.printf(_("Can't connect to IBus.\n"));
463 return Posix.EXIT_FAILURE;
464 }
465
466 var engines = bus.list_engines();
467
468 if (name_only) {
469 foreach (var engine in engines) {
470 print("%s\n", engine.get_name());
471 }
472 return Posix.EXIT_SUCCESS;
473 }
474
475 var map = new HashTable<string, EngineList>(GLib.str_hash, GLib.str_equal);
476
477 foreach (var engine in engines) {
478 var list = map.get(engine.get_language());
479 if (list == null) {
480 list = new EngineList();
481 map.insert(engine.get_language(), list);
482 }
483 list.data += engine;
484 }
485
486 foreach (var language in map.get_keys()) {
487 var list = map.get(language);
488 print(_("language: %s\n"), IBus.get_language_name(language));
489 foreach (var engine in list.data) {
490 print(" %s - %s\n", engine.get_name(), engine.get_longname());
491 }
492 }
493
494 return Posix.EXIT_SUCCESS;
495 }
496
497
498 private int exec_setxkbmap(IBus.EngineDesc engine) {
499 string layout = engine.get_layout();
500 string variant = engine.get_layout_variant();
501 string option = engine.get_layout_option();
502 string standard_error = null;
503 int exit_status = 0;
504 string[] args = { "setxkbmap" };
505
506 if (layout != null && layout != "" && layout != "default") {
507 args += "-layout";
508 args += layout;
509 }
510 if (variant != null && variant != "" && variant != "default") {
511 args += "-variant";
512 args += variant;
513 }
514 if (option != null && option != "" && option != "default") {
515 /*TODO: Need to get the session XKB options */
516 args += "-option";
517 args += "-option";
518 args += option;
519 }
520
521 if (args.length == 1) {
522 return Posix.EXIT_FAILURE;
523 }
524
525 try {
526 if (!GLib.Process.spawn_sync(null, args, null,
527 GLib.SpawnFlags.SEARCH_PATH,
528 null, null,
529 out standard_error,
530 out exit_status)) {
531 warning("Switch xkb layout to %s failed.",
532 engine.get_layout());
533 return Posix.EXIT_FAILURE;
534 }
535 } catch (GLib.SpawnError e) {
536 warning("Execute setxkbmap failed: %s", e.message);
537 return Posix.EXIT_FAILURE;
538 }
539
540 if (exit_status != 0) {
541 warning("Execute setxkbmap failed: %s", standard_error ?? "(null)");
542 return Posix.EXIT_FAILURE;
543 }
544
545 return Posix.EXIT_SUCCESS;
546 }
547
548
549 int get_set_engine(string[] argv) {
550 var bus = get_bus();
551 string engine = null;
552 if (argv.length > 1)
553 engine = argv[1];
554
555 if (engine == null) {
556 var desc = bus.get_global_engine();
557 if (desc == null) {
558 stderr.printf(_("No engine is set.\n"));
559 return Posix.EXIT_FAILURE;
560 }
561 print("%s\n", desc.get_name());
562 return Posix.EXIT_SUCCESS;
563 }
564
565 if(!bus.set_global_engine(engine)) {
566 stderr.printf(_("Set global engine failed.\n"));
567 return Posix.EXIT_FAILURE;
568 }
569 var desc = bus.get_global_engine();
570 if (desc == null) {
571 stderr.printf(_("Get global engine failed.\n"));
572 return Posix.EXIT_FAILURE;
573 }
574
575 var settings = new GLib.Settings(IBUS_SCHEMAS_GENERAL);
576 if (!settings.get_boolean("use-system-keyboard-layout"))
577 return exec_setxkbmap(desc);
578
579 return Posix.EXIT_SUCCESS;
580 }
581
582
583 int message_watch(string[] argv) {
584 return Posix.EXIT_SUCCESS;
585 }
586
587
588 bool operate_daemon_in_kde_wayland(GLib.DBusConnection connection,
589 bool start,
590 bool verbose) {
591 if (!is_kde(verbose))
592 return false;
593 if (Environment.get_variable("WAYLAND_DISPLAY") == null) {
594 if (verbose)
595 stderr.printf("Your KDE session is not Wayland\n.");
596 return false;
597 }
598 var kwinrc = GLib.Path.build_filename(
599 GLib.Environment.get_user_config_dir(), "kwinrc");
600 var key_file = new KRcFile();
601 try {
602 key_file.load_from_file(kwinrc, GLib.KeyFileFlags.KEEP_COMMENTS);
603 } catch (GLib.KeyFileError e) {
604 stderr.printf("Error in %s: %s\n", kwinrc, e.message);
605 return false;
606 } catch (GLib.FileError e) {
607 stderr.printf("Error in %s: %s\n", kwinrc, e.message);
608 return false;
609 }
610 try {
611 bool is_updated = false;
612 if (start) {
613 string ibus_value =
614 GLib.Path.build_filename(Config.DATADIR,
615 "applications",
616 Config.UI_WAYLAND_DESKTOP);
617 string? value = null;
618 if (key_file.has_group("Wayland") &&
619 key_file.has_key("Wayland", "InputMethod[$e]")) {
620 value = key_file.get_value("Wayland", "InputMethod[$e]");
621 }
622 if (value != ibus_value) {
623 key_file.set_value("Wayland", "InputMethod[$e]", ibus_value);
624 key_file.save_to_file(kwinrc);
625 is_updated = true;
626 }
627 } else {
628 if (key_file.has_group("Wayland")) {
629 var keys = key_file.get_keys("Wayland");
630 if (key_file.has_key("Wayland", "InputMethod[$e]")) {
631 if (keys.length == 1)
632 key_file.remove_group("Wayland");
633 else
634 key_file.remove_key("Wayland", "InputMethod[$e]");
635 key_file.save_to_file(kwinrc);
636 is_updated = true;
637 }
638 }
639 }
640 if (verbose) {
641 if (is_updated) {
642 stderr.printf("\"InputMethod\" was %s in kwinrc for %s.\n",
643 start ? "added" : "deleted",
644 start ? "start" : "exit");
645 } else {
646 if (start) {
647 stderr.printf(
648 "kwinrc is not updated for start. \"ibus exit\" " +
649 "command may be needed in case kwin_wayland " +
650 "restarted.\n");
651 } else {
652 stderr.printf("kwinrc is not updated for exit.\n");
653 return true;
654 }
655 }
656 }
657 } catch (GLib.KeyFileError e) {
658 stderr.printf("%s\n", e.message);
659 return false;
660 } catch (GLib.FileError e) {
661 stderr.printf("%s\n", e.message);
662 return false;
663 }
664 if (!operate_daemon_with_dbus_kde(connection, start, verbose))
665 return false;
666 if (verbose) {
667 stderr.printf("Succeed to %s ibus-daemon with a " +
668 "KDE Wayland method.\n", start ? "start" : "exit");
669 }
670 return true;
671 }
672
673 bool start_daemon_with_systemd(bool restart, bool verbose) {
674 GLib.DBusConnection? connection = get_session_bus(verbose);
675 if (connection == null)
676 return false;
677 string? object_path = null;
678 if (restart) {
679 object_path = get_ibus_systemd_object_path(connection, verbose);
680 if (object_path == null)
681 return false;
682 if (!is_running_daemon_via_systemd(connection,
683 object_path,
684 verbose)) {
685 return false;
686 }
687 }
688 if (!start_daemon_with_dbus_systemd(connection, restart, verbose))
689 return false;
690 // Do not check the systemd state in case of restart because
691 // the systemd file validation is already done and also stopping
692 // daemon and starting daemon take time and the state could be
693 // "inactive" with the time lag.
694 if (restart)
695 return true;
696 object_path = get_ibus_systemd_object_path(connection, verbose);
697 if (object_path == null)
698 return false;
699 if (!is_running_daemon_via_systemd(connection, object_path, verbose))
700 return false;
701 return true;
702 }
703
704
705 int start_daemon_real(string[] argv,
706 bool restart) {
707 const OptionEntry[] options = {
708 { "type", 0, 0, OptionArg.STRING, out daemon_type,
709 N_("Start or restart daemon with \"direct\", \"systemd\", " +
710 "\"kde-wayland\" or \"wayland\" TYPE."),
711 "TYPE" },
712 { "service-file", 0, 0, OptionArg.STRING, out systemd_service_file,
713 N_("Start or restart daemon with SYSTEMD_SERVICE file."),
714 "SYSTEMD_SERVICE" },
715 { "verbose", 0, 0, OptionArg.NONE, out verbose,
716 N_("Show debug messages."), null },
717 { null }
718 };
719
720 var option = new OptionContext();
721 option.add_main_entries(options, Config.GETTEXT_PACKAGE);
722 option.set_ignore_unknown_options(true);
723
724 try {
725 option.parse(ref argv);
726 } catch (OptionError e) {
727 stderr.printf("%s\n", e.message);
728 return Posix.EXIT_FAILURE;
729 }
730 if (daemon_type != null && daemon_type != "direct" &&
731 daemon_type != "systemd" && daemon_type != "kde-wayland" &&
732 daemon_type != "wayland") {
733 stderr.printf("type argument must be \"direct\" or \"systemd\" " +
734 "or \"kde-wayland\" or \"wayland\"\n");
735 return Posix.EXIT_FAILURE;
736 }
737 if (systemd_service_file == null)
738 systemd_service_file = SYSTEMD_SESSION_GNOME_FILE;
739
740 if (daemon_type == null || daemon_type == "wayland") {
741 #if IBUS_WAYLAND
742 if (start_daemon_in_wayland(restart, argv))
743 return Posix.EXIT_SUCCESS;
744 #else
745 if (daemon_type == "wayland") {
746 stderr.printf("Please build IBus with Wayland.\n");
747 return Posix.EXIT_FAILURE;
748 }
749 #endif
750 }
751
752 if (daemon_type == null || daemon_type == "kde-wayland") {
753 do {
754 GLib.DBusConnection? connection = get_session_bus(verbose);
755 if (connection == null)
756 break;
757 if (restart) {
758 if (operate_daemon_in_kde_wayland(connection, false, verbose))
759 Posix.sleep(3);
760 else
761 break;
762 }
763 if (operate_daemon_in_kde_wayland(connection, true, verbose))
764 return Posix.EXIT_SUCCESS;
765 } while (false);
766 }
767
768 if (daemon_type == null || daemon_type == "systemd") {
769 if (start_daemon_with_systemd(restart, verbose))
770 return Posix.EXIT_SUCCESS;
771 }
772
773 if (daemon_type == "systemd" || daemon_type == "kde-wayland")
774 return Posix.EXIT_FAILURE;
775 var bus = get_bus();
776 if (restart) {
777 if (bus == null) {
778 stderr.printf(_("Can't connect to IBus.\n"));
779 return Posix.EXIT_FAILURE;
780 }
781 bus.exit(true);
782 if (verbose) {
783 stderr.printf("Succeed to restart ibus-daemon with an IBus API " +
784 "directly.\n");
785 }
786 } else if (bus != null) {
787 stderr.printf("%s\n".printf(_("IBus is running.")));
788 return Posix.EXIT_FAILURE;
789 } else {
790 string startarg = "ibus-daemon";
791 argv[0] = startarg;
792 var paths = GLib.Environment.get_variable("PATH").split(":");
793 foreach (unowned string path in paths) {
794 var full_path = "%s/%s".printf(path, startarg);
795 if (GLib.FileUtils.test(full_path, GLib.FileTest.IS_EXECUTABLE)) {
796 startarg = full_path;
797 break;
798 }
799 }
800 // When ibus-daemon is launched by GLib.Process.spawn_async(),
801 // the parent process will be systemd
802 if (verbose) {
803 stderr.printf("Running \"%s\" directly as a foreground " +
804 "process.\n", startarg);
805 }
806 Posix.execv(startarg, argv);
807 }
808 return Posix.EXIT_SUCCESS;
809 }
810
811
812 int restart_daemon(string[] argv) {
813 return start_daemon_real(argv, true);
814 }
815
816 int start_daemon(string[] argv) {
817 return start_daemon_real(argv, false);
818 }
819
820 bool exit_daemon_with_systemd(IBus.Bus bus, bool verbose) {
821 if (systemd_service_file == null)
822 systemd_service_file = SYSTEMD_SESSION_GNOME_FILE;
823 GLib.DBusConnection? connection = get_session_bus(verbose);
824 if (connection == null)
825 return false;
826 string? object_path = get_ibus_systemd_object_path(connection, verbose);
827 if (object_path == null)
828 return false;
829 if (!is_running_daemon_via_systemd(connection,
830 object_path,
831 verbose)) {
832 return false;
833 }
834
835 // Wait for the KeyRelease of Return key.
836 var source = new GLib.TimeoutSource.seconds(1);
837 source.attach();
838 uint id = source.get_id();
839 source.set_callback(() => {
840 bus.exit(false);
841 id = 0;
842 return GLib.Source.REMOVE;
843 });
844 while (id > 0)
845 GLib.MainContext.default().iteration(true);
846 return true;
847 }
848
849 int exit_daemon(string[] argv) {
850 const OptionEntry[] options = {
851 { "type", 0, 0, OptionArg.STRING, out daemon_type,
852 N_("Exit daemon with \"direct\" or \"kde-wayland\" " +
853 "TYPE."),
854 "TYPE" },
855 { "verbose", 0, 0, OptionArg.NONE, out verbose,
856 N_("Show debug messages."), null },
857 { null }
858 };
859
860 var option = new OptionContext();
861 option.add_main_entries(options, Config.GETTEXT_PACKAGE);
862 option.set_ignore_unknown_options(true);
863
864 try {
865 option.parse(ref argv);
866 } catch (OptionError e) {
867 stderr.printf("%s\n", e.message);
868 return Posix.EXIT_FAILURE;
869 }
870 if (daemon_type != null && daemon_type != "direct" &&
871 daemon_type != "kde-wayland") {
872 stderr.printf("type argument must be \"direct\" or \"kde-wayland\"\n");
873 return Posix.EXIT_FAILURE;
874 }
875 if (daemon_type == null || daemon_type == "kde-wayland") {
876 GLib.DBusConnection? connection = get_session_bus(verbose);
877 if (connection != null &&
878 operate_daemon_in_kde_wayland(connection, false, verbose)) {
879 return Posix.EXIT_SUCCESS;
880 }
881 }
882
883 if (daemon_type == "kde-wayland")
884 return Posix.EXIT_FAILURE;
885 var bus = get_bus();
886 if (bus == null) {
887 stderr.printf(_("Can't connect to IBus.\n"));
888 return Posix.EXIT_FAILURE;
889 }
890 if (exit_daemon_with_systemd(bus, verbose))
891 return Posix.EXIT_SUCCESS;
892 if (daemon_type == "systemd")
893 return Posix.EXIT_FAILURE;
894 bus.exit(false);
895 return Posix.EXIT_SUCCESS;
896 }
897
898
899 int print_version(string[] argv) {
900 print("IBus %s\n", Config.PACKAGE_VERSION);
901 return Posix.EXIT_SUCCESS;
902 }
903
904
905 int read_cache (string[] argv) {
906 const OptionEntry[] options = {
907 { "system", 0, 0, OptionArg.NONE, out is_system,
908 N_("Read the system registry cache."), null },
909 { "file", 0, 0, OptionArg.STRING, out cache_file,
910 N_("Read the registry cache FILE."), "FILE" },
911 { null }
912 };
913
914 var option = new OptionContext();
915 option.add_main_entries(options, Config.GETTEXT_PACKAGE);
916
917 try {
918 option.parse(ref argv);
919 } catch (OptionError e) {
920 stderr.printf("%s\n", e.message);
921 return Posix.EXIT_FAILURE;
922 }
923
924 var registry = new IBus.Registry();
925
926 if (cache_file != null) {
927 if (!registry.load_cache_file(cache_file)) {
928 stderr.printf(_("The registry cache is invalid.\n"));
929 return Posix.EXIT_FAILURE;
930 }
931 } else {
932 if (!registry.load_cache(!is_system)) {
933 stderr.printf(_("The registry cache is invalid.\n"));
934 return Posix.EXIT_FAILURE;
935 }
936 }
937
938 var output = new GLib.StringBuilder();
939 registry.output(output, 1);
940
941 print ("%s\n", output.str);
942 return Posix.EXIT_SUCCESS;
943 }
944
945
946 int write_cache (string[] argv) {
947 const OptionEntry[] options = {
948 { "system", 0, 0, OptionArg.NONE, out is_system,
949 N_("Write the system registry cache."), null },
950 { "file", 0, 0, OptionArg.STRING, out cache_file,
951 N_("Write the registry cache FILE."),
952 "FILE" },
953 { null }
954 };
955
956 var option = new OptionContext();
957 option.add_main_entries(options, Config.GETTEXT_PACKAGE);
958
959 try {
960 option.parse(ref argv);
961 } catch (OptionError e) {
962 stderr.printf("%s\n", e.message);
963 return Posix.EXIT_FAILURE;
964 }
965
966 var registry = new IBus.Registry();
967 registry.load();
968
969 if (cache_file != null) {
970 return registry.save_cache_file(cache_file) ?
971 Posix.EXIT_SUCCESS : Posix.EXIT_FAILURE;
972 }
973
974 return registry.save_cache(!is_system) ?
975 Posix.EXIT_SUCCESS : Posix.EXIT_FAILURE;
976 }
977
978
979 int print_address(string[] argv) {
980 string address = IBus.get_address();
981 print("%s\n", address != null ? address : "(null)");
982 return Posix.EXIT_SUCCESS;
983 }
984
985
986 private int read_config_options(string[] argv) {
987 const OptionEntry[] options = {
988 { "engine-id", 0, 0, OptionArg.STRING, out engine_id,
989 N_("Use engine schema paths instead of ibus core, " +
990 "which can be comma-separated values."), "ENGINE_ID" },
991 { null }
992 };
993
994 var option = new OptionContext();
995 option.add_main_entries(options, Config.GETTEXT_PACKAGE);
996
997 try {
998 option.parse(ref argv);
999 } catch (OptionError e) {
1000 stderr.printf("%s\n", e.message);
1001 return Posix.EXIT_FAILURE;
1002 }
1003 return Posix.EXIT_SUCCESS;
1004 }
1005
1006
1007 private GLib.SList<string> get_ibus_schemas() {
1008 string[] ids = {};
1009 if (engine_id != null) {
1010 ids = engine_id.split(",");
1011 }
1012 GLib.SList<string> ibus_schemas = new GLib.SList<string>();
1013 GLib.SettingsSchemaSource schema_source =
1014 GLib.SettingsSchemaSource.get_default();
1015 string[] list_schemas = {};
1016 schema_source.list_schemas(true, out list_schemas, null);
1017 foreach (string schema in list_schemas) {
1018 if (ids.length != 0) {
1019 foreach (unowned string id in ids) {
1020 if (id == schema ||
1021 schema.has_prefix("org.freedesktop.ibus.engine." + id)) {
1022 ibus_schemas.prepend(schema);
1023 break;
1024 }
1025 }
1026 } else if (schema.has_prefix("org.freedesktop.ibus") &&
1027 !schema.has_prefix("org.freedesktop.ibus.engine")) {
1028 ibus_schemas.prepend(schema);
1029 }
1030 }
1031 if (ibus_schemas.length() == 0) {
1032 printerr("Not found schemas of \"org.freedesktop.ibus\"\n");
1033 return ibus_schemas;
1034 }
1035 ibus_schemas.sort(GLib.strcmp);
1036
1037 return ibus_schemas;
1038 }
1039
1040
1041 int read_config(string[] argv) {
1042 if (read_config_options(argv) == Posix.EXIT_FAILURE)
1043 return Posix.EXIT_FAILURE;
1044
1045 GLib.SList<string> ibus_schemas = get_ibus_schemas();
1046 if (ibus_schemas.length() == 0)
1047 return Posix.EXIT_FAILURE;
1048
1049 GLib.SettingsSchemaSource schema_source =
1050 GLib.SettingsSchemaSource.get_default();
1051 var output = new GLib.StringBuilder();
1052 foreach (string schema in ibus_schemas) {
1053 GLib.SettingsSchema settings_schema = schema_source.lookup(schema,
1054 false);
1055 GLib.Settings settings = new GLib.Settings(schema);
1056
1057 output.append_printf("SCHEMA: %s\n", schema);
1058
1059 foreach (string key in settings_schema.list_keys()) {
1060 GLib.Variant variant = settings.get_value(key);
1061 output.append_printf(" %s: %s\n", key, variant.print(true));
1062 }
1063 }
1064 print("%s", output.str);
1065
1066 return Posix.EXIT_SUCCESS;
1067 }
1068
1069
1070 int reset_config(string[] argv) {
1071 if (read_config_options(argv) == Posix.EXIT_FAILURE)
1072 return Posix.EXIT_FAILURE;
1073
1074 GLib.SList<string> ibus_schemas = get_ibus_schemas();
1075 if (ibus_schemas.length() == 0)
1076 return Posix.EXIT_FAILURE;
1077
1078 print("%s\n", _("Resetting…"));
1079
1080 GLib.SettingsSchemaSource schema_source =
1081 GLib.SettingsSchemaSource.get_default();
1082 foreach (string schema in ibus_schemas) {
1083 GLib.SettingsSchema settings_schema = schema_source.lookup(schema,
1084 false);
1085 GLib.Settings settings = new GLib.Settings(schema);
1086
1087 print("SCHEMA: %s\n", schema);
1088
1089 foreach (string key in settings_schema.list_keys()) {
1090 print(" %s\n", key);
1091 settings.reset(key);
1092 }
1093 }
1094
1095 GLib.Settings.sync();
1096 print("%s\n", _("Done"));
1097
1098 return Posix.EXIT_SUCCESS;
1099 }
1100
1101
1102 #if EMOJI_DICT
1103 int emoji_dialog(string[] argv) {
1104 string cmd = Config.LIBEXECDIR + "/ibus-ui-emojier";
1105
1106 var file = File.new_for_path(cmd);
1107 if (!file.query_exists())
1108 cmd = "../ui/gtk3/ibus-ui-emojier";
1109
1110 argv[0] = cmd;
1111
1112 string[] env = Environ.get();
1113
1114 try {
1115 // Non-blocking
1116 Process.spawn_async(null, argv, env,
1117 SpawnFlags.SEARCH_PATH,
1118 null, null);
1119 } catch (SpawnError e) {
1120 stderr.printf("%s\n", e.message);
1121 return Posix.EXIT_FAILURE;
1122 }
1123
1124 return Posix.EXIT_SUCCESS;
1125 }
1126 #endif
1127
1128
1129 int read_im_module(string[] argv) {
1130 string? im_module = IBusIMModule.im_module_get_id(argv);
1131 if (im_module == null)
1132 return Posix.EXIT_FAILURE;
1133 print("%s\n".printf(im_module));
1134 return Posix.EXIT_SUCCESS;
1135 }
1136
1137
1138 int print_help(string[] argv) {
1139 print_usage(stdout);
1140 return Posix.EXIT_SUCCESS;
1141 }
1142
1143
1144 delegate int EntryFunc(string[] argv);
1145
1146 struct CommandEntry {
1147 unowned string name;
1148 unowned string description;
1149 unowned EntryFunc entry;
1150 }
1151
1152
1153 const CommandEntry commands[] = {
1154 { "engine", N_("Set or get engine"), get_set_engine },
1155 { "exit", N_("Exit ibus-daemon"), exit_daemon },
1156 { "list-engine", N_("Show available engines"), list_engine },
1157 { "watch", N_("(Not implemented)"), message_watch },
1158 { "restart", N_("Restart ibus-daemon"), restart_daemon },
1159 { "start", N_("Start ibus-daemon"), start_daemon },
1160 { "version", N_("Show version"), print_version },
1161 { "read-cache", N_("Show the content of registry cache"), read_cache },
1162 { "write-cache", N_("Create registry cache"), write_cache },
1163 { "address", N_("Print the D-Bus address of ibus-daemon"), print_address },
1164 { "read-config", N_("Show the configuration values"), read_config },
1165 { "reset-config", N_("Reset the configuration values"), reset_config },
1166 #if EMOJI_DICT
1167 { "emoji", N_("Save emoji on dialog to clipboard"), emoji_dialog },
1168 #endif
1169 { "im-module", N_("Retrieve im-module value from GTK instance"),
1170 read_im_module },
1171 { "help", N_("Show this information"), print_help }
1172 };
1173
1174 static string program_name;
1175
1176
1177 void print_usage(FileStream stream) {
1178 stream.printf(_("Usage: %s COMMAND [OPTION...]\n\n"), program_name);
1179 stream.printf(_("Commands:\n"));
1180 for (int i = 0; i < commands.length; i++) {
1181 stream.printf(" %-12s %s\n",
1182 commands[i].name,
1183 GLib.dgettext(null, commands[i].description));
1184 }
1185 }
1186
1187
1188 public int main(string[] argv) {
1189 GLib.Intl.setlocale(GLib.LocaleCategory.ALL, "");
1190 GLib.Intl.bindtextdomain(Config.GETTEXT_PACKAGE, Config.LOCALEDIR);
1191 GLib.Intl.bind_textdomain_codeset(Config.GETTEXT_PACKAGE, "UTF-8");
1192 GLib.Intl.textdomain(Config.GETTEXT_PACKAGE);
1193
1194 IBus.init();
1195
1196 program_name = Path.get_basename(argv[0]);
1197 if (argv.length < 2) {
1198 print_usage(stderr);
1199 return Posix.EXIT_FAILURE;
1200 }
1201
1202 string[] new_argv = argv[1:argv.length];
1203 new_argv[0] = "%s %s".printf(program_name, new_argv[0]);
1204 for (int i = 0; i < commands.length; i++) {
1205 if (commands[i].name == argv[1])
1206 return commands[i].entry(new_argv);
1207 }
1208
1209 stderr.printf(_("%s is unknown command!\n"), argv[1]);
1210 print_usage(stderr);
1211 return Posix.EXIT_FAILURE;
1212 }