blob: 72c3b548b1ffd0bc7592877333e26c2012c3d196 [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);
Hans Boehmfbcef702015-04-27 18:07:47 -0700110 CalculatorResult.this.cancelLongPress();
111 // Ignore scrolls of error string, etc.
112 if (!mScrollable) return true;
Hans Boehm84614952014-11-25 18:46:17 -0800113 mScroller.fling(mCurrentPos, 0, - (int) velocityX,
114 0 /* horizontal only */, mMinPos,
115 MAX_RIGHT_SCROLL, 0, 0);
116 ViewCompat.postInvalidateOnAnimation(CalculatorResult.this);
117 return true;
118 }
119 @Override
120 public boolean onScroll(MotionEvent e1, MotionEvent e2,
121 float distanceX, float distanceY) {
122 // TODO: Should we be dealing with any edge effects here?
123 if (!mScroller.isFinished()) {
124 mCurrentPos = mScroller.getFinalX();
125 }
126 mScroller.forceFinished(true);
127 CalculatorResult.this.cancelLongPress();
128 if (!mScrollable) return true;
129 int duration = (int)(e2.getEventTime() - e1.getEventTime());
130 if (duration < 1 || duration > 100) duration = 10;
131 mScroller.startScroll(mCurrentPos, 0, (int)distanceX, 0,
132 (int)duration);
133 ViewCompat.postInvalidateOnAnimation(CalculatorResult.this);
134 return true;
135 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700136 @Override
137 public void onLongPress(MotionEvent e) {
Hans Boehmfbcef702015-04-27 18:07:47 -0700138 startActionMode(mCopyActionModeCallback,
139 ActionMode.TYPE_FLOATING);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700140 }
Hans Boehm84614952014-11-25 18:46:17 -0800141 });
142 setOnTouchListener(mTouchListener);
143 setHorizontallyScrolling(false); // do it ourselves
144 setCursorVisible(false);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700145
146 // Copy ActionMode is triggered explicitly, not through
147 // setCustomSelectionActionModeCallback.
Hans Boehm84614952014-11-25 18:46:17 -0800148 }
149
150 void setEvaluator(Evaluator evaluator) {
151 mEvaluator = evaluator;
152 }
153
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700154 @Override
155 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
156 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
157
Hans Boehm013969e2015-04-13 20:29:47 -0700158 char testChar = KeyMaps.translateResult("5").charAt(0);
159 // TODO: Redo on Locale change? Doesn't seem to matter?
160 // We try to determine the maximal size of a digit plus
161 // corresponding inter-character space.
162 // We assume that "5" has maximal width. Since any
163 // string includes one fewer inter-character space than
164 // characters, me measure one that's longer than any real
165 // display string, and then divide by the number of characters.
166 // This should bound the per-character space we need for any
167 // real string.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700168 StringBuilder sb = new StringBuilder(MAX_WIDTH);
169 for (int i = 0; i < MAX_WIDTH; ++i) {
Hans Boehm013969e2015-04-13 20:29:47 -0700170 sb.append(testChar);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700171 }
Hans Boehm013969e2015-04-13 20:29:47 -0700172 final int newWidthConstraint =
173 MeasureSpec.getSize(widthMeasureSpec)
174 - getPaddingLeft() - getPaddingRight();
175 final int newCharWidth =
Hans Boehmc5e6e152015-04-22 12:06:29 -0700176 (int)Math.ceil(getPaint().measureText(sb.toString())
177 / MAX_WIDTH);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700178 synchronized(mWidthLock) {
Hans Boehm013969e2015-04-13 20:29:47 -0700179 mWidthConstraint = newWidthConstraint;
180 mCharWidth = newCharWidth;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700181 }
182 }
183
Hans Boehm84614952014-11-25 18:46:17 -0800184 // Display a new result, given initial displayed
185 // precision and the string representing the whole part of
186 // the number to be displayed.
187 // We pass the string, instead of just the length, so we have
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700188 // one less place to fix in case we ever decide to
189 // correctly use a variable width font.
Hans Boehm84614952014-11-25 18:46:17 -0800190 void displayResult(int initPrec, String truncatedWholePart) {
191 mLastPos = INVALID;
Hans Boehm013969e2015-04-13 20:29:47 -0700192 synchronized(mWidthLock) {
193 mCurrentPos = initPrec * mCharWidth;
194 }
Hans Boehmc5e6e152015-04-22 12:06:29 -0700195 mMinPos = - (int) Math.ceil(getPaint().measureText(truncatedWholePart));
Hans Boehm84614952014-11-25 18:46:17 -0800196 redisplay();
197 }
198
Hans Boehm84614952014-11-25 18:46:17 -0800199 void displayError(int resourceId) {
Hans Boehm760a9dc2015-04-20 10:27:12 -0700200 mValid = true;
Hans Boehm84614952014-11-25 18:46:17 -0800201 mScrollable = false;
202 setText(resourceId);
203 }
204
Hans Boehm013969e2015-04-13 20:29:47 -0700205 private final int MAX_COPY_SIZE = 1000000;
206
Hans Boehm08e8f322015-04-21 13:18:38 -0700207 // Format a result returned by Evaluator.getString() into a single
208 // line containing ellipses (if appropriate) and an exponent
209 // (if appropriate). digs is the value that was passed to
210 // getString and thus identifies the significance of the
211 // rightmost digit.
212 // We add two distinct kinds of exponents:
213 // 1) If the final result contains the leading digit we use standard
214 // scientific notation.
215 // 2) If not, we add an exponent corresponding to an interpretation
216 // of the final result as an integer.
217 // We add an ellipsis on the left if the result was truncated.
218 // We add ellipses and exponents in a way that leaves most digits
219 // in the position they would have been in had we not done so.
220 // This minimizes jumps as a result of scrolling.
221 // Result is NOT internationalized, uses "e" for exponent.
222 // last_included[0] is set to the position of the last digit we
223 // actually include; thus caller can tell whether result is exact.
224 public String formatResult(String res, int digs,
225 int maxDigs, boolean truncated,
226 boolean negative) {
227 if (truncated) {
228 res = KeyMaps.ELLIPSIS + res.substring(1, res.length());
229 }
230 int decIndex = res.indexOf('.');
231 int resLen = res.length();
232 if (decIndex == -1 && digs != -1) {
233 // No decimal point displayed, and it's not just
234 // to the right of the last digit.
235 // Add an exponent to let the user track which
236 // digits are currently displayed.
237 // This is a bit tricky, since the number of displayed
238 // digits affects the displayed exponent, which can
239 // affect the room we have for mantissa digits.
240 // We occasionally display one digit too few.
241 // This is sometimes unavoidable, but we could
242 // avoid it in more cases.
243 int exp = digs > 0 ? -digs : -digs - 1;
244 // Can be used as TYPE (2) EXPONENT.
245 // -1 accounts for decimal point.
246 int msd; // Position of most significant digit in res
247 // or indication its outside res.
248 boolean hasPoint = false;
249 if (truncated) {
250 msd = -1;
251 } else {
252 msd = Evaluator.getMsdPos(res); // INVALID_MSD is OK
253 }
254 if (msd < maxDigs - 1 && msd >= 0) {
255 // TYPE (1) EXPONENT computation and transformation:
256 // Leading digit is in display window.
257 // Use standard calculator scientific notation
258 // with one digit to the left of the decimal point.
259 // Insert decimal point and delete leading zeroes.
260 String fraction = res.substring(msd + 1, resLen);
261 res = (negative ? "-" : "")
262 + res.substring(msd, msd+1) + "." + fraction;
263 exp += resLen - msd - 1;
264 // Original exp was correct for decimal point at right
265 // of fraction. Adjust by length of fraction.
266 resLen = res.length();
267 hasPoint = true;
268 }
269 if (exp != 0 || truncated) {
270 // Actually add the exponent of either type:
271 String expAsString = Integer.toString(exp);
272 int expDigits = expAsString.length();
273 int dropDigits = expDigits + 1;
274 // Drop digits even if there is room.
275 // Otherwise the scrolling gets jumpy.
276 if (dropDigits >= resLen - 1) {
277 dropDigits = Math.max(resLen - 2, 0);
278 // Jumpy is better than no mantissa.
279 }
280 if (!hasPoint) {
281 // Special handling for TYPE(2) EXPONENT:
282 exp += dropDigits;
283 expAsString = Integer.toString(exp);
284 // Adjust for digits we are about to drop
285 // to drop to make room for exponent.
286 // This can affect the room we have for the
287 // mantissa. We adjust only for positive exponents,
288 // when it could otherwise result in a truncated
289 // displayed result.
290 if (exp > 0 && expAsString.length() > expDigits) {
291 // ++expDigits; (dead code)
292 ++dropDigits;
293 ++exp;
294 // This cannot increase the length a second time.
295 }
296 }
297 res = res.substring(0, resLen - dropDigits);
298 res = res + "e" + expAsString;
299 } // else don't add zero exponent
300 }
301 return res;
302 }
303
304 // Get formatted, but not internationalized, result from
305 // mEvaluator.
306 private String getFormattedResult(int pos, int maxSize) {
307 final boolean truncated[] = new boolean[1];
308 final boolean negative[] = new boolean[1];
309 final int requested_prec[] = {pos};
310 final String raw_res = mEvaluator.getString(requested_prec, maxSize,
311 truncated, negative);
312 return formatResult(raw_res, requested_prec[0], maxSize,
313 truncated[0], negative[0]);
314 }
315
Hans Boehm84614952014-11-25 18:46:17 -0800316 // Return entire result (within reason) up to current displayed precision.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700317 public String getFullText() {
Hans Boehm760a9dc2015-04-20 10:27:12 -0700318 if (!mValid) return "";
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700319 if (!mScrollable) return getText().toString();
Hans Boehm013969e2015-04-13 20:29:47 -0700320 int currentCharPos = getCurrentCharPos();
321 return KeyMaps.translateResult(
Hans Boehm08e8f322015-04-21 13:18:38 -0700322 getFormattedResult(currentCharPos, MAX_COPY_SIZE));
Hans Boehm84614952014-11-25 18:46:17 -0800323 }
324
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700325 public boolean fullTextIsExact() {
326 BoundedRational rat = mEvaluator.getRational();
Hans Boehm013969e2015-04-13 20:29:47 -0700327 int currentCharPos = getCurrentCharPos();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700328 if (currentCharPos == -1) {
329 // Suppressing decimal point; still showing all
330 // integral digits.
331 currentCharPos = 0;
332 }
333 // TODO: Could handle scientific notation cases better;
334 // We currently treat those conservatively as approximate.
335 return (currentCharPos >= BoundedRational.digitsRequired(rat));
336 }
337
338 // May be called asynchronously from non-UI thread.
Hans Boehm84614952014-11-25 18:46:17 -0800339 int getMaxChars() {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700340 // We only use 2/3 of the available space, since the
341 // left 1/3 of the result is not visible when it is shown
342 // in large size.
343 int result;
344 synchronized(mWidthLock) {
345 result = 2 * mWidthConstraint / (3 * mCharWidth);
346 // We can apparently finish evaluating before
Hans Boehm08e8f322015-04-21 13:18:38 -0700347 // onMeasure in CalculatorText has been called, in
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700348 // which case we get 0 or -1 as the width constraint.
349 }
Hans Boehm84614952014-11-25 18:46:17 -0800350 if (result <= 0) {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700351 // Return something conservatively big, to force sufficient
352 // evaluation.
353 return MAX_WIDTH;
Hans Boehm84614952014-11-25 18:46:17 -0800354 } else {
355 return result;
356 }
357 }
358
Hans Boehm013969e2015-04-13 20:29:47 -0700359 int getCurrentCharPos() {
360 synchronized(mWidthLock) {
361 return mCurrentPos/mCharWidth;
362 }
363 }
364
Hans Boehm84614952014-11-25 18:46:17 -0800365 void clear() {
Hans Boehm760a9dc2015-04-20 10:27:12 -0700366 mValid = false;
Hans Boehm84614952014-11-25 18:46:17 -0800367 setText("");
368 }
369
370 void redisplay() {
Hans Boehm013969e2015-04-13 20:29:47 -0700371 int currentCharPos = getCurrentCharPos();
Hans Boehm84614952014-11-25 18:46:17 -0800372 int maxChars = getMaxChars();
Hans Boehm08e8f322015-04-21 13:18:38 -0700373 String result = getFormattedResult(currentCharPos, maxChars);
Hans Boehm84614952014-11-25 18:46:17 -0800374 int epos = result.indexOf('e');
Hans Boehm013969e2015-04-13 20:29:47 -0700375 result = KeyMaps.translateResult(result);
Hans Boehm84614952014-11-25 18:46:17 -0800376 if (epos > 0 && result.indexOf('.') == -1) {
377 // Gray out exponent if used as position indicator
378 SpannableString formattedResult = new SpannableString(result);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700379 formattedResult.setSpan(new ForegroundColorSpan(Color.LTGRAY),
Hans Boehm84614952014-11-25 18:46:17 -0800380 epos, result.length(),
381 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
382 setText(formattedResult);
383 } else {
384 setText(result);
385 }
Hans Boehm760a9dc2015-04-20 10:27:12 -0700386 mValid = true;
Hans Boehm84614952014-11-25 18:46:17 -0800387 mScrollable = true;
388 }
389
390 @Override
391 public void computeScroll() {
392 if (!mScrollable) return;
393 if (mScroller.computeScrollOffset()) {
394 mCurrentPos = mScroller.getCurrX();
395 if (mCurrentPos != mLastPos) {
396 mLastPos = mCurrentPos;
397 redisplay();
398 }
399 if (!mScroller.isFinished()) {
400 ViewCompat.postInvalidateOnAnimation(this);
401 }
402 }
403 }
404
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700405 // Copy support:
406
407 private ActionMode.Callback mCopyActionModeCallback =
408 new ActionMode.Callback() {
409 @Override
410 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
411 MenuInflater inflater = mode.getMenuInflater();
412 inflater.inflate(R.menu.copy, menu);
413 return true;
414 }
415
416 @Override
417 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
418 return false; // Return false if nothing is done
419 }
420
421 @Override
422 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
423 switch (item.getItemId()) {
424 case R.id.menu_copy:
425 copyContent();
426 mode.finish();
427 return true;
428 default:
429 return false;
430 }
431 }
432
433 @Override
434 public void onDestroyActionMode(ActionMode mode) {
435 }
436 };
437
438 private void setPrimaryClip(ClipData clip) {
439 ClipboardManager clipboard = (ClipboardManager) getContext().
440 getSystemService(Context.CLIPBOARD_SERVICE);
441 clipboard.setPrimaryClip(clip);
442 }
443
444 private void copyContent() {
445 final CharSequence text = getFullText();
446 ClipboardManager clipboard =
447 (ClipboardManager) getContext().getSystemService(
448 Context.CLIPBOARD_SERVICE);
449 // We include a tag URI, to allow us to recognize our
450 // own results and handle them specially.
451 ClipData.Item newItem = new ClipData.Item(text, null,
452 mEvaluator.capture());
453 String[] mimeTypes =
454 new String[] {ClipDescription.MIMETYPE_TEXT_PLAIN};
455 ClipData cd = new ClipData("calculator result",
456 mimeTypes, newItem);
457 clipboard.setPrimaryClip(cd);
458 Toast.makeText(getContext(), R.string.text_copied_toast,
459 Toast.LENGTH_SHORT).show();
460 }
461
Hans Boehm84614952014-11-25 18:46:17 -0800462}