blob: dc1b98052f99c8a69f9729e4920f190e662d9c50 [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
Chenjie Yu3937b652016-06-01 23:14:26 -070019import android.annotation.TargetApi;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070020import android.content.ClipData;
21import android.content.ClipDescription;
Justin Klaassen44595162015-05-28 17:55:20 -070022import android.content.ClipboardManager;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070023import android.content.Context;
Hans Boehm7f83e362015-06-10 15:41:04 -070024import android.graphics.Rect;
Chenjie Yu3937b652016-06-01 23:14:26 -070025import android.os.Build;
26import android.support.v4.content.ContextCompat;
Justin Klaassenf1b61f42016-04-27 16:00:11 -070027import android.support.v4.os.BuildCompat;
Justin Klaassen44595162015-05-28 17:55:20 -070028import android.text.Layout;
Hans Boehm7f83e362015-06-10 15:41:04 -070029import android.text.Spannable;
Hans Boehm84614952014-11-25 18:46:17 -080030import android.text.SpannableString;
Hans Boehm1176f232015-05-11 16:26:03 -070031import android.text.Spanned;
Justin Klaassen44595162015-05-28 17:55:20 -070032import android.text.TextPaint;
Hans Boehm7f83e362015-06-10 15:41:04 -070033import android.text.style.BackgroundColorSpan;
Hans Boehm84614952014-11-25 18:46:17 -080034import android.text.style.ForegroundColorSpan;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070035import android.util.AttributeSet;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070036import android.view.ActionMode;
Chenjie Yu3937b652016-06-01 23:14:26 -070037import android.view.ContextMenu;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070038import android.view.GestureDetector;
39import android.view.Menu;
40import android.view.MenuInflater;
41import android.view.MenuItem;
42import android.view.MotionEvent;
43import android.view.View;
Justin Klaassen44595162015-05-28 17:55:20 -070044import android.widget.OverScroller;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070045import android.widget.Toast;
Hans Boehm84614952014-11-25 18:46:17 -080046
Hans Boehm84614952014-11-25 18:46:17 -080047// A text widget that is "infinitely" scrollable to the right,
48// and obtains the text to display via a callback to Logic.
Chenjie Yu3937b652016-06-01 23:14:26 -070049public class CalculatorResult extends AlignedTextView implements MenuItem.OnMenuItemClickListener {
Hans Boehm61568a12015-05-18 18:25:41 -070050 static final int MAX_RIGHT_SCROLL = 10000000;
Hans Boehm08e8f322015-04-21 13:18:38 -070051 static final int INVALID = MAX_RIGHT_SCROLL + 10000;
Hans Boehm84614952014-11-25 18:46:17 -080052 // A larger value is unlikely to avoid running out of space
53 final OverScroller mScroller;
54 final GestureDetector mGestureDetector;
Hans Boehm84614952014-11-25 18:46:17 -080055 private Evaluator mEvaluator;
56 private boolean mScrollable = false;
57 // A scrollable result is currently displayed.
Hans Boehm760a9dc2015-04-20 10:27:12 -070058 private boolean mValid = false;
Hans Boehmc01cd7f2015-05-12 18:32:19 -070059 // The result holds something valid; either a a number or an error
60 // message.
Hans Boehm5e802f32015-06-22 17:18:52 -070061 // A suffix of "Pos" denotes a pixel offset. Zero represents a scroll position
62 // in which the decimal point is just barely visible on the right of the display.
Hans Boehmc01cd7f2015-05-12 18:32:19 -070063 private int mCurrentPos;// Position of right of display relative to decimal point, in pixels.
64 // Large positive values mean the decimal point is scrolled off the
65 // left of the display. Zero means decimal point is barely displayed
66 // on the right.
Hans Boehm61568a12015-05-18 18:25:41 -070067 private int mLastPos; // Position already reflected in display. Pixels.
Hans Boehm65a99a42016-02-03 18:16:07 -080068 private int mMinPos; // Minimum position to avoid unnecessary blanks on the left. Pixels.
Hans Boehm61568a12015-05-18 18:25:41 -070069 private int mMaxPos; // Maximum position before we start displaying the infinite
70 // sequence of trailing zeroes on the right. Pixels.
Hans Boehm65a99a42016-02-03 18:16:07 -080071 private int mWholeLen; // Length of the whole part of current result.
Hans Boehm5e802f32015-06-22 17:18:52 -070072 // In the following, we use a suffix of Offset to denote a character position in a numeric
73 // string relative to the decimal point. Positive is to the right and negative is to
74 // the left. 1 = tenths position, -1 = units. Integer.MAX_VALUE is sometimes used
75 // for the offset of the last digit in an a nonterminating decimal expansion.
76 // We use the suffix "Index" to denote a zero-based index into a string representing a
77 // result.
Hans Boehm5e802f32015-06-22 17:18:52 -070078 private int mMaxCharOffset; // Character offset from decimal point of rightmost digit
79 // that should be displayed. Essentially the same as
80 private int mLsdOffset; // Position of least-significant digit in result
81 private int mLastDisplayedOffset; // Offset of last digit actually displayed after adding
Hans Boehmf6dae112015-06-18 17:57:50 -070082 // exponent.
Justin Klaassen44595162015-05-28 17:55:20 -070083 private final Object mWidthLock = new Object();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070084 // Protects the next two fields.
85 private int mWidthConstraint = -1;
Hans Boehma0e45f32015-05-30 13:20:35 -070086 // Our total width in pixels minus space for ellipsis.
Justin Klaassen44595162015-05-28 17:55:20 -070087 private float mCharWidth = 1;
Hans Boehmc01cd7f2015-05-12 18:32:19 -070088 // Maximum character width. For now we pretend that all characters
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070089 // have this width.
Hans Boehmc01cd7f2015-05-12 18:32:19 -070090 // TODO: We're not really using a fixed width font. But it appears
91 // to be close enough for the characters we use that the difference
92 // is not noticeable.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070093 private static final int MAX_WIDTH = 100;
94 // Maximum number of digits displayed
Hans Boehm50ed3202015-06-09 14:35:49 -070095 public static final int MAX_LEADING_ZEROES = 6;
Hans Boehma0e45f32015-05-30 13:20:35 -070096 // Maximum number of leading zeroes after decimal point before we
97 // switch to scientific notation with negative exponent.
Hans Boehm50ed3202015-06-09 14:35:49 -070098 public static final int MAX_TRAILING_ZEROES = 6;
Hans Boehma0e45f32015-05-30 13:20:35 -070099 // Maximum number of trailing zeroes before the decimal point before
100 // we switch to scientific notation with positive exponent.
101 private static final int SCI_NOTATION_EXTRA = 1;
102 // Extra digits for standard scientific notation. In this case we
Hans Boehm80018c82015-08-02 16:59:07 -0700103 // have a decimal point and no ellipsis.
104 // We assume that we do not drop digits to make room for the decimal
105 // point in ordinary scientific notation. Thus >= 1.
Hans Boehm65a99a42016-02-03 18:16:07 -0800106 private static final int MAX_COPY_EXTRA = 100;
107 // The number of extra digits we are willing to compute to copy
108 // a result as an exact number.
109 private static final int MAX_RECOMPUTE_DIGITS = 2000;
110 // The maximum number of digits we're willing to recompute in the UI
111 // thread. We only do this for known rational results, where we
112 // can bound the computation cost.
Chenjie Yu3937b652016-06-01 23:14:26 -0700113 private final ForegroundColorSpan mExponentColorSpan;
114 private final BackgroundColorSpan mHighlightSpan;
Hans Boehm65a99a42016-02-03 18:16:07 -0800115
Hans Boehm1176f232015-05-11 16:26:03 -0700116 private ActionMode mActionMode;
Chenjie Yu3937b652016-06-01 23:14:26 -0700117 private ActionMode.Callback mCopyActionModeCallback;
118 private ContextMenu mContextMenu;
Hans Boehm84614952014-11-25 18:46:17 -0800119
120 public CalculatorResult(Context context, AttributeSet attrs) {
121 super(context, attrs);
122 mScroller = new OverScroller(context);
Chenjie Yu3937b652016-06-01 23:14:26 -0700123 mHighlightSpan = new BackgroundColorSpan(getHighlightColor());
124 mExponentColorSpan = new ForegroundColorSpan(
125 ContextCompat.getColor(context, R.color.display_result_exponent_text_color));
Hans Boehm84614952014-11-25 18:46:17 -0800126 mGestureDetector = new GestureDetector(context,
127 new GestureDetector.SimpleOnGestureListener() {
128 @Override
Justin Klaassend48b7562015-04-16 16:51:38 -0700129 public boolean onDown(MotionEvent e) {
130 return true;
131 }
132 @Override
Hans Boehm84614952014-11-25 18:46:17 -0800133 public boolean onFling(MotionEvent e1, MotionEvent e2,
134 float velocityX, float velocityY) {
135 if (!mScroller.isFinished()) {
136 mCurrentPos = mScroller.getFinalX();
137 }
138 mScroller.forceFinished(true);
Chenjie Yu3937b652016-06-01 23:14:26 -0700139 stopActionModeOrContextMenu();
Hans Boehmfbcef702015-04-27 18:07:47 -0700140 CalculatorResult.this.cancelLongPress();
141 // Ignore scrolls of error string, etc.
142 if (!mScrollable) return true;
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700143 mScroller.fling(mCurrentPos, 0, - (int) velocityX, 0 /* horizontal only */,
Hans Boehm61568a12015-05-18 18:25:41 -0700144 mMinPos, mMaxPos, 0, 0);
Justin Klaassen44595162015-05-28 17:55:20 -0700145 postInvalidateOnAnimation();
Hans Boehm84614952014-11-25 18:46:17 -0800146 return true;
147 }
148 @Override
149 public boolean onScroll(MotionEvent e1, MotionEvent e2,
150 float distanceX, float distanceY) {
Hans Boehm61568a12015-05-18 18:25:41 -0700151 int distance = (int)distanceX;
Hans Boehm84614952014-11-25 18:46:17 -0800152 if (!mScroller.isFinished()) {
153 mCurrentPos = mScroller.getFinalX();
154 }
155 mScroller.forceFinished(true);
Chenjie Yu3937b652016-06-01 23:14:26 -0700156 stopActionModeOrContextMenu();
Hans Boehm84614952014-11-25 18:46:17 -0800157 CalculatorResult.this.cancelLongPress();
158 if (!mScrollable) return true;
Hans Boehm61568a12015-05-18 18:25:41 -0700159 if (mCurrentPos + distance < mMinPos) {
160 distance = mMinPos - mCurrentPos;
161 } else if (mCurrentPos + distance > mMaxPos) {
162 distance = mMaxPos - mCurrentPos;
163 }
Hans Boehm84614952014-11-25 18:46:17 -0800164 int duration = (int)(e2.getEventTime() - e1.getEventTime());
165 if (duration < 1 || duration > 100) duration = 10;
Hans Boehm61568a12015-05-18 18:25:41 -0700166 mScroller.startScroll(mCurrentPos, 0, distance, 0, (int)duration);
Justin Klaassen44595162015-05-28 17:55:20 -0700167 postInvalidateOnAnimation();
Hans Boehm84614952014-11-25 18:46:17 -0800168 return true;
169 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700170 @Override
171 public void onLongPress(MotionEvent e) {
Hans Boehm1176f232015-05-11 16:26:03 -0700172 if (mValid) {
Justin Klaassen3a05c7e2016-03-04 12:40:02 -0800173 performLongClick();
Hans Boehm1176f232015-05-11 16:26:03 -0700174 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700175 }
Hans Boehm84614952014-11-25 18:46:17 -0800176 });
Justin Klaassen3a05c7e2016-03-04 12:40:02 -0800177 setOnTouchListener(new View.OnTouchListener() {
178 @Override
179 public boolean onTouch(View v, MotionEvent event) {
180 return mGestureDetector.onTouchEvent(event);
181 }
182 });
Chenjie Yu3937b652016-06-01 23:14:26 -0700183 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
184 setupActionMode();
185 } else {
186 setupContextMenu();
187 }
Hans Boehm84614952014-11-25 18:46:17 -0800188 setHorizontallyScrolling(false); // do it ourselves
189 setCursorVisible(false);
Hans Boehm84614952014-11-25 18:46:17 -0800190 }
191
192 void setEvaluator(Evaluator evaluator) {
193 mEvaluator = evaluator;
194 }
195
Hans Boehmcd72f7e2016-06-01 16:21:25 -0700196 // Compute maximum digit width the hard way.
197 private static float getMaxDigitWidth(TextPaint paint) {
198 // Compute the maximum advance width for each digit, thus accounting for between-character
199 // spaces. If we ever support other kinds of digits, we may have to avoid kerning effects
200 // that could reduce the advance width within this particular string.
201 final String allDigits = "0123456789";
202 final float[] widths = new float[allDigits.length()];
203 paint.getTextWidths(allDigits, widths);
204 float maxWidth = 0;
205 for (float x : widths) {
206 maxWidth = Math.max(x, maxWidth);
207 }
208 return maxWidth;
209 }
210
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700211 @Override
212 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
213 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
214
Justin Klaassen44595162015-05-28 17:55:20 -0700215 final TextPaint paint = getPaint();
Hans Boehm80018c82015-08-02 16:59:07 -0700216 final Context context = getContext();
Hans Boehmcd72f7e2016-06-01 16:21:25 -0700217 final float newCharWidth = getMaxDigitWidth(paint);
Hans Boehm80018c82015-08-02 16:59:07 -0700218 // Digits are presumed to have no more than newCharWidth.
219 // We sometimes replace a character by an ellipsis or, due to SCI_NOTATION_EXTRA, add
220 // an extra decimal separator beyond the maximum number of characters we normally allow.
221 // Empirically, our minus sign is also slightly wider than a digit, so we have to
222 // account for that. We never have both an ellipsis and two minus signs, and
223 // we assume an ellipsis is no narrower than a minus sign.
224 final float decimalSeparatorWidth = Layout.getDesiredWidth(
225 context.getString(R.string.dec_point), paint);
226 final float minusExtraWidth = Layout.getDesiredWidth(
227 context.getString(R.string.op_sub), paint) - newCharWidth;
228 final float ellipsisExtraWidth = Layout.getDesiredWidth(KeyMaps.ELLIPSIS, paint)
229 - newCharWidth;
230 final int extraWidth = (int) (Math.ceil(Math.max(decimalSeparatorWidth + minusExtraWidth,
231 ellipsisExtraWidth)) + Math.max(minusExtraWidth, 0.0f));
232 final int newWidthConstraint = MeasureSpec.getSize(widthMeasureSpec)
233 - (getPaddingLeft() + getPaddingRight()) - extraWidth;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700234 synchronized(mWidthLock) {
Hans Boehm013969e2015-04-13 20:29:47 -0700235 mWidthConstraint = newWidthConstraint;
236 mCharWidth = newCharWidth;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700237 }
238 }
239
Hans Boehma0e45f32015-05-30 13:20:35 -0700240 // Return the length of the exponent representation for the given exponent, in
241 // characters.
242 private final int expLen(int exp) {
243 if (exp == 0) return 0;
Hans Boehm5e802f32015-06-22 17:18:52 -0700244 final int abs_exp_digits = (int) Math.ceil(Math.log10(Math.abs((double)exp))
245 + 0.0000000001d /* Round whole numbers to next integer */);
246 return abs_exp_digits + (exp >= 0 ? 1 : 2);
Hans Boehm61568a12015-05-18 18:25:41 -0700247 }
248
Hans Boehma0e45f32015-05-30 13:20:35 -0700249 /**
250 * Initiate display of a new result.
251 * The parameters specify various properties of the result.
252 * @param initPrec Initial display precision computed by evaluator. (1 = tenths digit)
253 * @param msd Position of most significant digit. Offset from left of string.
254 Evaluator.INVALID_MSD if unknown.
255 * @param leastDigPos Position of least significant digit (1 = tenths digit)
256 * or Integer.MAX_VALUE.
257 * @param truncatedWholePart Result up to but not including decimal point.
258 Currently we only use the length.
259 */
260 void displayResult(int initPrec, int msd, int leastDigPos, String truncatedWholePart) {
261 initPositions(initPrec, msd, leastDigPos, truncatedWholePart);
Hans Boehm84614952014-11-25 18:46:17 -0800262 redisplay();
263 }
264
Hans Boehma0e45f32015-05-30 13:20:35 -0700265 /**
Hans Boehm5e802f32015-06-22 17:18:52 -0700266 * Set up scroll bounds (mMinPos, mMaxPos, etc.) and determine whether the result is
267 * scrollable, based on the supplied information about the result.
Hans Boehma0e45f32015-05-30 13:20:35 -0700268 * This is unfortunately complicated because we need to predict whether trailing digits
269 * will eventually be replaced by an exponent.
270 * Just appending the exponent during formatting would be simpler, but would produce
271 * jumpier results during transitions.
272 */
Hans Boehm5e802f32015-06-22 17:18:52 -0700273 private void initPositions(int initPrecOffset, int msdIndex, int lsdOffset,
274 String truncatedWholePart) {
Hans Boehma0e45f32015-05-30 13:20:35 -0700275 float charWidth;
276 int maxChars = getMaxChars();
277 mLastPos = INVALID;
Hans Boehm5e802f32015-06-22 17:18:52 -0700278 mLsdOffset = lsdOffset;
Hans Boehma0e45f32015-05-30 13:20:35 -0700279 synchronized(mWidthLock) {
280 charWidth = mCharWidth;
281 }
Hans Boehm5e802f32015-06-22 17:18:52 -0700282 mCurrentPos = mMinPos = (int) Math.round(initPrecOffset * charWidth);
Hans Boehma0e45f32015-05-30 13:20:35 -0700283 // Prevent scrolling past initial position, which is calculated to show leading digits.
Hans Boehm5e802f32015-06-22 17:18:52 -0700284 if (msdIndex == Evaluator.INVALID_MSD) {
Hans Boehma0e45f32015-05-30 13:20:35 -0700285 // Possible zero value
Hans Boehm5e802f32015-06-22 17:18:52 -0700286 if (lsdOffset == Integer.MIN_VALUE) {
Hans Boehma0e45f32015-05-30 13:20:35 -0700287 // Definite zero value.
288 mMaxPos = mMinPos;
Hans Boehm5e802f32015-06-22 17:18:52 -0700289 mMaxCharOffset = (int) Math.round(mMaxPos/charWidth);
Hans Boehma0e45f32015-05-30 13:20:35 -0700290 mScrollable = false;
291 } else {
292 // May be very small nonzero value. Allow user to find out.
Hans Boehm5e802f32015-06-22 17:18:52 -0700293 mMaxPos = mMaxCharOffset = MAX_RIGHT_SCROLL;
294 mMinPos -= charWidth; // Allow for future minus sign.
Hans Boehma0e45f32015-05-30 13:20:35 -0700295 mScrollable = true;
296 }
297 return;
298 }
Hans Boehm65a99a42016-02-03 18:16:07 -0800299 mWholeLen = truncatedWholePart.length();
Hans Boehma0e45f32015-05-30 13:20:35 -0700300 int negative = truncatedWholePart.charAt(0) == '-' ? 1 : 0;
Hans Boehm65a99a42016-02-03 18:16:07 -0800301 if (msdIndex > mWholeLen && msdIndex <= mWholeLen + 3) {
Hans Boehm5e802f32015-06-22 17:18:52 -0700302 // Avoid tiny negative exponent; pretend msdIndex is just to the right of decimal point.
Hans Boehm65a99a42016-02-03 18:16:07 -0800303 msdIndex = mWholeLen - 1;
Hans Boehma0e45f32015-05-30 13:20:35 -0700304 }
Hans Boehm65a99a42016-02-03 18:16:07 -0800305 int minCharOffset = msdIndex - mWholeLen;
Hans Boehma0e45f32015-05-30 13:20:35 -0700306 // Position of leftmost significant digit relative to dec. point.
307 // Usually negative.
Hans Boehm5e802f32015-06-22 17:18:52 -0700308 mMaxCharOffset = MAX_RIGHT_SCROLL; // How far does it make sense to scroll right?
Hans Boehma0e45f32015-05-30 13:20:35 -0700309 // If msd is left of decimal point should logically be
310 // mMinPos = - (int) Math.ceil(getPaint().measureText(truncatedWholePart)), but
311 // we eventually translate to a character position by dividing by mCharWidth.
312 // To avoid rounding issues, we use the analogous computation here.
Hans Boehm5e802f32015-06-22 17:18:52 -0700313 if (minCharOffset > -1 && minCharOffset < MAX_LEADING_ZEROES + 2) {
Hans Boehma0e45f32015-05-30 13:20:35 -0700314 // Small number of leading zeroes, avoid scientific notation.
Hans Boehm5e802f32015-06-22 17:18:52 -0700315 minCharOffset = -1;
Hans Boehma0e45f32015-05-30 13:20:35 -0700316 }
Hans Boehm5e802f32015-06-22 17:18:52 -0700317 if (lsdOffset < MAX_RIGHT_SCROLL) {
318 mMaxCharOffset = lsdOffset;
319 if (mMaxCharOffset < -1 && mMaxCharOffset > -(MAX_TRAILING_ZEROES + 2)) {
320 mMaxCharOffset = -1;
Hans Boehma0e45f32015-05-30 13:20:35 -0700321 }
Hans Boehm5e802f32015-06-22 17:18:52 -0700322 // lsdOffset is positive or negative, never 0.
323 int currentExpLen = 0; // Length of required standard scientific notation exponent.
324 if (mMaxCharOffset < -1) {
325 currentExpLen = expLen(-minCharOffset - 1);
326 } else if (minCharOffset > -1 || mMaxCharOffset >= maxChars) {
Hans Boehma0e45f32015-05-30 13:20:35 -0700327 // Number either entirely to the right of decimal point, or decimal point not
328 // visible when scrolled to the right.
Hans Boehm5e802f32015-06-22 17:18:52 -0700329 currentExpLen = expLen(-minCharOffset);
Hans Boehma0e45f32015-05-30 13:20:35 -0700330 }
Hans Boehm5e802f32015-06-22 17:18:52 -0700331 mScrollable = (mMaxCharOffset + currentExpLen - minCharOffset + negative >= maxChars);
332 int newMaxCharOffset;
333 if (currentExpLen > 0) {
334 if (mScrollable) {
335 // We'll use exponent corresponding to leastDigPos when scrolled to right.
336 newMaxCharOffset = mMaxCharOffset + expLen(-lsdOffset);
337 } else {
338 newMaxCharOffset = mMaxCharOffset + currentExpLen;
339 }
340 if (mMaxCharOffset <= -1 && newMaxCharOffset > -1) {
341 // Very unlikely; just drop exponent.
342 mMaxCharOffset = -1;
343 } else {
344 mMaxCharOffset = newMaxCharOffset;
Hans Boehma0e45f32015-05-30 13:20:35 -0700345 }
346 }
Hans Boehm5e802f32015-06-22 17:18:52 -0700347 mMaxPos = Math.min((int) Math.round(mMaxCharOffset * charWidth), MAX_RIGHT_SCROLL);
Hans Boehma0e45f32015-05-30 13:20:35 -0700348 if (!mScrollable) {
349 // Position the number consistently with our assumptions to make sure it
350 // actually fits.
351 mCurrentPos = mMaxPos;
352 }
353 } else {
Hans Boehm5e802f32015-06-22 17:18:52 -0700354 mMaxPos = mMaxCharOffset = MAX_RIGHT_SCROLL;
Hans Boehma0e45f32015-05-30 13:20:35 -0700355 mScrollable = true;
356 }
357 }
358
Hans Boehm84614952014-11-25 18:46:17 -0800359 void displayError(int resourceId) {
Hans Boehm760a9dc2015-04-20 10:27:12 -0700360 mValid = true;
Hans Boehm84614952014-11-25 18:46:17 -0800361 mScrollable = false;
362 setText(resourceId);
363 }
364
Hans Boehm013969e2015-04-13 20:29:47 -0700365 private final int MAX_COPY_SIZE = 1000000;
366
Hans Boehma0e45f32015-05-30 13:20:35 -0700367 /*
368 * Return the most significant digit position in the given string or Evaluator.INVALID_MSD.
Hans Boehm3666e632015-07-27 18:33:12 -0700369 * Unlike Evaluator.getMsdIndexOf, we treat a final 1 as significant.
Hans Boehma0e45f32015-05-30 13:20:35 -0700370 */
Hans Boehm3666e632015-07-27 18:33:12 -0700371 public static int getNaiveMsdIndexOf(String s) {
Hans Boehm65a99a42016-02-03 18:16:07 -0800372 final int len = s.length();
Hans Boehma0e45f32015-05-30 13:20:35 -0700373 for (int i = 0; i < len; ++i) {
374 char c = s.charAt(i);
375 if (c != '-' && c != '.' && c != '0') {
376 return i;
377 }
378 }
379 return Evaluator.INVALID_MSD;
380 }
381
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700382 // Format a result returned by Evaluator.getString() into a single line containing ellipses
Hans Boehm3666e632015-07-27 18:33:12 -0700383 // (if appropriate) and an exponent (if appropriate). precOffset is the value that was passed
384 // to getString and thus identifies the significance of the rightmost digit.
Hans Boehma0e45f32015-05-30 13:20:35 -0700385 // A value of 1 means the rightmost digits corresponds to tenths.
386 // maxDigs is the maximum number of characters in the result.
Hans Boehm65a99a42016-02-03 18:16:07 -0800387 // If lastDisplayedOffset is not null, we set lastDisplayedOffset[0] to the offset of
388 // the last digit actually appearing in the display.
Hans Boehmf6dae112015-06-18 17:57:50 -0700389 // If forcePrecision is true, we make sure that the last displayed digit corresponds to
Hans Boehm65a99a42016-02-03 18:16:07 -0800390 // precOffset, and allow maxDigs to be exceeded in adding the exponent.
Hans Boehm08e8f322015-04-21 13:18:38 -0700391 // We add two distinct kinds of exponents:
Hans Boehm5e802f32015-06-22 17:18:52 -0700392 // (1) If the final result contains the leading digit we use standard scientific notation.
393 // (2) If not, we add an exponent corresponding to an interpretation of the final result as
394 // an integer.
Hans Boehm08e8f322015-04-21 13:18:38 -0700395 // We add an ellipsis on the left if the result was truncated.
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700396 // We add ellipses and exponents in a way that leaves most digits in the position they
397 // would have been in had we not done so.
398 // This minimizes jumps as a result of scrolling. Result is NOT internationalized,
Hans Boehm0b9806f2015-06-29 16:07:15 -0700399 // uses "E" for exponent.
Hans Boehm5e802f32015-06-22 17:18:52 -0700400 public String formatResult(String in, int precOffset, int maxDigs, boolean truncated,
401 boolean negative, int lastDisplayedOffset[], boolean forcePrecision) {
402 final int minusSpace = negative ? 1 : 0;
Hans Boehm3666e632015-07-27 18:33:12 -0700403 final int msdIndex = truncated ? -1 : getNaiveMsdIndexOf(in); // INVALID_MSD is OK.
Hans Boehm5e802f32015-06-22 17:18:52 -0700404 String result = in;
Hans Boehm73ecff22015-09-03 16:04:50 -0700405 if (truncated || (negative && result.charAt(0) != '-')) {
406 result = KeyMaps.ELLIPSIS + result.substring(1, result.length());
407 // Ellipsis may be removed again in the type(1) scientific notation case.
408 }
409 final int decIndex = result.indexOf('.');
Hans Boehm65a99a42016-02-03 18:16:07 -0800410 if (lastDisplayedOffset != null) {
411 lastDisplayedOffset[0] = precOffset;
412 }
Hans Boehm5e802f32015-06-22 17:18:52 -0700413 if ((decIndex == -1 || msdIndex != Evaluator.INVALID_MSD
414 && msdIndex - decIndex > MAX_LEADING_ZEROES + 1) && precOffset != -1) {
Hans Boehma0e45f32015-05-30 13:20:35 -0700415 // No decimal point displayed, and it's not just to the right of the last digit,
416 // or we should suppress leading zeroes.
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700417 // Add an exponent to let the user track which digits are currently displayed.
Hans Boehm5e802f32015-06-22 17:18:52 -0700418 // Start with type (2) exponent if we dropped no digits. -1 accounts for decimal point.
419 final int initExponent = precOffset > 0 ? -precOffset : -precOffset - 1;
420 int exponent = initExponent;
Hans Boehm08e8f322015-04-21 13:18:38 -0700421 boolean hasPoint = false;
Hans Boehm5e802f32015-06-22 17:18:52 -0700422 if (!truncated && msdIndex < maxDigs - 1
423 && result.length() - msdIndex + 1 + minusSpace
424 <= maxDigs + SCI_NOTATION_EXTRA) {
425 // Type (1) exponent computation and transformation:
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700426 // Leading digit is in display window. Use standard calculator scientific notation
427 // with one digit to the left of the decimal point. Insert decimal point and
428 // delete leading zeroes.
Hans Boehma0e45f32015-05-30 13:20:35 -0700429 // We try to keep leading digits roughly in position, and never
Hans Boehmf6dae112015-06-18 17:57:50 -0700430 // lengthen the result by more than SCI_NOTATION_EXTRA.
Hans Boehm5e802f32015-06-22 17:18:52 -0700431 final int resLen = result.length();
432 String fraction = result.substring(msdIndex + 1, resLen);
433 result = (negative ? "-" : "") + result.substring(msdIndex, msdIndex + 1)
434 + "." + fraction;
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700435 // Original exp was correct for decimal point at right of fraction.
436 // Adjust by length of fraction.
Hans Boehm5e802f32015-06-22 17:18:52 -0700437 exponent = initExponent + resLen - msdIndex - 1;
Hans Boehm08e8f322015-04-21 13:18:38 -0700438 hasPoint = true;
439 }
Hans Boehm73ecff22015-09-03 16:04:50 -0700440 // Exponent can't be zero.
441 // Actually add the exponent of either type:
442 if (!forcePrecision) {
443 int dropDigits; // Digits to drop to make room for exponent.
444 if (hasPoint) {
445 // Type (1) exponent.
446 // Drop digits even if there is room. Otherwise the scrolling gets jumpy.
447 dropDigits = expLen(exponent);
448 if (dropDigits >= result.length() - 1) {
449 // Jumpy is better than no mantissa. Probably impossible anyway.
450 dropDigits = Math.max(result.length() - 2, 0);
Hans Boehma0e45f32015-05-30 13:20:35 -0700451 }
Hans Boehm73ecff22015-09-03 16:04:50 -0700452 } else {
453 // Type (2) exponent.
454 // Exponent depends on the number of digits we drop, which depends on
455 // exponent ...
456 for (dropDigits = 2; expLen(initExponent + dropDigits) > dropDigits;
457 ++dropDigits) {}
458 exponent = initExponent + dropDigits;
459 if (precOffset - dropDigits > mLsdOffset) {
460 // This can happen if e.g. result = 10^40 + 10^10
461 // It turns out we would otherwise display ...10e9 because it takes
462 // the same amount of space as ...1e10 but shows one more digit.
463 // But we don't want to display a trailing zero, even if it's free.
464 ++dropDigits;
465 ++exponent;
466 }
Hans Boehm08e8f322015-04-21 13:18:38 -0700467 }
Hans Boehm73ecff22015-09-03 16:04:50 -0700468 result = result.substring(0, result.length() - dropDigits);
Hans Boehm65a99a42016-02-03 18:16:07 -0800469 if (lastDisplayedOffset != null) {
470 lastDisplayedOffset[0] -= dropDigits;
471 }
Hans Boehm73ecff22015-09-03 16:04:50 -0700472 }
473 result = result + "E" + Integer.toString(exponent);
Hans Boehm5e802f32015-06-22 17:18:52 -0700474 }
475 return result;
Hans Boehm08e8f322015-04-21 13:18:38 -0700476 }
477
Hans Boehmf6dae112015-06-18 17:57:50 -0700478 /**
479 * Get formatted, but not internationalized, result from mEvaluator.
Hans Boehm5e802f32015-06-22 17:18:52 -0700480 * @param precOffset requested position (1 = tenths) of last included digit.
Hans Boehmf6dae112015-06-18 17:57:50 -0700481 * @param maxSize Maximum number of characters (more or less) in result.
Hans Boehm5e802f32015-06-22 17:18:52 -0700482 * @param lastDisplayedOffset Zeroth entry is set to actual offset of last included digit,
Hans Boehm65a99a42016-02-03 18:16:07 -0800483 * after adjusting for exponent, etc. May be null.
Hans Boehmf6dae112015-06-18 17:57:50 -0700484 * @param forcePrecision Ensure that last included digit is at pos, at the expense
485 * of treating maxSize as a soft limit.
486 */
Hans Boehm5e802f32015-06-22 17:18:52 -0700487 private String getFormattedResult(int precOffset, int maxSize, int lastDisplayedOffset[],
Hans Boehmf6dae112015-06-18 17:57:50 -0700488 boolean forcePrecision) {
Hans Boehm08e8f322015-04-21 13:18:38 -0700489 final boolean truncated[] = new boolean[1];
490 final boolean negative[] = new boolean[1];
Hans Boehm5e802f32015-06-22 17:18:52 -0700491 final int requestedPrecOffset[] = {precOffset};
492 final String rawResult = mEvaluator.getString(requestedPrecOffset, mMaxCharOffset,
Hans Boehma0e45f32015-05-30 13:20:35 -0700493 maxSize, truncated, negative);
Hans Boehm5e802f32015-06-22 17:18:52 -0700494 return formatResult(rawResult, requestedPrecOffset[0], maxSize, truncated[0], negative[0],
495 lastDisplayedOffset, forcePrecision);
Hans Boehm08e8f322015-04-21 13:18:38 -0700496 }
497
Hans Boehm65a99a42016-02-03 18:16:07 -0800498 /**
499 * Return entire result (within reason) up to current displayed precision.
500 */
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700501 public String getFullText() {
Hans Boehm760a9dc2015-04-20 10:27:12 -0700502 if (!mValid) return "";
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700503 if (!mScrollable) return getText().toString();
Hans Boehm5e802f32015-06-22 17:18:52 -0700504 return KeyMaps.translateResult(getFormattedResult(mLastDisplayedOffset, MAX_COPY_SIZE,
Hans Boehm65a99a42016-02-03 18:16:07 -0800505 null, true));
Hans Boehm84614952014-11-25 18:46:17 -0800506 }
507
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700508 public boolean fullTextIsExact() {
Hans Boehmf6dae112015-06-18 17:57:50 -0700509 return !mScrollable
Hans Boehm5e802f32015-06-22 17:18:52 -0700510 || mMaxCharOffset == getCurrentCharOffset() && mMaxCharOffset != MAX_RIGHT_SCROLL;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700511 }
512
Hans Boehm61568a12015-05-18 18:25:41 -0700513 /**
Hans Boehm65a99a42016-02-03 18:16:07 -0800514 * Get entire result up to current displayed precision, or up to MAX_COPY_EXTRA additional
515 * digits, if it will lead to an exact result.
516 */
517 public String getFullCopyText() {
518 if (!mValid
519 || mLsdOffset == Integer.MAX_VALUE
520 || fullTextIsExact()
521 || mWholeLen > MAX_RECOMPUTE_DIGITS
522 || mWholeLen + mLsdOffset > MAX_RECOMPUTE_DIGITS
523 || mLsdOffset - mLastDisplayedOffset > MAX_COPY_EXTRA) {
524 return getFullText();
525 }
526 // It's reasonable to compute and copy the exact result instead.
527 final int nonNegLsdOffset = Math.max(0, mLsdOffset);
Hans Boehm995e5eb2016-02-08 11:03:01 -0800528 final String rawResult = mEvaluator.getResult().toStringTruncated(nonNegLsdOffset);
Hans Boehm65a99a42016-02-03 18:16:07 -0800529 final String formattedResult = formatResult(rawResult, nonNegLsdOffset, MAX_COPY_SIZE,
530 false, rawResult.charAt(0) == '-', null, true);
531 return KeyMaps.translateResult(formattedResult);
532 }
533
534 /**
Hans Boehm61568a12015-05-18 18:25:41 -0700535 * Return the maximum number of characters that will fit in the result display.
536 * May be called asynchronously from non-UI thread.
537 */
Hans Boehm84614952014-11-25 18:46:17 -0800538 int getMaxChars() {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700539 int result;
540 synchronized(mWidthLock) {
Justin Klaassen44595162015-05-28 17:55:20 -0700541 result = (int) Math.floor(mWidthConstraint / mCharWidth);
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700542 // We can apparently finish evaluating before onMeasure in CalculatorText has been
543 // called, in which case we get 0 or -1 as the width constraint.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700544 }
Hans Boehm84614952014-11-25 18:46:17 -0800545 if (result <= 0) {
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700546 // Return something conservatively big, to force sufficient evaluation.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700547 return MAX_WIDTH;
Hans Boehm84614952014-11-25 18:46:17 -0800548 } else {
Hans Boehm80018c82015-08-02 16:59:07 -0700549 return result;
Hans Boehm84614952014-11-25 18:46:17 -0800550 }
551 }
552
Hans Boehm61568a12015-05-18 18:25:41 -0700553 /**
Justin Klaassen44595162015-05-28 17:55:20 -0700554 * @return {@code true} if the currently displayed result is scrollable
Hans Boehm61568a12015-05-18 18:25:41 -0700555 */
Justin Klaassen44595162015-05-28 17:55:20 -0700556 public boolean isScrollable() {
557 return mScrollable;
Hans Boehm61568a12015-05-18 18:25:41 -0700558 }
559
Hans Boehm5e802f32015-06-22 17:18:52 -0700560 int getCurrentCharOffset() {
Hans Boehm013969e2015-04-13 20:29:47 -0700561 synchronized(mWidthLock) {
Hans Boehma0e45f32015-05-30 13:20:35 -0700562 return (int) Math.round(mCurrentPos / mCharWidth);
Hans Boehm013969e2015-04-13 20:29:47 -0700563 }
564 }
565
Hans Boehm84614952014-11-25 18:46:17 -0800566 void clear() {
Hans Boehm760a9dc2015-04-20 10:27:12 -0700567 mValid = false;
Hans Boehm1176f232015-05-11 16:26:03 -0700568 mScrollable = false;
Hans Boehm84614952014-11-25 18:46:17 -0800569 setText("");
570 }
571
572 void redisplay() {
Hans Boehm5e802f32015-06-22 17:18:52 -0700573 int currentCharOffset = getCurrentCharOffset();
Hans Boehm84614952014-11-25 18:46:17 -0800574 int maxChars = getMaxChars();
Hans Boehm5e802f32015-06-22 17:18:52 -0700575 int lastDisplayedOffset[] = new int[1];
576 String result = getFormattedResult(currentCharOffset, maxChars, lastDisplayedOffset, false);
Hans Boehm0b9806f2015-06-29 16:07:15 -0700577 int expIndex = result.indexOf('E');
Hans Boehm013969e2015-04-13 20:29:47 -0700578 result = KeyMaps.translateResult(result);
Hans Boehm5e802f32015-06-22 17:18:52 -0700579 if (expIndex > 0 && result.indexOf('.') == -1) {
Hans Boehm84614952014-11-25 18:46:17 -0800580 // Gray out exponent if used as position indicator
581 SpannableString formattedResult = new SpannableString(result);
Hans Boehm5e802f32015-06-22 17:18:52 -0700582 formattedResult.setSpan(mExponentColorSpan, expIndex, result.length(),
Hans Boehm84614952014-11-25 18:46:17 -0800583 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
584 setText(formattedResult);
585 } else {
586 setText(result);
587 }
Hans Boehm5e802f32015-06-22 17:18:52 -0700588 mLastDisplayedOffset = lastDisplayedOffset[0];
Hans Boehm760a9dc2015-04-20 10:27:12 -0700589 mValid = true;
Hans Boehm84614952014-11-25 18:46:17 -0800590 }
591
592 @Override
593 public void computeScroll() {
594 if (!mScrollable) return;
595 if (mScroller.computeScrollOffset()) {
596 mCurrentPos = mScroller.getCurrX();
597 if (mCurrentPos != mLastPos) {
598 mLastPos = mCurrentPos;
599 redisplay();
600 }
601 if (!mScroller.isFinished()) {
Justin Klaassen44595162015-05-28 17:55:20 -0700602 postInvalidateOnAnimation();
Hans Boehm84614952014-11-25 18:46:17 -0800603 }
604 }
605 }
606
Chenjie Yu3937b652016-06-01 23:14:26 -0700607 /**
608 * Use ActionMode for copy support on M and higher.
609 */
610 @TargetApi(Build.VERSION_CODES.M)
611 private void setupActionMode() {
612 mCopyActionModeCallback = new ActionMode.Callback2() {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700613
Chenjie Yu3937b652016-06-01 23:14:26 -0700614 @Override
615 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
616 final MenuInflater inflater = mode.getMenuInflater();
617 return createCopyMenu(inflater, menu);
618 }
Hans Boehm7f83e362015-06-10 15:41:04 -0700619
Chenjie Yu3937b652016-06-01 23:14:26 -0700620 @Override
621 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
622 return false; // Return false if nothing is done
623 }
Hans Boehm7f83e362015-06-10 15:41:04 -0700624
Chenjie Yu3937b652016-06-01 23:14:26 -0700625 @Override
626 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
627 if (onMenuItemClick(item)) {
Hans Boehm65a99a42016-02-03 18:16:07 -0800628 mode.finish();
629 return true;
Chenjie Yu3937b652016-06-01 23:14:26 -0700630 } else {
631 return false;
Hans Boehm65a99a42016-02-03 18:16:07 -0800632 }
Chenjie Yu3937b652016-06-01 23:14:26 -0700633 }
634
635 @Override
636 public void onDestroyActionMode(ActionMode mode) {
637 unhighlightResult();
638 mActionMode = null;
639 }
640
641 @Override
642 public void onGetContentRect(ActionMode mode, View view, Rect outRect) {
643 super.onGetContentRect(mode, view, outRect);
644
645 outRect.left += view.getPaddingLeft();
646 outRect.top += view.getPaddingTop();
647 outRect.right -= view.getPaddingRight();
648 outRect.bottom -= view.getPaddingBottom();
649 final int width = (int) Layout.getDesiredWidth(getText(), getPaint());
650 if (width < outRect.width()) {
651 outRect.left = outRect.right - width;
652 }
653
654 if (!BuildCompat.isAtLeastN()) {
655 // The CAB (prior to N) only takes the translation of a view into account, so
656 // if a scale is applied to the view then the offset outRect will end up being
657 // positioned incorrectly. We workaround that limitation by manually applying
658 // the scale to the outRect, which the CAB will then offset to the correct
659 // position.
660 final float scaleX = view.getScaleX();
661 final float scaleY = view.getScaleY();
662 outRect.left *= scaleX;
663 outRect.right *= scaleX;
664 outRect.top *= scaleY;
665 outRect.bottom *= scaleY;
666 }
667 }
668 };
669 setOnLongClickListener(new View.OnLongClickListener() {
670 @Override
671 public boolean onLongClick(View v) {
672 if (mValid) {
673 mActionMode = startActionMode(mCopyActionModeCallback,
674 ActionMode.TYPE_FLOATING);
675 return true;
676 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700677 return false;
678 }
Chenjie Yu3937b652016-06-01 23:14:26 -0700679 });
680 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700681
Chenjie Yu3937b652016-06-01 23:14:26 -0700682 /**
683 * Use ContextMenu for copy support on L and lower.
684 */
685 private void setupContextMenu() {
686 setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
687 @Override
688 public void onCreateContextMenu(ContextMenu contextMenu, View view,
689 ContextMenu.ContextMenuInfo contextMenuInfo) {
690 final MenuInflater inflater = new MenuInflater(getContext());
691 createCopyMenu(inflater, contextMenu);
692 mContextMenu = contextMenu;
693 for(int i = 0; i < contextMenu.size(); i ++) {
694 contextMenu.getItem(i).setOnMenuItemClickListener(CalculatorResult.this);
695 }
Hans Boehm7f83e362015-06-10 15:41:04 -0700696 }
Chenjie Yu3937b652016-06-01 23:14:26 -0700697 });
698 setOnLongClickListener(new View.OnLongClickListener() {
699 @Override
700 public boolean onLongClick(View v) {
701 if (mValid) {
702 return showContextMenu();
703 }
704 return false;
Justin Klaassenf1b61f42016-04-27 16:00:11 -0700705 }
Chenjie Yu3937b652016-06-01 23:14:26 -0700706 });
707 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700708
Chenjie Yu3937b652016-06-01 23:14:26 -0700709 private boolean createCopyMenu(MenuInflater inflater, Menu menu) {
710 inflater.inflate(R.menu.copy, menu);
711 highlightResult();
712 return true;
713 }
714
715 public boolean stopActionModeOrContextMenu() {
Hans Boehm1176f232015-05-11 16:26:03 -0700716 if (mActionMode != null) {
717 mActionMode.finish();
718 return true;
719 }
Chenjie Yu3937b652016-06-01 23:14:26 -0700720 if (mContextMenu != null) {
721 unhighlightResult();
722 mContextMenu.close();
723 return true;
724 }
Hans Boehm1176f232015-05-11 16:26:03 -0700725 return false;
726 }
727
Chenjie Yu3937b652016-06-01 23:14:26 -0700728 private void highlightResult() {
729 final Spannable text = (Spannable) getText();
730 text.setSpan(mHighlightSpan, 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
731 }
732
733 private void unhighlightResult() {
734 final Spannable text = (Spannable) getText();
735 text.removeSpan(mHighlightSpan);
736 }
737
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700738 private void setPrimaryClip(ClipData clip) {
739 ClipboardManager clipboard = (ClipboardManager) getContext().
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700740 getSystemService(Context.CLIPBOARD_SERVICE);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700741 clipboard.setPrimaryClip(clip);
742 }
743
744 private void copyContent() {
Hans Boehm65a99a42016-02-03 18:16:07 -0800745 final CharSequence text = getFullCopyText();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700746 ClipboardManager clipboard =
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700747 (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
748 // We include a tag URI, to allow us to recognize our own results and handle them
749 // specially.
750 ClipData.Item newItem = new ClipData.Item(text, null, mEvaluator.capture());
751 String[] mimeTypes = new String[] {ClipDescription.MIMETYPE_TEXT_PLAIN};
752 ClipData cd = new ClipData("calculator result", mimeTypes, newItem);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700753 clipboard.setPrimaryClip(cd);
Hans Boehmc01cd7f2015-05-12 18:32:19 -0700754 Toast.makeText(getContext(), R.string.text_copied_toast, Toast.LENGTH_SHORT).show();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700755 }
756
Chenjie Yu3937b652016-06-01 23:14:26 -0700757 @Override
758 public boolean onMenuItemClick(MenuItem item) {
759 switch (item.getItemId()) {
760 case R.id.menu_copy:
761 if (mEvaluator.reevaluationInProgress()) {
762 // Refuse to copy placeholder characters.
763 return false;
764 } else {
765 copyContent();
766 unhighlightResult();
767 return true;
768 }
769 default:
770 return false;
771 }
772 }
Hans Boehm84614952014-11-25 18:46:17 -0800773}