[go: nahoru, domu]

1/*
2 * Copyright (C) 2016 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 com.android.setupwizardlib.util;
18
19import android.graphics.Rect;
20import android.os.Bundle;
21import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
22import android.support.v4.widget.ExploreByTouchHelper;
23import android.text.Layout;
24import android.text.Spanned;
25import android.text.style.ClickableSpan;
26import android.util.Log;
27import android.view.accessibility.AccessibilityEvent;
28import android.widget.TextView;
29
30import java.util.List;
31
32/**
33 * An accessibility delegate that allows {@link android.text.style.ClickableSpan} to be focused and
34 * clicked by accessibility services.
35 *
36 * <p />Sample usage:
37 * <pre>
38 * LinkAccessibilityHelper mAccessibilityHelper;
39 *
40 * private void init() {
41 *     mAccessibilityHelper = new LinkAccessibilityHelper(myTextView);
42 *     ViewCompat.setAccessibilityDelegate(myTextView, mLinkHelper);
43 * }
44 *
45 * {@literal @}Override
46 * protected boolean dispatchHoverEvent({@literal @}NonNull MotionEvent event) {
47 *     if (mAccessibilityHelper != null && mAccessibilityHelper.dispatchHoverEvent(event)) {
48 *         return true;
49 *     }
50 *     return super.dispatchHoverEvent(event);
51 * }
52 * </pre>
53 *
54 * @see com.android.setupwizardlib.view.RichTextView
55 * @see android.support.v4.widget.ExploreByTouchHelper
56 */
57public class LinkAccessibilityHelper extends ExploreByTouchHelper {
58
59    private static final String TAG = "LinkAccessibilityHelper";
60
61    private final TextView mView;
62    private final Rect mTempRect = new Rect();
63
64    public LinkAccessibilityHelper(TextView view) {
65        super(view);
66        mView = view;
67    }
68
69    @Override
70    protected int getVirtualViewAt(float x, float y) {
71        final CharSequence text = mView.getText();
72        if (text instanceof Spanned) {
73            final Spanned spannedText = (Spanned) text;
74            final int offset = getOffsetForPosition(mView, x, y);
75            ClickableSpan[] linkSpans = spannedText.getSpans(offset, offset, ClickableSpan.class);
76            if (linkSpans.length == 1) {
77                ClickableSpan linkSpan = linkSpans[0];
78                return spannedText.getSpanStart(linkSpan);
79            }
80        }
81        return INVALID_ID;
82    }
83
84    @Override
85    protected void getVisibleVirtualViews(List<Integer> virtualViewIds) {
86        final CharSequence text = mView.getText();
87        if (text instanceof Spanned) {
88            final Spanned spannedText = (Spanned) text;
89            ClickableSpan[] linkSpans = spannedText.getSpans(0, spannedText.length(),
90                    ClickableSpan.class);
91            for (ClickableSpan span : linkSpans) {
92                virtualViewIds.add(spannedText.getSpanStart(span));
93            }
94        }
95    }
96
97    @Override
98    protected void onPopulateEventForVirtualView(int virtualViewId, AccessibilityEvent event) {
99        final ClickableSpan span = getSpanForOffset(virtualViewId);
100        if (span != null) {
101            event.setContentDescription(getTextForSpan(span));
102        } else {
103            Log.e(TAG, "LinkSpan is null for offset: " + virtualViewId);
104            event.setContentDescription(mView.getText());
105        }
106    }
107
108    @Override
109    protected void onPopulateNodeForVirtualView(int virtualViewId,
110            AccessibilityNodeInfoCompat info) {
111        final ClickableSpan span = getSpanForOffset(virtualViewId);
112        if (span != null) {
113            info.setContentDescription(getTextForSpan(span));
114        } else {
115            Log.e(TAG, "LinkSpan is null for offset: " + virtualViewId);
116            info.setContentDescription(mView.getText());
117        }
118        info.setFocusable(true);
119        info.setClickable(true);
120        getBoundsForSpan(span, mTempRect);
121        if (!mTempRect.isEmpty()) {
122            info.setBoundsInParent(getBoundsForSpan(span, mTempRect));
123        } else {
124            Log.e(TAG, "LinkSpan bounds is empty for: " + virtualViewId);
125            mTempRect.set(0, 0, 1, 1);
126            info.setBoundsInParent(mTempRect);
127        }
128        info.addAction(AccessibilityNodeInfoCompat.ACTION_CLICK);
129    }
130
131    @Override
132    protected boolean onPerformActionForVirtualView(int virtualViewId, int action,
133            Bundle arguments) {
134        if (action == AccessibilityNodeInfoCompat.ACTION_CLICK) {
135            ClickableSpan span = getSpanForOffset(virtualViewId);
136            if (span != null) {
137                span.onClick(mView);
138                return true;
139            } else {
140                Log.e(TAG, "LinkSpan is null for offset: " + virtualViewId);
141            }
142        }
143        return false;
144    }
145
146    private ClickableSpan getSpanForOffset(int offset) {
147        CharSequence text = mView.getText();
148        if (text instanceof Spanned) {
149            Spanned spannedText = (Spanned) text;
150            ClickableSpan[] spans = spannedText.getSpans(offset, offset, ClickableSpan.class);
151            if (spans.length == 1) {
152                return spans[0];
153            }
154        }
155        return null;
156    }
157
158    private CharSequence getTextForSpan(ClickableSpan span) {
159        CharSequence text = mView.getText();
160        if (text instanceof Spanned) {
161            Spanned spannedText = (Spanned) text;
162            return spannedText.subSequence(spannedText.getSpanStart(span),
163                    spannedText.getSpanEnd(span));
164        }
165        return text;
166    }
167
168    // Find the bounds of a span. If it spans multiple lines, it will only return the bounds for the
169    // section on the first line.
170    private Rect getBoundsForSpan(ClickableSpan span, Rect outRect) {
171        CharSequence text = mView.getText();
172        outRect.setEmpty();
173        if (text instanceof Spanned) {
174            Spanned spannedText = (Spanned) text;
175            final int spanStart = spannedText.getSpanStart(span);
176            final int spanEnd = spannedText.getSpanEnd(span);
177            final Layout layout = mView.getLayout();
178            final float xStart = layout.getPrimaryHorizontal(spanStart);
179            final float xEnd = layout.getPrimaryHorizontal(spanEnd);
180            final int lineStart = layout.getLineForOffset(spanStart);
181            final int lineEnd = layout.getLineForOffset(spanEnd);
182            layout.getLineBounds(lineStart, outRect);
183            outRect.left = (int) xStart;
184            if (lineEnd == lineStart) {
185                outRect.right = (int) xEnd;
186            } // otherwise just leave it at the end of the start line
187
188            // Offset for padding
189            outRect.offset(mView.getTotalPaddingLeft(), mView.getTotalPaddingTop());
190        }
191        return outRect;
192    }
193
194    // Compat implementation of TextView#getOffsetForPosition().
195
196    private static int getOffsetForPosition(TextView view, float x, float y) {
197        if (view.getLayout() == null) return -1;
198        final int line = getLineAtCoordinate(view, y);
199        return getOffsetAtCoordinate(view, line, x);
200    }
201
202    private static float convertToLocalHorizontalCoordinate(TextView view, float x) {
203        x -= view.getTotalPaddingLeft();
204        // Clamp the position to inside of the view.
205        x = Math.max(0.0f, x);
206        x = Math.min(view.getWidth() - view.getTotalPaddingRight() - 1, x);
207        x += view.getScrollX();
208        return x;
209    }
210
211    private static int getLineAtCoordinate(TextView view, float y) {
212        y -= view.getTotalPaddingTop();
213        // Clamp the position to inside of the view.
214        y = Math.max(0.0f, y);
215        y = Math.min(view.getHeight() - view.getTotalPaddingBottom() - 1, y);
216        y += view.getScrollY();
217        return view.getLayout().getLineForVertical((int) y);
218    }
219
220    private static int getOffsetAtCoordinate(TextView view, int line, float x) {
221        x = convertToLocalHorizontalCoordinate(view, x);
222        return view.getLayout().getOffsetForHorizontal(line, x);
223    }
224}
225