blob: 59e9d848b05b0c947ebe5caa49464e6a02d38aff [file] [log] [blame]
Hans Boehm84614952014-11-25 18:46:17 -08001/*
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07002 * Copyright (C) 2015 The Android Open Source Project
Hans Boehm84614952014-11-25 18:46:17 -08003 *
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.calculator2;
18
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070019import android.content.ClipboardManager;
20import android.content.ClipData;
21import android.content.ClipDescription;
22import android.content.Context;
Hans Boehm84614952014-11-25 18:46:17 -080023import android.graphics.Typeface;
24import android.graphics.Paint;
25import android.graphics.Rect;
26import android.graphics.Color;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070027import android.net.Uri;
28import android.widget.TextView;
Hans Boehm84614952014-11-25 18:46:17 -080029import android.widget.OverScroller;
Hans Boehm84614952014-11-25 18:46:17 -080030import android.text.Editable;
31import android.text.Spanned;
32import android.text.SpannableString;
33import android.text.style.ForegroundColorSpan;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070034import android.util.AttributeSet;
35import android.util.Log;
36import android.view.ActionMode;
37import android.view.GestureDetector;
38import android.view.Menu;
39import android.view.MenuInflater;
40import android.view.MenuItem;
41import android.view.MotionEvent;
42import android.view.View;
43import android.widget.Toast;
Hans Boehm84614952014-11-25 18:46:17 -080044
45import android.support.v4.view.ViewCompat;
46
47
48// A text widget that is "infinitely" scrollable to the right,
49// and obtains the text to display via a callback to Logic.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070050public class CalculatorResult extends TextView {
Hans Boehm84614952014-11-25 18:46:17 -080051 final static int MAX_RIGHT_SCROLL = 100000000;
52 final static int INVALID = MAX_RIGHT_SCROLL + 10000;
53 // A larger value is unlikely to avoid running out of space
54 final OverScroller mScroller;
55 final GestureDetector mGestureDetector;
56 class MyTouchListener implements View.OnTouchListener {
57 @Override
58 public boolean onTouch(View v, MotionEvent event) {
59 boolean res = mGestureDetector.onTouchEvent(event);
60 return res;
61 }
62 }
63 final MyTouchListener mTouchListener = new MyTouchListener();
64 private Evaluator mEvaluator;
65 private boolean mScrollable = false;
66 // A scrollable result is currently displayed.
67 private int mCurrentPos;// Position of right of display relative
68 // to decimal point, in pixels.
69 // Large positive values mean the decimal
70 // point is scrolled off the left of the
71 // display. Zero means decimal point is
72 // barely displayed on the right.
73 private int mLastPos; // Position already reflected in display.
74 private int mMinPos; // Maximum position before all digits
75 // digits disappear of the right.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070076 private Object mWidthLock = new Object();
77 // Protects the next two fields.
78 private int mWidthConstraint = -1;
79 // Our total width in pixels.
80 private int mCharWidth = 1;
81 // Maximum character width.
82 // For now we pretend that all characters
83 // have this width.
84 // TODO: We're not really using a fixed
85 // width font. But it appears to be close
86 // enough for the characters we use that
87 // the difference is not noticeable.
Hans Boehm84614952014-11-25 18:46:17 -080088 private Paint mPaint; // Paint object matching display.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070089 private static final int MAX_WIDTH = 100;
90 // Maximum number of digits displayed
Hans Boehm84614952014-11-25 18:46:17 -080091
92 public CalculatorResult(Context context, AttributeSet attrs) {
93 super(context, attrs);
94 mScroller = new OverScroller(context);
95 mGestureDetector = new GestureDetector(context,
96 new GestureDetector.SimpleOnGestureListener() {
97 @Override
98 public boolean onFling(MotionEvent e1, MotionEvent e2,
99 float velocityX, float velocityY) {
100 if (!mScroller.isFinished()) {
101 mCurrentPos = mScroller.getFinalX();
102 }
103 mScroller.forceFinished(true);
104 CalculatorResult.this.cancelLongPress(); // Ignore scrolls of error string, etc.
105 if (!mScrollable) return true;
106 mScroller.fling(mCurrentPos, 0, - (int) velocityX,
107 0 /* horizontal only */, mMinPos,
108 MAX_RIGHT_SCROLL, 0, 0);
109 ViewCompat.postInvalidateOnAnimation(CalculatorResult.this);
110 return true;
111 }
112 @Override
113 public boolean onScroll(MotionEvent e1, MotionEvent e2,
114 float distanceX, float distanceY) {
115 // TODO: Should we be dealing with any edge effects here?
116 if (!mScroller.isFinished()) {
117 mCurrentPos = mScroller.getFinalX();
118 }
119 mScroller.forceFinished(true);
120 CalculatorResult.this.cancelLongPress();
121 if (!mScrollable) return true;
122 int duration = (int)(e2.getEventTime() - e1.getEventTime());
123 if (duration < 1 || duration > 100) duration = 10;
124 mScroller.startScroll(mCurrentPos, 0, (int)distanceX, 0,
125 (int)duration);
126 ViewCompat.postInvalidateOnAnimation(CalculatorResult.this);
127 return true;
128 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700129 @Override
130 public void onLongPress(MotionEvent e) {
131 startActionMode(mCopyActionModeCallback);
132 }
Hans Boehm84614952014-11-25 18:46:17 -0800133 });
134 setOnTouchListener(mTouchListener);
135 setHorizontallyScrolling(false); // do it ourselves
136 setCursorVisible(false);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700137
138 // Copy ActionMode is triggered explicitly, not through
139 // setCustomSelectionActionModeCallback.
Hans Boehm84614952014-11-25 18:46:17 -0800140 }
141
142 void setEvaluator(Evaluator evaluator) {
143 mEvaluator = evaluator;
144 }
145
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700146 @Override
147 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
148 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
149
150 mPaint = getPaint();
Hans Boehm013969e2015-04-13 20:29:47 -0700151 char testChar = KeyMaps.translateResult("5").charAt(0);
152 // TODO: Redo on Locale change? Doesn't seem to matter?
153 // We try to determine the maximal size of a digit plus
154 // corresponding inter-character space.
155 // We assume that "5" has maximal width. Since any
156 // string includes one fewer inter-character space than
157 // characters, me measure one that's longer than any real
158 // display string, and then divide by the number of characters.
159 // This should bound the per-character space we need for any
160 // real string.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700161 StringBuilder sb = new StringBuilder(MAX_WIDTH);
162 for (int i = 0; i < MAX_WIDTH; ++i) {
Hans Boehm013969e2015-04-13 20:29:47 -0700163 sb.append(testChar);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700164 }
Hans Boehm013969e2015-04-13 20:29:47 -0700165 final int newWidthConstraint =
166 MeasureSpec.getSize(widthMeasureSpec)
167 - getPaddingLeft() - getPaddingRight();
168 final int newCharWidth =
169 (int)Math.ceil(mPaint.measureText(sb.toString()) / MAX_WIDTH);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700170 synchronized(mWidthLock) {
Hans Boehm013969e2015-04-13 20:29:47 -0700171 mWidthConstraint = newWidthConstraint;
172 mCharWidth = newCharWidth;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700173 }
174 }
175
Hans Boehm84614952014-11-25 18:46:17 -0800176 // Display a new result, given initial displayed
177 // precision and the string representing the whole part of
178 // the number to be displayed.
179 // We pass the string, instead of just the length, so we have
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700180 // one less place to fix in case we ever decide to
181 // correctly use a variable width font.
Hans Boehm84614952014-11-25 18:46:17 -0800182 void displayResult(int initPrec, String truncatedWholePart) {
183 mLastPos = INVALID;
Hans Boehm013969e2015-04-13 20:29:47 -0700184 synchronized(mWidthLock) {
185 mCurrentPos = initPrec * mCharWidth;
186 }
Hans Boehm84614952014-11-25 18:46:17 -0800187 mMinPos = - (int) Math.ceil(mPaint.measureText(truncatedWholePart));
188 redisplay();
189 }
190
Hans Boehm84614952014-11-25 18:46:17 -0800191 void displayError(int resourceId) {
192 mScrollable = false;
193 setText(resourceId);
194 }
195
Hans Boehm013969e2015-04-13 20:29:47 -0700196 private final int MAX_COPY_SIZE = 1000000;
197
Hans Boehm84614952014-11-25 18:46:17 -0800198 // Return entire result (within reason) up to current displayed precision.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700199 public String getFullText() {
200 if (!mScrollable) return getText().toString();
Hans Boehm013969e2015-04-13 20:29:47 -0700201 int currentCharPos = getCurrentCharPos();
202 return KeyMaps.translateResult(
203 mEvaluator.getString(currentCharPos, MAX_COPY_SIZE));
Hans Boehm84614952014-11-25 18:46:17 -0800204 }
205
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700206 public boolean fullTextIsExact() {
207 BoundedRational rat = mEvaluator.getRational();
Hans Boehm013969e2015-04-13 20:29:47 -0700208 int currentCharPos = getCurrentCharPos();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700209 if (currentCharPos == -1) {
210 // Suppressing decimal point; still showing all
211 // integral digits.
212 currentCharPos = 0;
213 }
214 // TODO: Could handle scientific notation cases better;
215 // We currently treat those conservatively as approximate.
216 return (currentCharPos >= BoundedRational.digitsRequired(rat));
217 }
218
219 // May be called asynchronously from non-UI thread.
Hans Boehm84614952014-11-25 18:46:17 -0800220 int getMaxChars() {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700221 // We only use 2/3 of the available space, since the
222 // left 1/3 of the result is not visible when it is shown
223 // in large size.
224 int result;
225 synchronized(mWidthLock) {
226 result = 2 * mWidthConstraint / (3 * mCharWidth);
227 // We can apparently finish evaluating before
228 // onMeasure in CalculatorEditText has been called, in
229 // which case we get 0 or -1 as the width constraint.
230 }
Hans Boehm84614952014-11-25 18:46:17 -0800231 if (result <= 0) {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700232 // Return something conservatively big, to force sufficient
233 // evaluation.
234 return MAX_WIDTH;
Hans Boehm84614952014-11-25 18:46:17 -0800235 } else {
236 return result;
237 }
238 }
239
Hans Boehm013969e2015-04-13 20:29:47 -0700240 int getCurrentCharPos() {
241 synchronized(mWidthLock) {
242 return mCurrentPos/mCharWidth;
243 }
244 }
245
Hans Boehm84614952014-11-25 18:46:17 -0800246 void clear() {
247 setText("");
248 }
249
250 void redisplay() {
Hans Boehm013969e2015-04-13 20:29:47 -0700251 int currentCharPos = getCurrentCharPos();
Hans Boehm84614952014-11-25 18:46:17 -0800252 int maxChars = getMaxChars();
253 String result = mEvaluator.getString(currentCharPos, maxChars);
254 int epos = result.indexOf('e');
Hans Boehm013969e2015-04-13 20:29:47 -0700255 result = KeyMaps.translateResult(result);
Hans Boehm84614952014-11-25 18:46:17 -0800256 if (epos > 0 && result.indexOf('.') == -1) {
257 // Gray out exponent if used as position indicator
258 SpannableString formattedResult = new SpannableString(result);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700259 formattedResult.setSpan(new ForegroundColorSpan(Color.LTGRAY),
Hans Boehm84614952014-11-25 18:46:17 -0800260 epos, result.length(),
261 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
262 setText(formattedResult);
263 } else {
264 setText(result);
265 }
266 mScrollable = true;
267 }
268
269 @Override
270 public void computeScroll() {
271 if (!mScrollable) return;
272 if (mScroller.computeScrollOffset()) {
273 mCurrentPos = mScroller.getCurrX();
274 if (mCurrentPos != mLastPos) {
275 mLastPos = mCurrentPos;
276 redisplay();
277 }
278 if (!mScroller.isFinished()) {
279 ViewCompat.postInvalidateOnAnimation(this);
280 }
281 }
282 }
283
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700284 // Copy support:
285
286 private ActionMode.Callback mCopyActionModeCallback =
287 new ActionMode.Callback() {
288 @Override
289 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
290 MenuInflater inflater = mode.getMenuInflater();
291 inflater.inflate(R.menu.copy, menu);
292 return true;
293 }
294
295 @Override
296 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
297 return false; // Return false if nothing is done
298 }
299
300 @Override
301 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
302 switch (item.getItemId()) {
303 case R.id.menu_copy:
304 copyContent();
305 mode.finish();
306 return true;
307 default:
308 return false;
309 }
310 }
311
312 @Override
313 public void onDestroyActionMode(ActionMode mode) {
314 }
315 };
316
317 private void setPrimaryClip(ClipData clip) {
318 ClipboardManager clipboard = (ClipboardManager) getContext().
319 getSystemService(Context.CLIPBOARD_SERVICE);
320 clipboard.setPrimaryClip(clip);
321 }
322
323 private void copyContent() {
324 final CharSequence text = getFullText();
325 ClipboardManager clipboard =
326 (ClipboardManager) getContext().getSystemService(
327 Context.CLIPBOARD_SERVICE);
328 // We include a tag URI, to allow us to recognize our
329 // own results and handle them specially.
330 ClipData.Item newItem = new ClipData.Item(text, null,
331 mEvaluator.capture());
332 String[] mimeTypes =
333 new String[] {ClipDescription.MIMETYPE_TEXT_PLAIN};
334 ClipData cd = new ClipData("calculator result",
335 mimeTypes, newItem);
336 clipboard.setPrimaryClip(cd);
337 Toast.makeText(getContext(), R.string.text_copied_toast,
338 Toast.LENGTH_SHORT).show();
339 }
340
Hans Boehm84614952014-11-25 18:46:17 -0800341}