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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/input_method/ibus_controller_impl.h"
#include <algorithm> // for std::reverse.
#include <cstdio>
#include <cstring> // for std::strcmp.
#include <set>
#include <sstream>
#include <stack>
#include <utility>
#include "ash/shell.h"
#include "base/bind.h"
#include "base/environment.h"
#include "base/files/file_path_watcher.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/rand_util.h"
#include "base/stringprintf.h"
#include "base/strings/string_split.h"
#include "chrome/browser/chromeos/input_method/input_method_config.h"
#include "chrome/browser/chromeos/input_method/input_method_property.h"
#include "chrome/browser/chromeos/input_method/input_method_util.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/ibus/ibus_client.h"
#include "chromeos/dbus/ibus/ibus_config_client.h"
#include "chromeos/dbus/ibus/ibus_constants.h"
#include "chromeos/dbus/ibus/ibus_input_context_client.h"
#include "chromeos/dbus/ibus/ibus_panel_service.h"
#include "chromeos/dbus/ibus/ibus_property.h"
#include "content/public/browser/browser_thread.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/root_window.h"
#include "ui/base/ime/input_method_ibus.h"
namespace {
// Finds a property which has |new_prop.key| from |prop_list|, and replaces the
// property with |new_prop|. Returns true if such a property is found.
bool FindAndUpdateProperty(
const chromeos::input_method::InputMethodProperty& new_prop,
chromeos::input_method::InputMethodPropertyList* prop_list) {
for (size_t i = 0; i < prop_list->size(); ++i) {
chromeos::input_method::InputMethodProperty& prop = prop_list->at(i);
if (prop.key == new_prop.key) {
prop = new_prop;
return true;
}
}
return false;
}
void ConfigSetValueErrorCallback() {
DVLOG(1) << "IBusConfig: SetValue is failed.";
}
} // namespace
namespace chromeos {
namespace input_method {
namespace {
// Returns true if |key| is blacklisted.
bool PropertyKeyIsBlacklisted(const std::string& key) {
// The list of input method property keys that we don't handle.
static const char* kInputMethodPropertyKeysBlacklist[] = {
"setup", // used in ibus-m17n.
"status", // used in ibus-m17n.
};
for (size_t i = 0; i < arraysize(kInputMethodPropertyKeysBlacklist); ++i) {
if (key == kInputMethodPropertyKeysBlacklist[i])
return true;
}
return false;
}
// This function is called by and FlattenProperty() and converts IBus
// representation of a property, |ibus_prop|, to our own and push_back the
// result to |out_prop_list|. This function returns true on success, and
// returns false if sanity checks for |ibus_prop| fail.
bool ConvertProperty(const IBusProperty& ibus_prop,
InputMethodPropertyList* out_prop_list) {
DCHECK(out_prop_list);
DCHECK(ibus_prop.key().empty());
IBusProperty::IBusPropertyType type = ibus_prop.type();
// Sanity checks.
const bool has_sub_props = !ibus_prop.sub_properties().empty();
if (has_sub_props && (type != IBusProperty::IBUS_PROPERTY_TYPE_MENU)) {
DVLOG(1) << "The property has sub properties, "
<< "but the type of the property is not PROP_TYPE_MENU";
return false;
}
if ((!has_sub_props) &&
(type == IBusProperty::IBUS_PROPERTY_TYPE_MENU)) {
// This is usually not an error. ibus-daemon sometimes sends empty props.
DVLOG(1) << "Property list is empty";
return false;
}
if (type == IBusProperty::IBUS_PROPERTY_TYPE_SEPARATOR ||
type == IBusProperty::IBUS_PROPERTY_TYPE_MENU) {
// This is not an error, but we don't push an item for these types.
return true;
}
// This label will be localized later.
// See chrome/browser/chromeos/input_method/input_method_util.cc.
std::string label_to_use;
if (!ibus_prop.tooltip().empty())
label_to_use = ibus_prop.tooltip();
else if (!ibus_prop.label().empty())
label_to_use = ibus_prop.label();
else
label_to_use = ibus_prop.key();
out_prop_list->push_back(InputMethodProperty(
ibus_prop.key(),
label_to_use,
(type == IBusProperty::IBUS_PROPERTY_TYPE_RADIO),
ibus_prop.checked()));
return true;
}
// Converts |ibus_prop| to |out_prop_list|. Please note that |ibus_prop|
// may or may not have children. See the comment for FlattenPropertyList
// for details. Returns true if no error is found.
bool FlattenProperty(const IBusProperty& ibus_prop,
InputMethodPropertyList* out_prop_list) {
DCHECK(out_prop_list);
// Filter out unnecessary properties.
if (PropertyKeyIsBlacklisted(ibus_prop.key()))
return true;
// Convert |prop| to InputMethodProperty and push it to |out_prop_list|.
if (!ConvertProperty(ibus_prop, out_prop_list))
return false;
// Process childrens iteratively (if any). Push all sub properties to the
// stack.
if (!ibus_prop.sub_properties().empty()) {
const IBusPropertyList& sub_props = ibus_prop.sub_properties();
for (size_t i = 0; i < sub_props.size(); ++i) {
if (!FlattenProperty(*sub_props[i], out_prop_list))
return false;
}
}
return true;
}
// Converts IBus representation of a property list, |ibus_prop_list| to our
// own. This function also flatten the original list (actually it's a tree).
// Returns true if no error is found. The conversion to our own type is
// necessary since our language switcher in Chrome tree don't (or can't) know
// IBus types. Here is an example:
//
// ======================================================================
// Input:
//
// --- Item-1
// |- Item-2
// |- SubMenuRoot --- Item-3-1
// | |- Item-3-2
// | |- Item-3-3
// |- Item-4
//
// (Note: Item-3-X is a selection item since they're on a sub menu.)
//
// Output:
//
// Item-1, Item-2, Item-3-1, Item-3-2, Item-3-3, Item-4
// (Note: SubMenuRoot does not appear in the output.)
// ======================================================================
bool FlattenPropertyList(const IBusPropertyList& ibus_prop_list,
InputMethodPropertyList* out_prop_list) {
DCHECK(out_prop_list);
bool result = true;
for (size_t i = 0; i < ibus_prop_list.size(); ++i) {
result &= FlattenProperty(*ibus_prop_list[i], out_prop_list);
}
return result;
}
base::FilePathWatcher* g_file_path_watcher = NULL;
// Called when the ibus-daemon address file is modified.
void OnFilePathChanged(const base::Closure& closure,
const base::FilePath& file_path,
bool failed) {
if (failed)
return; // Can't recover, do nothing.
if (!g_file_path_watcher)
return; // Already discarded watch task.
content::BrowserThread::PostTask(content::BrowserThread::UI,
FROM_HERE,
closure);
MessageLoop::current()->DeleteSoon(FROM_HERE, g_file_path_watcher);
g_file_path_watcher = NULL;
}
// Start watching |address_file_path|. If the target file is changed, |callback|
// is called on UI thread. This function should be called on FILE thread.
void StartWatch(const std::string& address_file_path,
const base::Callback<void()>& callback) {
// Before start watching, discard on-going watching task.
delete g_file_path_watcher;
g_file_path_watcher = new base::FilePathWatcher;
bool result = g_file_path_watcher->Watch(
base::FilePath::FromUTF8Unsafe(address_file_path),
false, // do not watch child directory.
base::Bind(&OnFilePathChanged, callback));
DCHECK(result);
}
} // namespace
IBusControllerImpl::IBusControllerImpl()
: process_handle_(base::kNullProcessHandle),
ibus_daemon_status_(IBUS_DAEMON_STOP),
input_method_(NULL),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) {
}
IBusControllerImpl::~IBusControllerImpl() {
}
bool IBusControllerImpl::Start() {
if (IBusConnectionsAreAlive())
return true;
if (ibus_daemon_status_ == IBUS_DAEMON_STOP ||
ibus_daemon_status_ == IBUS_DAEMON_SHUTTING_DOWN) {
return StartIBusDaemon();
}
return true;
}
void IBusControllerImpl::Reset() {
if (!IBusConnectionsAreAlive())
return;
IBusInputContextClient* client
= DBusThreadManager::Get()->GetIBusInputContextClient();
// We don't need to call Reset if there is no on-going input context, because
// the input context will be reset at initialization.
if (client && client->IsObjectProxyReady())
client->Reset();
}
bool IBusControllerImpl::Stop() {
if (ibus_daemon_status_ == IBUS_DAEMON_SHUTTING_DOWN ||
ibus_daemon_status_ == IBUS_DAEMON_STOP) {
return true;
}
ibus_daemon_status_ = IBUS_DAEMON_SHUTTING_DOWN;
// TODO(nona): Shutdown ibus-bus connection.
if (IBusConnectionsAreAlive()) {
// Ask IBus to exit *asynchronously*.
IBusClient* client = DBusThreadManager::Get()->GetIBusClient();
if (client)
client->Exit(IBusClient::SHUT_DOWN_IBUS_DAEMON,
base::Bind(&base::DoNothing));
} else {
base::KillProcess(process_handle_, -1, false /* wait */);
DVLOG(1) << "Killing ibus-daemon. PID="
<< base::GetProcId(process_handle_);
}
process_handle_ = base::kNullProcessHandle;
return true;
}
bool IBusControllerImpl::ChangeInputMethod(const std::string& id) {
if (ibus_daemon_status_ == IBUS_DAEMON_SHUTTING_DOWN ||
ibus_daemon_status_ == IBUS_DAEMON_STOP) {
return false;
}
// Sanity checks.
DCHECK(!InputMethodUtil::IsKeyboardLayout(id));
if (!whitelist_.InputMethodIdIsWhitelisted(id) &&
!InputMethodUtil::IsExtensionInputMethod(id))
return false;
// Clear input method properties unconditionally if |id| is not equal to
// |current_input_method_id_|.
//
// When switching to another input method and no text area is focused,
// RegisterProperties signal for the new input method will NOT be sent
// until a text area is focused. Therefore, we have to clear the old input
// method properties here to keep the input method switcher status
// consistent.
//
// When |id| and |current_input_method_id_| are the same, the properties
// shouldn't be cleared. If we do that, something wrong happens in step #4
// below:
// 1. Enable "xkb:us::eng" and "mozc". Switch to "mozc".
// 2. Focus Omnibox. IME properties for mozc are sent to Chrome.
// 3. Switch to "xkb:us::eng". No function in this file is called.
// 4. Switch back to "mozc". ChangeInputMethod("mozc") is called, but it's
// basically NOP since ibus-daemon's current IME is already "mozc".
// IME properties are not sent to Chrome for the same reason.
if (id != current_input_method_id_) {
const IBusPropertyList empty_list;
RegisterProperties(empty_list);
}
current_input_method_id_ = id;
if (!IBusConnectionsAreAlive()) {
DVLOG(1) << "ChangeInputMethod: IBus connection is not alive (yet).";
// |id| will become usable shortly since Start() has already been called.
// Just return true.
} else {
SendChangeInputMethodRequest(id);
}
return true;
}
bool IBusControllerImpl::ActivateInputMethodProperty(const std::string& key) {
if (!IBusConnectionsAreAlive()) {
DVLOG(1) << "ActivateInputMethodProperty: IBus connection is not alive";
return false;
}
// The third parameter of ibus_input_context_property_activate() has to be
// true when the |key| points to a radio button. false otherwise.
bool is_radio = true;
size_t i;
for (i = 0; i < current_property_list_.size(); ++i) {
if (current_property_list_[i].key == key) {
is_radio = current_property_list_[i].is_selection_item;
break;
}
}
if (i == current_property_list_.size()) {
DVLOG(1) << "ActivateInputMethodProperty: unknown key: " << key;
return false;
}
IBusInputContextClient* client
= DBusThreadManager::Get()->GetIBusInputContextClient();
if (client)
client->PropertyActivate(key,
static_cast<ibus::IBusPropertyState>(is_radio));
return true;
}
bool IBusControllerImpl::IBusConnectionsAreAlive() {
return ibus_daemon_status_ == IBUS_DAEMON_RUNNING;
}
void IBusControllerImpl::SendChangeInputMethodRequest(const std::string& id) {
// Change the global engine *asynchronously*.
IBusClient* client = DBusThreadManager::Get()->GetIBusClient();
if (client)
client->SetGlobalEngine(id.c_str(), base::Bind(&base::DoNothing));
}
bool IBusControllerImpl::SetInputMethodConfigInternal(
const ConfigKeyType& key,
const InputMethodConfigValue& value) {
if (value.type != InputMethodConfigValue::kValueTypeString &&
value.type != InputMethodConfigValue::kValueTypeInt &&
value.type != InputMethodConfigValue::kValueTypeBool &&
value.type != InputMethodConfigValue::kValueTypeStringList) {
DVLOG(1) << "SendInputMethodConfig: unknown value.type";
return false;
}
IBusConfigClient* client = DBusThreadManager::Get()->GetIBusConfigClient();
if (!client) {
// Should return true if the ibus-memconf is not ready to use, otherwise IME
// configuration will not be initialized.
return true;
}
switch (value.type) {
case InputMethodConfigValue::kValueTypeString:
client->SetStringValue(key.first,
key.second,
value.string_value,
base::Bind(&ConfigSetValueErrorCallback));
return true;
case InputMethodConfigValue::kValueTypeInt:
client->SetIntValue(key.first,
key.second,
value.int_value,
base::Bind(&ConfigSetValueErrorCallback));
return true;
case InputMethodConfigValue::kValueTypeBool:
client->SetBoolValue(key.first,
key.second,
value.bool_value,
base::Bind(&ConfigSetValueErrorCallback));
return true;
case InputMethodConfigValue::kValueTypeStringList:
client->SetStringListValue(key.first,
key.second,
value.string_list_value,
base::Bind(&ConfigSetValueErrorCallback));
return true;
default:
NOTREACHED() << "SendInputMethodConfig: unknown value.type";
return false;
}
}
void IBusControllerImpl::RegisterProperties(
const IBusPropertyList& ibus_prop_list) {
// Note: |panel| can be NULL. See ChangeInputMethod().
current_property_list_.clear();
if (!FlattenPropertyList(ibus_prop_list, ¤t_property_list_))
current_property_list_.clear(); // Clear properties on errors.
FOR_EACH_OBSERVER(Observer, observers_, PropertyChanged());
}
void IBusControllerImpl::UpdateProperty(const IBusProperty& ibus_prop) {
InputMethodPropertyList prop_list; // our representation.
if (!FlattenProperty(ibus_prop, &prop_list)) {
// Don't update the UI on errors.
DVLOG(1) << "Malformed properties are detected";
return;
}
// Notify the change.
if (!prop_list.empty()) {
for (size_t i = 0; i < prop_list.size(); ++i) {
FindAndUpdateProperty(prop_list[i], ¤t_property_list_);
}
FOR_EACH_OBSERVER(Observer, observers_, PropertyChanged());
}
}
bool IBusControllerImpl::StartIBusDaemon() {
if (ibus_daemon_status_ == IBUS_DAEMON_INITIALIZING ||
ibus_daemon_status_ == IBUS_DAEMON_RUNNING) {
DVLOG(1) << "MaybeLaunchIBusDaemon: ibus-daemon is already running.";
return false;
}
ibus_daemon_status_ = IBUS_DAEMON_INITIALIZING;
ibus_daemon_address_ = base::StringPrintf(
"unix:abstract=ibus-%d",
base::RandInt(0, std::numeric_limits<int>::max()));
scoped_ptr<base::Environment> env(base::Environment::Create());
std::string address_file_path;
env->GetVar("IBUS_ADDRESS_FILE", &address_file_path);
DCHECK(!address_file_path.empty());
// Set up ibus-daemon address file watcher before launching ibus-daemon,
// because if watcher starts after ibus-daemon, we may miss the ibus
// connection initialization.
bool success = content::BrowserThread::PostTaskAndReply(
content::BrowserThread::FILE,
FROM_HERE,
base::Bind(&StartWatch,
address_file_path,
base::Bind(&IBusControllerImpl::IBusDaemonInitializationDone,
weak_ptr_factory_.GetWeakPtr(),
ibus_daemon_address_)),
base::Bind(&IBusControllerImpl::LaunchIBusDaemon,
weak_ptr_factory_.GetWeakPtr(),
ibus_daemon_address_));
DCHECK(success);
return true;
}
void IBusControllerImpl::LaunchIBusDaemon(const std::string& ibus_address) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK_EQ(base::kNullProcessHandle, process_handle_);
static const char kIBusDaemonPath[] = "/usr/bin/ibus-daemon";
// TODO(zork): Send output to /var/log/ibus.log
const std::string ibus_daemon_command_line =
base::StringPrintf("%s --panel=disable --cache=none --restart --replace"
" --address=%s",
kIBusDaemonPath,
ibus_address.c_str());
if (!LaunchProcess(ibus_daemon_command_line, &process_handle_)) {
DVLOG(1) << "Failed to launch " << ibus_daemon_command_line;
}
}
bool IBusControllerImpl::LaunchProcess(const std::string& command_line,
base::ProcessHandle* process_handle) {
std::vector<std::string> argv;
base::ProcessHandle handle = base::kNullProcessHandle;
base::SplitString(command_line, ' ', &argv);
if (!base::LaunchProcess(argv, base::LaunchOptions(), &handle)) {
DVLOG(1) << "Could not launch: " << command_line;
return false;
}
*process_handle = handle;
return true;
}
ui::InputMethodIBus* IBusControllerImpl::GetInputMethod() {
return input_method_ ? input_method_ :
static_cast<ui::InputMethodIBus*>(
ash::Shell::GetPrimaryRootWindow()->GetProperty(
aura::client::kRootWindowInputMethodKey));
}
void IBusControllerImpl::set_input_method_for_testing(
ui::InputMethodIBus* input_method) {
input_method_ = input_method;
}
void IBusControllerImpl::OnIBusConfigClientInitialized() {
DCHECK(thread_checker_.CalledOnValidThread());
InputMethodConfigRequests::const_iterator iter =
current_config_values_.begin();
for (; iter != current_config_values_.end(); ++iter) {
SetInputMethodConfigInternal(iter->first, iter->second);
}
}
void IBusControllerImpl::IBusDaemonInitializationDone(
const std::string& ibus_address) {
DCHECK(thread_checker_.CalledOnValidThread());
if (ibus_daemon_address_ != ibus_address)
return;
if (ibus_daemon_status_ != IBUS_DAEMON_INITIALIZING) {
// Stop() or OnIBusDaemonExit() has already been called.
return;
}
chromeos::DBusThreadManager::Get()->InitIBusBus(
ibus_address,
base::Bind(&IBusControllerImpl::OnIBusDaemonDisconnected,
weak_ptr_factory_.GetWeakPtr(),
base::GetProcId(process_handle_)));
ibus_daemon_status_ = IBUS_DAEMON_RUNNING;
ui::InputMethodIBus* input_method_ibus = GetInputMethod();
DCHECK(input_method_ibus);
input_method_ibus->OnConnected();
DBusThreadManager::Get()->GetIBusPanelService()->SetUpPropertyHandler(this);
// Restore previous input method at the beggining of connection.
if (!current_input_method_id_.empty())
SendChangeInputMethodRequest(current_input_method_id_);
DBusThreadManager::Get()->GetIBusConfigClient()->InitializeAsync(
base::Bind(&IBusControllerImpl::OnIBusConfigClientInitialized,
weak_ptr_factory_.GetWeakPtr()));
FOR_EACH_OBSERVER(Observer, observers_, OnConnected());
VLOG(1) << "The ibus-daemon initialization is done.";
}
void IBusControllerImpl::OnIBusDaemonDisconnected(base::ProcessId pid) {
if (!chromeos::DBusThreadManager::Get())
return; // Expected disconnection at shutting down. do nothing.
if (process_handle_ != base::kNullProcessHandle) {
if (base::GetProcId(process_handle_) == pid) {
// ibus-daemon crashed.
// TODO(nona): Shutdown ibus-bus connection.
process_handle_ = base::kNullProcessHandle;
} else {
// This condition is as follows.
// 1. Called Stop (process_handle_ becomes null)
// 2. Called LaunchProcess (process_handle_ becomes new instance)
// 3. Callbacked OnIBusDaemonExit for old instance and reach here.
// In this case, we should not reset process_handle_ as null, and do not
// re-launch ibus-daemon.
return;
}
}
const IBusDaemonStatus on_exit_state = ibus_daemon_status_;
ibus_daemon_status_ = IBUS_DAEMON_STOP;
ui::InputMethodIBus* input_method_ibus = GetInputMethod();
DCHECK(input_method_ibus);
input_method_ibus->OnDisconnected();
FOR_EACH_OBSERVER(Observer, observers_, OnDisconnected());
if (on_exit_state == IBUS_DAEMON_SHUTTING_DOWN) {
// Normal exitting, so do nothing.
return;
}
LOG(ERROR) << "The ibus-daemon crashed. Re-launching...";
StartIBusDaemon();
}
// static
bool IBusControllerImpl::FindAndUpdatePropertyForTesting(
const chromeos::input_method::InputMethodProperty& new_prop,
chromeos::input_method::InputMethodPropertyList* prop_list) {
return FindAndUpdateProperty(new_prop, prop_list);
}
} // namespace input_method
} // namespace chromeos
|