1 // Copyright (c) 2013 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.
5 #include "ui/views/touchui/touch_selection_controller_impl.h"
7 #include "base/time/time.h"
8 #include "grit/ui_resources.h"
9 #include "grit/ui_strings.h"
10 #include "ui/aura/client/cursor_client.h"
11 #include "ui/aura/env.h"
12 #include "ui/base/resource/resource_bundle.h"
13 #include "ui/gfx/canvas.h"
14 #include "ui/gfx/image/image.h"
15 #include "ui/gfx/path.h"
16 #include "ui/gfx/rect.h"
17 #include "ui/gfx/screen.h"
18 #include "ui/gfx/size.h"
19 #include "ui/views/widget/widget.h"
20 #include "ui/wm/core/masked_window_targeter.h"
21 #include "ui/wm/core/shadow_types.h"
22 #include "ui/wm/core/window_animations.h"
26 // Constants defining the visual attributes of selection handles
27 const int kSelectionHandleLineWidth = 1;
28 const SkColor kSelectionHandleLineColor =
29 SkColorSetRGB(0x42, 0x81, 0xf4);
31 // When a handle is dragged, the drag position reported to the client view is
32 // offset vertically to represent the cursor position. This constant specifies
33 // the offset in pixels above the "O" (see pic below). This is required because
34 // say if this is zero, that means the drag position we report is the point
35 // right above the "O" or the bottom most point of the cursor "|". In that case,
36 // a vertical movement of even one pixel will make the handle jump to the line
37 // below it. So when the user just starts dragging, the handle will jump to the
38 // next line if the user makes any vertical movement. It is correct but
39 // looks/feels weird. So we have this non-zero offset to prevent this jumping.
41 // Editing handle widget showing the difference between the position of the
42 // ET_GESTURE_SCROLL_UPDATE event and the drag position reported to the client:
44 // | |<-|---- Drag position reported to client
46 // Vertical Padding __| | <-|---- ET_GESTURE_SCROLL_UPDATE position
47 // |_ |_____|<--- Editing handle widget
53 const int kSelectionHandleVerticalDragOffset = 5;
55 // Padding around the selection handle defining the area that will be included
56 // in the touch target to make dragging the handle easier (see pic above).
57 const int kSelectionHandleHorizPadding = 10;
58 const int kSelectionHandleVertPadding = 20;
60 const int kContextMenuTimoutMs = 200;
62 const int kSelectionHandleQuickFadeDurationMs = 50;
64 // Minimum height for selection handle bar. If the bar height is going to be
65 // less than this value, handle will not be shown.
66 const int kSelectionHandleBarMinHeight = 5;
67 // Maximum amount that selection handle bar can stick out of client view's
69 const int kSelectionHandleBarBottomAllowance = 3;
71 // Creates a widget to host SelectionHandleView.
72 views::Widget* CreateTouchSelectionPopupWidget(
73 gfx::NativeView context,
74 views::WidgetDelegate* widget_delegate) {
75 views::Widget* widget = new views::Widget;
76 views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP);
77 params.can_activate = false;
78 params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;
79 params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
80 params.parent = context;
81 params.delegate = widget_delegate;
83 SetShadowType(widget->GetNativeView(), wm::SHADOW_TYPE_NONE);
87 gfx::Image* GetHandleImage() {
88 static gfx::Image* handle_image = NULL;
90 handle_image = &ui::ResourceBundle::GetSharedInstance().GetImageNamed(
91 IDR_TEXT_SELECTION_HANDLE);
96 gfx::Size GetHandleImageSize() {
97 return GetHandleImage()->Size();
100 // Cannot use gfx::UnionRect since it does not work for empty rects.
101 gfx::Rect Union(const gfx::Rect& r1, const gfx::Rect& r2) {
102 int rx = std::min(r1.x(), r2.x());
103 int ry = std::min(r1.y(), r2.y());
104 int rr = std::max(r1.right(), r2.right());
105 int rb = std::max(r1.bottom(), r2.bottom());
107 return gfx::Rect(rx, ry, rr - rx, rb - ry);
110 // Convenience methods to convert a |rect| from screen to the |client|'s
111 // coordinate system and vice versa.
112 // Note that this is not quite correct because it does not take into account
113 // transforms such as rotation and scaling. This should be in TouchEditable.
114 // TODO(varunjain): Fix this.
115 gfx::Rect ConvertFromScreen(ui::TouchEditable* client, const gfx::Rect& rect) {
116 gfx::Point origin = rect.origin();
117 client->ConvertPointFromScreen(&origin);
118 return gfx::Rect(origin, rect.size());
120 gfx::Rect ConvertToScreen(ui::TouchEditable* client, const gfx::Rect& rect) {
121 gfx::Point origin = rect.origin();
122 client->ConvertPointToScreen(&origin);
123 return gfx::Rect(origin, rect.size());
130 typedef TouchSelectionControllerImpl::EditingHandleView EditingHandleView;
132 class TouchHandleWindowTargeter : public wm::MaskedWindowTargeter {
134 TouchHandleWindowTargeter(aura::Window* window,
135 EditingHandleView* handle_view);
137 virtual ~TouchHandleWindowTargeter() {}
140 // wm::MaskedWindowTargeter:
141 virtual bool GetHitTestMask(aura::Window* window,
142 gfx::Path* mask) const OVERRIDE;
144 EditingHandleView* handle_view_;
146 DISALLOW_COPY_AND_ASSIGN(TouchHandleWindowTargeter);
149 // A View that displays the text selection handle.
150 class TouchSelectionControllerImpl::EditingHandleView
151 : public views::WidgetDelegateView {
153 EditingHandleView(TouchSelectionControllerImpl* controller,
154 gfx::NativeView context)
155 : controller_(controller),
157 draw_invisible_(false) {
158 widget_.reset(CreateTouchSelectionPopupWidget(context, this));
159 widget_->SetContentsView(this);
161 aura::Window* window = widget_->GetNativeWindow();
162 window->SetEventTargeter(scoped_ptr<ui::EventTargeter>(
163 new TouchHandleWindowTargeter(window, this)));
165 // We are owned by the TouchSelectionController.
166 set_owned_by_client();
169 virtual ~EditingHandleView() {
170 SetWidgetVisible(false, false);
173 // Overridden from views::WidgetDelegateView:
174 virtual bool WidgetHasHitTestMask() const OVERRIDE {
178 virtual void GetWidgetHitTestMask(gfx::Path* mask) const OVERRIDE {
179 gfx::Size image_size = GetHandleImageSize();
180 mask->addRect(SkIntToScalar(0), SkIntToScalar(selection_rect_.height()),
181 SkIntToScalar(image_size.width()) + 2 * kSelectionHandleHorizPadding,
182 SkIntToScalar(selection_rect_.height() + image_size.height() +
183 kSelectionHandleVertPadding));
186 virtual void DeleteDelegate() OVERRIDE {
187 // We are owned and deleted by TouchSelectionController.
190 // Overridden from views::View:
191 virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {
194 gfx::Size image_size = GetHandleImageSize();
195 int cursor_pos_x = image_size.width() / 2 - kSelectionHandleLineWidth +
196 kSelectionHandleHorizPadding;
198 // Draw the cursor line.
200 gfx::Rect(cursor_pos_x, 0,
201 2 * kSelectionHandleLineWidth + 1, selection_rect_.height()),
202 kSelectionHandleLineColor);
204 // Draw the handle image.
205 canvas->DrawImageInt(*GetHandleImage()->ToImageSkia(),
206 kSelectionHandleHorizPadding, selection_rect_.height());
209 virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE {
211 switch (event->type()) {
212 case ui::ET_GESTURE_SCROLL_BEGIN:
213 widget_->SetCapture(this);
214 controller_->SetDraggingHandle(this);
215 drag_offset_ = event->y() - selection_rect_.height() +
216 kSelectionHandleVerticalDragOffset;
218 case ui::ET_GESTURE_SCROLL_UPDATE: {
219 gfx::Point drag_pos(event->location().x(),
220 event->location().y() - drag_offset_);
221 controller_->SelectionHandleDragged(drag_pos);
224 case ui::ET_GESTURE_SCROLL_END:
225 case ui::ET_SCROLL_FLING_START:
226 widget_->ReleaseCapture();
227 controller_->SetDraggingHandle(NULL);
234 virtual gfx::Size GetPreferredSize() OVERRIDE {
235 gfx::Size image_size = GetHandleImageSize();
236 return gfx::Size(image_size.width() + 2 * kSelectionHandleHorizPadding,
237 image_size.height() + selection_rect_.height() +
238 kSelectionHandleVertPadding);
241 bool IsWidgetVisible() const {
242 return widget_->IsVisible();
245 void SetWidgetVisible(bool visible, bool quick) {
246 if (widget_->IsVisible() == visible)
248 wm::SetWindowVisibilityAnimationDuration(
249 widget_->GetNativeView(),
250 base::TimeDelta::FromMilliseconds(
251 quick ? kSelectionHandleQuickFadeDurationMs : 0));
258 void SetSelectionRectInScreen(const gfx::Rect& rect) {
259 gfx::Size image_size = GetHandleImageSize();
260 selection_rect_ = rect;
261 gfx::Rect widget_bounds(
262 rect.x() - image_size.width() / 2 - kSelectionHandleHorizPadding,
264 image_size.width() + 2 * kSelectionHandleHorizPadding,
265 rect.height() + image_size.height() + kSelectionHandleVertPadding);
266 widget_->SetBounds(widget_bounds);
269 gfx::Point GetScreenPosition() {
270 return widget_->GetClientAreaBoundsInScreen().origin();
273 void SetDrawInvisible(bool draw_invisible) {
274 if (draw_invisible_ == draw_invisible)
276 draw_invisible_ = draw_invisible;
280 const gfx::Rect& selection_rect() const { return selection_rect_; }
283 scoped_ptr<Widget> widget_;
284 TouchSelectionControllerImpl* controller_;
285 gfx::Rect selection_rect_;
287 // Vertical offset between the scroll event position and the drag position
288 // reported to the client view (see the ASCII figure at the top of the file
289 // and its description for more details).
292 // If set to true, the handle will not draw anything, hence providing an empty
293 // widget. We need this because we may want to stop showing the handle while
294 // it is being dragged. Since it is being dragged, we cannot destroy the
296 bool draw_invisible_;
298 DISALLOW_COPY_AND_ASSIGN(EditingHandleView);
301 TouchHandleWindowTargeter::TouchHandleWindowTargeter(
302 aura::Window* window,
303 EditingHandleView* handle_view)
304 : wm::MaskedWindowTargeter(window),
305 handle_view_(handle_view) {
308 bool TouchHandleWindowTargeter::GetHitTestMask(aura::Window* window,
309 gfx::Path* mask) const {
310 const gfx::Rect& selection_rect = handle_view_->selection_rect();
311 gfx::Size image_size = GetHandleImageSize();
312 mask->addRect(SkIntToScalar(0), SkIntToScalar(selection_rect.height()),
313 SkIntToScalar(image_size.width()) + 2 * kSelectionHandleHorizPadding,
314 SkIntToScalar(selection_rect.height() + image_size.height() +
315 kSelectionHandleVertPadding));
319 TouchSelectionControllerImpl::TouchSelectionControllerImpl(
320 ui::TouchEditable* client_view)
321 : client_view_(client_view),
322 client_widget_(NULL),
323 selection_handle_1_(new EditingHandleView(this,
324 client_view->GetNativeView())),
325 selection_handle_2_(new EditingHandleView(this,
326 client_view->GetNativeView())),
327 cursor_handle_(new EditingHandleView(this,
328 client_view->GetNativeView())),
330 dragging_handle_(NULL) {
331 client_widget_ = Widget::GetTopLevelWidgetForNativeView(
332 client_view_->GetNativeView());
334 client_widget_->AddObserver(this);
335 aura::Env::GetInstance()->AddPreTargetHandler(this);
338 TouchSelectionControllerImpl::~TouchSelectionControllerImpl() {
340 aura::Env::GetInstance()->RemovePreTargetHandler(this);
342 client_widget_->RemoveObserver(this);
345 void TouchSelectionControllerImpl::SelectionChanged() {
347 client_view_->GetSelectionEndPoints(&r1, &r2);
348 gfx::Rect screen_rect_1 = ConvertToScreen(client_view_, r1);
349 gfx::Rect screen_rect_2 = ConvertToScreen(client_view_, r2);
350 gfx::Rect client_bounds = client_view_->GetBounds();
351 if (r1.y() < client_bounds.y())
352 r1.Inset(0, client_bounds.y() - r1.y(), 0, 0);
353 if (r2.y() < client_bounds.y())
354 r2.Inset(0, client_bounds.y() - r2.y(), 0, 0);
355 gfx::Rect screen_rect_1_clipped = ConvertToScreen(client_view_, r1);
356 gfx::Rect screen_rect_2_clipped = ConvertToScreen(client_view_, r2);
357 if (screen_rect_1_clipped == selection_end_point_1_clipped_ &&
358 screen_rect_2_clipped == selection_end_point_2_clipped_)
361 selection_end_point_1_ = screen_rect_1;
362 selection_end_point_2_ = screen_rect_2;
363 selection_end_point_1_clipped_ = screen_rect_1_clipped;
364 selection_end_point_2_clipped_ = screen_rect_2_clipped;
366 if (client_view_->DrawsHandles()) {
370 if (dragging_handle_) {
371 // We need to reposition only the selection handle that is being dragged.
372 // The other handle stays the same. Also, the selection handle being dragged
373 // will always be at the end of selection, while the other handle will be at
375 // If the new location of this handle is out of client view, its widget
376 // should not get hidden, since it should still receive touch events.
377 // Hence, we are not using |SetHandleSelectionRect()| method here.
378 dragging_handle_->SetSelectionRectInScreen(screen_rect_2_clipped);
380 // Temporary fix for selection handle going outside a window. On a webpage,
381 // the page should scroll if the selection handle is dragged outside the
382 // window. That does not happen currently. So we just hide the handle for
384 // TODO(varunjain): Fix this: crbug.com/269003
385 dragging_handle_->SetDrawInvisible(!ShouldShowHandleFor(r2));
387 if (dragging_handle_ != cursor_handle_.get()) {
388 // The non-dragging-handle might have recently become visible.
389 EditingHandleView* non_dragging_handle = selection_handle_1_.get();
390 if (dragging_handle_ == selection_handle_1_) {
391 non_dragging_handle = selection_handle_2_.get();
392 // if handle 1 is being dragged, it is corresponding to the end of
393 // selection and the other handle to the start of selection.
394 selection_end_point_1_ = screen_rect_2;
395 selection_end_point_2_ = screen_rect_1;
396 selection_end_point_1_clipped_ = screen_rect_2_clipped;
397 selection_end_point_2_clipped_ = screen_rect_1_clipped;
399 SetHandleSelectionRect(non_dragging_handle, r1, screen_rect_1_clipped);
404 // Check if there is any selection at all.
405 if (screen_rect_1.origin() == screen_rect_2.origin()) {
406 selection_handle_1_->SetWidgetVisible(false, false);
407 selection_handle_2_->SetWidgetVisible(false, false);
408 SetHandleSelectionRect(cursor_handle_.get(), r1, screen_rect_1_clipped);
412 cursor_handle_->SetWidgetVisible(false, false);
413 SetHandleSelectionRect(selection_handle_1_.get(), r1,
414 screen_rect_1_clipped);
415 SetHandleSelectionRect(selection_handle_2_.get(), r2,
416 screen_rect_2_clipped);
420 bool TouchSelectionControllerImpl::IsHandleDragInProgress() {
421 return !!dragging_handle_;
424 void TouchSelectionControllerImpl::HideHandles(bool quick) {
425 selection_handle_1_->SetWidgetVisible(false, quick);
426 selection_handle_2_->SetWidgetVisible(false, quick);
427 cursor_handle_->SetWidgetVisible(false, quick);
430 void TouchSelectionControllerImpl::SetDraggingHandle(
431 EditingHandleView* handle) {
432 dragging_handle_ = handle;
433 if (dragging_handle_)
436 StartContextMenuTimer();
439 void TouchSelectionControllerImpl::SelectionHandleDragged(
440 const gfx::Point& drag_pos) {
441 // We do not want to show the context menu while dragging.
444 DCHECK(dragging_handle_);
445 gfx::Point drag_pos_in_client = drag_pos;
446 ConvertPointToClientView(dragging_handle_, &drag_pos_in_client);
448 if (dragging_handle_ == cursor_handle_.get()) {
449 client_view_->MoveCaretTo(drag_pos_in_client);
453 // Find the stationary selection handle.
454 gfx::Rect fixed_handle_rect = selection_end_point_1_;
455 if (selection_handle_1_ == dragging_handle_)
456 fixed_handle_rect = selection_end_point_2_;
458 // Find selection end points in client_view's coordinate system.
459 gfx::Point p2 = fixed_handle_rect.origin();
460 p2.Offset(0, fixed_handle_rect.height() / 2);
461 client_view_->ConvertPointFromScreen(&p2);
463 // Instruct client_view to select the region between p1 and p2. The position
464 // of |fixed_handle| is the start and that of |dragging_handle| is the end
466 client_view_->SelectRect(p2, drag_pos_in_client);
469 void TouchSelectionControllerImpl::ConvertPointToClientView(
470 EditingHandleView* source, gfx::Point* point) {
471 View::ConvertPointToScreen(source, point);
472 client_view_->ConvertPointFromScreen(point);
475 void TouchSelectionControllerImpl::SetHandleSelectionRect(
476 EditingHandleView* handle,
477 const gfx::Rect& rect,
478 const gfx::Rect& rect_in_screen) {
479 handle->SetWidgetVisible(ShouldShowHandleFor(rect), false);
480 if (handle->IsWidgetVisible())
481 handle->SetSelectionRectInScreen(rect_in_screen);
484 bool TouchSelectionControllerImpl::ShouldShowHandleFor(
485 const gfx::Rect& rect) const {
486 if (rect.height() < kSelectionHandleBarMinHeight)
488 gfx::Rect bounds = client_view_->GetBounds();
489 bounds.Inset(0, 0, 0, -kSelectionHandleBarBottomAllowance);
490 return bounds.Contains(rect);
493 bool TouchSelectionControllerImpl::IsCommandIdEnabled(int command_id) const {
494 return client_view_->IsCommandIdEnabled(command_id);
497 void TouchSelectionControllerImpl::ExecuteCommand(int command_id,
500 client_view_->ExecuteCommand(command_id, event_flags);
503 void TouchSelectionControllerImpl::OpenContextMenu() {
504 // Context menu should appear centered on top of the selected region.
505 const gfx::Rect rect = context_menu_->GetAnchorRect();
506 const gfx::Point anchor(rect.CenterPoint().x(), rect.y());
508 client_view_->OpenContextMenu(anchor);
511 void TouchSelectionControllerImpl::OnMenuClosed(TouchEditingMenuView* menu) {
512 if (menu == context_menu_)
513 context_menu_ = NULL;
516 void TouchSelectionControllerImpl::OnWidgetClosing(Widget* widget) {
517 DCHECK_EQ(client_widget_, widget);
518 client_widget_ = NULL;
521 void TouchSelectionControllerImpl::OnWidgetBoundsChanged(
523 const gfx::Rect& new_bounds) {
524 DCHECK_EQ(client_widget_, widget);
529 void TouchSelectionControllerImpl::OnKeyEvent(ui::KeyEvent* event) {
530 client_view_->DestroyTouchSelection();
533 void TouchSelectionControllerImpl::OnMouseEvent(ui::MouseEvent* event) {
534 aura::client::CursorClient* cursor_client = aura::client::GetCursorClient(
535 client_view_->GetNativeView()->GetRootWindow());
536 if (!cursor_client || cursor_client->IsMouseEventsEnabled())
537 client_view_->DestroyTouchSelection();
540 void TouchSelectionControllerImpl::OnScrollEvent(ui::ScrollEvent* event) {
541 client_view_->DestroyTouchSelection();
544 void TouchSelectionControllerImpl::ContextMenuTimerFired() {
545 // Get selection end points in client_view's space.
546 gfx::Rect end_rect_1_in_screen;
547 gfx::Rect end_rect_2_in_screen;
548 if (cursor_handle_->IsWidgetVisible()) {
549 end_rect_1_in_screen = selection_end_point_1_clipped_;
550 end_rect_2_in_screen = end_rect_1_in_screen;
552 end_rect_1_in_screen = selection_end_point_1_clipped_;
553 end_rect_2_in_screen = selection_end_point_2_clipped_;
556 // Convert from screen to client.
557 gfx::Rect end_rect_1(ConvertFromScreen(client_view_, end_rect_1_in_screen));
558 gfx::Rect end_rect_2(ConvertFromScreen(client_view_, end_rect_2_in_screen));
560 // if selection is completely inside the view, we display the context menu
561 // in the middle of the end points on the top. Else, we show it above the
562 // visible handle. If no handle is visible, we do not show the menu.
563 gfx::Rect menu_anchor;
564 if (ShouldShowHandleFor(end_rect_1) &&
565 ShouldShowHandleFor(end_rect_2))
566 menu_anchor = Union(end_rect_1_in_screen,end_rect_2_in_screen);
567 else if (ShouldShowHandleFor(end_rect_1))
568 menu_anchor = end_rect_1_in_screen;
569 else if (ShouldShowHandleFor(end_rect_2))
570 menu_anchor = end_rect_2_in_screen;
574 DCHECK(!context_menu_);
575 context_menu_ = TouchEditingMenuView::Create(this, menu_anchor,
576 GetHandleImageSize(),
577 client_view_->GetNativeView());
580 void TouchSelectionControllerImpl::StartContextMenuTimer() {
581 if (context_menu_timer_.IsRunning())
583 context_menu_timer_.Start(
585 base::TimeDelta::FromMilliseconds(kContextMenuTimoutMs),
587 &TouchSelectionControllerImpl::ContextMenuTimerFired);
590 void TouchSelectionControllerImpl::UpdateContextMenu() {
591 // Hide context menu to be shown when the timer fires.
593 StartContextMenuTimer();
596 void TouchSelectionControllerImpl::HideContextMenu() {
598 context_menu_->Close();
599 context_menu_ = NULL;
600 context_menu_timer_.Stop();
603 gfx::NativeView TouchSelectionControllerImpl::GetCursorHandleNativeView() {
604 return cursor_handle_->GetWidget()->GetNativeView();
607 gfx::Point TouchSelectionControllerImpl::GetSelectionHandle1Position() {
608 return selection_handle_1_->GetScreenPosition();
611 gfx::Point TouchSelectionControllerImpl::GetSelectionHandle2Position() {
612 return selection_handle_2_->GetScreenPosition();
615 gfx::Point TouchSelectionControllerImpl::GetCursorHandlePosition() {
616 return cursor_handle_->GetScreenPosition();
619 bool TouchSelectionControllerImpl::IsSelectionHandle1Visible() {
620 return selection_handle_1_->IsWidgetVisible();
623 bool TouchSelectionControllerImpl::IsSelectionHandle2Visible() {
624 return selection_handle_2_->IsWidgetVisible();
627 bool TouchSelectionControllerImpl::IsCursorHandleVisible() {
628 return cursor_handle_->IsWidgetVisible();