blob: c716ce4e6a40e678a363e9bef511ad077a6648bc [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;
Justin Klaassen3b4d13d2014-06-06 18:18:37 +010045import android.support.v4.view.ViewPager;
Annie Chine918fd22016-03-09 11:07:54 -080046import android.text.Editable;
Hans Boehm8a4f81c2015-07-09 10:41:25 -070047import android.text.SpannableStringBuilder;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070048import android.text.Spanned;
Annie Chinf360ef02016-03-10 13:45:39 -080049import android.text.TextUtils;
Annie Chine918fd22016-03-09 11:07:54 -080050import android.text.TextWatcher;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070051import android.text.style.ForegroundColorSpan;
Justin Klaassen44595162015-05-28 17:55:20 -070052import android.util.Property;
Annie Chine918fd22016-03-09 11:07:54 -080053import android.view.ActionMode;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070054import android.view.KeyCharacterMap;
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -070055import android.view.KeyEvent;
Hans Boehm84614952014-11-25 18:46:17 -080056import android.view.Menu;
57import android.view.MenuItem;
Justin Klaassen4b3af052014-05-27 17:53:10 -070058import android.view.View;
59import android.view.View.OnLongClickListener;
Justin Klaassen5f2a3342014-06-11 17:40:22 -070060import android.view.ViewAnimationUtils;
Justin Klaassen8fff1442014-06-19 10:43:29 -070061import android.view.ViewGroupOverlay;
Annie Chine918fd22016-03-09 11:07:54 -080062import android.view.ViewTreeObserver;
Justin Klaassen4b3af052014-05-27 17:53:10 -070063import android.view.animation.AccelerateDecelerateInterpolator;
Annie Chine918fd22016-03-09 11:07:54 -080064import android.widget.HorizontalScrollView;
Justin Klaassenfed941a2014-06-09 18:42:40 +010065import android.widget.TextView;
Justin Klaassend48b7562015-04-16 16:51:38 -070066import android.widget.Toolbar;
Justin Klaassenfed941a2014-06-09 18:42:40 +010067
Hans Boehm08e8f322015-04-21 13:18:38 -070068import com.android.calculator2.CalculatorText.OnTextSizeChangeListener;
Hans Boehm84614952014-11-25 18:46:17 -080069
70import java.io.ByteArrayInputStream;
Hans Boehm84614952014-11-25 18:46:17 -080071import java.io.ByteArrayOutputStream;
Hans Boehm84614952014-11-25 18:46:17 -080072import java.io.IOException;
Justin Klaassen721ec842015-05-28 14:30:08 -070073import java.io.ObjectInput;
74import java.io.ObjectInputStream;
75import java.io.ObjectOutput;
76import java.io.ObjectOutputStream;
Justin Klaassen4b3af052014-05-27 17:53:10 -070077
Justin Klaassen04f79c72014-06-27 17:25:35 -070078public class Calculator extends Activity
Hans Boehm5e6a0ca2015-09-22 17:09:01 -070079 implements OnTextSizeChangeListener, OnLongClickListener, CalculatorText.OnPasteListener,
80 AlertDialogFragment.OnClickListener {
Justin Klaassen2be4fdb2014-08-06 19:54:09 -070081
82 /**
83 * Constant for an invalid resource id.
84 */
85 public static final int INVALID_RES_ID = -1;
Justin Klaassen4b3af052014-05-27 17:53:10 -070086
87 private enum CalculatorState {
Hans Boehm84614952014-11-25 18:46:17 -080088 INPUT, // Result and formula both visible, no evaluation requested,
89 // Though result may be visible on bottom line.
90 EVALUATE, // Both visible, evaluation requested, evaluation/animation incomplete.
Hans Boehmc1ea0912015-06-19 15:05:07 -070091 // Not used for instant result evaluation.
Hans Boehm84614952014-11-25 18:46:17 -080092 INIT, // Very temporary state used as alternative to EVALUATE
93 // during reinitialization. Do not animate on completion.
94 ANIMATE, // Result computed, animation to enlarge result window in progress.
95 RESULT, // Result displayed, formula invisible.
96 // If we are in RESULT state, the formula was evaluated without
97 // error to initial precision.
98 ERROR // Error displayed: Formula visible, result shows error message.
99 // Display similar to INPUT state.
Justin Klaassen4b3af052014-05-27 17:53:10 -0700100 }
Hans Boehm84614952014-11-25 18:46:17 -0800101 // Normal transition sequence is
102 // INPUT -> EVALUATE -> ANIMATE -> RESULT (or ERROR) -> INPUT
103 // A RESULT -> ERROR transition is possible in rare corner cases, in which
104 // a higher precision evaluation exposes an error. This is possible, since we
105 // initially evaluate assuming we were given a well-defined problem. If we
106 // were actually asked to compute sqrt(<extremely tiny negative number>) we produce 0
107 // unless we are asked for enough precision that we can distinguish the argument from zero.
108 // TODO: Consider further heuristics to reduce the chance of observing this?
109 // It already seems to be observable only in contrived cases.
110 // ANIMATE, ERROR, and RESULT are translated to an INIT state if the application
111 // is restarted in that state. This leads us to recompute and redisplay the result
112 // ASAP.
113 // TODO: Possibly save a bit more information, e.g. its initial display string
114 // or most significant digit position, to speed up restart.
Justin Klaassen4b3af052014-05-27 17:53:10 -0700115
Justin Klaassen44595162015-05-28 17:55:20 -0700116 private final Property<TextView, Integer> TEXT_COLOR =
117 new Property<TextView, Integer>(Integer.class, "textColor") {
118 @Override
119 public Integer get(TextView textView) {
120 return textView.getCurrentTextColor();
121 }
122
123 @Override
124 public void set(TextView textView, Integer textColor) {
125 textView.setTextColor(textColor);
126 }
127 };
128
Justin Klaassen3e223ea2016-02-05 14:18:06 -0800129 private static final String NAME = "Calculator";
Hans Boehm84614952014-11-25 18:46:17 -0800130 private static final String KEY_DISPLAY_STATE = NAME + "_display_state";
Hans Boehm760a9dc2015-04-20 10:27:12 -0700131 private static final String KEY_UNPROCESSED_CHARS = NAME + "_unprocessed_chars";
Justin Klaassen3e223ea2016-02-05 14:18:06 -0800132 /**
133 * Associated value is a byte array holding the evaluator state.
134 */
Hans Boehm84614952014-11-25 18:46:17 -0800135 private static final String KEY_EVAL_STATE = NAME + "_eval_state";
Justin Klaassen3e223ea2016-02-05 14:18:06 -0800136 private static final String KEY_INVERSE_MODE = NAME + "_inverse_mode";
Justin Klaassen741471e2014-06-11 09:43:44 -0700137
Annie Chine918fd22016-03-09 11:07:54 -0800138 private final ViewTreeObserver.OnPreDrawListener mPreDrawListener =
139 new ViewTreeObserver.OnPreDrawListener() {
140 @Override
141 public boolean onPreDraw() {
Justin Klaassen12da1ad2016-04-04 14:20:37 -0700142 mFormulaContainer.scrollTo(mFormulaText.getRight(), 0);
Annie Chine918fd22016-03-09 11:07:54 -0800143 final ViewTreeObserver observer = mFormulaContainer.getViewTreeObserver();
144 if (observer.isAlive()) {
145 observer.removeOnPreDrawListener(this);
146 }
147 return false;
148 }
149 };
150
151 private final TextWatcher mFormulaTextWatcher = new TextWatcher() {
152 @Override
153 public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
154 }
155
156 @Override
157 public void onTextChanged(CharSequence charSequence, int start, int count, int after) {
158 }
159
160 @Override
161 public void afterTextChanged(Editable editable) {
162 final ViewTreeObserver observer = mFormulaContainer.getViewTreeObserver();
163 if (observer.isAlive()) {
164 observer.removeOnPreDrawListener(mPreDrawListener);
165 observer.addOnPreDrawListener(mPreDrawListener);
166 }
167 }
168 };
169
Justin Klaassen4b3af052014-05-27 17:53:10 -0700170 private CalculatorState mCurrentState;
Hans Boehm84614952014-11-25 18:46:17 -0800171 private Evaluator mEvaluator;
Justin Klaassen4b3af052014-05-27 17:53:10 -0700172
Justin Klaassen9d33cdc2016-02-21 14:16:14 -0800173 private CalculatorDisplay mDisplayView;
Justin Klaassend48b7562015-04-16 16:51:38 -0700174 private TextView mModeView;
Hans Boehm08e8f322015-04-21 13:18:38 -0700175 private CalculatorText mFormulaText;
Justin Klaassen44595162015-05-28 17:55:20 -0700176 private CalculatorResult mResultText;
Annie Chine918fd22016-03-09 11:07:54 -0800177 private HorizontalScrollView mFormulaContainer;
Justin Klaassend48b7562015-04-16 16:51:38 -0700178
Justin Klaassen3b4d13d2014-06-06 18:18:37 +0100179 private ViewPager mPadViewPager;
Justin Klaassen4b3af052014-05-27 17:53:10 -0700180 private View mDeleteButton;
181 private View mClearButton;
Justin Klaassend48b7562015-04-16 16:51:38 -0700182 private View mEqualButton;
Justin Klaassene2711cb2015-05-28 11:13:17 -0700183
184 private TextView mInverseToggle;
185 private TextView mModeToggle;
186
Justin Klaassen721ec842015-05-28 14:30:08 -0700187 private View[] mInvertibleButtons;
Justin Klaassene2711cb2015-05-28 11:13:17 -0700188 private View[] mInverseButtons;
Justin Klaassen4b3af052014-05-27 17:53:10 -0700189
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700190 private View mCurrentButton;
Justin Klaassen4b3af052014-05-27 17:53:10 -0700191 private Animator mCurrentAnimator;
192
Hans Boehm8a4f81c2015-07-09 10:41:25 -0700193 // Characters that were recently entered at the end of the display that have not yet
194 // been added to the underlying expression.
195 private String mUnprocessedChars = null;
196
197 // Color to highlight unprocessed characters from physical keyboard.
198 // TODO: should probably match this to the error color?
199 private ForegroundColorSpan mUnprocessedColorSpan = new ForegroundColorSpan(Color.RED);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700200
Justin Klaassen4b3af052014-05-27 17:53:10 -0700201 @Override
202 protected void onCreate(Bundle savedInstanceState) {
203 super.onCreate(savedInstanceState);
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700204 setContentView(R.layout.activity_calculator);
Justin Klaassend48b7562015-04-16 16:51:38 -0700205 setActionBar((Toolbar) findViewById(R.id.toolbar));
206
207 // Hide all default options in the ActionBar.
208 getActionBar().setDisplayOptions(0);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700209
Justin Klaassen9d33cdc2016-02-21 14:16:14 -0800210 // Ensure the toolbar stays visible while the options menu is displayed.
211 getActionBar().addOnMenuVisibilityListener(new ActionBar.OnMenuVisibilityListener() {
212 @Override
213 public void onMenuVisibilityChanged(boolean isVisible) {
214 mDisplayView.setForceToolbarVisible(isVisible);
215 }
216 });
217
218 mDisplayView = (CalculatorDisplay) findViewById(R.id.display);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700219 mModeView = (TextView) findViewById(R.id.mode);
Hans Boehm08e8f322015-04-21 13:18:38 -0700220 mFormulaText = (CalculatorText) findViewById(R.id.formula);
Justin Klaassen44595162015-05-28 17:55:20 -0700221 mResultText = (CalculatorResult) findViewById(R.id.result);
Annie Chine918fd22016-03-09 11:07:54 -0800222 mFormulaContainer = (HorizontalScrollView) findViewById(R.id.formula_container);
Justin Klaassend48b7562015-04-16 16:51:38 -0700223
Justin Klaassen3b4d13d2014-06-06 18:18:37 +0100224 mPadViewPager = (ViewPager) findViewById(R.id.pad_pager);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700225 mDeleteButton = findViewById(R.id.del);
226 mClearButton = findViewById(R.id.clr);
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700227 mEqualButton = findViewById(R.id.pad_numeric).findViewById(R.id.eq);
228 if (mEqualButton == null || mEqualButton.getVisibility() != View.VISIBLE) {
229 mEqualButton = findViewById(R.id.pad_operator).findViewById(R.id.eq);
230 }
Justin Klaassene2711cb2015-05-28 11:13:17 -0700231
232 mInverseToggle = (TextView) findViewById(R.id.toggle_inv);
233 mModeToggle = (TextView) findViewById(R.id.toggle_mode);
234
Justin Klaassen721ec842015-05-28 14:30:08 -0700235 mInvertibleButtons = new View[] {
236 findViewById(R.id.fun_sin),
237 findViewById(R.id.fun_cos),
Hans Boehm4db31b42015-05-31 12:19:05 -0700238 findViewById(R.id.fun_tan),
239 findViewById(R.id.fun_ln),
240 findViewById(R.id.fun_log),
241 findViewById(R.id.op_sqrt)
Justin Klaassene2711cb2015-05-28 11:13:17 -0700242 };
243 mInverseButtons = new View[] {
244 findViewById(R.id.fun_arcsin),
245 findViewById(R.id.fun_arccos),
Hans Boehm4db31b42015-05-31 12:19:05 -0700246 findViewById(R.id.fun_arctan),
247 findViewById(R.id.fun_exp),
248 findViewById(R.id.fun_10pow),
249 findViewById(R.id.op_sqr)
Justin Klaassene2711cb2015-05-28 11:13:17 -0700250 };
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700251
Justin Klaassen44595162015-05-28 17:55:20 -0700252 mEvaluator = new Evaluator(this, mResultText);
253 mResultText.setEvaluator(mEvaluator);
Hans Boehm013969e2015-04-13 20:29:47 -0700254 KeyMaps.setActivity(this);
Justin Klaassen2be4fdb2014-08-06 19:54:09 -0700255
Hans Boehm84614952014-11-25 18:46:17 -0800256 if (savedInstanceState != null) {
257 setState(CalculatorState.values()[
258 savedInstanceState.getInt(KEY_DISPLAY_STATE,
259 CalculatorState.INPUT.ordinal())]);
Hans Boehm760a9dc2015-04-20 10:27:12 -0700260 CharSequence unprocessed = savedInstanceState.getCharSequence(KEY_UNPROCESSED_CHARS);
261 if (unprocessed != null) {
262 mUnprocessedChars = unprocessed.toString();
263 }
264 byte[] state = savedInstanceState.getByteArray(KEY_EVAL_STATE);
Hans Boehm84614952014-11-25 18:46:17 -0800265 if (state != null) {
266 try (ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(state))) {
267 mEvaluator.restoreInstanceState(in);
268 } catch (Throwable ignored) {
269 // When in doubt, revert to clean state
270 mCurrentState = CalculatorState.INPUT;
271 mEvaluator.clear();
272 }
273 }
Hans Boehmfbcef702015-04-27 18:07:47 -0700274 } else {
275 mCurrentState = CalculatorState.INPUT;
276 mEvaluator.clear();
Hans Boehm84614952014-11-25 18:46:17 -0800277 }
Justin Klaassene2711cb2015-05-28 11:13:17 -0700278
Hans Boehm08e8f322015-04-21 13:18:38 -0700279 mFormulaText.setOnTextSizeChangeListener(this);
Justin Klaassenfc5ac822015-06-18 13:15:17 -0700280 mFormulaText.setOnPasteListener(this);
Annie Chine918fd22016-03-09 11:07:54 -0800281 mFormulaText.addTextChangedListener(mFormulaTextWatcher);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700282 mDeleteButton.setOnLongClickListener(this);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700283
Justin Klaassen3e223ea2016-02-05 14:18:06 -0800284 onInverseToggled(savedInstanceState != null
285 && savedInstanceState.getBoolean(KEY_INVERSE_MODE));
Justin Klaassene2711cb2015-05-28 11:13:17 -0700286 onModeChanged(mEvaluator.getDegreeMode());
287
Hans Boehm84614952014-11-25 18:46:17 -0800288 if (mCurrentState != CalculatorState.INPUT) {
Hans Boehmfbcef702015-04-27 18:07:47 -0700289 // Just reevaluate.
290 redisplayFormula();
Hans Boehm84614952014-11-25 18:46:17 -0800291 setState(CalculatorState.INIT);
Hans Boehm84614952014-11-25 18:46:17 -0800292 mEvaluator.requireResult();
293 } else {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700294 redisplayAfterFormulaChange();
Hans Boehm84614952014-11-25 18:46:17 -0800295 }
296 // TODO: We're currently not saving and restoring scroll position.
297 // We probably should. Details may require care to deal with:
298 // - new display size
299 // - slow recomputation if we've scrolled far.
Justin Klaassen4b3af052014-05-27 17:53:10 -0700300 }
301
302 @Override
Justin Klaassen9d33cdc2016-02-21 14:16:14 -0800303 protected void onResume() {
304 super.onResume();
305
Hans Boehm52d477a2016-04-01 17:42:50 -0700306 // Always temporarily show the toolbar initially on launch.
307 showAndMaybeHideToolbar();
Justin Klaassen9d33cdc2016-02-21 14:16:14 -0800308 }
309
310 @Override
Justin Klaassenf79d6f62014-08-26 12:27:08 -0700311 protected void onSaveInstanceState(@NonNull Bundle outState) {
Hans Boehm40125442016-01-22 10:35:35 -0800312 mEvaluator.cancelAll(true);
Justin Klaassenf79d6f62014-08-26 12:27:08 -0700313 // If there's an animation in progress, cancel it first to ensure our state is up-to-date.
314 if (mCurrentAnimator != null) {
315 mCurrentAnimator.cancel();
316 }
317
Justin Klaassen4b3af052014-05-27 17:53:10 -0700318 super.onSaveInstanceState(outState);
Hans Boehm84614952014-11-25 18:46:17 -0800319 outState.putInt(KEY_DISPLAY_STATE, mCurrentState.ordinal());
Hans Boehm760a9dc2015-04-20 10:27:12 -0700320 outState.putCharSequence(KEY_UNPROCESSED_CHARS, mUnprocessedChars);
Hans Boehm84614952014-11-25 18:46:17 -0800321 ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
322 try (ObjectOutput out = new ObjectOutputStream(byteArrayStream)) {
323 mEvaluator.saveInstanceState(out);
324 } catch (IOException e) {
325 // Impossible; No IO involved.
326 throw new AssertionError("Impossible IO exception", e);
327 }
328 outState.putByteArray(KEY_EVAL_STATE, byteArrayStream.toByteArray());
Justin Klaassen3e223ea2016-02-05 14:18:06 -0800329 outState.putBoolean(KEY_INVERSE_MODE, mInverseToggle.isSelected());
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
Justin Klaassen12da1ad2016-04-04 14:20:37 -0700366 @Override
367 public void onActionModeStarted(ActionMode mode) {
368 super.onActionModeStarted(mode);
369 if (mode.getTag() == CalculatorText.TAG_ACTION_MODE) {
370 mFormulaContainer.scrollTo(mFormulaText.getRight(), 0);
371 }
372 }
373
Hans Boehm1176f232015-05-11 16:26:03 -0700374 // Stop any active ActionMode. Return true if there was one.
375 private boolean stopActionMode() {
Justin Klaassen44595162015-05-28 17:55:20 -0700376 if (mResultText.stopActionMode()) {
Hans Boehm1176f232015-05-11 16:26:03 -0700377 return true;
378 }
379 if (mFormulaText.stopActionMode()) {
380 return true;
381 }
382 return false;
383 }
384
Justin Klaassen4b3af052014-05-27 17:53:10 -0700385 @Override
Justin Klaassen12da1ad2016-04-04 14:20:37 -0700386 public void onUserInteraction() {
387 super.onUserInteraction();
388
389 // If there's an animation in progress, end it immediately, so the user interaction can
390 // be handled.
391 if (mCurrentAnimator != null) {
392 mCurrentAnimator.end();
393 }
394 }
395
396 @Override
Justin Klaassen3b4d13d2014-06-06 18:18:37 +0100397 public void onBackPressed() {
Hans Boehm1176f232015-05-11 16:26:03 -0700398 if (!stopActionMode()) {
399 if (mPadViewPager != null && mPadViewPager.getCurrentItem() != 0) {
400 // Select the previous pad.
401 mPadViewPager.setCurrentItem(mPadViewPager.getCurrentItem() - 1);
402 } else {
403 // If the user is currently looking at the first pad (or the pad is not paged),
404 // allow the system to handle the Back button.
405 super.onBackPressed();
406 }
Justin Klaassen3b4d13d2014-06-06 18:18:37 +0100407 }
408 }
409
410 @Override
Justin Klaassen12da1ad2016-04-04 14:20:37 -0700411 public boolean onKeyUp(int keyCode, KeyEvent event) {
Justin Klaassen83959da2016-04-06 11:55:24 -0700412 // Allow the system to handle special key codes (e.g. "BACK" or "DPAD").
Justin Klaassen12da1ad2016-04-04 14:20:37 -0700413 switch (keyCode) {
Justin Klaassen83959da2016-04-06 11:55:24 -0700414 case KeyEvent.KEYCODE_BACK:
Justin Klaassen12da1ad2016-04-04 14:20:37 -0700415 case KeyEvent.KEYCODE_DPAD_UP:
416 case KeyEvent.KEYCODE_DPAD_DOWN:
417 case KeyEvent.KEYCODE_DPAD_LEFT:
418 case KeyEvent.KEYCODE_DPAD_RIGHT:
419 return super.onKeyUp(keyCode, event);
420 }
421
Justin Klaassend12e0622016-04-27 16:26:47 -0700422 // Stop the action mode if it's showing.
423 stopActionMode();
424
Justin Klaassen12da1ad2016-04-04 14:20:37 -0700425 // Always cancel unrequested in-progress evaluation, so that we don't have to worry about
426 // subsequent asynchronous completion.
427 // Requested in-progress evaluations are handled below.
428 if (mCurrentState != CalculatorState.EVALUATE) {
429 mEvaluator.cancelAll(true);
430 }
431
432 switch (keyCode) {
433 case KeyEvent.KEYCODE_NUMPAD_ENTER:
434 case KeyEvent.KEYCODE_ENTER:
435 case KeyEvent.KEYCODE_DPAD_CENTER:
436 mCurrentButton = mEqualButton;
437 onEquals();
438 return true;
439 case KeyEvent.KEYCODE_DEL:
440 mCurrentButton = mDeleteButton;
441 onDelete();
442 return true;
443 default:
444 cancelIfEvaluating(false);
445 final int raw = event.getKeyCharacterMap().get(keyCode, event.getMetaState());
446 if ((raw & KeyCharacterMap.COMBINING_ACCENT) != 0) {
447 return true; // discard
448 }
449 // Try to discard non-printing characters and the like.
450 // The user will have to explicitly delete other junk that gets past us.
451 if (Character.isIdentifierIgnorable(raw) || Character.isWhitespace(raw)) {
452 return true;
453 }
454 char c = (char) raw;
455 if (c == '=') {
456 mCurrentButton = mEqualButton;
457 onEquals();
458 } else {
459 addChars(String.valueOf(c), true);
460 redisplayAfterFormulaChange();
461 }
462 return true;
Justin Klaassen4b3af052014-05-27 17:53:10 -0700463 }
464 }
465
Justin Klaassene2711cb2015-05-28 11:13:17 -0700466 /**
467 * Invoked whenever the inverse button is toggled to update the UI.
468 *
469 * @param showInverse {@code true} if inverse functions should be shown
470 */
471 private void onInverseToggled(boolean showInverse) {
Justin Klaassen3e223ea2016-02-05 14:18:06 -0800472 mInverseToggle.setSelected(showInverse);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700473 if (showInverse) {
474 mInverseToggle.setContentDescription(getString(R.string.desc_inv_on));
Justin Klaassen721ec842015-05-28 14:30:08 -0700475 for (View invertibleButton : mInvertibleButtons) {
476 invertibleButton.setVisibility(View.GONE);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700477 }
478 for (View inverseButton : mInverseButtons) {
479 inverseButton.setVisibility(View.VISIBLE);
480 }
481 } else {
482 mInverseToggle.setContentDescription(getString(R.string.desc_inv_off));
Justin Klaassen721ec842015-05-28 14:30:08 -0700483 for (View invertibleButton : mInvertibleButtons) {
484 invertibleButton.setVisibility(View.VISIBLE);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700485 }
486 for (View inverseButton : mInverseButtons) {
487 inverseButton.setVisibility(View.GONE);
488 }
489 }
490 }
491
492 /**
493 * Invoked whenever the deg/rad mode may have changed to update the UI.
494 *
495 * @param degreeMode {@code true} if in degree mode
496 */
497 private void onModeChanged(boolean degreeMode) {
498 if (degreeMode) {
Justin Klaassend48b7562015-04-16 16:51:38 -0700499 mModeView.setText(R.string.mode_deg);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700500 mModeView.setContentDescription(getString(R.string.desc_mode_deg));
501
502 mModeToggle.setText(R.string.mode_rad);
503 mModeToggle.setContentDescription(getString(R.string.desc_switch_rad));
Hans Boehmbfe8c222015-04-02 16:26:07 -0700504 } else {
Justin Klaassend48b7562015-04-16 16:51:38 -0700505 mModeView.setText(R.string.mode_rad);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700506 mModeView.setContentDescription(getString(R.string.desc_mode_rad));
507
508 mModeToggle.setText(R.string.mode_deg);
509 mModeToggle.setContentDescription(getString(R.string.desc_switch_deg));
Hans Boehmbfe8c222015-04-02 16:26:07 -0700510 }
Justin Klaassen9d33cdc2016-02-21 14:16:14 -0800511
512 // Show the toolbar to highlight the mode change.
Hans Boehm52d477a2016-04-01 17:42:50 -0700513 showAndMaybeHideToolbar();
Hans Boehmbfe8c222015-04-02 16:26:07 -0700514 }
Hans Boehm84614952014-11-25 18:46:17 -0800515
Hans Boehm5d79d102015-09-16 16:33:47 -0700516 /**
517 * Switch to INPUT from RESULT state in response to input of the specified button_id.
518 * View.NO_ID is treated as an incomplete function id.
519 */
520 private void switchToInput(int button_id) {
521 if (KeyMaps.isBinary(button_id) || KeyMaps.isSuffix(button_id)) {
522 mEvaluator.collapse();
523 } else {
524 announceClearedForAccessibility();
525 mEvaluator.clear();
526 }
527 setState(CalculatorState.INPUT);
528 }
529
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700530 // Add the given button id to input expression.
531 // If appropriate, clear the expression before doing so.
532 private void addKeyToExpr(int id) {
533 if (mCurrentState == CalculatorState.ERROR) {
534 setState(CalculatorState.INPUT);
535 } else if (mCurrentState == CalculatorState.RESULT) {
Hans Boehm5d79d102015-09-16 16:33:47 -0700536 switchToInput(id);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700537 }
538 if (!mEvaluator.append(id)) {
539 // TODO: Some user visible feedback?
540 }
541 }
542
Hans Boehm017de982015-06-10 17:46:03 -0700543 /**
544 * Add the given button id to input expression, assuming it was explicitly
545 * typed/touched.
546 * We perform slightly more aggressive correction than in pasted expressions.
547 */
548 private void addExplicitKeyToExpr(int id) {
549 if (mCurrentState == CalculatorState.INPUT && id == R.id.op_sub) {
550 mEvaluator.getExpr().removeTrailingAdditiveOperators();
551 }
552 addKeyToExpr(id);
553 }
554
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700555 private void redisplayAfterFormulaChange() {
556 // TODO: Could do this more incrementally.
557 redisplayFormula();
558 setState(CalculatorState.INPUT);
Hans Boehmaf04c3a2016-01-27 14:50:08 -0800559 if (haveUnprocessed()) {
Justin Klaassen44595162015-05-28 17:55:20 -0700560 mResultText.clear();
Hans Boehmaf04c3a2016-01-27 14:50:08 -0800561 // Force reevaluation when text is deleted, even if expression is unchanged.
562 mEvaluator.touch();
563 } else {
564 if (mEvaluator.getExpr().hasInterestingOps()) {
565 mEvaluator.evaluateAndShowResult();
566 } else {
567 mResultText.clear();
568 }
Hans Boehmc023b732015-04-29 11:30:47 -0700569 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700570 }
571
Hans Boehm52d477a2016-04-01 17:42:50 -0700572 /**
573 * Show the toolbar.
574 * Automatically hide it again if it's not relevant to current formula.
575 */
576 private void showAndMaybeHideToolbar() {
577 final boolean shouldBeVisible =
578 mCurrentState == CalculatorState.INPUT && mEvaluator.hasTrigFuncs();
579 mDisplayView.showToolbar(!shouldBeVisible);
580 }
581
582 /**
583 * Display or hide the toolbar depending on calculator state.
584 */
585 private void showOrHideToolbar() {
586 final boolean shouldBeVisible =
587 mCurrentState == CalculatorState.INPUT && mEvaluator.hasTrigFuncs();
588 if (shouldBeVisible) {
589 mDisplayView.showToolbar(false);
590 } else {
591 mDisplayView.hideToolbar();
592 }
593 }
594
Justin Klaassen4b3af052014-05-27 17:53:10 -0700595 public void onButtonClick(View view) {
Hans Boehmc1ea0912015-06-19 15:05:07 -0700596 // Any animation is ended before we get here.
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700597 mCurrentButton = view;
Hans Boehm1176f232015-05-11 16:26:03 -0700598 stopActionMode();
Justin Klaassen9d33cdc2016-02-21 14:16:14 -0800599
Hans Boehmc1ea0912015-06-19 15:05:07 -0700600 // See onKey above for the rationale behind some of the behavior below:
601 if (mCurrentState != CalculatorState.EVALUATE) {
602 // Cancel evaluations that were not specifically requested.
603 mEvaluator.cancelAll(true);
Hans Boehm84614952014-11-25 18:46:17 -0800604 }
Justin Klaassen9d33cdc2016-02-21 14:16:14 -0800605
Justin Klaassend48b7562015-04-16 16:51:38 -0700606 final int id = view.getId();
Hans Boehm84614952014-11-25 18:46:17 -0800607 switch (id) {
Justin Klaassen4b3af052014-05-27 17:53:10 -0700608 case R.id.eq:
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700609 onEquals();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700610 break;
611 case R.id.del:
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700612 onDelete();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700613 break;
614 case R.id.clr:
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700615 onClear();
Hans Boehm52d477a2016-04-01 17:42:50 -0700616 return; // Toolbar visibility adjusted at end of animation.
Justin Klaassene2711cb2015-05-28 11:13:17 -0700617 case R.id.toggle_inv:
618 final boolean selected = !mInverseToggle.isSelected();
619 mInverseToggle.setSelected(selected);
620 onInverseToggled(selected);
Hans Boehmc1ea0912015-06-19 15:05:07 -0700621 if (mCurrentState == CalculatorState.RESULT) {
622 mResultText.redisplay(); // In case we cancelled reevaluation.
623 }
Justin Klaassene2711cb2015-05-28 11:13:17 -0700624 break;
625 case R.id.toggle_mode:
Hans Boehmc1ea0912015-06-19 15:05:07 -0700626 cancelIfEvaluating(false);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700627 final boolean mode = !mEvaluator.getDegreeMode();
Hans Boehmbfe8c222015-04-02 16:26:07 -0700628 if (mCurrentState == CalculatorState.RESULT) {
629 mEvaluator.collapse(); // Capture result evaluated in old mode
630 redisplayFormula();
631 }
632 // In input mode, we reinterpret already entered trig functions.
633 mEvaluator.setDegreeMode(mode);
Justin Klaassene2711cb2015-05-28 11:13:17 -0700634 onModeChanged(mode);
Hans Boehmbfe8c222015-04-02 16:26:07 -0700635 setState(CalculatorState.INPUT);
Justin Klaassen44595162015-05-28 17:55:20 -0700636 mResultText.clear();
Hans Boehmaf04c3a2016-01-27 14:50:08 -0800637 if (!haveUnprocessed() && mEvaluator.getExpr().hasInterestingOps()) {
Hans Boehmc023b732015-04-29 11:30:47 -0700638 mEvaluator.evaluateAndShowResult();
639 }
Hans Boehm52d477a2016-04-01 17:42:50 -0700640 return; // onModeChanged adjusted toolbar visibility.
Justin Klaassen4b3af052014-05-27 17:53:10 -0700641 default:
Hans Boehmc1ea0912015-06-19 15:05:07 -0700642 cancelIfEvaluating(false);
Hans Boehmaf04c3a2016-01-27 14:50:08 -0800643 if (haveUnprocessed()) {
644 // For consistency, append as uninterpreted characters.
645 // This may actually be useful for a left parenthesis.
646 addChars(KeyMaps.toString(this, id), true);
647 } else {
648 addExplicitKeyToExpr(id);
649 redisplayAfterFormulaChange();
650 }
Justin Klaassen4b3af052014-05-27 17:53:10 -0700651 break;
652 }
Hans Boehm52d477a2016-04-01 17:42:50 -0700653 showOrHideToolbar();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700654 }
655
Hans Boehm84614952014-11-25 18:46:17 -0800656 void redisplayFormula() {
Hans Boehm8a4f81c2015-07-09 10:41:25 -0700657 SpannableStringBuilder formula = mEvaluator.getExpr().toSpannableStringBuilder(this);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700658 if (mUnprocessedChars != null) {
659 // Add and highlight characters we couldn't process.
Hans Boehm8a4f81c2015-07-09 10:41:25 -0700660 formula.append(mUnprocessedChars, mUnprocessedColorSpan,
661 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700662 }
Hans Boehm8a4f81c2015-07-09 10:41:25 -0700663 mFormulaText.changeTextTo(formula);
Annie Chinf360ef02016-03-10 13:45:39 -0800664 mFormulaText.setContentDescription(TextUtils.isEmpty(formula)
665 ? getString(R.string.desc_formula) : formula.toString());
Hans Boehm84614952014-11-25 18:46:17 -0800666 }
667
Justin Klaassen4b3af052014-05-27 17:53:10 -0700668 @Override
669 public boolean onLongClick(View view) {
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700670 mCurrentButton = view;
671
Justin Klaassen4b3af052014-05-27 17:53:10 -0700672 if (view.getId() == R.id.del) {
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700673 onClear();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700674 return true;
675 }
676 return false;
677 }
678
Hans Boehm84614952014-11-25 18:46:17 -0800679 // Initial evaluation completed successfully. Initiate display.
Hans Boehma0e45f32015-05-30 13:20:35 -0700680 public void onEvaluate(int initDisplayPrec, int msd, int leastDigPos,
681 String truncatedWholeNumber) {
Justin Klaassend48b7562015-04-16 16:51:38 -0700682 // Invalidate any options that may depend on the current result.
683 invalidateOptionsMenu();
684
Hans Boehma0e45f32015-05-30 13:20:35 -0700685 mResultText.displayResult(initDisplayPrec, msd, leastDigPos, truncatedWholeNumber);
Hans Boehm61568a12015-05-18 18:25:41 -0700686 if (mCurrentState != CalculatorState.INPUT) { // in EVALUATE or INIT state
Hans Boehm84614952014-11-25 18:46:17 -0800687 onResult(mCurrentState != CalculatorState.INIT);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700688 }
Hans Boehm84614952014-11-25 18:46:17 -0800689 }
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700690
Hans Boehmc1ea0912015-06-19 15:05:07 -0700691 // Reset state to reflect evaluator cancellation. Invoked by evaluator.
Hans Boehm84614952014-11-25 18:46:17 -0800692 public void onCancelled() {
693 // We should be in EVALUATE state.
Hans Boehm84614952014-11-25 18:46:17 -0800694 setState(CalculatorState.INPUT);
Justin Klaassen44595162015-05-28 17:55:20 -0700695 mResultText.clear();
Hans Boehm84614952014-11-25 18:46:17 -0800696 }
697
698 // Reevaluation completed; ask result to redisplay current value.
699 public void onReevaluate()
700 {
Justin Klaassen44595162015-05-28 17:55:20 -0700701 mResultText.redisplay();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700702 }
703
Justin Klaassenfed941a2014-06-09 18:42:40 +0100704 @Override
705 public void onTextSizeChanged(final TextView textView, float oldSize) {
706 if (mCurrentState != CalculatorState.INPUT) {
707 // Only animate text changes that occur from user input.
708 return;
709 }
710
711 // Calculate the values needed to perform the scale and translation animations,
712 // maintaining the same apparent baseline for the displayed text.
713 final float textScale = oldSize / textView.getTextSize();
714 final float translationX = (1.0f - textScale) *
715 (textView.getWidth() / 2.0f - textView.getPaddingEnd());
716 final float translationY = (1.0f - textScale) *
717 (textView.getHeight() / 2.0f - textView.getPaddingBottom());
718
719 final AnimatorSet animatorSet = new AnimatorSet();
720 animatorSet.playTogether(
721 ObjectAnimator.ofFloat(textView, View.SCALE_X, textScale, 1.0f),
722 ObjectAnimator.ofFloat(textView, View.SCALE_Y, textScale, 1.0f),
723 ObjectAnimator.ofFloat(textView, View.TRANSLATION_X, translationX, 0.0f),
724 ObjectAnimator.ofFloat(textView, View.TRANSLATION_Y, translationY, 0.0f));
Justin Klaassen94db7202014-06-11 11:22:31 -0700725 animatorSet.setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime));
Justin Klaassenfed941a2014-06-09 18:42:40 +0100726 animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
727 animatorSet.start();
728 }
729
Hans Boehmc1ea0912015-06-19 15:05:07 -0700730 /**
731 * Cancel any in-progress explicitly requested evaluations.
732 * @param quiet suppress pop-up message. Explicit evaluation can change the expression
733 value, and certainly changes the display, so it seems reasonable to warn.
734 * @return true if there was such an evaluation
735 */
736 private boolean cancelIfEvaluating(boolean quiet) {
737 if (mCurrentState == CalculatorState.EVALUATE) {
738 mEvaluator.cancelAll(quiet);
739 return true;
740 } else {
741 return false;
742 }
743 }
744
Hans Boehmaf04c3a2016-01-27 14:50:08 -0800745 private boolean haveUnprocessed() {
746 return mUnprocessedChars != null && !mUnprocessedChars.isEmpty();
747 }
748
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700749 private void onEquals() {
Hans Boehmc1ea0912015-06-19 15:05:07 -0700750 // In non-INPUT state assume this was redundant and ignore it.
Hans Boehmc023b732015-04-29 11:30:47 -0700751 if (mCurrentState == CalculatorState.INPUT && !mEvaluator.getExpr().isEmpty()) {
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700752 setState(CalculatorState.EVALUATE);
Hans Boehmaf04c3a2016-01-27 14:50:08 -0800753 if (haveUnprocessed()) {
754 onError(R.string.error_syntax);
755 } else {
756 mEvaluator.requireResult();
757 }
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700758 }
759 }
760
761 private void onDelete() {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700762 // Delete works like backspace; remove the last character or operator from the expression.
763 // Note that we handle keyboard delete exactly like the delete button. For
764 // example the delete button can be used to delete a character from an incomplete
765 // function name typed on a physical keyboard.
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700766 // This should be impossible in RESULT state.
Hans Boehmc1ea0912015-06-19 15:05:07 -0700767 // If there is an in-progress explicit evaluation, just cancel it and return.
768 if (cancelIfEvaluating(false)) return;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700769 setState(CalculatorState.INPUT);
Hans Boehmaf04c3a2016-01-27 14:50:08 -0800770 if (haveUnprocessed()) {
771 mUnprocessedChars = mUnprocessedChars.substring(0, mUnprocessedChars.length() - 1);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700772 } else {
Hans Boehmc023b732015-04-29 11:30:47 -0700773 mEvaluator.delete();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700774 }
Hans Boehmaf04c3a2016-01-27 14:50:08 -0800775 if (mEvaluator.getExpr().isEmpty() && !haveUnprocessed()) {
Hans Boehmdb6f9992015-08-19 12:32:56 -0700776 // Resulting formula won't be announced, since it's empty.
777 announceClearedForAccessibility();
778 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700779 redisplayAfterFormulaChange();
Budi Kusmiantoroad8e88a2014-08-11 17:21:09 -0700780 }
781
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700782 private void reveal(View sourceView, int colorRes, AnimatorListener listener) {
Justin Klaassen06360f92014-08-28 11:08:44 -0700783 final ViewGroupOverlay groupOverlay =
784 (ViewGroupOverlay) getWindow().getDecorView().getOverlay();
Justin Klaassen8fff1442014-06-19 10:43:29 -0700785
786 final Rect displayRect = new Rect();
Justin Klaassen06360f92014-08-28 11:08:44 -0700787 mDisplayView.getGlobalVisibleRect(displayRect);
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700788
789 // Make reveal cover the display and status bar.
790 final View revealView = new View(this);
Justin Klaassen8fff1442014-06-19 10:43:29 -0700791 revealView.setBottom(displayRect.bottom);
792 revealView.setLeft(displayRect.left);
793 revealView.setRight(displayRect.right);
Hans Boehmaf04c3a2016-01-27 14:50:08 -0800794 revealView.setBackgroundColor(getColor(colorRes));
Justin Klaassen06360f92014-08-28 11:08:44 -0700795 groupOverlay.add(revealView);
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700796
Justin Klaassen4b3af052014-05-27 17:53:10 -0700797 final int[] clearLocation = new int[2];
798 sourceView.getLocationInWindow(clearLocation);
799 clearLocation[0] += sourceView.getWidth() / 2;
800 clearLocation[1] += sourceView.getHeight() / 2;
801
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700802 final int revealCenterX = clearLocation[0] - revealView.getLeft();
803 final int revealCenterY = clearLocation[1] - revealView.getTop();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700804
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700805 final double x1_2 = Math.pow(revealView.getLeft() - revealCenterX, 2);
806 final double x2_2 = Math.pow(revealView.getRight() - revealCenterX, 2);
807 final double y_2 = Math.pow(revealView.getTop() - revealCenterY, 2);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700808 final float revealRadius = (float) Math.max(Math.sqrt(x1_2 + y_2), Math.sqrt(x2_2 + y_2));
809
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700810 final Animator revealAnimator =
811 ViewAnimationUtils.createCircularReveal(revealView,
ztenghui3d6ecaf2014-06-05 09:56:00 -0700812 revealCenterX, revealCenterY, 0.0f, revealRadius);
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700813 revealAnimator.setDuration(
Justin Klaassen4b3af052014-05-27 17:53:10 -0700814 getResources().getInteger(android.R.integer.config_longAnimTime));
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700815 revealAnimator.addListener(listener);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700816
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700817 final Animator alphaAnimator = ObjectAnimator.ofFloat(revealView, View.ALPHA, 0.0f);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700818 alphaAnimator.setDuration(
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700819 getResources().getInteger(android.R.integer.config_mediumAnimTime));
Justin Klaassen4b3af052014-05-27 17:53:10 -0700820
821 final AnimatorSet animatorSet = new AnimatorSet();
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700822 animatorSet.play(revealAnimator).before(alphaAnimator);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700823 animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
824 animatorSet.addListener(new AnimatorListenerAdapter() {
825 @Override
Justin Klaassen4b3af052014-05-27 17:53:10 -0700826 public void onAnimationEnd(Animator animator) {
Justin Klaassen8fff1442014-06-19 10:43:29 -0700827 groupOverlay.remove(revealView);
Justin Klaassen4b3af052014-05-27 17:53:10 -0700828 mCurrentAnimator = null;
829 }
830 });
831
832 mCurrentAnimator = animatorSet;
833 animatorSet.start();
834 }
835
Hans Boehmdb6f9992015-08-19 12:32:56 -0700836 private void announceClearedForAccessibility() {
837 mResultText.announceForAccessibility(getResources().getString(R.string.cleared));
Hans Boehmccc55662015-07-07 14:16:59 -0700838 }
839
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700840 private void onClear() {
Justin Klaassen1a428cf2016-02-24 15:58:18 -0800841 if (mEvaluator.getExpr().isEmpty() && !haveUnprocessed()) {
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700842 return;
843 }
Hans Boehmc1ea0912015-06-19 15:05:07 -0700844 cancelIfEvaluating(true);
Hans Boehmdb6f9992015-08-19 12:32:56 -0700845 announceClearedForAccessibility();
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700846 reveal(mCurrentButton, R.color.calculator_accent_color, new AnimatorListenerAdapter() {
847 @Override
848 public void onAnimationEnd(Animator animation) {
Hans Boehm760a9dc2015-04-20 10:27:12 -0700849 mUnprocessedChars = null;
Justin Klaassen44595162015-05-28 17:55:20 -0700850 mResultText.clear();
Hans Boehm760a9dc2015-04-20 10:27:12 -0700851 mEvaluator.clear();
852 setState(CalculatorState.INPUT);
Hans Boehm52d477a2016-04-01 17:42:50 -0700853 showOrHideToolbar();
Hans Boehm84614952014-11-25 18:46:17 -0800854 redisplayFormula();
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700855 }
856 });
857 }
858
Hans Boehm84614952014-11-25 18:46:17 -0800859 // Evaluation encountered en error. Display the error.
860 void onError(final int errorResourceId) {
Hans Boehmfbcef702015-04-27 18:07:47 -0700861 if (mCurrentState == CalculatorState.EVALUATE) {
862 setState(CalculatorState.ANIMATE);
Hans Boehmccc55662015-07-07 14:16:59 -0700863 mResultText.announceForAccessibility(getResources().getString(errorResourceId));
Hans Boehmfbcef702015-04-27 18:07:47 -0700864 reveal(mCurrentButton, R.color.calculator_error_color,
865 new AnimatorListenerAdapter() {
866 @Override
867 public void onAnimationEnd(Animator animation) {
868 setState(CalculatorState.ERROR);
Justin Klaassen44595162015-05-28 17:55:20 -0700869 mResultText.displayError(errorResourceId);
Hans Boehmfbcef702015-04-27 18:07:47 -0700870 }
871 });
872 } else if (mCurrentState == CalculatorState.INIT) {
873 setState(CalculatorState.ERROR);
Justin Klaassen44595162015-05-28 17:55:20 -0700874 mResultText.displayError(errorResourceId);
Hans Boehmc023b732015-04-29 11:30:47 -0700875 } else {
Justin Klaassen44595162015-05-28 17:55:20 -0700876 mResultText.clear();
Justin Klaassen2be4fdb2014-08-06 19:54:09 -0700877 }
Justin Klaassen5f2a3342014-06-11 17:40:22 -0700878 }
879
Hans Boehm84614952014-11-25 18:46:17 -0800880 // Animate movement of result into the top formula slot.
881 // Result window now remains translated in the top slot while the result is displayed.
882 // (We convert it back to formula use only when the user provides new input.)
Justin Klaassen44595162015-05-28 17:55:20 -0700883 // Historical note: In the Lollipop version, this invisibly and instantaneously moved
Hans Boehm84614952014-11-25 18:46:17 -0800884 // formula and result displays back at the end of the animation. We no longer do that,
885 // so that we can continue to properly support scrolling of the result.
886 // We assume the result already contains the text to be expanded.
887 private void onResult(boolean animate) {
Justin Klaassen44595162015-05-28 17:55:20 -0700888 // Calculate the textSize that would be used to display the result in the formula.
889 // For scrollable results just use the minimum textSize to maximize the number of digits
890 // that are visible on screen.
891 float textSize = mFormulaText.getMinimumTextSize();
892 if (!mResultText.isScrollable()) {
893 textSize = mFormulaText.getVariableTextSize(mResultText.getText().toString());
894 }
895
896 // Scale the result to match the calculated textSize, minimizing the jump-cut transition
897 // when a result is reused in a subsequent expression.
898 final float resultScale = textSize / mResultText.getTextSize();
899
900 // Set the result's pivot to match its gravity.
901 mResultText.setPivotX(mResultText.getWidth() - mResultText.getPaddingRight());
902 mResultText.setPivotY(mResultText.getHeight() - mResultText.getPaddingBottom());
903
904 // Calculate the necessary translations so the result takes the place of the formula and
905 // the formula moves off the top of the screen.
Annie Chine918fd22016-03-09 11:07:54 -0800906 final float resultTranslationY = (mFormulaContainer.getBottom() - mResultText.getBottom())
Justin Klaassenf9ae3632016-03-23 11:07:46 -0700907 - (mFormulaText.getPaddingBottom() - mResultText.getPaddingBottom());
Annie Chine918fd22016-03-09 11:07:54 -0800908 final float formulaTranslationY = -mFormulaContainer.getBottom();
Justin Klaassen4b3af052014-05-27 17:53:10 -0700909
Justin Klaassen44595162015-05-28 17:55:20 -0700910 // Change the result's textColor to match the formula.
911 final int formulaTextColor = mFormulaText.getCurrentTextColor();
912
Hans Boehm84614952014-11-25 18:46:17 -0800913 if (animate) {
Hans Boehmccc55662015-07-07 14:16:59 -0700914 mResultText.announceForAccessibility(getResources().getString(R.string.desc_eq));
915 mResultText.announceForAccessibility(mResultText.getText());
Hans Boehmc1ea0912015-06-19 15:05:07 -0700916 setState(CalculatorState.ANIMATE);
Hans Boehm84614952014-11-25 18:46:17 -0800917 final AnimatorSet animatorSet = new AnimatorSet();
918 animatorSet.playTogether(
Justin Klaassen44595162015-05-28 17:55:20 -0700919 ObjectAnimator.ofPropertyValuesHolder(mResultText,
920 PropertyValuesHolder.ofFloat(View.SCALE_X, resultScale),
921 PropertyValuesHolder.ofFloat(View.SCALE_Y, resultScale),
922 PropertyValuesHolder.ofFloat(View.TRANSLATION_Y, resultTranslationY)),
923 ObjectAnimator.ofArgb(mResultText, TEXT_COLOR, formulaTextColor),
Annie Chine918fd22016-03-09 11:07:54 -0800924 ObjectAnimator.ofFloat(mFormulaContainer, View.TRANSLATION_Y,
925 formulaTranslationY));
Justin Klaassen44595162015-05-28 17:55:20 -0700926 animatorSet.setDuration(getResources().getInteger(
927 android.R.integer.config_longAnimTime));
Hans Boehm84614952014-11-25 18:46:17 -0800928 animatorSet.addListener(new AnimatorListenerAdapter() {
929 @Override
Hans Boehm84614952014-11-25 18:46:17 -0800930 public void onAnimationEnd(Animator animation) {
931 setState(CalculatorState.RESULT);
932 mCurrentAnimator = null;
933 }
934 });
Justin Klaassen4b3af052014-05-27 17:53:10 -0700935
Hans Boehm84614952014-11-25 18:46:17 -0800936 mCurrentAnimator = animatorSet;
937 animatorSet.start();
938 } else /* No animation desired; get there fast, e.g. when restarting */ {
Justin Klaassen44595162015-05-28 17:55:20 -0700939 mResultText.setScaleX(resultScale);
940 mResultText.setScaleY(resultScale);
941 mResultText.setTranslationY(resultTranslationY);
942 mResultText.setTextColor(formulaTextColor);
Annie Chine918fd22016-03-09 11:07:54 -0800943 mFormulaContainer.setTranslationY(formulaTranslationY);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700944 setState(CalculatorState.RESULT);
Hans Boehm84614952014-11-25 18:46:17 -0800945 }
Justin Klaassen4b3af052014-05-27 17:53:10 -0700946 }
Hans Boehm84614952014-11-25 18:46:17 -0800947
948 // Restore positions of the formula and result displays back to their original,
949 // pre-animation state.
950 private void restoreDisplayPositions() {
951 // Clear result.
Justin Klaassen44595162015-05-28 17:55:20 -0700952 mResultText.setText("");
Hans Boehm84614952014-11-25 18:46:17 -0800953 // Reset all of the values modified during the animation.
Justin Klaassen44595162015-05-28 17:55:20 -0700954 mResultText.setScaleX(1.0f);
955 mResultText.setScaleY(1.0f);
956 mResultText.setTranslationX(0.0f);
957 mResultText.setTranslationY(0.0f);
Annie Chine918fd22016-03-09 11:07:54 -0800958 mFormulaContainer.setTranslationY(0.0f);
Hans Boehm84614952014-11-25 18:46:17 -0800959
Hans Boehm08e8f322015-04-21 13:18:38 -0700960 mFormulaText.requestFocus();
Hans Boehm5e6a0ca2015-09-22 17:09:01 -0700961 }
962
963 @Override
964 public void onClick(AlertDialogFragment fragment, int which) {
965 if (which == DialogInterface.BUTTON_POSITIVE) {
966 // Timeout extension request.
967 mEvaluator.setLongTimeOut();
968 }
969 }
Hans Boehm84614952014-11-25 18:46:17 -0800970
Justin Klaassend48b7562015-04-16 16:51:38 -0700971 @Override
972 public boolean onCreateOptionsMenu(Menu menu) {
Justin Klaassend36d63e2015-05-05 12:59:36 -0700973 super.onCreateOptionsMenu(menu);
974
975 getMenuInflater().inflate(R.menu.activity_calculator, menu);
Justin Klaassend48b7562015-04-16 16:51:38 -0700976 return true;
977 }
978
979 @Override
980 public boolean onPrepareOptionsMenu(Menu menu) {
Justin Klaassend36d63e2015-05-05 12:59:36 -0700981 super.onPrepareOptionsMenu(menu);
982
983 // Show the leading option when displaying a result.
984 menu.findItem(R.id.menu_leading).setVisible(mCurrentState == CalculatorState.RESULT);
985
986 // Show the fraction option when displaying a rational result.
987 menu.findItem(R.id.menu_fraction).setVisible(mCurrentState == CalculatorState.RESULT
Hans Boehm995e5eb2016-02-08 11:03:01 -0800988 && mEvaluator.getResult().exactlyDisplayable());
Justin Klaassend36d63e2015-05-05 12:59:36 -0700989
Justin Klaassend48b7562015-04-16 16:51:38 -0700990 return true;
Hans Boehm84614952014-11-25 18:46:17 -0800991 }
992
993 @Override
Justin Klaassend48b7562015-04-16 16:51:38 -0700994 public boolean onOptionsItemSelected(MenuItem item) {
Hans Boehm84614952014-11-25 18:46:17 -0800995 switch (item.getItemId()) {
Justin Klaassend36d63e2015-05-05 12:59:36 -0700996 case R.id.menu_leading:
997 displayFull();
Hans Boehm84614952014-11-25 18:46:17 -0800998 return true;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700999 case R.id.menu_fraction:
1000 displayFraction();
1001 return true;
Justin Klaassend36d63e2015-05-05 12:59:36 -07001002 case R.id.menu_licenses:
1003 startActivity(new Intent(this, Licenses.class));
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001004 return true;
Hans Boehm84614952014-11-25 18:46:17 -08001005 default:
1006 return super.onOptionsItemSelected(item);
1007 }
1008 }
1009
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001010 private void displayMessage(String s) {
Hans Boehm5e6a0ca2015-09-22 17:09:01 -07001011 AlertDialogFragment.showMessageDialog(this, s, null);
Hans Boehm84614952014-11-25 18:46:17 -08001012 }
1013
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001014 private void displayFraction() {
Hans Boehm995e5eb2016-02-08 11:03:01 -08001015 UnifiedReal result = mEvaluator.getResult();
Hans Boehm013969e2015-04-13 20:29:47 -07001016 displayMessage(KeyMaps.translateResult(result.toNiceString()));
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001017 }
1018
1019 // Display full result to currently evaluated precision
1020 private void displayFull() {
1021 Resources res = getResources();
Justin Klaassen44595162015-05-28 17:55:20 -07001022 String msg = mResultText.getFullText() + " ";
1023 if (mResultText.fullTextIsExact()) {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001024 msg += res.getString(R.string.exact);
1025 } else {
1026 msg += res.getString(R.string.approximate);
1027 }
1028 displayMessage(msg);
1029 }
1030
Hans Boehm017de982015-06-10 17:46:03 -07001031 /**
1032 * Add input characters to the end of the expression.
1033 * Map them to the appropriate button pushes when possible. Leftover characters
1034 * are added to mUnprocessedChars, which is presumed to immediately precede the newly
1035 * added characters.
Hans Boehm65a99a42016-02-03 18:16:07 -08001036 * @param moreChars characters to be added
1037 * @param explicit these characters were explicitly typed by the user, not pasted
Hans Boehm017de982015-06-10 17:46:03 -07001038 */
1039 private void addChars(String moreChars, boolean explicit) {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001040 if (mUnprocessedChars != null) {
1041 moreChars = mUnprocessedChars + moreChars;
1042 }
1043 int current = 0;
1044 int len = moreChars.length();
Hans Boehm0b9806f2015-06-29 16:07:15 -07001045 boolean lastWasDigit = false;
Hans Boehm5d79d102015-09-16 16:33:47 -07001046 if (mCurrentState == CalculatorState.RESULT && len != 0) {
1047 // Clear display immediately for incomplete function name.
1048 switchToInput(KeyMaps.keyForChar(moreChars.charAt(current)));
1049 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001050 while (current < len) {
1051 char c = moreChars.charAt(current);
Hans Boehm013969e2015-04-13 20:29:47 -07001052 int k = KeyMaps.keyForChar(c);
Hans Boehm0b9806f2015-06-29 16:07:15 -07001053 if (!explicit) {
1054 int expEnd;
1055 if (lastWasDigit && current !=
1056 (expEnd = Evaluator.exponentEnd(moreChars, current))) {
1057 // Process scientific notation with 'E' when pasting, in spite of ambiguity
1058 // with base of natural log.
1059 // Otherwise the 10^x key is the user's friend.
1060 mEvaluator.addExponent(moreChars, current, expEnd);
1061 current = expEnd;
1062 lastWasDigit = false;
1063 continue;
1064 } else {
1065 boolean isDigit = KeyMaps.digVal(k) != KeyMaps.NOT_DIGIT;
1066 if (current == 0 && (isDigit || k == R.id.dec_point)
1067 && mEvaluator.getExpr().hasTrailingConstant()) {
1068 // Refuse to concatenate pasted content to trailing constant.
1069 // This makes pasting of calculator results more consistent, whether or
1070 // not the old calculator instance is still around.
1071 addKeyToExpr(R.id.op_mul);
1072 }
1073 lastWasDigit = (isDigit || lastWasDigit && k == R.id.dec_point);
1074 }
1075 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001076 if (k != View.NO_ID) {
1077 mCurrentButton = findViewById(k);
Hans Boehm017de982015-06-10 17:46:03 -07001078 if (explicit) {
1079 addExplicitKeyToExpr(k);
1080 } else {
1081 addKeyToExpr(k);
1082 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001083 if (Character.isSurrogate(c)) {
1084 current += 2;
1085 } else {
1086 ++current;
1087 }
1088 continue;
1089 }
Hans Boehm013969e2015-04-13 20:29:47 -07001090 int f = KeyMaps.funForString(moreChars, current);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001091 if (f != View.NO_ID) {
1092 mCurrentButton = findViewById(f);
Hans Boehm017de982015-06-10 17:46:03 -07001093 if (explicit) {
1094 addExplicitKeyToExpr(f);
1095 } else {
1096 addKeyToExpr(f);
1097 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001098 if (f == R.id.op_sqrt) {
1099 // Square root entered as function; don't lose the parenthesis.
1100 addKeyToExpr(R.id.lparen);
1101 }
1102 current = moreChars.indexOf('(', current) + 1;
1103 continue;
1104 }
1105 // There are characters left, but we can't convert them to button presses.
1106 mUnprocessedChars = moreChars.substring(current);
1107 redisplayAfterFormulaChange();
Hans Boehm52d477a2016-04-01 17:42:50 -07001108 showOrHideToolbar();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001109 return;
1110 }
1111 mUnprocessedChars = null;
1112 redisplayAfterFormulaChange();
Hans Boehm52d477a2016-04-01 17:42:50 -07001113 showOrHideToolbar();
Hans Boehm84614952014-11-25 18:46:17 -08001114 }
1115
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001116 @Override
Justin Klaassenfc5ac822015-06-18 13:15:17 -07001117 public boolean onPaste(ClipData clip) {
1118 final ClipData.Item item = clip.getItemCount() == 0 ? null : clip.getItemAt(0);
1119 if (item == null) {
1120 // nothing to paste, bail early...
1121 return false;
1122 }
1123
1124 // Check if the item is a previously copied result, otherwise paste as raw text.
1125 final Uri uri = item.getUri();
1126 if (uri != null && mEvaluator.isLastSaved(uri)) {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001127 if (mCurrentState == CalculatorState.ERROR
Justin Klaassenfc5ac822015-06-18 13:15:17 -07001128 || mCurrentState == CalculatorState.RESULT) {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001129 setState(CalculatorState.INPUT);
1130 mEvaluator.clear();
Hans Boehm84614952014-11-25 18:46:17 -08001131 }
Hans Boehm3666e632015-07-27 18:33:12 -07001132 mEvaluator.appendSaved();
Hans Boehm4a6b7cb2015-04-03 18:41:52 -07001133 redisplayAfterFormulaChange();
Justin Klaassenfc5ac822015-06-18 13:15:17 -07001134 } else {
Hans Boehm017de982015-06-10 17:46:03 -07001135 addChars(item.coerceToText(this).toString(), false);
Hans Boehm84614952014-11-25 18:46:17 -08001136 }
Justin Klaassenfc5ac822015-06-18 13:15:17 -07001137 return true;
Hans Boehm84614952014-11-25 18:46:17 -08001138 }
Justin Klaassen4b3af052014-05-27 17:53:10 -07001139}