blob: ef62be3226266b59c4c48fe1978033402992b9da [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 Boehm08e8f322015-04-21 13:18:38 -070051 static final int MAX_RIGHT_SCROLL = 100000000;
52 static final int INVALID = MAX_RIGHT_SCROLL + 10000;
Hans Boehm84614952014-11-25 18:46:17 -080053 // 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.
Hans Boehm760a9dc2015-04-20 10:27:12 -070067 private boolean mValid = false;
68 // The result holds something valid; either a
69 // a number or an error message.
Hans Boehm84614952014-11-25 18:46:17 -080070 private int mCurrentPos;// Position of right of display relative
71 // to decimal point, in pixels.
72 // Large positive values mean the decimal
73 // point is scrolled off the left of the
74 // display. Zero means decimal point is
75 // barely displayed on the right.
76 private int mLastPos; // Position already reflected in display.
77 private int mMinPos; // Maximum position before all digits
78 // digits disappear of the right.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070079 private Object mWidthLock = new Object();
80 // Protects the next two fields.
81 private int mWidthConstraint = -1;
82 // Our total width in pixels.
83 private int mCharWidth = 1;
84 // Maximum character width.
85 // For now we pretend that all characters
86 // have this width.
87 // TODO: We're not really using a fixed
88 // width font. But it appears to be close
89 // enough for the characters we use that
90 // the difference is not noticeable.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070091 private static final int MAX_WIDTH = 100;
92 // Maximum number of digits displayed
Hans Boehm84614952014-11-25 18:46:17 -080093
94 public CalculatorResult(Context context, AttributeSet attrs) {
95 super(context, attrs);
96 mScroller = new OverScroller(context);
97 mGestureDetector = new GestureDetector(context,
98 new GestureDetector.SimpleOnGestureListener() {
99 @Override
Justin Klaassend48b7562015-04-16 16:51:38 -0700100 public boolean onDown(MotionEvent e) {
101 return true;
102 }
103 @Override
Hans Boehm84614952014-11-25 18:46:17 -0800104 public boolean onFling(MotionEvent e1, MotionEvent e2,
105 float velocityX, float velocityY) {
106 if (!mScroller.isFinished()) {
107 mCurrentPos = mScroller.getFinalX();
108 }
109 mScroller.forceFinished(true);
110 CalculatorResult.this.cancelLongPress(); // Ignore scrolls of error string, etc.
111 if (!mScrollable) return true;
112 mScroller.fling(mCurrentPos, 0, - (int) velocityX,
113 0 /* horizontal only */, mMinPos,
114 MAX_RIGHT_SCROLL, 0, 0);
115 ViewCompat.postInvalidateOnAnimation(CalculatorResult.this);
116 return true;
117 }
118 @Override
119 public boolean onScroll(MotionEvent e1, MotionEvent e2,
120 float distanceX, float distanceY) {
121 // TODO: Should we be dealing with any edge effects here?
122 if (!mScroller.isFinished()) {
123 mCurrentPos = mScroller.getFinalX();
124 }
125 mScroller.forceFinished(true);
126 CalculatorResult.this.cancelLongPress();
127 if (!mScrollable) return true;
128 int duration = (int)(e2.getEventTime() - e1.getEventTime());
129 if (duration < 1 || duration > 100) duration = 10;
130 mScroller.startScroll(mCurrentPos, 0, (int)distanceX, 0,
131 (int)duration);
132 ViewCompat.postInvalidateOnAnimation(CalculatorResult.this);
133 return true;
134 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700135 @Override
136 public void onLongPress(MotionEvent e) {
137 startActionMode(mCopyActionModeCallback);
138 }
Hans Boehm84614952014-11-25 18:46:17 -0800139 });
140 setOnTouchListener(mTouchListener);
141 setHorizontallyScrolling(false); // do it ourselves
142 setCursorVisible(false);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700143
144 // Copy ActionMode is triggered explicitly, not through
145 // setCustomSelectionActionModeCallback.
Hans Boehm84614952014-11-25 18:46:17 -0800146 }
147
148 void setEvaluator(Evaluator evaluator) {
149 mEvaluator = evaluator;
150 }
151
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700152 @Override
153 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
154 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
155
Hans Boehm013969e2015-04-13 20:29:47 -0700156 char testChar = KeyMaps.translateResult("5").charAt(0);
157 // TODO: Redo on Locale change? Doesn't seem to matter?
158 // We try to determine the maximal size of a digit plus
159 // corresponding inter-character space.
160 // We assume that "5" has maximal width. Since any
161 // string includes one fewer inter-character space than
162 // characters, me measure one that's longer than any real
163 // display string, and then divide by the number of characters.
164 // This should bound the per-character space we need for any
165 // real string.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700166 StringBuilder sb = new StringBuilder(MAX_WIDTH);
167 for (int i = 0; i < MAX_WIDTH; ++i) {
Hans Boehm013969e2015-04-13 20:29:47 -0700168 sb.append(testChar);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700169 }
Hans Boehm013969e2015-04-13 20:29:47 -0700170 final int newWidthConstraint =
171 MeasureSpec.getSize(widthMeasureSpec)
172 - getPaddingLeft() - getPaddingRight();
173 final int newCharWidth =
Hans Boehmc5e6e152015-04-22 12:06:29 -0700174 (int)Math.ceil(getPaint().measureText(sb.toString())
175 / MAX_WIDTH);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700176 synchronized(mWidthLock) {
Hans Boehm013969e2015-04-13 20:29:47 -0700177 mWidthConstraint = newWidthConstraint;
178 mCharWidth = newCharWidth;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700179 }
180 }
181
Hans Boehm84614952014-11-25 18:46:17 -0800182 // Display a new result, given initial displayed
183 // precision and the string representing the whole part of
184 // the number to be displayed.
185 // We pass the string, instead of just the length, so we have
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700186 // one less place to fix in case we ever decide to
187 // correctly use a variable width font.
Hans Boehm84614952014-11-25 18:46:17 -0800188 void displayResult(int initPrec, String truncatedWholePart) {
189 mLastPos = INVALID;
Hans Boehm013969e2015-04-13 20:29:47 -0700190 synchronized(mWidthLock) {
191 mCurrentPos = initPrec * mCharWidth;
192 }
Hans Boehmc5e6e152015-04-22 12:06:29 -0700193 mMinPos = - (int) Math.ceil(getPaint().measureText(truncatedWholePart));
Hans Boehm84614952014-11-25 18:46:17 -0800194 redisplay();
195 }
196
Hans Boehm84614952014-11-25 18:46:17 -0800197 void displayError(int resourceId) {
Hans Boehm760a9dc2015-04-20 10:27:12 -0700198 mValid = true;
Hans Boehm84614952014-11-25 18:46:17 -0800199 mScrollable = false;
200 setText(resourceId);
201 }
202
Hans Boehm013969e2015-04-13 20:29:47 -0700203 private final int MAX_COPY_SIZE = 1000000;
204
Hans Boehm08e8f322015-04-21 13:18:38 -0700205 // Format a result returned by Evaluator.getString() into a single
206 // line containing ellipses (if appropriate) and an exponent
207 // (if appropriate). digs is the value that was passed to
208 // getString and thus identifies the significance of the
209 // rightmost digit.
210 // We add two distinct kinds of exponents:
211 // 1) If the final result contains the leading digit we use standard
212 // scientific notation.
213 // 2) If not, we add an exponent corresponding to an interpretation
214 // of the final result as an integer.
215 // We add an ellipsis on the left if the result was truncated.
216 // We add ellipses and exponents in a way that leaves most digits
217 // in the position they would have been in had we not done so.
218 // This minimizes jumps as a result of scrolling.
219 // Result is NOT internationalized, uses "e" for exponent.
220 // last_included[0] is set to the position of the last digit we
221 // actually include; thus caller can tell whether result is exact.
222 public String formatResult(String res, int digs,
223 int maxDigs, boolean truncated,
224 boolean negative) {
225 if (truncated) {
226 res = KeyMaps.ELLIPSIS + res.substring(1, res.length());
227 }
228 int decIndex = res.indexOf('.');
229 int resLen = res.length();
230 if (decIndex == -1 && digs != -1) {
231 // No decimal point displayed, and it's not just
232 // to the right of the last digit.
233 // Add an exponent to let the user track which
234 // digits are currently displayed.
235 // This is a bit tricky, since the number of displayed
236 // digits affects the displayed exponent, which can
237 // affect the room we have for mantissa digits.
238 // We occasionally display one digit too few.
239 // This is sometimes unavoidable, but we could
240 // avoid it in more cases.
241 int exp = digs > 0 ? -digs : -digs - 1;
242 // Can be used as TYPE (2) EXPONENT.
243 // -1 accounts for decimal point.
244 int msd; // Position of most significant digit in res
245 // or indication its outside res.
246 boolean hasPoint = false;
247 if (truncated) {
248 msd = -1;
249 } else {
250 msd = Evaluator.getMsdPos(res); // INVALID_MSD is OK
251 }
252 if (msd < maxDigs - 1 && msd >= 0) {
253 // TYPE (1) EXPONENT computation and transformation:
254 // Leading digit is in display window.
255 // Use standard calculator scientific notation
256 // with one digit to the left of the decimal point.
257 // Insert decimal point and delete leading zeroes.
258 String fraction = res.substring(msd + 1, resLen);
259 res = (negative ? "-" : "")
260 + res.substring(msd, msd+1) + "." + fraction;
261 exp += resLen - msd - 1;
262 // Original exp was correct for decimal point at right
263 // of fraction. Adjust by length of fraction.
264 resLen = res.length();
265 hasPoint = true;
266 }
267 if (exp != 0 || truncated) {
268 // Actually add the exponent of either type:
269 String expAsString = Integer.toString(exp);
270 int expDigits = expAsString.length();
271 int dropDigits = expDigits + 1;
272 // Drop digits even if there is room.
273 // Otherwise the scrolling gets jumpy.
274 if (dropDigits >= resLen - 1) {
275 dropDigits = Math.max(resLen - 2, 0);
276 // Jumpy is better than no mantissa.
277 }
278 if (!hasPoint) {
279 // Special handling for TYPE(2) EXPONENT:
280 exp += dropDigits;
281 expAsString = Integer.toString(exp);
282 // Adjust for digits we are about to drop
283 // to drop to make room for exponent.
284 // This can affect the room we have for the
285 // mantissa. We adjust only for positive exponents,
286 // when it could otherwise result in a truncated
287 // displayed result.
288 if (exp > 0 && expAsString.length() > expDigits) {
289 // ++expDigits; (dead code)
290 ++dropDigits;
291 ++exp;
292 // This cannot increase the length a second time.
293 }
294 }
295 res = res.substring(0, resLen - dropDigits);
296 res = res + "e" + expAsString;
297 } // else don't add zero exponent
298 }
299 return res;
300 }
301
302 // Get formatted, but not internationalized, result from
303 // mEvaluator.
304 private String getFormattedResult(int pos, int maxSize) {
305 final boolean truncated[] = new boolean[1];
306 final boolean negative[] = new boolean[1];
307 final int requested_prec[] = {pos};
308 final String raw_res = mEvaluator.getString(requested_prec, maxSize,
309 truncated, negative);
310 return formatResult(raw_res, requested_prec[0], maxSize,
311 truncated[0], negative[0]);
312 }
313
Hans Boehm84614952014-11-25 18:46:17 -0800314 // Return entire result (within reason) up to current displayed precision.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700315 public String getFullText() {
Hans Boehm760a9dc2015-04-20 10:27:12 -0700316 if (!mValid) return "";
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700317 if (!mScrollable) return getText().toString();
Hans Boehm013969e2015-04-13 20:29:47 -0700318 int currentCharPos = getCurrentCharPos();
319 return KeyMaps.translateResult(
Hans Boehm08e8f322015-04-21 13:18:38 -0700320 getFormattedResult(currentCharPos, MAX_COPY_SIZE));
Hans Boehm84614952014-11-25 18:46:17 -0800321 }
322
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700323 public boolean fullTextIsExact() {
324 BoundedRational rat = mEvaluator.getRational();
Hans Boehm013969e2015-04-13 20:29:47 -0700325 int currentCharPos = getCurrentCharPos();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700326 if (currentCharPos == -1) {
327 // Suppressing decimal point; still showing all
328 // integral digits.
329 currentCharPos = 0;
330 }
331 // TODO: Could handle scientific notation cases better;
332 // We currently treat those conservatively as approximate.
333 return (currentCharPos >= BoundedRational.digitsRequired(rat));
334 }
335
336 // May be called asynchronously from non-UI thread.
Hans Boehm84614952014-11-25 18:46:17 -0800337 int getMaxChars() {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700338 // We only use 2/3 of the available space, since the
339 // left 1/3 of the result is not visible when it is shown
340 // in large size.
341 int result;
342 synchronized(mWidthLock) {
343 result = 2 * mWidthConstraint / (3 * mCharWidth);
344 // We can apparently finish evaluating before
Hans Boehm08e8f322015-04-21 13:18:38 -0700345 // onMeasure in CalculatorText has been called, in
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700346 // which case we get 0 or -1 as the width constraint.
347 }
Hans Boehm84614952014-11-25 18:46:17 -0800348 if (result <= 0) {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700349 // Return something conservatively big, to force sufficient
350 // evaluation.
351 return MAX_WIDTH;
Hans Boehm84614952014-11-25 18:46:17 -0800352 } else {
353 return result;
354 }
355 }
356
Hans Boehm013969e2015-04-13 20:29:47 -0700357 int getCurrentCharPos() {
358 synchronized(mWidthLock) {
359 return mCurrentPos/mCharWidth;
360 }
361 }
362
Hans Boehm84614952014-11-25 18:46:17 -0800363 void clear() {
Hans Boehm760a9dc2015-04-20 10:27:12 -0700364 mValid = false;
Hans Boehm84614952014-11-25 18:46:17 -0800365 setText("");
366 }
367
368 void redisplay() {
Hans Boehm013969e2015-04-13 20:29:47 -0700369 int currentCharPos = getCurrentCharPos();
Hans Boehm84614952014-11-25 18:46:17 -0800370 int maxChars = getMaxChars();
Hans Boehm08e8f322015-04-21 13:18:38 -0700371 String result = getFormattedResult(currentCharPos, maxChars);
Hans Boehm84614952014-11-25 18:46:17 -0800372 int epos = result.indexOf('e');
Hans Boehm013969e2015-04-13 20:29:47 -0700373 result = KeyMaps.translateResult(result);
Hans Boehm84614952014-11-25 18:46:17 -0800374 if (epos > 0 && result.indexOf('.') == -1) {
375 // Gray out exponent if used as position indicator
376 SpannableString formattedResult = new SpannableString(result);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700377 formattedResult.setSpan(new ForegroundColorSpan(Color.LTGRAY),
Hans Boehm84614952014-11-25 18:46:17 -0800378 epos, result.length(),
379 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
380 setText(formattedResult);
381 } else {
382 setText(result);
383 }
Hans Boehm760a9dc2015-04-20 10:27:12 -0700384 mValid = true;
Hans Boehm84614952014-11-25 18:46:17 -0800385 mScrollable = true;
386 }
387
388 @Override
389 public void computeScroll() {
390 if (!mScrollable) return;
391 if (mScroller.computeScrollOffset()) {
392 mCurrentPos = mScroller.getCurrX();
393 if (mCurrentPos != mLastPos) {
394 mLastPos = mCurrentPos;
395 redisplay();
396 }
397 if (!mScroller.isFinished()) {
398 ViewCompat.postInvalidateOnAnimation(this);
399 }
400 }
401 }
402
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700403 // Copy support:
404
405 private ActionMode.Callback mCopyActionModeCallback =
406 new ActionMode.Callback() {
407 @Override
408 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
409 MenuInflater inflater = mode.getMenuInflater();
410 inflater.inflate(R.menu.copy, menu);
411 return true;
412 }
413
414 @Override
415 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
416 return false; // Return false if nothing is done
417 }
418
419 @Override
420 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
421 switch (item.getItemId()) {
422 case R.id.menu_copy:
423 copyContent();
424 mode.finish();
425 return true;
426 default:
427 return false;
428 }
429 }
430
431 @Override
432 public void onDestroyActionMode(ActionMode mode) {
433 }
434 };
435
436 private void setPrimaryClip(ClipData clip) {
437 ClipboardManager clipboard = (ClipboardManager) getContext().
438 getSystemService(Context.CLIPBOARD_SERVICE);
439 clipboard.setPrimaryClip(clip);
440 }
441
442 private void copyContent() {
443 final CharSequence text = getFullText();
444 ClipboardManager clipboard =
445 (ClipboardManager) getContext().getSystemService(
446 Context.CLIPBOARD_SERVICE);
447 // We include a tag URI, to allow us to recognize our
448 // own results and handle them specially.
449 ClipData.Item newItem = new ClipData.Item(text, null,
450 mEvaluator.capture());
451 String[] mimeTypes =
452 new String[] {ClipDescription.MIMETYPE_TEXT_PLAIN};
453 ClipData cd = new ClipData("calculator result",
454 mimeTypes, newItem);
455 clipboard.setPrimaryClip(cd);
456 Toast.makeText(getContext(), R.string.text_copied_toast,
457 Toast.LENGTH_SHORT).show();
458 }
459
Hans Boehm84614952014-11-25 18:46:17 -0800460}