blob: 6fac5a6a9b5224974634a0a7999fa8ced8145054 [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
Justin Klaassend48b7562015-04-16 16:51:38 -070098 public boolean onDown(MotionEvent e) {
99 return true;
100 }
101 @Override
Hans Boehm84614952014-11-25 18:46:17 -0800102 public boolean onFling(MotionEvent e1, MotionEvent e2,
103 float velocityX, float velocityY) {
104 if (!mScroller.isFinished()) {
105 mCurrentPos = mScroller.getFinalX();
106 }
107 mScroller.forceFinished(true);
108 CalculatorResult.this.cancelLongPress(); // Ignore scrolls of error string, etc.
109 if (!mScrollable) return true;
110 mScroller.fling(mCurrentPos, 0, - (int) velocityX,
111 0 /* horizontal only */, mMinPos,
112 MAX_RIGHT_SCROLL, 0, 0);
113 ViewCompat.postInvalidateOnAnimation(CalculatorResult.this);
114 return true;
115 }
116 @Override
117 public boolean onScroll(MotionEvent e1, MotionEvent e2,
118 float distanceX, float distanceY) {
119 // TODO: Should we be dealing with any edge effects here?
120 if (!mScroller.isFinished()) {
121 mCurrentPos = mScroller.getFinalX();
122 }
123 mScroller.forceFinished(true);
124 CalculatorResult.this.cancelLongPress();
125 if (!mScrollable) return true;
126 int duration = (int)(e2.getEventTime() - e1.getEventTime());
127 if (duration < 1 || duration > 100) duration = 10;
128 mScroller.startScroll(mCurrentPos, 0, (int)distanceX, 0,
129 (int)duration);
130 ViewCompat.postInvalidateOnAnimation(CalculatorResult.this);
131 return true;
132 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700133 @Override
134 public void onLongPress(MotionEvent e) {
135 startActionMode(mCopyActionModeCallback);
136 }
Hans Boehm84614952014-11-25 18:46:17 -0800137 });
138 setOnTouchListener(mTouchListener);
139 setHorizontallyScrolling(false); // do it ourselves
140 setCursorVisible(false);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700141
142 // Copy ActionMode is triggered explicitly, not through
143 // setCustomSelectionActionModeCallback.
Hans Boehm84614952014-11-25 18:46:17 -0800144 }
145
146 void setEvaluator(Evaluator evaluator) {
147 mEvaluator = evaluator;
148 }
149
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700150 @Override
151 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
152 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
153
154 mPaint = getPaint();
Hans Boehm013969e2015-04-13 20:29:47 -0700155 char testChar = KeyMaps.translateResult("5").charAt(0);
156 // TODO: Redo on Locale change? Doesn't seem to matter?
157 // We try to determine the maximal size of a digit plus
158 // corresponding inter-character space.
159 // We assume that "5" has maximal width. Since any
160 // string includes one fewer inter-character space than
161 // characters, me measure one that's longer than any real
162 // display string, and then divide by the number of characters.
163 // This should bound the per-character space we need for any
164 // real string.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700165 StringBuilder sb = new StringBuilder(MAX_WIDTH);
166 for (int i = 0; i < MAX_WIDTH; ++i) {
Hans Boehm013969e2015-04-13 20:29:47 -0700167 sb.append(testChar);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700168 }
Hans Boehm013969e2015-04-13 20:29:47 -0700169 final int newWidthConstraint =
170 MeasureSpec.getSize(widthMeasureSpec)
171 - getPaddingLeft() - getPaddingRight();
172 final int newCharWidth =
173 (int)Math.ceil(mPaint.measureText(sb.toString()) / MAX_WIDTH);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700174 synchronized(mWidthLock) {
Hans Boehm013969e2015-04-13 20:29:47 -0700175 mWidthConstraint = newWidthConstraint;
176 mCharWidth = newCharWidth;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700177 }
178 }
179
Hans Boehm84614952014-11-25 18:46:17 -0800180 // Display a new result, given initial displayed
181 // precision and the string representing the whole part of
182 // the number to be displayed.
183 // We pass the string, instead of just the length, so we have
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700184 // one less place to fix in case we ever decide to
185 // correctly use a variable width font.
Hans Boehm84614952014-11-25 18:46:17 -0800186 void displayResult(int initPrec, String truncatedWholePart) {
187 mLastPos = INVALID;
Hans Boehm013969e2015-04-13 20:29:47 -0700188 synchronized(mWidthLock) {
189 mCurrentPos = initPrec * mCharWidth;
190 }
Hans Boehm84614952014-11-25 18:46:17 -0800191 mMinPos = - (int) Math.ceil(mPaint.measureText(truncatedWholePart));
192 redisplay();
193 }
194
Hans Boehm84614952014-11-25 18:46:17 -0800195 void displayError(int resourceId) {
196 mScrollable = false;
197 setText(resourceId);
198 }
199
Hans Boehm013969e2015-04-13 20:29:47 -0700200 private final int MAX_COPY_SIZE = 1000000;
201
Hans Boehm84614952014-11-25 18:46:17 -0800202 // Return entire result (within reason) up to current displayed precision.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700203 public String getFullText() {
204 if (!mScrollable) return getText().toString();
Hans Boehm013969e2015-04-13 20:29:47 -0700205 int currentCharPos = getCurrentCharPos();
206 return KeyMaps.translateResult(
207 mEvaluator.getString(currentCharPos, MAX_COPY_SIZE));
Hans Boehm84614952014-11-25 18:46:17 -0800208 }
209
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700210 public boolean fullTextIsExact() {
211 BoundedRational rat = mEvaluator.getRational();
Hans Boehm013969e2015-04-13 20:29:47 -0700212 int currentCharPos = getCurrentCharPos();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700213 if (currentCharPos == -1) {
214 // Suppressing decimal point; still showing all
215 // integral digits.
216 currentCharPos = 0;
217 }
218 // TODO: Could handle scientific notation cases better;
219 // We currently treat those conservatively as approximate.
220 return (currentCharPos >= BoundedRational.digitsRequired(rat));
221 }
222
223 // May be called asynchronously from non-UI thread.
Hans Boehm84614952014-11-25 18:46:17 -0800224 int getMaxChars() {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700225 // We only use 2/3 of the available space, since the
226 // left 1/3 of the result is not visible when it is shown
227 // in large size.
228 int result;
229 synchronized(mWidthLock) {
230 result = 2 * mWidthConstraint / (3 * mCharWidth);
231 // We can apparently finish evaluating before
232 // onMeasure in CalculatorEditText has been called, in
233 // which case we get 0 or -1 as the width constraint.
234 }
Hans Boehm84614952014-11-25 18:46:17 -0800235 if (result <= 0) {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700236 // Return something conservatively big, to force sufficient
237 // evaluation.
238 return MAX_WIDTH;
Hans Boehm84614952014-11-25 18:46:17 -0800239 } else {
240 return result;
241 }
242 }
243
Hans Boehm013969e2015-04-13 20:29:47 -0700244 int getCurrentCharPos() {
245 synchronized(mWidthLock) {
246 return mCurrentPos/mCharWidth;
247 }
248 }
249
Hans Boehm84614952014-11-25 18:46:17 -0800250 void clear() {
251 setText("");
252 }
253
254 void redisplay() {
Hans Boehm013969e2015-04-13 20:29:47 -0700255 int currentCharPos = getCurrentCharPos();
Hans Boehm84614952014-11-25 18:46:17 -0800256 int maxChars = getMaxChars();
257 String result = mEvaluator.getString(currentCharPos, maxChars);
258 int epos = result.indexOf('e');
Hans Boehm013969e2015-04-13 20:29:47 -0700259 result = KeyMaps.translateResult(result);
Hans Boehm84614952014-11-25 18:46:17 -0800260 if (epos > 0 && result.indexOf('.') == -1) {
261 // Gray out exponent if used as position indicator
262 SpannableString formattedResult = new SpannableString(result);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700263 formattedResult.setSpan(new ForegroundColorSpan(Color.LTGRAY),
Hans Boehm84614952014-11-25 18:46:17 -0800264 epos, result.length(),
265 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
266 setText(formattedResult);
267 } else {
268 setText(result);
269 }
270 mScrollable = true;
271 }
272
273 @Override
274 public void computeScroll() {
275 if (!mScrollable) return;
276 if (mScroller.computeScrollOffset()) {
277 mCurrentPos = mScroller.getCurrX();
278 if (mCurrentPos != mLastPos) {
279 mLastPos = mCurrentPos;
280 redisplay();
281 }
282 if (!mScroller.isFinished()) {
283 ViewCompat.postInvalidateOnAnimation(this);
284 }
285 }
286 }
287
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700288 // Copy support:
289
290 private ActionMode.Callback mCopyActionModeCallback =
291 new ActionMode.Callback() {
292 @Override
293 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
294 MenuInflater inflater = mode.getMenuInflater();
295 inflater.inflate(R.menu.copy, menu);
296 return true;
297 }
298
299 @Override
300 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
301 return false; // Return false if nothing is done
302 }
303
304 @Override
305 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
306 switch (item.getItemId()) {
307 case R.id.menu_copy:
308 copyContent();
309 mode.finish();
310 return true;
311 default:
312 return false;
313 }
314 }
315
316 @Override
317 public void onDestroyActionMode(ActionMode mode) {
318 }
319 };
320
321 private void setPrimaryClip(ClipData clip) {
322 ClipboardManager clipboard = (ClipboardManager) getContext().
323 getSystemService(Context.CLIPBOARD_SERVICE);
324 clipboard.setPrimaryClip(clip);
325 }
326
327 private void copyContent() {
328 final CharSequence text = getFullText();
329 ClipboardManager clipboard =
330 (ClipboardManager) getContext().getSystemService(
331 Context.CLIPBOARD_SERVICE);
332 // We include a tag URI, to allow us to recognize our
333 // own results and handle them specially.
334 ClipData.Item newItem = new ClipData.Item(text, null,
335 mEvaluator.capture());
336 String[] mimeTypes =
337 new String[] {ClipDescription.MIMETYPE_TEXT_PLAIN};
338 ClipData cd = new ClipData("calculator result",
339 mimeTypes, newItem);
340 clipboard.setPrimaryClip(cd);
341 Toast.makeText(getContext(), R.string.text_copied_toast,
342 Toast.LENGTH_SHORT).show();
343 }
344
Hans Boehm84614952014-11-25 18:46:17 -0800345}