1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.text.method;
18
19import android.text.Layout;
20import android.text.Layout.Alignment;
21import android.text.NoCopySpan;
22import android.text.Spannable;
23import android.view.KeyEvent;
24import android.view.MotionEvent;
25import android.view.ViewConfiguration;
26import android.widget.TextView;
27
28public class Touch {
29    private Touch() { }
30
31    /**
32     * Scrolls the specified widget to the specified coordinates, except
33     * constrains the X scrolling position to the horizontal regions of
34     * the text that will be visible after scrolling to the specified
35     * Y position.
36     */
37    public static void scrollTo(TextView widget, Layout layout, int x, int y) {
38        final int horizontalPadding = widget.getTotalPaddingLeft() + widget.getTotalPaddingRight();
39        final int availableWidth = widget.getWidth() - horizontalPadding;
40
41        final int top = layout.getLineForVertical(y);
42        Alignment a = layout.getParagraphAlignment(top);
43        boolean ltr = layout.getParagraphDirection(top) > 0;
44
45        int left, right;
46        if (widget.getHorizontallyScrolling()) {
47            final int verticalPadding = widget.getTotalPaddingTop() + widget.getTotalPaddingBottom();
48            final int bottom = layout.getLineForVertical(y + widget.getHeight() - verticalPadding);
49
50            left = Integer.MAX_VALUE;
51            right = 0;
52
53            for (int i = top; i <= bottom; i++) {
54                left = (int) Math.min(left, layout.getLineLeft(i));
55                right = (int) Math.max(right, layout.getLineRight(i));
56            }
57        } else {
58            left = 0;
59            right = availableWidth;
60        }
61
62        final int actualWidth = right - left;
63
64        if (actualWidth < availableWidth) {
65            if (a == Alignment.ALIGN_CENTER) {
66                x = left - ((availableWidth - actualWidth) / 2);
67            } else if ((ltr && (a == Alignment.ALIGN_OPPOSITE)) || (a == Alignment.ALIGN_RIGHT)) {
68                // align_opposite does NOT mean align_right, we need the paragraph
69                // direction to resolve it to left or right
70                x = left - (availableWidth - actualWidth);
71            } else {
72                x = left;
73            }
74        } else {
75            x = Math.min(x, right - availableWidth);
76            x = Math.max(x, left);
77        }
78
79        widget.scrollTo(x, y);
80    }
81
82    /**
83     * Handles touch events for dragging.  You may want to do other actions
84     * like moving the cursor on touch as well.
85     */
86    public static boolean onTouchEvent(TextView widget, Spannable buffer,
87                                       MotionEvent event) {
88        DragState[] ds;
89
90        switch (event.getActionMasked()) {
91        case MotionEvent.ACTION_DOWN:
92            ds = buffer.getSpans(0, buffer.length(), DragState.class);
93
94            for (int i = 0; i < ds.length; i++) {
95                buffer.removeSpan(ds[i]);
96            }
97
98            buffer.setSpan(new DragState(event.getX(), event.getY(),
99                            widget.getScrollX(), widget.getScrollY()),
100                    0, 0, Spannable.SPAN_MARK_MARK);
101            return true;
102
103        case MotionEvent.ACTION_UP:
104            ds = buffer.getSpans(0, buffer.length(), DragState.class);
105
106            for (int i = 0; i < ds.length; i++) {
107                buffer.removeSpan(ds[i]);
108            }
109
110            if (ds.length > 0 && ds[0].mUsed) {
111                return true;
112            } else {
113                return false;
114            }
115
116        case MotionEvent.ACTION_MOVE:
117            ds = buffer.getSpans(0, buffer.length(), DragState.class);
118
119            if (ds.length > 0) {
120                if (ds[0].mFarEnough == false) {
121                    int slop = ViewConfiguration.get(widget.getContext()).getScaledTouchSlop();
122
123                    if (Math.abs(event.getX() - ds[0].mX) >= slop ||
124                        Math.abs(event.getY() - ds[0].mY) >= slop) {
125                        ds[0].mFarEnough = true;
126                    }
127                }
128
129                if (ds[0].mFarEnough) {
130                    ds[0].mUsed = true;
131                    boolean cap = (event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0
132                            || MetaKeyKeyListener.getMetaState(buffer,
133                                    MetaKeyKeyListener.META_SHIFT_ON) == 1
134                            || MetaKeyKeyListener.getMetaState(buffer,
135                                    MetaKeyKeyListener.META_SELECTING) != 0;
136                    float dx;
137                    float dy;
138                    if (cap) {
139                        // if we're selecting, we want the scroll to go in
140                        // the direction of the drag
141                        dx = event.getX() - ds[0].mX;
142                        dy = event.getY() - ds[0].mY;
143                    } else {
144                        dx = ds[0].mX - event.getX();
145                        dy = ds[0].mY - event.getY();
146                    }
147                    ds[0].mX = event.getX();
148                    ds[0].mY = event.getY();
149
150                    int nx = widget.getScrollX() + (int) dx;
151                    int ny = widget.getScrollY() + (int) dy;
152
153                    int padding = widget.getTotalPaddingTop() + widget.getTotalPaddingBottom();
154                    Layout layout = widget.getLayout();
155
156                    ny = Math.min(ny, layout.getHeight() - (widget.getHeight() - padding));
157                    ny = Math.max(ny, 0);
158
159                    int oldX = widget.getScrollX();
160                    int oldY = widget.getScrollY();
161
162                    scrollTo(widget, layout, nx, ny);
163
164                    // If we actually scrolled, then cancel the up action.
165                    if (oldX != widget.getScrollX() || oldY != widget.getScrollY()) {
166                        widget.cancelLongPress();
167                    }
168
169                    return true;
170                }
171            }
172        }
173
174        return false;
175    }
176
177    /**
178     * @param widget The text view.
179     * @param buffer The text buffer.
180     */
181    public static int getInitialScrollX(TextView widget, Spannable buffer) {
182        DragState[] ds = buffer.getSpans(0, buffer.length(), DragState.class);
183        return ds.length > 0 ? ds[0].mScrollX : -1;
184    }
185
186    /**
187     * @param widget The text view.
188     * @param buffer The text buffer.
189     */
190    public static int getInitialScrollY(TextView widget, Spannable buffer) {
191        DragState[] ds = buffer.getSpans(0, buffer.length(), DragState.class);
192        return ds.length > 0 ? ds[0].mScrollY : -1;
193    }
194
195    private static class DragState implements NoCopySpan {
196        public float mX;
197        public float mY;
198        public int mScrollX;
199        public int mScrollY;
200        public boolean mFarEnough;
201        public boolean mUsed;
202
203        public DragState(float x, float y, int scrollX, int scrollY) {
204            mX = x;
205            mY = y;
206            mScrollX = scrollX;
207            mScrollY = scrollY;
208        }
209    }
210}
211