blob: bfad8b43ad64aece44b55667848d0a15dca6890c [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;
Hans Boehm7f83e362015-06-10 15:41:04 -070023import android.graphics.Rect;
Justin Klaassen44595162015-05-28 17:55:20 -070024import android.text.Layout;
Hans Boehm7f83e362015-06-10 15:41:04 -070025import android.text.Spannable;
Hans Boehm84614952014-11-25 18:46:17 -080026import android.text.SpannableString;
Hans Boehm1176f232015-05-11 16:26:03 -070027import android.text.Spanned;
Justin Klaassen44595162015-05-28 17:55:20 -070028import android.text.TextPaint;
Hans Boehm7f83e362015-06-10 15:41:04 -070029import android.text.style.BackgroundColorSpan;
Hans Boehm84614952014-11-25 18:46:17 -080030import android.text.style.ForegroundColorSpan;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070031import android.util.AttributeSet;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070032import android.view.ActionMode;
33import android.view.GestureDetector;
34import android.view.Menu;
35import android.view.MenuInflater;
36import android.view.MenuItem;
37import android.view.MotionEvent;
38import android.view.View;
Justin Klaassen44595162015-05-28 17:55:20 -070039import android.widget.OverScroller;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070040import android.widget.Toast;
Hans Boehm84614952014-11-25 18:46:17 -080041
Hans Boehm84614952014-11-25 18:46:17 -080042// A text widget that is "infinitely" scrollable to the right,
43// and obtains the text to display via a callback to Logic.
Justin Klaassen44595162015-05-28 17:55:20 -070044public class CalculatorResult extends AlignedTextView {
Hans Boehm61568a12015-05-18 18:25:41 -070045 static final int MAX_RIGHT_SCROLL = 10000000;
Hans Boehm08e8f322015-04-21 13:18:38 -070046 static final int INVALID = MAX_RIGHT_SCROLL + 10000;
Hans Boehm84614952014-11-25 18:46:17 -080047 // A larger value is unlikely to avoid running out of space
48 final OverScroller mScroller;
49 final GestureDetector mGestureDetector;
Hans Boehm84614952014-11-25 18:46:17 -080050 private Evaluator mEvaluator;
51 private boolean mScrollable = false;
52 // A scrollable result is currently displayed.
Hans Boehm760a9dc2015-04-20 10:27:12 -070053 private boolean mValid = false;
Hans Boehmc01cd7f2015-05-12 18:32:19 -070054 // The result holds something valid; either a a number or an error
55 // message.
Hans Boehm5e802f32015-06-22 17:18:52 -070056 // A suffix of "Pos" denotes a pixel offset. Zero represents a scroll position
57 // in which the decimal point is just barely visible on the right of the display.
Hans Boehmc01cd7f2015-05-12 18:32:19 -070058 private int mCurrentPos;// Position of right of display relative to decimal point, in pixels.
59 // Large positive values mean the decimal point is scrolled off the
60 // left of the display. Zero means decimal point is barely displayed
61 // on the right.
Hans Boehm61568a12015-05-18 18:25:41 -070062 private int mLastPos; // Position already reflected in display. Pixels.
63 private int mMinPos; // Minimum position before all digits disappear off the right. Pixels.
64 private int mMaxPos; // Maximum position before we start displaying the infinite
65 // sequence of trailing zeroes on the right. Pixels.
Hans Boehm5e802f32015-06-22 17:18:52 -070066 // In the following, we use a suffix of Offset to denote a character position in a numeric
67 // string relative to the decimal point. Positive is to the right and negative is to
68 // the left. 1 = tenths position, -1 = units. Integer.MAX_VALUE is sometimes used
69 // for the offset of the last digit in an a nonterminating decimal expansion.
70 // We use the suffix "Index" to denote a zero-based index into a string representing a
71 // result.
72 // TODO: Apply the same convention to other classes.
73 private int mMaxCharOffset; // Character offset from decimal point of rightmost digit
74 // that should be displayed. Essentially the same as
75 private int mLsdOffset; // Position of least-significant digit in result
76 private int mLastDisplayedOffset; // Offset of last digit actually displayed after adding
Hans Boehmf6dae112015-06-18 17:57:50 -070077 // exponent.
Justin Klaassen44595162015-05-28 17:55:20 -070078 private final Object mWidthLock = new Object();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070079 // Protects the next two fields.
80 private int mWidthConstraint = -1;
Hans Boehma0e45f32015-05-30 13:20:35 -070081 // Our total width in pixels minus space for ellipsis.
Justin Klaassen44595162015-05-28 17:55:20 -070082 private float mCharWidth = 1;
Hans Boehmc01cd7f2015-05-12 18:32:19 -070083 // Maximum character width. For now we pretend that all characters
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070084 // have this width.
Hans Boehmc01cd7f2015-05-12 18:32:19 -070085 // TODO: We're not really using a fixed width font. But it appears
86 // to be close enough for the characters we use that the difference
87 // is not noticeable.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070088 private static final int MAX_WIDTH = 100;
89 // Maximum number of digits displayed
Hans Boehm50ed3202015-06-09 14:35:49 -070090 public static final int MAX_LEADING_ZEROES = 6;
Hans Boehma0e45f32015-05-30 13:20:35 -070091 // Maximum number of leading zeroes after decimal point before we
92 // switch to scientific notation with negative exponent.
Hans Boehm50ed3202015-06-09 14:35:49 -070093 public static final int MAX_TRAILING_ZEROES = 6;
Hans Boehma0e45f32015-05-30 13:20:35 -070094 // Maximum number of trailing zeroes before the decimal point before
95 // we switch to scientific notation with positive exponent.
96 private static final int SCI_NOTATION_EXTRA = 1;
97 // Extra digits for standard scientific notation. In this case we
Hans Boehm80018c82015-08-02 16:59:07 -070098 // have a decimal point and no ellipsis.
99 // We assume that we do not drop digits to make room for the decimal
100 // point in ordinary scientific notation. Thus >= 1.
Hans Boehm1176f232015-05-11 16:26:03 -0700101 private ActionMode mActionMode;
102 private final ForegroundColorSpan mExponentColorSpan;
Hans Boehm84614952014-11-25 18:46:17 -0800103
104 public CalculatorResult(Context context, AttributeSet attrs) {
105 super(context, attrs);
106 mScroller = new OverScroller(context);
107 mGestureDetector = new GestureDetector(context,
108 new GestureDetector.SimpleOnGestureListener() {
109 @Override
Justin Klaassend48b7562015-04-16 16:51:38 -0700110 public boolean onDown(MotionEvent e) {
111 return true;
112 }
113 @Override
Hans Boehm84614952014-11-25 18:46:17 -0800114 public boolean onFling(MotionEvent e1, MotionEvent e2,
115 float velocityX, float velocityY) {
116 if (!mScroller.isFinished()) {
117 mCurrentPos = mScroller.getFinalX();
118 }
119 mScroller.forceFinished(true);
Hans Boehm1176f232015-05-11 16:26:03 -0700120 stopActionMode();
Hans Boehmfbcef702015-04-27 18:07:47 -0700121 CalculatorResult.this.cancelLongPress();
122 // Ignore scrolls of error string, etc.
123 if (!mScrollable) return true;
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700124 mScroller.fling(mCurrentPos, 0, - (int) velocityX, 0 /* horizontal only */,
Hans Boehm61568a12015-05-18 18:25:41 -0700125 mMinPos, mMaxPos, 0, 0);
Justin Klaassen44595162015-05-28 17:55:20 -0700126 postInvalidateOnAnimation();
Hans Boehm84614952014-11-25 18:46:17 -0800127 return true;
128 }
129 @Override
130 public boolean onScroll(MotionEvent e1, MotionEvent e2,
131 float distanceX, float distanceY) {
Hans Boehm61568a12015-05-18 18:25:41 -0700132 int distance = (int)distanceX;
Hans Boehm84614952014-11-25 18:46:17 -0800133 if (!mScroller.isFinished()) {
134 mCurrentPos = mScroller.getFinalX();
135 }
136 mScroller.forceFinished(true);
Hans Boehm1176f232015-05-11 16:26:03 -0700137 stopActionMode();
Hans Boehm84614952014-11-25 18:46:17 -0800138 CalculatorResult.this.cancelLongPress();
139 if (!mScrollable) return true;
Hans Boehm61568a12015-05-18 18:25:41 -0700140 if (mCurrentPos + distance < mMinPos) {
141 distance = mMinPos - mCurrentPos;
142 } else if (mCurrentPos + distance > mMaxPos) {
143 distance = mMaxPos - mCurrentPos;
144 }
Hans Boehm84614952014-11-25 18:46:17 -0800145 int duration = (int)(e2.getEventTime() - e1.getEventTime());
146 if (duration < 1 || duration > 100) duration = 10;
Hans Boehm61568a12015-05-18 18:25:41 -0700147 mScroller.startScroll(mCurrentPos, 0, distance, 0, (int)duration);
Justin Klaassen44595162015-05-28 17:55:20 -0700148 postInvalidateOnAnimation();
Hans Boehm84614952014-11-25 18:46:17 -0800149 return true;
150 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700151 @Override
152 public void onLongPress(MotionEvent e) {
Hans Boehm1176f232015-05-11 16:26:03 -0700153 if (mValid) {
Justin Klaassen3a05c7e2016-03-04 12:40:02 -0800154 performLongClick();
Hans Boehm1176f232015-05-11 16:26:03 -0700155 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700156 }
Hans Boehm84614952014-11-25 18:46:17 -0800157 });
Justin Klaassen3a05c7e2016-03-04 12:40:02 -0800158 setOnTouchListener(new View.OnTouchListener() {
159 @Override
160 public boolean onTouch(View v, MotionEvent event) {
161 return mGestureDetector.onTouchEvent(event);
162 }
163 });
164 setOnLongClickListener(new View.OnLongClickListener() {
165 @Override
166 public boolean onLongClick(View v) {
167 if (mValid) {
168 mActionMode = startActionMode(mCopyActionModeCallback,
169 ActionMode.TYPE_FLOATING);
170 return true;
171 }
172 return false;
173 }
174 });
Hans Boehm84614952014-11-25 18:46:17 -0800175 setHorizontallyScrolling(false); // do it ourselves
176 setCursorVisible(false);
Hans Boehm1176f232015-05-11 16:26:03 -0700177 mExponentColorSpan = new ForegroundColorSpan(
178 context.getColor(R.color.display_result_exponent_text_color));
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700179
180 // Copy ActionMode is triggered explicitly, not through
181 // setCustomSelectionActionModeCallback.
Hans Boehm84614952014-11-25 18:46:17 -0800182 }
183
184 void setEvaluator(Evaluator evaluator) {
185 mEvaluator = evaluator;
186 }
187
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700188 @Override
189 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
190 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
191
Justin Klaassen44595162015-05-28 17:55:20 -0700192 final TextPaint paint = getPaint();
Hans Boehm80018c82015-08-02 16:59:07 -0700193 final Context context = getContext();
Justin Klaassen44595162015-05-28 17:55:20 -0700194 final float newCharWidth = Layout.getDesiredWidth("\u2007", paint);
Hans Boehm80018c82015-08-02 16:59:07 -0700195 // Digits are presumed to have no more than newCharWidth.
196 // We sometimes replace a character by an ellipsis or, due to SCI_NOTATION_EXTRA, add
197 // an extra decimal separator beyond the maximum number of characters we normally allow.
198 // Empirically, our minus sign is also slightly wider than a digit, so we have to
199 // account for that. We never have both an ellipsis and two minus signs, and
200 // we assume an ellipsis is no narrower than a minus sign.
201 final float decimalSeparatorWidth = Layout.getDesiredWidth(
202 context.getString(R.string.dec_point), paint);
203 final float minusExtraWidth = Layout.getDesiredWidth(
204 context.getString(R.string.op_sub), paint) - newCharWidth;
205 final float ellipsisExtraWidth = Layout.getDesiredWidth(KeyMaps.ELLIPSIS, paint)
206 - newCharWidth;
207 final int extraWidth = (int) (Math.ceil(Math.max(decimalSeparatorWidth + minusExtraWidth,
208 ellipsisExtraWidth)) + Math.max(minusExtraWidth, 0.0f));
209 final int newWidthConstraint = MeasureSpec.getSize(widthMeasureSpec)
210 - (getPaddingLeft() + getPaddingRight()) - extraWidth;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700211 synchronized(mWidthLock) {
Hans Boehm013969e2015-04-13 20:29:47 -0700212 mWidthConstraint = newWidthConstraint;
213 mCharWidth = newCharWidth;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700214 }
215 }
216
Hans Boehma0e45f32015-05-30 13:20:35 -0700217 // Return the length of the exponent representation for the given exponent, in
218 // characters.
219 private final int expLen(int exp) {
220 if (exp == 0) return 0;
Hans Boehm5e802f32015-06-22 17:18:52 -0700221 final int abs_exp_digits = (int) Math.ceil(Math.log10(Math.abs((double)exp))
222 + 0.0000000001d /* Round whole numbers to next integer */);
223 return abs_exp_digits + (exp >= 0 ? 1 : 2);
Hans Boehm61568a12015-05-18 18:25:41 -0700224 }
225
Hans Boehma0e45f32015-05-30 13:20:35 -0700226 /**
227 * Initiate display of a new result.
228 * The parameters specify various properties of the result.
229 * @param initPrec Initial display precision computed by evaluator. (1 = tenths digit)
230 * @param msd Position of most significant digit. Offset from left of string.
231 Evaluator.INVALID_MSD if unknown.
232 * @param leastDigPos Position of least significant digit (1 = tenths digit)
233 * or Integer.MAX_VALUE.
234 * @param truncatedWholePart Result up to but not including decimal point.
235 Currently we only use the length.
236 */
237 void displayResult(int initPrec, int msd, int leastDigPos, String truncatedWholePart) {
238 initPositions(initPrec, msd, leastDigPos, truncatedWholePart);
Hans Boehm84614952014-11-25 18:46:17 -0800239 redisplay();
240 }
241
Hans Boehma0e45f32015-05-30 13:20:35 -0700242 /**
Hans Boehm5e802f32015-06-22 17:18:52 -0700243 * Set up scroll bounds (mMinPos, mMaxPos, etc.) and determine whether the result is
244 * scrollable, based on the supplied information about the result.
Hans Boehma0e45f32015-05-30 13:20:35 -0700245 * This is unfortunately complicated because we need to predict whether trailing digits
246 * will eventually be replaced by an exponent.
247 * Just appending the exponent during formatting would be simpler, but would produce
248 * jumpier results during transitions.
249 */
Hans Boehm5e802f32015-06-22 17:18:52 -0700250 private void initPositions(int initPrecOffset, int msdIndex, int lsdOffset,
251 String truncatedWholePart) {
Hans Boehma0e45f32015-05-30 13:20:35 -0700252 float charWidth;
253 int maxChars = getMaxChars();
254 mLastPos = INVALID;
Hans Boehm5e802f32015-06-22 17:18:52 -0700255 mLsdOffset = lsdOffset;
Hans Boehma0e45f32015-05-30 13:20:35 -0700256 synchronized(mWidthLock) {
257 charWidth = mCharWidth;
258 }
Hans Boehm5e802f32015-06-22 17:18:52 -0700259 mCurrentPos = mMinPos = (int) Math.round(initPrecOffset * charWidth);
Hans Boehma0e45f32015-05-30 13:20:35 -0700260 // Prevent scrolling past initial position, which is calculated to show leading digits.
Hans Boehm5e802f32015-06-22 17:18:52 -0700261 if (msdIndex == Evaluator.INVALID_MSD) {
Hans Boehma0e45f32015-05-30 13:20:35 -0700262 // Possible zero value
Hans Boehm5e802f32015-06-22 17:18:52 -0700263 if (lsdOffset == Integer.MIN_VALUE) {
Hans Boehma0e45f32015-05-30 13:20:35 -0700264 // Definite zero value.
265 mMaxPos = mMinPos;
Hans Boehm5e802f32015-06-22 17:18:52 -0700266 mMaxCharOffset = (int) Math.round(mMaxPos/charWidth);
Hans Boehma0e45f32015-05-30 13:20:35 -0700267 mScrollable = false;
268 } else {
269 // May be very small nonzero value. Allow user to find out.
Hans Boehm5e802f32015-06-22 17:18:52 -0700270 mMaxPos = mMaxCharOffset = MAX_RIGHT_SCROLL;
271 mMinPos -= charWidth; // Allow for future minus sign.
Hans Boehma0e45f32015-05-30 13:20:35 -0700272 mScrollable = true;
273 }
274 return;
275 }
276 int wholeLen = truncatedWholePart.length();
277 int negative = truncatedWholePart.charAt(0) == '-' ? 1 : 0;
Hans Boehm5e802f32015-06-22 17:18:52 -0700278 if (msdIndex > wholeLen && msdIndex <= wholeLen + 3) {
279 // Avoid tiny negative exponent; pretend msdIndex is just to the right of decimal point.
280 msdIndex = wholeLen - 1;
Hans Boehma0e45f32015-05-30 13:20:35 -0700281 }
Hans Boehm5e802f32015-06-22 17:18:52 -0700282 int minCharOffset = msdIndex - wholeLen;
Hans Boehma0e45f32015-05-30 13:20:35 -0700283 // Position of leftmost significant digit relative to dec. point.
284 // Usually negative.
Hans Boehm5e802f32015-06-22 17:18:52 -0700285 mMaxCharOffset = MAX_RIGHT_SCROLL; // How far does it make sense to scroll right?
Hans Boehma0e45f32015-05-30 13:20:35 -0700286 // If msd is left of decimal point should logically be
287 // mMinPos = - (int) Math.ceil(getPaint().measureText(truncatedWholePart)), but
288 // we eventually translate to a character position by dividing by mCharWidth.
289 // To avoid rounding issues, we use the analogous computation here.
Hans Boehm5e802f32015-06-22 17:18:52 -0700290 if (minCharOffset > -1 && minCharOffset < MAX_LEADING_ZEROES + 2) {
Hans Boehma0e45f32015-05-30 13:20:35 -0700291 // Small number of leading zeroes, avoid scientific notation.
Hans Boehm5e802f32015-06-22 17:18:52 -0700292 minCharOffset = -1;
Hans Boehma0e45f32015-05-30 13:20:35 -0700293 }
Hans Boehm5e802f32015-06-22 17:18:52 -0700294 if (lsdOffset < MAX_RIGHT_SCROLL) {
295 mMaxCharOffset = lsdOffset;
296 if (mMaxCharOffset < -1 && mMaxCharOffset > -(MAX_TRAILING_ZEROES + 2)) {
297 mMaxCharOffset = -1;
Hans Boehma0e45f32015-05-30 13:20:35 -0700298 }
Hans Boehm5e802f32015-06-22 17:18:52 -0700299 // lsdOffset is positive or negative, never 0.
300 int currentExpLen = 0; // Length of required standard scientific notation exponent.
301 if (mMaxCharOffset < -1) {
302 currentExpLen = expLen(-minCharOffset - 1);
303 } else if (minCharOffset > -1 || mMaxCharOffset >= maxChars) {
Hans Boehma0e45f32015-05-30 13:20:35 -0700304 // Number either entirely to the right of decimal point, or decimal point not
305 // visible when scrolled to the right.
Hans Boehm5e802f32015-06-22 17:18:52 -0700306 currentExpLen = expLen(-minCharOffset);
Hans Boehma0e45f32015-05-30 13:20:35 -0700307 }
Hans Boehm5e802f32015-06-22 17:18:52 -0700308 mScrollable = (mMaxCharOffset + currentExpLen - minCharOffset + negative >= maxChars);
309 int newMaxCharOffset;
310 if (currentExpLen > 0) {
311 if (mScrollable) {
312 // We'll use exponent corresponding to leastDigPos when scrolled to right.
313 newMaxCharOffset = mMaxCharOffset + expLen(-lsdOffset);
314 } else {
315 newMaxCharOffset = mMaxCharOffset + currentExpLen;
316 }
317 if (mMaxCharOffset <= -1 && newMaxCharOffset > -1) {
318 // Very unlikely; just drop exponent.
319 mMaxCharOffset = -1;
320 } else {
321 mMaxCharOffset = newMaxCharOffset;
Hans Boehma0e45f32015-05-30 13:20:35 -0700322 }
323 }
Hans Boehm5e802f32015-06-22 17:18:52 -0700324 mMaxPos = Math.min((int) Math.round(mMaxCharOffset * charWidth), MAX_RIGHT_SCROLL);
Hans Boehma0e45f32015-05-30 13:20:35 -0700325 if (!mScrollable) {
326 // Position the number consistently with our assumptions to make sure it
327 // actually fits.
328 mCurrentPos = mMaxPos;
329 }
330 } else {
Hans Boehm5e802f32015-06-22 17:18:52 -0700331 mMaxPos = mMaxCharOffset = MAX_RIGHT_SCROLL;
Hans Boehma0e45f32015-05-30 13:20:35 -0700332 mScrollable = true;
333 }
334 }
335
Hans Boehm84614952014-11-25 18:46:17 -0800336 void displayError(int resourceId) {
Hans Boehm760a9dc2015-04-20 10:27:12 -0700337 mValid = true;
Hans Boehm84614952014-11-25 18:46:17 -0800338 mScrollable = false;
339 setText(resourceId);
340 }
341
Hans Boehm013969e2015-04-13 20:29:47 -0700342 private final int MAX_COPY_SIZE = 1000000;
343
Hans Boehma0e45f32015-05-30 13:20:35 -0700344 /*
345 * Return the most significant digit position in the given string or Evaluator.INVALID_MSD.
Hans Boehm3666e632015-07-27 18:33:12 -0700346 * Unlike Evaluator.getMsdIndexOf, we treat a final 1 as significant.
Hans Boehma0e45f32015-05-30 13:20:35 -0700347 */
Hans Boehm3666e632015-07-27 18:33:12 -0700348 public static int getNaiveMsdIndexOf(String s) {
Hans Boehma0e45f32015-05-30 13:20:35 -0700349 int len = s.length();
Hans Boehma0e45f32015-05-30 13:20:35 -0700350 for (int i = 0; i < len; ++i) {
351 char c = s.charAt(i);
352 if (c != '-' && c != '.' && c != '0') {
353 return i;
354 }
355 }
356 return Evaluator.INVALID_MSD;
357 }
358
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700359 // Format a result returned by Evaluator.getString() into a single line containing ellipses
Hans Boehm3666e632015-07-27 18:33:12 -0700360 // (if appropriate) and an exponent (if appropriate). precOffset is the value that was passed
361 // to getString and thus identifies the significance of the rightmost digit.
Hans Boehma0e45f32015-05-30 13:20:35 -0700362 // A value of 1 means the rightmost digits corresponds to tenths.
363 // maxDigs is the maximum number of characters in the result.
Hans Boehm5e802f32015-06-22 17:18:52 -0700364 // We set lastDisplayedOffset[0] to the offset of the last digit actually appearing in
Hans Boehmf6dae112015-06-18 17:57:50 -0700365 // the display.
366 // If forcePrecision is true, we make sure that the last displayed digit corresponds to
Hans Boehm3666e632015-07-27 18:33:12 -0700367 // precOffset, and allow maxDigs to be exceeded in assing the exponent.
Hans Boehm08e8f322015-04-21 13:18:38 -0700368 // We add two distinct kinds of exponents:
Hans Boehm5e802f32015-06-22 17:18:52 -0700369 // (1) If the final result contains the leading digit we use standard scientific notation.
370 // (2) If not, we add an exponent corresponding to an interpretation of the final result as
371 // an integer.
Hans Boehm08e8f322015-04-21 13:18:38 -0700372 // We add an ellipsis on the left if the result was truncated.
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700373 // We add ellipses and exponents in a way that leaves most digits in the position they
374 // would have been in had we not done so.
375 // This minimizes jumps as a result of scrolling. Result is NOT internationalized,
Hans Boehm0b9806f2015-06-29 16:07:15 -0700376 // uses "E" for exponent.
Hans Boehm5e802f32015-06-22 17:18:52 -0700377 public String formatResult(String in, int precOffset, int maxDigs, boolean truncated,
378 boolean negative, int lastDisplayedOffset[], boolean forcePrecision) {
379 final int minusSpace = negative ? 1 : 0;
Hans Boehm3666e632015-07-27 18:33:12 -0700380 final int msdIndex = truncated ? -1 : getNaiveMsdIndexOf(in); // INVALID_MSD is OK.
Hans Boehm5e802f32015-06-22 17:18:52 -0700381 String result = in;
Hans Boehm73ecff22015-09-03 16:04:50 -0700382 if (truncated || (negative && result.charAt(0) != '-')) {
383 result = KeyMaps.ELLIPSIS + result.substring(1, result.length());
384 // Ellipsis may be removed again in the type(1) scientific notation case.
385 }
386 final int decIndex = result.indexOf('.');
Hans Boehm5e802f32015-06-22 17:18:52 -0700387 lastDisplayedOffset[0] = precOffset;
388 if ((decIndex == -1 || msdIndex != Evaluator.INVALID_MSD
389 && msdIndex - decIndex > MAX_LEADING_ZEROES + 1) && precOffset != -1) {
Hans Boehma0e45f32015-05-30 13:20:35 -0700390 // No decimal point displayed, and it's not just to the right of the last digit,
391 // or we should suppress leading zeroes.
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700392 // Add an exponent to let the user track which digits are currently displayed.
Hans Boehm5e802f32015-06-22 17:18:52 -0700393 // Start with type (2) exponent if we dropped no digits. -1 accounts for decimal point.
394 final int initExponent = precOffset > 0 ? -precOffset : -precOffset - 1;
395 int exponent = initExponent;
Hans Boehm08e8f322015-04-21 13:18:38 -0700396 boolean hasPoint = false;
Hans Boehm5e802f32015-06-22 17:18:52 -0700397 if (!truncated && msdIndex < maxDigs - 1
398 && result.length() - msdIndex + 1 + minusSpace
399 <= maxDigs + SCI_NOTATION_EXTRA) {
400 // Type (1) exponent computation and transformation:
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700401 // Leading digit is in display window. Use standard calculator scientific notation
402 // with one digit to the left of the decimal point. Insert decimal point and
403 // delete leading zeroes.
Hans Boehma0e45f32015-05-30 13:20:35 -0700404 // We try to keep leading digits roughly in position, and never
Hans Boehmf6dae112015-06-18 17:57:50 -0700405 // lengthen the result by more than SCI_NOTATION_EXTRA.
Hans Boehm5e802f32015-06-22 17:18:52 -0700406 final int resLen = result.length();
407 String fraction = result.substring(msdIndex + 1, resLen);
408 result = (negative ? "-" : "") + result.substring(msdIndex, msdIndex + 1)
409 + "." + fraction;
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700410 // Original exp was correct for decimal point at right of fraction.
411 // Adjust by length of fraction.
Hans Boehm5e802f32015-06-22 17:18:52 -0700412 exponent = initExponent + resLen - msdIndex - 1;
Hans Boehm08e8f322015-04-21 13:18:38 -0700413 hasPoint = true;
414 }
Hans Boehm73ecff22015-09-03 16:04:50 -0700415 // Exponent can't be zero.
416 // Actually add the exponent of either type:
417 if (!forcePrecision) {
418 int dropDigits; // Digits to drop to make room for exponent.
419 if (hasPoint) {
420 // Type (1) exponent.
421 // Drop digits even if there is room. Otherwise the scrolling gets jumpy.
422 dropDigits = expLen(exponent);
423 if (dropDigits >= result.length() - 1) {
424 // Jumpy is better than no mantissa. Probably impossible anyway.
425 dropDigits = Math.max(result.length() - 2, 0);
Hans Boehma0e45f32015-05-30 13:20:35 -0700426 }
Hans Boehm73ecff22015-09-03 16:04:50 -0700427 } else {
428 // Type (2) exponent.
429 // Exponent depends on the number of digits we drop, which depends on
430 // exponent ...
431 for (dropDigits = 2; expLen(initExponent + dropDigits) > dropDigits;
432 ++dropDigits) {}
433 exponent = initExponent + dropDigits;
434 if (precOffset - dropDigits > mLsdOffset) {
435 // This can happen if e.g. result = 10^40 + 10^10
436 // It turns out we would otherwise display ...10e9 because it takes
437 // the same amount of space as ...1e10 but shows one more digit.
438 // But we don't want to display a trailing zero, even if it's free.
439 ++dropDigits;
440 ++exponent;
441 }
Hans Boehm08e8f322015-04-21 13:18:38 -0700442 }
Hans Boehm73ecff22015-09-03 16:04:50 -0700443 result = result.substring(0, result.length() - dropDigits);
444 lastDisplayedOffset[0] -= dropDigits;
445 }
446 result = result + "E" + Integer.toString(exponent);
Hans Boehm5e802f32015-06-22 17:18:52 -0700447 }
448 return result;
Hans Boehm08e8f322015-04-21 13:18:38 -0700449 }
450
Hans Boehmf6dae112015-06-18 17:57:50 -0700451 /**
452 * Get formatted, but not internationalized, result from mEvaluator.
Hans Boehm5e802f32015-06-22 17:18:52 -0700453 * @param precOffset requested position (1 = tenths) of last included digit.
Hans Boehmf6dae112015-06-18 17:57:50 -0700454 * @param maxSize Maximum number of characters (more or less) in result.
Hans Boehm5e802f32015-06-22 17:18:52 -0700455 * @param lastDisplayedOffset Zeroth entry is set to actual offset of last included digit,
456 * after adjusting for exponent, etc.
Hans Boehmf6dae112015-06-18 17:57:50 -0700457 * @param forcePrecision Ensure that last included digit is at pos, at the expense
458 * of treating maxSize as a soft limit.
459 */
Hans Boehm5e802f32015-06-22 17:18:52 -0700460 private String getFormattedResult(int precOffset, int maxSize, int lastDisplayedOffset[],
Hans Boehmf6dae112015-06-18 17:57:50 -0700461 boolean forcePrecision) {
Hans Boehm08e8f322015-04-21 13:18:38 -0700462 final boolean truncated[] = new boolean[1];
463 final boolean negative[] = new boolean[1];
Hans Boehm5e802f32015-06-22 17:18:52 -0700464 final int requestedPrecOffset[] = {precOffset};
465 final String rawResult = mEvaluator.getString(requestedPrecOffset, mMaxCharOffset,
Hans Boehma0e45f32015-05-30 13:20:35 -0700466 maxSize, truncated, negative);
Hans Boehm5e802f32015-06-22 17:18:52 -0700467 return formatResult(rawResult, requestedPrecOffset[0], maxSize, truncated[0], negative[0],
468 lastDisplayedOffset, forcePrecision);
Hans Boehm08e8f322015-04-21 13:18:38 -0700469 }
470
Hans Boehm84614952014-11-25 18:46:17 -0800471 // Return entire result (within reason) up to current displayed precision.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700472 public String getFullText() {
Hans Boehm760a9dc2015-04-20 10:27:12 -0700473 if (!mValid) return "";
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700474 if (!mScrollable) return getText().toString();
Hans Boehm5e802f32015-06-22 17:18:52 -0700475 int currentCharOffset = getCurrentCharOffset();
Hans Boehmf6dae112015-06-18 17:57:50 -0700476 int unused[] = new int[1];
Hans Boehm5e802f32015-06-22 17:18:52 -0700477 return KeyMaps.translateResult(getFormattedResult(mLastDisplayedOffset, MAX_COPY_SIZE,
Hans Boehmf6dae112015-06-18 17:57:50 -0700478 unused, true));
Hans Boehm84614952014-11-25 18:46:17 -0800479 }
480
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700481 public boolean fullTextIsExact() {
Hans Boehmf6dae112015-06-18 17:57:50 -0700482 return !mScrollable
Hans Boehm5e802f32015-06-22 17:18:52 -0700483 || mMaxCharOffset == getCurrentCharOffset() && mMaxCharOffset != MAX_RIGHT_SCROLL;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700484 }
485
Hans Boehm61568a12015-05-18 18:25:41 -0700486 /**
487 * Return the maximum number of characters that will fit in the result display.
488 * May be called asynchronously from non-UI thread.
489 */
Hans Boehm84614952014-11-25 18:46:17 -0800490 int getMaxChars() {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700491 int result;
492 synchronized(mWidthLock) {
Justin Klaassen44595162015-05-28 17:55:20 -0700493 result = (int) Math.floor(mWidthConstraint / mCharWidth);
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700494 // We can apparently finish evaluating before onMeasure in CalculatorText has been
495 // called, in which case we get 0 or -1 as the width constraint.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700496 }
Hans Boehm84614952014-11-25 18:46:17 -0800497 if (result <= 0) {
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700498 // Return something conservatively big, to force sufficient evaluation.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700499 return MAX_WIDTH;
Hans Boehm84614952014-11-25 18:46:17 -0800500 } else {
Hans Boehm80018c82015-08-02 16:59:07 -0700501 return result;
Hans Boehm84614952014-11-25 18:46:17 -0800502 }
503 }
504
Hans Boehm61568a12015-05-18 18:25:41 -0700505 /**
Justin Klaassen44595162015-05-28 17:55:20 -0700506 * @return {@code true} if the currently displayed result is scrollable
Hans Boehm61568a12015-05-18 18:25:41 -0700507 */
Justin Klaassen44595162015-05-28 17:55:20 -0700508 public boolean isScrollable() {
509 return mScrollable;
Hans Boehm61568a12015-05-18 18:25:41 -0700510 }
511
Hans Boehm5e802f32015-06-22 17:18:52 -0700512 int getCurrentCharOffset() {
Hans Boehm013969e2015-04-13 20:29:47 -0700513 synchronized(mWidthLock) {
Hans Boehma0e45f32015-05-30 13:20:35 -0700514 return (int) Math.round(mCurrentPos / mCharWidth);
Hans Boehm013969e2015-04-13 20:29:47 -0700515 }
516 }
517
Hans Boehm84614952014-11-25 18:46:17 -0800518 void clear() {
Hans Boehm760a9dc2015-04-20 10:27:12 -0700519 mValid = false;
Hans Boehm1176f232015-05-11 16:26:03 -0700520 mScrollable = false;
Hans Boehm84614952014-11-25 18:46:17 -0800521 setText("");
522 }
523
524 void redisplay() {
Hans Boehm5e802f32015-06-22 17:18:52 -0700525 int currentCharOffset = getCurrentCharOffset();
Hans Boehm84614952014-11-25 18:46:17 -0800526 int maxChars = getMaxChars();
Hans Boehm5e802f32015-06-22 17:18:52 -0700527 int lastDisplayedOffset[] = new int[1];
528 String result = getFormattedResult(currentCharOffset, maxChars, lastDisplayedOffset, false);
Hans Boehm0b9806f2015-06-29 16:07:15 -0700529 int expIndex = result.indexOf('E');
Hans Boehm013969e2015-04-13 20:29:47 -0700530 result = KeyMaps.translateResult(result);
Hans Boehm5e802f32015-06-22 17:18:52 -0700531 if (expIndex > 0 && result.indexOf('.') == -1) {
Hans Boehm84614952014-11-25 18:46:17 -0800532 // Gray out exponent if used as position indicator
533 SpannableString formattedResult = new SpannableString(result);
Hans Boehm5e802f32015-06-22 17:18:52 -0700534 formattedResult.setSpan(mExponentColorSpan, expIndex, result.length(),
Hans Boehm84614952014-11-25 18:46:17 -0800535 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
536 setText(formattedResult);
537 } else {
538 setText(result);
539 }
Hans Boehm5e802f32015-06-22 17:18:52 -0700540 mLastDisplayedOffset = lastDisplayedOffset[0];
Hans Boehm760a9dc2015-04-20 10:27:12 -0700541 mValid = true;
Hans Boehm84614952014-11-25 18:46:17 -0800542 }
543
544 @Override
545 public void computeScroll() {
546 if (!mScrollable) return;
547 if (mScroller.computeScrollOffset()) {
548 mCurrentPos = mScroller.getCurrX();
549 if (mCurrentPos != mLastPos) {
550 mLastPos = mCurrentPos;
551 redisplay();
552 }
553 if (!mScroller.isFinished()) {
Justin Klaassen44595162015-05-28 17:55:20 -0700554 postInvalidateOnAnimation();
Hans Boehm84614952014-11-25 18:46:17 -0800555 }
556 }
557 }
558
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700559 // Copy support:
560
Hans Boehm7f83e362015-06-10 15:41:04 -0700561 private ActionMode.Callback2 mCopyActionModeCallback = new ActionMode.Callback2() {
562
563 private BackgroundColorSpan mHighlightSpan;
564
565 private void highlightResult() {
566 final Spannable text = (Spannable) getText();
567 mHighlightSpan = new BackgroundColorSpan(getHighlightColor());
568 text.setSpan(mHighlightSpan, 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
569 }
570
571 private void unhighlightResult() {
572 final Spannable text = (Spannable) getText();
573 text.removeSpan(mHighlightSpan);
574 }
575
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700576 @Override
577 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
578 MenuInflater inflater = mode.getMenuInflater();
579 inflater.inflate(R.menu.copy, menu);
Hans Boehm7f83e362015-06-10 15:41:04 -0700580 highlightResult();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700581 return true;
582 }
583
584 @Override
585 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
586 return false; // Return false if nothing is done
587 }
588
589 @Override
590 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
591 switch (item.getItemId()) {
592 case R.id.menu_copy:
593 copyContent();
594 mode.finish();
595 return true;
596 default:
597 return false;
598 }
599 }
600
601 @Override
602 public void onDestroyActionMode(ActionMode mode) {
Hans Boehm7f83e362015-06-10 15:41:04 -0700603 unhighlightResult();
Hans Boehm1176f232015-05-11 16:26:03 -0700604 mActionMode = null;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700605 }
Hans Boehm7f83e362015-06-10 15:41:04 -0700606
607 @Override
608 public void onGetContentRect(ActionMode mode, View view, Rect outRect) {
609 super.onGetContentRect(mode, view, outRect);
Justin Klaassenac6a9ba2016-01-28 18:39:23 -0800610
611 outRect.left += view.getPaddingLeft();
612 outRect.top += view.getPaddingTop();
613 outRect.right -= view.getPaddingRight();
614 outRect.bottom -= view.getPaddingBottom();
Hans Boehm7f83e362015-06-10 15:41:04 -0700615 final int width = (int) Layout.getDesiredWidth(getText(), getPaint());
616 if (width < outRect.width()) {
617 outRect.left = outRect.right - width;
618 }
Justin Klaassenac6a9ba2016-01-28 18:39:23 -0800619
620 // The CAB *currently* only takes the translation of a view into account, so if a scale
621 // is applied to the view then the offset outRect will end up being positioned
622 // incorrectly. We workaround that limitation by manually applying the scale to the
623 // outRect, which the CAB will then offset to the correct position.
624 final float scaleX = view.getScaleX();
625 final float scaleY = view.getScaleY();
626 outRect.left *= scaleX;
627 outRect.right *= scaleX;
628 outRect.top *= scaleY;
629 outRect.bottom *= scaleY;
630
Hans Boehm7f83e362015-06-10 15:41:04 -0700631 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700632 };
633
Hans Boehm1176f232015-05-11 16:26:03 -0700634 public boolean stopActionMode() {
635 if (mActionMode != null) {
636 mActionMode.finish();
637 return true;
638 }
639 return false;
640 }
641
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700642 private void setPrimaryClip(ClipData clip) {
643 ClipboardManager clipboard = (ClipboardManager) getContext().
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700644 getSystemService(Context.CLIPBOARD_SERVICE);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700645 clipboard.setPrimaryClip(clip);
646 }
647
648 private void copyContent() {
649 final CharSequence text = getFullText();
650 ClipboardManager clipboard =
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700651 (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
652 // We include a tag URI, to allow us to recognize our own results and handle them
653 // specially.
654 ClipData.Item newItem = new ClipData.Item(text, null, mEvaluator.capture());
655 String[] mimeTypes = new String[] {ClipDescription.MIMETYPE_TEXT_PLAIN};
656 ClipData cd = new ClipData("calculator result", mimeTypes, newItem);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700657 clipboard.setPrimaryClip(cd);
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700658 Toast.makeText(getContext(), R.string.text_copied_toast, Toast.LENGTH_SHORT).show();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700659 }
660
Hans Boehm84614952014-11-25 18:46:17 -0800661}