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)) ||
68                       (!ltr && (a == Alignment.ALIGN_NORMAL)) ||
69                       (a == Alignment.ALIGN_RIGHT)) {
70                // align_opposite does NOT mean align_right, we need the paragraph
71                // direction to resolve it to left or right
72                x = left - (availableWidth - actualWidth);
73            } else {
74                x = left;
75            }
76        } else {
77            x = Math.min(x, right - availableWidth);
78            x = Math.max(x, left);
79        }
80
81        widget.scrollTo(x, y);
82    }
83
84    /**
85     * Handles touch events for dragging.  You may want to do other actions
86     * like moving the cursor on touch as well.
87     */
88    public static boolean onTouchEvent(TextView widget, Spannable buffer,
89                                       MotionEvent event) {
90        DragState[] ds;
91
92        switch (event.getActionMasked()) {
93        case MotionEvent.ACTION_DOWN:
94            ds = buffer.getSpans(0, buffer.length(), DragState.class);
95
96            for (int i = 0; i < ds.length; i++) {
97                buffer.removeSpan(ds[i]);
98            }
99
100            buffer.setSpan(new DragState(event.getX(), event.getY(),
101                            widget.getScrollX(), widget.getScrollY()),
102                    0, 0, Spannable.SPAN_MARK_MARK);
103            return true;
104
105        case MotionEvent.ACTION_UP:
106            ds = buffer.getSpans(0, buffer.length(), DragState.class);
107
108            for (int i = 0; i < ds.length; i++) {
109                buffer.removeSpan(ds[i]);
110            }
111
112            if (ds.length > 0 && ds[0].mUsed) {
113                return true;
114            } else {
115                return false;
116            }
117
118        case MotionEvent.ACTION_MOVE:
119            ds = buffer.getSpans(0, buffer.length(), DragState.class);
120
121            if (ds.length > 0) {
122                if (ds[0].mFarEnough == false) {
123                    int slop = ViewConfiguration.get(widget.getContext()).getScaledTouchSlop();
124
125                    if (Math.abs(event.getX() - ds[0].mX) >= slop ||
126                        Math.abs(event.getY() - ds[0].mY) >= slop) {
127                        ds[0].mFarEnough = true;
128                    }
129                }
130
131                if (ds[0].mFarEnough) {
132                    ds[0].mUsed = true;
133                    boolean cap = (event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0
134                            || MetaKeyKeyListener.getMetaState(buffer,
135                                    MetaKeyKeyListener.META_SHIFT_ON) == 1
136                            || MetaKeyKeyListener.getMetaState(buffer,
137                                    MetaKeyKeyListener.META_SELECTING) != 0;
138
139                    float dx;
140                    float dy;
141                    if (cap) {
142                        // if we're selecting, we want the scroll to go in
143                        // the direction of the drag
144                        dx = event.getX() - ds[0].mX;
145                        dy = event.getY() - ds[0].mY;
146                    } else {
147                        dx = ds[0].mX - event.getX();
148                        dy = ds[0].mY - event.getY();
149                    }
150                    ds[0].mX = event.getX();
151                    ds[0].mY = event.getY();
152
153                    int nx = widget.getScrollX() + (int) dx;
154                    int ny = widget.getScrollY() + (int) dy;
155
156                    int padding = widget.getTotalPaddingTop() + widget.getTotalPaddingBottom();
157                    Layout layout = widget.getLayout();
158
159                    ny = Math.min(ny, layout.getHeight() - (widget.getHeight() - padding));
160                    ny = Math.max(ny, 0);
161
162                    int oldX = widget.getScrollX();
163                    int oldY = widget.getScrollY();
164
165                    scrollTo(widget, layout, nx, ny);
166
167                    // If we actually scrolled, then cancel the up action.
168                    if (oldX != widget.getScrollX() || oldY != widget.getScrollY()) {
169                        widget.cancelLongPress();
170                    }
171
172                    return true;
173                }
174            }
175        }
176
177        return false;
178    }
179
180    /**
181     * @param widget The text view.
182     * @param buffer The text buffer.
183     */
184    public static int getInitialScrollX(TextView widget, Spannable buffer) {
185        DragState[] ds = buffer.getSpans(0, buffer.length(), DragState.class);
186        return ds.length > 0 ? ds[0].mScrollX : -1;
187    }
188
189    /**
190     * @param widget The text view.
191     * @param buffer The text buffer.
192     */
193    public static int getInitialScrollY(TextView widget, Spannable buffer) {
194        DragState[] ds = buffer.getSpans(0, buffer.length(), DragState.class);
195        return ds.length > 0 ? ds[0].mScrollY : -1;
196    }
197
198    private static class DragState implements NoCopySpan {
199        public float mX;
200        public float mY;
201        public int mScrollX;
202        public int mScrollY;
203        public boolean mFarEnough;
204        public boolean mUsed;
205
206        public DragState(float x, float y, int scrollX, int scrollY) {
207            mX = x;
208            mY = y;
209            mScrollX = scrollX;
210            mScrollY = scrollY;
211        }
212    }
213}
214