Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(318)

Side by Side Diff: chrome/browser/chromeos/input_method/ibus_controller_impl.cc

Issue 9999018: chrome/browser/chromeos/input_method/ refactoring [part 6 of 6] (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: review fix Created 8 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "chrome/browser/chromeos/input_method/ibus_controller_impl.h"
6
7 #include <algorithm> // for std::reverse.
8 #include <cstdio>
9 #include <cstring> // for std::strcmp.
10 #include <set>
11 #include <sstream>
12 #include <stack>
13 #include <utility>
14
15 #include "base/memory/scoped_ptr.h"
16 #include "base/stringprintf.h"
17 #include "base/string_split.h"
18 #include "chrome/browser/chromeos/input_method/input_method_config.h"
19 #include "chrome/browser/chromeos/input_method/input_method_property.h"
20 #include "chrome/browser/chromeos/input_method/input_method_util.h"
21
22 // TODO(nona): Remove libibus dependency from this file. Then, write unit tests
23 // for all functions in this file. crbug.com/26334
24 #if defined(HAVE_IBUS)
25 #include <ibus.h>
26 #endif
27
28 namespace {
29
30 // Finds a property which has |new_prop.key| from |prop_list|, and replaces the
31 // property with |new_prop|. Returns true if such a property is found.
32 bool FindAndUpdateProperty(
33 const chromeos::input_method::InputMethodProperty& new_prop,
34 chromeos::input_method::InputMethodPropertyList* prop_list) {
35 for (size_t i = 0; i < prop_list->size(); ++i) {
36 chromeos::input_method::InputMethodProperty& prop = prop_list->at(i);
37 if (prop.key == new_prop.key) {
38 const int saved_id = prop.selection_item_id;
39 // Update the list except the radio id. As written in
40 // chromeos_input_method.h, |prop.selection_item_id| is dummy.
41 prop = new_prop;
42 prop.selection_item_id = saved_id;
43 return true;
44 }
45 }
46 return false;
47 }
48
49 } // namespace
50
51 namespace chromeos {
52 namespace input_method {
53
54 #if defined(HAVE_IBUS)
55 const char kPanelObjectKey[] = "panel-object";
56
57 namespace {
58
59 const char* Or(const char* str1, const char* str2) {
60 return str1 ? str1 : str2;
61 }
62
63 // Returns true if |key| is blacklisted.
64 bool PropertyKeyIsBlacklisted(const char* key) {
65 // The list of input method property keys that we don't handle.
66 static const char* kInputMethodPropertyKeysBlacklist[] = {
67 "status", // used in ibus-m17n.
68 };
69 for (size_t i = 0; i < arraysize(kInputMethodPropertyKeysBlacklist); ++i) {
70 if (!std::strcmp(key, kInputMethodPropertyKeysBlacklist[i]))
71 return true;
72 }
73 return false;
74 }
75
76 // Returns IBusInputContext for |input_context_path|. NULL on errors.
77 IBusInputContext* GetInputContext(const std::string& input_context_path,
78 IBusBus* ibus) {
79 GDBusConnection* connection = ibus_bus_get_connection(ibus);
80 if (!connection) {
81 LOG(ERROR) << "IBusConnection is null";
82 return NULL;
83 }
84 // This function does not issue an IBus IPC.
85 IBusInputContext* context = ibus_input_context_get_input_context(
86 input_context_path.c_str(), connection);
87 if (!context)
88 LOG(ERROR) << "IBusInputContext is null: " << input_context_path;
89 return context;
90 }
91
92 // Returns true if |prop| has children.
93 bool PropertyHasChildren(IBusProperty* prop) {
94 return prop && ibus_property_get_sub_props(prop) &&
95 ibus_prop_list_get(ibus_property_get_sub_props(prop), 0);
96 }
97
98 // This function is called by and FlattenProperty() and converts IBus
99 // representation of a property, |ibus_prop|, to our own and push_back the
100 // result to |out_prop_list|. This function returns true on success, and
101 // returns false if sanity checks for |ibus_prop| fail.
102 bool ConvertProperty(IBusProperty* ibus_prop,
103 int selection_item_id,
104 InputMethodPropertyList* out_prop_list) {
105 DCHECK(ibus_prop);
106 DCHECK(out_prop_list);
107
108 const IBusPropType type = ibus_property_get_prop_type(ibus_prop);
109 const IBusPropState state = ibus_property_get_state(ibus_prop);
110 const IBusText* tooltip = ibus_property_get_tooltip(ibus_prop);
111 const IBusText* label = ibus_property_get_label(ibus_prop);
112 const gchar* key = ibus_property_get_key(ibus_prop);
113 DCHECK(key);
114
115 // Sanity checks.
116 const bool has_sub_props = PropertyHasChildren(ibus_prop);
117 if (has_sub_props && (type != PROP_TYPE_MENU)) {
118 LOG(ERROR) << "The property has sub properties, "
119 << "but the type of the property is not PROP_TYPE_MENU";
120 return false;
121 }
122 if ((!has_sub_props) && (type == PROP_TYPE_MENU)) {
123 // This is usually not an error. ibus-daemon sometimes sends empty props.
124 VLOG(1) << "Property list is empty";
125 return false;
126 }
127 if (type == PROP_TYPE_SEPARATOR || type == PROP_TYPE_MENU) {
128 // This is not an error, but we don't push an item for these types.
129 return true;
130 }
131
132 const bool is_selection_item = (type == PROP_TYPE_RADIO);
133 selection_item_id = is_selection_item ?
134 selection_item_id : InputMethodProperty::kInvalidSelectionItemId;
135
136 bool is_selection_item_checked = false;
137 if (state == PROP_STATE_INCONSISTENT) {
138 LOG(WARNING) << "The property is in PROP_STATE_INCONSISTENT, "
139 << "which is not supported.";
140 } else if ((!is_selection_item) && (state == PROP_STATE_CHECKED)) {
141 LOG(WARNING) << "PROP_STATE_CHECKED is meaningful only if the type is "
142 << "PROP_TYPE_RADIO.";
143 } else {
144 is_selection_item_checked = (state == PROP_STATE_CHECKED);
145 }
146
147 if (!key)
148 LOG(ERROR) << "key is NULL";
149 if (tooltip && !tooltip->text) {
150 LOG(ERROR) << "tooltip is NOT NULL, but tooltip->text IS NULL: key="
151 << Or(key, "");
152 }
153 if (label && !label->text) {
154 LOG(ERROR) << "label is NOT NULL, but label->text IS NULL: key="
155 << Or(key, "");
156 }
157
158 // This label will be localized later.
159 // See chrome/browser/chromeos/input_method/input_method_util.cc.
160 std::string label_to_use = (tooltip && tooltip->text) ? tooltip->text : "";
161 if (label_to_use.empty()) {
162 // Usually tooltips are more descriptive than labels.
163 label_to_use = (label && label->text) ? label->text : "";
164 }
165 if (label_to_use.empty()) {
166 LOG(ERROR) << "The tooltip and label are both empty. Use " << key;
167 label_to_use = Or(key, "");
168 }
169
170 out_prop_list->push_back(InputMethodProperty(key,
171 label_to_use,
172 is_selection_item,
173 is_selection_item_checked,
174 selection_item_id));
175 return true;
176 }
177
178 // Converts |ibus_prop| to |out_prop_list|. Please note that |ibus_prop|
179 // may or may not have children. See the comment for FlattenPropertyList
180 // for details. Returns true if no error is found.
181 bool FlattenProperty(IBusProperty* ibus_prop,
182 InputMethodPropertyList* out_prop_list) {
183 DCHECK(ibus_prop);
184 DCHECK(out_prop_list);
185
186 int selection_item_id = -1;
187 std::stack<std::pair<IBusProperty*, int> > prop_stack;
188 prop_stack.push(std::make_pair(ibus_prop, selection_item_id));
189
190 while (!prop_stack.empty()) {
191 IBusProperty* prop = prop_stack.top().first;
192 const gchar* key = ibus_property_get_key(prop);
193 const int current_selection_item_id = prop_stack.top().second;
194 prop_stack.pop();
195
196 // Filter out unnecessary properties.
197 if (PropertyKeyIsBlacklisted(key))
198 continue;
199
200 // Convert |prop| to InputMethodProperty and push it to |out_prop_list|.
201 if (!ConvertProperty(prop, current_selection_item_id, out_prop_list))
202 return false;
203
204 // Process childrens iteratively (if any). Push all sub properties to the
205 // stack.
206 if (PropertyHasChildren(prop)) {
207 ++selection_item_id;
208 for (int i = 0;; ++i) {
209 IBusProperty* sub_prop =
210 ibus_prop_list_get(ibus_property_get_sub_props(prop), i);
211 if (!sub_prop)
212 break;
213 prop_stack.push(std::make_pair(sub_prop, selection_item_id));
214 }
215 ++selection_item_id;
216 }
217 }
218 std::reverse(out_prop_list->begin(), out_prop_list->end());
219
220 return true;
221 }
222
223 // Converts IBus representation of a property list, |ibus_prop_list| to our
224 // own. This function also flatten the original list (actually it's a tree).
225 // Returns true if no error is found. The conversion to our own type is
226 // necessary since our language switcher in Chrome tree don't (or can't) know
227 // IBus types. Here is an example:
228 //
229 // ======================================================================
230 // Input:
231 //
232 // --- Item-1
233 // |- Item-2
234 // |- SubMenuRoot --- Item-3-1
235 // | |- Item-3-2
236 // | |- Item-3-3
237 // |- Item-4
238 //
239 // (Note: Item-3-X is a selection item since they're on a sub menu.)
240 //
241 // Output:
242 //
243 // Item-1, Item-2, Item-3-1, Item-3-2, Item-3-3, Item-4
244 // (Note: SubMenuRoot does not appear in the output.)
245 // ======================================================================
246 bool FlattenPropertyList(IBusPropList* ibus_prop_list,
247 InputMethodPropertyList* out_prop_list) {
248 DCHECK(ibus_prop_list);
249 DCHECK(out_prop_list);
250
251 IBusProperty* fake_root_prop = ibus_property_new("Dummy.Key",
252 PROP_TYPE_MENU,
253 NULL, /* label */
254 "", /* icon */
255 NULL, /* tooltip */
256 FALSE, /* sensitive */
257 FALSE, /* visible */
258 PROP_STATE_UNCHECKED,
259 ibus_prop_list);
260 g_return_val_if_fail(fake_root_prop, false);
261 // Increase the ref count so it won't get deleted when |fake_root_prop|
262 // is deleted.
263 g_object_ref(ibus_prop_list);
264 const bool result = FlattenProperty(fake_root_prop, out_prop_list);
265 g_object_unref(fake_root_prop);
266
267 return result;
268 }
269
270 // Debug print function.
271 const char* PropTypeToString(int prop_type) {
272 switch (static_cast<IBusPropType>(prop_type)) {
273 case PROP_TYPE_NORMAL:
274 return "NORMAL";
275 case PROP_TYPE_TOGGLE:
276 return "TOGGLE";
277 case PROP_TYPE_RADIO:
278 return "RADIO";
279 case PROP_TYPE_MENU:
280 return "MENU";
281 case PROP_TYPE_SEPARATOR:
282 return "SEPARATOR";
283 }
284 return "UNKNOWN";
285 }
286
287 // Debug print function.
288 const char* PropStateToString(int prop_state) {
289 switch (static_cast<IBusPropState>(prop_state)) {
290 case PROP_STATE_UNCHECKED:
291 return "UNCHECKED";
292 case PROP_STATE_CHECKED:
293 return "CHECKED";
294 case PROP_STATE_INCONSISTENT:
295 return "INCONSISTENT";
296 }
297 return "UNKNOWN";
298 }
299
300 // Debug print function.
301 std::string Spacer(int n) {
302 return std::string(n, ' ');
303 }
304
305 // Debug print function.
306 std::string PrintProp(IBusProperty *prop, int tree_level) {
307 std::string PrintPropList(IBusPropList *prop_list, int tree_level);
308
309 if (!prop)
310 return "";
311
312 const IBusPropType type = ibus_property_get_prop_type(prop);
313 const IBusPropState state = ibus_property_get_state(prop);
314 const IBusText* tooltip = ibus_property_get_tooltip(prop);
315 const IBusText* label = ibus_property_get_label(prop);
316 const gchar* key = ibus_property_get_key(prop);
317
318 std::stringstream stream;
319 stream << Spacer(tree_level) << "=========================" << std::endl;
320 stream << Spacer(tree_level) << "key: " << Or(key, "<none>")
321 << std::endl;
322 stream << Spacer(tree_level) << "label: "
323 << ((label && label->text) ? label->text : "<none>")
324 << std::endl;
325 stream << Spacer(tree_level) << "tooptip: "
326 << ((tooltip && tooltip->text)
327 ? tooltip->text : "<none>") << std::endl;
328 stream << Spacer(tree_level) << "sensitive: "
329 << (ibus_property_get_sensitive(prop) ? "YES" : "NO") << std::endl;
330 stream << Spacer(tree_level) << "visible: "
331 << (ibus_property_get_visible(prop) ? "YES" : "NO") << std::endl;
332 stream << Spacer(tree_level) << "type: " << PropTypeToString(type)
333 << std::endl;
334 stream << Spacer(tree_level) << "state: " << PropStateToString(state)
335 << std::endl;
336 stream << Spacer(tree_level) << "sub_props: "
337 << (PropertyHasChildren(prop) ? "" : "<none>") << std::endl;
338 stream << PrintPropList(ibus_property_get_sub_props(prop), tree_level + 1);
339 stream << Spacer(tree_level) << "=========================" << std::endl;
340
341 return stream.str();
342 }
343
344 // Debug print function.
345 std::string PrintPropList(IBusPropList *prop_list, int tree_level) {
346 if (!prop_list)
347 return "";
348
349 std::stringstream stream;
350 for (int i = 0;; ++i) {
351 IBusProperty* prop = ibus_prop_list_get(prop_list, i);
352 if (!prop)
353 break;
354 stream << PrintProp(prop, tree_level);
355 }
356 return stream.str();
357 }
358
359 } // namespace
360
361 IBusControllerImpl::IBusControllerImpl()
362 : ibus_(NULL),
363 ibus_config_(NULL),
364 should_launch_daemon_(false),
365 process_handle_(base::kNullProcessHandle) {
366 }
367
368 IBusControllerImpl::~IBusControllerImpl() {
369 // Disconnect signals so the handler functions will not be called with
370 // |this| which is already freed.
371 if (ibus_) {
372 g_signal_handlers_disconnect_by_func(
373 ibus_,
374 reinterpret_cast<gpointer>(G_CALLBACK(BusConnectedThunk)),
375 this);
376 g_signal_handlers_disconnect_by_func(
377 ibus_,
378 reinterpret_cast<gpointer>(G_CALLBACK(BusDisconnectedThunk)),
379 this);
380 g_signal_handlers_disconnect_by_func(
381 ibus_,
382 reinterpret_cast<gpointer>(G_CALLBACK(BusNameOwnerChangedThunk)),
383 this);
384
385 // Disconnect signals for the panel service as well.
386 IBusPanelService* ibus_panel_service = IBUS_PANEL_SERVICE(
387 g_object_get_data(G_OBJECT(ibus_), kPanelObjectKey));
388 if (ibus_panel_service) {
389 g_signal_handlers_disconnect_by_func(
390 ibus_panel_service,
391 reinterpret_cast<gpointer>(G_CALLBACK(FocusInThunk)),
392 this);
393 g_signal_handlers_disconnect_by_func(
394 ibus_panel_service,
395 reinterpret_cast<gpointer>(G_CALLBACK(RegisterPropertiesThunk)),
396 this);
397 g_signal_handlers_disconnect_by_func(
398 ibus_panel_service,
399 reinterpret_cast<gpointer>(G_CALLBACK(UpdatePropertyThunk)),
400 this);
401 }
402 }
403 }
404
405 bool IBusControllerImpl::Start(const std::vector<std::string>& ids) {
406 MaybeInitializeIBusBus();
407 should_launch_daemon_ = true;
408 return MaybeLaunchIBusDaemon();
409 }
410
411 bool IBusControllerImpl::Stop() {
412 if (IBusConnectionsAreAlive()) {
413 // Ask IBus to exit *asynchronously*.
414 ibus_bus_exit_async(ibus_,
415 FALSE /* do not restart */,
416 -1 /* timeout */,
417 NULL /* cancellable */,
418 NULL /* callback */,
419 NULL /* user_data */);
420 if (ibus_config_) {
421 // Release |ibus_config_| unconditionally to make sure next
422 // IBusConnectionsAreAlive() call will return false.
423 g_object_unref(ibus_config_);
424 ibus_config_ = NULL;
425 }
426 } else if (process_handle_ != base::kNullProcessHandle) {
427 base::KillProcess(process_handle_, -1, false /* wait */);
428 LOG(ERROR) << "Killing ibus-daemon. PID="
429 << base::GetProcId(process_handle_);
430 } else {
431 // The daemon hasn't been started yet.
432 }
433
434 process_handle_ = base::kNullProcessHandle;
435 should_launch_daemon_ = false;
436 return true;
437 }
438
439 bool IBusControllerImpl::ChangeInputMethod(const std::string& id) {
440 DCHECK(should_launch_daemon_);
441
442 // Sanity checks.
443 DCHECK(!InputMethodUtil::IsKeyboardLayout(id));
444 if (!whitelist_.InputMethodIdIsWhitelisted(id) &&
445 !InputMethodUtil::IsExtensionInputMethod(id))
446 return false;
447
448 current_input_method_id_ = id;
449
450 // Clear all input method properties unconditionally.
451 //
452 // When switching to another input method and no text area is focused,
453 // RegisterProperties signal for the new input method will NOT be sent
454 // until a text area is focused. Therefore, we have to clear the old input
455 // method properties here to keep the input method switcher status
456 // consistent.
457 RegisterProperties(NULL, NULL);
458
459 if (!IBusConnectionsAreAlive()) {
460 LOG(INFO) << "ChangeInputMethod: IBus connection is not alive (yet).";
461 // |id| will become usable shortly since Start() has already been called.
462 // Just return true.
463 } else {
464 SendChangeInputMethodRequest(id);
465 }
466
467 return true;
468 }
469
470 bool IBusControllerImpl::ActivateInputMethodProperty(const std::string& key) {
471 if (!IBusConnectionsAreAlive()) {
472 LOG(ERROR) << "ActivateInputMethodProperty: IBus connection is not alive";
473 return false;
474 }
475 if (current_input_context_path_.empty()) {
476 LOG(ERROR) << "Input context is unknown";
477 return false;
478 }
479
480 // The third parameter of ibus_input_context_property_activate() has to be
481 // true when the |key| points to a radio button. false otherwise.
482 bool is_radio = true;
483 size_t i;
484 for (i = 0; i < current_property_list_.size(); ++i) {
485 if (current_property_list_[i].key == key) {
486 is_radio = current_property_list_[i].is_selection_item;
487 break;
488 }
489 }
490 if (i == current_property_list_.size()) {
491 LOG(ERROR) << "ActivateInputMethodProperty: unknown key: " << key;
492 return false;
493 }
494
495 IBusInputContext* context =
496 GetInputContext(current_input_context_path_, ibus_);
497 if (!context)
498 return false;
499
500 // Activate the property *asynchronously*.
501 ibus_input_context_property_activate(context, key.c_str(), is_radio);
502
503 // We don't have to call ibus_proxy_destroy(context) explicitly here,
504 // i.e. we can just call g_object_unref(context), since g_object_unref can
505 // trigger both dispose, which is overridden by src/ibusproxy.c, and
506 // finalize functions. For details, see
507 // http://library.gnome.org/devel/gobject/stable/gobject-memory.html
508 g_object_unref(context);
509
510 return true;
511 }
512
513 #if defined(USE_VIRTUAL_KEYBOARD)
514 // IBusController override.
515 void IBusControllerImpl::SendHandwritingStroke(
516 const HandwritingStroke& stroke) {
517 if (stroke.size() < 2) {
518 LOG(WARNING) << "Empty stroke data or a single dot is passed.";
519 return;
520 }
521
522 IBusInputContext* context =
523 GetInputContext(current_input_context_path_, ibus_);
524 if (!context)
525 return;
526
527 const size_t raw_stroke_size = stroke.size() * 2;
528 scoped_array<double> raw_stroke(new double[raw_stroke_size]);
529 for (size_t n = 0; n < stroke.size(); ++n) {
530 raw_stroke[n * 2] = stroke[n].first; // x
531 raw_stroke[n * 2 + 1] = stroke[n].second; // y
532 }
533 ibus_input_context_process_hand_writing_event(
534 context, raw_stroke.get(), raw_stroke_size);
535 g_object_unref(context);
536 }
537
538 // IBusController override.
539 void IBusControllerImpl::CancelHandwriting(int n_strokes) {
540 IBusInputContext* context =
541 GetInputContext(current_input_context_path_, ibus_);
542 if (!context)
543 return;
544 ibus_input_context_cancel_hand_writing(context, n_strokes);
545 g_object_unref(context);
546 }
547 #endif
548
549 bool IBusControllerImpl::IBusConnectionsAreAlive() {
550 return (process_handle_ != base::kNullProcessHandle) &&
551 ibus_ && ibus_bus_is_connected(ibus_) && ibus_config_;
552 }
553
554 void IBusControllerImpl::MaybeRestoreConnections() {
555 if (IBusConnectionsAreAlive())
556 return;
557 MaybeRestoreIBusConfig();
558 if (IBusConnectionsAreAlive()) {
559 LOG(INFO) << "ibus-daemon and ibus-memconf processes are ready.";
560 ConnectPanelServiceSignals();
561 SendAllInputMethodConfigs();
562 if (!current_input_method_id_.empty())
563 SendChangeInputMethodRequest(current_input_method_id_);
564 }
565 }
566
567 void IBusControllerImpl::MaybeInitializeIBusBus() {
568 if (ibus_)
569 return;
570
571 ibus_init();
572 // Establish IBus connection between ibus-daemon to change the current input
573 // method engine, properties, and so on.
574 ibus_ = ibus_bus_new();
575 DCHECK(ibus_);
576
577 // Register callback functions for IBusBus signals.
578 ConnectBusSignals();
579
580 // Ask libibus to watch the NameOwnerChanged signal *asynchronously*.
581 ibus_bus_set_watch_dbus_signal(ibus_, TRUE);
582
583 if (ibus_bus_is_connected(ibus_)) {
584 LOG(ERROR) << "IBus connection is ready: ibus-daemon is already running?";
585 BusConnected(ibus_);
586 }
587 }
588
589 void IBusControllerImpl::MaybeRestoreIBusConfig() {
590 if (!ibus_)
591 return;
592
593 // Destroy the current |ibus_config_| object. No-op if it's NULL.
594 MaybeDestroyIBusConfig();
595
596 if (ibus_config_)
597 return;
598
599 GDBusConnection* ibus_connection = ibus_bus_get_connection(ibus_);
600 if (!ibus_connection) {
601 VLOG(1) << "Couldn't create an ibus config object since "
602 << "IBus connection is not ready.";
603 return;
604 }
605
606 const gboolean disconnected
607 = g_dbus_connection_is_closed(ibus_connection);
608 if (disconnected) {
609 // |ibus_| object is not NULL, but the connection between ibus-daemon
610 // is not yet established. In this case, we don't create |ibus_config_|
611 // object.
612 LOG(ERROR) << "Couldn't create an ibus config object since "
613 << "IBus connection is closed.";
614 return;
615 }
616 // If memconf is not successfully started yet, ibus_config_new() will
617 // return NULL. Otherwise, it returns a transfer-none and non-floating
618 // object. ibus_config_new() sometimes issues a D-Bus *synchronous* IPC
619 // to check if the org.freedesktop.IBus.Config service is available.
620 ibus_config_ = ibus_config_new(ibus_connection,
621 NULL /* do not cancel the operation */,
622 NULL /* do not get error information */);
623 if (!ibus_config_) {
624 LOG(ERROR) << "ibus_config_new() failed. ibus-memconf is not ready?";
625 return;
626 }
627
628 // TODO(yusukes): g_object_weak_ref might be better since it allows
629 // libcros to detect the delivery of the "destroy" glib signal the
630 // |ibus_config_| object.
631 g_object_ref(ibus_config_);
632 VLOG(1) << "ibus_config_ is ready.";
633 }
634
635 void IBusControllerImpl::MaybeDestroyIBusConfig() {
636 if (!ibus_) {
637 LOG(ERROR) << "MaybeDestroyIBusConfig: ibus_ is NULL";
638 return;
639 }
640 if (ibus_config_ && !ibus_bus_is_connected(ibus_)) {
641 g_object_unref(ibus_config_);
642 ibus_config_ = NULL;
643 }
644 }
645
646 void IBusControllerImpl::SendChangeInputMethodRequest(const std::string& id) {
647 // Change the global engine *asynchronously*.
648 ibus_bus_set_global_engine_async(ibus_,
649 id.c_str(),
650 -1, // use the default ibus timeout
651 NULL, // cancellable
652 NULL, // callback
653 NULL); // user_data
654 }
655
656 void IBusControllerImpl::SendAllInputMethodConfigs() {
657 DCHECK(IBusConnectionsAreAlive());
658
659 InputMethodConfigRequests::const_iterator iter =
660 current_config_values_.begin();
661 for (; iter != current_config_values_.end(); ++iter) {
662 SetInputMethodConfigInternal(iter->first, iter->second);
663 }
664 }
665
666 bool IBusControllerImpl::SetInputMethodConfigInternal(
667 const ConfigKeyType& key,
668 const InputMethodConfigValue& value) {
669 if (!IBusConnectionsAreAlive())
670 return true;
671
672 // Convert the type of |value| from our structure to GVariant.
673 GVariant* variant = NULL;
674 switch (value.type) {
675 case InputMethodConfigValue::kValueTypeString:
676 variant = g_variant_new_string(value.string_value.c_str());
677 break;
678 case InputMethodConfigValue::kValueTypeInt:
679 variant = g_variant_new_int32(value.int_value);
680 break;
681 case InputMethodConfigValue::kValueTypeBool:
682 variant = g_variant_new_boolean(value.bool_value);
683 break;
684 case InputMethodConfigValue::kValueTypeStringList:
685 GVariantBuilder variant_builder;
686 g_variant_builder_init(&variant_builder, G_VARIANT_TYPE("as"));
687 const size_t size = value.string_list_value.size();
688 // |size| could be 0 for some special configurations such as IBus hotkeys.
689 for (size_t i = 0; i < size; ++i) {
690 g_variant_builder_add(&variant_builder,
691 "s",
692 value.string_list_value[i].c_str());
693 }
694 variant = g_variant_builder_end(&variant_builder);
695 break;
696 }
697
698 if (!variant) {
699 LOG(ERROR) << "SendInputMethodConfig: unknown value.type";
700 return false;
701 }
702 DCHECK(g_variant_is_floating(variant));
703 DCHECK(ibus_config_);
704
705 // Set an ibus configuration value *asynchronously*.
706 ibus_config_set_value_async(ibus_config_,
707 key.first.c_str(),
708 key.second.c_str(),
709 variant,
710 -1, // use the default ibus timeout
711 NULL, // cancellable
712 SetInputMethodConfigCallback,
713 g_object_ref(ibus_config_));
714
715 // Since |variant| is floating, ibus_config_set_value_async consumes
716 // (takes ownership of) the variable.
717 return true;
718 }
719
720 void IBusControllerImpl::ConnectBusSignals() {
721 if (!ibus_)
722 return;
723
724 // We use g_signal_connect_after here since the callback should be called
725 // *after* the IBusBusDisconnectedCallback in chromeos_input_method_ui.cc
726 // is called. chromeos_input_method_ui.cc attaches the panel service object
727 // to |ibus_|, and the callback in this file use the attached object.
728 g_signal_connect_after(ibus_,
729 "connected",
730 G_CALLBACK(BusConnectedThunk),
731 this);
732
733 g_signal_connect(ibus_,
734 "disconnected",
735 G_CALLBACK(BusDisconnectedThunk),
736 this);
737
738 g_signal_connect(ibus_,
739 "name-owner-changed",
740 G_CALLBACK(BusNameOwnerChangedThunk),
741 this);
742 }
743
744 void IBusControllerImpl::ConnectPanelServiceSignals() {
745 if (!ibus_)
746 return;
747
748 IBusPanelService* ibus_panel_service = IBUS_PANEL_SERVICE(
749 g_object_get_data(G_OBJECT(ibus_), kPanelObjectKey));
750 if (!ibus_panel_service) {
751 LOG(ERROR) << "IBusPanelService is NOT available.";
752 return;
753 }
754 // We don't _ref() or _weak_ref() the panel service object, since we're not
755 // interested in the life time of the object.
756
757 g_signal_connect(ibus_panel_service,
758 "focus-in",
759 G_CALLBACK(FocusInThunk),
760 this);
761 g_signal_connect(ibus_panel_service,
762 "register-properties",
763 G_CALLBACK(RegisterPropertiesThunk),
764 this);
765 g_signal_connect(ibus_panel_service,
766 "update-property",
767 G_CALLBACK(UpdatePropertyThunk),
768 this);
769 }
770
771 void IBusControllerImpl::BusConnected(IBusBus* bus) {
772 LOG(INFO) << "IBus connection is established.";
773 MaybeRestoreConnections();
774 }
775
776 void IBusControllerImpl::BusDisconnected(IBusBus* bus) {
777 LOG(INFO) << "IBus connection is terminated.";
778 // ibus-daemon might be terminated. Since |ibus_| object will automatically
779 // connect to the daemon if it restarts, we don't have to set NULL on ibus_.
780 // Call MaybeDestroyIBusConfig() to set |ibus_config_| to NULL temporarily.
781 MaybeDestroyIBusConfig();
782 }
783
784 void IBusControllerImpl::BusNameOwnerChanged(IBusBus* bus,
785 const gchar* name,
786 const gchar* old_name,
787 const gchar* new_name) {
788 DCHECK(name);
789 DCHECK(old_name);
790 DCHECK(new_name);
791
792 if (name != std::string("org.freedesktop.IBus.Config")) {
793 // Not a signal for ibus-memconf.
794 return;
795 }
796
797 const std::string empty_string;
798 if (old_name != empty_string || new_name == empty_string) {
799 // ibus-memconf died?
800 LOG(WARNING) << "Unexpected name owner change: name=" << name
801 << ", old_name=" << old_name << ", new_name=" << new_name;
802 // TODO(yusukes): it might be nice to set |ibus_config_| to NULL and call
803 // a new callback function like OnDisconnect() here to allow Chrome to
804 // recover all input method configurations when ibus-memconf is
805 // automatically restarted by ibus-daemon. Though ibus-memconf is pretty
806 // stable and unlikely crashes.
807 return;
808 }
809 VLOG(1) << "IBus config daemon is started. Recovering ibus_config_";
810
811 // Try to recover |ibus_config_|. If the |ibus_config_| object is
812 // successfully created, |OnConnectionChange| will be called to
813 // notify Chrome that IBus is ready.
814 MaybeRestoreConnections();
815 }
816
817 void IBusControllerImpl::FocusIn(IBusPanelService* panel,
818 const gchar* input_context_path) {
819 if (!input_context_path)
820 LOG(ERROR) << "NULL context passed";
821 else
822 VLOG(1) << "FocusIn: " << input_context_path;
823 // Remember the current ic path.
824 current_input_context_path_ = Or(input_context_path, "");
825 }
826
827 void IBusControllerImpl::RegisterProperties(IBusPanelService* panel,
828 IBusPropList* ibus_prop_list) {
829 // Note: |panel| can be NULL. See ChangeInputMethod().
830 VLOG(1) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)");
831
832 current_property_list_.clear();
833 if (ibus_prop_list) {
834 // You can call
835 // LOG(INFO) << "\n" << PrintPropList(ibus_prop_list, 0);
836 // here to dump |ibus_prop_list|.
837 if (!FlattenPropertyList(ibus_prop_list, &current_property_list_)) {
838 // Clear properties on errors.
839 current_property_list_.clear();
840 }
841 }
842 FOR_EACH_OBSERVER(Observer, observers_, PropertyChanged());
843 }
844
845 void IBusControllerImpl::UpdateProperty(IBusPanelService* panel,
846 IBusProperty* ibus_prop) {
847 VLOG(1) << "UpdateProperty";
848 DCHECK(ibus_prop);
849
850 // You can call
851 // LOG(INFO) << "\n" << PrintProp(ibus_prop, 0);
852 // here to dump |ibus_prop|.
853
854 InputMethodPropertyList prop_list; // our representation.
855 if (!FlattenProperty(ibus_prop, &prop_list)) {
856 // Don't update the UI on errors.
857 LOG(ERROR) << "Malformed properties are detected";
858 return;
859 }
860
861 // Notify the change.
862 if (!prop_list.empty()) {
863 for (size_t i = 0; i < prop_list.size(); ++i) {
864 FindAndUpdateProperty(prop_list[i], &current_property_list_);
865 }
866 FOR_EACH_OBSERVER(Observer, observers_, PropertyChanged());
867 }
868 }
869
870 bool IBusControllerImpl::MaybeLaunchIBusDaemon() {
871 static const char kIBusDaemonPath[] = "/usr/bin/ibus-daemon";
872
873 if (process_handle_ != base::kNullProcessHandle) {
874 LOG(ERROR) << "MaybeLaunchIBusDaemon: ibus-daemon is already running.";
875 return false;
876 }
877 if (!should_launch_daemon_)
878 return false;
879
880 // TODO(zork): Send output to /var/log/ibus.log
881 const std::string ibus_daemon_command_line =
882 base::StringPrintf("%s --panel=disable --cache=none --restart --replace",
883 kIBusDaemonPath);
884 if (!LaunchProcess(ibus_daemon_command_line,
885 &process_handle_,
886 reinterpret_cast<GChildWatchFunc>(OnIBusDaemonExit))) {
887 LOG(ERROR) << "Failed to launch " << ibus_daemon_command_line;
888 return false;
889 }
890 return true;
891 }
892
893 bool IBusControllerImpl::LaunchProcess(const std::string& command_line,
894 base::ProcessHandle* process_handle,
895 GChildWatchFunc watch_func) {
896 std::vector<std::string> argv;
897 base::ProcessHandle handle = base::kNullProcessHandle;
898
899 base::SplitString(command_line, ' ', &argv);
900
901 if (!base::LaunchProcess(argv, base::LaunchOptions(), &handle)) {
902 LOG(ERROR) << "Could not launch: " << command_line;
903 return false;
904 }
905
906 // g_child_watch_add is necessary to prevent the process from becoming a
907 // zombie.
908 // TODO(yusukes): port g_child_watch_add to base/process_utils_posix.cc.
909 const base::ProcessId pid = base::GetProcId(handle);
910 g_child_watch_add(pid, watch_func, this);
911
912 *process_handle = handle;
913 VLOG(1) << command_line << "is started. PID=" << pid;
914 return true;
915 }
916
917 // static
918 void IBusControllerImpl::SetInputMethodConfigCallback(GObject* source_object,
919 GAsyncResult* res,
920 gpointer user_data) {
921 IBusConfig* config = IBUS_CONFIG(user_data);
922 g_return_if_fail(config);
923
924 GError* error = NULL;
925 const gboolean result =
926 ibus_config_set_value_async_finish(config, res, &error);
927
928 if (!result) {
929 std::string message = "(unknown error)";
930 if (error && error->message) {
931 message = error->message;
932 }
933 LOG(ERROR) << "ibus_config_set_value_async failed: " << message;
934 }
935
936 if (error)
937 g_error_free(error);
938 g_object_unref(config);
939 }
940
941 // static
942 void IBusControllerImpl::OnIBusDaemonExit(GPid pid,
943 gint status,
944 IBusControllerImpl* controller) {
945 if (controller->process_handle_ != base::kNullProcessHandle &&
946 base::GetProcId(controller->process_handle_) == pid) {
947 controller->process_handle_ = base::kNullProcessHandle;
948 }
949 // Restart the daemon if needed.
950 controller->MaybeLaunchIBusDaemon();
951 }
952 #endif // defined(HAVE_IBUS)
953
954 // static
955 bool IBusControllerImpl::FindAndUpdatePropertyForTesting(
956 const chromeos::input_method::InputMethodProperty& new_prop,
957 chromeos::input_method::InputMethodPropertyList* prop_list) {
958 return FindAndUpdateProperty(new_prop, prop_list);
959 }
960
961 } // namespace input_method
962 } // namespace chromeos
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698