blob: d70b9725f60814fcd6011eebfc6c37fdda739552 [file] [log] [blame]
Justin Klaassen4b3af052014-05-27 17:53:10 -07001/*
Justin Klaassen12da1ad2016-04-04 14:20:37 -07002 * Copyright (C) 2016 The Android Open Source Project
Justin Klaassen4b3af052014-05-27 17:53:10 -07003 *
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
Hans Boehm013969e2015-04-13 20:29:47 -070017// TODO: Copy & more general paste in formula? Note that this requires
18// great care: Currently the text version of a displayed formula
19// is not directly useful for re-evaluating the formula later, since
20// it contains ellipses representing subexpressions evaluated with
21// a different degree mode. Rather than supporting copy from the
22// formula window, we may eventually want to support generation of a
23// more useful text version in a separate window. It's not clear
24// this is worth the added (code and user) complexity.
Hans Boehm84614952014-11-25 18:46:17 -080025
Justin Klaassen4b3af052014-05-27 17:53:10 -070026package com.android.calculator2;
27
28import android.animation.Animator;
Justin Klaassen5f2a3342014-06-11 17:40:22 -070029import android.animation.Animator.AnimatorListener;
Justin Klaassen4b3af052014-05-27 17:53:10 -070030import android.animation.AnimatorListenerAdapter;
31import android.animation.AnimatorSet;
Justin Klaassen4b3af052014-05-27 17:53:10 -070032import android.animation.ObjectAnimator;
Justin Klaassen44595162015-05-28 17:55:20 -070033import android.animation.PropertyValuesHolder;
Justin Klaassen9d33cdc2016-02-21 14:16:14 -080034import android.app.ActionBar;
Justin Klaassen4b3af052014-05-27 17:53:10 -070035import android.app.Activity;
Justin Klaassenfc5ac822015-06-18 13:15:17 -070036import android.content.ClipData;
Hans Boehm5e6a0ca2015-09-22 17:09:01 -070037import android.content.DialogInterface;
Justin Klaassend36d63e2015-05-05 12:59:36 -070038import android.content.Intent;
Hans Boehmbfe8c222015-04-02 16:26:07 -070039import android.content.res.Resources;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070040import android.graphics.Color;
Justin Klaassen8fff1442014-06-19 10:43:29 -070041import android.graphics.Rect;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070042import android.net.Uri;
Justin Klaassen4b3af052014-05-27 17:53:10 -070043import android.os.Bundle;
Justin Klaassenf79d6f62014-08-26 12:27:08 -070044import android.support.annotation.NonNull;
Chenjie Yu3937b652016-06-01 23:14:26 -070045import android.support.v4.content.ContextCompat;
Justin Klaassen3b4d13d2014-06-06 18:18:37 +010046import android.support.v4.view.ViewPager;
Annie Chine918fd22016-03-09 11:07:54 -080047import android.text.Editable;
Hans Boehm8a4f81c2015-07-09 10:41:25 -070048import android.text.SpannableStringBuilder;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070049import android.text.Spanned;
Annie Chinf360ef02016-03-10 13:45:39 -080050import android.text.TextUtils;
Annie Chine918fd22016-03-09 11:07:54 -080051import android.text.TextWatcher;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070052import android.text.style.ForegroundColorSpan;
Justin Klaassen44595162015-05-28 17:55:20 -070053import android.util.Property;
Annie Chine918fd22016-03-09 11:07:54 -080054import android.view.ActionMode;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070055import android.view.KeyCharacterMap;
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -070056import android.view.KeyEvent;
Hans Boehm84614952014-11-25 18:46:17 -080057import android.view.Menu;
58import android.view.MenuItem;
Justin Klaassen4b3af052014-05-27 17:53:10 -070059import android.view.View;
60import android.view.View.OnLongClickListener;
Justin Klaassen5f2a3342014-06-11 17:40:22 -070061import android.view.ViewAnimationUtils;
Justin Klaassen8fff1442014-06-19 10:43:29 -070062import android.view.ViewGroupOverlay;
Annie Chine918fd22016-03-09 11:07:54 -080063import android.view.ViewTreeObserver;
Justin Klaassen4b3af052014-05-27 17:53:10 -070064import android.view.animation.AccelerateDecelerateInterpolator;
Annie Chine918fd22016-03-09 11:07:54 -080065import android.widget.HorizontalScrollView;
Justin Klaassenfed941a2014-06-09 18:42:40 +010066import android.widget.TextView;
Justin Klaassend48b7562015-04-16 16:51:38 -070067import android.widget.Toolbar;
Justin Klaassenfed941a2014-06-09 18:42:40 +010068
Hans Boehm08e8f322015-04-21 13:18:38 -070069import com.android.calculator2.CalculatorText.OnTextSizeChangeListener;
Hans Boehm84614952014-11-25 18:46:17 -080070
71import java.io.ByteArrayInputStream;
Hans Boehm84614952014-11-25 18:46:17 -080072import java.io.ByteArrayOutputStream;
Hans Boehm84614952014-11-25 18:46:17 -080073import java.io.IOException;
Justin Klaassen721ec842015-05-28 14:30:08 -070074import java.io.ObjectInput;
75import java.io.ObjectInputStream;
76import java.io.ObjectOutput;
77import java.io.ObjectOutputStream;
Justin Klaassen4b3af052014-05-27 17:53:10 -070078
Justin Klaassen04f79c72014-06-27 17:25:35 -070079public class Calculator extends Activity
Hans Boehm5e6a0ca2015-09-22 17:09:01 -070080 implements OnTextSizeChangeListener, OnLongClickListener, CalculatorText.OnPasteListener,
81 AlertDialogFragment.OnClickListener {
Justin Klaassen2be4fdb2014-08-06 19:54:09 -070082
83 /**
84 * Constant for an invalid resource id.
85 */
86 public static final int INVALID_RES_ID = -1;
Justin Klaassen4b3af052014-05-27 17:53:10 -070087
88 private enum CalculatorState {
Hans Boehm84614952014-11-25 18:46:17 -080089 INPUT, // Result and formula both visible, no evaluation requested,
90 // Though result may be visible on bottom line.
91 EVALUATE, // Both visible, evaluation requested, evaluation/animation incomplete.
Hans Boehmc1ea0912015-06-19 15:05:07 -070092 // Not used for instant result evaluation.
Hans Boehm84614952014-11-25 18:46:17 -080093 INIT, // Very temporary state used as alternative to EVALUATE
94 // during reinitialization. Do not animate on completion.
95 ANIMATE, // Result computed, animation to enlarge result window in progress.
96 RESULT, // Result displayed, formula invisible.
97 // If we are in RESULT state, the formula was evaluated without
98 // error to initial precision.
99 ERROR // Error displayed: Formula visible, result shows error message.
100 // Display similar to INPUT state.
Justin Klaassen4b3af052014-05-27 17:53:10 -0700101 }
Hans Boehm84614952014-11-25 18:46:17 -0800102 // Normal transition sequence is
103 // INPUT -> EVALUATE -> ANIMATE -> RESULT (or ERROR) -> INPUT
104 // A RESULT -> ERROR transition is possible in rare corner cases, in which
105 // a higher precision evaluation exposes an error. This is possible, since we
106 // initially evaluate assuming we were given a well-defined problem. If we
107 // were actually asked to compute sqrt(<extremely tiny negative number>) we produce 0
108 // unless we are asked for enough precision that we can distinguish the argument from zero.
109 // TODO: Consider further heuristics to reduce the chance of observing this?
110 // It already seems to be observable only in contrived cases.
111 // ANIMATE, ERROR, and RESULT are translated to an INIT state if the application
112 // is restarted in that state. This leads us to recompute and redisplay the result
113 // ASAP.
114 // TODO: Possibly save a bit more information, e.g. its initial display string
115 // or most significant digit position, to speed up restart.
Justin Klaassen4b3af052014-05-27 17:53:10 -0700116
Justin Klaassen44595162015-05-28 17:55:20 -0700117 private final Property<TextView, Integer> TEXT_COLOR =
118 new Property<TextView, Integer>(Integer.class, "textColor") {
119 @Override
120 public Integer get(TextView textView) {
121 return textView.getCurrentTextColor();
122 }
123
124 @Override
125 public void set(TextView textView, Integer textColor) {
126 textView.setTextColor(textColor);
127 }
128 };
129
Justin Klaassen3e223ea2016-02-05 14:18:06 -0800130 private static final String NAME = "Calculator";
Hans Boehm84614952014-11-25 18:46:17 -0800131 private static final String KEY_DISPLAY_STATE = NAME + "_display_state";
Hans Boehm760a9dc2015-04-20 10:27:12 -0700132 private static final String KEY_UNPROCESSED_CHARS = NAME + "_unprocessed_chars";
Justin Klaassen3e223ea2016-02-05 14:18:06 -0800133 /**
134 * Associated value is a byte array holding the evaluator state.
135 */
Hans Boehm84614952014-11-25 18:46:17 -0800136 private static final String KEY_EVAL_STATE = NAME + "_eval_state";
Justin Klaassen3e223ea2016-02-05 14:18:06 -0800137 private static final String KEY_INVERSE_MODE = NAME + "_inverse_mode";
Christine Frankseeff27f2016-07-29 12:05:29 -0700138 /**
139 * Associated value is an boolean holding the visibility state of the toolbar.
140 */
141 private static final String KEY_SHOW_TOOLBAR = NAME + "_show_toolbar";
Justin Klaassen741471e2014-06-11 09:43:44 -0700142
Annie Chine918fd22016-03-09 11:07:54 -0800143 private final ViewTreeObserver.OnPreDrawListener mPreDrawListener =
144 new ViewTreeObserver.OnPreDrawListener() {
145 @Override
146 public boolean onPreDraw() {
Justin Klaassen12da1ad2016-04-04 14:20:37 -0700147 mFormulaContainer.scrollTo(mFormulaText.getRight(), 0);
Annie Chine918fd22016-03-09 11:07:54 -0800148 final ViewTreeObserver observer = mFormulaContainer.getViewTreeObserver();
149 if (observer.isAlive()) {
150 observer.removeOnPreDrawListener(this);
151 }
152 return false;
153 }
154 };
155
156 private final TextWatcher mFormulaTextWatcher = new TextWatcher() {
157 @Override
158 public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
159 }
160
161 @Override
162 public void onTextChanged(CharSequence charSequence, int start, int count, int after) {
163 }
164
165 @Override
166 public void afterTextChanged(Editable editable) {
167 final ViewTreeObserver observer = mFormulaContainer.getViewTreeObserver();
168 if (observer.isAlive()) {
169 observer.removeOnPreDrawListener(mPreDrawListener);
170 observer.addOnPreDrawListener(mPreDrawListener);
171 }
172 }
173 };
174
Justin Klaassen4b3af052014-05-27 17:53:10 -0700175 private CalculatorState mCurrentState;
Hans Boehm84614952014-11-25 18:46:17 -0800176 private Evaluator mEvaluator;
Justin Klaassen4b3af052014-05-27 17:53:10 -0700177
Justin Klaassen9d33cdc2016-02-21 14:16:14 -0800178 private CalculatorDisplay mDisplayView;
Justin Klaassend48b7562015-04-16 16:51:38 -0700179 private TextView mModeView;
Hans Boehm08e8f322015-04-21 13:18:38 -0700180 private CalculatorText mFormulaText;
Justin Klaassen44595162015-05-28 17:55:20 -0700181 private CalculatorResult mResultText;
Annie Chine918fd22016-03-09 11:07:54 -0800182 private HorizontalScrollView mFormulaContainer;
Justin Klaassend48b7562015-04-16 16:51:38 -0700183
Justin Klaassen3b4d13d2014-06-06 18:18:37 +0100184 private ViewPager mPadViewPager;
Justin Klaassen4b3af052014-05-27 17:53:10 -0700185 private View mDeleteButton;
186 private View mClearButton;
Justin Klaassend48b7562015-04-16 16:51:38 -0700187 private View mEqualButton;
Justin Klaassene2711cb2015-05-28 11:13:17 -0700188
189 private TextView mInverseToggle;
190 private TextView mModeToggle;
191
Justin Klaassen721ec842015-05-28 14:30:08 -0700192 private View[] mInvertibleButtons;
Justin Klaassene2711cb2015-05-28 11:13:17 -0700193 private View[] mInverseButtons;
Justin Klaassen4b3af052014-05-27 17:53:10 -0700194
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700195 private View mCurrentButton;
Justin Klaassen4b3af052014-05-27 17:53:10 -0700196 private Animator mCurrentAnimator;
197
Hans Boehm8a4f81c2015-07-09 10:41:25 -0700198 // Characters that were recently entered at the end of the display that have not yet
199 // been added to the underlying expression.
200 private String mUnprocessedChars = null;
201
202 // Color to highlight unprocessed characters from physical keyboard.
203 // TODO: should probably match this to the error color?
204 private ForegroundColorSpan mUnprocessedColorSpan = new ForegroundColorSpan(Color.RED);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700205
Annie Chin26e159e2016-05-18 15:17:14 -0700206 // Whether the display is one line.
207 private boolean mOneLine;
208
Justin Klaassen4b3af052014-05-27 17:53:10 -0700209 @Override
210 protected void onCreate(Bundle savedInstanceState) {
211 super.onCreate(savedInstanceState);
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700212 setContentView(R.layout.activity_calculator);
Justin Klaassend48b7562015-04-16 16:51:38 -0700213 setActionBar((Toolbar) findViewById(R.id.toolbar));
214
215 // Hide all default options in the ActionBar.
216 getActionBar().setDisplayOptions(0);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700217
Justin Klaassen9d33cdc2016-02-21 14:16:14 -0800218 // Ensure the toolbar stays visible while the options menu is displayed.
219 getActionBar().addOnMenuVisibilityListener(new ActionBar.OnMenuVisibilityListener() {
220 @Override
221 public void onMenuVisibilityChanged(boolean isVisible) {
222 mDisplayView.setForceToolbarVisible(isVisible);
223 }
224 });
225
226 mDisplayView = (CalculatorDisplay) findViewById(R.id.display);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700227 mModeView = (TextView) findViewById(R.id.mode);
Hans Boehm08e8f322015-04-21 13:18:38 -0700228 mFormulaText = (CalculatorText) findViewById(R.id.formula);
Justin Klaassen44595162015-05-28 17:55:20 -0700229 mResultText = (CalculatorResult) findViewById(R.id.result);
Annie Chine918fd22016-03-09 11:07:54 -0800230 mFormulaContainer = (HorizontalScrollView) findViewById(R.id.formula_container);
Justin Klaassend48b7562015-04-16 16:51:38 -0700231
Justin Klaassen3b4d13d2014-06-06 18:18:37 +0100232 mPadViewPager = (ViewPager) findViewById(R.id.pad_pager);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700233 mDeleteButton = findViewById(R.id.del);
234 mClearButton = findViewById(R.id.clr);
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700235 mEqualButton = findViewById(R.id.pad_numeric).findViewById(R.id.eq);
236 if (mEqualButton == null || mEqualButton.getVisibility() != View.VISIBLE) {
237 mEqualButton = findViewById(R.id.pad_operator).findViewById(R.id.eq);
238 }
Justin Klaassene2711cb2015-05-28 11:13:17 -0700239
240 mInverseToggle = (TextView) findViewById(R.id.toggle_inv);
241 mModeToggle = (TextView) findViewById(R.id.toggle_mode);
242
Annie Chin26e159e2016-05-18 15:17:14 -0700243 mOneLine = mResultText.getVisibility() == View.INVISIBLE;
244
Justin Klaassen721ec842015-05-28 14:30:08 -0700245 mInvertibleButtons = new View[] {
246 findViewById(R.id.fun_sin),
247 findViewById(R.id.fun_cos),
Hans Boehm4db31b42015-05-31 12:19:05 -0700248 findViewById(R.id.fun_tan),
249 findViewById(R.id.fun_ln),
250 findViewById(R.id.fun_log),
251 findViewById(R.id.op_sqrt)
Justin Klaassene2711cb2015-05-28 11:13:17 -0700252 };
253 mInverseButtons = new View[] {
254 findViewById(R.id.fun_arcsin),
255 findViewById(R.id.fun_arccos),
Hans Boehm4db31b42015-05-31 12:19:05 -0700256 findViewById(R.id.fun_arctan),
257 findViewById(R.id.fun_exp),
258 findViewById(R.id.fun_10pow),
259 findViewById(R.id.op_sqr)
Justin Klaassene2711cb2015-05-28 11:13:17 -0700260 };
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700261
Justin Klaassen44595162015-05-28 17:55:20 -0700262 mEvaluator = new Evaluator(this, mResultText);
263 mResultText.setEvaluator(mEvaluator);
Hans Boehm013969e2015-04-13 20:29:47 -0700264 KeyMaps.setActivity(this);
Justin Klaassen2be4fdb2014-08-06 19:54:09 -0700265
Hans Boehm84614952014-11-25 18:46:17 -0800266 if (savedInstanceState != null) {
267 setState(CalculatorState.values()[
268 savedInstanceState.getInt(KEY_DISPLAY_STATE,
269 CalculatorState.INPUT.ordinal())]);
Hans Boehm760a9dc2015-04-20 10:27:12 -0700270 CharSequence unprocessed = savedInstanceState.getCharSequence(KEY_UNPROCESSED_CHARS);
271 if (unprocessed != null) {
272 mUnprocessedChars = unprocessed.toString();
273 }
274 byte[] state = savedInstanceState.getByteArray(KEY_EVAL_STATE);
Hans Boehm84614952014-11-25 18:46:17 -0800275 if (state != null) {
276 try (ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(state))) {
277 mEvaluator.restoreInstanceState(in);
278 } catch (Throwable ignored) {
279 // When in doubt, revert to clean state
280 mCurrentState = CalculatorState.INPUT;
281 mEvaluator.clear();
282 }
283 }
Hans Boehmfbcef702015-04-27 18:07:47 -0700284 } else {
285 mCurrentState = CalculatorState.INPUT;
286 mEvaluator.clear();
Hans Boehm84614952014-11-25 18:46:17 -0800287 }
Justin Klaassene2711cb2015-05-28 11:13:17 -0700288
Hans Boehm08e8f322015-04-21 13:18:38 -0700289 mFormulaText.setOnTextSizeChangeListener(this);
Justin Klaassenfc5ac822015-06-18 13:15:17 -0700290 mFormulaText.setOnPasteListener(this);
Annie Chine918fd22016-03-09 11:07:54 -0800291 mFormulaText.addTextChangedListener(mFormulaTextWatcher);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700292 mDeleteButton.setOnLongClickListener(this);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700293
Justin Klaassen3e223ea2016-02-05 14:18:06 -0800294 onInverseToggled(savedInstanceState != null
295 && savedInstanceState.getBoolean(KEY_INVERSE_MODE));
Christine Frankseeff27f2016-07-29 12:05:29 -0700296
Justin Klaassene2711cb2015-05-28 11:13:17 -0700297 onModeChanged(mEvaluator.getDegreeMode());
Christine Frankseeff27f2016-07-29 12:05:29 -0700298 if (savedInstanceState != null &&
299 savedInstanceState.getBoolean(KEY_SHOW_TOOLBAR, true) == false) {
300 mDisplayView.hideToolbar();
301 } else {
302 showAndMaybeHideToolbar();
303 }
Justin Klaassene2711cb2015-05-28 11:13:17 -0700304
Hans Boehm84614952014-11-25 18:46:17 -0800305 if (mCurrentState != CalculatorState.INPUT) {
Hans Boehmfbcef702015-04-27 18:07:47 -0700306 // Just reevaluate.
307 redisplayFormula();
Hans Boehm84614952014-11-25 18:46:17 -0800308 setState(CalculatorState.INIT);
Hans Boehm84614952014-11-25 18:46:17 -0800309 mEvaluator.requireResult();
310 } else {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700311 redisplayAfterFormulaChange();
Hans Boehm84614952014-11-25 18:46:17 -0800312 }
313 // TODO: We're currently not saving and restoring scroll position.
314 // We probably should. Details may require care to deal with:
315 // - new display size
316 // - slow recomputation if we've scrolled far.
Justin Klaassen4b3af052014-05-27 17:53:10 -0700317 }
318
319 @Override
Justin Klaassen9d33cdc2016-02-21 14:16:14 -0800320 protected void onResume() {
321 super.onResume();
Christine Frankseeff27f2016-07-29 12:05:29 -0700322 if (mDisplayView.isToolbarVisible()) {
323 showAndMaybeHideToolbar();
324 }
Justin Klaassen9d33cdc2016-02-21 14:16:14 -0800325 }
326
327 @Override
Justin Klaassenf79d6f62014-08-26 12:27:08 -0700328 protected void onSaveInstanceState(@NonNull Bundle outState) {
Hans Boehm40125442016-01-22 10:35:35 -0800329 mEvaluator.cancelAll(true);
Justin Klaassenf79d6f62014-08-26 12:27:08 -0700330 // If there's an animation in progress, cancel it first to ensure our state is up-to-date.
331 if (mCurrentAnimator != null) {
332 mCurrentAnimator.cancel();
333 }
334
Justin Klaassen4b3af052014-05-27 17:53:10 -0700335 super.onSaveInstanceState(outState);
Hans Boehm84614952014-11-25 18:46:17 -0800336 outState.putInt(KEY_DISPLAY_STATE, mCurrentState.ordinal());
Hans Boehm760a9dc2015-04-20 10:27:12 -0700337 outState.putCharSequence(KEY_UNPROCESSED_CHARS, mUnprocessedChars);
Hans Boehm84614952014-11-25 18:46:17 -0800338 ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
339 try (ObjectOutput out = new ObjectOutputStream(byteArrayStream)) {
340 mEvaluator.saveInstanceState(out);
341 } catch (IOException e) {
342 // Impossible; No IO involved.
343 throw new AssertionError("Impossible IO exception", e);
344 }
345 outState.putByteArray(KEY_EVAL_STATE, byteArrayStream.toByteArray());
Justin Klaassen3e223ea2016-02-05 14:18:06 -0800346 outState.putBoolean(KEY_INVERSE_MODE, mInverseToggle.isSelected());
Christine Frankseeff27f2016-07-29 12:05:29 -0700347 outState.putBoolean(KEY_SHOW_TOOLBAR, mDisplayView.isToolbarVisible());
Justin Klaassen4b3af052014-05-27 17:53:10 -0700348 }
349
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700350 // Set the state, updating delete label and display colors.
351 // This restores display positions on moving to INPUT.
Justin Klaassend48b7562015-04-16 16:51:38 -0700352 // But movement/animation for moving to RESULT has already been done.
Justin Klaassen4b3af052014-05-27 17:53:10 -0700353 private void setState(CalculatorState state) {
354 if (mCurrentState != state) {
Hans Boehm84614952014-11-25 18:46:17 -0800355 if (state == CalculatorState.INPUT) {
356 restoreDisplayPositions();
357 }
Justin Klaassen4b3af052014-05-27 17:53:10 -0700358 mCurrentState = state;
359
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700360 if (mCurrentState == CalculatorState.RESULT) {
361 // No longer do this for ERROR; allow mistakes to be corrected.
Justin Klaassen4b3af052014-05-27 17:53:10 -0700362 mDeleteButton.setVisibility(View.GONE);
363 mClearButton.setVisibility(View.VISIBLE);
364 } else {
365 mDeleteButton.setVisibility(View.VISIBLE);
366 mClearButton.setVisibility(View.GONE);
367 }
368
Annie Chin26e159e2016-05-18 15:17:14 -0700369 if (mOneLine) {
370 if (mCurrentState == CalculatorState.RESULT
371 || mCurrentState == CalculatorState.EVALUATE
372 || mCurrentState == CalculatorState.ANIMATE) {
373 mFormulaText.setVisibility(View.VISIBLE);
374 mResultText.setVisibility(View.VISIBLE);
Annie Chin947d93b2016-06-14 10:18:54 -0700375 } else if (mCurrentState == CalculatorState.ERROR) {
376 mFormulaText.setVisibility(View.INVISIBLE);
377 mResultText.setVisibility(View.VISIBLE);
Annie Chin26e159e2016-05-18 15:17:14 -0700378 } else {
379 mFormulaText.setVisibility(View.VISIBLE);
380 mResultText.setVisibility(View.INVISIBLE);
381 }
382 }
383
Hans Boehm84614952014-11-25 18:46:17 -0800384 if (mCurrentState == CalculatorState.ERROR) {
Chenjie Yu3937b652016-06-01 23:14:26 -0700385 final int errorColor =
386 ContextCompat.getColor(this, R.color.calculator_error_color);
Hans Boehm08e8f322015-04-21 13:18:38 -0700387 mFormulaText.setTextColor(errorColor);
Justin Klaassen44595162015-05-28 17:55:20 -0700388 mResultText.setTextColor(errorColor);
Justin Klaassen8fff1442014-06-19 10:43:29 -0700389 getWindow().setStatusBarColor(errorColor);
Justin Klaassen44595162015-05-28 17:55:20 -0700390 } else if (mCurrentState != CalculatorState.RESULT) {
Chenjie Yu3937b652016-06-01 23:14:26 -0700391 mFormulaText.setTextColor(
392 ContextCompat.getColor(this, R.color.display_formula_text_color));
393 mResultText.setTextColor(
394 ContextCompat.getColor(this, R.color.display_result_text_color));
395 getWindow().setStatusBarColor(
396 ContextCompat.getColor(this, R.color.calculator_accent_color));
Justin Klaassen4b3af052014-05-27 17:53:10 -0700397 }
Justin Klaassend48b7562015-04-16 16:51:38 -0700398
399 invalidateOptionsMenu();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700400 }
401 }
402
Justin Klaassen12da1ad2016-04-04 14:20:37 -0700403 @Override
404 public void onActionModeStarted(ActionMode mode) {
405 super.onActionModeStarted(mode);
406 if (mode.getTag() == CalculatorText.TAG_ACTION_MODE) {
407 mFormulaContainer.scrollTo(mFormulaText.getRight(), 0);
408 }
409 }
410
Chenjie Yu3937b652016-06-01 23:14:26 -0700411 /**
412 * Stop any active ActionMode or ContextMenu for copy/paste actions.
413 * Return true if there was one.
414 */
415 private boolean stopActionModeOrContextMenu() {
416 if (mResultText.stopActionModeOrContextMenu()) {
Hans Boehm1176f232015-05-11 16:26:03 -0700417 return true;
418 }
Chenjie Yu3937b652016-06-01 23:14:26 -0700419 if (mFormulaText.stopActionModeOrContextMenu()) {
Hans Boehm1176f232015-05-11 16:26:03 -0700420 return true;
421 }
422 return false;
423 }
424
Justin Klaassen4b3af052014-05-27 17:53:10 -0700425 @Override
Justin Klaassen12da1ad2016-04-04 14:20:37 -0700426 public void onUserInteraction() {
427 super.onUserInteraction();
428
429 // If there's an animation in progress, end it immediately, so the user interaction can
430 // be handled.
431 if (mCurrentAnimator != null) {
432 mCurrentAnimator.end();
433 }
434 }
435
436 @Override
Justin Klaassen3b4d13d2014-06-06 18:18:37 +0100437 public void onBackPressed() {
Chenjie Yu3937b652016-06-01 23:14:26 -0700438 if (!stopActionModeOrContextMenu()) {
Hans Boehm1176f232015-05-11 16:26:03 -0700439 if (mPadViewPager != null && mPadViewPager.getCurrentItem() != 0) {
440 // Select the previous pad.
441 mPadViewPager.setCurrentItem(mPadViewPager.getCurrentItem() - 1);
442 } else {
443 // If the user is currently looking at the first pad (or the pad is not paged),
444 // allow the system to handle the Back button.
445 super.onBackPressed();
446 }
Justin Klaassen3b4d13d2014-06-06 18:18:37 +0100447 }
448 }
449
450 @Override
Justin Klaassen12da1ad2016-04-04 14:20:37 -0700451 public boolean onKeyUp(int keyCode, KeyEvent event) {
Justin Klaassen83959da2016-04-06 11:55:24 -0700452 // Allow the system to handle special key codes (e.g. "BACK" or "DPAD").
Justin Klaassen12da1ad2016-04-04 14:20:37 -0700453 switch (keyCode) {
Justin Klaassen83959da2016-04-06 11:55:24 -0700454 case KeyEvent.KEYCODE_BACK:
Justin Klaassen12da1ad2016-04-04 14:20:37 -0700455 case KeyEvent.KEYCODE_DPAD_UP:
456 case KeyEvent.KEYCODE_DPAD_DOWN:
457 case KeyEvent.KEYCODE_DPAD_LEFT:
458 case KeyEvent.KEYCODE_DPAD_RIGHT:
459 return super.onKeyUp(keyCode, event);
460 }
461
Chenjie Yu3937b652016-06-01 23:14:26 -0700462 // Stop the action mode or context menu if it's showing.
463 stopActionModeOrContextMenu();
Justin Klaassend12e0622016-04-27 16:26:47 -0700464
Justin Klaassen12da1ad2016-04-04 14:20:37 -0700465 // Always cancel unrequested in-progress evaluation, so that we don't have to worry about
466 // subsequent asynchronous completion.
467 // Requested in-progress evaluations are handled below.
468 if (mCurrentState != CalculatorState.EVALUATE) {
469 mEvaluator.cancelAll(true);
470 }
471
472 switch (keyCode) {
473 case KeyEvent.KEYCODE_NUMPAD_ENTER:
474 case KeyEvent.KEYCODE_ENTER:
475 case KeyEvent.KEYCODE_DPAD_CENTER:
476 mCurrentButton = mEqualButton;
477 onEquals();
478 return true;
479 case KeyEvent.KEYCODE_DEL:
480 mCurrentButton = mDeleteButton;
481 onDelete();
482 return true;
Annie Chin56bcbf12016-09-23 17:04:22 -0700483 case KeyEvent.KEYCODE_CLEAR:
484 mCurrentButton = mClearButton;
485 onClear();
486 return true;
Justin Klaassen12da1ad2016-04-04 14:20:37 -0700487 default:
488 cancelIfEvaluating(false);
489 final int raw = event.getKeyCharacterMap().get(keyCode, event.getMetaState());
490 if ((raw & KeyCharacterMap.COMBINING_ACCENT) != 0) {
491 return true; // discard
492 }
493 // Try to discard non-printing characters and the like.
494 // The user will have to explicitly delete other junk that gets past us.
495 if (Character.isIdentifierIgnorable(raw) || Character.isWhitespace(raw)) {
496 return true;
497 }
498 char c = (char) raw;
499 if (c == '=') {
500 mCurrentButton = mEqualButton;
501 onEquals();
502 } else {
503 addChars(String.valueOf(c), true);
504 redisplayAfterFormulaChange();
505 }
506 return true;
Justin Klaassen4b3af052014-05-27 17:53:10 -0700507 }
508 }
509
Justin Klaassene2711cb2015-05-28 11:13:17 -0700510 /**
511 * Invoked whenever the inverse button is toggled to update the UI.
512 *
513 * @param showInverse {@code true} if inverse functions should be shown
514 */
515 private void onInverseToggled(boolean showInverse) {
Justin Klaassen3e223ea2016-02-05 14:18:06 -0800516 mInverseToggle.setSelected(showInverse);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700517 if (showInverse) {
518 mInverseToggle.setContentDescription(getString(R.string.desc_inv_on));
Justin Klaassen721ec842015-05-28 14:30:08 -0700519 for (View invertibleButton : mInvertibleButtons) {
520 invertibleButton.setVisibility(View.GONE);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700521 }
522 for (View inverseButton : mInverseButtons) {
523 inverseButton.setVisibility(View.VISIBLE);
524 }
525 } else {
526 mInverseToggle.setContentDescription(getString(R.string.desc_inv_off));
Justin Klaassen721ec842015-05-28 14:30:08 -0700527 for (View invertibleButton : mInvertibleButtons) {
528 invertibleButton.setVisibility(View.VISIBLE);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700529 }
530 for (View inverseButton : mInverseButtons) {
531 inverseButton.setVisibility(View.GONE);
532 }
533 }
534 }
535
536 /**
Christine Frankseeff27f2016-07-29 12:05:29 -0700537 * Invoked whenever the deg/rad mode may have changed to update the UI. Note that the mode has
538 * not necessarily actually changed where this is invoked.
Justin Klaassene2711cb2015-05-28 11:13:17 -0700539 *
540 * @param degreeMode {@code true} if in degree mode
541 */
542 private void onModeChanged(boolean degreeMode) {
543 if (degreeMode) {
Justin Klaassend48b7562015-04-16 16:51:38 -0700544 mModeView.setText(R.string.mode_deg);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700545 mModeView.setContentDescription(getString(R.string.desc_mode_deg));
546
547 mModeToggle.setText(R.string.mode_rad);
548 mModeToggle.setContentDescription(getString(R.string.desc_switch_rad));
Hans Boehmbfe8c222015-04-02 16:26:07 -0700549 } else {
Justin Klaassend48b7562015-04-16 16:51:38 -0700550 mModeView.setText(R.string.mode_rad);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700551 mModeView.setContentDescription(getString(R.string.desc_mode_rad));
552
553 mModeToggle.setText(R.string.mode_deg);
554 mModeToggle.setContentDescription(getString(R.string.desc_switch_deg));
Hans Boehmbfe8c222015-04-02 16:26:07 -0700555 }
556 }
Hans Boehm84614952014-11-25 18:46:17 -0800557
Hans Boehm5d79d102015-09-16 16:33:47 -0700558 /**
559 * Switch to INPUT from RESULT state in response to input of the specified button_id.
560 * View.NO_ID is treated as an incomplete function id.
561 */
562 private void switchToInput(int button_id) {
563 if (KeyMaps.isBinary(button_id) || KeyMaps.isSuffix(button_id)) {
564 mEvaluator.collapse();
565 } else {
566 announceClearedForAccessibility();
567 mEvaluator.clear();
568 }
569 setState(CalculatorState.INPUT);
570 }
571
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700572 // Add the given button id to input expression.
573 // If appropriate, clear the expression before doing so.
574 private void addKeyToExpr(int id) {
575 if (mCurrentState == CalculatorState.ERROR) {
576 setState(CalculatorState.INPUT);
577 } else if (mCurrentState == CalculatorState.RESULT) {
Hans Boehm5d79d102015-09-16 16:33:47 -0700578 switchToInput(id);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700579 }
580 if (!mEvaluator.append(id)) {
581 // TODO: Some user visible feedback?
582 }
583 }
584
Hans Boehm017de982015-06-10 17:46:03 -0700585 /**
586 * Add the given button id to input expression, assuming it was explicitly
587 * typed/touched.
588 * We perform slightly more aggressive correction than in pasted expressions.
589 */
590 private void addExplicitKeyToExpr(int id) {
591 if (mCurrentState == CalculatorState.INPUT && id == R.id.op_sub) {
592 mEvaluator.getExpr().removeTrailingAdditiveOperators();
593 }
594 addKeyToExpr(id);
595 }
596
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700597 private void redisplayAfterFormulaChange() {
598 // TODO: Could do this more incrementally.
599 redisplayFormula();
600 setState(CalculatorState.INPUT);
Hans Boehmaf04c3a2016-01-27 14:50:08 -0800601 if (haveUnprocessed()) {
Justin Klaassen44595162015-05-28 17:55:20 -0700602 mResultText.clear();
Hans Boehmaf04c3a2016-01-27 14:50:08 -0800603 // Force reevaluation when text is deleted, even if expression is unchanged.
604 mEvaluator.touch();
605 } else {
606 if (mEvaluator.getExpr().hasInterestingOps()) {
607 mEvaluator.evaluateAndShowResult();
608 } else {
609 mResultText.clear();
610 }
Hans Boehmc023b732015-04-29 11:30:47 -0700611 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700612 }
613
Hans Boehm52d477a2016-04-01 17:42:50 -0700614 /**
615 * Show the toolbar.
616 * Automatically hide it again if it's not relevant to current formula.
617 */
618 private void showAndMaybeHideToolbar() {
619 final boolean shouldBeVisible =
620 mCurrentState == CalculatorState.INPUT && mEvaluator.hasTrigFuncs();
621 mDisplayView.showToolbar(!shouldBeVisible);
622 }
623
624 /**
625 * Display or hide the toolbar depending on calculator state.
626 */
627 private void showOrHideToolbar() {
628 final boolean shouldBeVisible =
629 mCurrentState == CalculatorState.INPUT && mEvaluator.hasTrigFuncs();
630 if (shouldBeVisible) {
631 mDisplayView.showToolbar(false);
632 } else {
633 mDisplayView.hideToolbar();
634 }
635 }
636
Justin Klaassen4b3af052014-05-27 17:53:10 -0700637 public void onButtonClick(View view) {
Hans Boehmc1ea0912015-06-19 15:05:07 -0700638 // Any animation is ended before we get here.
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700639 mCurrentButton = view;
Chenjie Yu3937b652016-06-01 23:14:26 -0700640 stopActionModeOrContextMenu();
Justin Klaassen9d33cdc2016-02-21 14:16:14 -0800641
Hans Boehmc1ea0912015-06-19 15:05:07 -0700642 // See onKey above for the rationale behind some of the behavior below:
643 if (mCurrentState != CalculatorState.EVALUATE) {
644 // Cancel evaluations that were not specifically requested.
645 mEvaluator.cancelAll(true);
Hans Boehm84614952014-11-25 18:46:17 -0800646 }
Justin Klaassen9d33cdc2016-02-21 14:16:14 -0800647
Justin Klaassend48b7562015-04-16 16:51:38 -0700648 final int id = view.getId();
Hans Boehm84614952014-11-25 18:46:17 -0800649 switch (id) {
Justin Klaassen4b3af052014-05-27 17:53:10 -0700650 case R.id.eq:
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700651 onEquals();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700652 break;
653 case R.id.del:
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700654 onDelete();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700655 break;
656 case R.id.clr:
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700657 onClear();
Hans Boehm52d477a2016-04-01 17:42:50 -0700658 return; // Toolbar visibility adjusted at end of animation.
Justin Klaassene2711cb2015-05-28 11:13:17 -0700659 case R.id.toggle_inv:
660 final boolean selected = !mInverseToggle.isSelected();
661 mInverseToggle.setSelected(selected);
662 onInverseToggled(selected);
Hans Boehmc1ea0912015-06-19 15:05:07 -0700663 if (mCurrentState == CalculatorState.RESULT) {
664 mResultText.redisplay(); // In case we cancelled reevaluation.
665 }
Justin Klaassene2711cb2015-05-28 11:13:17 -0700666 break;
667 case R.id.toggle_mode:
Hans Boehmc1ea0912015-06-19 15:05:07 -0700668 cancelIfEvaluating(false);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700669 final boolean mode = !mEvaluator.getDegreeMode();
Hans Boehmbfe8c222015-04-02 16:26:07 -0700670 if (mCurrentState == CalculatorState.RESULT) {
671 mEvaluator.collapse(); // Capture result evaluated in old mode
672 redisplayFormula();
673 }
674 // In input mode, we reinterpret already entered trig functions.
675 mEvaluator.setDegreeMode(mode);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700676 onModeChanged(mode);
Christine Frankseeff27f2016-07-29 12:05:29 -0700677 // Show the toolbar to highlight the mode change.
678 showAndMaybeHideToolbar();
Hans Boehmbfe8c222015-04-02 16:26:07 -0700679 setState(CalculatorState.INPUT);
Justin Klaassen44595162015-05-28 17:55:20 -0700680 mResultText.clear();
Hans Boehmaf04c3a2016-01-27 14:50:08 -0800681 if (!haveUnprocessed() && mEvaluator.getExpr().hasInterestingOps()) {
Hans Boehmc023b732015-04-29 11:30:47 -0700682 mEvaluator.evaluateAndShowResult();
683 }
Christine Frankseeff27f2016-07-29 12:05:29 -0700684 return;
Justin Klaassen4b3af052014-05-27 17:53:10 -0700685 default:
Hans Boehmc1ea0912015-06-19 15:05:07 -0700686 cancelIfEvaluating(false);
Hans Boehmaf04c3a2016-01-27 14:50:08 -0800687 if (haveUnprocessed()) {
688 // For consistency, append as uninterpreted characters.
689 // This may actually be useful for a left parenthesis.
690 addChars(KeyMaps.toString(this, id), true);
691 } else {
692 addExplicitKeyToExpr(id);
693 redisplayAfterFormulaChange();
694 }
Justin Klaassen4b3af052014-05-27 17:53:10 -0700695 break;
696 }
Hans Boehm52d477a2016-04-01 17:42:50 -0700697 showOrHideToolbar();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700698 }
699
Hans Boehm84614952014-11-25 18:46:17 -0800700 void redisplayFormula() {
Hans Boehm8a4f81c2015-07-09 10:41:25 -0700701 SpannableStringBuilder formula = mEvaluator.getExpr().toSpannableStringBuilder(this);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700702 if (mUnprocessedChars != null) {
703 // Add and highlight characters we couldn't process.
Hans Boehm8a4f81c2015-07-09 10:41:25 -0700704 formula.append(mUnprocessedChars, mUnprocessedColorSpan,
705 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700706 }
Hans Boehm8a4f81c2015-07-09 10:41:25 -0700707 mFormulaText.changeTextTo(formula);
Annie Chinf360ef02016-03-10 13:45:39 -0800708 mFormulaText.setContentDescription(TextUtils.isEmpty(formula)
Justin Klaassend1831412016-07-19 21:59:10 -0700709 ? getString(R.string.desc_formula) : null);
Hans Boehm84614952014-11-25 18:46:17 -0800710 }
711
Justin Klaassen4b3af052014-05-27 17:53:10 -0700712 @Override
713 public boolean onLongClick(View view) {
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700714 mCurrentButton = view;
715
Justin Klaassen4b3af052014-05-27 17:53:10 -0700716 if (view.getId() == R.id.del) {
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700717 onClear();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700718 return true;
719 }
720 return false;
721 }
722
Hans Boehm84614952014-11-25 18:46:17 -0800723 // Initial evaluation completed successfully. Initiate display.
Hans Boehma0e45f32015-05-30 13:20:35 -0700724 public void onEvaluate(int initDisplayPrec, int msd, int leastDigPos,
725 String truncatedWholeNumber) {
Justin Klaassend48b7562015-04-16 16:51:38 -0700726 // Invalidate any options that may depend on the current result.
727 invalidateOptionsMenu();
728
Hans Boehma0e45f32015-05-30 13:20:35 -0700729 mResultText.displayResult(initDisplayPrec, msd, leastDigPos, truncatedWholeNumber);
Hans Boehm61568a12015-05-18 18:25:41 -0700730 if (mCurrentState != CalculatorState.INPUT) { // in EVALUATE or INIT state
Hans Boehm84614952014-11-25 18:46:17 -0800731 onResult(mCurrentState != CalculatorState.INIT);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700732 }
Hans Boehm84614952014-11-25 18:46:17 -0800733 }
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700734
Hans Boehmc1ea0912015-06-19 15:05:07 -0700735 // Reset state to reflect evaluator cancellation. Invoked by evaluator.
Hans Boehm84614952014-11-25 18:46:17 -0800736 public void onCancelled() {
737 // We should be in EVALUATE state.
Hans Boehm84614952014-11-25 18:46:17 -0800738 setState(CalculatorState.INPUT);
Justin Klaassen44595162015-05-28 17:55:20 -0700739 mResultText.clear();
Hans Boehm84614952014-11-25 18:46:17 -0800740 }
741
742 // Reevaluation completed; ask result to redisplay current value.
743 public void onReevaluate()
744 {
Justin Klaassen44595162015-05-28 17:55:20 -0700745 mResultText.redisplay();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700746 }
747
Justin Klaassenfed941a2014-06-09 18:42:40 +0100748 @Override
749 public void onTextSizeChanged(final TextView textView, float oldSize) {
750 if (mCurrentState != CalculatorState.INPUT) {
751 // Only animate text changes that occur from user input.
752 return;
753 }
754
755 // Calculate the values needed to perform the scale and translation animations,
756 // maintaining the same apparent baseline for the displayed text.
757 final float textScale = oldSize / textView.getTextSize();
758 final float translationX = (1.0f - textScale) *
759 (textView.getWidth() / 2.0f - textView.getPaddingEnd());
760 final float translationY = (1.0f - textScale) *
761 (textView.getHeight() / 2.0f - textView.getPaddingBottom());
762
763 final AnimatorSet animatorSet = new AnimatorSet();
764 animatorSet.playTogether(
765 ObjectAnimator.ofFloat(textView, View.SCALE_X, textScale, 1.0f),
766 ObjectAnimator.ofFloat(textView, View.SCALE_Y, textScale, 1.0f),
767 ObjectAnimator.ofFloat(textView, View.TRANSLATION_X, translationX, 0.0f),
768 ObjectAnimator.ofFloat(textView, View.TRANSLATION_Y, translationY, 0.0f));
Justin Klaassen94db7202014-06-11 11:22:31 -0700769 animatorSet.setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime));
Justin Klaassenfed941a2014-06-09 18:42:40 +0100770 animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
771 animatorSet.start();
772 }
773
Hans Boehmc1ea0912015-06-19 15:05:07 -0700774 /**
775 * Cancel any in-progress explicitly requested evaluations.
776 * @param quiet suppress pop-up message. Explicit evaluation can change the expression
777 value, and certainly changes the display, so it seems reasonable to warn.
778 * @return true if there was such an evaluation
779 */
780 private boolean cancelIfEvaluating(boolean quiet) {
781 if (mCurrentState == CalculatorState.EVALUATE) {
782 mEvaluator.cancelAll(quiet);
783 return true;
784 } else {
785 return false;
786 }
787 }
788
Hans Boehmaf04c3a2016-01-27 14:50:08 -0800789 private boolean haveUnprocessed() {
790 return mUnprocessedChars != null && !mUnprocessedChars.isEmpty();
791 }
792
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700793 private void onEquals() {
Hans Boehm56d6e762016-06-06 11:46:29 -0700794 // Ignore if in non-INPUT state, or if there are no operators.
Justin Klaassena8075af2016-07-27 15:24:45 -0700795 if (mCurrentState == CalculatorState.INPUT) {
Hans Boehmaf04c3a2016-01-27 14:50:08 -0800796 if (haveUnprocessed()) {
Justin Klaassena8075af2016-07-27 15:24:45 -0700797 setState(CalculatorState.EVALUATE);
Hans Boehmaf04c3a2016-01-27 14:50:08 -0800798 onError(R.string.error_syntax);
Justin Klaassena8075af2016-07-27 15:24:45 -0700799 } else if (mEvaluator.getExpr().hasInterestingOps()) {
800 setState(CalculatorState.EVALUATE);
Hans Boehmaf04c3a2016-01-27 14:50:08 -0800801 mEvaluator.requireResult();
802 }
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700803 }
804 }
805
806 private void onDelete() {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700807 // Delete works like backspace; remove the last character or operator from the expression.
808 // Note that we handle keyboard delete exactly like the delete button. For
809 // example the delete button can be used to delete a character from an incomplete
810 // function name typed on a physical keyboard.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700811 // This should be impossible in RESULT state.
Hans Boehmc1ea0912015-06-19 15:05:07 -0700812 // If there is an in-progress explicit evaluation, just cancel it and return.
813 if (cancelIfEvaluating(false)) return;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700814 setState(CalculatorState.INPUT);
Hans Boehmaf04c3a2016-01-27 14:50:08 -0800815 if (haveUnprocessed()) {
816 mUnprocessedChars = mUnprocessedChars.substring(0, mUnprocessedChars.length() - 1);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700817 } else {
Hans Boehmc023b732015-04-29 11:30:47 -0700818 mEvaluator.delete();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700819 }
Hans Boehmaf04c3a2016-01-27 14:50:08 -0800820 if (mEvaluator.getExpr().isEmpty() && !haveUnprocessed()) {
Hans Boehmdb6f9992015-08-19 12:32:56 -0700821 // Resulting formula won't be announced, since it's empty.
822 announceClearedForAccessibility();
823 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700824 redisplayAfterFormulaChange();
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700825 }
826
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700827 private void reveal(View sourceView, int colorRes, AnimatorListener listener) {
Justin Klaassen06360f92014-08-28 11:08:44 -0700828 final ViewGroupOverlay groupOverlay =
829 (ViewGroupOverlay) getWindow().getDecorView().getOverlay();
Justin Klaassen8fff1442014-06-19 10:43:29 -0700830
831 final Rect displayRect = new Rect();
Justin Klaassen06360f92014-08-28 11:08:44 -0700832 mDisplayView.getGlobalVisibleRect(displayRect);
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700833
834 // Make reveal cover the display and status bar.
835 final View revealView = new View(this);
Justin Klaassen8fff1442014-06-19 10:43:29 -0700836 revealView.setBottom(displayRect.bottom);
837 revealView.setLeft(displayRect.left);
838 revealView.setRight(displayRect.right);
Chenjie Yu3937b652016-06-01 23:14:26 -0700839 revealView.setBackgroundColor(ContextCompat.getColor(this, colorRes));
Justin Klaassen06360f92014-08-28 11:08:44 -0700840 groupOverlay.add(revealView);
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700841
Justin Klaassen4b3af052014-05-27 17:53:10 -0700842 final int[] clearLocation = new int[2];
843 sourceView.getLocationInWindow(clearLocation);
844 clearLocation[0] += sourceView.getWidth() / 2;
845 clearLocation[1] += sourceView.getHeight() / 2;
846
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700847 final int revealCenterX = clearLocation[0] - revealView.getLeft();
848 final int revealCenterY = clearLocation[1] - revealView.getTop();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700849
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700850 final double x1_2 = Math.pow(revealView.getLeft() - revealCenterX, 2);
851 final double x2_2 = Math.pow(revealView.getRight() - revealCenterX, 2);
852 final double y_2 = Math.pow(revealView.getTop() - revealCenterY, 2);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700853 final float revealRadius = (float) Math.max(Math.sqrt(x1_2 + y_2), Math.sqrt(x2_2 + y_2));
854
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700855 final Animator revealAnimator =
856 ViewAnimationUtils.createCircularReveal(revealView,
ztenghui3d6ecaf2014-06-05 09:56:00 -0700857 revealCenterX, revealCenterY, 0.0f, revealRadius);
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700858 revealAnimator.setDuration(
Justin Klaassen4b3af052014-05-27 17:53:10 -0700859 getResources().getInteger(android.R.integer.config_longAnimTime));
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700860 revealAnimator.addListener(listener);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700861
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700862 final Animator alphaAnimator = ObjectAnimator.ofFloat(revealView, View.ALPHA, 0.0f);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700863 alphaAnimator.setDuration(
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700864 getResources().getInteger(android.R.integer.config_mediumAnimTime));
Justin Klaassen4b3af052014-05-27 17:53:10 -0700865
866 final AnimatorSet animatorSet = new AnimatorSet();
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700867 animatorSet.play(revealAnimator).before(alphaAnimator);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700868 animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
869 animatorSet.addListener(new AnimatorListenerAdapter() {
870 @Override
Justin Klaassen4b3af052014-05-27 17:53:10 -0700871 public void onAnimationEnd(Animator animator) {
Justin Klaassen8fff1442014-06-19 10:43:29 -0700872 groupOverlay.remove(revealView);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700873 mCurrentAnimator = null;
874 }
875 });
876
877 mCurrentAnimator = animatorSet;
878 animatorSet.start();
879 }
880
Hans Boehmdb6f9992015-08-19 12:32:56 -0700881 private void announceClearedForAccessibility() {
882 mResultText.announceForAccessibility(getResources().getString(R.string.cleared));
Hans Boehmccc55662015-07-07 14:16:59 -0700883 }
884
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700885 private void onClear() {
Justin Klaassen1a428cf2016-02-24 15:58:18 -0800886 if (mEvaluator.getExpr().isEmpty() && !haveUnprocessed()) {
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700887 return;
888 }
Hans Boehmc1ea0912015-06-19 15:05:07 -0700889 cancelIfEvaluating(true);
Hans Boehmdb6f9992015-08-19 12:32:56 -0700890 announceClearedForAccessibility();
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700891 reveal(mCurrentButton, R.color.calculator_accent_color, new AnimatorListenerAdapter() {
892 @Override
893 public void onAnimationEnd(Animator animation) {
Hans Boehm760a9dc2015-04-20 10:27:12 -0700894 mUnprocessedChars = null;
Justin Klaassen44595162015-05-28 17:55:20 -0700895 mResultText.clear();
Hans Boehm760a9dc2015-04-20 10:27:12 -0700896 mEvaluator.clear();
897 setState(CalculatorState.INPUT);
Hans Boehm52d477a2016-04-01 17:42:50 -0700898 showOrHideToolbar();
Hans Boehm84614952014-11-25 18:46:17 -0800899 redisplayFormula();
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700900 }
901 });
902 }
903
Hans Boehm84614952014-11-25 18:46:17 -0800904 // Evaluation encountered en error. Display the error.
905 void onError(final int errorResourceId) {
Hans Boehmfbcef702015-04-27 18:07:47 -0700906 if (mCurrentState == CalculatorState.EVALUATE) {
907 setState(CalculatorState.ANIMATE);
Hans Boehmccc55662015-07-07 14:16:59 -0700908 mResultText.announceForAccessibility(getResources().getString(errorResourceId));
Hans Boehmfbcef702015-04-27 18:07:47 -0700909 reveal(mCurrentButton, R.color.calculator_error_color,
910 new AnimatorListenerAdapter() {
911 @Override
912 public void onAnimationEnd(Animator animation) {
913 setState(CalculatorState.ERROR);
Justin Klaassen44595162015-05-28 17:55:20 -0700914 mResultText.displayError(errorResourceId);
Hans Boehmfbcef702015-04-27 18:07:47 -0700915 }
916 });
917 } else if (mCurrentState == CalculatorState.INIT) {
918 setState(CalculatorState.ERROR);
Justin Klaassen44595162015-05-28 17:55:20 -0700919 mResultText.displayError(errorResourceId);
Hans Boehmc023b732015-04-29 11:30:47 -0700920 } else {
Justin Klaassen44595162015-05-28 17:55:20 -0700921 mResultText.clear();
Justin Klaassen2be4fdb2014-08-06 19:54:09 -0700922 }
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700923 }
924
Hans Boehm84614952014-11-25 18:46:17 -0800925 // Animate movement of result into the top formula slot.
926 // Result window now remains translated in the top slot while the result is displayed.
927 // (We convert it back to formula use only when the user provides new input.)
Justin Klaassen44595162015-05-28 17:55:20 -0700928 // Historical note: In the Lollipop version, this invisibly and instantaneously moved
Hans Boehm84614952014-11-25 18:46:17 -0800929 // formula and result displays back at the end of the animation. We no longer do that,
930 // so that we can continue to properly support scrolling of the result.
931 // We assume the result already contains the text to be expanded.
932 private void onResult(boolean animate) {
Justin Klaassen44595162015-05-28 17:55:20 -0700933 // Calculate the textSize that would be used to display the result in the formula.
934 // For scrollable results just use the minimum textSize to maximize the number of digits
935 // that are visible on screen.
936 float textSize = mFormulaText.getMinimumTextSize();
937 if (!mResultText.isScrollable()) {
938 textSize = mFormulaText.getVariableTextSize(mResultText.getText().toString());
939 }
940
941 // Scale the result to match the calculated textSize, minimizing the jump-cut transition
942 // when a result is reused in a subsequent expression.
943 final float resultScale = textSize / mResultText.getTextSize();
944
945 // Set the result's pivot to match its gravity.
946 mResultText.setPivotX(mResultText.getWidth() - mResultText.getPaddingRight());
947 mResultText.setPivotY(mResultText.getHeight() - mResultText.getPaddingBottom());
948
949 // Calculate the necessary translations so the result takes the place of the formula and
950 // the formula moves off the top of the screen.
Annie Chin28589dc2016-06-09 17:50:51 -0700951 final float resultTranslationY = (mFormulaContainer.getBottom() - mResultText.getBottom())
952 - (mFormulaText.getPaddingBottom() - mResultText.getPaddingBottom());
953 float formulaTranslationY = -mFormulaContainer.getBottom();
Annie Chin26e159e2016-05-18 15:17:14 -0700954 if (mOneLine) {
955 // Position the result text.
956 mResultText.setY(mResultText.getBottom());
Annie Chin28589dc2016-06-09 17:50:51 -0700957 formulaTranslationY = -(findViewById(R.id.toolbar).getBottom()
958 + mFormulaContainer.getBottom());
Annie Chin26e159e2016-05-18 15:17:14 -0700959 }
Justin Klaassen4b3af052014-05-27 17:53:10 -0700960
Justin Klaassen44595162015-05-28 17:55:20 -0700961 // Change the result's textColor to match the formula.
962 final int formulaTextColor = mFormulaText.getCurrentTextColor();
963
Hans Boehm84614952014-11-25 18:46:17 -0800964 if (animate) {
Hans Boehmccc55662015-07-07 14:16:59 -0700965 mResultText.announceForAccessibility(getResources().getString(R.string.desc_eq));
966 mResultText.announceForAccessibility(mResultText.getText());
Hans Boehmc1ea0912015-06-19 15:05:07 -0700967 setState(CalculatorState.ANIMATE);
Hans Boehm84614952014-11-25 18:46:17 -0800968 final AnimatorSet animatorSet = new AnimatorSet();
969 animatorSet.playTogether(
Justin Klaassen44595162015-05-28 17:55:20 -0700970 ObjectAnimator.ofPropertyValuesHolder(mResultText,
971 PropertyValuesHolder.ofFloat(View.SCALE_X, resultScale),
972 PropertyValuesHolder.ofFloat(View.SCALE_Y, resultScale),
973 PropertyValuesHolder.ofFloat(View.TRANSLATION_Y, resultTranslationY)),
974 ObjectAnimator.ofArgb(mResultText, TEXT_COLOR, formulaTextColor),
Annie Chine918fd22016-03-09 11:07:54 -0800975 ObjectAnimator.ofFloat(mFormulaContainer, View.TRANSLATION_Y,
976 formulaTranslationY));
Justin Klaassen44595162015-05-28 17:55:20 -0700977 animatorSet.setDuration(getResources().getInteger(
978 android.R.integer.config_longAnimTime));
Hans Boehm84614952014-11-25 18:46:17 -0800979 animatorSet.addListener(new AnimatorListenerAdapter() {
980 @Override
Hans Boehm84614952014-11-25 18:46:17 -0800981 public void onAnimationEnd(Animator animation) {
982 setState(CalculatorState.RESULT);
983 mCurrentAnimator = null;
984 }
985 });
Justin Klaassen4b3af052014-05-27 17:53:10 -0700986
Hans Boehm84614952014-11-25 18:46:17 -0800987 mCurrentAnimator = animatorSet;
988 animatorSet.start();
989 } else /* No animation desired; get there fast, e.g. when restarting */ {
Justin Klaassen44595162015-05-28 17:55:20 -0700990 mResultText.setScaleX(resultScale);
991 mResultText.setScaleY(resultScale);
992 mResultText.setTranslationY(resultTranslationY);
993 mResultText.setTextColor(formulaTextColor);
Annie Chine918fd22016-03-09 11:07:54 -0800994 mFormulaContainer.setTranslationY(formulaTranslationY);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700995 setState(CalculatorState.RESULT);
Hans Boehm84614952014-11-25 18:46:17 -0800996 }
Justin Klaassen4b3af052014-05-27 17:53:10 -0700997 }
Hans Boehm84614952014-11-25 18:46:17 -0800998
999 // Restore positions of the formula and result displays back to their original,
1000 // pre-animation state.
1001 private void restoreDisplayPositions() {
1002 // Clear result.
Justin Klaassen44595162015-05-28 17:55:20 -07001003 mResultText.setText("");
Hans Boehm84614952014-11-25 18:46:17 -08001004 // Reset all of the values modified during the animation.
Justin Klaassen44595162015-05-28 17:55:20 -07001005 mResultText.setScaleX(1.0f);
1006 mResultText.setScaleY(1.0f);
1007 mResultText.setTranslationX(0.0f);
1008 mResultText.setTranslationY(0.0f);
Annie Chine918fd22016-03-09 11:07:54 -08001009 mFormulaContainer.setTranslationY(0.0f);
Hans Boehm84614952014-11-25 18:46:17 -08001010
Hans Boehm08e8f322015-04-21 13:18:38 -07001011 mFormulaText.requestFocus();
Hans Boehm5e6a0ca2015-09-22 17:09:01 -07001012 }
1013
1014 @Override
1015 public void onClick(AlertDialogFragment fragment, int which) {
1016 if (which == DialogInterface.BUTTON_POSITIVE) {
1017 // Timeout extension request.
1018 mEvaluator.setLongTimeOut();
1019 }
1020 }
Hans Boehm84614952014-11-25 18:46:17 -08001021
Justin Klaassend48b7562015-04-16 16:51:38 -07001022 @Override
1023 public boolean onCreateOptionsMenu(Menu menu) {
Justin Klaassend36d63e2015-05-05 12:59:36 -07001024 super.onCreateOptionsMenu(menu);
1025
1026 getMenuInflater().inflate(R.menu.activity_calculator, menu);
Justin Klaassend48b7562015-04-16 16:51:38 -07001027 return true;
1028 }
1029
1030 @Override
1031 public boolean onPrepareOptionsMenu(Menu menu) {
Justin Klaassend36d63e2015-05-05 12:59:36 -07001032 super.onPrepareOptionsMenu(menu);
1033
1034 // Show the leading option when displaying a result.
1035 menu.findItem(R.id.menu_leading).setVisible(mCurrentState == CalculatorState.RESULT);
1036
1037 // Show the fraction option when displaying a rational result.
1038 menu.findItem(R.id.menu_fraction).setVisible(mCurrentState == CalculatorState.RESULT
Hans Boehm995e5eb2016-02-08 11:03:01 -08001039 && mEvaluator.getResult().exactlyDisplayable());
Justin Klaassend36d63e2015-05-05 12:59:36 -07001040
Justin Klaassend48b7562015-04-16 16:51:38 -07001041 return true;
Hans Boehm84614952014-11-25 18:46:17 -08001042 }
1043
1044 @Override
Justin Klaassend48b7562015-04-16 16:51:38 -07001045 public boolean onOptionsItemSelected(MenuItem item) {
Hans Boehm84614952014-11-25 18:46:17 -08001046 switch (item.getItemId()) {
Justin Klaassend36d63e2015-05-05 12:59:36 -07001047 case R.id.menu_leading:
1048 displayFull();
Hans Boehm84614952014-11-25 18:46:17 -08001049 return true;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001050 case R.id.menu_fraction:
1051 displayFraction();
1052 return true;
Justin Klaassend36d63e2015-05-05 12:59:36 -07001053 case R.id.menu_licenses:
1054 startActivity(new Intent(this, Licenses.class));
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001055 return true;
Hans Boehm84614952014-11-25 18:46:17 -08001056 default:
1057 return super.onOptionsItemSelected(item);
1058 }
1059 }
1060
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001061 private void displayMessage(String s) {
Hans Boehm5e6a0ca2015-09-22 17:09:01 -07001062 AlertDialogFragment.showMessageDialog(this, s, null);
Hans Boehm84614952014-11-25 18:46:17 -08001063 }
1064
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001065 private void displayFraction() {
Hans Boehm995e5eb2016-02-08 11:03:01 -08001066 UnifiedReal result = mEvaluator.getResult();
Hans Boehm013969e2015-04-13 20:29:47 -07001067 displayMessage(KeyMaps.translateResult(result.toNiceString()));
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001068 }
1069
1070 // Display full result to currently evaluated precision
1071 private void displayFull() {
1072 Resources res = getResources();
Hans Boehm24c91ed2016-06-30 18:53:44 -07001073 String msg = mResultText.getFullText(true /* withSeparators */) + " ";
Justin Klaassen44595162015-05-28 17:55:20 -07001074 if (mResultText.fullTextIsExact()) {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001075 msg += res.getString(R.string.exact);
1076 } else {
1077 msg += res.getString(R.string.approximate);
1078 }
1079 displayMessage(msg);
1080 }
1081
Hans Boehm017de982015-06-10 17:46:03 -07001082 /**
1083 * Add input characters to the end of the expression.
1084 * Map them to the appropriate button pushes when possible. Leftover characters
1085 * are added to mUnprocessedChars, which is presumed to immediately precede the newly
1086 * added characters.
Hans Boehm65a99a42016-02-03 18:16:07 -08001087 * @param moreChars characters to be added
1088 * @param explicit these characters were explicitly typed by the user, not pasted
Hans Boehm017de982015-06-10 17:46:03 -07001089 */
1090 private void addChars(String moreChars, boolean explicit) {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001091 if (mUnprocessedChars != null) {
1092 moreChars = mUnprocessedChars + moreChars;
1093 }
1094 int current = 0;
1095 int len = moreChars.length();
Hans Boehm0b9806f2015-06-29 16:07:15 -07001096 boolean lastWasDigit = false;
Hans Boehm5d79d102015-09-16 16:33:47 -07001097 if (mCurrentState == CalculatorState.RESULT && len != 0) {
1098 // Clear display immediately for incomplete function name.
1099 switchToInput(KeyMaps.keyForChar(moreChars.charAt(current)));
1100 }
Hans Boehm24c91ed2016-06-30 18:53:44 -07001101 char groupingSeparator = KeyMaps.translateResult(",").charAt(0);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001102 while (current < len) {
1103 char c = moreChars.charAt(current);
Hans Boehm24c91ed2016-06-30 18:53:44 -07001104 if (Character.isSpaceChar(c) || c == groupingSeparator) {
1105 ++current;
1106 continue;
1107 }
Hans Boehm013969e2015-04-13 20:29:47 -07001108 int k = KeyMaps.keyForChar(c);
Hans Boehm0b9806f2015-06-29 16:07:15 -07001109 if (!explicit) {
1110 int expEnd;
1111 if (lastWasDigit && current !=
1112 (expEnd = Evaluator.exponentEnd(moreChars, current))) {
1113 // Process scientific notation with 'E' when pasting, in spite of ambiguity
1114 // with base of natural log.
1115 // Otherwise the 10^x key is the user's friend.
1116 mEvaluator.addExponent(moreChars, current, expEnd);
1117 current = expEnd;
1118 lastWasDigit = false;
1119 continue;
1120 } else {
1121 boolean isDigit = KeyMaps.digVal(k) != KeyMaps.NOT_DIGIT;
1122 if (current == 0 && (isDigit || k == R.id.dec_point)
1123 && mEvaluator.getExpr().hasTrailingConstant()) {
1124 // Refuse to concatenate pasted content to trailing constant.
1125 // This makes pasting of calculator results more consistent, whether or
1126 // not the old calculator instance is still around.
1127 addKeyToExpr(R.id.op_mul);
1128 }
1129 lastWasDigit = (isDigit || lastWasDigit && k == R.id.dec_point);
1130 }
1131 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001132 if (k != View.NO_ID) {
1133 mCurrentButton = findViewById(k);
Hans Boehm017de982015-06-10 17:46:03 -07001134 if (explicit) {
1135 addExplicitKeyToExpr(k);
1136 } else {
1137 addKeyToExpr(k);
1138 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001139 if (Character.isSurrogate(c)) {
1140 current += 2;
1141 } else {
1142 ++current;
1143 }
1144 continue;
1145 }
Hans Boehm013969e2015-04-13 20:29:47 -07001146 int f = KeyMaps.funForString(moreChars, current);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001147 if (f != View.NO_ID) {
1148 mCurrentButton = findViewById(f);
Hans Boehm017de982015-06-10 17:46:03 -07001149 if (explicit) {
1150 addExplicitKeyToExpr(f);
1151 } else {
1152 addKeyToExpr(f);
1153 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001154 if (f == R.id.op_sqrt) {
1155 // Square root entered as function; don't lose the parenthesis.
1156 addKeyToExpr(R.id.lparen);
1157 }
1158 current = moreChars.indexOf('(', current) + 1;
1159 continue;
1160 }
1161 // There are characters left, but we can't convert them to button presses.
1162 mUnprocessedChars = moreChars.substring(current);
1163 redisplayAfterFormulaChange();
Hans Boehm52d477a2016-04-01 17:42:50 -07001164 showOrHideToolbar();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001165 return;
1166 }
1167 mUnprocessedChars = null;
1168 redisplayAfterFormulaChange();
Hans Boehm52d477a2016-04-01 17:42:50 -07001169 showOrHideToolbar();
Hans Boehm84614952014-11-25 18:46:17 -08001170 }
1171
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001172 @Override
Justin Klaassenfc5ac822015-06-18 13:15:17 -07001173 public boolean onPaste(ClipData clip) {
1174 final ClipData.Item item = clip.getItemCount() == 0 ? null : clip.getItemAt(0);
1175 if (item == null) {
1176 // nothing to paste, bail early...
1177 return false;
1178 }
1179
1180 // Check if the item is a previously copied result, otherwise paste as raw text.
1181 final Uri uri = item.getUri();
1182 if (uri != null && mEvaluator.isLastSaved(uri)) {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001183 if (mCurrentState == CalculatorState.ERROR
Justin Klaassenfc5ac822015-06-18 13:15:17 -07001184 || mCurrentState == CalculatorState.RESULT) {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001185 setState(CalculatorState.INPUT);
1186 mEvaluator.clear();
Hans Boehm84614952014-11-25 18:46:17 -08001187 }
Hans Boehm3666e632015-07-27 18:33:12 -07001188 mEvaluator.appendSaved();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001189 redisplayAfterFormulaChange();
Justin Klaassenfc5ac822015-06-18 13:15:17 -07001190 } else {
Hans Boehm017de982015-06-10 17:46:03 -07001191 addChars(item.coerceToText(this).toString(), false);
Hans Boehm84614952014-11-25 18:46:17 -08001192 }
Justin Klaassenfc5ac822015-06-18 13:15:17 -07001193 return true;
Hans Boehm84614952014-11-25 18:46:17 -08001194 }
Chenjie Yu3937b652016-06-01 23:14:26 -07001195
1196 /**
1197 * Clean up animation for context menu.
1198 */
1199 @Override
1200 public void onContextMenuClosed(Menu menu) {
1201 stopActionModeOrContextMenu();
1202 }
Justin Klaassen4b3af052014-05-27 17:53:10 -07001203}