blob: b43983f9c36fab2ec7dcacb443f5b948a851e631 [file] [log] [blame]
Mindy Pereira9b875682012-02-15 18:10:54 -08001/*
2 * Copyright (C) 2012 Google Inc.
3 * Licensed to The Android Open Source Project.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package com.android.mail.ui;
19
mindypf4fce122012-09-14 15:55:33 -070020
Paul Westbrookb8361c92012-09-27 10:57:14 -070021import android.content.ContentResolver;
Mindy Pereira9b875682012-02-15 18:10:54 -080022import android.content.Context;
Mindy Pereira8e915722012-02-16 14:42:56 -080023import android.content.Loader;
mindypad0c30d2012-09-25 12:09:13 -070024import android.content.res.Resources;
Mindy Pereira9b875682012-02-15 18:10:54 -080025import android.database.Cursor;
Andy Huang9d3fd922012-09-26 22:23:58 -070026import android.database.DataSetObserver;
Paul Westbrookb8361c92012-09-27 10:57:14 -070027import android.net.Uri;
Paul Westbrookcebcc642012-08-08 10:06:04 -070028import android.os.AsyncTask;
Mindy Pereira9b875682012-02-15 18:10:54 -080029import android.os.Bundle;
mindyp3bcf1802012-09-09 11:17:00 -070030import android.os.SystemClock;
Andy Huang47aa9c92012-07-31 15:37:21 -070031import android.text.TextUtils;
Mindy Pereira9b875682012-02-15 18:10:54 -080032import android.view.LayoutInflater;
Andy Huang02f9d182012-11-28 22:38:02 -080033import android.view.ScaleGestureDetector;
Andy Huang02f9d182012-11-28 22:38:02 -080034import android.view.ScaleGestureDetector.OnScaleGestureListener;
Andy Huangc1fb9a92013-02-11 13:09:12 -080035import android.view.View;
Mark Wei4071c2f2012-09-26 14:38:38 -070036import android.view.View.OnLayoutChangeListener;
Mindy Pereira9b875682012-02-15 18:10:54 -080037import android.view.ViewGroup;
Andy Huangf70fc402012-02-17 15:37:42 -080038import android.webkit.ConsoleMessage;
Paul Westbrookcebcc642012-08-08 10:06:04 -070039import android.webkit.CookieManager;
40import android.webkit.CookieSyncManager;
Mindy Pereira974c9662012-09-14 10:02:08 -070041import android.webkit.JavascriptInterface;
Andy Huangf70fc402012-02-17 15:37:42 -080042import android.webkit.WebChromeClient;
43import android.webkit.WebSettings;
Andy Huang17a9cde2012-03-09 18:03:16 -080044import android.webkit.WebView;
45import android.webkit.WebViewClient;
Andy Huang47aa9c92012-07-31 15:37:21 -070046import android.widget.TextView;
Mindy Pereira9b875682012-02-15 18:10:54 -080047
Andy Huang59e0b182012-08-14 14:32:23 -070048import com.android.mail.FormattedDateBuilder;
Mindy Pereira9b875682012-02-15 18:10:54 -080049import com.android.mail.R;
Andy Huang5ff63742012-03-16 20:30:23 -070050import com.android.mail.browse.ConversationContainer;
Andy Huangadbf3e82012-10-13 13:30:19 -070051import com.android.mail.browse.ConversationContainer.OverlayPosition;
Andy Huang46dfba62012-04-19 01:47:32 -070052import com.android.mail.browse.ConversationOverlayItem;
Andy Huang7bdc3752012-03-25 17:18:19 -070053import com.android.mail.browse.ConversationViewAdapter;
Andy Huang46dfba62012-04-19 01:47:32 -070054import com.android.mail.browse.ConversationViewAdapter.MessageFooterItem;
Andy Huang7bdc3752012-03-25 17:18:19 -070055import com.android.mail.browse.ConversationViewAdapter.MessageHeaderItem;
Andy Huang46dfba62012-04-19 01:47:32 -070056import com.android.mail.browse.ConversationViewAdapter.SuperCollapsedBlockItem;
Andy Huang5ff63742012-03-16 20:30:23 -070057import com.android.mail.browse.ConversationViewHeader;
58import com.android.mail.browse.ConversationWebView;
Andy Huangc1fb9a92013-02-11 13:09:12 -080059import com.android.mail.browse.MailWebView.ContentSizeChangeListener;
Andy Huang7bdc3752012-03-25 17:18:19 -070060import com.android.mail.browse.MessageCursor;
Andy Huang28b7aee2012-08-20 20:27:32 -070061import com.android.mail.browse.MessageCursor.ConversationMessage;
Andy Huang59e0b182012-08-14 14:32:23 -070062import com.android.mail.browse.MessageHeaderView;
Andy Huangadbf3e82012-10-13 13:30:19 -070063import com.android.mail.browse.ScrollIndicatorsView;
Andy Huang46dfba62012-04-19 01:47:32 -070064import com.android.mail.browse.SuperCollapsedBlock;
Andy Huang0b7ed6f2012-07-25 19:23:26 -070065import com.android.mail.browse.WebViewContextMenu;
Andy Huangc1fb9a92013-02-11 13:09:12 -080066import com.android.mail.preferences.MailPrefs;
Mindy Pereira9b875682012-02-15 18:10:54 -080067import com.android.mail.providers.Account;
Andy Huang65fe28f2012-04-06 18:08:53 -070068import com.android.mail.providers.Address;
Mindy Pereira9b875682012-02-15 18:10:54 -080069import com.android.mail.providers.Conversation;
Andy Huangf70fc402012-02-17 15:37:42 -080070import com.android.mail.providers.Message;
Paul Westbrookb8361c92012-09-27 10:57:14 -070071import com.android.mail.providers.UIProvider;
Andy Huangcd5c5ee2012-08-12 19:03:51 -070072import com.android.mail.ui.ConversationViewState.ExpansionState;
Paul Westbrookb334c902012-06-25 11:42:46 -070073import com.android.mail.utils.LogTag;
Mindy Pereira9b875682012-02-15 18:10:54 -080074import com.android.mail.utils.LogUtils;
Andy Huang2e9acfe2012-03-15 22:39:36 -070075import com.android.mail.utils.Utils;
Andy Huang543e7092013-04-22 11:44:56 -070076import com.google.common.collect.ImmutableList;
Andy Huang46dfba62012-04-19 01:47:32 -070077import com.google.common.collect.Lists;
Andy Huang05c70c82013-03-14 15:15:50 -070078import com.google.common.collect.Maps;
Andy Huangb8331b42012-07-16 19:08:53 -070079import com.google.common.collect.Sets;
Andy Huang65fe28f2012-04-06 18:08:53 -070080
Scott Kennedyeb9a4bd2012-11-12 10:33:04 -080081import java.util.ArrayList;
Andy Huang46dfba62012-04-19 01:47:32 -070082import java.util.List;
Andy Huang05c70c82013-03-14 15:15:50 -070083import java.util.Map;
Andy Huangb8331b42012-07-16 19:08:53 -070084import java.util.Set;
Mindy Pereira9b875682012-02-15 18:10:54 -080085
Andy Huangf70fc402012-02-17 15:37:42 -080086
Mindy Pereira9b875682012-02-15 18:10:54 -080087/**
88 * The conversation view UI component.
89 */
mindypf4fce122012-09-14 15:55:33 -070090public final class ConversationViewFragment extends AbstractConversationViewFragment implements
Andy Huangcd5c5ee2012-08-12 19:03:51 -070091 SuperCollapsedBlock.OnClickListener,
Andy Huang57f354c2013-04-11 17:23:40 -070092 OnLayoutChangeListener {
Mindy Pereira8e915722012-02-16 14:42:56 -080093
Paul Westbrookb334c902012-06-25 11:42:46 -070094 private static final String LOG_TAG = LogTag.getLogTag();
Andy Huang632721e2012-04-11 16:57:26 -070095 public static final String LAYOUT_TAG = "ConvLayout";
Mindy Pereira9b875682012-02-15 18:10:54 -080096
Andy Huang3c276bf2013-02-19 14:24:43 -080097 private static final boolean ENABLE_CSS_ZOOM = false;
98
Andy Huang9d3fd922012-09-26 22:23:58 -070099 /**
mindyp1b3cc472012-09-27 11:32:59 -0700100 * Difference in the height of the message header whose details have been expanded/collapsed
101 */
102 private int mDiff = 0;
103
104 /**
Andy Huang9d3fd922012-09-26 22:23:58 -0700105 * Default value for {@link #mLoadWaitReason}. Conversation load will happen immediately.
106 */
107 private final int LOAD_NOW = 0;
108 /**
109 * Value for {@link #mLoadWaitReason} that means we are offscreen and waiting for the visible
110 * conversation to finish loading before beginning our load.
111 * <p>
112 * When this value is set, the fragment should register with {@link ConversationListCallbacks}
113 * to know when the visible conversation is loaded. When it is unset, it should unregister.
114 */
115 private final int LOAD_WAIT_FOR_INITIAL_CONVERSATION = 1;
116 /**
117 * Value for {@link #mLoadWaitReason} used when a conversation is too heavyweight to load at
118 * all when not visible (e.g. requires network fetch, or too complex). Conversation load will
119 * wait until this fragment is visible.
120 */
121 private final int LOAD_WAIT_UNTIL_VISIBLE = 2;
mindyp3bcf1802012-09-09 11:17:00 -0700122
Andy Huangf70fc402012-02-17 15:37:42 -0800123 private ConversationContainer mConversationContainer;
Mindy Pereira9b875682012-02-15 18:10:54 -0800124
Andy Huangf70fc402012-02-17 15:37:42 -0800125 private ConversationWebView mWebView;
Mindy Pereira9b875682012-02-15 18:10:54 -0800126
Mark Wei56d83852012-09-19 14:28:50 -0700127 private ScrollIndicatorsView mScrollIndicators;
128
Andy Huang47aa9c92012-07-31 15:37:21 -0700129 private View mNewMessageBar;
130
Andy Huangf70fc402012-02-17 15:37:42 -0800131 private HtmlConversationTemplates mTemplates;
132
Andy Huangf70fc402012-02-17 15:37:42 -0800133 private final MailJsBridge mJsBridge = new MailJsBridge();
134
Andy Huang17a9cde2012-03-09 18:03:16 -0800135 private final WebViewClient mWebViewClient = new ConversationWebViewClient();
136
Andy Huang7bdc3752012-03-25 17:18:19 -0700137 private ConversationViewAdapter mAdapter;
Andy Huang51067132012-03-12 20:08:19 -0700138
139 private boolean mViewsCreated;
Mark Wei4071c2f2012-09-26 14:38:38 -0700140 // True if we attempted to render before the views were laid out
141 // We will render immediately once layout is done
142 private boolean mNeedRender;
Andy Huang51067132012-03-12 20:08:19 -0700143
Andy Huang46dfba62012-04-19 01:47:32 -0700144 /**
145 * Temporary string containing the message bodies of the messages within a super-collapsed
146 * block, for one-time use during block expansion. We cannot easily pass the body HTML
147 * into JS without problematic escaping, so hold onto it momentarily and signal JS to fetch it
148 * using {@link MailJsBridge}.
149 */
150 private String mTempBodiesHtml;
151
Andy Huang632721e2012-04-11 16:57:26 -0700152 private int mMaxAutoLoadMessages;
153
Andy Huang02f9d182012-11-28 22:38:02 -0800154 private int mSideMarginPx;
155
Andy Huang9d3fd922012-09-26 22:23:58 -0700156 /**
157 * If this conversation fragment is not visible, and it's inappropriate to load up front,
158 * this is the reason we are waiting. This flag should be cleared once it's okay to load
159 * the conversation.
160 */
161 private int mLoadWaitReason = LOAD_NOW;
Andy Huang632721e2012-04-11 16:57:26 -0700162
mindyp3bcf1802012-09-09 11:17:00 -0700163 private boolean mEnableContentReadySignal;
Andy Huang28b7aee2012-08-20 20:27:32 -0700164
mindypdde3f9f2012-09-10 17:35:35 -0700165 private ContentSizeChangeListener mWebViewSizeChangeListener;
166
Andy Huange964eee2012-10-02 19:24:58 -0700167 private float mWebViewYPercent;
168
169 /**
170 * Has loadData been called on the WebView yet?
171 */
172 private boolean mWebViewLoadedData;
173
Andy Huang63b3c672012-10-05 19:27:28 -0700174 private long mWebViewLoadStartMs;
175
Andy Huang05c70c82013-03-14 15:15:50 -0700176 private final Map<String, String> mMessageTransforms = Maps.newHashMap();
177
Andy Huang9d3fd922012-09-26 22:23:58 -0700178 private final DataSetObserver mLoadedObserver = new DataSetObserver() {
179 @Override
180 public void onChanged() {
181 getHandler().post(new FragmentRunnable("delayedConversationLoad") {
182 @Override
183 public void go() {
184 LogUtils.d(LOG_TAG, "CVF load observer fired, this=%s",
185 ConversationViewFragment.this);
186 handleDelayedConversationLoad();
187 }
188 });
189 }
190 };
Andy Huangf70fc402012-02-17 15:37:42 -0800191
Andy Huang30bcfe72012-10-18 18:09:03 -0700192 private final Runnable mOnProgressDismiss = new FragmentRunnable("onProgressDismiss") {
Andy Huang7d4746e2012-10-17 17:03:17 -0700193 @Override
194 public void go() {
195 if (isUserVisible()) {
196 onConversationSeen();
197 }
Andy Huang30bcfe72012-10-18 18:09:03 -0700198 mWebView.onRenderComplete();
Andy Huang7d4746e2012-10-17 17:03:17 -0700199 }
200 };
201
Andy Huangbd544e32012-05-29 15:56:51 -0700202 private static final boolean DEBUG_DUMP_CONVERSATION_HTML = false;
Andy Huang47aa9c92012-07-31 15:37:21 -0700203 private static final boolean DISABLE_OFFSCREEN_LOADING = false;
Andy Huang06c03622012-10-22 18:59:45 -0700204 private static final boolean DEBUG_DUMP_CURSOR_CONTENTS = false;
Andy Huange964eee2012-10-02 19:24:58 -0700205
206 private static final String BUNDLE_KEY_WEBVIEW_Y_PERCENT =
207 ConversationViewFragment.class.getName() + "webview-y-percent";
Andy Huangbd544e32012-05-29 15:56:51 -0700208
Vikram Aggarwal6c511582012-02-27 10:59:47 -0800209 /**
210 * Constructor needs to be public to handle orientation changes and activity lifecycle events.
211 */
Andy Huangf70fc402012-02-17 15:37:42 -0800212 public ConversationViewFragment() {
Vikram Aggarwal6c511582012-02-27 10:59:47 -0800213 super();
Mindy Pereira9b875682012-02-15 18:10:54 -0800214 }
215
216 /**
217 * Creates a new instance of {@link ConversationViewFragment}, initialized
Andy Huang632721e2012-04-11 16:57:26 -0700218 * to display a conversation with other parameters inherited/copied from an existing bundle,
219 * typically one created using {@link #makeBasicArgs}.
220 */
221 public static ConversationViewFragment newInstance(Bundle existingArgs,
222 Conversation conversation) {
223 ConversationViewFragment f = new ConversationViewFragment();
224 Bundle args = new Bundle(existingArgs);
225 args.putParcelable(ARG_CONVERSATION, conversation);
226 f.setArguments(args);
227 return f;
228 }
229
mindypf4fce122012-09-14 15:55:33 -0700230 @Override
Andy Huangadbf3e82012-10-13 13:30:19 -0700231 public void onAccountChanged(Account newAccount, Account oldAccount) {
232 // if overview mode has changed, re-render completely (no need to also update headers)
233 if (isOverviewMode(newAccount) != isOverviewMode(oldAccount)) {
234 setupOverviewMode();
235 final MessageCursor c = getMessageCursor();
236 if (c != null) {
237 renderConversation(c);
238 } else {
239 // Null cursor means this fragment is either waiting to load or in the middle of
240 // loading. Either way, a future render will happen anyway, and the new setting
241 // will take effect when that happens.
242 }
243 return;
244 }
245
mindypf4fce122012-09-14 15:55:33 -0700246 // settings may have been updated; refresh views that are known to
247 // depend on settings
mindypf4fce122012-09-14 15:55:33 -0700248 mAdapter.notifyDataSetChanged();
Andy Huang632721e2012-04-11 16:57:26 -0700249 }
250
Mindy Pereira9b875682012-02-15 18:10:54 -0800251 @Override
252 public void onActivityCreated(Bundle savedInstanceState) {
Andy Huang9d3fd922012-09-26 22:23:58 -0700253 LogUtils.d(LOG_TAG, "IN CVF.onActivityCreated, this=%s visible=%s", this, isUserVisible());
Mindy Pereira9b875682012-02-15 18:10:54 -0800254 super.onActivityCreated(savedInstanceState);
Mark Wei1abfcaf2012-09-27 11:11:07 -0700255
256 if (mActivity == null || mActivity.isFinishing()) {
257 // Activity is finishing, just bail.
258 return;
259 }
260
mindypf4fce122012-09-14 15:55:33 -0700261 Context context = getContext();
262 mTemplates = new HtmlConversationTemplates(context);
Andy Huang59e0b182012-08-14 14:32:23 -0700263
mindypf4fce122012-09-14 15:55:33 -0700264 final FormattedDateBuilder dateBuilder = new FormattedDateBuilder(context);
Andy Huang59e0b182012-08-14 14:32:23 -0700265
Paul Westbrook8081df42012-09-10 15:43:36 -0700266 mAdapter = new ConversationViewAdapter(mActivity, this,
mindypf4fce122012-09-14 15:55:33 -0700267 getLoaderManager(), this, getContactInfoSource(), this,
Paul Westbrook8081df42012-09-10 15:43:36 -0700268 this, mAddressCache, dateBuilder);
Andy Huang51067132012-03-12 20:08:19 -0700269 mConversationContainer.setOverlayAdapter(mAdapter);
270
Andy Huang59e0b182012-08-14 14:32:23 -0700271 // set up snap header (the adapter usually does this with the other ones)
272 final MessageHeaderView snapHeader = mConversationContainer.getSnapHeader();
Andy Huangc1fb9a92013-02-11 13:09:12 -0800273 initHeaderView(snapHeader, dateBuilder);
274
Andy Huang632721e2012-04-11 16:57:26 -0700275 mMaxAutoLoadMessages = getResources().getInteger(R.integer.max_auto_load_messages);
276
Andy Huang02f9d182012-11-28 22:38:02 -0800277 mSideMarginPx = getResources().getDimensionPixelOffset(
278 R.dimen.conversation_view_margin_side) + getResources().getDimensionPixelOffset(
279 R.dimen.conversation_message_content_margin_side);
280
mindypf4fce122012-09-14 15:55:33 -0700281 mWebView.setOnCreateContextMenuListener(new WebViewContextMenu(getActivity()));
Andy Huang0b7ed6f2012-07-25 19:23:26 -0700282
Andy Huangadbf3e82012-10-13 13:30:19 -0700283 // set this up here instead of onCreateView to ensure the latest Account is loaded
284 setupOverviewMode();
285
Andy Huang9d3fd922012-09-26 22:23:58 -0700286 // Defer the call to initLoader with a Handler.
287 // We want to wait until we know which fragments are present and their final visibility
288 // states before going off and doing work. This prevents extraneous loading from occurring
289 // as the ViewPager shifts about before the initial position is set.
290 //
291 // e.g. click on item #10
292 // ViewPager.setAdapter() actually first loads #0 and #1 under the assumption that #0 is
293 // the initial primary item
294 // Then CPC immediately sets the primary item to #10, which tears down #0/#1 and sets up
295 // #9/#10/#11.
296 getHandler().post(new FragmentRunnable("showConversation") {
297 @Override
298 public void go() {
299 showConversation();
300 }
301 });
Paul Westbrookcebcc642012-08-08 10:06:04 -0700302
303 if (mConversation.conversationBaseUri != null &&
Paul Westbrookb8361c92012-09-27 10:57:14 -0700304 !Utils.isEmpty(mAccount.accoutCookieQueryUri)) {
Paul Westbrookcebcc642012-08-08 10:06:04 -0700305 // Set the cookie for this base url
Paul Westbrookb8361c92012-09-27 10:57:14 -0700306 new SetCookieTask(getContext(), mConversation.conversationBaseUri,
307 mAccount.accoutCookieQueryUri).execute();
Paul Westbrookcebcc642012-08-08 10:06:04 -0700308 }
Mindy Pereira9b875682012-02-15 18:10:54 -0800309 }
310
Andy Huangc1fb9a92013-02-11 13:09:12 -0800311 private void initHeaderView(MessageHeaderView headerView, FormattedDateBuilder dateBuilder) {
312 headerView.initialize(dateBuilder, this, mAddressCache);
313 headerView.setCallbacks(this);
314 headerView.setContactInfoSource(getContactInfoSource());
315 headerView.setVeiledMatcher(mActivity.getAccountController().getVeiledAddressMatcher());
316 }
317
Mindy Pereira9b875682012-02-15 18:10:54 -0800318 @Override
Andy Huange964eee2012-10-02 19:24:58 -0700319 public void onCreate(Bundle savedState) {
320 super.onCreate(savedState);
321
322 if (savedState != null) {
323 mWebViewYPercent = savedState.getFloat(BUNDLE_KEY_WEBVIEW_Y_PERCENT);
324 }
325 }
326
327 @Override
Mindy Pereira9b875682012-02-15 18:10:54 -0800328 public View onCreateView(LayoutInflater inflater,
329 ViewGroup container, Bundle savedInstanceState) {
Andy Huang839ada22012-07-20 15:48:40 -0700330
Andy Huang632721e2012-04-11 16:57:26 -0700331 View rootView = inflater.inflate(R.layout.conversation_view, container, false);
Andy Huangf70fc402012-02-17 15:37:42 -0800332 mConversationContainer = (ConversationContainer) rootView
333 .findViewById(R.id.conversation_container);
Andy Huang8f187782012-11-06 17:49:25 -0800334 mConversationContainer.setAccountController(this);
Andy Huang47aa9c92012-07-31 15:37:21 -0700335
336 mNewMessageBar = mConversationContainer.findViewById(R.id.new_message_notification_bar);
337 mNewMessageBar.setOnClickListener(new View.OnClickListener() {
338 @Override
339 public void onClick(View v) {
340 onNewMessageBarClick();
341 }
342 });
343
mindypff282d02012-09-17 10:33:02 -0700344 instantiateProgressIndicators(rootView);
mindyp3bcf1802012-09-09 11:17:00 -0700345
Andy Huang5ff63742012-03-16 20:30:23 -0700346 mWebView = (ConversationWebView) mConversationContainer.findViewById(R.id.webview);
Andy Huangf70fc402012-02-17 15:37:42 -0800347
Andy Huangf70fc402012-02-17 15:37:42 -0800348 mWebView.addJavascriptInterface(mJsBridge, "mail");
mindyp3bcf1802012-09-09 11:17:00 -0700349 // On JB or newer, we use the 'webkitAnimationStart' DOM event to signal load complete
350 // Below JB, try to speed up initial render by having the webview do supplemental draws to
351 // custom a software canvas.
mindypb941fdb2012-09-11 08:28:23 -0700352 // TODO(mindyp):
353 //PAGE READINESS SIGNAL FOR JELLYBEAN AND NEWER
354 // Notify the app on 'webkitAnimationStart' of a simple dummy element with a simple no-op
355 // animation that immediately runs on page load. The app uses this as a signal that the
356 // content is loaded and ready to draw, since WebView delays firing this event until the
357 // layers are composited and everything is ready to draw.
358 // This signal does not seem to be reliable, so just use the old method for now.
mindyp32d911f2012-09-24 15:14:22 -0700359 mEnableContentReadySignal = Utils.isRunningJellybeanOrLater();
mindypafc9b362012-09-25 09:20:47 -0700360 mWebView.setUseSoftwareLayer(!mEnableContentReadySignal);
Andy Huang30bcfe72012-10-18 18:09:03 -0700361 mWebView.onUserVisibilityChanged(isUserVisible());
Andy Huang17a9cde2012-03-09 18:03:16 -0800362 mWebView.setWebViewClient(mWebViewClient);
Andy Huangc1fb9a92013-02-11 13:09:12 -0800363 final WebChromeClient wcc = new WebChromeClient() {
Andy Huangf70fc402012-02-17 15:37:42 -0800364 @Override
365 public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Andy Huang5ea5a832013-03-07 16:49:09 -0800366 LogUtils.i(LOG_TAG, "JS: %s (%s:%d) f=%s", consoleMessage.message(),
367 consoleMessage.sourceId(), consoleMessage.lineNumber(),
368 ConversationViewFragment.this);
Andy Huangf70fc402012-02-17 15:37:42 -0800369 return true;
370 }
Andy Huangc1fb9a92013-02-11 13:09:12 -0800371 };
372 mWebView.setWebChromeClient(wcc);
Andy Huangf70fc402012-02-17 15:37:42 -0800373
Andy Huang3233bff2012-03-20 19:38:45 -0700374 final WebSettings settings = mWebView.getSettings();
Andy Huangf70fc402012-02-17 15:37:42 -0800375
Mark Wei56d83852012-09-19 14:28:50 -0700376 mScrollIndicators = (ScrollIndicatorsView) rootView.findViewById(R.id.scroll_indicators);
377 mScrollIndicators.setSourceView(mWebView);
378
Andy Huangf70fc402012-02-17 15:37:42 -0800379 settings.setJavaScriptEnabled(true);
Andy Huangf70fc402012-02-17 15:37:42 -0800380
Andy Huangc319b552012-04-25 19:53:50 -0700381 final float fontScale = getResources().getConfiguration().fontScale;
Andy Huangba283732012-06-25 19:14:10 -0700382 final int desiredFontSizePx = getResources()
383 .getInteger(R.integer.conversation_desired_font_size_px);
384 final int unstyledFontSizePx = getResources()
385 .getInteger(R.integer.conversation_unstyled_font_size_px);
Andy Huangc319b552012-04-25 19:53:50 -0700386
Andy Huangba283732012-06-25 19:14:10 -0700387 int textZoom = settings.getTextZoom();
388 // apply a correction to the default body text style to get regular text to the size we want
389 textZoom = textZoom * desiredFontSizePx / unstyledFontSizePx;
390 // then apply any system font scaling
Andy Huangc319b552012-04-25 19:53:50 -0700391 textZoom = (int) (textZoom * fontScale);
392 settings.setTextZoom(textZoom);
393
Andy Huang51067132012-03-12 20:08:19 -0700394 mViewsCreated = true;
Andy Huange964eee2012-10-02 19:24:58 -0700395 mWebViewLoadedData = false;
Andy Huang51067132012-03-12 20:08:19 -0700396
Mindy Pereira9b875682012-02-15 18:10:54 -0800397 return rootView;
398 }
399
400 @Override
401 public void onDestroyView() {
Mindy Pereira9b875682012-02-15 18:10:54 -0800402 super.onDestroyView();
Andy Huang46dfba62012-04-19 01:47:32 -0700403 mConversationContainer.setOverlayAdapter(null);
404 mAdapter = null;
Andy Huang9d3fd922012-09-26 22:23:58 -0700405 resetLoadWaiting(); // be sure to unregister any active load observer
Andy Huang51067132012-03-12 20:08:19 -0700406 mViewsCreated = false;
Mindy Pereira9b875682012-02-15 18:10:54 -0800407 }
408
Andy Huange964eee2012-10-02 19:24:58 -0700409 @Override
Scott Kennedyfafcd172012-11-01 17:23:33 -0700410 protected WebView getWebView() {
411 return mWebView;
412 }
413
414 @Override
Andy Huange964eee2012-10-02 19:24:58 -0700415 public void onSaveInstanceState(Bundle outState) {
416 super.onSaveInstanceState(outState);
417
418 outState.putFloat(BUNDLE_KEY_WEBVIEW_Y_PERCENT, calculateScrollYPercent());
419 }
420
421 private float calculateScrollYPercent() {
Paul Westbrook1b56a672013-04-19 01:19:05 -0700422 final float p;
423 if (mWebView == null) {
424 // onCreateView hasn't been called, return 0 as the user hasn't scrolled the view.
425 return 0;
426 }
427
428 final int scrollY = mWebView.getScrollY();
429 final int viewH = mWebView.getHeight();
430 final int webH = (int) (mWebView.getContentHeight() * mWebView.getScale());
Andy Huange964eee2012-10-02 19:24:58 -0700431
432 if (webH == 0 || webH <= viewH) {
433 p = 0;
434 } else if (scrollY + viewH >= webH) {
435 // The very bottom is a special case, it acts as a stronger anchor than the scroll top
436 // at that point.
437 p = 1.0f;
438 } else {
439 p = (float) scrollY / webH;
440 }
441 return p;
442 }
443
Andy Huang9d3fd922012-09-26 22:23:58 -0700444 private void resetLoadWaiting() {
445 if (mLoadWaitReason == LOAD_WAIT_FOR_INITIAL_CONVERSATION) {
446 getListController().unregisterConversationLoadedObserver(mLoadedObserver);
447 }
448 mLoadWaitReason = LOAD_NOW;
449 }
450
Andy Huang5ff63742012-03-16 20:30:23 -0700451 @Override
mindypf4fce122012-09-14 15:55:33 -0700452 protected void markUnread() {
Vikram Aggarwald82a31f2013-02-05 15:03:00 -0800453 super.markUnread();
Andy Huang839ada22012-07-20 15:48:40 -0700454 // Ignore unsafe calls made after a fragment is detached from an activity
455 final ControllableActivity activity = (ControllableActivity) getActivity();
456 if (activity == null) {
457 LogUtils.w(LOG_TAG, "ignoring markUnread for conv=%s", mConversation.id);
458 return;
459 }
460
Andy Huang28e31e22012-07-26 16:33:15 -0700461 if (mViewState == null) {
462 LogUtils.i(LOG_TAG, "ignoring markUnread for conv with no view state (%d)",
463 mConversation.id);
464 return;
465 }
Andy Huang839ada22012-07-20 15:48:40 -0700466 activity.getConversationUpdater().markConversationMessagesUnread(mConversation,
Vikram Aggarwal4a878b62012-07-31 15:09:25 -0700467 mViewState.getUnreadMessageUris(), mViewState.getConversationInfo());
Andy Huang839ada22012-07-20 15:48:40 -0700468 }
469
mindypf4fce122012-09-14 15:55:33 -0700470 @Override
471 public void onUserVisibleHintChanged() {
Andy Huang9d3fd922012-09-26 22:23:58 -0700472 final boolean userVisible = isUserVisible();
473
474 if (!userVisible) {
mindyp32d911f2012-09-24 15:14:22 -0700475 dismissLoadingStatus();
Andy Huang9d3fd922012-09-26 22:23:58 -0700476 } else if (mViewsCreated) {
477 if (getMessageCursor() != null) {
478 LogUtils.d(LOG_TAG, "Fragment is now user-visible, onConversationSeen: %s", this);
479 onConversationSeen();
480 } else if (isLoadWaiting()) {
481 LogUtils.d(LOG_TAG, "Fragment is now user-visible, showing conversation: %s", this);
482 handleDelayedConversationLoad();
483 }
Andy Huang632721e2012-04-11 16:57:26 -0700484 }
Andy Huang632721e2012-04-11 16:57:26 -0700485
Andy Huang30bcfe72012-10-18 18:09:03 -0700486 if (mWebView != null) {
487 mWebView.onUserVisibilityChanged(userVisible);
488 }
Andy Huangf8cf5462012-10-17 18:29:14 -0700489 }
490
Andy Huang9d3fd922012-09-26 22:23:58 -0700491 /**
492 * Will either call initLoader now to begin loading, or set {@link #mLoadWaitReason} and do
493 * nothing (in which case you should later call {@link #handleDelayedConversationLoad()}).
494 */
Mindy Pereira9b875682012-02-15 18:10:54 -0800495 private void showConversation() {
Andy Huang9d3fd922012-09-26 22:23:58 -0700496 final int reason;
497
498 if (isUserVisible()) {
499 LogUtils.i(LOG_TAG,
500 "SHOWCONV: CVF is user-visible, immediately loading conversation (%s)", this);
501 reason = LOAD_NOW;
Andy Huang243c2362013-03-01 17:50:35 -0800502 timerMark("CVF.showConversation");
Andy Huang9d3fd922012-09-26 22:23:58 -0700503 } else {
504 final boolean disableOffscreenLoading = DISABLE_OFFSCREEN_LOADING
505 || (mConversation.isRemote
506 || mConversation.getNumMessages() > mMaxAutoLoadMessages);
507
508 // When not visible, we should not immediately load if either this conversation is
509 // too heavyweight, or if the main/initial conversation is busy loading.
510 if (disableOffscreenLoading) {
511 reason = LOAD_WAIT_UNTIL_VISIBLE;
512 LogUtils.i(LOG_TAG, "SHOWCONV: CVF waiting until visible to load (%s)", this);
513 } else if (getListController().isInitialConversationLoading()) {
514 reason = LOAD_WAIT_FOR_INITIAL_CONVERSATION;
515 LogUtils.i(LOG_TAG, "SHOWCONV: CVF waiting for initial to finish (%s)", this);
516 getListController().registerConversationLoadedObserver(mLoadedObserver);
517 } else {
518 LogUtils.i(LOG_TAG,
519 "SHOWCONV: CVF is not visible, but no reason to wait. loading now. (%s)",
520 this);
521 reason = LOAD_NOW;
522 }
Andy Huang632721e2012-04-11 16:57:26 -0700523 }
Andy Huang9d3fd922012-09-26 22:23:58 -0700524
525 mLoadWaitReason = reason;
526 if (mLoadWaitReason == LOAD_NOW) {
527 startConversationLoad();
528 }
529 }
530
531 private void handleDelayedConversationLoad() {
532 resetLoadWaiting();
533 startConversationLoad();
534 }
535
536 private void startConversationLoad() {
mindyp3bcf1802012-09-09 11:17:00 -0700537 mWebView.setVisibility(View.VISIBLE);
mindypf4fce122012-09-14 15:55:33 -0700538 getLoaderManager().initLoader(MESSAGE_LOADER, Bundle.EMPTY, getMessageLoaderCallbacks());
mindyp3bcf1802012-09-09 11:17:00 -0700539 // TODO(mindyp): don't show loading status for a previously rendered
540 // conversation. Ielieve this is better done by making sure don't show loading status
541 // until XX ms have passed without loading completed.
542 showLoadingStatus();
Mindy Pereira8e915722012-02-16 14:42:56 -0800543 }
544
Andy Huang7d4746e2012-10-17 17:03:17 -0700545 private void revealConversation() {
Andy Huang243c2362013-03-01 17:50:35 -0800546 timerMark("revealing conversation");
Andy Huang30bcfe72012-10-18 18:09:03 -0700547 dismissLoadingStatus(mOnProgressDismiss);
Andy Huang7d4746e2012-10-17 17:03:17 -0700548 }
549
Andy Huang9d3fd922012-09-26 22:23:58 -0700550 private boolean isLoadWaiting() {
551 return mLoadWaitReason != LOAD_NOW;
552 }
553
Andy Huang51067132012-03-12 20:08:19 -0700554 private void renderConversation(MessageCursor messageCursor) {
mindyp3bcf1802012-09-09 11:17:00 -0700555 final String convHtml = renderMessageBodies(messageCursor, mEnableContentReadySignal);
Andy Huang243c2362013-03-01 17:50:35 -0800556 timerMark("rendered conversation");
Andy Huangbd544e32012-05-29 15:56:51 -0700557
558 if (DEBUG_DUMP_CONVERSATION_HTML) {
559 java.io.FileWriter fw = null;
560 try {
561 fw = new java.io.FileWriter("/sdcard/conv" + mConversation.id
562 + ".html");
563 fw.write(convHtml);
564 } catch (java.io.IOException e) {
565 e.printStackTrace();
566 } finally {
567 if (fw != null) {
568 try {
569 fw.close();
570 } catch (java.io.IOException e) {
571 e.printStackTrace();
572 }
573 }
574 }
575 }
576
Andy Huange964eee2012-10-02 19:24:58 -0700577 // save off existing scroll position before re-rendering
578 if (mWebViewLoadedData) {
579 mWebViewYPercent = calculateScrollYPercent();
580 }
581
Andy Huangbd544e32012-05-29 15:56:51 -0700582 mWebView.loadDataWithBaseURL(mBaseUri, convHtml, "text/html", "utf-8", null);
Andy Huange964eee2012-10-02 19:24:58 -0700583 mWebViewLoadedData = true;
Andy Huang63b3c672012-10-05 19:27:28 -0700584 mWebViewLoadStartMs = SystemClock.uptimeMillis();
Andy Huang51067132012-03-12 20:08:19 -0700585 }
586
Andy Huang7bdc3752012-03-25 17:18:19 -0700587 /**
588 * Populate the adapter with overlay views (message headers, super-collapsed blocks, a
589 * conversation header), and return an HTML document with spacer divs inserted for all overlays.
590 *
591 */
mindyp3bcf1802012-09-09 11:17:00 -0700592 private String renderMessageBodies(MessageCursor messageCursor,
593 boolean enableContentReadySignal) {
Andy Huangf70fc402012-02-17 15:37:42 -0800594 int pos = -1;
Andy Huang632721e2012-04-11 16:57:26 -0700595
Andy Huang1ee96b22012-08-24 20:19:53 -0700596 LogUtils.d(LOG_TAG, "IN renderMessageBodies, fragment=%s", this);
Andy Huang7bdc3752012-03-25 17:18:19 -0700597 boolean allowNetworkImages = false;
598
Andy Huangc7543572012-04-03 15:34:29 -0700599 // TODO: re-use any existing adapter item state (expanded, details expanded, show pics)
Andy Huang28b7aee2012-08-20 20:27:32 -0700600
Andy Huang7bdc3752012-03-25 17:18:19 -0700601 // Walk through the cursor and build up an overlay adapter as you go.
602 // Each overlay has an entry in the adapter for easy scroll handling in the container.
603 // Items are not necessarily 1:1 in cursor and adapter because of super-collapsed blocks.
604 // When adding adapter items, also add their heights to help the container later determine
605 // overlay dimensions.
606
Andy Huangdb620fe2012-08-24 15:45:28 -0700607 // When re-rendering, prevent ConversationContainer from laying out overlays until after
608 // the new spacers are positioned by WebView.
609 mConversationContainer.invalidateSpacerGeometry();
610
Andy Huang7bdc3752012-03-25 17:18:19 -0700611 mAdapter.clear();
612
Andy Huang47aa9c92012-07-31 15:37:21 -0700613 // re-evaluate the message parts of the view state, since the messages may have changed
614 // since the previous render
615 final ConversationViewState prevState = mViewState;
616 mViewState = new ConversationViewState(prevState);
617
Andy Huang5ff63742012-03-16 20:30:23 -0700618 // N.B. the units of height for spacers are actually dp and not px because WebView assumes
Andy Huang2e9acfe2012-03-15 22:39:36 -0700619 // a pixel is an mdpi pixel, unless you set device-dpi.
Andy Huang5ff63742012-03-16 20:30:23 -0700620
Andy Huang7bdc3752012-03-25 17:18:19 -0700621 // add a single conversation header item
622 final int convHeaderPos = mAdapter.addConversationHeader(mConversation);
Andy Huang23014702012-07-09 12:50:36 -0700623 final int convHeaderPx = measureOverlayHeight(convHeaderPos);
Andy Huang5ff63742012-03-16 20:30:23 -0700624
Andy Huang02f9d182012-11-28 22:38:02 -0800625 mTemplates.startConversation(mWebView.screenPxToWebPx(mSideMarginPx),
Andy Huang256b35c2012-08-22 15:19:13 -0700626 mWebView.screenPxToWebPx(convHeaderPx));
Andy Huang3233bff2012-03-20 19:38:45 -0700627
Andy Huang46dfba62012-04-19 01:47:32 -0700628 int collapsedStart = -1;
Andy Huang839ada22012-07-20 15:48:40 -0700629 ConversationMessage prevCollapsedMsg = null;
Andy Huang46dfba62012-04-19 01:47:32 -0700630 boolean prevSafeForImages = false;
631
Andy Huangf70fc402012-02-17 15:37:42 -0800632 while (messageCursor.moveToPosition(++pos)) {
Andy Huang839ada22012-07-20 15:48:40 -0700633 final ConversationMessage msg = messageCursor.getMessage();
Andy Huang46dfba62012-04-19 01:47:32 -0700634
Scott Kennedy20273842012-11-07 11:16:21 -0800635 final boolean safeForImages =
636 msg.alwaysShowImages || prevState.getShouldShowImages(msg);
Andy Huang3233bff2012-03-20 19:38:45 -0700637 allowNetworkImages |= safeForImages;
Andy Huang24055282012-03-27 17:37:06 -0700638
Paul Westbrook08098ec2012-08-12 15:30:28 -0700639 final Integer savedExpanded = prevState.getExpansionState(msg);
640 final int expandedState;
Andy Huang839ada22012-07-20 15:48:40 -0700641 if (savedExpanded != null) {
Andy Huang1ee96b22012-08-24 20:19:53 -0700642 if (ExpansionState.isSuperCollapsed(savedExpanded) && messageCursor.isLast()) {
643 // override saved state when this is now the new last message
644 // this happens to the second-to-last message when you discard a draft
645 expandedState = ExpansionState.EXPANDED;
646 } else {
647 expandedState = savedExpanded;
648 }
Andy Huang839ada22012-07-20 15:48:40 -0700649 } else {
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700650 // new messages that are not expanded default to being eligible for super-collapse
Paul Westbrook08098ec2012-08-12 15:30:28 -0700651 expandedState = (!msg.read || msg.starred || messageCursor.isLast()) ?
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700652 ExpansionState.EXPANDED : ExpansionState.SUPER_COLLAPSED;
Andy Huang839ada22012-07-20 15:48:40 -0700653 }
Scott Kennedy20273842012-11-07 11:16:21 -0800654 mViewState.setShouldShowImages(msg, prevState.getShouldShowImages(msg));
Paul Westbrook08098ec2012-08-12 15:30:28 -0700655 mViewState.setExpansionState(msg, expandedState);
Andy Huangc7543572012-04-03 15:34:29 -0700656
Andy Huang839ada22012-07-20 15:48:40 -0700657 // save off "read" state from the cursor
658 // later, the view may not match the cursor (e.g. conversation marked read on open)
Andy Huang423bea22012-08-21 12:00:49 -0700659 // however, if a previous state indicated this message was unread, trust that instead
660 // so "mark unread" marks all originally unread messages
661 mViewState.setReadState(msg, msg.read && !prevState.isUnread(msg));
Andy Huang839ada22012-07-20 15:48:40 -0700662
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700663 // We only want to consider this for inclusion in the super collapsed block if
664 // 1) The we don't have previous state about this message (The first time that the
665 // user opens a conversation)
666 // 2) The previously saved state for this message indicates that this message is
667 // in the super collapsed block.
668 if (ExpansionState.isSuperCollapsed(expandedState)) {
669 // contribute to a super-collapsed block that will be emitted just before the
670 // next expanded header
671 if (collapsedStart < 0) {
672 collapsedStart = pos;
Andy Huang46dfba62012-04-19 01:47:32 -0700673 }
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700674 prevCollapsedMsg = msg;
675 prevSafeForImages = safeForImages;
676 continue;
Andy Huang46dfba62012-04-19 01:47:32 -0700677 }
Andy Huang24055282012-03-27 17:37:06 -0700678
Andy Huang46dfba62012-04-19 01:47:32 -0700679 // resolve any deferred decisions on previous collapsed items
680 if (collapsedStart >= 0) {
681 if (pos - collapsedStart == 1) {
682 // special-case for a single collapsed message: no need to super-collapse it
683 renderMessage(prevCollapsedMsg, false /* expanded */,
684 prevSafeForImages);
685 } else {
686 renderSuperCollapsedBlock(collapsedStart, pos - 1);
687 }
688 prevCollapsedMsg = null;
689 collapsedStart = -1;
690 }
Andy Huang7bdc3752012-03-25 17:18:19 -0700691
Paul Westbrook08098ec2012-08-12 15:30:28 -0700692 renderMessage(msg, ExpansionState.isExpanded(expandedState), safeForImages);
Mindy Pereira9b875682012-02-15 18:10:54 -0800693 }
Andy Huang3233bff2012-03-20 19:38:45 -0700694
695 mWebView.getSettings().setBlockNetworkImage(!allowNetworkImages);
696
Andrew Sapperstein2fc67302013-04-29 18:24:56 -0700697 final boolean applyTransforms = shouldApplyTransforms();
Andy Huang57f354c2013-04-11 17:23:40 -0700698
Andy Huang0180f272013-03-08 18:33:22 -0800699 final MailPrefs prefs = MailPrefs.get(getContext());
Andrew Sapperstein2fc67302013-04-29 18:24:56 -0700700
Andy Huangc1fb9a92013-02-11 13:09:12 -0800701 // If the conversation has specified a base uri, use it here, otherwise use mBaseUri
702 return mTemplates.endConversation(mBaseUri, mConversation.getBaseUri(mBaseUri), 320,
Andy Huang5ea5a832013-03-07 16:49:09 -0800703 mWebView.getViewportWidth(), enableContentReadySignal, isOverviewMode(mAccount),
Andy Huang57f354c2013-04-11 17:23:40 -0700704 applyTransforms, applyTransforms);
Mindy Pereira9b875682012-02-15 18:10:54 -0800705 }
Mindy Pereira674afa42012-02-17 14:05:24 -0800706
Andy Huang46dfba62012-04-19 01:47:32 -0700707 private void renderSuperCollapsedBlock(int start, int end) {
708 final int blockPos = mAdapter.addSuperCollapsedBlock(start, end);
Andy Huang23014702012-07-09 12:50:36 -0700709 final int blockPx = measureOverlayHeight(blockPos);
710 mTemplates.appendSuperCollapsedHtml(start, mWebView.screenPxToWebPx(blockPx));
Andy Huang46dfba62012-04-19 01:47:32 -0700711 }
712
Andy Huang839ada22012-07-20 15:48:40 -0700713 private void renderMessage(ConversationMessage msg, boolean expanded,
714 boolean safeForImages) {
Scott Kennedy20273842012-11-07 11:16:21 -0800715 final int headerPos = mAdapter.addMessageHeader(msg, expanded,
716 mViewState.getShouldShowImages(msg));
Andy Huang46dfba62012-04-19 01:47:32 -0700717 final MessageHeaderItem headerItem = (MessageHeaderItem) mAdapter.getItem(headerPos);
718
719 final int footerPos = mAdapter.addMessageFooter(headerItem);
720
721 // Measure item header and footer heights to allocate spacers in HTML
722 // But since the views themselves don't exist yet, render each item temporarily into
723 // a host view for measurement.
Andy Huang23014702012-07-09 12:50:36 -0700724 final int headerPx = measureOverlayHeight(headerPos);
725 final int footerPx = measureOverlayHeight(footerPos);
Andy Huang46dfba62012-04-19 01:47:32 -0700726
Andy Huang256b35c2012-08-22 15:19:13 -0700727 mTemplates.appendMessageHtml(msg, expanded, safeForImages,
Andy Huang23014702012-07-09 12:50:36 -0700728 mWebView.screenPxToWebPx(headerPx), mWebView.screenPxToWebPx(footerPx));
Andy Huang243c2362013-03-01 17:50:35 -0800729 timerMark("rendered message");
Andy Huang46dfba62012-04-19 01:47:32 -0700730 }
731
732 private String renderCollapsedHeaders(MessageCursor cursor,
733 SuperCollapsedBlockItem blockToReplace) {
734 final List<ConversationOverlayItem> replacements = Lists.newArrayList();
735
736 mTemplates.reset();
737
Mark Wei2b24e992012-09-10 16:40:07 -0700738 // In devices with non-integral density multiplier, screen pixels translate to non-integral
739 // web pixels. Keep track of the error that occurs when we cast all heights to int
740 float error = 0f;
Andy Huang46dfba62012-04-19 01:47:32 -0700741 for (int i = blockToReplace.getStart(), end = blockToReplace.getEnd(); i <= end; i++) {
742 cursor.moveToPosition(i);
Andy Huang839ada22012-07-20 15:48:40 -0700743 final ConversationMessage msg = cursor.getMessage();
Andy Huang46dfba62012-04-19 01:47:32 -0700744 final MessageHeaderItem header = mAdapter.newMessageHeaderItem(msg,
Scott Kennedy20273842012-11-07 11:16:21 -0800745 false /* expanded */, mViewState.getShouldShowImages(msg));
Andy Huang46dfba62012-04-19 01:47:32 -0700746 final MessageFooterItem footer = mAdapter.newMessageFooterItem(header);
747
Andy Huang23014702012-07-09 12:50:36 -0700748 final int headerPx = measureOverlayHeight(header);
749 final int footerPx = measureOverlayHeight(footer);
Mark Wei2b24e992012-09-10 16:40:07 -0700750 error += mWebView.screenPxToWebPxError(headerPx)
751 + mWebView.screenPxToWebPxError(footerPx);
752
753 // When the error becomes greater than 1 pixel, make the next header 1 pixel taller
754 int correction = 0;
755 if (error >= 1) {
756 correction = 1;
757 error -= 1;
758 }
Andy Huang46dfba62012-04-19 01:47:32 -0700759
Andy Huang256b35c2012-08-22 15:19:13 -0700760 mTemplates.appendMessageHtml(msg, false /* expanded */, msg.alwaysShowImages,
Mark Wei2b24e992012-09-10 16:40:07 -0700761 mWebView.screenPxToWebPx(headerPx) + correction,
762 mWebView.screenPxToWebPx(footerPx));
Andy Huang46dfba62012-04-19 01:47:32 -0700763 replacements.add(header);
764 replacements.add(footer);
Andy Huang839ada22012-07-20 15:48:40 -0700765
Paul Westbrook08098ec2012-08-12 15:30:28 -0700766 mViewState.setExpansionState(msg, ExpansionState.COLLAPSED);
Andy Huang46dfba62012-04-19 01:47:32 -0700767 }
768
769 mAdapter.replaceSuperCollapsedBlock(blockToReplace, replacements);
Andy Huang06c03622012-10-22 18:59:45 -0700770 mAdapter.notifyDataSetChanged();
Andy Huang46dfba62012-04-19 01:47:32 -0700771
772 return mTemplates.emit();
773 }
774
775 private int measureOverlayHeight(int position) {
776 return measureOverlayHeight(mAdapter.getItem(position));
777 }
778
Andy Huang7bdc3752012-03-25 17:18:19 -0700779 /**
Andy Huangb8331b42012-07-16 19:08:53 -0700780 * Measure the height of an adapter view by rendering an adapter item into a temporary
Andy Huang46dfba62012-04-19 01:47:32 -0700781 * host view, and asking the view to immediately measure itself. This method will reuse
Andy Huang7bdc3752012-03-25 17:18:19 -0700782 * a previous adapter view from {@link ConversationContainer}'s scrap views if one was generated
783 * earlier.
784 * <p>
Andy Huang46dfba62012-04-19 01:47:32 -0700785 * After measuring the height, this method also saves the height in the
786 * {@link ConversationOverlayItem} for later use in overlay positioning.
Andy Huang7bdc3752012-03-25 17:18:19 -0700787 *
Andy Huang46dfba62012-04-19 01:47:32 -0700788 * @param convItem adapter item with data to render and measure
Andy Huang23014702012-07-09 12:50:36 -0700789 * @return height of the rendered view in screen px
Andy Huang7bdc3752012-03-25 17:18:19 -0700790 */
Andy Huang46dfba62012-04-19 01:47:32 -0700791 private int measureOverlayHeight(ConversationOverlayItem convItem) {
Andy Huang7bdc3752012-03-25 17:18:19 -0700792 final int type = convItem.getType();
793
794 final View convertView = mConversationContainer.getScrapView(type);
Andy Huangb8331b42012-07-16 19:08:53 -0700795 final View hostView = mAdapter.getView(convItem, convertView, mConversationContainer,
796 true /* measureOnly */);
Andy Huang7bdc3752012-03-25 17:18:19 -0700797 if (convertView == null) {
798 mConversationContainer.addScrapView(type, hostView);
799 }
800
Andy Huang9875bb42012-04-04 20:36:21 -0700801 final int heightPx = mConversationContainer.measureOverlay(hostView);
Andy Huang7bdc3752012-03-25 17:18:19 -0700802 convItem.setHeight(heightPx);
Andy Huang9875bb42012-04-04 20:36:21 -0700803 convItem.markMeasurementValid();
Andy Huang7bdc3752012-03-25 17:18:19 -0700804
Andy Huang23014702012-07-09 12:50:36 -0700805 return heightPx;
Andy Huang7bdc3752012-03-25 17:18:19 -0700806 }
807
Andy Huang5ff63742012-03-16 20:30:23 -0700808 @Override
809 public void onConversationViewHeaderHeightChange(int newHeight) {
Mark Weiab2d9982012-09-25 13:06:17 -0700810 final int h = mWebView.screenPxToWebPx(newHeight);
811
812 mWebView.loadUrl(String.format("javascript:setConversationHeaderSpacerHeight(%s);", h));
Andy Huang5ff63742012-03-16 20:30:23 -0700813 }
814
Andy Huang3233bff2012-03-20 19:38:45 -0700815 // END conversation header callbacks
816
817 // START message header callbacks
818 @Override
Andy Huangc7543572012-04-03 15:34:29 -0700819 public void setMessageSpacerHeight(MessageHeaderItem item, int newSpacerHeightPx) {
820 mConversationContainer.invalidateSpacerGeometry();
821
822 // update message HTML spacer height
Andy Huang23014702012-07-09 12:50:36 -0700823 final int h = mWebView.screenPxToWebPx(newSpacerHeightPx);
824 LogUtils.i(LAYOUT_TAG, "setting HTML spacer h=%dwebPx (%dscreenPx)", h,
825 newSpacerHeightPx);
Vikram Aggarwal5349ce12012-09-24 14:12:40 -0700826 mWebView.loadUrl(String.format("javascript:setMessageHeaderSpacerHeight('%s', %s);",
Andy Huang014ea4c2012-09-25 14:50:54 -0700827 mTemplates.getMessageDomId(item.getMessage()), h));
Andy Huang3233bff2012-03-20 19:38:45 -0700828 }
829
830 @Override
Andy Huangc7543572012-04-03 15:34:29 -0700831 public void setMessageExpanded(MessageHeaderItem item, int newSpacerHeightPx) {
832 mConversationContainer.invalidateSpacerGeometry();
833
834 // show/hide the HTML message body and update the spacer height
Andy Huang23014702012-07-09 12:50:36 -0700835 final int h = mWebView.screenPxToWebPx(newSpacerHeightPx);
836 LogUtils.i(LAYOUT_TAG, "setting HTML spacer expanded=%s h=%dwebPx (%dscreenPx)",
837 item.isExpanded(), h, newSpacerHeightPx);
Vikram Aggarwal5349ce12012-09-24 14:12:40 -0700838 mWebView.loadUrl(String.format("javascript:setMessageBodyVisible('%s', %s, %s);",
Andy Huang014ea4c2012-09-25 14:50:54 -0700839 mTemplates.getMessageDomId(item.getMessage()), item.isExpanded(), h));
Andy Huang839ada22012-07-20 15:48:40 -0700840
Andy Huang014ea4c2012-09-25 14:50:54 -0700841 mViewState.setExpansionState(item.getMessage(),
Paul Westbrook08098ec2012-08-12 15:30:28 -0700842 item.isExpanded() ? ExpansionState.EXPANDED : ExpansionState.COLLAPSED);
Andy Huang3233bff2012-03-20 19:38:45 -0700843 }
844
845 @Override
Scott Kennedyeb9a4bd2012-11-12 10:33:04 -0800846 public void showExternalResources(final Message msg) {
Scott Kennedy20273842012-11-07 11:16:21 -0800847 mViewState.setShouldShowImages(msg, true);
Andy Huang3233bff2012-03-20 19:38:45 -0700848 mWebView.getSettings().setBlockNetworkImage(false);
Scott Kennedyeb9a4bd2012-11-12 10:33:04 -0800849 mWebView.loadUrl("javascript:unblockImages(['" + mTemplates.getMessageDomId(msg) + "']);");
850 }
851
852 @Override
853 public void showExternalResources(final String senderRawAddress) {
854 mWebView.getSettings().setBlockNetworkImage(false);
855
856 final Address sender = getAddress(senderRawAddress);
857 final MessageCursor cursor = getMessageCursor();
858
859 final List<String> messageDomIds = new ArrayList<String>();
860
861 int pos = -1;
862 while (cursor.moveToPosition(++pos)) {
863 final ConversationMessage message = cursor.getMessage();
864 if (sender.equals(getAddress(message.getFrom()))) {
865 message.alwaysShowImages = true;
866
867 mViewState.setShouldShowImages(message, true);
868 messageDomIds.add(mTemplates.getMessageDomId(message));
869 }
870 }
871
872 final String url = String.format(
873 "javascript:unblockImages(['%s']);", TextUtils.join("','", messageDomIds));
874 mWebView.loadUrl(url);
Andy Huang3233bff2012-03-20 19:38:45 -0700875 }
Alice Yang1ebc2db2013-03-14 21:21:44 -0700876
877 @Override
Andy Huang75b52a52013-03-15 15:40:24 -0700878 public boolean supportsMessageTransforms() {
879 return true;
880 }
881
882 @Override
Alice Yang1ebc2db2013-03-14 21:21:44 -0700883 public String getMessageTransforms(final Message msg) {
884 final String domId = mTemplates.getMessageDomId(msg);
885 return (domId == null) ? null : mMessageTransforms.get(domId);
886 }
887
Andy Huang3233bff2012-03-20 19:38:45 -0700888 // END message header callbacks
Andy Huang5ff63742012-03-16 20:30:23 -0700889
Andy Huang46dfba62012-04-19 01:47:32 -0700890 @Override
Andrew Sapperstein2fc67302013-04-29 18:24:56 -0700891 public void showUntransformedConversation() {
892 super.showUntransformedConversation();
893 renderConversation(getMessageCursor());
894 }
895
896 @Override
Andy Huang46dfba62012-04-19 01:47:32 -0700897 public void onSuperCollapsedClick(SuperCollapsedBlockItem item) {
mindypf4fce122012-09-14 15:55:33 -0700898 MessageCursor cursor = getMessageCursor();
899 if (cursor == null || !mViewsCreated) {
Andy Huang46dfba62012-04-19 01:47:32 -0700900 return;
901 }
902
mindypf4fce122012-09-14 15:55:33 -0700903 mTempBodiesHtml = renderCollapsedHeaders(cursor, item);
Andy Huang46dfba62012-04-19 01:47:32 -0700904 mWebView.loadUrl("javascript:replaceSuperCollapsedBlock(" + item.getStart() + ")");
905 }
906
Andy Huang47aa9c92012-07-31 15:37:21 -0700907 private void showNewMessageNotification(NewMessagesInfo info) {
908 final TextView descriptionView = (TextView) mNewMessageBar.findViewById(
909 R.id.new_message_description);
910 descriptionView.setText(info.getNotificationText());
911 mNewMessageBar.setVisibility(View.VISIBLE);
912 }
913
914 private void onNewMessageBarClick() {
915 mNewMessageBar.setVisibility(View.GONE);
916
mindypf4fce122012-09-14 15:55:33 -0700917 renderConversation(getMessageCursor()); // mCursor is already up-to-date
918 // per onLoadFinished()
Andy Huang5fbda022012-02-28 18:22:03 -0800919 }
920
Andy Huangadbf3e82012-10-13 13:30:19 -0700921 private static OverlayPosition[] parsePositions(final String[] topArray,
922 final String[] bottomArray) {
923 final int len = topArray.length;
924 final OverlayPosition[] positions = new OverlayPosition[len];
Andy Huangb5078b22012-03-05 19:52:29 -0800925 for (int i = 0; i < len; i++) {
Andy Huangadbf3e82012-10-13 13:30:19 -0700926 positions[i] = new OverlayPosition(
927 Integer.parseInt(topArray[i]), Integer.parseInt(bottomArray[i]));
Andy Huangb5078b22012-03-05 19:52:29 -0800928 }
Andy Huangadbf3e82012-10-13 13:30:19 -0700929 return positions;
Andy Huangb5078b22012-03-05 19:52:29 -0800930 }
931
Andy Huang16174812012-08-16 16:40:35 -0700932 private Address getAddress(String rawFrom) {
Andy Huang543e7092013-04-22 11:44:56 -0700933 Address addr;
934 synchronized (mAddressCache) {
935 addr = mAddressCache.get(rawFrom);
936 if (addr == null) {
937 addr = Address.getEmailAddress(rawFrom);
938 mAddressCache.put(rawFrom, addr);
939 }
Andy Huang16174812012-08-16 16:40:35 -0700940 }
941 return addr;
942 }
943
Andy Huang9d3fd922012-09-26 22:23:58 -0700944 private void ensureContentSizeChangeListener() {
945 if (mWebViewSizeChangeListener == null) {
Andy Huangc1fb9a92013-02-11 13:09:12 -0800946 mWebViewSizeChangeListener = new ContentSizeChangeListener() {
Andy Huang9d3fd922012-09-26 22:23:58 -0700947 @Override
948 public void onHeightChange(int h) {
949 // When WebKit says the DOM height has changed, re-measure
950 // bodies and re-position their headers.
951 // This is separate from the typical JavaScript DOM change
952 // listeners because cases like NARROW_COLUMNS text reflow do not trigger DOM
953 // events.
954 mWebView.loadUrl("javascript:measurePositions();");
955 }
956 };
957 }
958 mWebView.setContentSizeChangeListener(mWebViewSizeChangeListener);
959 }
960
Andy Huangadbf3e82012-10-13 13:30:19 -0700961 private static boolean isOverviewMode(Account acct) {
Andy Huangccf67802013-03-15 14:31:57 -0700962 return acct.settings.isOverviewMode();
Andy Huangadbf3e82012-10-13 13:30:19 -0700963 }
964
965 private void setupOverviewMode() {
Andy Huang02f9d182012-11-28 22:38:02 -0800966 // for now, overview mode means use the built-in WebView zoom and disable custom scale
967 // gesture handling
Andy Huangadbf3e82012-10-13 13:30:19 -0700968 final boolean overviewMode = isOverviewMode(mAccount);
969 final WebSettings settings = mWebView.getSettings();
Andy Huang06def562012-10-14 00:19:11 -0700970 settings.setUseWideViewPort(overviewMode);
Andy Huangc1fb9a92013-02-11 13:09:12 -0800971
972 final OnScaleGestureListener listener;
973
Andy Huang57f354c2013-04-11 17:23:40 -0700974 settings.setSupportZoom(overviewMode);
975 settings.setBuiltInZoomControls(overviewMode);
976 if (overviewMode) {
977 settings.setDisplayZoomControls(false);
Andy Huangadbf3e82012-10-13 13:30:19 -0700978 }
Andy Huang57f354c2013-04-11 17:23:40 -0700979 listener = ENABLE_CSS_ZOOM && !overviewMode ? new CssScaleInterceptor() : null;
Andy Huangc1fb9a92013-02-11 13:09:12 -0800980
Andy Huang57f354c2013-04-11 17:23:40 -0700981 mWebView.setOnScaleGestureListener(listener);
Andy Huangadbf3e82012-10-13 13:30:19 -0700982 }
983
Paul Westbrook542fec92012-09-18 14:47:51 -0700984 private class ConversationWebViewClient extends AbstractConversationWebViewClient {
Andy Huang17a9cde2012-03-09 18:03:16 -0800985 @Override
986 public void onPageFinished(WebView view, String url) {
Andy Huang9a8bc1e2012-10-23 19:48:25 -0700987 // Ignore unsafe calls made after a fragment is detached from an activity.
988 // This method needs to, for example, get at the loader manager, which needs
989 // the fragment to be added.
Andy Huang9a8bc1e2012-10-23 19:48:25 -0700990 if (!isAdded() || !mViewsCreated) {
Andy Huangde56e972012-07-26 18:23:08 -0700991 LogUtils.i(LOG_TAG, "ignoring CVF.onPageFinished, url=%s fragment=%s", url,
Andy Huangb95da852012-07-18 14:16:58 -0700992 ConversationViewFragment.this);
993 return;
994 }
995
Andy Huang30bcfe72012-10-18 18:09:03 -0700996 LogUtils.i(LOG_TAG, "IN CVF.onPageFinished, url=%s fragment=%s wv=%s t=%sms", url,
997 ConversationViewFragment.this, view,
Andy Huang63b3c672012-10-05 19:27:28 -0700998 (SystemClock.uptimeMillis() - mWebViewLoadStartMs));
Andy Huang632721e2012-04-11 16:57:26 -0700999
Andy Huang9d3fd922012-09-26 22:23:58 -07001000 ensureContentSizeChangeListener();
1001
mindyp3bcf1802012-09-09 11:17:00 -07001002 if (!mEnableContentReadySignal) {
Andy Huang7d4746e2012-10-17 17:03:17 -07001003 revealConversation();
mindyp3bcf1802012-09-09 11:17:00 -07001004 }
Andy Huang9d3fd922012-09-26 22:23:58 -07001005
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001006 final Set<String> emailAddresses = Sets.newHashSet();
Andy Huang543e7092013-04-22 11:44:56 -07001007 final List<Address> cacheCopy;
1008 synchronized (mAddressCache) {
1009 cacheCopy = ImmutableList.copyOf(mAddressCache.values());
1010 }
1011 for (Address addr : cacheCopy) {
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001012 emailAddresses.add(addr.getAddress());
Andy Huangb8331b42012-07-16 19:08:53 -07001013 }
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001014 ContactLoaderCallbacks callbacks = getContactInfoSource();
1015 getContactInfoSource().setSenders(emailAddresses);
1016 getLoaderManager().restartLoader(CONTACT_LOADER, Bundle.EMPTY, callbacks);
Andy Huang17a9cde2012-03-09 18:03:16 -08001017 }
1018
Andy Huangaf5d4e02012-03-19 19:02:12 -07001019 @Override
1020 public boolean shouldOverrideUrlLoading(WebView view, String url) {
Paul Westbrook542fec92012-09-18 14:47:51 -07001021 return mViewsCreated && super.shouldOverrideUrlLoading(view, url);
Andy Huangaf5d4e02012-03-19 19:02:12 -07001022 }
Andy Huang17a9cde2012-03-09 18:03:16 -08001023 }
1024
Andy Huangf70fc402012-02-17 15:37:42 -08001025 /**
1026 * NOTE: all public methods must be listed in the proguard flags so that they can be accessed
1027 * via reflection and not stripped.
1028 *
1029 */
1030 private class MailJsBridge {
1031
1032 @SuppressWarnings("unused")
Mindy Pereira974c9662012-09-14 10:02:08 -07001033 @JavascriptInterface
Andy Huangadbf3e82012-10-13 13:30:19 -07001034 public void onWebContentGeometryChange(final String[] overlayTopStrs,
1035 final String[] overlayBottomStrs) {
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001036 getHandler().post(new FragmentRunnable("onWebContentGeometryChange") {
mindyp1b3cc472012-09-27 11:32:59 -07001037
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001038 @Override
1039 public void go() {
1040 try {
Andy Huang46dfba62012-04-19 01:47:32 -07001041 if (!mViewsCreated) {
mindyp1b3cc472012-09-27 11:32:59 -07001042 LogUtils.d(LOG_TAG, "ignoring webContentGeometryChange because views"
1043 + " are gone, %s", ConversationViewFragment.this);
Andy Huang46dfba62012-04-19 01:47:32 -07001044 return;
1045 }
Andy Huangadbf3e82012-10-13 13:30:19 -07001046 mConversationContainer.onGeometryChange(
1047 parsePositions(overlayTopStrs, overlayBottomStrs));
mindyp1b3cc472012-09-27 11:32:59 -07001048 if (mDiff != 0) {
1049 // SCROLL!
1050 int scale = (int) (mWebView.getScale() / mWebView.getInitialScale());
1051 if (scale > 1) {
1052 mWebView.scrollBy(0, (mDiff * (scale - 1)));
1053 }
1054 mDiff = 0;
1055 }
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001056 } catch (Throwable t) {
1057 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onWebContentGeometryChange");
Andy Huang46dfba62012-04-19 01:47:32 -07001058 }
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001059 }
1060 });
Andy Huang46dfba62012-04-19 01:47:32 -07001061 }
1062
1063 @SuppressWarnings("unused")
Mindy Pereira974c9662012-09-14 10:02:08 -07001064 @JavascriptInterface
Andy Huang46dfba62012-04-19 01:47:32 -07001065 public String getTempMessageBodies() {
1066 try {
1067 if (!mViewsCreated) {
1068 return "";
Andy Huangf70fc402012-02-17 15:37:42 -08001069 }
Andy Huang46dfba62012-04-19 01:47:32 -07001070
1071 final String s = mTempBodiesHtml;
1072 mTempBodiesHtml = null;
1073 return s;
1074 } catch (Throwable t) {
1075 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getTempMessageBodies");
1076 return "";
1077 }
Andy Huangf70fc402012-02-17 15:37:42 -08001078 }
1079
Andy Huang014ea4c2012-09-25 14:50:54 -07001080 @SuppressWarnings("unused")
1081 @JavascriptInterface
1082 public String getMessageBody(String domId) {
1083 try {
1084 final MessageCursor cursor = getMessageCursor();
1085 if (!mViewsCreated || cursor == null) {
1086 return "";
1087 }
1088
1089 int pos = -1;
1090 while (cursor.moveToPosition(++pos)) {
1091 final ConversationMessage msg = cursor.getMessage();
1092 if (TextUtils.equals(domId, mTemplates.getMessageDomId(msg))) {
1093 return msg.getBodyAsHtml();
1094 }
1095 }
1096
1097 return "";
1098
1099 } catch (Throwable t) {
1100 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getMessageBody");
1101 return "";
1102 }
1103 }
1104
mindyp3bcf1802012-09-09 11:17:00 -07001105 @SuppressWarnings("unused")
Mindy Pereira974c9662012-09-14 10:02:08 -07001106 @JavascriptInterface
Andy Huang543e7092013-04-22 11:44:56 -07001107 public String getMessageSender(String domId) {
1108 try {
1109 final MessageCursor cursor = getMessageCursor();
1110 if (!mViewsCreated || cursor == null) {
1111 return "";
1112 }
1113
1114 int pos = -1;
1115 while (cursor.moveToPosition(++pos)) {
1116 final ConversationMessage msg = cursor.getMessage();
1117 if (TextUtils.equals(domId, mTemplates.getMessageDomId(msg))) {
1118 return getAddress(msg.getFrom()).getAddress();
1119 }
1120 }
1121
1122 return "";
1123
1124 } catch (Throwable t) {
1125 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getMessageSender");
1126 return "";
1127 }
1128 }
1129
1130 @SuppressWarnings("unused")
1131 @JavascriptInterface
mindyp3bcf1802012-09-09 11:17:00 -07001132 public void onContentReady() {
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001133 getHandler().post(new FragmentRunnable("onContentReady") {
1134 @Override
1135 public void go() {
1136 try {
Andy Huang63b3c672012-10-05 19:27:28 -07001137 if (mWebViewLoadStartMs != 0) {
1138 LogUtils.i(LOG_TAG, "IN CVF.onContentReady, f=%s vis=%s t=%sms",
1139 ConversationViewFragment.this,
1140 isUserVisible(),
1141 (SystemClock.uptimeMillis() - mWebViewLoadStartMs));
1142 }
Andy Huang7d4746e2012-10-17 17:03:17 -07001143 revealConversation();
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001144 } catch (Throwable t) {
1145 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onContentReady");
1146 // Still try to show the conversation.
1147 revealConversation();
mindyp3bcf1802012-09-09 11:17:00 -07001148 }
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001149 }
1150 });
mindyp3bcf1802012-09-09 11:17:00 -07001151 }
Andy Huange964eee2012-10-02 19:24:58 -07001152
1153 @SuppressWarnings("unused")
1154 @JavascriptInterface
1155 public float getScrollYPercent() {
1156 try {
1157 return mWebViewYPercent;
1158 } catch (Throwable t) {
1159 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getScrollYPercent");
1160 return 0f;
1161 }
1162 }
Andy Huang05c70c82013-03-14 15:15:50 -07001163
1164 @SuppressWarnings("unused")
1165 @JavascriptInterface
1166 public void onMessageTransform(String messageDomId, String transformText) {
Andrew Sappersteinae92e152013-05-03 13:55:18 -07001167 try {
1168 LogUtils.i(LOG_TAG, "TRANSFORM: (%s) %s", messageDomId, transformText);
1169 mMessageTransforms.put(messageDomId, transformText);
1170 onConversationTransformed();
1171 } catch (Throwable t) {
1172 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onMessageTransform");
1173 return;
1174 }
Andy Huang05c70c82013-03-14 15:15:50 -07001175 }
Andy Huangf70fc402012-02-17 15:37:42 -08001176 }
1177
Andy Huang47aa9c92012-07-31 15:37:21 -07001178 private class NewMessagesInfo {
1179 int count;
Andy Huang06c03622012-10-22 18:59:45 -07001180 int countFromSelf;
Andy Huang47aa9c92012-07-31 15:37:21 -07001181 String senderAddress;
1182
1183 /**
1184 * Return the display text for the new message notification overlay. It will be formatted
1185 * appropriately for a single new message vs. multiple new messages.
1186 *
1187 * @return display text
1188 */
1189 public String getNotificationText() {
mindypad0c30d2012-09-25 12:09:13 -07001190 Resources res = getResources();
Andy Huang47aa9c92012-07-31 15:37:21 -07001191 if (count > 1) {
mindypad0c30d2012-09-25 12:09:13 -07001192 return res.getString(R.string.new_incoming_messages_many, count);
Andy Huang47aa9c92012-07-31 15:37:21 -07001193 } else {
Andy Huang16174812012-08-16 16:40:35 -07001194 final Address addr = getAddress(senderAddress);
mindypad0c30d2012-09-25 12:09:13 -07001195 return res.getString(R.string.new_incoming_messages_one,
1196 TextUtils.isEmpty(addr.getName()) ? addr.getAddress() : addr.getName());
Andy Huang47aa9c92012-07-31 15:37:21 -07001197 }
Andy Huang47aa9c92012-07-31 15:37:21 -07001198 }
1199 }
1200
mindypf4fce122012-09-14 15:55:33 -07001201 @Override
Andy Huang014ea4c2012-09-25 14:50:54 -07001202 public void onMessageCursorLoadFinished(Loader<Cursor> loader, MessageCursor newCursor,
1203 MessageCursor oldCursor) {
mindypf4fce122012-09-14 15:55:33 -07001204 /*
1205 * what kind of changes affect the MessageCursor? 1. new message(s) 2.
1206 * read/unread state change 3. deleted message, either regular or draft
1207 * 4. updated message, either from self or from others, updated in
1208 * content or state or sender 5. star/unstar of message (technically
1209 * similar to #1) 6. other label change Use MessageCursor.hashCode() to
1210 * sort out interesting vs. no-op cursor updates.
1211 */
Andy Huangb8331b42012-07-16 19:08:53 -07001212
Andy Huang233d4352012-10-18 14:00:24 -07001213 if (oldCursor != null && !oldCursor.isClosed()) {
Andy Huang014ea4c2012-09-25 14:50:54 -07001214 final NewMessagesInfo info = getNewIncomingMessagesInfo(newCursor);
Andy Huangb8331b42012-07-16 19:08:53 -07001215
Andy Huang014ea4c2012-09-25 14:50:54 -07001216 if (info.count > 0) {
1217 // don't immediately render new incoming messages from other
1218 // senders
1219 // (to avoid a new message from losing the user's focus)
1220 LogUtils.i(LOG_TAG, "CONV RENDER: conversation updated"
Andy Huang9d3fd922012-09-26 22:23:58 -07001221 + ", holding cursor for new incoming message (%s)", this);
Andy Huang014ea4c2012-09-25 14:50:54 -07001222 showNewMessageNotification(info);
1223 return;
1224 }
1225
Andy Huang06c03622012-10-22 18:59:45 -07001226 final int oldState = oldCursor.getStateHashCode();
1227 final boolean changed = newCursor.getStateHashCode() != oldState;
Andy Huang233d4352012-10-18 14:00:24 -07001228
Andy Huang014ea4c2012-09-25 14:50:54 -07001229 if (!changed) {
1230 final boolean processedInPlace = processInPlaceUpdates(newCursor, oldCursor);
1231 if (processedInPlace) {
Andy Huang9d3fd922012-09-26 22:23:58 -07001232 LogUtils.i(LOG_TAG, "CONV RENDER: processed update(s) in place (%s)", this);
Andy Huang1ee96b22012-08-24 20:19:53 -07001233 } else {
mindypf4fce122012-09-14 15:55:33 -07001234 LogUtils.i(LOG_TAG, "CONV RENDER: uninteresting update"
Andy Huang9d3fd922012-09-26 22:23:58 -07001235 + ", ignoring this conversation update (%s)", this);
Andy Huang1ee96b22012-08-24 20:19:53 -07001236 }
Andy Huangb8331b42012-07-16 19:08:53 -07001237 return;
Andy Huang06c03622012-10-22 18:59:45 -07001238 } else if (info.countFromSelf == 1) {
1239 // Special-case the very common case of a new cursor that is the same as the old
1240 // one, except that there is a new message from yourself. This happens upon send.
1241 final boolean sameExceptNewLast = newCursor.getStateHashCode(1) == oldState;
1242 if (sameExceptNewLast) {
1243 LogUtils.i(LOG_TAG, "CONV RENDER: update is a single new message from self"
1244 + " (%s)", this);
1245 newCursor.moveToLast();
1246 processNewOutgoingMessage(newCursor.getMessage());
1247 return;
1248 }
Andy Huangb8331b42012-07-16 19:08:53 -07001249 }
Andy Huang6766b6e2012-09-28 12:43:52 -07001250 // cursors are different, and not due to an incoming message. fall
1251 // through and render.
1252 LogUtils.i(LOG_TAG, "CONV RENDER: conversation updated"
1253 + ", but not due to incoming message. rendering. (%s)", this);
Andy Huang06c03622012-10-22 18:59:45 -07001254
1255 if (DEBUG_DUMP_CURSOR_CONTENTS) {
1256 LogUtils.i(LOG_TAG, "old cursor: %s", oldCursor.getDebugDump());
1257 LogUtils.i(LOG_TAG, "new cursor: %s", newCursor.getDebugDump());
1258 }
Andy Huang6766b6e2012-09-28 12:43:52 -07001259 } else {
1260 LogUtils.i(LOG_TAG, "CONV RENDER: initial render. (%s)", this);
Andy Huang243c2362013-03-01 17:50:35 -08001261 timerMark("message cursor load finished");
Andy Huangb8331b42012-07-16 19:08:53 -07001262 }
1263
Mark Wei4071c2f2012-09-26 14:38:38 -07001264 // if layout hasn't happened, delay render
1265 // This is needed in addition to the showConversation() delay to speed
1266 // up rotation and restoration.
1267 if (mConversationContainer.getWidth() == 0) {
1268 mNeedRender = true;
1269 mConversationContainer.addOnLayoutChangeListener(this);
1270 } else {
1271 renderConversation(newCursor);
1272 }
Andy Huangb8331b42012-07-16 19:08:53 -07001273 }
1274
mindypf4fce122012-09-14 15:55:33 -07001275 private NewMessagesInfo getNewIncomingMessagesInfo(MessageCursor newCursor) {
1276 final NewMessagesInfo info = new NewMessagesInfo();
Andy Huangb8331b42012-07-16 19:08:53 -07001277
mindypf4fce122012-09-14 15:55:33 -07001278 int pos = -1;
1279 while (newCursor.moveToPosition(++pos)) {
1280 final Message m = newCursor.getMessage();
1281 if (!mViewState.contains(m)) {
1282 LogUtils.i(LOG_TAG, "conversation diff: found new msg: %s", m.uri);
Andy Huangb8331b42012-07-16 19:08:53 -07001283
Scott Kennedy8960f0a2012-11-07 15:35:50 -08001284 final Address from = getAddress(m.getFrom());
mindypf4fce122012-09-14 15:55:33 -07001285 // distinguish ours from theirs
1286 // new messages from the account owner should not trigger a
1287 // notification
1288 if (mAccount.ownsFromAddress(from.getAddress())) {
1289 LogUtils.i(LOG_TAG, "found message from self: %s", m.uri);
Andy Huang06c03622012-10-22 18:59:45 -07001290 info.countFromSelf++;
mindypf4fce122012-09-14 15:55:33 -07001291 continue;
1292 }
Andy Huangb8331b42012-07-16 19:08:53 -07001293
mindypf4fce122012-09-14 15:55:33 -07001294 info.count++;
Scott Kennedy8960f0a2012-11-07 15:35:50 -08001295 info.senderAddress = m.getFrom();
Andy Huangb8331b42012-07-16 19:08:53 -07001296 }
Andy Huangb8331b42012-07-16 19:08:53 -07001297 }
mindypf4fce122012-09-14 15:55:33 -07001298 return info;
Andy Huangb8331b42012-07-16 19:08:53 -07001299 }
1300
Andy Huang014ea4c2012-09-25 14:50:54 -07001301 private boolean processInPlaceUpdates(MessageCursor newCursor, MessageCursor oldCursor) {
1302 final Set<String> idsOfChangedBodies = Sets.newHashSet();
Andy Huang6b3d0d92012-10-30 15:46:48 -07001303 final List<Integer> changedOverlayPositions = Lists.newArrayList();
1304
Andy Huang014ea4c2012-09-25 14:50:54 -07001305 boolean changed = false;
1306
1307 int pos = 0;
1308 while (true) {
1309 if (!newCursor.moveToPosition(pos) || !oldCursor.moveToPosition(pos)) {
1310 break;
1311 }
1312
1313 final ConversationMessage newMsg = newCursor.getMessage();
1314 final ConversationMessage oldMsg = oldCursor.getMessage();
1315
Scott Kennedy8960f0a2012-11-07 15:35:50 -08001316 if (!TextUtils.equals(newMsg.getFrom(), oldMsg.getFrom()) ||
Andy Huang2a1e8e32012-10-23 18:54:57 -07001317 newMsg.isSending != oldMsg.isSending) {
Andy Huang6b3d0d92012-10-30 15:46:48 -07001318 mAdapter.updateItemsForMessage(newMsg, changedOverlayPositions);
Andy Huang2a1e8e32012-10-23 18:54:57 -07001319 LogUtils.i(LOG_TAG, "msg #%d (%d): detected from/sending change. isSending=%s",
1320 pos, newMsg.id, newMsg.isSending);
Andy Huang014ea4c2012-09-25 14:50:54 -07001321 }
1322
1323 // update changed message bodies in-place
1324 if (!TextUtils.equals(newMsg.bodyHtml, oldMsg.bodyHtml) ||
1325 !TextUtils.equals(newMsg.bodyText, oldMsg.bodyText)) {
1326 // maybe just set a flag to notify JS to re-request changed bodies
1327 idsOfChangedBodies.add('"' + mTemplates.getMessageDomId(newMsg) + '"');
1328 LogUtils.i(LOG_TAG, "msg #%d (%d): detected body change", pos, newMsg.id);
1329 }
1330
1331 pos++;
1332 }
1333
Andy Huang6b3d0d92012-10-30 15:46:48 -07001334
1335 if (!changedOverlayPositions.isEmpty()) {
Andy Huang06c03622012-10-22 18:59:45 -07001336 // notify once after the entire adapter is updated
Andy Huang6b3d0d92012-10-30 15:46:48 -07001337 mConversationContainer.onOverlayModelUpdate(changedOverlayPositions);
1338 changed = true;
Andy Huang06c03622012-10-22 18:59:45 -07001339 }
1340
Andy Huang014ea4c2012-09-25 14:50:54 -07001341 if (!idsOfChangedBodies.isEmpty()) {
1342 mWebView.loadUrl(String.format("javascript:replaceMessageBodies([%s]);",
1343 TextUtils.join(",", idsOfChangedBodies)));
1344 changed = true;
1345 }
1346
1347 return changed;
1348 }
1349
Andy Huang06c03622012-10-22 18:59:45 -07001350 private void processNewOutgoingMessage(ConversationMessage msg) {
1351 mTemplates.reset();
1352 // this method will add some items to mAdapter, but we deliberately want to avoid notifying
1353 // adapter listeners (i.e. ConversationContainer) until onWebContentGeometryChange is next
1354 // called, to prevent N+1 headers rendering with N message bodies.
1355 renderMessage(msg, true /* expanded */, msg.alwaysShowImages);
1356 mTempBodiesHtml = mTemplates.emit();
1357
1358 mViewState.setExpansionState(msg, ExpansionState.EXPANDED);
1359 // FIXME: should the provider set this as initial state?
1360 mViewState.setReadState(msg, false /* read */);
1361
Andy Huang91d782a2012-10-25 12:37:29 -07001362 // From now until the updated spacer geometry is returned, the adapter items are mismatched
1363 // with the existing spacers. Do not let them layout.
1364 mConversationContainer.invalidateSpacerGeometry();
1365
Andy Huang06c03622012-10-22 18:59:45 -07001366 mWebView.loadUrl("javascript:appendMessageHtml();");
1367 }
1368
Paul Westbrookcebcc642012-08-08 10:06:04 -07001369 private class SetCookieTask extends AsyncTask<Void, Void, Void> {
1370 final String mUri;
Paul Westbrookb8361c92012-09-27 10:57:14 -07001371 final Uri mAccountCookieQueryUri;
1372 final ContentResolver mResolver;
Paul Westbrookcebcc642012-08-08 10:06:04 -07001373
Paul Westbrookb8361c92012-09-27 10:57:14 -07001374 SetCookieTask(Context context, Uri baseUri, Uri accountCookieQueryUri) {
1375 mUri = baseUri.toString();
1376 mAccountCookieQueryUri = accountCookieQueryUri;
1377 mResolver = context.getContentResolver();
Paul Westbrookcebcc642012-08-08 10:06:04 -07001378 }
1379
1380 @Override
1381 public Void doInBackground(Void... args) {
Paul Westbrookb8361c92012-09-27 10:57:14 -07001382 // First query for the coookie string from the UI provider
1383 final Cursor cookieCursor = mResolver.query(mAccountCookieQueryUri,
1384 UIProvider.ACCOUNT_COOKIE_PROJECTION, null, null, null);
1385 if (cookieCursor == null) {
1386 return null;
1387 }
1388
1389 try {
1390 if (cookieCursor.moveToFirst()) {
1391 final String cookie = cookieCursor.getString(
1392 cookieCursor.getColumnIndex(UIProvider.AccountCookieColumns.COOKIE));
1393
1394 if (cookie != null) {
1395 final CookieSyncManager csm =
1396 CookieSyncManager.createInstance(getContext());
1397 CookieManager.getInstance().setCookie(mUri, cookie);
1398 csm.sync();
1399 }
1400 }
1401
1402 } finally {
1403 cookieCursor.close();
1404 }
1405
1406
Paul Westbrookcebcc642012-08-08 10:06:04 -07001407 return null;
1408 }
1409 }
mindyp36280f32012-09-09 16:11:23 -07001410
mindyp26d4d2d2012-09-18 17:30:32 -07001411 @Override
mindyp36280f32012-09-09 16:11:23 -07001412 public void onConversationUpdated(Conversation conv) {
1413 final ConversationViewHeader headerView = (ConversationViewHeader) mConversationContainer
1414 .findViewById(R.id.conversation_header);
mindypb2b98ba2012-09-24 14:13:58 -07001415 mConversation = conv;
mindyp9e0b2362012-09-09 16:31:21 -07001416 if (headerView != null) {
1417 headerView.onConversationUpdated(conv);
Vikram Aggarwal51ad9042013-01-17 13:18:09 -08001418 headerView.setSubject(conv.subject);
mindyp9e0b2362012-09-09 16:31:21 -07001419 }
mindyp36280f32012-09-09 16:11:23 -07001420 }
Mark Wei4071c2f2012-09-26 14:38:38 -07001421
1422 @Override
1423 public void onLayoutChange(View v, int left, int top, int right,
1424 int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
1425 boolean sizeChanged = mNeedRender
1426 && mConversationContainer.getWidth() != 0;
1427 if (sizeChanged) {
1428 mNeedRender = false;
1429 mConversationContainer.removeOnLayoutChangeListener(this);
1430 renderConversation(getMessageCursor());
1431 }
1432 }
mindyp1b3cc472012-09-27 11:32:59 -07001433
1434 @Override
1435 public void setMessageDetailsExpanded(MessageHeaderItem i, boolean expanded,
1436 int heightBefore) {
1437 mDiff = (expanded ? 1 : -1) * Math.abs(i.getHeight() - heightBefore);
1438 }
Andy Huang02f9d182012-11-28 22:38:02 -08001439
Andy Huangc1fb9a92013-02-11 13:09:12 -08001440 private class CssScaleInterceptor implements OnScaleGestureListener {
Andy Huang02f9d182012-11-28 22:38:02 -08001441
1442 private float getFocusXWebPx(ScaleGestureDetector detector) {
1443 return (detector.getFocusX() - mSideMarginPx) / mWebView.getInitialScale();
1444 }
1445
1446 private float getFocusYWebPx(ScaleGestureDetector detector) {
1447 return detector.getFocusY() / mWebView.getInitialScale();
1448 }
1449
1450 @Override
1451 public boolean onScale(ScaleGestureDetector detector) {
1452 mWebView.loadUrl(String.format("javascript:onScale(%s, %s, %s);",
1453 detector.getScaleFactor(), getFocusXWebPx(detector),
1454 getFocusYWebPx(detector)));
1455 return false;
1456 }
1457
1458 @Override
1459 public boolean onScaleBegin(ScaleGestureDetector detector) {
1460 mWebView.loadUrl(String.format("javascript:onScaleBegin(%s, %s);",
1461 getFocusXWebPx(detector), getFocusYWebPx(detector)));
1462 return true;
1463 }
1464
1465 @Override
1466 public void onScaleEnd(ScaleGestureDetector detector) {
1467 mWebView.loadUrl(String.format("javascript:onScaleEnd(%s, %s);",
1468 getFocusXWebPx(detector), getFocusYWebPx(detector)));
1469 }
1470
1471 }
1472
Mindy Pereira9b875682012-02-15 18:10:54 -08001473}