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

Side by Side Diff: chrome/browser/renderer_host/gtk_im_context_wrapper.cc

Issue 160577: Cleanup GtkIMContext related code by splitting it into separated source file. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src/
Patch Set: '' Created 11 years, 4 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
Property Changes:
Name: svn:eol-style
+ LF
OLDNEW
(Empty)
1 // Copyright (c) 2009 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/renderer_host/gtk_im_context_wrapper.h"
6
7 #include <gdk/gdk.h>
8 #include <gdk/gdkkeysyms.h>
9 #include <gtk/gtk.h>
10
11 #include "base/gfx/rect.h"
12 #include "base/logging.h"
13 #include "base/string_util.h"
14 #include "chrome/common/native_web_keyboard_event.h"
15 #include "chrome/browser/renderer_host/render_widget_host.h"
16 #include "chrome/browser/renderer_host/render_widget_host_view_gtk.h"
17
18 GtkIMContextWrapper::GtkIMContextWrapper(RenderWidgetHostViewGtk* host_view)
19 : host_view_(host_view),
20 context_(gtk_im_multicontext_new()),
21 context_simple_(gtk_im_context_simple_new()),
22 is_focused_(false),
23 is_composing_text_(false),
24 is_enabled_(false),
25 is_in_key_event_handler_(false),
26 preedit_cursor_position_(0),
27 is_preedit_changed_(false) {
28 DCHECK(context_);
29 DCHECK(context_simple_);
30
31 // context_ and context_simple_ share the same callback handlers.
32 // All data come from them are treated equally.
33 // context_ is for full input method support.
34 // context_simple_ is for supporting dead/compose keys when input method is
35 // disabled by webkit, eg. in password input box.
36 g_signal_connect(context_, "preedit_start",
37 G_CALLBACK(HandlePreeditStartThunk), this);
38 g_signal_connect(context_, "preedit_end",
39 G_CALLBACK(HandlePreeditEndThunk), this);
40 g_signal_connect(context_, "preedit_changed",
41 G_CALLBACK(HandlePreeditChangedThunk), this);
42 g_signal_connect(context_, "commit",
43 G_CALLBACK(HandleCommitThunk), this);
44
45 g_signal_connect(context_simple_, "preedit_start",
46 G_CALLBACK(HandlePreeditStartThunk), this);
47 g_signal_connect(context_simple_, "preedit_end",
48 G_CALLBACK(HandlePreeditEndThunk), this);
49 g_signal_connect(context_simple_, "preedit_changed",
50 G_CALLBACK(HandlePreeditChangedThunk), this);
51 g_signal_connect(context_simple_, "commit",
52 G_CALLBACK(HandleCommitThunk), this);
53 }
54
55 GtkIMContextWrapper::~GtkIMContextWrapper() {
56 if (context_)
57 g_object_unref(context_);
58 if (context_simple_)
59 g_object_unref(context_simple_);
60 }
61
62 void GtkIMContextWrapper::ProcessKeyEvent(GdkEventKey* event) {
63 // Indicates preedit-changed and commit signal handlers that we are
64 // processing a key event.
65 is_in_key_event_handler_ = true;
66 // Reset this flag so that we can know if preedit is changed after
67 // processing this key event.
68 is_preedit_changed_ = false;
69 // Clear it so that we can know if something needs committing after
70 // processing this key event.
71 commit_text_.clear();
72
73 // According to Document Object Model (DOM) Level 3 Events Specification
74 // Appendix A: Keyboard events and key identifiers
75 // http://www.w3.org/TR/DOM-Level-3-Events/keyset.html:
76 // The event sequence would be:
77 // 1. keydown
78 // 2. textInput
79 // 3. keyup
80 //
81 // So keydown must be sent to webkit before sending input method result,
82 // while keyup must be sent afterwards.
83 // However on Windows, if a keydown event has been processed by IME, its
84 // virtual keycode will be changed to VK_PROCESSKEY(0xE5) before being sent
85 // to application.
86 // To emulate the windows behavior as much as possible, we need to send the
87 // key event to the GtkIMContext object first, and decide whether or not to
88 // send the original key event to webkit according to the result from IME.
89 //
90 // If IME is enabled by WebKit, this event will be dispatched to context_
91 // to get full IME support. Otherwise it'll be dispatched to
92 // context_simple_, so that dead/compose keys can still work.
93 //
94 // It sends a "commit" signal when it has a character to be inserted
95 // even when we use a US keyboard so that we can send a Char event
96 // (or an IME event) to the renderer in our "commit"-signal handler.
97 // We should send a KeyDown (or a KeyUp) event before dispatching this
98 // event to the GtkIMContext object (and send a Char event) so that WebKit
99 // can dispatch the JavaScript events in the following order: onkeydown(),
100 // onkeypress(), and onkeyup(). (Many JavaScript pages assume this.)
101 gboolean filtered = false;
102 if (is_enabled_) {
103 filtered = gtk_im_context_filter_keypress(context_, event);
104 } else {
105 filtered = gtk_im_context_filter_keypress(context_simple_, event);
106 }
107
108 NativeWebKeyboardEvent wke(event);
109
110 // Send filtered keydown event before sending IME result.
111 if (event->type == GDK_KEY_PRESS && filtered)
112 ProcessFilteredKeyPressEvent(&wke);
113
114 // Send IME results. In most cases, it's only available if the key event
115 // is filtered by IME. But in rare cases, an unfiltered key event may also
116 // generate IME results.
117 // Any IME results generated by a unfiltered key down event must be sent
118 // before the key down event, to avoid some tricky issues. For example,
119 // when using latin-post input method, pressing 'a' then Backspace, may
120 // generate following events in sequence:
121 // 1. keydown 'a' (filtered)
122 // 2. preedit changed to "a"
123 // 3. keyup 'a' (unfiltered)
124 // 4. keydown Backspace (unfiltered)
125 // 5. commit "a"
126 // 6. preedit end
127 // 7. keyup Backspace (unfiltered)
128 //
129 // In this case, the input box will be in a strange state if keydown
130 // Backspace is sent to webkit before commit "a" and preedit end.
131 ProcessInputMethodResult(event, filtered);
132
133 // Send unfiltered keydown and keyup events after sending IME result.
134 if (event->type == GDK_KEY_PRESS && !filtered)
135 ProcessUnfilteredKeyPressEvent(&wke);
136 else if (event->type == GDK_KEY_RELEASE)
137 host_view_->GetRenderWidgetHost()->ForwardKeyboardEvent(wke);
138
139 // End of key event processing.
140 is_in_key_event_handler_ = false;
141 }
142
143 void GtkIMContextWrapper::UpdateStatus(int control,
144 const gfx::Rect& caret_rect) {
145 // The renderer has updated its IME status.
146 // Control the GtkIMContext object according to this status.
147 if (!context_ || !is_focused_)
148 return;
149
150 DCHECK(!is_in_key_event_handler_);
151
152 // TODO(james.su@gmail.com): Following code causes a side effect:
153 // When trying to move cursor from one text input box to another while
154 // composition text is still not confirmed, following CompleteComposition()
155 // calls will prevent the cursor from moving outside the first input box.
156 if (control == IME_DISABLE) {
157 if (is_enabled_) {
158 CompleteComposition();
159 gtk_im_context_reset(context_simple_);
160 gtk_im_context_focus_out(context_);
161 is_enabled_ = false;
162 }
163 } else {
164 // Enable the GtkIMContext object if it's not enabled yet.
165 if (!is_enabled_) {
166 // Reset context_simple_ to its initial state, in case it's currently
167 // in middle of a composition session inside a password box.
168 gtk_im_context_reset(context_simple_);
169 gtk_im_context_focus_in(context_);
170 // It might be true when switching from a password box in middle of a
171 // composition session.
172 is_composing_text_ = false;
173 is_enabled_ = true;
174 } else if (control == IME_COMPLETE_COMPOSITION) {
175 CompleteComposition();
176 }
177
178 // Updates the position of the IME candidate window.
179 // The position sent from the renderer is a relative one, so we need to
180 // attach the GtkIMContext object to this window before changing the
181 // position.
182 GdkRectangle cursor_rect(caret_rect.ToGdkRectangle());
183 gtk_im_context_set_cursor_location(context_, &cursor_rect);
184 }
185 }
186
187 void GtkIMContextWrapper::OnFocusIn() {
188 if (is_focused_)
189 return;
190
191 // Tracks the focused state so that we can give focus to the
192 // GtkIMContext object correctly later when IME is enabled by WebKit.
193 is_focused_ = true;
194
195 // We should call gtk_im_context_set_client_window() only when this window
196 // gain (or release) the window focus because an immodule may reset its
197 // internal status when processing this function.
198 gtk_im_context_set_client_window(context_,
199 host_view_->native_view()->window);
200
201 // Notify the GtkIMContext object of this focus-in event only if IME is
202 // enabled by WebKit.
203 if (is_enabled_)
204 gtk_im_context_focus_in(context_);
205
206 // Actually current GtkIMContextSimple implementation doesn't care about
207 // client window. This line is just for safe.
208 gtk_im_context_set_client_window(context_simple_,
209 host_view_->native_view()->window);
210
211 // context_simple_ is always enabled.
212 // Actually it doesn't care focus state at all.
213 gtk_im_context_focus_in(context_simple_);
214
215 // Enables RenderWidget's IME related events, so that we can be notified
216 // when WebKit wants to enable or disable IME.
217 host_view_->GetRenderWidgetHost()->ImeSetInputMode(true);
218 }
219
220 void GtkIMContextWrapper::OnFocusOut() {
221 if (!is_focused_)
222 return;
223
224 // Tracks the focused state so that we won't give focus to the
225 // GtkIMContext object unexpectly.
226 is_focused_ = false;
227
228 // Notify the GtkIMContext object of this focus-out event only if IME is
229 // enabled by WebKit.
230 if (is_enabled_) {
231 // To reset the GtkIMContext object and prevent data loss.
232 CompleteComposition();
233 gtk_im_context_focus_out(context_);
234 }
235
236 // Detach this GtkIMContext object from this window.
237 gtk_im_context_set_client_window(context_, NULL);
238
239 // To make sure it'll be in correct state when focused in again.
240 gtk_im_context_reset(context_simple_);
241 gtk_im_context_focus_out(context_simple_);
242 gtk_im_context_set_client_window(context_simple_, NULL);
243
244 // Reset stored IME status.
245 is_composing_text_ = false;
246 preedit_text_.clear();
247 preedit_cursor_position_ = 0;
248
249 // Disable RenderWidget's IME related events to save bandwidth.
250 host_view_->GetRenderWidgetHost()->ImeSetInputMode(false);
251 }
252
253 bool GtkIMContextWrapper::NeedCommitByForwardingCharEvent() {
254 // If there is no composition text and has only one character to be
255 // committed, then the character will be send to webkit as a Char event
256 // instead of a confirmed composition text.
257 // It should be fine to handle BMP character only, as non-BMP characters
258 // can always be committed as confirmed composition text.
259 return !is_composing_text_ && commit_text_.length() == 1;
260 }
261
262 void GtkIMContextWrapper::ProcessFilteredKeyPressEvent(
263 NativeWebKeyboardEvent* wke) {
264 // Copied from third_party/WebKit/WebCore/page/EventHandler.cpp
265 //
266 // Match key code of composition keydown event on windows.
267 // IE sends VK_PROCESSKEY which has value 229;
268 //
269 // Please refer to following documents for detals:
270 // - Virtual-Key Codes
271 // http://msdn.microsoft.com/en-us/library/ms645540(VS.85).aspx
272 // - How the IME System Works
273 // http://msdn.microsoft.com/en-us/library/cc194848.aspx
274 // - ImmGetVirtualKey Function
275 // http://msdn.microsoft.com/en-us/library/dd318570(VS.85).aspx
276 const int kCompositionEventKeyCode = 229;
277
278 // If IME has filtered this event, then replace virtual key code with
279 // VK_PROCESSKEY. See comment in ProcessKeyEvent() for details.
280 // It's only required for keydown events.
281 // To emulate windows behavior, when input method is enabled, if the commit
282 // text can be emulated by a Char event, then don't do this replacement.
283 if (!NeedCommitByForwardingCharEvent()) {
284 wke->windowsKeyCode = kCompositionEventKeyCode;
285 // keyidentifier must be updated accordingly, otherwise this key event may
286 // still be processed by webkit.
287 wke->setKeyIdentifierFromWindowsKeyCode();
288 // Prevent RenderView::UnhandledKeyboardEvent() from processing it.
289 // Otherwise unexpected result may occur. For example if it's a
290 // Backspace key event, the browser may go back to previous page.
291 if (wke->os_event) {
292 wke->os_event->keyval = GDK_VoidSymbol;
293 wke->os_event->state = 0;
294 }
295 }
296 host_view_->GetRenderWidgetHost()->ForwardKeyboardEvent(*wke);
297 }
298
299 void GtkIMContextWrapper::ProcessUnfilteredKeyPressEvent(
300 NativeWebKeyboardEvent* wke) {
301 RenderWidgetHost* host = host_view_->GetRenderWidgetHost();
302
303 // Send keydown event as it, because it's not filtered by IME.
304 host->ForwardKeyboardEvent(*wke);
305
306 // IME is disabled by WebKit or the GtkIMContext object cannot handle
307 // this key event.
308 // This case is caused by two reasons:
309 // 1. The given key event is a control-key event, (e.g. return, page up,
310 // page down, tab, arrows, etc.) or;
311 // 2. The given key event is not a control-key event but printable
312 // characters aren't assigned to the event, (e.g. alt+d, etc.)
313 // Create a Char event manually from this key event and send it to the
314 // renderer when this Char event contains a printable character which
315 // should be processed by WebKit.
316 // isSystemKey will be set to true if this key event has Alt modifier,
317 // see WebInputEventFactory::keyboardEvent() for details.
318 if (wke->text[0]) {
319 wke->type = WebKit::WebInputEvent::Char;
320 host->ForwardKeyboardEvent(*wke);
321 }
322 }
323
324 void GtkIMContextWrapper::ProcessInputMethodResult(const GdkEventKey* event,
325 bool filtered) {
326 RenderWidgetHost* host = host_view_->GetRenderWidgetHost();
327 bool committed = false;
328 // We do commit before preedit change, so that we can optimize some
329 // unnecessary preedit changes.
330 if (commit_text_.length()) {
331 if (filtered && NeedCommitByForwardingCharEvent()) {
332 // Send a Char event when we input a composed character without IMEs
333 // so that this event is to be dispatched to onkeypress() handlers,
334 // autofill, etc.
335 // Only commit text generated by a filtered key down event can be sent
336 // as a Char event, because a unfiltered key down event will probably
337 // generate another Char event.
338 // TODO(james.su@gmail.com): Is it necessary to support non BMP chars
339 // here?
340 NativeWebKeyboardEvent char_event(commit_text_[0],
341 event->state,
342 base::Time::Now().ToDoubleT());
343 host->ForwardKeyboardEvent(char_event);
344 } else {
345 committed = true;
346 // Send an IME event.
347 // Unlike a Char event, an IME event is NOT dispatched to onkeypress()
348 // handlers or autofill.
349 host->ImeConfirmComposition(commit_text_);
350 // Set this flag to false, as this composition session has been
351 // finished.
352 is_composing_text_ = false;
353 }
354 }
355
356 // Send preedit text only if it's changed.
357 // If a text has been committed, then we don't need to send the empty
358 // preedit text again.
359 if (is_preedit_changed_) {
360 if (preedit_text_.length()) {
361 host->ImeSetComposition(preedit_text_, preedit_cursor_position_,
362 -1, -1);
363 } else if (!committed) {
364 host->ImeCancelComposition();
365 }
366 }
367 }
368
369 void GtkIMContextWrapper::CompleteComposition() {
370 if (!is_enabled_)
371 return;
372
373 // If WebKit requires to complete current composition, then we need commit
374 // existing preedit text and reset the GtkIMContext object.
375
376 // Backup existing preedit text to avoid it's being cleared when resetting
377 // the GtkIMContext object.
378 string16 old_preedit_text = preedit_text_;
379
380 // Clear it so that we can know if anything is committed by following
381 // line.
382 commit_text_.clear();
383
384 // Resetting the GtkIMContext. Input method may commit something at this
385 // point. In this case, we shall not commit the preedit text again.
386 gtk_im_context_reset(context_);
387
388 // If nothing was committed by above line, then commit stored preedit text
389 // to prevent data loss.
390 if (old_preedit_text.length() && commit_text_.length() == 0) {
391 host_view_->GetRenderWidgetHost()->ImeConfirmComposition(
392 old_preedit_text);
393 }
394
395 is_composing_text_ = false;
396 preedit_text_.clear();
397 preedit_cursor_position_ = 0;
398 }
399
400 void GtkIMContextWrapper::HandleCommit(const string16& text) {
401 // Append the text to the buffer, because commit signal might be fired
402 // multiple times when processing a key event.
403 commit_text_.append(text);
404 // Nothing needs to do, if it's currently in ProcessKeyEvent()
405 // handler, which will send commit text to webkit later. Otherwise,
406 // we need send it here.
407 // It's possible that commit signal is fired without a key event, for
408 // example when user input via a voice or handwriting recognition software.
409 // In this case, the text must be committed directly.
410 if (!is_in_key_event_handler_) {
411 host_view_->GetRenderWidgetHost()->ImeConfirmComposition(text);
412 }
413 }
414
415 void GtkIMContextWrapper::HandlePreeditStart() {
416 is_composing_text_ = true;
417 }
418
419 void GtkIMContextWrapper::HandlePreeditChanged(const string16& text,
420 int cursor_position) {
421 bool changed = false;
422 // If preedit text or cursor position is not changed since last time,
423 // then it's not necessary to update it again.
424 // Preedit text is always stored, so that we can commit it when webkit
425 // requires.
426 // Don't set is_preedit_changed_ to false if there is no change, because
427 // this handler might be called multiple times with the same data.
428 if (cursor_position != preedit_cursor_position_ || text != preedit_text_) {
429 preedit_text_ = text;
430 preedit_cursor_position_ = cursor_position;
431 is_preedit_changed_ = true;
432 changed = true;
433 }
434
435 // In case we are using a buggy input method which doesn't fire
436 // "preedit_start" signal.
437 if (text.length())
438 is_composing_text_ = true;
439
440 // Nothing needs to do, if it's currently in ProcessKeyEvent()
441 // handler, which will send preedit text to webkit later.
442 // Otherwise, we need send it here if it's been changed.
443 if (!is_in_key_event_handler_ && changed) {
444 if (text.length()) {
445 host_view_->GetRenderWidgetHost()->ImeSetComposition(
446 text, cursor_position, -1, -1);
447 } else {
448 host_view_->GetRenderWidgetHost()->ImeCancelComposition();
449 }
450 }
451 }
452
453 void GtkIMContextWrapper::HandlePreeditEnd() {
454 bool changed = false;
455 if (preedit_text_.length()) {
456 // The composition session has been finished.
457 preedit_text_.clear();
458 preedit_cursor_position_ = 0;
459 is_preedit_changed_ = true;
460 changed = true;
461 }
462
463 // If there is still a preedit text when firing "preedit-end" signal,
464 // we need inform webkit to clear it.
465 // It's only necessary when it's not in ProcessKeyEvent ().
466 if (!is_in_key_event_handler_ && changed) {
467 host_view_->GetRenderWidgetHost()->ImeCancelComposition();
468 }
469
470 // Don't set is_composing_text_ to false here, because "preedit_end"
471 // signal may be fired before "commit" signal.
472 }
473
474 void GtkIMContextWrapper::HandleCommitThunk(
475 GtkIMContext* context, gchar* text, GtkIMContextWrapper* self) {
476 self->HandleCommit(UTF8ToUTF16(text));
477 }
478
479 void GtkIMContextWrapper::HandlePreeditStartThunk(
480 GtkIMContext* context, GtkIMContextWrapper* self) {
481 self->HandlePreeditStart();
482 }
483
484 void GtkIMContextWrapper::HandlePreeditChangedThunk(
485 GtkIMContext* context, GtkIMContextWrapper* self) {
486 gchar* text = NULL;
487 gint cursor_position = 0;
488 gtk_im_context_get_preedit_string(context, &text, NULL, &cursor_position);
489 self->HandlePreeditChanged(UTF8ToUTF16(text), cursor_position);
490 g_free(text);
491 }
492
493 void GtkIMContextWrapper::HandlePreeditEndThunk(
494 GtkIMContext* context, GtkIMContextWrapper* self) {
495 self->HandlePreeditEnd();
496 }
OLDNEW
« no previous file with comments | « chrome/browser/renderer_host/gtk_im_context_wrapper.h ('k') | chrome/browser/renderer_host/render_widget_host_view_gtk.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698