blob: c7e14a43eabb352f842a8df70d7dd839ead36f03 [file] [log] [blame]
Justin Klaassen4b3af052014-05-27 17:53:10 -07001/*
Justin Klaassen44595162015-05-28 17:55:20 -07002 * Copyright (C) 2015 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 Klaassen4b3af052014-05-27 17:53:10 -070034import android.app.Activity;
Justin Klaassenfc5ac822015-06-18 13:15:17 -070035import android.content.ClipData;
Justin Klaassend36d63e2015-05-05 12:59:36 -070036import android.content.Intent;
Hans Boehmbfe8c222015-04-02 16:26:07 -070037import android.content.res.Resources;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070038import android.graphics.Color;
Justin Klaassen8fff1442014-06-19 10:43:29 -070039import android.graphics.Rect;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070040import android.net.Uri;
Justin Klaassen4b3af052014-05-27 17:53:10 -070041import android.os.Bundle;
Justin Klaassenf79d6f62014-08-26 12:27:08 -070042import android.support.annotation.NonNull;
Justin Klaassen3b4d13d2014-06-06 18:18:37 +010043import android.support.v4.view.ViewPager;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070044import android.text.SpannableString;
Hans Boehm8a4f81c2015-07-09 10:41:25 -070045import android.text.SpannableStringBuilder;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070046import android.text.Spanned;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070047import android.text.style.ForegroundColorSpan;
Hans Boehm8a4f81c2015-07-09 10:41:25 -070048import android.text.TextUtils;
Justin Klaassen44595162015-05-28 17:55:20 -070049import android.util.Property;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070050import android.view.KeyCharacterMap;
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -070051import android.view.KeyEvent;
Hans Boehm84614952014-11-25 18:46:17 -080052import android.view.Menu;
53import android.view.MenuItem;
Justin Klaassen4b3af052014-05-27 17:53:10 -070054import android.view.View;
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -070055import android.view.View.OnKeyListener;
Justin Klaassen4b3af052014-05-27 17:53:10 -070056import android.view.View.OnLongClickListener;
Justin Klaassen5f2a3342014-06-11 17:40:22 -070057import android.view.ViewAnimationUtils;
Justin Klaassen8fff1442014-06-19 10:43:29 -070058import android.view.ViewGroupOverlay;
Justin Klaassen4b3af052014-05-27 17:53:10 -070059import android.view.animation.AccelerateDecelerateInterpolator;
Justin Klaassenfed941a2014-06-09 18:42:40 +010060import android.widget.TextView;
Justin Klaassend48b7562015-04-16 16:51:38 -070061import android.widget.Toolbar;
Justin Klaassenfed941a2014-06-09 18:42:40 +010062
Hans Boehm08e8f322015-04-21 13:18:38 -070063import com.android.calculator2.CalculatorText.OnTextSizeChangeListener;
Hans Boehm84614952014-11-25 18:46:17 -080064
65import java.io.ByteArrayInputStream;
Hans Boehm84614952014-11-25 18:46:17 -080066import java.io.ByteArrayOutputStream;
Hans Boehm84614952014-11-25 18:46:17 -080067import java.io.IOException;
Justin Klaassen721ec842015-05-28 14:30:08 -070068import java.io.ObjectInput;
69import java.io.ObjectInputStream;
70import java.io.ObjectOutput;
71import java.io.ObjectOutputStream;
Justin Klaassen4b3af052014-05-27 17:53:10 -070072
Justin Klaassen04f79c72014-06-27 17:25:35 -070073public class Calculator extends Activity
Justin Klaassenfc5ac822015-06-18 13:15:17 -070074 implements OnTextSizeChangeListener, OnLongClickListener, CalculatorText.OnPasteListener {
Justin Klaassen2be4fdb2014-08-06 19:54:09 -070075
76 /**
77 * Constant for an invalid resource id.
78 */
79 public static final int INVALID_RES_ID = -1;
Justin Klaassen4b3af052014-05-27 17:53:10 -070080
81 private enum CalculatorState {
Hans Boehm84614952014-11-25 18:46:17 -080082 INPUT, // Result and formula both visible, no evaluation requested,
83 // Though result may be visible on bottom line.
84 EVALUATE, // Both visible, evaluation requested, evaluation/animation incomplete.
Hans Boehmc1ea0912015-06-19 15:05:07 -070085 // Not used for instant result evaluation.
Hans Boehm84614952014-11-25 18:46:17 -080086 INIT, // Very temporary state used as alternative to EVALUATE
87 // during reinitialization. Do not animate on completion.
88 ANIMATE, // Result computed, animation to enlarge result window in progress.
89 RESULT, // Result displayed, formula invisible.
90 // If we are in RESULT state, the formula was evaluated without
91 // error to initial precision.
92 ERROR // Error displayed: Formula visible, result shows error message.
93 // Display similar to INPUT state.
Justin Klaassen4b3af052014-05-27 17:53:10 -070094 }
Hans Boehm84614952014-11-25 18:46:17 -080095 // Normal transition sequence is
96 // INPUT -> EVALUATE -> ANIMATE -> RESULT (or ERROR) -> INPUT
97 // A RESULT -> ERROR transition is possible in rare corner cases, in which
98 // a higher precision evaluation exposes an error. This is possible, since we
99 // initially evaluate assuming we were given a well-defined problem. If we
100 // were actually asked to compute sqrt(<extremely tiny negative number>) we produce 0
101 // unless we are asked for enough precision that we can distinguish the argument from zero.
102 // TODO: Consider further heuristics to reduce the chance of observing this?
103 // It already seems to be observable only in contrived cases.
104 // ANIMATE, ERROR, and RESULT are translated to an INIT state if the application
105 // is restarted in that state. This leads us to recompute and redisplay the result
106 // ASAP.
107 // TODO: Possibly save a bit more information, e.g. its initial display string
108 // or most significant digit position, to speed up restart.
Justin Klaassen4b3af052014-05-27 17:53:10 -0700109
Justin Klaassen44595162015-05-28 17:55:20 -0700110 private final Property<TextView, Integer> TEXT_COLOR =
111 new Property<TextView, Integer>(Integer.class, "textColor") {
112 @Override
113 public Integer get(TextView textView) {
114 return textView.getCurrentTextColor();
115 }
116
117 @Override
118 public void set(TextView textView, Integer textColor) {
119 textView.setTextColor(textColor);
120 }
121 };
122
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700123 // We currently assume that the formula does not change out from under us in
124 // any way. We explicitly handle all input to the formula here.
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700125 private final OnKeyListener mFormulaOnKeyListener = new OnKeyListener() {
126 @Override
127 public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
Hans Boehm1176f232015-05-11 16:26:03 -0700128 stopActionMode();
Justin Klaassen06c49442015-06-04 14:39:27 -0700129 // Never consume DPAD key events.
130 switch (keyCode) {
131 case KeyEvent.KEYCODE_DPAD_UP:
132 case KeyEvent.KEYCODE_DPAD_DOWN:
133 case KeyEvent.KEYCODE_DPAD_LEFT:
134 case KeyEvent.KEYCODE_DPAD_RIGHT:
135 return false;
136 }
Hans Boehmc1ea0912015-06-19 15:05:07 -0700137 // Always cancel unrequested in-progress evaluation, so that we don't have
138 // to worry about subsequent asynchronous completion.
139 // Requested in-progress evaluations are handled below.
140 if (mCurrentState != CalculatorState.EVALUATE) {
141 mEvaluator.cancelAll(true);
142 }
143 // In other cases we go ahead and process the input normally after cancelling:
Justin Klaassen06c49442015-06-04 14:39:27 -0700144 if (keyEvent.getAction() != KeyEvent.ACTION_UP) {
145 return true;
146 }
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700147 switch (keyCode) {
148 case KeyEvent.KEYCODE_NUMPAD_ENTER:
149 case KeyEvent.KEYCODE_ENTER:
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700150 case KeyEvent.KEYCODE_DPAD_CENTER:
151 mCurrentButton = mEqualButton;
152 onEquals();
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700153 return true;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700154 case KeyEvent.KEYCODE_DEL:
155 mCurrentButton = mDeleteButton;
156 onDelete();
157 return true;
158 default:
Hans Boehmc1ea0912015-06-19 15:05:07 -0700159 cancelIfEvaluating(false);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700160 final int raw = keyEvent.getKeyCharacterMap()
Justin Klaassen44595162015-05-28 17:55:20 -0700161 .get(keyCode, keyEvent.getMetaState());
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700162 if ((raw & KeyCharacterMap.COMBINING_ACCENT) != 0) {
163 return true; // discard
164 }
165 // Try to discard non-printing characters and the like.
166 // The user will have to explicitly delete other junk that gets past us.
167 if (Character.isIdentifierIgnorable(raw)
Justin Klaassen44595162015-05-28 17:55:20 -0700168 || Character.isWhitespace(raw)) {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700169 return true;
170 }
Justin Klaassen44595162015-05-28 17:55:20 -0700171 char c = (char) raw;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700172 if (c == '=') {
Hans Boehme57fb012015-05-07 19:52:32 -0700173 mCurrentButton = mEqualButton;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700174 onEquals();
175 } else {
Hans Boehm017de982015-06-10 17:46:03 -0700176 addChars(String.valueOf(c), true);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700177 redisplayAfterFormulaChange();
178 }
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700179 }
180 return false;
181 }
182 };
183
Hans Boehm84614952014-11-25 18:46:17 -0800184 private static final String NAME = Calculator.class.getName();
185 private static final String KEY_DISPLAY_STATE = NAME + "_display_state";
Hans Boehm760a9dc2015-04-20 10:27:12 -0700186 private static final String KEY_UNPROCESSED_CHARS = NAME + "_unprocessed_chars";
Hans Boehm84614952014-11-25 18:46:17 -0800187 private static final String KEY_EVAL_STATE = NAME + "_eval_state";
188 // Associated value is a byte array holding both mCalculatorState
189 // and the (much more complex) evaluator state.
Justin Klaassen741471e2014-06-11 09:43:44 -0700190
Justin Klaassen4b3af052014-05-27 17:53:10 -0700191 private CalculatorState mCurrentState;
Hans Boehm84614952014-11-25 18:46:17 -0800192 private Evaluator mEvaluator;
Justin Klaassen4b3af052014-05-27 17:53:10 -0700193
Justin Klaassen06360f92014-08-28 11:08:44 -0700194 private View mDisplayView;
Justin Klaassend48b7562015-04-16 16:51:38 -0700195 private TextView mModeView;
Hans Boehm08e8f322015-04-21 13:18:38 -0700196 private CalculatorText mFormulaText;
Justin Klaassen44595162015-05-28 17:55:20 -0700197 private CalculatorResult mResultText;
Justin Klaassend48b7562015-04-16 16:51:38 -0700198
Justin Klaassen3b4d13d2014-06-06 18:18:37 +0100199 private ViewPager mPadViewPager;
Justin Klaassen4b3af052014-05-27 17:53:10 -0700200 private View mDeleteButton;
201 private View mClearButton;
Justin Klaassend48b7562015-04-16 16:51:38 -0700202 private View mEqualButton;
Justin Klaassene2711cb2015-05-28 11:13:17 -0700203
204 private TextView mInverseToggle;
205 private TextView mModeToggle;
206
Justin Klaassen721ec842015-05-28 14:30:08 -0700207 private View[] mInvertibleButtons;
Justin Klaassene2711cb2015-05-28 11:13:17 -0700208 private View[] mInverseButtons;
Justin Klaassen4b3af052014-05-27 17:53:10 -0700209
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700210 private View mCurrentButton;
Justin Klaassen4b3af052014-05-27 17:53:10 -0700211 private Animator mCurrentAnimator;
212
Hans Boehm8a4f81c2015-07-09 10:41:25 -0700213 // Characters that were recently entered at the end of the display that have not yet
214 // been added to the underlying expression.
215 private String mUnprocessedChars = null;
216
217 // Color to highlight unprocessed characters from physical keyboard.
218 // TODO: should probably match this to the error color?
219 private ForegroundColorSpan mUnprocessedColorSpan = new ForegroundColorSpan(Color.RED);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700220
Justin Klaassen4b3af052014-05-27 17:53:10 -0700221 @Override
222 protected void onCreate(Bundle savedInstanceState) {
223 super.onCreate(savedInstanceState);
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700224 setContentView(R.layout.activity_calculator);
Justin Klaassend48b7562015-04-16 16:51:38 -0700225 setActionBar((Toolbar) findViewById(R.id.toolbar));
226
227 // Hide all default options in the ActionBar.
228 getActionBar().setDisplayOptions(0);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700229
Justin Klaassen06360f92014-08-28 11:08:44 -0700230 mDisplayView = findViewById(R.id.display);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700231 mModeView = (TextView) findViewById(R.id.mode);
Hans Boehm08e8f322015-04-21 13:18:38 -0700232 mFormulaText = (CalculatorText) findViewById(R.id.formula);
Justin Klaassen44595162015-05-28 17:55:20 -0700233 mResultText = (CalculatorResult) findViewById(R.id.result);
Justin Klaassend48b7562015-04-16 16:51:38 -0700234
Justin Klaassen3b4d13d2014-06-06 18:18:37 +0100235 mPadViewPager = (ViewPager) findViewById(R.id.pad_pager);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700236 mDeleteButton = findViewById(R.id.del);
237 mClearButton = findViewById(R.id.clr);
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700238 mEqualButton = findViewById(R.id.pad_numeric).findViewById(R.id.eq);
239 if (mEqualButton == null || mEqualButton.getVisibility() != View.VISIBLE) {
240 mEqualButton = findViewById(R.id.pad_operator).findViewById(R.id.eq);
241 }
Justin Klaassene2711cb2015-05-28 11:13:17 -0700242
243 mInverseToggle = (TextView) findViewById(R.id.toggle_inv);
244 mModeToggle = (TextView) findViewById(R.id.toggle_mode);
245
Justin Klaassen721ec842015-05-28 14:30:08 -0700246 mInvertibleButtons = new View[] {
247 findViewById(R.id.fun_sin),
248 findViewById(R.id.fun_cos),
Hans Boehm4db31b42015-05-31 12:19:05 -0700249 findViewById(R.id.fun_tan),
250 findViewById(R.id.fun_ln),
251 findViewById(R.id.fun_log),
252 findViewById(R.id.op_sqrt)
Justin Klaassene2711cb2015-05-28 11:13:17 -0700253 };
254 mInverseButtons = new View[] {
255 findViewById(R.id.fun_arcsin),
256 findViewById(R.id.fun_arccos),
Hans Boehm4db31b42015-05-31 12:19:05 -0700257 findViewById(R.id.fun_arctan),
258 findViewById(R.id.fun_exp),
259 findViewById(R.id.fun_10pow),
260 findViewById(R.id.op_sqr)
Justin Klaassene2711cb2015-05-28 11:13:17 -0700261 };
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700262
Justin Klaassen44595162015-05-28 17:55:20 -0700263 mEvaluator = new Evaluator(this, mResultText);
264 mResultText.setEvaluator(mEvaluator);
Hans Boehm013969e2015-04-13 20:29:47 -0700265 KeyMaps.setActivity(this);
Justin Klaassen2be4fdb2014-08-06 19:54:09 -0700266
Hans Boehm84614952014-11-25 18:46:17 -0800267 if (savedInstanceState != null) {
268 setState(CalculatorState.values()[
269 savedInstanceState.getInt(KEY_DISPLAY_STATE,
270 CalculatorState.INPUT.ordinal())]);
Hans Boehm760a9dc2015-04-20 10:27:12 -0700271 CharSequence unprocessed = savedInstanceState.getCharSequence(KEY_UNPROCESSED_CHARS);
272 if (unprocessed != null) {
273 mUnprocessedChars = unprocessed.toString();
274 }
275 byte[] state = savedInstanceState.getByteArray(KEY_EVAL_STATE);
Hans Boehm84614952014-11-25 18:46:17 -0800276 if (state != null) {
277 try (ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(state))) {
278 mEvaluator.restoreInstanceState(in);
279 } catch (Throwable ignored) {
280 // When in doubt, revert to clean state
281 mCurrentState = CalculatorState.INPUT;
282 mEvaluator.clear();
283 }
284 }
Hans Boehmfbcef702015-04-27 18:07:47 -0700285 } else {
286 mCurrentState = CalculatorState.INPUT;
287 mEvaluator.clear();
Hans Boehm84614952014-11-25 18:46:17 -0800288 }
Justin Klaassene2711cb2015-05-28 11:13:17 -0700289
Hans Boehm08e8f322015-04-21 13:18:38 -0700290 mFormulaText.setOnKeyListener(mFormulaOnKeyListener);
291 mFormulaText.setOnTextSizeChangeListener(this);
Justin Klaassenfc5ac822015-06-18 13:15:17 -0700292 mFormulaText.setOnPasteListener(this);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700293 mDeleteButton.setOnLongClickListener(this);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700294
295 onInverseToggled(mInverseToggle.isSelected());
296 onModeChanged(mEvaluator.getDegreeMode());
297
Hans Boehm84614952014-11-25 18:46:17 -0800298 if (mCurrentState != CalculatorState.INPUT) {
Hans Boehmfbcef702015-04-27 18:07:47 -0700299 // Just reevaluate.
300 redisplayFormula();
Hans Boehm84614952014-11-25 18:46:17 -0800301 setState(CalculatorState.INIT);
Hans Boehm84614952014-11-25 18:46:17 -0800302 mEvaluator.requireResult();
303 } else {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700304 redisplayAfterFormulaChange();
Hans Boehm84614952014-11-25 18:46:17 -0800305 }
306 // TODO: We're currently not saving and restoring scroll position.
307 // We probably should. Details may require care to deal with:
308 // - new display size
309 // - slow recomputation if we've scrolled far.
Justin Klaassen4b3af052014-05-27 17:53:10 -0700310 }
311
312 @Override
Justin Klaassenf79d6f62014-08-26 12:27:08 -0700313 protected void onSaveInstanceState(@NonNull Bundle outState) {
314 // If there's an animation in progress, cancel it first to ensure our state is up-to-date.
315 if (mCurrentAnimator != null) {
316 mCurrentAnimator.cancel();
317 }
318
Justin Klaassen4b3af052014-05-27 17:53:10 -0700319 super.onSaveInstanceState(outState);
Hans Boehm84614952014-11-25 18:46:17 -0800320 outState.putInt(KEY_DISPLAY_STATE, mCurrentState.ordinal());
Hans Boehm760a9dc2015-04-20 10:27:12 -0700321 outState.putCharSequence(KEY_UNPROCESSED_CHARS, mUnprocessedChars);
Hans Boehm84614952014-11-25 18:46:17 -0800322 ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
323 try (ObjectOutput out = new ObjectOutputStream(byteArrayStream)) {
324 mEvaluator.saveInstanceState(out);
325 } catch (IOException e) {
326 // Impossible; No IO involved.
327 throw new AssertionError("Impossible IO exception", e);
328 }
329 outState.putByteArray(KEY_EVAL_STATE, byteArrayStream.toByteArray());
Justin Klaassen4b3af052014-05-27 17:53:10 -0700330 }
331
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700332 // Set the state, updating delete label and display colors.
333 // This restores display positions on moving to INPUT.
Justin Klaassend48b7562015-04-16 16:51:38 -0700334 // But movement/animation for moving to RESULT has already been done.
Justin Klaassen4b3af052014-05-27 17:53:10 -0700335 private void setState(CalculatorState state) {
336 if (mCurrentState != state) {
Hans Boehm84614952014-11-25 18:46:17 -0800337 if (state == CalculatorState.INPUT) {
338 restoreDisplayPositions();
339 }
Justin Klaassen4b3af052014-05-27 17:53:10 -0700340 mCurrentState = state;
341
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700342 if (mCurrentState == CalculatorState.RESULT) {
343 // No longer do this for ERROR; allow mistakes to be corrected.
Justin Klaassen4b3af052014-05-27 17:53:10 -0700344 mDeleteButton.setVisibility(View.GONE);
345 mClearButton.setVisibility(View.VISIBLE);
346 } else {
347 mDeleteButton.setVisibility(View.VISIBLE);
348 mClearButton.setVisibility(View.GONE);
349 }
350
Hans Boehm84614952014-11-25 18:46:17 -0800351 if (mCurrentState == CalculatorState.ERROR) {
Justin Klaassen44595162015-05-28 17:55:20 -0700352 final int errorColor = getColor(R.color.calculator_error_color);
Hans Boehm08e8f322015-04-21 13:18:38 -0700353 mFormulaText.setTextColor(errorColor);
Justin Klaassen44595162015-05-28 17:55:20 -0700354 mResultText.setTextColor(errorColor);
Justin Klaassen8fff1442014-06-19 10:43:29 -0700355 getWindow().setStatusBarColor(errorColor);
Justin Klaassen44595162015-05-28 17:55:20 -0700356 } else if (mCurrentState != CalculatorState.RESULT) {
357 mFormulaText.setTextColor(getColor(R.color.display_formula_text_color));
358 mResultText.setTextColor(getColor(R.color.display_result_text_color));
359 getWindow().setStatusBarColor(getColor(R.color.calculator_accent_color));
Justin Klaassen4b3af052014-05-27 17:53:10 -0700360 }
Justin Klaassend48b7562015-04-16 16:51:38 -0700361
362 invalidateOptionsMenu();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700363 }
364 }
365
Hans Boehm1176f232015-05-11 16:26:03 -0700366 // Stop any active ActionMode. Return true if there was one.
367 private boolean stopActionMode() {
Justin Klaassen44595162015-05-28 17:55:20 -0700368 if (mResultText.stopActionMode()) {
Hans Boehm1176f232015-05-11 16:26:03 -0700369 return true;
370 }
371 if (mFormulaText.stopActionMode()) {
372 return true;
373 }
374 return false;
375 }
376
Justin Klaassen4b3af052014-05-27 17:53:10 -0700377 @Override
Justin Klaassen3b4d13d2014-06-06 18:18:37 +0100378 public void onBackPressed() {
Hans Boehm1176f232015-05-11 16:26:03 -0700379 if (!stopActionMode()) {
380 if (mPadViewPager != null && mPadViewPager.getCurrentItem() != 0) {
381 // Select the previous pad.
382 mPadViewPager.setCurrentItem(mPadViewPager.getCurrentItem() - 1);
383 } else {
384 // If the user is currently looking at the first pad (or the pad is not paged),
385 // allow the system to handle the Back button.
386 super.onBackPressed();
387 }
Justin Klaassen3b4d13d2014-06-06 18:18:37 +0100388 }
389 }
390
391 @Override
Justin Klaassen4b3af052014-05-27 17:53:10 -0700392 public void onUserInteraction() {
393 super.onUserInteraction();
394
Hans Boehmc1ea0912015-06-19 15:05:07 -0700395 // If there's an animation in progress, end it immediately, so the user interaction can
396 // be handled.
Justin Klaassen4b3af052014-05-27 17:53:10 -0700397 if (mCurrentAnimator != null) {
Hans Boehmc1ea0912015-06-19 15:05:07 -0700398 mCurrentAnimator.end();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700399 }
400 }
401
Justin Klaassene2711cb2015-05-28 11:13:17 -0700402 /**
403 * Invoked whenever the inverse button is toggled to update the UI.
404 *
405 * @param showInverse {@code true} if inverse functions should be shown
406 */
407 private void onInverseToggled(boolean showInverse) {
408 if (showInverse) {
409 mInverseToggle.setContentDescription(getString(R.string.desc_inv_on));
Justin Klaassen721ec842015-05-28 14:30:08 -0700410 for (View invertibleButton : mInvertibleButtons) {
411 invertibleButton.setVisibility(View.GONE);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700412 }
413 for (View inverseButton : mInverseButtons) {
414 inverseButton.setVisibility(View.VISIBLE);
415 }
416 } else {
417 mInverseToggle.setContentDescription(getString(R.string.desc_inv_off));
Justin Klaassen721ec842015-05-28 14:30:08 -0700418 for (View invertibleButton : mInvertibleButtons) {
419 invertibleButton.setVisibility(View.VISIBLE);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700420 }
421 for (View inverseButton : mInverseButtons) {
422 inverseButton.setVisibility(View.GONE);
423 }
424 }
425 }
426
427 /**
428 * Invoked whenever the deg/rad mode may have changed to update the UI.
429 *
430 * @param degreeMode {@code true} if in degree mode
431 */
432 private void onModeChanged(boolean degreeMode) {
433 if (degreeMode) {
Justin Klaassend48b7562015-04-16 16:51:38 -0700434 mModeView.setText(R.string.mode_deg);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700435 mModeView.setContentDescription(getString(R.string.desc_mode_deg));
436
437 mModeToggle.setText(R.string.mode_rad);
438 mModeToggle.setContentDescription(getString(R.string.desc_switch_rad));
Hans Boehmbfe8c222015-04-02 16:26:07 -0700439 } else {
Justin Klaassend48b7562015-04-16 16:51:38 -0700440 mModeView.setText(R.string.mode_rad);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700441 mModeView.setContentDescription(getString(R.string.desc_mode_rad));
442
443 mModeToggle.setText(R.string.mode_deg);
444 mModeToggle.setContentDescription(getString(R.string.desc_switch_deg));
Hans Boehmbfe8c222015-04-02 16:26:07 -0700445 }
446 }
Hans Boehm84614952014-11-25 18:46:17 -0800447
Hans Boehm5d79d102015-09-16 16:33:47 -0700448 /**
449 * Switch to INPUT from RESULT state in response to input of the specified button_id.
450 * View.NO_ID is treated as an incomplete function id.
451 */
452 private void switchToInput(int button_id) {
453 if (KeyMaps.isBinary(button_id) || KeyMaps.isSuffix(button_id)) {
454 mEvaluator.collapse();
455 } else {
456 announceClearedForAccessibility();
457 mEvaluator.clear();
458 }
459 setState(CalculatorState.INPUT);
460 }
461
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700462 // Add the given button id to input expression.
463 // If appropriate, clear the expression before doing so.
464 private void addKeyToExpr(int id) {
465 if (mCurrentState == CalculatorState.ERROR) {
466 setState(CalculatorState.INPUT);
467 } else if (mCurrentState == CalculatorState.RESULT) {
Hans Boehm5d79d102015-09-16 16:33:47 -0700468 switchToInput(id);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700469 }
470 if (!mEvaluator.append(id)) {
471 // TODO: Some user visible feedback?
472 }
473 }
474
Hans Boehm017de982015-06-10 17:46:03 -0700475 /**
476 * Add the given button id to input expression, assuming it was explicitly
477 * typed/touched.
478 * We perform slightly more aggressive correction than in pasted expressions.
479 */
480 private void addExplicitKeyToExpr(int id) {
481 if (mCurrentState == CalculatorState.INPUT && id == R.id.op_sub) {
482 mEvaluator.getExpr().removeTrailingAdditiveOperators();
483 }
484 addKeyToExpr(id);
485 }
486
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700487 private void redisplayAfterFormulaChange() {
488 // TODO: Could do this more incrementally.
489 redisplayFormula();
490 setState(CalculatorState.INPUT);
Hans Boehmc023b732015-04-29 11:30:47 -0700491 if (mEvaluator.getExpr().hasInterestingOps()) {
492 mEvaluator.evaluateAndShowResult();
493 } else {
Justin Klaassen44595162015-05-28 17:55:20 -0700494 mResultText.clear();
Hans Boehmc023b732015-04-29 11:30:47 -0700495 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700496 }
497
Justin Klaassen4b3af052014-05-27 17:53:10 -0700498 public void onButtonClick(View view) {
Hans Boehmc1ea0912015-06-19 15:05:07 -0700499 // Any animation is ended before we get here.
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700500 mCurrentButton = view;
Hans Boehm1176f232015-05-11 16:26:03 -0700501 stopActionMode();
Hans Boehmc1ea0912015-06-19 15:05:07 -0700502 // See onKey above for the rationale behind some of the behavior below:
503 if (mCurrentState != CalculatorState.EVALUATE) {
504 // Cancel evaluations that were not specifically requested.
505 mEvaluator.cancelAll(true);
Hans Boehm84614952014-11-25 18:46:17 -0800506 }
Justin Klaassend48b7562015-04-16 16:51:38 -0700507 final int id = view.getId();
Hans Boehm84614952014-11-25 18:46:17 -0800508 switch (id) {
Justin Klaassen4b3af052014-05-27 17:53:10 -0700509 case R.id.eq:
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700510 onEquals();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700511 break;
512 case R.id.del:
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700513 onDelete();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700514 break;
515 case R.id.clr:
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700516 onClear();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700517 break;
Justin Klaassene2711cb2015-05-28 11:13:17 -0700518 case R.id.toggle_inv:
519 final boolean selected = !mInverseToggle.isSelected();
520 mInverseToggle.setSelected(selected);
521 onInverseToggled(selected);
Hans Boehmc1ea0912015-06-19 15:05:07 -0700522 if (mCurrentState == CalculatorState.RESULT) {
523 mResultText.redisplay(); // In case we cancelled reevaluation.
524 }
Justin Klaassene2711cb2015-05-28 11:13:17 -0700525 break;
526 case R.id.toggle_mode:
Hans Boehmc1ea0912015-06-19 15:05:07 -0700527 cancelIfEvaluating(false);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700528 final boolean mode = !mEvaluator.getDegreeMode();
Hans Boehmbfe8c222015-04-02 16:26:07 -0700529 if (mCurrentState == CalculatorState.RESULT) {
530 mEvaluator.collapse(); // Capture result evaluated in old mode
531 redisplayFormula();
532 }
533 // In input mode, we reinterpret already entered trig functions.
534 mEvaluator.setDegreeMode(mode);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700535 onModeChanged(mode);
Hans Boehmbfe8c222015-04-02 16:26:07 -0700536 setState(CalculatorState.INPUT);
Justin Klaassen44595162015-05-28 17:55:20 -0700537 mResultText.clear();
Hans Boehmc023b732015-04-29 11:30:47 -0700538 if (mEvaluator.getExpr().hasInterestingOps()) {
539 mEvaluator.evaluateAndShowResult();
540 }
Hans Boehmbfe8c222015-04-02 16:26:07 -0700541 break;
Justin Klaassen4b3af052014-05-27 17:53:10 -0700542 default:
Hans Boehmc1ea0912015-06-19 15:05:07 -0700543 cancelIfEvaluating(false);
Hans Boehm017de982015-06-10 17:46:03 -0700544 addExplicitKeyToExpr(id);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700545 redisplayAfterFormulaChange();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700546 break;
547 }
548 }
549
Hans Boehm84614952014-11-25 18:46:17 -0800550 void redisplayFormula() {
Hans Boehm8a4f81c2015-07-09 10:41:25 -0700551 SpannableStringBuilder formula = mEvaluator.getExpr().toSpannableStringBuilder(this);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700552 if (mUnprocessedChars != null) {
553 // Add and highlight characters we couldn't process.
Hans Boehm8a4f81c2015-07-09 10:41:25 -0700554 formula.append(mUnprocessedChars, mUnprocessedColorSpan,
555 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700556 }
Hans Boehm8a4f81c2015-07-09 10:41:25 -0700557 mFormulaText.changeTextTo(formula);
Hans Boehm84614952014-11-25 18:46:17 -0800558 }
559
Justin Klaassen4b3af052014-05-27 17:53:10 -0700560 @Override
561 public boolean onLongClick(View view) {
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700562 mCurrentButton = view;
563
Justin Klaassen4b3af052014-05-27 17:53:10 -0700564 if (view.getId() == R.id.del) {
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700565 onClear();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700566 return true;
567 }
568 return false;
569 }
570
Hans Boehm84614952014-11-25 18:46:17 -0800571 // Initial evaluation completed successfully. Initiate display.
Hans Boehma0e45f32015-05-30 13:20:35 -0700572 public void onEvaluate(int initDisplayPrec, int msd, int leastDigPos,
573 String truncatedWholeNumber) {
Justin Klaassend48b7562015-04-16 16:51:38 -0700574 // Invalidate any options that may depend on the current result.
575 invalidateOptionsMenu();
576
Hans Boehma0e45f32015-05-30 13:20:35 -0700577 mResultText.displayResult(initDisplayPrec, msd, leastDigPos, truncatedWholeNumber);
Hans Boehm61568a12015-05-18 18:25:41 -0700578 if (mCurrentState != CalculatorState.INPUT) { // in EVALUATE or INIT state
Hans Boehm84614952014-11-25 18:46:17 -0800579 onResult(mCurrentState != CalculatorState.INIT);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700580 }
Hans Boehm84614952014-11-25 18:46:17 -0800581 }
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700582
Hans Boehmc1ea0912015-06-19 15:05:07 -0700583 // Reset state to reflect evaluator cancellation. Invoked by evaluator.
Hans Boehm84614952014-11-25 18:46:17 -0800584 public void onCancelled() {
585 // We should be in EVALUATE state.
Hans Boehm84614952014-11-25 18:46:17 -0800586 setState(CalculatorState.INPUT);
Justin Klaassen44595162015-05-28 17:55:20 -0700587 mResultText.clear();
Hans Boehm84614952014-11-25 18:46:17 -0800588 }
589
590 // Reevaluation completed; ask result to redisplay current value.
591 public void onReevaluate()
592 {
Justin Klaassen44595162015-05-28 17:55:20 -0700593 mResultText.redisplay();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700594 }
595
Justin Klaassenfed941a2014-06-09 18:42:40 +0100596 @Override
597 public void onTextSizeChanged(final TextView textView, float oldSize) {
598 if (mCurrentState != CalculatorState.INPUT) {
599 // Only animate text changes that occur from user input.
600 return;
601 }
602
603 // Calculate the values needed to perform the scale and translation animations,
604 // maintaining the same apparent baseline for the displayed text.
605 final float textScale = oldSize / textView.getTextSize();
606 final float translationX = (1.0f - textScale) *
607 (textView.getWidth() / 2.0f - textView.getPaddingEnd());
608 final float translationY = (1.0f - textScale) *
609 (textView.getHeight() / 2.0f - textView.getPaddingBottom());
610
611 final AnimatorSet animatorSet = new AnimatorSet();
612 animatorSet.playTogether(
613 ObjectAnimator.ofFloat(textView, View.SCALE_X, textScale, 1.0f),
614 ObjectAnimator.ofFloat(textView, View.SCALE_Y, textScale, 1.0f),
615 ObjectAnimator.ofFloat(textView, View.TRANSLATION_X, translationX, 0.0f),
616 ObjectAnimator.ofFloat(textView, View.TRANSLATION_Y, translationY, 0.0f));
Justin Klaassen94db7202014-06-11 11:22:31 -0700617 animatorSet.setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime));
Justin Klaassenfed941a2014-06-09 18:42:40 +0100618 animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
619 animatorSet.start();
620 }
621
Hans Boehmc1ea0912015-06-19 15:05:07 -0700622 /**
623 * Cancel any in-progress explicitly requested evaluations.
624 * @param quiet suppress pop-up message. Explicit evaluation can change the expression
625 value, and certainly changes the display, so it seems reasonable to warn.
626 * @return true if there was such an evaluation
627 */
628 private boolean cancelIfEvaluating(boolean quiet) {
629 if (mCurrentState == CalculatorState.EVALUATE) {
630 mEvaluator.cancelAll(quiet);
631 return true;
632 } else {
633 return false;
634 }
635 }
636
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700637 private void onEquals() {
Hans Boehmc1ea0912015-06-19 15:05:07 -0700638 // In non-INPUT state assume this was redundant and ignore it.
Hans Boehmc023b732015-04-29 11:30:47 -0700639 if (mCurrentState == CalculatorState.INPUT && !mEvaluator.getExpr().isEmpty()) {
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700640 setState(CalculatorState.EVALUATE);
Hans Boehm84614952014-11-25 18:46:17 -0800641 mEvaluator.requireResult();
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700642 }
643 }
644
645 private void onDelete() {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700646 // Delete works like backspace; remove the last character or operator from the expression.
647 // Note that we handle keyboard delete exactly like the delete button. For
648 // example the delete button can be used to delete a character from an incomplete
649 // function name typed on a physical keyboard.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700650 // This should be impossible in RESULT state.
Hans Boehmc1ea0912015-06-19 15:05:07 -0700651 // If there is an in-progress explicit evaluation, just cancel it and return.
652 if (cancelIfEvaluating(false)) return;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700653 setState(CalculatorState.INPUT);
654 if (mUnprocessedChars != null) {
655 int len = mUnprocessedChars.length();
656 if (len > 0) {
657 mUnprocessedChars = mUnprocessedChars.substring(0, len-1);
658 } else {
Hans Boehmc023b732015-04-29 11:30:47 -0700659 mEvaluator.delete();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700660 }
661 } else {
Hans Boehmc023b732015-04-29 11:30:47 -0700662 mEvaluator.delete();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700663 }
Hans Boehmdb6f9992015-08-19 12:32:56 -0700664 if (mEvaluator.getExpr().isEmpty()
665 && (mUnprocessedChars == null || mUnprocessedChars.isEmpty())) {
666 // Resulting formula won't be announced, since it's empty.
667 announceClearedForAccessibility();
668 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700669 redisplayAfterFormulaChange();
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700670 }
671
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700672 private void reveal(View sourceView, int colorRes, AnimatorListener listener) {
Justin Klaassen06360f92014-08-28 11:08:44 -0700673 final ViewGroupOverlay groupOverlay =
674 (ViewGroupOverlay) getWindow().getDecorView().getOverlay();
Justin Klaassen8fff1442014-06-19 10:43:29 -0700675
676 final Rect displayRect = new Rect();
Justin Klaassen06360f92014-08-28 11:08:44 -0700677 mDisplayView.getGlobalVisibleRect(displayRect);
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700678
679 // Make reveal cover the display and status bar.
680 final View revealView = new View(this);
Justin Klaassen8fff1442014-06-19 10:43:29 -0700681 revealView.setBottom(displayRect.bottom);
682 revealView.setLeft(displayRect.left);
683 revealView.setRight(displayRect.right);
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700684 revealView.setBackgroundColor(getResources().getColor(colorRes));
Justin Klaassen06360f92014-08-28 11:08:44 -0700685 groupOverlay.add(revealView);
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700686
Justin Klaassen4b3af052014-05-27 17:53:10 -0700687 final int[] clearLocation = new int[2];
688 sourceView.getLocationInWindow(clearLocation);
689 clearLocation[0] += sourceView.getWidth() / 2;
690 clearLocation[1] += sourceView.getHeight() / 2;
691
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700692 final int revealCenterX = clearLocation[0] - revealView.getLeft();
693 final int revealCenterY = clearLocation[1] - revealView.getTop();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700694
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700695 final double x1_2 = Math.pow(revealView.getLeft() - revealCenterX, 2);
696 final double x2_2 = Math.pow(revealView.getRight() - revealCenterX, 2);
697 final double y_2 = Math.pow(revealView.getTop() - revealCenterY, 2);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700698 final float revealRadius = (float) Math.max(Math.sqrt(x1_2 + y_2), Math.sqrt(x2_2 + y_2));
699
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700700 final Animator revealAnimator =
701 ViewAnimationUtils.createCircularReveal(revealView,
ztenghui3d6ecaf2014-06-05 09:56:00 -0700702 revealCenterX, revealCenterY, 0.0f, revealRadius);
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700703 revealAnimator.setDuration(
Justin Klaassen4b3af052014-05-27 17:53:10 -0700704 getResources().getInteger(android.R.integer.config_longAnimTime));
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700705 revealAnimator.addListener(listener);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700706
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700707 final Animator alphaAnimator = ObjectAnimator.ofFloat(revealView, View.ALPHA, 0.0f);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700708 alphaAnimator.setDuration(
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700709 getResources().getInteger(android.R.integer.config_mediumAnimTime));
Justin Klaassen4b3af052014-05-27 17:53:10 -0700710
711 final AnimatorSet animatorSet = new AnimatorSet();
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700712 animatorSet.play(revealAnimator).before(alphaAnimator);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700713 animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
714 animatorSet.addListener(new AnimatorListenerAdapter() {
715 @Override
Justin Klaassen4b3af052014-05-27 17:53:10 -0700716 public void onAnimationEnd(Animator animator) {
Justin Klaassen8fff1442014-06-19 10:43:29 -0700717 groupOverlay.remove(revealView);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700718 mCurrentAnimator = null;
719 }
720 });
721
722 mCurrentAnimator = animatorSet;
723 animatorSet.start();
724 }
725
Hans Boehmdb6f9992015-08-19 12:32:56 -0700726 private void announceClearedForAccessibility() {
727 mResultText.announceForAccessibility(getResources().getString(R.string.cleared));
Hans Boehmccc55662015-07-07 14:16:59 -0700728 }
729
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700730 private void onClear() {
Hans Boehm84614952014-11-25 18:46:17 -0800731 if (mEvaluator.getExpr().isEmpty()) {
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700732 return;
733 }
Hans Boehmc1ea0912015-06-19 15:05:07 -0700734 cancelIfEvaluating(true);
Hans Boehmdb6f9992015-08-19 12:32:56 -0700735 announceClearedForAccessibility();
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700736 reveal(mCurrentButton, R.color.calculator_accent_color, new AnimatorListenerAdapter() {
737 @Override
738 public void onAnimationEnd(Animator animation) {
Hans Boehm760a9dc2015-04-20 10:27:12 -0700739 mUnprocessedChars = null;
Justin Klaassen44595162015-05-28 17:55:20 -0700740 mResultText.clear();
Hans Boehm760a9dc2015-04-20 10:27:12 -0700741 mEvaluator.clear();
742 setState(CalculatorState.INPUT);
Hans Boehm84614952014-11-25 18:46:17 -0800743 redisplayFormula();
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700744 }
745 });
746 }
747
Hans Boehm84614952014-11-25 18:46:17 -0800748 // Evaluation encountered en error. Display the error.
749 void onError(final int errorResourceId) {
Hans Boehmfbcef702015-04-27 18:07:47 -0700750 if (mCurrentState == CalculatorState.EVALUATE) {
751 setState(CalculatorState.ANIMATE);
Hans Boehmccc55662015-07-07 14:16:59 -0700752 mResultText.announceForAccessibility(getResources().getString(errorResourceId));
Hans Boehmfbcef702015-04-27 18:07:47 -0700753 reveal(mCurrentButton, R.color.calculator_error_color,
754 new AnimatorListenerAdapter() {
755 @Override
756 public void onAnimationEnd(Animator animation) {
757 setState(CalculatorState.ERROR);
Justin Klaassen44595162015-05-28 17:55:20 -0700758 mResultText.displayError(errorResourceId);
Hans Boehmfbcef702015-04-27 18:07:47 -0700759 }
760 });
761 } else if (mCurrentState == CalculatorState.INIT) {
762 setState(CalculatorState.ERROR);
Justin Klaassen44595162015-05-28 17:55:20 -0700763 mResultText.displayError(errorResourceId);
Hans Boehmc023b732015-04-29 11:30:47 -0700764 } else {
Justin Klaassen44595162015-05-28 17:55:20 -0700765 mResultText.clear();
Justin Klaassen2be4fdb2014-08-06 19:54:09 -0700766 }
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700767 }
768
Hans Boehm84614952014-11-25 18:46:17 -0800769
770 // Animate movement of result into the top formula slot.
771 // Result window now remains translated in the top slot while the result is displayed.
772 // (We convert it back to formula use only when the user provides new input.)
Justin Klaassen44595162015-05-28 17:55:20 -0700773 // Historical note: In the Lollipop version, this invisibly and instantaneously moved
Hans Boehm84614952014-11-25 18:46:17 -0800774 // formula and result displays back at the end of the animation. We no longer do that,
775 // so that we can continue to properly support scrolling of the result.
776 // We assume the result already contains the text to be expanded.
777 private void onResult(boolean animate) {
Justin Klaassen44595162015-05-28 17:55:20 -0700778 // Calculate the textSize that would be used to display the result in the formula.
779 // For scrollable results just use the minimum textSize to maximize the number of digits
780 // that are visible on screen.
781 float textSize = mFormulaText.getMinimumTextSize();
782 if (!mResultText.isScrollable()) {
783 textSize = mFormulaText.getVariableTextSize(mResultText.getText().toString());
784 }
785
786 // Scale the result to match the calculated textSize, minimizing the jump-cut transition
787 // when a result is reused in a subsequent expression.
788 final float resultScale = textSize / mResultText.getTextSize();
789
790 // Set the result's pivot to match its gravity.
791 mResultText.setPivotX(mResultText.getWidth() - mResultText.getPaddingRight());
792 mResultText.setPivotY(mResultText.getHeight() - mResultText.getPaddingBottom());
793
794 // Calculate the necessary translations so the result takes the place of the formula and
795 // the formula moves off the top of the screen.
796 final float resultTranslationY = (mFormulaText.getBottom() - mResultText.getBottom())
797 - (mFormulaText.getPaddingBottom() - mResultText.getPaddingBottom());
Hans Boehm08e8f322015-04-21 13:18:38 -0700798 final float formulaTranslationY = -mFormulaText.getBottom();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700799
Justin Klaassen44595162015-05-28 17:55:20 -0700800 // Change the result's textColor to match the formula.
801 final int formulaTextColor = mFormulaText.getCurrentTextColor();
802
Hans Boehm84614952014-11-25 18:46:17 -0800803 if (animate) {
Hans Boehmccc55662015-07-07 14:16:59 -0700804 mResultText.announceForAccessibility(getResources().getString(R.string.desc_eq));
805 mResultText.announceForAccessibility(mResultText.getText());
Hans Boehmc1ea0912015-06-19 15:05:07 -0700806 setState(CalculatorState.ANIMATE);
Hans Boehm84614952014-11-25 18:46:17 -0800807 final AnimatorSet animatorSet = new AnimatorSet();
808 animatorSet.playTogether(
Justin Klaassen44595162015-05-28 17:55:20 -0700809 ObjectAnimator.ofPropertyValuesHolder(mResultText,
810 PropertyValuesHolder.ofFloat(View.SCALE_X, resultScale),
811 PropertyValuesHolder.ofFloat(View.SCALE_Y, resultScale),
812 PropertyValuesHolder.ofFloat(View.TRANSLATION_Y, resultTranslationY)),
813 ObjectAnimator.ofArgb(mResultText, TEXT_COLOR, formulaTextColor),
814 ObjectAnimator.ofFloat(mFormulaText, View.TRANSLATION_Y, formulaTranslationY));
815 animatorSet.setDuration(getResources().getInteger(
816 android.R.integer.config_longAnimTime));
Hans Boehm84614952014-11-25 18:46:17 -0800817 animatorSet.addListener(new AnimatorListenerAdapter() {
818 @Override
Hans Boehm84614952014-11-25 18:46:17 -0800819 public void onAnimationEnd(Animator animation) {
820 setState(CalculatorState.RESULT);
821 mCurrentAnimator = null;
822 }
823 });
Justin Klaassen4b3af052014-05-27 17:53:10 -0700824
Hans Boehm84614952014-11-25 18:46:17 -0800825 mCurrentAnimator = animatorSet;
826 animatorSet.start();
827 } else /* No animation desired; get there fast, e.g. when restarting */ {
Justin Klaassen44595162015-05-28 17:55:20 -0700828 mResultText.setScaleX(resultScale);
829 mResultText.setScaleY(resultScale);
830 mResultText.setTranslationY(resultTranslationY);
831 mResultText.setTextColor(formulaTextColor);
Hans Boehm08e8f322015-04-21 13:18:38 -0700832 mFormulaText.setTranslationY(formulaTranslationY);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700833 setState(CalculatorState.RESULT);
Hans Boehm84614952014-11-25 18:46:17 -0800834 }
Justin Klaassen4b3af052014-05-27 17:53:10 -0700835 }
Hans Boehm84614952014-11-25 18:46:17 -0800836
837 // Restore positions of the formula and result displays back to their original,
838 // pre-animation state.
839 private void restoreDisplayPositions() {
840 // Clear result.
Justin Klaassen44595162015-05-28 17:55:20 -0700841 mResultText.setText("");
Hans Boehm84614952014-11-25 18:46:17 -0800842 // Reset all of the values modified during the animation.
Justin Klaassen44595162015-05-28 17:55:20 -0700843 mResultText.setScaleX(1.0f);
844 mResultText.setScaleY(1.0f);
845 mResultText.setTranslationX(0.0f);
846 mResultText.setTranslationY(0.0f);
Hans Boehm08e8f322015-04-21 13:18:38 -0700847 mFormulaText.setTranslationY(0.0f);
Hans Boehm84614952014-11-25 18:46:17 -0800848
Hans Boehm08e8f322015-04-21 13:18:38 -0700849 mFormulaText.requestFocus();
Hans Boehm84614952014-11-25 18:46:17 -0800850 }
851
Justin Klaassend48b7562015-04-16 16:51:38 -0700852 @Override
853 public boolean onCreateOptionsMenu(Menu menu) {
Justin Klaassend36d63e2015-05-05 12:59:36 -0700854 super.onCreateOptionsMenu(menu);
855
856 getMenuInflater().inflate(R.menu.activity_calculator, menu);
Justin Klaassend48b7562015-04-16 16:51:38 -0700857 return true;
858 }
859
860 @Override
861 public boolean onPrepareOptionsMenu(Menu menu) {
Justin Klaassend36d63e2015-05-05 12:59:36 -0700862 super.onPrepareOptionsMenu(menu);
863
864 // Show the leading option when displaying a result.
865 menu.findItem(R.id.menu_leading).setVisible(mCurrentState == CalculatorState.RESULT);
866
867 // Show the fraction option when displaying a rational result.
868 menu.findItem(R.id.menu_fraction).setVisible(mCurrentState == CalculatorState.RESULT
869 && mEvaluator.getRational() != null);
870
Justin Klaassend48b7562015-04-16 16:51:38 -0700871 return true;
Hans Boehm84614952014-11-25 18:46:17 -0800872 }
873
874 @Override
Justin Klaassend48b7562015-04-16 16:51:38 -0700875 public boolean onOptionsItemSelected(MenuItem item) {
Hans Boehm84614952014-11-25 18:46:17 -0800876 switch (item.getItemId()) {
Justin Klaassend36d63e2015-05-05 12:59:36 -0700877 case R.id.menu_leading:
878 displayFull();
Hans Boehm84614952014-11-25 18:46:17 -0800879 return true;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700880 case R.id.menu_fraction:
881 displayFraction();
882 return true;
Justin Klaassend36d63e2015-05-05 12:59:36 -0700883 case R.id.menu_licenses:
884 startActivity(new Intent(this, Licenses.class));
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700885 return true;
Hans Boehm84614952014-11-25 18:46:17 -0800886 default:
887 return super.onOptionsItemSelected(item);
888 }
889 }
890
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700891 private void displayMessage(String s) {
Hans Boehma3723842015-06-24 17:54:13 -0700892 AlertDialogFragment.showMessageDialog(this, s);
Hans Boehm84614952014-11-25 18:46:17 -0800893 }
894
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700895 private void displayFraction() {
896 BoundedRational result = mEvaluator.getRational();
Hans Boehm013969e2015-04-13 20:29:47 -0700897 displayMessage(KeyMaps.translateResult(result.toNiceString()));
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700898 }
899
900 // Display full result to currently evaluated precision
901 private void displayFull() {
902 Resources res = getResources();
Justin Klaassen44595162015-05-28 17:55:20 -0700903 String msg = mResultText.getFullText() + " ";
904 if (mResultText.fullTextIsExact()) {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700905 msg += res.getString(R.string.exact);
906 } else {
907 msg += res.getString(R.string.approximate);
908 }
909 displayMessage(msg);
910 }
911
Hans Boehm017de982015-06-10 17:46:03 -0700912 /**
913 * Add input characters to the end of the expression.
914 * Map them to the appropriate button pushes when possible. Leftover characters
915 * are added to mUnprocessedChars, which is presumed to immediately precede the newly
916 * added characters.
917 * @param moreChars Characters to be added.
Hans Boehm0b9806f2015-06-29 16:07:15 -0700918 * @param explicit These characters were explicitly typed by the user, not pasted.
Hans Boehm017de982015-06-10 17:46:03 -0700919 */
920 private void addChars(String moreChars, boolean explicit) {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700921 if (mUnprocessedChars != null) {
922 moreChars = mUnprocessedChars + moreChars;
923 }
924 int current = 0;
925 int len = moreChars.length();
Hans Boehm0b9806f2015-06-29 16:07:15 -0700926 boolean lastWasDigit = false;
Hans Boehm5d79d102015-09-16 16:33:47 -0700927 if (mCurrentState == CalculatorState.RESULT && len != 0) {
928 // Clear display immediately for incomplete function name.
929 switchToInput(KeyMaps.keyForChar(moreChars.charAt(current)));
930 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700931 while (current < len) {
932 char c = moreChars.charAt(current);
Hans Boehm013969e2015-04-13 20:29:47 -0700933 int k = KeyMaps.keyForChar(c);
Hans Boehm0b9806f2015-06-29 16:07:15 -0700934 if (!explicit) {
935 int expEnd;
936 if (lastWasDigit && current !=
937 (expEnd = Evaluator.exponentEnd(moreChars, current))) {
938 // Process scientific notation with 'E' when pasting, in spite of ambiguity
939 // with base of natural log.
940 // Otherwise the 10^x key is the user's friend.
941 mEvaluator.addExponent(moreChars, current, expEnd);
942 current = expEnd;
943 lastWasDigit = false;
944 continue;
945 } else {
946 boolean isDigit = KeyMaps.digVal(k) != KeyMaps.NOT_DIGIT;
947 if (current == 0 && (isDigit || k == R.id.dec_point)
948 && mEvaluator.getExpr().hasTrailingConstant()) {
949 // Refuse to concatenate pasted content to trailing constant.
950 // This makes pasting of calculator results more consistent, whether or
951 // not the old calculator instance is still around.
952 addKeyToExpr(R.id.op_mul);
953 }
954 lastWasDigit = (isDigit || lastWasDigit && k == R.id.dec_point);
955 }
956 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700957 if (k != View.NO_ID) {
958 mCurrentButton = findViewById(k);
Hans Boehm017de982015-06-10 17:46:03 -0700959 if (explicit) {
960 addExplicitKeyToExpr(k);
961 } else {
962 addKeyToExpr(k);
963 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700964 if (Character.isSurrogate(c)) {
965 current += 2;
966 } else {
967 ++current;
968 }
969 continue;
970 }
Hans Boehm013969e2015-04-13 20:29:47 -0700971 int f = KeyMaps.funForString(moreChars, current);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700972 if (f != View.NO_ID) {
973 mCurrentButton = findViewById(f);
Hans Boehm017de982015-06-10 17:46:03 -0700974 if (explicit) {
975 addExplicitKeyToExpr(f);
976 } else {
977 addKeyToExpr(f);
978 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700979 if (f == R.id.op_sqrt) {
980 // Square root entered as function; don't lose the parenthesis.
981 addKeyToExpr(R.id.lparen);
982 }
983 current = moreChars.indexOf('(', current) + 1;
984 continue;
985 }
986 // There are characters left, but we can't convert them to button presses.
987 mUnprocessedChars = moreChars.substring(current);
988 redisplayAfterFormulaChange();
989 return;
990 }
991 mUnprocessedChars = null;
992 redisplayAfterFormulaChange();
Hans Boehm84614952014-11-25 18:46:17 -0800993 }
994
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700995 @Override
Justin Klaassenfc5ac822015-06-18 13:15:17 -0700996 public boolean onPaste(ClipData clip) {
997 final ClipData.Item item = clip.getItemCount() == 0 ? null : clip.getItemAt(0);
998 if (item == null) {
999 // nothing to paste, bail early...
1000 return false;
1001 }
1002
1003 // Check if the item is a previously copied result, otherwise paste as raw text.
1004 final Uri uri = item.getUri();
1005 if (uri != null && mEvaluator.isLastSaved(uri)) {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001006 if (mCurrentState == CalculatorState.ERROR
Justin Klaassenfc5ac822015-06-18 13:15:17 -07001007 || mCurrentState == CalculatorState.RESULT) {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001008 setState(CalculatorState.INPUT);
1009 mEvaluator.clear();
Hans Boehm84614952014-11-25 18:46:17 -08001010 }
Hans Boehm3666e632015-07-27 18:33:12 -07001011 mEvaluator.appendSaved();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001012 redisplayAfterFormulaChange();
Justin Klaassenfc5ac822015-06-18 13:15:17 -07001013 } else {
Hans Boehm017de982015-06-10 17:46:03 -07001014 addChars(item.coerceToText(this).toString(), false);
Hans Boehm84614952014-11-25 18:46:17 -08001015 }
Justin Klaassenfc5ac822015-06-18 13:15:17 -07001016 return true;
Hans Boehm84614952014-11-25 18:46:17 -08001017 }
Justin Klaassen4b3af052014-05-27 17:53:10 -07001018}