blob: 7752525529fb15d223d8ff1b5d5cc7fcd5fe6d58 [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.ClipData;
20import android.content.ClipDescription;
Justin Klaassen44595162015-05-28 17:55:20 -070021import android.content.ClipboardManager;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070022import android.content.Context;
Justin Klaassen44595162015-05-28 17:55:20 -070023import android.text.Layout;
Hans Boehm84614952014-11-25 18:46:17 -080024import android.text.SpannableString;
Hans Boehm1176f232015-05-11 16:26:03 -070025import android.text.Spanned;
Justin Klaassen44595162015-05-28 17:55:20 -070026import android.text.TextPaint;
Hans Boehm84614952014-11-25 18:46:17 -080027import android.text.style.ForegroundColorSpan;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070028import android.util.AttributeSet;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070029import android.view.ActionMode;
30import android.view.GestureDetector;
31import android.view.Menu;
32import android.view.MenuInflater;
33import android.view.MenuItem;
34import android.view.MotionEvent;
35import android.view.View;
Justin Klaassen44595162015-05-28 17:55:20 -070036import android.widget.OverScroller;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070037import android.widget.Toast;
Hans Boehm84614952014-11-25 18:46:17 -080038
Hans Boehm84614952014-11-25 18:46:17 -080039// A text widget that is "infinitely" scrollable to the right,
40// and obtains the text to display via a callback to Logic.
Justin Klaassen44595162015-05-28 17:55:20 -070041public class CalculatorResult extends AlignedTextView {
Hans Boehm61568a12015-05-18 18:25:41 -070042 static final int MAX_RIGHT_SCROLL = 10000000;
Hans Boehm08e8f322015-04-21 13:18:38 -070043 static final int INVALID = MAX_RIGHT_SCROLL + 10000;
Hans Boehm84614952014-11-25 18:46:17 -080044 // A larger value is unlikely to avoid running out of space
45 final OverScroller mScroller;
46 final GestureDetector mGestureDetector;
47 class MyTouchListener implements View.OnTouchListener {
48 @Override
49 public boolean onTouch(View v, MotionEvent event) {
Justin Klaassen44595162015-05-28 17:55:20 -070050 return mGestureDetector.onTouchEvent(event);
Hans Boehm84614952014-11-25 18:46:17 -080051 }
52 }
53 final MyTouchListener mTouchListener = new MyTouchListener();
54 private Evaluator mEvaluator;
55 private boolean mScrollable = false;
56 // A scrollable result is currently displayed.
Hans Boehm760a9dc2015-04-20 10:27:12 -070057 private boolean mValid = false;
Hans Boehmc01cd7f2015-05-12 18:32:19 -070058 // The result holds something valid; either a a number or an error
59 // message.
60 private int mCurrentPos;// Position of right of display relative to decimal point, in pixels.
61 // Large positive values mean the decimal point is scrolled off the
62 // left of the display. Zero means decimal point is barely displayed
63 // on the right.
Hans Boehm61568a12015-05-18 18:25:41 -070064 private int mLastPos; // Position already reflected in display. Pixels.
65 private int mMinPos; // Minimum position before all digits disappear off the right. Pixels.
66 private int mMaxPos; // Maximum position before we start displaying the infinite
67 // sequence of trailing zeroes on the right. Pixels.
Hans Boehma0e45f32015-05-30 13:20:35 -070068 private int mMaxCharPos; // The same, but in characters.
69 private int mLsd; // Position of least-significant digit in result
70 // (1 = tenths, -1 = tens), or Integer.MAX_VALUE.
Justin Klaassen44595162015-05-28 17:55:20 -070071 private final Object mWidthLock = new Object();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070072 // Protects the next two fields.
73 private int mWidthConstraint = -1;
Hans Boehma0e45f32015-05-30 13:20:35 -070074 // Our total width in pixels minus space for ellipsis.
Justin Klaassen44595162015-05-28 17:55:20 -070075 private float mCharWidth = 1;
Hans Boehmc01cd7f2015-05-12 18:32:19 -070076 // Maximum character width. For now we pretend that all characters
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070077 // have this width.
Hans Boehmc01cd7f2015-05-12 18:32:19 -070078 // TODO: We're not really using a fixed width font. But it appears
79 // to be close enough for the characters we use that the difference
80 // is not noticeable.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070081 private static final int MAX_WIDTH = 100;
82 // Maximum number of digits displayed
Hans Boehma0e45f32015-05-30 13:20:35 -070083 private static final int MAX_LEADING_ZEROES = 6;
84 // Maximum number of leading zeroes after decimal point before we
85 // switch to scientific notation with negative exponent.
86 private static final int MAX_TRAILING_ZEROES = 6;
87 // Maximum number of trailing zeroes before the decimal point before
88 // we switch to scientific notation with positive exponent.
89 private static final int SCI_NOTATION_EXTRA = 1;
90 // Extra digits for standard scientific notation. In this case we
91 // have a deecimal point and no ellipsis.
Hans Boehm1176f232015-05-11 16:26:03 -070092 private ActionMode mActionMode;
93 private final ForegroundColorSpan mExponentColorSpan;
Hans Boehm84614952014-11-25 18:46:17 -080094
95 public CalculatorResult(Context context, AttributeSet attrs) {
96 super(context, attrs);
97 mScroller = new OverScroller(context);
98 mGestureDetector = new GestureDetector(context,
99 new GestureDetector.SimpleOnGestureListener() {
100 @Override
Justin Klaassend48b7562015-04-16 16:51:38 -0700101 public boolean onDown(MotionEvent e) {
102 return true;
103 }
104 @Override
Hans Boehm84614952014-11-25 18:46:17 -0800105 public boolean onFling(MotionEvent e1, MotionEvent e2,
106 float velocityX, float velocityY) {
107 if (!mScroller.isFinished()) {
108 mCurrentPos = mScroller.getFinalX();
109 }
110 mScroller.forceFinished(true);
Hans Boehm1176f232015-05-11 16:26:03 -0700111 stopActionMode();
Hans Boehmfbcef702015-04-27 18:07:47 -0700112 CalculatorResult.this.cancelLongPress();
113 // Ignore scrolls of error string, etc.
114 if (!mScrollable) return true;
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700115 mScroller.fling(mCurrentPos, 0, - (int) velocityX, 0 /* horizontal only */,
Hans Boehm61568a12015-05-18 18:25:41 -0700116 mMinPos, mMaxPos, 0, 0);
Justin Klaassen44595162015-05-28 17:55:20 -0700117 postInvalidateOnAnimation();
Hans Boehm84614952014-11-25 18:46:17 -0800118 return true;
119 }
120 @Override
121 public boolean onScroll(MotionEvent e1, MotionEvent e2,
122 float distanceX, float distanceY) {
Hans Boehm61568a12015-05-18 18:25:41 -0700123 int distance = (int)distanceX;
Hans Boehm84614952014-11-25 18:46:17 -0800124 if (!mScroller.isFinished()) {
125 mCurrentPos = mScroller.getFinalX();
126 }
127 mScroller.forceFinished(true);
Hans Boehm1176f232015-05-11 16:26:03 -0700128 stopActionMode();
Hans Boehm84614952014-11-25 18:46:17 -0800129 CalculatorResult.this.cancelLongPress();
130 if (!mScrollable) return true;
Hans Boehm61568a12015-05-18 18:25:41 -0700131 if (mCurrentPos + distance < mMinPos) {
132 distance = mMinPos - mCurrentPos;
133 } else if (mCurrentPos + distance > mMaxPos) {
134 distance = mMaxPos - mCurrentPos;
135 }
Hans Boehm84614952014-11-25 18:46:17 -0800136 int duration = (int)(e2.getEventTime() - e1.getEventTime());
137 if (duration < 1 || duration > 100) duration = 10;
Hans Boehm61568a12015-05-18 18:25:41 -0700138 mScroller.startScroll(mCurrentPos, 0, distance, 0, (int)duration);
Justin Klaassen44595162015-05-28 17:55:20 -0700139 postInvalidateOnAnimation();
Hans Boehm84614952014-11-25 18:46:17 -0800140 return true;
141 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700142 @Override
143 public void onLongPress(MotionEvent e) {
Hans Boehm1176f232015-05-11 16:26:03 -0700144 if (mValid) {
145 mActionMode = startActionMode(mCopyActionModeCallback,
146 ActionMode.TYPE_FLOATING);
147 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700148 }
Hans Boehm84614952014-11-25 18:46:17 -0800149 });
150 setOnTouchListener(mTouchListener);
151 setHorizontallyScrolling(false); // do it ourselves
152 setCursorVisible(false);
Hans Boehm1176f232015-05-11 16:26:03 -0700153 mExponentColorSpan = new ForegroundColorSpan(
154 context.getColor(R.color.display_result_exponent_text_color));
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700155
156 // Copy ActionMode is triggered explicitly, not through
157 // setCustomSelectionActionModeCallback.
Hans Boehm84614952014-11-25 18:46:17 -0800158 }
159
160 void setEvaluator(Evaluator evaluator) {
161 mEvaluator = evaluator;
162 }
163
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700164 @Override
165 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
166 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
167
Justin Klaassen44595162015-05-28 17:55:20 -0700168 final TextPaint paint = getPaint();
169 final int newWidthConstraint = MeasureSpec.getSize(widthMeasureSpec)
170 - (getPaddingLeft() + getPaddingRight())
171 - (int) Math.ceil(Layout.getDesiredWidth(KeyMaps.ELLIPSIS, paint));
172 final float newCharWidth = Layout.getDesiredWidth("\u2007", paint);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700173 synchronized(mWidthLock) {
Hans Boehm013969e2015-04-13 20:29:47 -0700174 mWidthConstraint = newWidthConstraint;
175 mCharWidth = newCharWidth;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700176 }
177 }
178
Hans Boehma0e45f32015-05-30 13:20:35 -0700179 // Return the length of the exponent representation for the given exponent, in
180 // characters.
181 private final int expLen(int exp) {
182 if (exp == 0) return 0;
183 return (int)Math.ceil(Math.log10(Math.abs((double)exp))) + (exp >= 0 ? 1 : 2);
Hans Boehm61568a12015-05-18 18:25:41 -0700184 }
185
Hans Boehma0e45f32015-05-30 13:20:35 -0700186 /**
187 * Initiate display of a new result.
188 * The parameters specify various properties of the result.
189 * @param initPrec Initial display precision computed by evaluator. (1 = tenths digit)
190 * @param msd Position of most significant digit. Offset from left of string.
191 Evaluator.INVALID_MSD if unknown.
192 * @param leastDigPos Position of least significant digit (1 = tenths digit)
193 * or Integer.MAX_VALUE.
194 * @param truncatedWholePart Result up to but not including decimal point.
195 Currently we only use the length.
196 */
197 void displayResult(int initPrec, int msd, int leastDigPos, String truncatedWholePart) {
198 initPositions(initPrec, msd, leastDigPos, truncatedWholePart);
Hans Boehm84614952014-11-25 18:46:17 -0800199 redisplay();
200 }
201
Hans Boehma0e45f32015-05-30 13:20:35 -0700202 /**
203 * Set up scroll bounds and determine whether the result is scrollable, based on the
204 * supplied information about the result.
205 * This is unfortunately complicated because we need to predict whether trailing digits
206 * will eventually be replaced by an exponent.
207 * Just appending the exponent during formatting would be simpler, but would produce
208 * jumpier results during transitions.
209 */
210 private void initPositions(int initPrec, int msd, int leastDigPos, String truncatedWholePart) {
211 float charWidth;
212 int maxChars = getMaxChars();
213 mLastPos = INVALID;
214 mLsd = leastDigPos;
215 synchronized(mWidthLock) {
216 charWidth = mCharWidth;
217 }
218 mCurrentPos = mMinPos = (int) Math.round(initPrec * charWidth);
219 // Prevent scrolling past initial position, which is calculated to show leading digits.
220 if (msd == Evaluator.INVALID_MSD) {
221 // Possible zero value
222 if (leastDigPos == Integer.MIN_VALUE) {
223 // Definite zero value.
224 mMaxPos = mMinPos;
225 mMaxCharPos = (int) Math.round(mMaxPos/charWidth);
226 mScrollable = false;
227 } else {
228 // May be very small nonzero value. Allow user to find out.
229 mMaxPos = mMaxCharPos = MAX_RIGHT_SCROLL;
230 mScrollable = true;
231 }
232 return;
233 }
234 int wholeLen = truncatedWholePart.length();
235 int negative = truncatedWholePart.charAt(0) == '-' ? 1 : 0;
236 boolean adjustedForExp = false; // Adjusted for normal exponent.
237 if (msd > wholeLen && msd <= wholeLen + 3) {
238 // Avoid tiny negative exponent; pretend msd is just to the right of decimal point.
239 msd = wholeLen - 1;
240 }
241 int minCharPos = msd - negative - wholeLen;
242 // Position of leftmost significant digit relative to dec. point.
243 // Usually negative.
244 mMaxCharPos = MAX_RIGHT_SCROLL; // How far does it make sense to scroll right?
245 // If msd is left of decimal point should logically be
246 // mMinPos = - (int) Math.ceil(getPaint().measureText(truncatedWholePart)), but
247 // we eventually translate to a character position by dividing by mCharWidth.
248 // To avoid rounding issues, we use the analogous computation here.
249 if (minCharPos > -1 && minCharPos < MAX_LEADING_ZEROES + 2) {
250 // Small number of leading zeroes, avoid scientific notation.
251 minCharPos = -1;
252 }
253 if (leastDigPos < MAX_RIGHT_SCROLL) {
254 mMaxCharPos = leastDigPos;
255 if (mMaxCharPos < -1 && mMaxCharPos > -(MAX_TRAILING_ZEROES + 2)) {
256 mMaxCharPos = -1;
257 }
258 // leastDigPos is positive or negative, never 0.
259 if (mMaxCharPos < -1) {
260 // Number entirely to left of decimal point.
261 // We'll need a positive exponent or displayed zeros to display entire number.
262 mMaxCharPos = Math.min(-1, mMaxCharPos + expLen(-minCharPos - 1));
263 if (mMaxCharPos >= -1) {
264 // Unlikely; huge exponent.
265 mMaxCharPos = -1;
266 } else {
267 adjustedForExp = true;
268 }
269 } else if (minCharPos > -1 || mMaxCharPos >= maxChars) {
270 // Number either entirely to the right of decimal point, or decimal point not
271 // visible when scrolled to the right.
272 // We will need an exponent when looking at the rightmost digit.
273 // Allow additional scrolling to make room.
274 mMaxCharPos += expLen(-(minCharPos + 1));
275 adjustedForExp = true;
276 // Assumed an exponent for standard scientific notation for now.
277 // Adjusted below if necessary.
278 }
279 mScrollable = (mMaxCharPos - minCharPos + negative >= maxChars);
280 if (mScrollable) {
281 if (adjustedForExp) {
282 // We may need a slightly larger negative exponent while scrolling.
283 mMaxCharPos += expLen(-leastDigPos) - expLen(-(minCharPos + 1));
284 }
285 }
286 mMaxPos = Math.min((int) Math.round(mMaxCharPos * charWidth), MAX_RIGHT_SCROLL);
287 if (!mScrollable) {
288 // Position the number consistently with our assumptions to make sure it
289 // actually fits.
290 mCurrentPos = mMaxPos;
291 }
292 } else {
293 mMaxPos = mMaxCharPos = MAX_RIGHT_SCROLL;
294 mScrollable = true;
295 }
296 }
297
Hans Boehm84614952014-11-25 18:46:17 -0800298 void displayError(int resourceId) {
Hans Boehm760a9dc2015-04-20 10:27:12 -0700299 mValid = true;
Hans Boehm84614952014-11-25 18:46:17 -0800300 mScrollable = false;
301 setText(resourceId);
302 }
303
Hans Boehm013969e2015-04-13 20:29:47 -0700304 private final int MAX_COPY_SIZE = 1000000;
305
Hans Boehma0e45f32015-05-30 13:20:35 -0700306 /*
307 * Return the most significant digit position in the given string or Evaluator.INVALID_MSD.
308 * Unlike Evaluator.getMsdPos, we treat a final 1 as significant.
309 */
310 public static int getNaiveMsdPos(String s) {
311 int len = s.length();
312 int nonzeroPos = -1;
313 for (int i = 0; i < len; ++i) {
314 char c = s.charAt(i);
315 if (c != '-' && c != '.' && c != '0') {
316 return i;
317 }
318 }
319 return Evaluator.INVALID_MSD;
320 }
321
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700322 // Format a result returned by Evaluator.getString() into a single line containing ellipses
Hans Boehma0e45f32015-05-30 13:20:35 -0700323 // (if appropriate) and an exponent (if appropriate). prec is the value that was passed to
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700324 // getString and thus identifies the significance of the rightmost digit.
Hans Boehma0e45f32015-05-30 13:20:35 -0700325 // A value of 1 means the rightmost digits corresponds to tenths.
326 // maxDigs is the maximum number of characters in the result.
Hans Boehm08e8f322015-04-21 13:18:38 -0700327 // We add two distinct kinds of exponents:
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700328 // 1) If the final result contains the leading digit we use standard scientific notation.
329 // 2) If not, we add an exponent corresponding to an interpretation of the final result as
330 // an integer.
Hans Boehm08e8f322015-04-21 13:18:38 -0700331 // We add an ellipsis on the left if the result was truncated.
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700332 // We add ellipses and exponents in a way that leaves most digits in the position they
333 // would have been in had we not done so.
334 // This minimizes jumps as a result of scrolling. Result is NOT internationalized,
335 // uses "e" for exponent.
Hans Boehma0e45f32015-05-30 13:20:35 -0700336 public String formatResult(String res, int prec,
Hans Boehm08e8f322015-04-21 13:18:38 -0700337 int maxDigs, boolean truncated,
338 boolean negative) {
Hans Boehma0e45f32015-05-30 13:20:35 -0700339 int msd; // Position of most significant digit in res or indication its outside res.
340 int minusSpace = negative ? 1 : 0;
Hans Boehm08e8f322015-04-21 13:18:38 -0700341 if (truncated) {
342 res = KeyMaps.ELLIPSIS + res.substring(1, res.length());
Hans Boehma0e45f32015-05-30 13:20:35 -0700343 msd = -1;
344 } else {
345 msd = getNaiveMsdPos(res); // INVALID_MSD is OK and is treated as large.
Hans Boehm08e8f322015-04-21 13:18:38 -0700346 }
347 int decIndex = res.indexOf('.');
348 int resLen = res.length();
Hans Boehma0e45f32015-05-30 13:20:35 -0700349 if ((decIndex == -1 || msd != Evaluator.INVALID_MSD
350 && msd - decIndex > MAX_LEADING_ZEROES + 1) && prec != -1) {
351 // No decimal point displayed, and it's not just to the right of the last digit,
352 // or we should suppress leading zeroes.
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700353 // Add an exponent to let the user track which digits are currently displayed.
354 // This is a bit tricky, since the number of displayed digits affects the displayed
355 // exponent, which can affect the room we have for mantissa digits. We occasionally
356 // display one digit too few. This is sometimes unavoidable, but we could
Hans Boehm08e8f322015-04-21 13:18:38 -0700357 // avoid it in more cases.
Hans Boehma0e45f32015-05-30 13:20:35 -0700358 int exp = prec > 0 ? -prec : -prec - 1;
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700359 // Can be used as TYPE (2) EXPONENT. -1 accounts for decimal point.
Hans Boehm08e8f322015-04-21 13:18:38 -0700360 boolean hasPoint = false;
Hans Boehma0e45f32015-05-30 13:20:35 -0700361 if (msd < maxDigs - 1 && msd >= 0 &&
362 resLen - msd + 1 /* dec. pt. */ + minusSpace <= maxDigs + SCI_NOTATION_EXTRA) {
Hans Boehm08e8f322015-04-21 13:18:38 -0700363 // TYPE (1) EXPONENT computation and transformation:
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700364 // Leading digit is in display window. Use standard calculator scientific notation
365 // with one digit to the left of the decimal point. Insert decimal point and
366 // delete leading zeroes.
Hans Boehma0e45f32015-05-30 13:20:35 -0700367 // We try to keep leading digits roughly in position, and never
368 // lengthen the result by more than SCI_NOT_EXTRA.
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700369 String fraction = res.substring(msd + 1, resLen);
Hans Boehma0e45f32015-05-30 13:20:35 -0700370 res = (negative ? "-" : "") + res.substring(msd, msd + 1) + "." + fraction;
Hans Boehm08e8f322015-04-21 13:18:38 -0700371 exp += resLen - msd - 1;
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700372 // Original exp was correct for decimal point at right of fraction.
373 // Adjust by length of fraction.
Hans Boehm08e8f322015-04-21 13:18:38 -0700374 resLen = res.length();
375 hasPoint = true;
376 }
377 if (exp != 0 || truncated) {
378 // Actually add the exponent of either type:
379 String expAsString = Integer.toString(exp);
380 int expDigits = expAsString.length();
381 int dropDigits = expDigits + 1;
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700382 // Drop digits even if there is room. Otherwise the scrolling gets jumpy.
Hans Boehm08e8f322015-04-21 13:18:38 -0700383 if (dropDigits >= resLen - 1) {
384 dropDigits = Math.max(resLen - 2, 0);
Hans Boehma0e45f32015-05-30 13:20:35 -0700385 // Jumpy is better than no mantissa. Probably impossible anyway.
Hans Boehm08e8f322015-04-21 13:18:38 -0700386 }
387 if (!hasPoint) {
388 // Special handling for TYPE(2) EXPONENT:
389 exp += dropDigits;
390 expAsString = Integer.toString(exp);
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700391 // Adjust for digits we are about to drop to drop to make room for exponent.
392 // This can affect the room we have for the mantissa. We adjust only for
393 // positive exponents, when it could otherwise result in a truncated
Hans Boehm08e8f322015-04-21 13:18:38 -0700394 // displayed result.
395 if (exp > 0 && expAsString.length() > expDigits) {
396 // ++expDigits; (dead code)
397 ++dropDigits;
398 ++exp;
Hans Boehma0e45f32015-05-30 13:20:35 -0700399 expAsString = Integer.toString(exp);
Hans Boehm08e8f322015-04-21 13:18:38 -0700400 // This cannot increase the length a second time.
401 }
Hans Boehma0e45f32015-05-30 13:20:35 -0700402 if (prec - dropDigits > mLsd) {
403 // This can happen if e.g. result = 10^40 + 10^10
404 // It turns out we would otherwise display ...10e9 because
405 // it takes the same amount of space as ...1e10 but shows one more digit.
406 // But we don't want to display a trailing zero, even if it's free.
407 ++dropDigits;
408 ++exp;
409 expAsString = Integer.toString(exp);
410 }
Hans Boehm08e8f322015-04-21 13:18:38 -0700411 }
412 res = res.substring(0, resLen - dropDigits);
413 res = res + "e" + expAsString;
414 } // else don't add zero exponent
415 }
416 return res;
417 }
418
419 // Get formatted, but not internationalized, result from
420 // mEvaluator.
421 private String getFormattedResult(int pos, int maxSize) {
422 final boolean truncated[] = new boolean[1];
423 final boolean negative[] = new boolean[1];
424 final int requested_prec[] = {pos};
Hans Boehma0e45f32015-05-30 13:20:35 -0700425 final String raw_res = mEvaluator.getString(requested_prec, mMaxCharPos,
426 maxSize, truncated, negative);
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700427 return formatResult(raw_res, requested_prec[0], maxSize, truncated[0], negative[0]);
Hans Boehm08e8f322015-04-21 13:18:38 -0700428 }
429
Hans Boehm84614952014-11-25 18:46:17 -0800430 // Return entire result (within reason) up to current displayed precision.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700431 public String getFullText() {
Hans Boehm760a9dc2015-04-20 10:27:12 -0700432 if (!mValid) return "";
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700433 if (!mScrollable) return getText().toString();
Hans Boehm013969e2015-04-13 20:29:47 -0700434 int currentCharPos = getCurrentCharPos();
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700435 return KeyMaps.translateResult(getFormattedResult(currentCharPos, MAX_COPY_SIZE));
Hans Boehm84614952014-11-25 18:46:17 -0800436 }
437
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700438 public boolean fullTextIsExact() {
439 BoundedRational rat = mEvaluator.getRational();
Hans Boehm013969e2015-04-13 20:29:47 -0700440 int currentCharPos = getCurrentCharPos();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700441 if (currentCharPos == -1) {
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700442 // Suppressing decimal point; still showing all integral digits.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700443 currentCharPos = 0;
444 }
445 // TODO: Could handle scientific notation cases better;
446 // We currently treat those conservatively as approximate.
447 return (currentCharPos >= BoundedRational.digitsRequired(rat));
448 }
449
Hans Boehm61568a12015-05-18 18:25:41 -0700450 /**
451 * Return the maximum number of characters that will fit in the result display.
452 * May be called asynchronously from non-UI thread.
453 */
Hans Boehm84614952014-11-25 18:46:17 -0800454 int getMaxChars() {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700455 int result;
456 synchronized(mWidthLock) {
Justin Klaassen44595162015-05-28 17:55:20 -0700457 result = (int) Math.floor(mWidthConstraint / mCharWidth);
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700458 // We can apparently finish evaluating before onMeasure in CalculatorText has been
459 // called, in which case we get 0 or -1 as the width constraint.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700460 }
Hans Boehm84614952014-11-25 18:46:17 -0800461 if (result <= 0) {
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700462 // Return something conservatively big, to force sufficient evaluation.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700463 return MAX_WIDTH;
Hans Boehm84614952014-11-25 18:46:17 -0800464 } else {
Justin Klaassen44595162015-05-28 17:55:20 -0700465 // Always allow for the ellipsis character which already accounted for in the width
466 // constraint.
467 return result + 1;
Hans Boehm84614952014-11-25 18:46:17 -0800468 }
469 }
470
Hans Boehm61568a12015-05-18 18:25:41 -0700471 /**
Justin Klaassen44595162015-05-28 17:55:20 -0700472 * @return {@code true} if the currently displayed result is scrollable
Hans Boehm61568a12015-05-18 18:25:41 -0700473 */
Justin Klaassen44595162015-05-28 17:55:20 -0700474 public boolean isScrollable() {
475 return mScrollable;
Hans Boehm61568a12015-05-18 18:25:41 -0700476 }
477
Hans Boehm013969e2015-04-13 20:29:47 -0700478 int getCurrentCharPos() {
479 synchronized(mWidthLock) {
Hans Boehma0e45f32015-05-30 13:20:35 -0700480 return (int) Math.round(mCurrentPos / mCharWidth);
Hans Boehm013969e2015-04-13 20:29:47 -0700481 }
482 }
483
Hans Boehm84614952014-11-25 18:46:17 -0800484 void clear() {
Hans Boehm760a9dc2015-04-20 10:27:12 -0700485 mValid = false;
Hans Boehm1176f232015-05-11 16:26:03 -0700486 mScrollable = false;
Hans Boehm84614952014-11-25 18:46:17 -0800487 setText("");
488 }
489
490 void redisplay() {
Hans Boehm013969e2015-04-13 20:29:47 -0700491 int currentCharPos = getCurrentCharPos();
Hans Boehm84614952014-11-25 18:46:17 -0800492 int maxChars = getMaxChars();
Hans Boehm08e8f322015-04-21 13:18:38 -0700493 String result = getFormattedResult(currentCharPos, maxChars);
Hans Boehm84614952014-11-25 18:46:17 -0800494 int epos = result.indexOf('e');
Hans Boehm013969e2015-04-13 20:29:47 -0700495 result = KeyMaps.translateResult(result);
Hans Boehm84614952014-11-25 18:46:17 -0800496 if (epos > 0 && result.indexOf('.') == -1) {
497 // Gray out exponent if used as position indicator
498 SpannableString formattedResult = new SpannableString(result);
Hans Boehm1176f232015-05-11 16:26:03 -0700499 formattedResult.setSpan(mExponentColorSpan, epos, result.length(),
Hans Boehm84614952014-11-25 18:46:17 -0800500 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
501 setText(formattedResult);
502 } else {
503 setText(result);
504 }
Hans Boehm760a9dc2015-04-20 10:27:12 -0700505 mValid = true;
Hans Boehm84614952014-11-25 18:46:17 -0800506 }
507
508 @Override
509 public void computeScroll() {
510 if (!mScrollable) return;
511 if (mScroller.computeScrollOffset()) {
512 mCurrentPos = mScroller.getCurrX();
513 if (mCurrentPos != mLastPos) {
514 mLastPos = mCurrentPos;
515 redisplay();
516 }
517 if (!mScroller.isFinished()) {
Justin Klaassen44595162015-05-28 17:55:20 -0700518 postInvalidateOnAnimation();
Hans Boehm84614952014-11-25 18:46:17 -0800519 }
520 }
521 }
522
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700523 // Copy support:
524
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700525 private ActionMode.Callback mCopyActionModeCallback = new ActionMode.Callback() {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700526 @Override
527 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
528 MenuInflater inflater = mode.getMenuInflater();
529 inflater.inflate(R.menu.copy, menu);
530 return true;
531 }
532
533 @Override
534 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
535 return false; // Return false if nothing is done
536 }
537
538 @Override
539 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
540 switch (item.getItemId()) {
541 case R.id.menu_copy:
542 copyContent();
543 mode.finish();
544 return true;
545 default:
546 return false;
547 }
548 }
549
550 @Override
551 public void onDestroyActionMode(ActionMode mode) {
Hans Boehm1176f232015-05-11 16:26:03 -0700552 mActionMode = null;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700553 }
554 };
555
Hans Boehm1176f232015-05-11 16:26:03 -0700556 public boolean stopActionMode() {
557 if (mActionMode != null) {
558 mActionMode.finish();
559 return true;
560 }
561 return false;
562 }
563
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700564 private void setPrimaryClip(ClipData clip) {
565 ClipboardManager clipboard = (ClipboardManager) getContext().
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700566 getSystemService(Context.CLIPBOARD_SERVICE);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700567 clipboard.setPrimaryClip(clip);
568 }
569
570 private void copyContent() {
571 final CharSequence text = getFullText();
572 ClipboardManager clipboard =
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700573 (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
574 // We include a tag URI, to allow us to recognize our own results and handle them
575 // specially.
576 ClipData.Item newItem = new ClipData.Item(text, null, mEvaluator.capture());
577 String[] mimeTypes = new String[] {ClipDescription.MIMETYPE_TEXT_PLAIN};
578 ClipData cd = new ClipData("calculator result", mimeTypes, newItem);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700579 clipboard.setPrimaryClip(cd);
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700580 Toast.makeText(getContext(), R.string.text_copied_toast, Toast.LENGTH_SHORT).show();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700581 }
582
Hans Boehm84614952014-11-25 18:46:17 -0800583}