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

Side by Side Diff: views/controls/textfield/native_textfield_win.cc

Issue 113940: Make Textfield more portable.... (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src/
Patch Set: '' Created 11 years, 6 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) 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 "app/l10n_util.h"
6 #include "app/l10n_util_win.h"
7 #include "app/win_util.h"
8 #include "base/clipboard.h"
9 #include "base/gfx/native_theme.h"
10 #include "base/scoped_clipboard_writer.h"
11 #include "base/string_util.h"
12 #include "base/win_util.h"
13 #include "grit/app_strings.h"
14 #include "skia/ext/skia_utils_win.h"
15 #include "views/controls/hwnd_view.h"
16 #include "views/controls/menu/menu_win.h"
17 #include "views/controls/textfield/native_textfield_win.h"
18 #include "views/controls/textfield/textfield.h"
19 #include "views/focus/focus_util_win.h"
20 #include "views/views_delegate.h"
21 #include "views/widget/widget.h"
22
23 namespace views {
24
25 ///////////////////////////////////////////////////////////////////////////////
26 // Helper classes
27
28 NativeTextfieldWin::ScopedFreeze::ScopedFreeze(NativeTextfieldWin* edit,
29 ITextDocument* text_object_model)
30 : edit_(edit),
31 text_object_model_(text_object_model) {
32 // Freeze the screen.
33 if (text_object_model_) {
34 long count;
35 text_object_model_->Freeze(&count);
36 }
37 }
38
39 NativeTextfieldWin::ScopedFreeze::~ScopedFreeze() {
40 // Unfreeze the screen.
41 if (text_object_model_) {
42 long count;
43 text_object_model_->Unfreeze(&count);
44 if (count == 0) {
45 // We need to UpdateWindow() here instead of InvalidateRect() because, as
46 // far as I can tell, the edit likes to synchronously erase its background
47 // when unfreezing, thus requiring us to synchronously redraw if we don't
48 // want flicker.
49 edit_->UpdateWindow();
50 }
51 }
52 }
53
54 ///////////////////////////////////////////////////////////////////////////////
55 // NativeTextfieldWin
56
57 bool NativeTextfieldWin::did_load_library_ = false;
58
59 NativeTextfieldWin::NativeTextfieldWin(Textfield* textfield)
60 : textfield_(textfield),
61 tracking_double_click_(false),
62 double_click_time_(0),
63 can_discard_mousemove_(false),
64 contains_mouse_(false),
65 ime_discard_composition_(false),
66 ime_composition_start_(0),
67 ime_composition_length_(0),
68 bg_color_(0) {
69 if (!did_load_library_)
70 did_load_library_ = !!LoadLibrary(L"riched20.dll");
71
72 DWORD style = kDefaultEditStyle;
73 if (textfield_->style() & Textfield::STYLE_PASSWORD)
74 style |= ES_PASSWORD;
75
76 if (textfield_->read_only())
77 style |= ES_READONLY;
78
79 if (textfield_->style() & Textfield::STYLE_MULTILINE)
80 style |= ES_MULTILINE | ES_WANTRETURN | ES_AUTOVSCROLL;
81 else
82 style |= ES_AUTOHSCROLL;
83 // Make sure we apply RTL related extended window styles if necessary.
84 DWORD ex_style = l10n_util::GetExtendedStyles();
85
86 RECT r = {0, 0, textfield_->width(), textfield_->height()};
87 Create(textfield_->GetWidget()->GetNativeView(), r, NULL, style, ex_style);
88
89 if (textfield_->style() & Textfield::STYLE_LOWERCASE) {
90 DCHECK((textfield_->style() & Textfield::STYLE_PASSWORD) == 0);
91 SetEditStyle(SES_LOWERCASE, SES_LOWERCASE);
92 }
93
94 // Set up the text_object_model_.
95 CComPtr<IRichEditOle> ole_interface;
96 ole_interface.Attach(GetOleInterface());
97 text_object_model_ = ole_interface;
98
99 context_menu_.reset(new MenuWin(this, Menu::TOPLEFT, m_hWnd));
100 context_menu_->AppendMenuItemWithLabel(IDS_APP_UNDO,
101 l10n_util::GetString(IDS_APP_UNDO));
102 context_menu_->AppendSeparator();
103 context_menu_->AppendMenuItemWithLabel(IDS_APP_CUT,
104 l10n_util::GetString(IDS_APP_CUT));
105 context_menu_->AppendMenuItemWithLabel(IDS_APP_COPY,
106 l10n_util::GetString(IDS_APP_COPY));
107 context_menu_->AppendMenuItemWithLabel(IDS_APP_PASTE,
108 l10n_util::GetString(IDS_APP_PASTE));
109 context_menu_->AppendSeparator();
110 context_menu_->AppendMenuItemWithLabel(
111 IDS_APP_SELECT_ALL,
112 l10n_util::GetString(IDS_APP_SELECT_ALL));
113
114 container_view_ = new HWNDView;
115 textfield_->AddChildView(container_view_);
116 container_view_->SetAssociatedFocusView(textfield_);
117 container_view_->Attach(m_hWnd);
118 }
119
120 NativeTextfieldWin::~NativeTextfieldWin() {
121 if (IsWindow())
122 DestroyWindow();
123 }
124
125 ////////////////////////////////////////////////////////////////////////////////
126 // NativeTextfieldWin, NativeTextfieldWrapper implementation:
127
128 std::wstring NativeTextfieldWin::GetText() const {
129 int len = GetTextLength() + 1;
130 std::wstring str;
131 GetWindowText(WriteInto(&str, len), len);
132 return str;
133 }
134
135 void NativeTextfieldWin::UpdateText() {
136 std::wstring text = textfield_->text();
137 // Adjusting the string direction before setting the text in order to make
138 // sure both RTL and LTR strings are displayed properly.
139 std::wstring text_to_set;
140 if (!l10n_util::AdjustStringForLocaleDirection(text, &text_to_set))
141 text_to_set = text;
142 if (textfield_->style() & Textfield::STYLE_LOWERCASE)
143 text_to_set = l10n_util::ToLower(text_to_set);
144 SetWindowText(text_to_set.c_str());
145 }
146
147 void NativeTextfieldWin::AppendText(const std::wstring& text) {
148 int text_length = GetWindowTextLength();
149 ::SendMessage(m_hWnd, TBM_SETSEL, true, MAKELPARAM(text_length, text_length));
150 ::SendMessage(m_hWnd, EM_REPLACESEL, false,
151 reinterpret_cast<LPARAM>(text.c_str()));
152 }
153
154 std::wstring NativeTextfieldWin::GetSelectedText() const {
155 // Figure out the length of the selection.
156 long start;
157 long end;
158 GetSel(start, end);
159
160 // Grab the selected text.
161 std::wstring str;
162 GetSelText(WriteInto(&str, end - start + 1));
163
164 return str;
165 }
166
167 void NativeTextfieldWin::SelectAll() {
168 // Select from the end to the front so that the first part of the text is
169 // always visible.
170 SetSel(GetTextLength(), 0);
171 }
172
173 void NativeTextfieldWin::ClearSelection() {
174 SetSel(GetTextLength(), GetTextLength());
175 }
176
177 void NativeTextfieldWin::UpdateBorder() {
178 SetWindowPos(NULL, 0, 0, 0, 0,
179 SWP_NOMOVE | SWP_FRAMECHANGED | SWP_NOACTIVATE |
180 SWP_NOOWNERZORDER | SWP_NOSIZE);
181 }
182
183 void NativeTextfieldWin::UpdateBackgroundColor() {
184 if (!textfield_->use_default_background_color()) {
185 bg_color_ = skia::SkColorToCOLORREF(textfield_->background_color());
186 } else {
187 bg_color_ = GetSysColor(textfield_->read_only() ? COLOR_3DFACE
188 : COLOR_WINDOW);
189 }
190 CRichEditCtrl::SetBackgroundColor(bg_color_);
191 }
192
193 void NativeTextfieldWin::UpdateReadOnly() {
194 SendMessage(m_hWnd, EM_SETREADONLY, textfield_->read_only(), 0);
195 }
196
197 void NativeTextfieldWin::UpdateFont() {
198 SendMessage(m_hWnd, WM_SETFONT,
199 reinterpret_cast<WPARAM>(textfield_->font().hfont()), TRUE);
200 }
201
202 void NativeTextfieldWin::UpdateEnabled() {
203 SendMessage(m_hWnd, WM_ENABLE, textfield_->IsEnabled(), 0);
204 }
205
206 void NativeTextfieldWin::SetHorizontalMargins(int left, int right) {
207 // SendMessage expects the two values to be packed into one using MAKELONG
208 // so we truncate to 16 bits if necessary.
209 SendMessage(m_hWnd, EM_SETMARGINS,
210 EC_LEFTMARGIN | EC_RIGHTMARGIN,
211 MAKELONG(left & 0xFFFF, right & 0xFFFF));
212 }
213
214 void NativeTextfieldWin::SetFocus() {
215 // Focus the associated HWND.
216 //container_view_->Focus();
217 ::SetFocus(m_hWnd);
218 }
219
220 View* NativeTextfieldWin::GetView() {
221 return container_view_;
222 }
223
224 gfx::NativeView NativeTextfieldWin::GetTestingHandle() const {
225 return m_hWnd;
226 }
227
228 ////////////////////////////////////////////////////////////////////////////////
229 // NativeTextfieldWin, Menu::Delegate implementation:
230
231 bool NativeTextfieldWin::IsCommandEnabled(int id) const {
232 switch (id) {
233 case IDS_APP_UNDO: return !textfield_->read_only() && !!CanUndo();
234 case IDS_APP_CUT: return !textfield_->read_only() &&
235 !textfield_->IsPassword() && !!CanCut();
236 case IDS_APP_COPY: return !!CanCopy() && !textfield_->IsPassword();
237 case IDS_APP_PASTE: return !textfield_->read_only() && !!CanPaste();
238 case IDS_APP_SELECT_ALL: return !!CanSelectAll();
239 default: NOTREACHED();
240 return false;
241 }
242 }
243
244 void NativeTextfieldWin::ExecuteCommand(int id) {
245 ScopedFreeze freeze(this, GetTextObjectModel());
246 OnBeforePossibleChange();
247 switch (id) {
248 case IDS_APP_UNDO: Undo(); break;
249 case IDS_APP_CUT: Cut(); break;
250 case IDS_APP_COPY: Copy(); break;
251 case IDS_APP_PASTE: Paste(); break;
252 case IDS_APP_SELECT_ALL: SelectAll(); break;
253 default: NOTREACHED(); break;
254 }
255 OnAfterPossibleChange();
256 }
257
258 ////////////////////////////////////////////////////////////////////////////////
259 // NativeTextfieldWin, private:
260
261 void NativeTextfieldWin::OnChar(TCHAR ch, UINT repeat_count, UINT flags) {
262 HandleKeystroke(GetCurrentMessage()->message, ch, repeat_count, flags);
263 }
264
265 void NativeTextfieldWin::OnContextMenu(HWND window, const CPoint& point) {
266 CPoint p(point);
267 if (point.x == -1 || point.y == -1) {
268 GetCaretPos(&p);
269 MapWindowPoints(HWND_DESKTOP, &p, 1);
270 }
271 context_menu_->RunMenuAt(p.x, p.y);
272 }
273
274 void NativeTextfieldWin::OnCopy() {
275 if (textfield_->IsPassword())
276 return;
277
278 const std::wstring text(GetSelectedText());
279
280 if (!text.empty() && ViewsDelegate::views_delegate) {
281 ScopedClipboardWriter scw(ViewsDelegate::views_delegate->GetClipboard());
282 scw.WriteText(text);
283 }
284 }
285
286 void NativeTextfieldWin::OnCut() {
287 if (textfield_->read_only() || textfield_->IsPassword())
288 return;
289
290 OnCopy();
291
292 // This replace selection will have no effect (even on the undo stack) if the
293 // current selection is empty.
294 ReplaceSel(L"", true);
295 }
296
297 LRESULT NativeTextfieldWin::OnImeChar(UINT message, WPARAM wparam, LPARAM lparam ) {
298 // http://crbug.com/7707: a rich-edit control may crash when it receives a
299 // WM_IME_CHAR message while it is processing a WM_IME_COMPOSITION message.
300 // Since view controls don't need WM_IME_CHAR messages, we prevent WM_IME_CHAR
301 // messages from being dispatched to view controls via the CallWindowProc()
302 // call.
303 return 0;
304 }
305
306 LRESULT NativeTextfieldWin::OnImeStartComposition(UINT message,
307 WPARAM wparam,
308 LPARAM lparam) {
309 // Users may press alt+shift or control+shift keys to change their keyboard
310 // layouts. So, we retrieve the input locale identifier everytime we start
311 // an IME composition.
312 int language_id = PRIMARYLANGID(GetKeyboardLayout(0));
313 ime_discard_composition_ =
314 language_id == LANG_JAPANESE || language_id == LANG_CHINESE;
315 ime_composition_start_ = 0;
316 ime_composition_length_ = 0;
317
318 return DefWindowProc(message, wparam, lparam);
319 }
320
321 LRESULT NativeTextfieldWin::OnImeComposition(UINT message,
322 WPARAM wparam,
323 LPARAM lparam) {
324 text_before_change_.clear();
325 LRESULT result = DefWindowProc(message, wparam, lparam);
326
327 ime_composition_start_ = 0;
328 ime_composition_length_ = 0;
329 if (ime_discard_composition_) {
330 // Call IMM32 functions to retrieve the position and the length of the
331 // ongoing composition string and notify the OnAfterPossibleChange()
332 // function that it should discard the composition string from a search
333 // string. We should not call IMM32 functions in the function because it
334 // is called when an IME is not composing a string.
335 HIMC imm_context = ImmGetContext(m_hWnd);
336 if (imm_context) {
337 CHARRANGE selection;
338 GetSel(selection);
339 const int cursor_position =
340 ImmGetCompositionString(imm_context, GCS_CURSORPOS, NULL, 0);
341 if (cursor_position >= 0)
342 ime_composition_start_ = selection.cpMin - cursor_position;
343
344 const int composition_size =
345 ImmGetCompositionString(imm_context, GCS_COMPSTR, NULL, 0);
346 if (composition_size >= 0)
347 ime_composition_length_ = composition_size / sizeof(wchar_t);
348
349 ImmReleaseContext(m_hWnd, imm_context);
350 }
351 }
352
353 OnAfterPossibleChange();
354 return result;
355 }
356
357 LRESULT NativeTextfieldWin::OnImeEndComposition(UINT message,
358 WPARAM wparam,
359 LPARAM lparam) {
360 // Bug 11863: Korean IMEs send a WM_IME_ENDCOMPOSITION message without
361 // sending any WM_IME_COMPOSITION messages when a user deletes all
362 // composition characters, i.e. a composition string becomes empty. To handle
363 // this case, we need to update the find results when a composition is
364 // finished or canceled.
365 textfield_->SyncText();
366 if (textfield_->GetController())
367 textfield_->GetController()->ContentsChanged(textfield_, GetText());
368 return DefWindowProc(message, wparam, lparam);
369 }
370
371 void NativeTextfieldWin::OnKeyDown(TCHAR key, UINT repeat_count, UINT flags) {
372 // NOTE: Annoyingly, ctrl-alt-<key> generates WM_KEYDOWN rather than
373 // WM_SYSKEYDOWN, so we need to check (flags & KF_ALTDOWN) in various places
374 // in this function even with a WM_SYSKEYDOWN handler.
375
376 switch (key) {
377 case VK_RETURN:
378 // If we are multi-line, we want to let returns through so they start a
379 // new line.
380 if (textfield_->IsMultiLine())
381 break;
382 else
383 return;
384 // Hijacking Editing Commands
385 //
386 // We hijack the keyboard short-cuts for Cut, Copy, and Paste here so that
387 // they go through our clipboard routines. This allows us to be smarter
388 // about how we interact with the clipboard and avoid bugs in the
389 // CRichEditCtrl. If we didn't hijack here, the edit control would handle
390 // these internally with sending the WM_CUT, WM_COPY, or WM_PASTE messages.
391 //
392 // Cut: Shift-Delete and Ctrl-x are treated as cut. Ctrl-Shift-Delete and
393 // Ctrl-Shift-x are not treated as cut even though the underlying
394 // CRichTextEdit would treat them as such.
395 // Copy: Ctrl-c is treated as copy. Shift-Ctrl-c is not.
396 // Paste: Shift-Insert and Ctrl-v are tread as paste. Ctrl-Shift-Insert and
397 // Ctrl-Shift-v are not.
398 //
399 // This behavior matches most, but not all Windows programs, and largely
400 // conforms to what users expect.
401
402 case VK_DELETE:
403 case 'X':
404 if ((flags & KF_ALTDOWN) ||
405 (GetKeyState((key == 'X') ? VK_CONTROL : VK_SHIFT) >= 0))
406 break;
407 if (GetKeyState((key == 'X') ? VK_SHIFT : VK_CONTROL) >= 0) {
408 ScopedFreeze freeze(this, GetTextObjectModel());
409 OnBeforePossibleChange();
410 Cut();
411 OnAfterPossibleChange();
412 }
413 return;
414
415 case 'C':
416 if ((flags & KF_ALTDOWN) || (GetKeyState(VK_CONTROL) >= 0))
417 break;
418 if (GetKeyState(VK_SHIFT) >= 0)
419 Copy();
420 return;
421
422 case VK_INSERT:
423 case 'V':
424 if ((flags & KF_ALTDOWN) ||
425 (GetKeyState((key == 'V') ? VK_CONTROL : VK_SHIFT) >= 0))
426 break;
427 if (GetKeyState((key == 'V') ? VK_SHIFT : VK_CONTROL) >= 0) {
428 ScopedFreeze freeze(this, GetTextObjectModel());
429 OnBeforePossibleChange();
430 Paste();
431 OnAfterPossibleChange();
432 }
433 return;
434
435 case 0xbb: // Ctrl-'='. Triggers subscripting, even in plain text mode.
436 return;
437
438 case VK_PROCESSKEY:
439 // This key event is consumed by an IME.
440 // We ignore this event because an IME sends WM_IME_COMPOSITION messages
441 // when it updates the CRichEditCtrl text.
442 return;
443 }
444
445 // CRichEditCtrl changes its text on WM_KEYDOWN instead of WM_CHAR for many
446 // different keys (backspace, ctrl-v, ...), so we call this in both cases.
447 HandleKeystroke(GetCurrentMessage()->message, key, repeat_count, flags);
448 }
449
450 void NativeTextfieldWin::OnLButtonDblClk(UINT keys, const CPoint& point) {
451 // Save the double click info for later triple-click detection.
452 tracking_double_click_ = true;
453 double_click_point_ = point;
454 double_click_time_ = GetCurrentMessage()->time;
455
456 ScopedFreeze freeze(this, GetTextObjectModel());
457 OnBeforePossibleChange();
458 DefWindowProc(WM_LBUTTONDBLCLK, keys,
459 MAKELPARAM(ClipXCoordToVisibleText(point.x, false), point.y));
460 OnAfterPossibleChange();
461 }
462
463 void NativeTextfieldWin::OnLButtonDown(UINT keys, const CPoint& point) {
464 // Check for triple click, then reset tracker. Should be safe to subtract
465 // double_click_time_ from the current message's time even if the timer has
466 // wrapped in between.
467 const bool is_triple_click = tracking_double_click_ &&
468 win_util::IsDoubleClick(double_click_point_, point,
469 GetCurrentMessage()->time - double_click_time_);
470 tracking_double_click_ = false;
471
472 ScopedFreeze freeze(this, GetTextObjectModel());
473 OnBeforePossibleChange();
474 DefWindowProc(WM_LBUTTONDOWN, keys,
475 MAKELPARAM(ClipXCoordToVisibleText(point.x, is_triple_click),
476 point.y));
477 OnAfterPossibleChange();
478 }
479
480 void NativeTextfieldWin::OnLButtonUp(UINT keys, const CPoint& point) {
481 ScopedFreeze freeze(this, GetTextObjectModel());
482 OnBeforePossibleChange();
483 DefWindowProc(WM_LBUTTONUP, keys,
484 MAKELPARAM(ClipXCoordToVisibleText(point.x, false), point.y));
485 OnAfterPossibleChange();
486 }
487
488 void NativeTextfieldWin::OnMouseLeave() {
489 SetContainsMouse(false);
490 }
491
492 LRESULT NativeTextfieldWin::OnMouseWheel(UINT message, WPARAM w_param,
493 LPARAM l_param) {
494 // Reroute the mouse-wheel to the window under the mouse pointer if
495 // applicable.
496 if (views::RerouteMouseWheel(m_hWnd, w_param, l_param))
497 return 0;
498 return DefWindowProc(message, w_param, l_param);;
499 }
500
501 void NativeTextfieldWin::OnMouseMove(UINT keys, const CPoint& point) {
502 SetContainsMouse(true);
503 // Clamp the selection to the visible text so the user can't drag to select
504 // the "phantom newline". In theory we could achieve this by clipping the X
505 // coordinate, but in practice the edit seems to behave nondeterministically
506 // with similar sequences of clipped input coordinates fed to it. Maybe it's
507 // reading the mouse cursor position directly?
508 //
509 // This solution has a minor visual flaw, however: if there's a visible
510 // cursor at the edge of the text (only true when there's no selection),
511 // dragging the mouse around outside that edge repaints the cursor on every
512 // WM_MOUSEMOVE instead of allowing it to blink normally. To fix this, we
513 // special-case this exact case and discard the WM_MOUSEMOVE messages instead
514 // of passing them along.
515 //
516 // But even this solution has a flaw! (Argh.) In the case where the user
517 // has a selection that starts at the edge of the edit, and proceeds to the
518 // middle of the edit, and the user is dragging back past the start edge to
519 // remove the selection, there's a redraw problem where the change between
520 // having the last few bits of text still selected and having nothing
521 // selected can be slow to repaint (which feels noticeably strange). This
522 // occurs if you only let the edit receive a single WM_MOUSEMOVE past the
523 // edge of the text. I think on each WM_MOUSEMOVE the edit is repainting its
524 // previous state, then updating its internal variables to the new state but
525 // not repainting. To fix this, we allow one more WM_MOUSEMOVE through after
526 // the selection has supposedly been shrunk to nothing; this makes the edit
527 // redraw the selection quickly so it feels smooth.
528 CHARRANGE selection;
529 GetSel(selection);
530 const bool possibly_can_discard_mousemove =
531 (selection.cpMin == selection.cpMax) &&
532 (((selection.cpMin == 0) &&
533 (ClipXCoordToVisibleText(point.x, false) > point.x)) ||
534 ((selection.cpMin == GetTextLength()) &&
535 (ClipXCoordToVisibleText(point.x, false) < point.x)));
536 if (!can_discard_mousemove_ || !possibly_can_discard_mousemove) {
537 can_discard_mousemove_ = possibly_can_discard_mousemove;
538 ScopedFreeze freeze(this, GetTextObjectModel());
539 OnBeforePossibleChange();
540 // Force the Y coordinate to the center of the clip rect. The edit
541 // behaves strangely when the cursor is dragged vertically: if the cursor
542 // is in the middle of the text, drags inside the clip rect do nothing,
543 // and drags outside the clip rect act as if the cursor jumped to the
544 // left edge of the text. When the cursor is at the right edge, drags of
545 // just a few pixels vertically end up selecting the "phantom newline"...
546 // sometimes.
547 RECT r;
548 GetRect(&r);
549 DefWindowProc(WM_MOUSEMOVE, keys,
550 MAKELPARAM(point.x, (r.bottom - r.top) / 2));
551 OnAfterPossibleChange();
552 }
553 }
554
555 int NativeTextfieldWin::OnNCCalcSize(BOOL w_param, LPARAM l_param) {
556 content_insets_.Set(0, 0, 0, 0);
557 textfield_->CalculateInsets(&content_insets_);
558 if (w_param) {
559 NCCALCSIZE_PARAMS* nc_params =
560 reinterpret_cast<NCCALCSIZE_PARAMS*>(l_param);
561 nc_params->rgrc[0].left += content_insets_.left();
562 nc_params->rgrc[0].right -= content_insets_.right();
563 nc_params->rgrc[0].top += content_insets_.top();
564 nc_params->rgrc[0].bottom -= content_insets_.bottom();
565 } else {
566 RECT* rect = reinterpret_cast<RECT*>(l_param);
567 rect->left += content_insets_.left();
568 rect->right -= content_insets_.right();
569 rect->top += content_insets_.top();
570 rect->bottom -= content_insets_.bottom();
571 }
572 return 0;
573 }
574
575 void NativeTextfieldWin::OnNCPaint(HRGN region) {
576 if (!textfield_->draw_border())
577 return;
578
579 HDC hdc = GetWindowDC();
580
581 CRect window_rect;
582 GetWindowRect(&window_rect);
583 // Convert to be relative to 0x0.
584 window_rect.MoveToXY(0, 0);
585
586 ExcludeClipRect(hdc,
587 window_rect.left + content_insets_.left(),
588 window_rect.top + content_insets_.top(),
589 window_rect.right - content_insets_.right(),
590 window_rect.bottom - content_insets_.bottom());
591
592 HBRUSH brush = CreateSolidBrush(bg_color_);
593 FillRect(hdc, &window_rect, brush);
594 DeleteObject(brush);
595
596 int part;
597 int state;
598
599 if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA) {
600 part = EP_EDITTEXT;
601
602 if (!textfield_->IsEnabled())
603 state = ETS_DISABLED;
604 else if (textfield_->read_only())
605 state = ETS_READONLY;
606 else if (!contains_mouse_)
607 state = ETS_NORMAL;
608 else
609 state = ETS_HOT;
610 } else {
611 part = EP_EDITBORDER_HVSCROLL;
612
613 if (!textfield_->IsEnabled())
614 state = EPSHV_DISABLED;
615 else if (GetFocus() == m_hWnd)
616 state = EPSHV_FOCUSED;
617 else if (contains_mouse_)
618 state = EPSHV_HOT;
619 else
620 state = EPSHV_NORMAL;
621 // Vista doesn't appear to have a unique state for readonly.
622 }
623
624 int classic_state =
625 (!textfield_->IsEnabled() || textfield_->read_only()) ? DFCS_INACTIVE : 0;
626
627 gfx::NativeTheme::instance()->PaintTextField(hdc, part, state, classic_state,
628 &window_rect, bg_color_, false,
629 true);
630
631 // NOTE: I tried checking the transparent property of the theme and invoking
632 // drawParentBackground, but it didn't seem to make a difference.
633
634 ReleaseDC(hdc);
635 }
636
637 void NativeTextfieldWin::OnNonLButtonDown(UINT keys, const CPoint& point) {
638 // Interestingly, the edit doesn't seem to cancel triple clicking when the
639 // x-buttons (which usually means "thumb buttons") are pressed, so we only
640 // call this for M and R down.
641 tracking_double_click_ = false;
642 SetMsgHandled(false);
643 }
644
645 void NativeTextfieldWin::OnPaste() {
646 if (textfield_->read_only() || !ViewsDelegate::views_delegate)
647 return;
648
649 Clipboard* clipboard = ViewsDelegate::views_delegate->GetClipboard();
650 if (!clipboard->IsFormatAvailable(Clipboard::GetPlainTextWFormatType()))
651 return;
652
653 std::wstring clipboard_str;
654 clipboard->ReadText(&clipboard_str);
655 if (!clipboard_str.empty()) {
656 std::wstring collapsed(CollapseWhitespace(clipboard_str, false));
657 if (textfield_->style() & Textfield::STYLE_LOWERCASE)
658 collapsed = l10n_util::ToLower(collapsed);
659 // Force a Paste operation to trigger OnContentsChanged, even if identical
660 // contents are pasted into the text box.
661 text_before_change_.clear();
662 ReplaceSel(collapsed.c_str(), true);
663 }
664 }
665
666 void NativeTextfieldWin::OnSysChar(TCHAR ch, UINT repeat_count, UINT flags) {
667 // Nearly all alt-<xxx> combos result in beeping rather than doing something
668 // useful, so we discard most. Exceptions:
669 // * ctrl-alt-<xxx>, which is sometimes important, generates WM_CHAR instead
670 // of WM_SYSCHAR, so it doesn't need to be handled here.
671 // * alt-space gets translated by the default WM_SYSCHAR handler to a
672 // WM_SYSCOMMAND to open the application context menu, so we need to allow
673 // it through.
674 if (ch == VK_SPACE)
675 SetMsgHandled(false);
676 }
677
678 void NativeTextfieldWin::HandleKeystroke(UINT message,
679 TCHAR key,
680 UINT repeat_count,
681 UINT flags) {
682 ScopedFreeze freeze(this, GetTextObjectModel());
683
684 Textfield::Controller* controller = textfield_->GetController();
685 bool handled = false;
686 if (controller) {
687 handled = controller->HandleKeystroke(textfield_,
688 Textfield::Keystroke(message, key, repeat_count, flags));
689 }
690
691 if (!handled) {
692 OnBeforePossibleChange();
693 DefWindowProc(message, key, MAKELPARAM(repeat_count, flags));
694 OnAfterPossibleChange();
695 }
696 }
697
698 void NativeTextfieldWin::OnBeforePossibleChange() {
699 // Record our state.
700 text_before_change_ = GetText();
701 }
702
703 void NativeTextfieldWin::OnAfterPossibleChange() {
704 // Prevent the user from selecting the "phantom newline" at the end of the
705 // edit. If they try, we just silently move the end of the selection back to
706 // the end of the real text.
707 CHARRANGE new_sel;
708 GetSel(new_sel);
709 const int length = GetTextLength();
710 if (new_sel.cpMax > length) {
711 new_sel.cpMax = length;
712 if (new_sel.cpMin > length)
713 new_sel.cpMin = length;
714 SetSel(new_sel);
715 }
716
717 std::wstring new_text(GetText());
718 if (new_text != text_before_change_) {
719 if (ime_discard_composition_ && ime_composition_start_ >= 0 &&
720 ime_composition_length_ > 0) {
721 // A string retrieved with a GetText() call contains a string being
722 // composed by an IME. We remove the composition string from this search
723 // string.
724 new_text.erase(ime_composition_start_, ime_composition_length_);
725 ime_composition_start_ = 0;
726 ime_composition_length_ = 0;
727 if (new_text.empty())
728 return;
729 }
730 textfield_->SyncText();
731 if (textfield_->GetController())
732 textfield_->GetController()->ContentsChanged(textfield_, new_text);
733 }
734 }
735
736 LONG NativeTextfieldWin::ClipXCoordToVisibleText(LONG x,
737 bool is_triple_click) const {
738 // Clip the X coordinate to the left edge of the text. Careful:
739 // PosFromChar(0) may return a negative X coordinate if the beginning of the
740 // text has scrolled off the edit, so don't go past the clip rect's edge.
741 PARAFORMAT2 pf2;
742 GetParaFormat(pf2);
743 // Calculation of the clipped coordinate is more complicated if the paragraph
744 // layout is RTL layout, or if there is RTL characters inside the LTR layout
745 // paragraph.
746 bool ltr_text_in_ltr_layout = true;
747 if ((pf2.wEffects & PFE_RTLPARA) ||
748 l10n_util::StringContainsStrongRTLChars(GetText())) {
749 ltr_text_in_ltr_layout = false;
750 }
751 const int length = GetTextLength();
752 RECT r;
753 GetRect(&r);
754 // The values returned by PosFromChar() seem to refer always
755 // to the left edge of the character's bounding box.
756 const LONG first_position_x = PosFromChar(0).x;
757 LONG min_x = first_position_x;
758 if (!ltr_text_in_ltr_layout) {
759 for (int i = 1; i < length; ++i)
760 min_x = std::min(min_x, PosFromChar(i).x);
761 }
762 const LONG left_bound = std::max(r.left, min_x);
763
764 // PosFromChar(length) is a phantom character past the end of the text. It is
765 // not necessarily a right bound; in RTL controls it may be a left bound. So
766 // treat it as a right bound only if it is to the right of the first
767 // character.
768 LONG right_bound = r.right;
769 LONG end_position_x = PosFromChar(length).x;
770 if (end_position_x >= first_position_x) {
771 right_bound = std::min(right_bound, end_position_x); // LTR case.
772 }
773 // For trailing characters that are 2 pixels wide of less (like "l" in some
774 // fonts), we have a problem:
775 // * Clicks on any pixel within the character will place the cursor before
776 // the character.
777 // * Clicks on the pixel just after the character will not allow triple-
778 // click to work properly (true for any last character width).
779 // So, we move to the last pixel of the character when this is a
780 // triple-click, and moving to one past the last pixel in all other
781 // scenarios. This way, all clicks that can move the cursor will place it at
782 // the end of the text, but triple-click will still work.
783 if (x < left_bound) {
784 return (is_triple_click && ltr_text_in_ltr_layout) ? left_bound - 1 :
785 left_bound;
786 }
787 if ((length == 0) || (x < right_bound))
788 return x;
789 return is_triple_click ? (right_bound - 1) : right_bound;
790 }
791
792 void NativeTextfieldWin::SetContainsMouse(bool contains_mouse) {
793 if (contains_mouse == contains_mouse_)
794 return;
795
796 contains_mouse_ = contains_mouse;
797
798 if (!textfield_->draw_border())
799 return;
800
801 if (contains_mouse_) {
802 // Register for notification when the mouse leaves. Need to do this so
803 // that we can reset contains mouse properly.
804 TRACKMOUSEEVENT tme;
805 tme.cbSize = sizeof(tme);
806 tme.dwFlags = TME_LEAVE;
807 tme.hwndTrack = m_hWnd;
808 tme.dwHoverTime = 0;
809 TrackMouseEvent(&tme);
810 }
811 RedrawWindow(NULL, NULL, RDW_INVALIDATE | RDW_FRAME);
812 }
813
814 ITextDocument* NativeTextfieldWin::GetTextObjectModel() const {
815 if (!text_object_model_) {
816 CComPtr<IRichEditOle> ole_interface;
817 ole_interface.Attach(GetOleInterface());
818 text_object_model_ = ole_interface;
819 }
820 return text_object_model_;
821 }
822
823 ////////////////////////////////////////////////////////////////////////////////
824 // NativeTextfieldWrapper, public:
825
826 // static
827 NativeTextfieldWrapper* NativeTextfieldWrapper::CreateWrapper(
828 Textfield* field) {
829 return new NativeTextfieldWin(field);
830 }
831
832 } // namespace views
OLDNEW
« no previous file with comments | « views/controls/textfield/native_textfield_win.h ('k') | views/controls/textfield/native_textfield_wrapper.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698