blob: cac5b64605df7e9a6d95bfac987a298f52689f39 [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;
Andrew Sapperstein8812d3c2013-06-04 17:06:41 -070052import com.android.mail.browse.ConversationMessage;
Andy Huang46dfba62012-04-19 01:47:32 -070053import com.android.mail.browse.ConversationOverlayItem;
Andy Huang7bdc3752012-03-25 17:18:19 -070054import com.android.mail.browse.ConversationViewAdapter;
Andy Huang46dfba62012-04-19 01:47:32 -070055import com.android.mail.browse.ConversationViewAdapter.MessageFooterItem;
Andy Huang7bdc3752012-03-25 17:18:19 -070056import com.android.mail.browse.ConversationViewAdapter.MessageHeaderItem;
Andy Huang46dfba62012-04-19 01:47:32 -070057import com.android.mail.browse.ConversationViewAdapter.SuperCollapsedBlockItem;
Andy Huang5ff63742012-03-16 20:30:23 -070058import com.android.mail.browse.ConversationViewHeader;
59import com.android.mail.browse.ConversationWebView;
Andy Huangc1fb9a92013-02-11 13:09:12 -080060import com.android.mail.browse.MailWebView.ContentSizeChangeListener;
Andy Huang7bdc3752012-03-25 17:18:19 -070061import com.android.mail.browse.MessageCursor;
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;
Paul Westbrookc42ad5e2013-05-09 16:52:15 -070066import com.android.mail.content.ObjectCursor;
Andy Huangc1fb9a92013-02-11 13:09:12 -080067import com.android.mail.preferences.MailPrefs;
Mindy Pereira9b875682012-02-15 18:10:54 -080068import com.android.mail.providers.Account;
Andy Huang65fe28f2012-04-06 18:08:53 -070069import com.android.mail.providers.Address;
Mindy Pereira9b875682012-02-15 18:10:54 -080070import com.android.mail.providers.Conversation;
Andy Huangf70fc402012-02-17 15:37:42 -080071import com.android.mail.providers.Message;
Paul Westbrookb8361c92012-09-27 10:57:14 -070072import com.android.mail.providers.UIProvider;
Andy Huangcd5c5ee2012-08-12 19:03:51 -070073import com.android.mail.ui.ConversationViewState.ExpansionState;
Paul Westbrookb334c902012-06-25 11:42:46 -070074import com.android.mail.utils.LogTag;
Mindy Pereira9b875682012-02-15 18:10:54 -080075import com.android.mail.utils.LogUtils;
Andy Huang2e9acfe2012-03-15 22:39:36 -070076import com.android.mail.utils.Utils;
Andy Huang543e7092013-04-22 11:44:56 -070077import com.google.common.collect.ImmutableList;
Andy Huang46dfba62012-04-19 01:47:32 -070078import com.google.common.collect.Lists;
Andy Huang05c70c82013-03-14 15:15:50 -070079import com.google.common.collect.Maps;
Andy Huangb8331b42012-07-16 19:08:53 -070080import com.google.common.collect.Sets;
Andy Huang65fe28f2012-04-06 18:08:53 -070081
Scott Kennedyeb9a4bd2012-11-12 10:33:04 -080082import java.util.ArrayList;
Andy Huang46dfba62012-04-19 01:47:32 -070083import java.util.List;
Andy Huang05c70c82013-03-14 15:15:50 -070084import java.util.Map;
Andy Huangb8331b42012-07-16 19:08:53 -070085import java.util.Set;
Mindy Pereira9b875682012-02-15 18:10:54 -080086
Andy Huangf70fc402012-02-17 15:37:42 -080087
Mindy Pereira9b875682012-02-15 18:10:54 -080088/**
89 * The conversation view UI component.
90 */
mindypf4fce122012-09-14 15:55:33 -070091public final class ConversationViewFragment extends AbstractConversationViewFragment implements
Andy Huangcd5c5ee2012-08-12 19:03:51 -070092 SuperCollapsedBlock.OnClickListener,
Andy Huang57f354c2013-04-11 17:23:40 -070093 OnLayoutChangeListener {
Mindy Pereira8e915722012-02-16 14:42:56 -080094
Paul Westbrookb334c902012-06-25 11:42:46 -070095 private static final String LOG_TAG = LogTag.getLogTag();
Andy Huang632721e2012-04-11 16:57:26 -070096 public static final String LAYOUT_TAG = "ConvLayout";
Mindy Pereira9b875682012-02-15 18:10:54 -080097
Andy Huang3c276bf2013-02-19 14:24:43 -080098 private static final boolean ENABLE_CSS_ZOOM = false;
99
Andy Huang9d3fd922012-09-26 22:23:58 -0700100 /**
mindyp1b3cc472012-09-27 11:32:59 -0700101 * Difference in the height of the message header whose details have been expanded/collapsed
102 */
103 private int mDiff = 0;
104
105 /**
Andy Huang9d3fd922012-09-26 22:23:58 -0700106 * Default value for {@link #mLoadWaitReason}. Conversation load will happen immediately.
107 */
108 private final int LOAD_NOW = 0;
109 /**
110 * Value for {@link #mLoadWaitReason} that means we are offscreen and waiting for the visible
111 * conversation to finish loading before beginning our load.
112 * <p>
113 * When this value is set, the fragment should register with {@link ConversationListCallbacks}
114 * to know when the visible conversation is loaded. When it is unset, it should unregister.
115 */
116 private final int LOAD_WAIT_FOR_INITIAL_CONVERSATION = 1;
117 /**
118 * Value for {@link #mLoadWaitReason} used when a conversation is too heavyweight to load at
119 * all when not visible (e.g. requires network fetch, or too complex). Conversation load will
120 * wait until this fragment is visible.
121 */
122 private final int LOAD_WAIT_UNTIL_VISIBLE = 2;
mindyp3bcf1802012-09-09 11:17:00 -0700123
Andy Huangf70fc402012-02-17 15:37:42 -0800124 private ConversationContainer mConversationContainer;
Mindy Pereira9b875682012-02-15 18:10:54 -0800125
Andy Huangf70fc402012-02-17 15:37:42 -0800126 private ConversationWebView mWebView;
Mindy Pereira9b875682012-02-15 18:10:54 -0800127
Mark Wei56d83852012-09-19 14:28:50 -0700128 private ScrollIndicatorsView mScrollIndicators;
129
Andy Huang47aa9c92012-07-31 15:37:21 -0700130 private View mNewMessageBar;
131
Andy Huangf70fc402012-02-17 15:37:42 -0800132 private HtmlConversationTemplates mTemplates;
133
Andy Huangf70fc402012-02-17 15:37:42 -0800134 private final MailJsBridge mJsBridge = new MailJsBridge();
135
Andy Huang17a9cde2012-03-09 18:03:16 -0800136 private final WebViewClient mWebViewClient = new ConversationWebViewClient();
137
Andy Huang7bdc3752012-03-25 17:18:19 -0700138 private ConversationViewAdapter mAdapter;
Andy Huang51067132012-03-12 20:08:19 -0700139
140 private boolean mViewsCreated;
Mark Wei4071c2f2012-09-26 14:38:38 -0700141 // True if we attempted to render before the views were laid out
142 // We will render immediately once layout is done
143 private boolean mNeedRender;
Andy Huang51067132012-03-12 20:08:19 -0700144
Andy Huang46dfba62012-04-19 01:47:32 -0700145 /**
146 * Temporary string containing the message bodies of the messages within a super-collapsed
147 * block, for one-time use during block expansion. We cannot easily pass the body HTML
148 * into JS without problematic escaping, so hold onto it momentarily and signal JS to fetch it
149 * using {@link MailJsBridge}.
150 */
151 private String mTempBodiesHtml;
152
Andy Huang632721e2012-04-11 16:57:26 -0700153 private int mMaxAutoLoadMessages;
154
Andy Huang02f9d182012-11-28 22:38:02 -0800155 private int mSideMarginPx;
156
Andy Huang9d3fd922012-09-26 22:23:58 -0700157 /**
158 * If this conversation fragment is not visible, and it's inappropriate to load up front,
159 * this is the reason we are waiting. This flag should be cleared once it's okay to load
160 * the conversation.
161 */
162 private int mLoadWaitReason = LOAD_NOW;
Andy Huang632721e2012-04-11 16:57:26 -0700163
mindyp3bcf1802012-09-09 11:17:00 -0700164 private boolean mEnableContentReadySignal;
Andy Huang28b7aee2012-08-20 20:27:32 -0700165
mindypdde3f9f2012-09-10 17:35:35 -0700166 private ContentSizeChangeListener mWebViewSizeChangeListener;
167
Andy Huange964eee2012-10-02 19:24:58 -0700168 private float mWebViewYPercent;
169
170 /**
171 * Has loadData been called on the WebView yet?
172 */
173 private boolean mWebViewLoadedData;
174
Andy Huang63b3c672012-10-05 19:27:28 -0700175 private long mWebViewLoadStartMs;
176
Andy Huang05c70c82013-03-14 15:15:50 -0700177 private final Map<String, String> mMessageTransforms = Maps.newHashMap();
178
Andy Huang9d3fd922012-09-26 22:23:58 -0700179 private final DataSetObserver mLoadedObserver = new DataSetObserver() {
180 @Override
181 public void onChanged() {
182 getHandler().post(new FragmentRunnable("delayedConversationLoad") {
183 @Override
184 public void go() {
185 LogUtils.d(LOG_TAG, "CVF load observer fired, this=%s",
186 ConversationViewFragment.this);
187 handleDelayedConversationLoad();
188 }
189 });
190 }
191 };
Andy Huangf70fc402012-02-17 15:37:42 -0800192
Andy Huang30bcfe72012-10-18 18:09:03 -0700193 private final Runnable mOnProgressDismiss = new FragmentRunnable("onProgressDismiss") {
Andy Huang7d4746e2012-10-17 17:03:17 -0700194 @Override
195 public void go() {
Scott Kennedy58192e52013-05-08 16:35:57 -0700196 LogUtils.d(LOG_TAG, "onProgressDismiss go() - isUserVisible() = %b", isUserVisible());
Andy Huang7d4746e2012-10-17 17:03:17 -0700197 if (isUserVisible()) {
198 onConversationSeen();
199 }
Andy Huang30bcfe72012-10-18 18:09:03 -0700200 mWebView.onRenderComplete();
Andy Huang7d4746e2012-10-17 17:03:17 -0700201 }
202 };
203
Andy Huangbd544e32012-05-29 15:56:51 -0700204 private static final boolean DEBUG_DUMP_CONVERSATION_HTML = false;
Andy Huang47aa9c92012-07-31 15:37:21 -0700205 private static final boolean DISABLE_OFFSCREEN_LOADING = false;
Andy Huang06c03622012-10-22 18:59:45 -0700206 private static final boolean DEBUG_DUMP_CURSOR_CONTENTS = false;
Andy Huange964eee2012-10-02 19:24:58 -0700207
208 private static final String BUNDLE_KEY_WEBVIEW_Y_PERCENT =
209 ConversationViewFragment.class.getName() + "webview-y-percent";
Andy Huangbd544e32012-05-29 15:56:51 -0700210
Vikram Aggarwal6c511582012-02-27 10:59:47 -0800211 /**
212 * Constructor needs to be public to handle orientation changes and activity lifecycle events.
213 */
Andy Huangf70fc402012-02-17 15:37:42 -0800214 public ConversationViewFragment() {
Vikram Aggarwal6c511582012-02-27 10:59:47 -0800215 super();
Mindy Pereira9b875682012-02-15 18:10:54 -0800216 }
217
218 /**
219 * Creates a new instance of {@link ConversationViewFragment}, initialized
Andy Huang632721e2012-04-11 16:57:26 -0700220 * to display a conversation with other parameters inherited/copied from an existing bundle,
221 * typically one created using {@link #makeBasicArgs}.
222 */
223 public static ConversationViewFragment newInstance(Bundle existingArgs,
224 Conversation conversation) {
225 ConversationViewFragment f = new ConversationViewFragment();
226 Bundle args = new Bundle(existingArgs);
227 args.putParcelable(ARG_CONVERSATION, conversation);
228 f.setArguments(args);
229 return f;
230 }
231
mindypf4fce122012-09-14 15:55:33 -0700232 @Override
Andy Huangadbf3e82012-10-13 13:30:19 -0700233 public void onAccountChanged(Account newAccount, Account oldAccount) {
234 // if overview mode has changed, re-render completely (no need to also update headers)
235 if (isOverviewMode(newAccount) != isOverviewMode(oldAccount)) {
236 setupOverviewMode();
237 final MessageCursor c = getMessageCursor();
238 if (c != null) {
239 renderConversation(c);
240 } else {
241 // Null cursor means this fragment is either waiting to load or in the middle of
242 // loading. Either way, a future render will happen anyway, and the new setting
243 // will take effect when that happens.
244 }
245 return;
246 }
247
mindypf4fce122012-09-14 15:55:33 -0700248 // settings may have been updated; refresh views that are known to
249 // depend on settings
mindypf4fce122012-09-14 15:55:33 -0700250 mAdapter.notifyDataSetChanged();
Andy Huang632721e2012-04-11 16:57:26 -0700251 }
252
Mindy Pereira9b875682012-02-15 18:10:54 -0800253 @Override
254 public void onActivityCreated(Bundle savedInstanceState) {
Andy Huang9d3fd922012-09-26 22:23:58 -0700255 LogUtils.d(LOG_TAG, "IN CVF.onActivityCreated, this=%s visible=%s", this, isUserVisible());
Mindy Pereira9b875682012-02-15 18:10:54 -0800256 super.onActivityCreated(savedInstanceState);
Mark Wei1abfcaf2012-09-27 11:11:07 -0700257
258 if (mActivity == null || mActivity.isFinishing()) {
259 // Activity is finishing, just bail.
260 return;
261 }
262
mindypf4fce122012-09-14 15:55:33 -0700263 Context context = getContext();
264 mTemplates = new HtmlConversationTemplates(context);
Andy Huang59e0b182012-08-14 14:32:23 -0700265
mindypf4fce122012-09-14 15:55:33 -0700266 final FormattedDateBuilder dateBuilder = new FormattedDateBuilder(context);
Andy Huang59e0b182012-08-14 14:32:23 -0700267
Paul Westbrook8081df42012-09-10 15:43:36 -0700268 mAdapter = new ConversationViewAdapter(mActivity, this,
mindypf4fce122012-09-14 15:55:33 -0700269 getLoaderManager(), this, getContactInfoSource(), this,
Paul Westbrook8081df42012-09-10 15:43:36 -0700270 this, mAddressCache, dateBuilder);
Andy Huang51067132012-03-12 20:08:19 -0700271 mConversationContainer.setOverlayAdapter(mAdapter);
272
Andy Huang59e0b182012-08-14 14:32:23 -0700273 // set up snap header (the adapter usually does this with the other ones)
274 final MessageHeaderView snapHeader = mConversationContainer.getSnapHeader();
Andy Huangc1fb9a92013-02-11 13:09:12 -0800275 initHeaderView(snapHeader, dateBuilder);
276
Andy Huang632721e2012-04-11 16:57:26 -0700277 mMaxAutoLoadMessages = getResources().getInteger(R.integer.max_auto_load_messages);
278
Andy Huang02f9d182012-11-28 22:38:02 -0800279 mSideMarginPx = getResources().getDimensionPixelOffset(
280 R.dimen.conversation_view_margin_side) + getResources().getDimensionPixelOffset(
281 R.dimen.conversation_message_content_margin_side);
282
mindypf4fce122012-09-14 15:55:33 -0700283 mWebView.setOnCreateContextMenuListener(new WebViewContextMenu(getActivity()));
Andy Huang0b7ed6f2012-07-25 19:23:26 -0700284
Andy Huangadbf3e82012-10-13 13:30:19 -0700285 // set this up here instead of onCreateView to ensure the latest Account is loaded
286 setupOverviewMode();
287
Andy Huang9d3fd922012-09-26 22:23:58 -0700288 // Defer the call to initLoader with a Handler.
289 // We want to wait until we know which fragments are present and their final visibility
290 // states before going off and doing work. This prevents extraneous loading from occurring
291 // as the ViewPager shifts about before the initial position is set.
292 //
293 // e.g. click on item #10
294 // ViewPager.setAdapter() actually first loads #0 and #1 under the assumption that #0 is
295 // the initial primary item
296 // Then CPC immediately sets the primary item to #10, which tears down #0/#1 and sets up
297 // #9/#10/#11.
298 getHandler().post(new FragmentRunnable("showConversation") {
299 @Override
300 public void go() {
301 showConversation();
302 }
303 });
Paul Westbrookcebcc642012-08-08 10:06:04 -0700304
305 if (mConversation.conversationBaseUri != null &&
Paul Westbrookb8361c92012-09-27 10:57:14 -0700306 !Utils.isEmpty(mAccount.accoutCookieQueryUri)) {
Paul Westbrookcebcc642012-08-08 10:06:04 -0700307 // Set the cookie for this base url
Paul Westbrookb8361c92012-09-27 10:57:14 -0700308 new SetCookieTask(getContext(), mConversation.conversationBaseUri,
309 mAccount.accoutCookieQueryUri).execute();
Paul Westbrookcebcc642012-08-08 10:06:04 -0700310 }
Mindy Pereira9b875682012-02-15 18:10:54 -0800311 }
312
Andy Huangc1fb9a92013-02-11 13:09:12 -0800313 private void initHeaderView(MessageHeaderView headerView, FormattedDateBuilder dateBuilder) {
314 headerView.initialize(dateBuilder, this, mAddressCache);
315 headerView.setCallbacks(this);
316 headerView.setContactInfoSource(getContactInfoSource());
317 headerView.setVeiledMatcher(mActivity.getAccountController().getVeiledAddressMatcher());
318 }
319
Mindy Pereira9b875682012-02-15 18:10:54 -0800320 @Override
Andy Huange964eee2012-10-02 19:24:58 -0700321 public void onCreate(Bundle savedState) {
322 super.onCreate(savedState);
323
324 if (savedState != null) {
325 mWebViewYPercent = savedState.getFloat(BUNDLE_KEY_WEBVIEW_Y_PERCENT);
326 }
327 }
328
329 @Override
Mindy Pereira9b875682012-02-15 18:10:54 -0800330 public View onCreateView(LayoutInflater inflater,
331 ViewGroup container, Bundle savedInstanceState) {
Andy Huang839ada22012-07-20 15:48:40 -0700332
Andy Huang632721e2012-04-11 16:57:26 -0700333 View rootView = inflater.inflate(R.layout.conversation_view, container, false);
Andy Huangf70fc402012-02-17 15:37:42 -0800334 mConversationContainer = (ConversationContainer) rootView
335 .findViewById(R.id.conversation_container);
Andy Huang8f187782012-11-06 17:49:25 -0800336 mConversationContainer.setAccountController(this);
Andy Huang47aa9c92012-07-31 15:37:21 -0700337
338 mNewMessageBar = mConversationContainer.findViewById(R.id.new_message_notification_bar);
339 mNewMessageBar.setOnClickListener(new View.OnClickListener() {
340 @Override
341 public void onClick(View v) {
342 onNewMessageBarClick();
343 }
344 });
345
mindypff282d02012-09-17 10:33:02 -0700346 instantiateProgressIndicators(rootView);
mindyp3bcf1802012-09-09 11:17:00 -0700347
Andy Huang5ff63742012-03-16 20:30:23 -0700348 mWebView = (ConversationWebView) mConversationContainer.findViewById(R.id.webview);
Andy Huangf70fc402012-02-17 15:37:42 -0800349
Andy Huangf70fc402012-02-17 15:37:42 -0800350 mWebView.addJavascriptInterface(mJsBridge, "mail");
mindyp3bcf1802012-09-09 11:17:00 -0700351 // On JB or newer, we use the 'webkitAnimationStart' DOM event to signal load complete
352 // Below JB, try to speed up initial render by having the webview do supplemental draws to
353 // custom a software canvas.
mindypb941fdb2012-09-11 08:28:23 -0700354 // TODO(mindyp):
355 //PAGE READINESS SIGNAL FOR JELLYBEAN AND NEWER
356 // Notify the app on 'webkitAnimationStart' of a simple dummy element with a simple no-op
357 // animation that immediately runs on page load. The app uses this as a signal that the
358 // content is loaded and ready to draw, since WebView delays firing this event until the
359 // layers are composited and everything is ready to draw.
360 // This signal does not seem to be reliable, so just use the old method for now.
mindyp32d911f2012-09-24 15:14:22 -0700361 mEnableContentReadySignal = Utils.isRunningJellybeanOrLater();
mindypafc9b362012-09-25 09:20:47 -0700362 mWebView.setUseSoftwareLayer(!mEnableContentReadySignal);
Andy Huang30bcfe72012-10-18 18:09:03 -0700363 mWebView.onUserVisibilityChanged(isUserVisible());
Andy Huang17a9cde2012-03-09 18:03:16 -0800364 mWebView.setWebViewClient(mWebViewClient);
Andy Huangc1fb9a92013-02-11 13:09:12 -0800365 final WebChromeClient wcc = new WebChromeClient() {
Andy Huangf70fc402012-02-17 15:37:42 -0800366 @Override
367 public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Andy Huang5ea5a832013-03-07 16:49:09 -0800368 LogUtils.i(LOG_TAG, "JS: %s (%s:%d) f=%s", consoleMessage.message(),
369 consoleMessage.sourceId(), consoleMessage.lineNumber(),
370 ConversationViewFragment.this);
Andy Huangf70fc402012-02-17 15:37:42 -0800371 return true;
372 }
Andy Huangc1fb9a92013-02-11 13:09:12 -0800373 };
374 mWebView.setWebChromeClient(wcc);
Andy Huangf70fc402012-02-17 15:37:42 -0800375
Andy Huang3233bff2012-03-20 19:38:45 -0700376 final WebSettings settings = mWebView.getSettings();
Andy Huangf70fc402012-02-17 15:37:42 -0800377
Mark Wei56d83852012-09-19 14:28:50 -0700378 mScrollIndicators = (ScrollIndicatorsView) rootView.findViewById(R.id.scroll_indicators);
379 mScrollIndicators.setSourceView(mWebView);
380
Andy Huangf70fc402012-02-17 15:37:42 -0800381 settings.setJavaScriptEnabled(true);
Andy Huangf70fc402012-02-17 15:37:42 -0800382
Andrew Sappersteina8d623a2013-05-29 12:43:18 -0700383 setTextZoom(settings);
Andy Huangc319b552012-04-25 19:53:50 -0700384
Andy Huang51067132012-03-12 20:08:19 -0700385 mViewsCreated = true;
Andy Huange964eee2012-10-02 19:24:58 -0700386 mWebViewLoadedData = false;
Andy Huang51067132012-03-12 20:08:19 -0700387
Mindy Pereira9b875682012-02-15 18:10:54 -0800388 return rootView;
389 }
390
391 @Override
392 public void onDestroyView() {
Mindy Pereira9b875682012-02-15 18:10:54 -0800393 super.onDestroyView();
Andy Huang46dfba62012-04-19 01:47:32 -0700394 mConversationContainer.setOverlayAdapter(null);
395 mAdapter = null;
Andy Huang9d3fd922012-09-26 22:23:58 -0700396 resetLoadWaiting(); // be sure to unregister any active load observer
Andy Huang51067132012-03-12 20:08:19 -0700397 mViewsCreated = false;
Mindy Pereira9b875682012-02-15 18:10:54 -0800398 }
399
Andy Huange964eee2012-10-02 19:24:58 -0700400 @Override
Scott Kennedyfafcd172012-11-01 17:23:33 -0700401 protected WebView getWebView() {
402 return mWebView;
403 }
404
405 @Override
Andy Huange964eee2012-10-02 19:24:58 -0700406 public void onSaveInstanceState(Bundle outState) {
407 super.onSaveInstanceState(outState);
408
409 outState.putFloat(BUNDLE_KEY_WEBVIEW_Y_PERCENT, calculateScrollYPercent());
410 }
411
412 private float calculateScrollYPercent() {
Paul Westbrook1b56a672013-04-19 01:19:05 -0700413 final float p;
414 if (mWebView == null) {
415 // onCreateView hasn't been called, return 0 as the user hasn't scrolled the view.
416 return 0;
417 }
418
419 final int scrollY = mWebView.getScrollY();
420 final int viewH = mWebView.getHeight();
421 final int webH = (int) (mWebView.getContentHeight() * mWebView.getScale());
Andy Huange964eee2012-10-02 19:24:58 -0700422
423 if (webH == 0 || webH <= viewH) {
424 p = 0;
425 } else if (scrollY + viewH >= webH) {
426 // The very bottom is a special case, it acts as a stronger anchor than the scroll top
427 // at that point.
428 p = 1.0f;
429 } else {
430 p = (float) scrollY / webH;
431 }
432 return p;
433 }
434
Andy Huang9d3fd922012-09-26 22:23:58 -0700435 private void resetLoadWaiting() {
436 if (mLoadWaitReason == LOAD_WAIT_FOR_INITIAL_CONVERSATION) {
437 getListController().unregisterConversationLoadedObserver(mLoadedObserver);
438 }
439 mLoadWaitReason = LOAD_NOW;
440 }
441
Andy Huang5ff63742012-03-16 20:30:23 -0700442 @Override
mindypf4fce122012-09-14 15:55:33 -0700443 protected void markUnread() {
Vikram Aggarwald82a31f2013-02-05 15:03:00 -0800444 super.markUnread();
Andy Huang839ada22012-07-20 15:48:40 -0700445 // Ignore unsafe calls made after a fragment is detached from an activity
446 final ControllableActivity activity = (ControllableActivity) getActivity();
447 if (activity == null) {
448 LogUtils.w(LOG_TAG, "ignoring markUnread for conv=%s", mConversation.id);
449 return;
450 }
451
Andy Huang28e31e22012-07-26 16:33:15 -0700452 if (mViewState == null) {
453 LogUtils.i(LOG_TAG, "ignoring markUnread for conv with no view state (%d)",
454 mConversation.id);
455 return;
456 }
Andy Huang839ada22012-07-20 15:48:40 -0700457 activity.getConversationUpdater().markConversationMessagesUnread(mConversation,
Vikram Aggarwal4a878b62012-07-31 15:09:25 -0700458 mViewState.getUnreadMessageUris(), mViewState.getConversationInfo());
Andy Huang839ada22012-07-20 15:48:40 -0700459 }
460
mindypf4fce122012-09-14 15:55:33 -0700461 @Override
462 public void onUserVisibleHintChanged() {
Andy Huang9d3fd922012-09-26 22:23:58 -0700463 final boolean userVisible = isUserVisible();
Scott Kennedy58192e52013-05-08 16:35:57 -0700464 LogUtils.d(LOG_TAG, "ConversationViewFragment#onUserVisibleHintChanged(), userVisible = %b",
465 userVisible);
Andy Huang9d3fd922012-09-26 22:23:58 -0700466
467 if (!userVisible) {
mindyp32d911f2012-09-24 15:14:22 -0700468 dismissLoadingStatus();
Andy Huang9d3fd922012-09-26 22:23:58 -0700469 } else if (mViewsCreated) {
470 if (getMessageCursor() != null) {
471 LogUtils.d(LOG_TAG, "Fragment is now user-visible, onConversationSeen: %s", this);
472 onConversationSeen();
473 } else if (isLoadWaiting()) {
474 LogUtils.d(LOG_TAG, "Fragment is now user-visible, showing conversation: %s", this);
475 handleDelayedConversationLoad();
476 }
Andy Huang632721e2012-04-11 16:57:26 -0700477 }
Andy Huang632721e2012-04-11 16:57:26 -0700478
Andy Huang30bcfe72012-10-18 18:09:03 -0700479 if (mWebView != null) {
480 mWebView.onUserVisibilityChanged(userVisible);
481 }
Andy Huangf8cf5462012-10-17 18:29:14 -0700482 }
483
Andy Huang9d3fd922012-09-26 22:23:58 -0700484 /**
485 * Will either call initLoader now to begin loading, or set {@link #mLoadWaitReason} and do
486 * nothing (in which case you should later call {@link #handleDelayedConversationLoad()}).
487 */
Mindy Pereira9b875682012-02-15 18:10:54 -0800488 private void showConversation() {
Andy Huang9d3fd922012-09-26 22:23:58 -0700489 final int reason;
490
491 if (isUserVisible()) {
492 LogUtils.i(LOG_TAG,
493 "SHOWCONV: CVF is user-visible, immediately loading conversation (%s)", this);
494 reason = LOAD_NOW;
Andy Huang243c2362013-03-01 17:50:35 -0800495 timerMark("CVF.showConversation");
Andy Huang9d3fd922012-09-26 22:23:58 -0700496 } else {
497 final boolean disableOffscreenLoading = DISABLE_OFFSCREEN_LOADING
498 || (mConversation.isRemote
499 || mConversation.getNumMessages() > mMaxAutoLoadMessages);
500
501 // When not visible, we should not immediately load if either this conversation is
502 // too heavyweight, or if the main/initial conversation is busy loading.
503 if (disableOffscreenLoading) {
504 reason = LOAD_WAIT_UNTIL_VISIBLE;
505 LogUtils.i(LOG_TAG, "SHOWCONV: CVF waiting until visible to load (%s)", this);
506 } else if (getListController().isInitialConversationLoading()) {
507 reason = LOAD_WAIT_FOR_INITIAL_CONVERSATION;
508 LogUtils.i(LOG_TAG, "SHOWCONV: CVF waiting for initial to finish (%s)", this);
509 getListController().registerConversationLoadedObserver(mLoadedObserver);
510 } else {
511 LogUtils.i(LOG_TAG,
512 "SHOWCONV: CVF is not visible, but no reason to wait. loading now. (%s)",
513 this);
514 reason = LOAD_NOW;
515 }
Andy Huang632721e2012-04-11 16:57:26 -0700516 }
Andy Huang9d3fd922012-09-26 22:23:58 -0700517
518 mLoadWaitReason = reason;
519 if (mLoadWaitReason == LOAD_NOW) {
520 startConversationLoad();
521 }
522 }
523
524 private void handleDelayedConversationLoad() {
525 resetLoadWaiting();
526 startConversationLoad();
527 }
528
529 private void startConversationLoad() {
mindyp3bcf1802012-09-09 11:17:00 -0700530 mWebView.setVisibility(View.VISIBLE);
mindypf4fce122012-09-14 15:55:33 -0700531 getLoaderManager().initLoader(MESSAGE_LOADER, Bundle.EMPTY, getMessageLoaderCallbacks());
mindyp3bcf1802012-09-09 11:17:00 -0700532 // TODO(mindyp): don't show loading status for a previously rendered
533 // conversation. Ielieve this is better done by making sure don't show loading status
534 // until XX ms have passed without loading completed.
535 showLoadingStatus();
Mindy Pereira8e915722012-02-16 14:42:56 -0800536 }
537
Andy Huang7d4746e2012-10-17 17:03:17 -0700538 private void revealConversation() {
Andy Huang243c2362013-03-01 17:50:35 -0800539 timerMark("revealing conversation");
Andy Huang30bcfe72012-10-18 18:09:03 -0700540 dismissLoadingStatus(mOnProgressDismiss);
Andy Huang7d4746e2012-10-17 17:03:17 -0700541 }
542
Andy Huang9d3fd922012-09-26 22:23:58 -0700543 private boolean isLoadWaiting() {
544 return mLoadWaitReason != LOAD_NOW;
545 }
546
Andy Huang51067132012-03-12 20:08:19 -0700547 private void renderConversation(MessageCursor messageCursor) {
mindyp3bcf1802012-09-09 11:17:00 -0700548 final String convHtml = renderMessageBodies(messageCursor, mEnableContentReadySignal);
Andy Huang243c2362013-03-01 17:50:35 -0800549 timerMark("rendered conversation");
Andy Huangbd544e32012-05-29 15:56:51 -0700550
551 if (DEBUG_DUMP_CONVERSATION_HTML) {
552 java.io.FileWriter fw = null;
553 try {
554 fw = new java.io.FileWriter("/sdcard/conv" + mConversation.id
555 + ".html");
556 fw.write(convHtml);
557 } catch (java.io.IOException e) {
558 e.printStackTrace();
559 } finally {
560 if (fw != null) {
561 try {
562 fw.close();
563 } catch (java.io.IOException e) {
564 e.printStackTrace();
565 }
566 }
567 }
568 }
569
Andy Huange964eee2012-10-02 19:24:58 -0700570 // save off existing scroll position before re-rendering
571 if (mWebViewLoadedData) {
572 mWebViewYPercent = calculateScrollYPercent();
573 }
574
Andy Huangbd544e32012-05-29 15:56:51 -0700575 mWebView.loadDataWithBaseURL(mBaseUri, convHtml, "text/html", "utf-8", null);
Andy Huange964eee2012-10-02 19:24:58 -0700576 mWebViewLoadedData = true;
Andy Huang63b3c672012-10-05 19:27:28 -0700577 mWebViewLoadStartMs = SystemClock.uptimeMillis();
Andy Huang51067132012-03-12 20:08:19 -0700578 }
579
Andy Huang7bdc3752012-03-25 17:18:19 -0700580 /**
581 * Populate the adapter with overlay views (message headers, super-collapsed blocks, a
582 * conversation header), and return an HTML document with spacer divs inserted for all overlays.
583 *
584 */
mindyp3bcf1802012-09-09 11:17:00 -0700585 private String renderMessageBodies(MessageCursor messageCursor,
586 boolean enableContentReadySignal) {
Andy Huangf70fc402012-02-17 15:37:42 -0800587 int pos = -1;
Andy Huang632721e2012-04-11 16:57:26 -0700588
Andy Huang1ee96b22012-08-24 20:19:53 -0700589 LogUtils.d(LOG_TAG, "IN renderMessageBodies, fragment=%s", this);
Andy Huang7bdc3752012-03-25 17:18:19 -0700590 boolean allowNetworkImages = false;
591
Andy Huangc7543572012-04-03 15:34:29 -0700592 // TODO: re-use any existing adapter item state (expanded, details expanded, show pics)
Andy Huang28b7aee2012-08-20 20:27:32 -0700593
Andy Huang7bdc3752012-03-25 17:18:19 -0700594 // Walk through the cursor and build up an overlay adapter as you go.
595 // Each overlay has an entry in the adapter for easy scroll handling in the container.
596 // Items are not necessarily 1:1 in cursor and adapter because of super-collapsed blocks.
597 // When adding adapter items, also add their heights to help the container later determine
598 // overlay dimensions.
599
Andy Huangdb620fe2012-08-24 15:45:28 -0700600 // When re-rendering, prevent ConversationContainer from laying out overlays until after
601 // the new spacers are positioned by WebView.
602 mConversationContainer.invalidateSpacerGeometry();
603
Andy Huang7bdc3752012-03-25 17:18:19 -0700604 mAdapter.clear();
605
Andy Huang47aa9c92012-07-31 15:37:21 -0700606 // re-evaluate the message parts of the view state, since the messages may have changed
607 // since the previous render
608 final ConversationViewState prevState = mViewState;
609 mViewState = new ConversationViewState(prevState);
610
Andy Huang5ff63742012-03-16 20:30:23 -0700611 // N.B. the units of height for spacers are actually dp and not px because WebView assumes
Andy Huang2e9acfe2012-03-15 22:39:36 -0700612 // a pixel is an mdpi pixel, unless you set device-dpi.
Andy Huang5ff63742012-03-16 20:30:23 -0700613
Andy Huang7bdc3752012-03-25 17:18:19 -0700614 // add a single conversation header item
615 final int convHeaderPos = mAdapter.addConversationHeader(mConversation);
Andy Huang23014702012-07-09 12:50:36 -0700616 final int convHeaderPx = measureOverlayHeight(convHeaderPos);
Andy Huang5ff63742012-03-16 20:30:23 -0700617
Andy Huang02f9d182012-11-28 22:38:02 -0800618 mTemplates.startConversation(mWebView.screenPxToWebPx(mSideMarginPx),
Andy Huang256b35c2012-08-22 15:19:13 -0700619 mWebView.screenPxToWebPx(convHeaderPx));
Andy Huang3233bff2012-03-20 19:38:45 -0700620
Andy Huang46dfba62012-04-19 01:47:32 -0700621 int collapsedStart = -1;
Andy Huang839ada22012-07-20 15:48:40 -0700622 ConversationMessage prevCollapsedMsg = null;
Andy Huang46dfba62012-04-19 01:47:32 -0700623 boolean prevSafeForImages = false;
624
Andy Huangf70fc402012-02-17 15:37:42 -0800625 while (messageCursor.moveToPosition(++pos)) {
Andy Huang839ada22012-07-20 15:48:40 -0700626 final ConversationMessage msg = messageCursor.getMessage();
Andy Huang46dfba62012-04-19 01:47:32 -0700627
Scott Kennedy20273842012-11-07 11:16:21 -0800628 final boolean safeForImages =
629 msg.alwaysShowImages || prevState.getShouldShowImages(msg);
Andy Huang3233bff2012-03-20 19:38:45 -0700630 allowNetworkImages |= safeForImages;
Andy Huang24055282012-03-27 17:37:06 -0700631
Paul Westbrook08098ec2012-08-12 15:30:28 -0700632 final Integer savedExpanded = prevState.getExpansionState(msg);
633 final int expandedState;
Andy Huang839ada22012-07-20 15:48:40 -0700634 if (savedExpanded != null) {
Andy Huang1ee96b22012-08-24 20:19:53 -0700635 if (ExpansionState.isSuperCollapsed(savedExpanded) && messageCursor.isLast()) {
636 // override saved state when this is now the new last message
637 // this happens to the second-to-last message when you discard a draft
638 expandedState = ExpansionState.EXPANDED;
639 } else {
640 expandedState = savedExpanded;
641 }
Andy Huang839ada22012-07-20 15:48:40 -0700642 } else {
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700643 // new messages that are not expanded default to being eligible for super-collapse
Paul Westbrook08098ec2012-08-12 15:30:28 -0700644 expandedState = (!msg.read || msg.starred || messageCursor.isLast()) ?
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700645 ExpansionState.EXPANDED : ExpansionState.SUPER_COLLAPSED;
Andy Huang839ada22012-07-20 15:48:40 -0700646 }
Scott Kennedy20273842012-11-07 11:16:21 -0800647 mViewState.setShouldShowImages(msg, prevState.getShouldShowImages(msg));
Paul Westbrook08098ec2012-08-12 15:30:28 -0700648 mViewState.setExpansionState(msg, expandedState);
Andy Huangc7543572012-04-03 15:34:29 -0700649
Andy Huang839ada22012-07-20 15:48:40 -0700650 // save off "read" state from the cursor
651 // later, the view may not match the cursor (e.g. conversation marked read on open)
Andy Huang423bea22012-08-21 12:00:49 -0700652 // however, if a previous state indicated this message was unread, trust that instead
653 // so "mark unread" marks all originally unread messages
654 mViewState.setReadState(msg, msg.read && !prevState.isUnread(msg));
Andy Huang839ada22012-07-20 15:48:40 -0700655
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700656 // We only want to consider this for inclusion in the super collapsed block if
657 // 1) The we don't have previous state about this message (The first time that the
658 // user opens a conversation)
659 // 2) The previously saved state for this message indicates that this message is
660 // in the super collapsed block.
661 if (ExpansionState.isSuperCollapsed(expandedState)) {
662 // contribute to a super-collapsed block that will be emitted just before the
663 // next expanded header
664 if (collapsedStart < 0) {
665 collapsedStart = pos;
Andy Huang46dfba62012-04-19 01:47:32 -0700666 }
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700667 prevCollapsedMsg = msg;
668 prevSafeForImages = safeForImages;
Andrew Sapperstein7dc7fa02013-05-08 16:39:31 -0700669
670 // This line puts the from address in the address cache so that
671 // we get the sender image for it if it's in a super-collapsed block.
672 getAddress(msg.getFrom());
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700673 continue;
Andy Huang46dfba62012-04-19 01:47:32 -0700674 }
Andy Huang24055282012-03-27 17:37:06 -0700675
Andy Huang46dfba62012-04-19 01:47:32 -0700676 // resolve any deferred decisions on previous collapsed items
677 if (collapsedStart >= 0) {
678 if (pos - collapsedStart == 1) {
679 // special-case for a single collapsed message: no need to super-collapse it
680 renderMessage(prevCollapsedMsg, false /* expanded */,
681 prevSafeForImages);
682 } else {
683 renderSuperCollapsedBlock(collapsedStart, pos - 1);
684 }
685 prevCollapsedMsg = null;
686 collapsedStart = -1;
687 }
Andy Huang7bdc3752012-03-25 17:18:19 -0700688
Paul Westbrook08098ec2012-08-12 15:30:28 -0700689 renderMessage(msg, ExpansionState.isExpanded(expandedState), safeForImages);
Mindy Pereira9b875682012-02-15 18:10:54 -0800690 }
Andy Huang3233bff2012-03-20 19:38:45 -0700691
692 mWebView.getSettings().setBlockNetworkImage(!allowNetworkImages);
693
Andrew Sapperstein2fc67302013-04-29 18:24:56 -0700694 final boolean applyTransforms = shouldApplyTransforms();
Andy Huang57f354c2013-04-11 17:23:40 -0700695
Andy Huang0180f272013-03-08 18:33:22 -0800696 final MailPrefs prefs = MailPrefs.get(getContext());
Andrew Sapperstein2fc67302013-04-29 18:24:56 -0700697
Andy Huangc1fb9a92013-02-11 13:09:12 -0800698 // If the conversation has specified a base uri, use it here, otherwise use mBaseUri
699 return mTemplates.endConversation(mBaseUri, mConversation.getBaseUri(mBaseUri), 320,
Andy Huang5ea5a832013-03-07 16:49:09 -0800700 mWebView.getViewportWidth(), enableContentReadySignal, isOverviewMode(mAccount),
Andy Huang57f354c2013-04-11 17:23:40 -0700701 applyTransforms, applyTransforms);
Mindy Pereira9b875682012-02-15 18:10:54 -0800702 }
Mindy Pereira674afa42012-02-17 14:05:24 -0800703
Andy Huang46dfba62012-04-19 01:47:32 -0700704 private void renderSuperCollapsedBlock(int start, int end) {
705 final int blockPos = mAdapter.addSuperCollapsedBlock(start, end);
Andy Huang23014702012-07-09 12:50:36 -0700706 final int blockPx = measureOverlayHeight(blockPos);
707 mTemplates.appendSuperCollapsedHtml(start, mWebView.screenPxToWebPx(blockPx));
Andy Huang46dfba62012-04-19 01:47:32 -0700708 }
709
Andy Huang839ada22012-07-20 15:48:40 -0700710 private void renderMessage(ConversationMessage msg, boolean expanded,
711 boolean safeForImages) {
Scott Kennedy20273842012-11-07 11:16:21 -0800712 final int headerPos = mAdapter.addMessageHeader(msg, expanded,
713 mViewState.getShouldShowImages(msg));
Andy Huang46dfba62012-04-19 01:47:32 -0700714 final MessageHeaderItem headerItem = (MessageHeaderItem) mAdapter.getItem(headerPos);
715
716 final int footerPos = mAdapter.addMessageFooter(headerItem);
717
718 // Measure item header and footer heights to allocate spacers in HTML
719 // But since the views themselves don't exist yet, render each item temporarily into
720 // a host view for measurement.
Andy Huang23014702012-07-09 12:50:36 -0700721 final int headerPx = measureOverlayHeight(headerPos);
722 final int footerPx = measureOverlayHeight(footerPos);
Andy Huang46dfba62012-04-19 01:47:32 -0700723
Andy Huang256b35c2012-08-22 15:19:13 -0700724 mTemplates.appendMessageHtml(msg, expanded, safeForImages,
Andy Huang23014702012-07-09 12:50:36 -0700725 mWebView.screenPxToWebPx(headerPx), mWebView.screenPxToWebPx(footerPx));
Andy Huang243c2362013-03-01 17:50:35 -0800726 timerMark("rendered message");
Andy Huang46dfba62012-04-19 01:47:32 -0700727 }
728
729 private String renderCollapsedHeaders(MessageCursor cursor,
730 SuperCollapsedBlockItem blockToReplace) {
731 final List<ConversationOverlayItem> replacements = Lists.newArrayList();
732
733 mTemplates.reset();
734
Mark Wei2b24e992012-09-10 16:40:07 -0700735 // In devices with non-integral density multiplier, screen pixels translate to non-integral
736 // web pixels. Keep track of the error that occurs when we cast all heights to int
737 float error = 0f;
Andy Huang46dfba62012-04-19 01:47:32 -0700738 for (int i = blockToReplace.getStart(), end = blockToReplace.getEnd(); i <= end; i++) {
739 cursor.moveToPosition(i);
Andy Huang839ada22012-07-20 15:48:40 -0700740 final ConversationMessage msg = cursor.getMessage();
Andy Huang46dfba62012-04-19 01:47:32 -0700741 final MessageHeaderItem header = mAdapter.newMessageHeaderItem(msg,
Scott Kennedy20273842012-11-07 11:16:21 -0800742 false /* expanded */, mViewState.getShouldShowImages(msg));
Andy Huang46dfba62012-04-19 01:47:32 -0700743 final MessageFooterItem footer = mAdapter.newMessageFooterItem(header);
744
Andy Huang23014702012-07-09 12:50:36 -0700745 final int headerPx = measureOverlayHeight(header);
746 final int footerPx = measureOverlayHeight(footer);
Mark Wei2b24e992012-09-10 16:40:07 -0700747 error += mWebView.screenPxToWebPxError(headerPx)
748 + mWebView.screenPxToWebPxError(footerPx);
749
750 // When the error becomes greater than 1 pixel, make the next header 1 pixel taller
751 int correction = 0;
752 if (error >= 1) {
753 correction = 1;
754 error -= 1;
755 }
Andy Huang46dfba62012-04-19 01:47:32 -0700756
Andy Huang256b35c2012-08-22 15:19:13 -0700757 mTemplates.appendMessageHtml(msg, false /* expanded */, msg.alwaysShowImages,
Mark Wei2b24e992012-09-10 16:40:07 -0700758 mWebView.screenPxToWebPx(headerPx) + correction,
759 mWebView.screenPxToWebPx(footerPx));
Andy Huang46dfba62012-04-19 01:47:32 -0700760 replacements.add(header);
761 replacements.add(footer);
Andy Huang839ada22012-07-20 15:48:40 -0700762
Paul Westbrook08098ec2012-08-12 15:30:28 -0700763 mViewState.setExpansionState(msg, ExpansionState.COLLAPSED);
Andy Huang46dfba62012-04-19 01:47:32 -0700764 }
765
766 mAdapter.replaceSuperCollapsedBlock(blockToReplace, replacements);
Andy Huang06c03622012-10-22 18:59:45 -0700767 mAdapter.notifyDataSetChanged();
Andy Huang46dfba62012-04-19 01:47:32 -0700768
769 return mTemplates.emit();
770 }
771
772 private int measureOverlayHeight(int position) {
773 return measureOverlayHeight(mAdapter.getItem(position));
774 }
775
Andy Huang7bdc3752012-03-25 17:18:19 -0700776 /**
Andy Huangb8331b42012-07-16 19:08:53 -0700777 * Measure the height of an adapter view by rendering an adapter item into a temporary
Andy Huang46dfba62012-04-19 01:47:32 -0700778 * host view, and asking the view to immediately measure itself. This method will reuse
Andy Huang7bdc3752012-03-25 17:18:19 -0700779 * a previous adapter view from {@link ConversationContainer}'s scrap views if one was generated
780 * earlier.
781 * <p>
Andy Huang46dfba62012-04-19 01:47:32 -0700782 * After measuring the height, this method also saves the height in the
783 * {@link ConversationOverlayItem} for later use in overlay positioning.
Andy Huang7bdc3752012-03-25 17:18:19 -0700784 *
Andy Huang46dfba62012-04-19 01:47:32 -0700785 * @param convItem adapter item with data to render and measure
Andy Huang23014702012-07-09 12:50:36 -0700786 * @return height of the rendered view in screen px
Andy Huang7bdc3752012-03-25 17:18:19 -0700787 */
Andy Huang46dfba62012-04-19 01:47:32 -0700788 private int measureOverlayHeight(ConversationOverlayItem convItem) {
Andy Huang7bdc3752012-03-25 17:18:19 -0700789 final int type = convItem.getType();
790
791 final View convertView = mConversationContainer.getScrapView(type);
Andy Huangb8331b42012-07-16 19:08:53 -0700792 final View hostView = mAdapter.getView(convItem, convertView, mConversationContainer,
793 true /* measureOnly */);
Andy Huang7bdc3752012-03-25 17:18:19 -0700794 if (convertView == null) {
795 mConversationContainer.addScrapView(type, hostView);
796 }
797
Andy Huang9875bb42012-04-04 20:36:21 -0700798 final int heightPx = mConversationContainer.measureOverlay(hostView);
Andy Huang7bdc3752012-03-25 17:18:19 -0700799 convItem.setHeight(heightPx);
Andy Huang9875bb42012-04-04 20:36:21 -0700800 convItem.markMeasurementValid();
Andy Huang7bdc3752012-03-25 17:18:19 -0700801
Andy Huang23014702012-07-09 12:50:36 -0700802 return heightPx;
Andy Huang7bdc3752012-03-25 17:18:19 -0700803 }
804
Andy Huang5ff63742012-03-16 20:30:23 -0700805 @Override
806 public void onConversationViewHeaderHeightChange(int newHeight) {
Mark Weiab2d9982012-09-25 13:06:17 -0700807 final int h = mWebView.screenPxToWebPx(newHeight);
808
809 mWebView.loadUrl(String.format("javascript:setConversationHeaderSpacerHeight(%s);", h));
Andy Huang5ff63742012-03-16 20:30:23 -0700810 }
811
Andy Huang3233bff2012-03-20 19:38:45 -0700812 // END conversation header callbacks
813
814 // START message header callbacks
815 @Override
Andy Huangc7543572012-04-03 15:34:29 -0700816 public void setMessageSpacerHeight(MessageHeaderItem item, int newSpacerHeightPx) {
817 mConversationContainer.invalidateSpacerGeometry();
818
819 // update message HTML spacer height
Andy Huang23014702012-07-09 12:50:36 -0700820 final int h = mWebView.screenPxToWebPx(newSpacerHeightPx);
821 LogUtils.i(LAYOUT_TAG, "setting HTML spacer h=%dwebPx (%dscreenPx)", h,
822 newSpacerHeightPx);
Vikram Aggarwal5349ce12012-09-24 14:12:40 -0700823 mWebView.loadUrl(String.format("javascript:setMessageHeaderSpacerHeight('%s', %s);",
Andy Huang014ea4c2012-09-25 14:50:54 -0700824 mTemplates.getMessageDomId(item.getMessage()), h));
Andy Huang3233bff2012-03-20 19:38:45 -0700825 }
826
827 @Override
Andy Huangc7543572012-04-03 15:34:29 -0700828 public void setMessageExpanded(MessageHeaderItem item, int newSpacerHeightPx) {
829 mConversationContainer.invalidateSpacerGeometry();
830
831 // show/hide the HTML message body and update the spacer height
Andy Huang23014702012-07-09 12:50:36 -0700832 final int h = mWebView.screenPxToWebPx(newSpacerHeightPx);
833 LogUtils.i(LAYOUT_TAG, "setting HTML spacer expanded=%s h=%dwebPx (%dscreenPx)",
834 item.isExpanded(), h, newSpacerHeightPx);
Vikram Aggarwal5349ce12012-09-24 14:12:40 -0700835 mWebView.loadUrl(String.format("javascript:setMessageBodyVisible('%s', %s, %s);",
Andy Huang014ea4c2012-09-25 14:50:54 -0700836 mTemplates.getMessageDomId(item.getMessage()), item.isExpanded(), h));
Andy Huang839ada22012-07-20 15:48:40 -0700837
Andy Huang014ea4c2012-09-25 14:50:54 -0700838 mViewState.setExpansionState(item.getMessage(),
Paul Westbrook08098ec2012-08-12 15:30:28 -0700839 item.isExpanded() ? ExpansionState.EXPANDED : ExpansionState.COLLAPSED);
Andy Huang3233bff2012-03-20 19:38:45 -0700840 }
841
842 @Override
Scott Kennedyeb9a4bd2012-11-12 10:33:04 -0800843 public void showExternalResources(final Message msg) {
Scott Kennedy20273842012-11-07 11:16:21 -0800844 mViewState.setShouldShowImages(msg, true);
Andy Huang3233bff2012-03-20 19:38:45 -0700845 mWebView.getSettings().setBlockNetworkImage(false);
Scott Kennedyeb9a4bd2012-11-12 10:33:04 -0800846 mWebView.loadUrl("javascript:unblockImages(['" + mTemplates.getMessageDomId(msg) + "']);");
847 }
848
849 @Override
850 public void showExternalResources(final String senderRawAddress) {
851 mWebView.getSettings().setBlockNetworkImage(false);
852
853 final Address sender = getAddress(senderRawAddress);
854 final MessageCursor cursor = getMessageCursor();
855
856 final List<String> messageDomIds = new ArrayList<String>();
857
858 int pos = -1;
859 while (cursor.moveToPosition(++pos)) {
860 final ConversationMessage message = cursor.getMessage();
861 if (sender.equals(getAddress(message.getFrom()))) {
862 message.alwaysShowImages = true;
863
864 mViewState.setShouldShowImages(message, true);
865 messageDomIds.add(mTemplates.getMessageDomId(message));
866 }
867 }
868
869 final String url = String.format(
870 "javascript:unblockImages(['%s']);", TextUtils.join("','", messageDomIds));
871 mWebView.loadUrl(url);
Andy Huang3233bff2012-03-20 19:38:45 -0700872 }
Alice Yang1ebc2db2013-03-14 21:21:44 -0700873
874 @Override
Andy Huang75b52a52013-03-15 15:40:24 -0700875 public boolean supportsMessageTransforms() {
876 return true;
877 }
878
879 @Override
Alice Yang1ebc2db2013-03-14 21:21:44 -0700880 public String getMessageTransforms(final Message msg) {
881 final String domId = mTemplates.getMessageDomId(msg);
882 return (domId == null) ? null : mMessageTransforms.get(domId);
883 }
884
Andy Huang3233bff2012-03-20 19:38:45 -0700885 // END message header callbacks
Andy Huang5ff63742012-03-16 20:30:23 -0700886
Andy Huang46dfba62012-04-19 01:47:32 -0700887 @Override
Andrew Sapperstein2fc67302013-04-29 18:24:56 -0700888 public void showUntransformedConversation() {
889 super.showUntransformedConversation();
890 renderConversation(getMessageCursor());
891 }
892
893 @Override
Andy Huang46dfba62012-04-19 01:47:32 -0700894 public void onSuperCollapsedClick(SuperCollapsedBlockItem item) {
mindypf4fce122012-09-14 15:55:33 -0700895 MessageCursor cursor = getMessageCursor();
896 if (cursor == null || !mViewsCreated) {
Andy Huang46dfba62012-04-19 01:47:32 -0700897 return;
898 }
899
mindypf4fce122012-09-14 15:55:33 -0700900 mTempBodiesHtml = renderCollapsedHeaders(cursor, item);
Andy Huang46dfba62012-04-19 01:47:32 -0700901 mWebView.loadUrl("javascript:replaceSuperCollapsedBlock(" + item.getStart() + ")");
902 }
903
Andy Huang47aa9c92012-07-31 15:37:21 -0700904 private void showNewMessageNotification(NewMessagesInfo info) {
905 final TextView descriptionView = (TextView) mNewMessageBar.findViewById(
906 R.id.new_message_description);
907 descriptionView.setText(info.getNotificationText());
908 mNewMessageBar.setVisibility(View.VISIBLE);
909 }
910
911 private void onNewMessageBarClick() {
912 mNewMessageBar.setVisibility(View.GONE);
913
mindypf4fce122012-09-14 15:55:33 -0700914 renderConversation(getMessageCursor()); // mCursor is already up-to-date
915 // per onLoadFinished()
Andy Huang5fbda022012-02-28 18:22:03 -0800916 }
917
Andy Huangadbf3e82012-10-13 13:30:19 -0700918 private static OverlayPosition[] parsePositions(final String[] topArray,
919 final String[] bottomArray) {
920 final int len = topArray.length;
921 final OverlayPosition[] positions = new OverlayPosition[len];
Andy Huangb5078b22012-03-05 19:52:29 -0800922 for (int i = 0; i < len; i++) {
Andy Huangadbf3e82012-10-13 13:30:19 -0700923 positions[i] = new OverlayPosition(
924 Integer.parseInt(topArray[i]), Integer.parseInt(bottomArray[i]));
Andy Huangb5078b22012-03-05 19:52:29 -0800925 }
Andy Huangadbf3e82012-10-13 13:30:19 -0700926 return positions;
Andy Huangb5078b22012-03-05 19:52:29 -0800927 }
928
Andy Huang16174812012-08-16 16:40:35 -0700929 private Address getAddress(String rawFrom) {
Andy Huang543e7092013-04-22 11:44:56 -0700930 Address addr;
931 synchronized (mAddressCache) {
932 addr = mAddressCache.get(rawFrom);
933 if (addr == null) {
934 addr = Address.getEmailAddress(rawFrom);
935 mAddressCache.put(rawFrom, addr);
936 }
Andy Huang16174812012-08-16 16:40:35 -0700937 }
938 return addr;
939 }
940
Andy Huang9d3fd922012-09-26 22:23:58 -0700941 private void ensureContentSizeChangeListener() {
942 if (mWebViewSizeChangeListener == null) {
Andy Huangc1fb9a92013-02-11 13:09:12 -0800943 mWebViewSizeChangeListener = new ContentSizeChangeListener() {
Andy Huang9d3fd922012-09-26 22:23:58 -0700944 @Override
945 public void onHeightChange(int h) {
946 // When WebKit says the DOM height has changed, re-measure
947 // bodies and re-position their headers.
948 // This is separate from the typical JavaScript DOM change
949 // listeners because cases like NARROW_COLUMNS text reflow do not trigger DOM
950 // events.
951 mWebView.loadUrl("javascript:measurePositions();");
952 }
953 };
954 }
955 mWebView.setContentSizeChangeListener(mWebViewSizeChangeListener);
956 }
957
Andy Huangadbf3e82012-10-13 13:30:19 -0700958 private static boolean isOverviewMode(Account acct) {
Andy Huangccf67802013-03-15 14:31:57 -0700959 return acct.settings.isOverviewMode();
Andy Huangadbf3e82012-10-13 13:30:19 -0700960 }
961
962 private void setupOverviewMode() {
Andy Huang02f9d182012-11-28 22:38:02 -0800963 // for now, overview mode means use the built-in WebView zoom and disable custom scale
964 // gesture handling
Andy Huangadbf3e82012-10-13 13:30:19 -0700965 final boolean overviewMode = isOverviewMode(mAccount);
966 final WebSettings settings = mWebView.getSettings();
Andy Huang06def562012-10-14 00:19:11 -0700967 settings.setUseWideViewPort(overviewMode);
Andy Huangc1fb9a92013-02-11 13:09:12 -0800968
969 final OnScaleGestureListener listener;
970
Andy Huang57f354c2013-04-11 17:23:40 -0700971 settings.setSupportZoom(overviewMode);
972 settings.setBuiltInZoomControls(overviewMode);
973 if (overviewMode) {
974 settings.setDisplayZoomControls(false);
Andy Huangadbf3e82012-10-13 13:30:19 -0700975 }
Andy Huang57f354c2013-04-11 17:23:40 -0700976 listener = ENABLE_CSS_ZOOM && !overviewMode ? new CssScaleInterceptor() : null;
Andy Huangc1fb9a92013-02-11 13:09:12 -0800977
Andy Huang57f354c2013-04-11 17:23:40 -0700978 mWebView.setOnScaleGestureListener(listener);
Andy Huangadbf3e82012-10-13 13:30:19 -0700979 }
980
Paul Westbrook542fec92012-09-18 14:47:51 -0700981 private class ConversationWebViewClient extends AbstractConversationWebViewClient {
Andy Huang17a9cde2012-03-09 18:03:16 -0800982 @Override
983 public void onPageFinished(WebView view, String url) {
Andy Huang9a8bc1e2012-10-23 19:48:25 -0700984 // Ignore unsafe calls made after a fragment is detached from an activity.
985 // This method needs to, for example, get at the loader manager, which needs
986 // the fragment to be added.
Andy Huang9a8bc1e2012-10-23 19:48:25 -0700987 if (!isAdded() || !mViewsCreated) {
Andy Huangde56e972012-07-26 18:23:08 -0700988 LogUtils.i(LOG_TAG, "ignoring CVF.onPageFinished, url=%s fragment=%s", url,
Andy Huangb95da852012-07-18 14:16:58 -0700989 ConversationViewFragment.this);
990 return;
991 }
992
Andy Huang30bcfe72012-10-18 18:09:03 -0700993 LogUtils.i(LOG_TAG, "IN CVF.onPageFinished, url=%s fragment=%s wv=%s t=%sms", url,
994 ConversationViewFragment.this, view,
Andy Huang63b3c672012-10-05 19:27:28 -0700995 (SystemClock.uptimeMillis() - mWebViewLoadStartMs));
Andy Huang632721e2012-04-11 16:57:26 -0700996
Andy Huang9d3fd922012-09-26 22:23:58 -0700997 ensureContentSizeChangeListener();
998
mindyp3bcf1802012-09-09 11:17:00 -0700999 if (!mEnableContentReadySignal) {
Andy Huang7d4746e2012-10-17 17:03:17 -07001000 revealConversation();
mindyp3bcf1802012-09-09 11:17:00 -07001001 }
Andy Huang9d3fd922012-09-26 22:23:58 -07001002
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001003 final Set<String> emailAddresses = Sets.newHashSet();
Andy Huang543e7092013-04-22 11:44:56 -07001004 final List<Address> cacheCopy;
1005 synchronized (mAddressCache) {
1006 cacheCopy = ImmutableList.copyOf(mAddressCache.values());
1007 }
1008 for (Address addr : cacheCopy) {
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001009 emailAddresses.add(addr.getAddress());
Andy Huangb8331b42012-07-16 19:08:53 -07001010 }
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001011 ContactLoaderCallbacks callbacks = getContactInfoSource();
1012 getContactInfoSource().setSenders(emailAddresses);
1013 getLoaderManager().restartLoader(CONTACT_LOADER, Bundle.EMPTY, callbacks);
Andy Huang17a9cde2012-03-09 18:03:16 -08001014 }
1015
Andy Huangaf5d4e02012-03-19 19:02:12 -07001016 @Override
1017 public boolean shouldOverrideUrlLoading(WebView view, String url) {
Paul Westbrook542fec92012-09-18 14:47:51 -07001018 return mViewsCreated && super.shouldOverrideUrlLoading(view, url);
Andy Huangaf5d4e02012-03-19 19:02:12 -07001019 }
Andy Huang17a9cde2012-03-09 18:03:16 -08001020 }
1021
Andy Huangf70fc402012-02-17 15:37:42 -08001022 /**
1023 * NOTE: all public methods must be listed in the proguard flags so that they can be accessed
1024 * via reflection and not stripped.
1025 *
1026 */
1027 private class MailJsBridge {
1028
1029 @SuppressWarnings("unused")
Mindy Pereira974c9662012-09-14 10:02:08 -07001030 @JavascriptInterface
Andy Huangadbf3e82012-10-13 13:30:19 -07001031 public void onWebContentGeometryChange(final String[] overlayTopStrs,
1032 final String[] overlayBottomStrs) {
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001033 getHandler().post(new FragmentRunnable("onWebContentGeometryChange") {
mindyp1b3cc472012-09-27 11:32:59 -07001034
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001035 @Override
1036 public void go() {
1037 try {
Andy Huang46dfba62012-04-19 01:47:32 -07001038 if (!mViewsCreated) {
mindyp1b3cc472012-09-27 11:32:59 -07001039 LogUtils.d(LOG_TAG, "ignoring webContentGeometryChange because views"
1040 + " are gone, %s", ConversationViewFragment.this);
Andy Huang46dfba62012-04-19 01:47:32 -07001041 return;
1042 }
Andy Huangadbf3e82012-10-13 13:30:19 -07001043 mConversationContainer.onGeometryChange(
1044 parsePositions(overlayTopStrs, overlayBottomStrs));
mindyp1b3cc472012-09-27 11:32:59 -07001045 if (mDiff != 0) {
1046 // SCROLL!
1047 int scale = (int) (mWebView.getScale() / mWebView.getInitialScale());
1048 if (scale > 1) {
1049 mWebView.scrollBy(0, (mDiff * (scale - 1)));
1050 }
1051 mDiff = 0;
1052 }
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001053 } catch (Throwable t) {
1054 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onWebContentGeometryChange");
Andy Huang46dfba62012-04-19 01:47:32 -07001055 }
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001056 }
1057 });
Andy Huang46dfba62012-04-19 01:47:32 -07001058 }
1059
1060 @SuppressWarnings("unused")
Mindy Pereira974c9662012-09-14 10:02:08 -07001061 @JavascriptInterface
Andy Huang46dfba62012-04-19 01:47:32 -07001062 public String getTempMessageBodies() {
1063 try {
1064 if (!mViewsCreated) {
1065 return "";
Andy Huangf70fc402012-02-17 15:37:42 -08001066 }
Andy Huang46dfba62012-04-19 01:47:32 -07001067
1068 final String s = mTempBodiesHtml;
1069 mTempBodiesHtml = null;
1070 return s;
1071 } catch (Throwable t) {
1072 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getTempMessageBodies");
1073 return "";
1074 }
Andy Huangf70fc402012-02-17 15:37:42 -08001075 }
1076
Andy Huang014ea4c2012-09-25 14:50:54 -07001077 @SuppressWarnings("unused")
1078 @JavascriptInterface
1079 public String getMessageBody(String domId) {
1080 try {
1081 final MessageCursor cursor = getMessageCursor();
1082 if (!mViewsCreated || cursor == null) {
1083 return "";
1084 }
1085
1086 int pos = -1;
1087 while (cursor.moveToPosition(++pos)) {
1088 final ConversationMessage msg = cursor.getMessage();
1089 if (TextUtils.equals(domId, mTemplates.getMessageDomId(msg))) {
1090 return msg.getBodyAsHtml();
1091 }
1092 }
1093
1094 return "";
1095
1096 } catch (Throwable t) {
1097 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getMessageBody");
1098 return "";
1099 }
1100 }
1101
mindyp3bcf1802012-09-09 11:17:00 -07001102 @SuppressWarnings("unused")
Mindy Pereira974c9662012-09-14 10:02:08 -07001103 @JavascriptInterface
Andy Huang543e7092013-04-22 11:44:56 -07001104 public String getMessageSender(String domId) {
1105 try {
1106 final MessageCursor cursor = getMessageCursor();
1107 if (!mViewsCreated || cursor == null) {
1108 return "";
1109 }
1110
1111 int pos = -1;
1112 while (cursor.moveToPosition(++pos)) {
1113 final ConversationMessage msg = cursor.getMessage();
1114 if (TextUtils.equals(domId, mTemplates.getMessageDomId(msg))) {
1115 return getAddress(msg.getFrom()).getAddress();
1116 }
1117 }
1118
1119 return "";
1120
1121 } catch (Throwable t) {
1122 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getMessageSender");
1123 return "";
1124 }
1125 }
1126
1127 @SuppressWarnings("unused")
1128 @JavascriptInterface
mindyp3bcf1802012-09-09 11:17:00 -07001129 public void onContentReady() {
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001130 getHandler().post(new FragmentRunnable("onContentReady") {
1131 @Override
1132 public void go() {
1133 try {
Andy Huang63b3c672012-10-05 19:27:28 -07001134 if (mWebViewLoadStartMs != 0) {
1135 LogUtils.i(LOG_TAG, "IN CVF.onContentReady, f=%s vis=%s t=%sms",
1136 ConversationViewFragment.this,
1137 isUserVisible(),
1138 (SystemClock.uptimeMillis() - mWebViewLoadStartMs));
1139 }
Andy Huang7d4746e2012-10-17 17:03:17 -07001140 revealConversation();
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001141 } catch (Throwable t) {
1142 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onContentReady");
1143 // Still try to show the conversation.
1144 revealConversation();
mindyp3bcf1802012-09-09 11:17:00 -07001145 }
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001146 }
1147 });
mindyp3bcf1802012-09-09 11:17:00 -07001148 }
Andy Huange964eee2012-10-02 19:24:58 -07001149
1150 @SuppressWarnings("unused")
1151 @JavascriptInterface
1152 public float getScrollYPercent() {
1153 try {
1154 return mWebViewYPercent;
1155 } catch (Throwable t) {
1156 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getScrollYPercent");
1157 return 0f;
1158 }
1159 }
Andy Huang05c70c82013-03-14 15:15:50 -07001160
1161 @SuppressWarnings("unused")
1162 @JavascriptInterface
1163 public void onMessageTransform(String messageDomId, String transformText) {
Andrew Sappersteinae92e152013-05-03 13:55:18 -07001164 try {
1165 LogUtils.i(LOG_TAG, "TRANSFORM: (%s) %s", messageDomId, transformText);
1166 mMessageTransforms.put(messageDomId, transformText);
1167 onConversationTransformed();
1168 } catch (Throwable t) {
1169 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onMessageTransform");
1170 return;
1171 }
Andy Huang05c70c82013-03-14 15:15:50 -07001172 }
Andy Huangf70fc402012-02-17 15:37:42 -08001173 }
1174
Andy Huang47aa9c92012-07-31 15:37:21 -07001175 private class NewMessagesInfo {
1176 int count;
Andy Huang06c03622012-10-22 18:59:45 -07001177 int countFromSelf;
Andy Huang47aa9c92012-07-31 15:37:21 -07001178 String senderAddress;
1179
1180 /**
1181 * Return the display text for the new message notification overlay. It will be formatted
1182 * appropriately for a single new message vs. multiple new messages.
1183 *
1184 * @return display text
1185 */
1186 public String getNotificationText() {
mindypad0c30d2012-09-25 12:09:13 -07001187 Resources res = getResources();
Andy Huang47aa9c92012-07-31 15:37:21 -07001188 if (count > 1) {
mindypad0c30d2012-09-25 12:09:13 -07001189 return res.getString(R.string.new_incoming_messages_many, count);
Andy Huang47aa9c92012-07-31 15:37:21 -07001190 } else {
Andy Huang16174812012-08-16 16:40:35 -07001191 final Address addr = getAddress(senderAddress);
mindypad0c30d2012-09-25 12:09:13 -07001192 return res.getString(R.string.new_incoming_messages_one,
1193 TextUtils.isEmpty(addr.getName()) ? addr.getAddress() : addr.getName());
Andy Huang47aa9c92012-07-31 15:37:21 -07001194 }
Andy Huang47aa9c92012-07-31 15:37:21 -07001195 }
1196 }
1197
mindypf4fce122012-09-14 15:55:33 -07001198 @Override
Paul Westbrookc42ad5e2013-05-09 16:52:15 -07001199 public void onMessageCursorLoadFinished(Loader<ObjectCursor<ConversationMessage>> loader,
1200 MessageCursor newCursor, MessageCursor oldCursor) {
mindypf4fce122012-09-14 15:55:33 -07001201 /*
1202 * what kind of changes affect the MessageCursor? 1. new message(s) 2.
1203 * read/unread state change 3. deleted message, either regular or draft
1204 * 4. updated message, either from self or from others, updated in
1205 * content or state or sender 5. star/unstar of message (technically
1206 * similar to #1) 6. other label change Use MessageCursor.hashCode() to
1207 * sort out interesting vs. no-op cursor updates.
1208 */
Andy Huangb8331b42012-07-16 19:08:53 -07001209
Andy Huang233d4352012-10-18 14:00:24 -07001210 if (oldCursor != null && !oldCursor.isClosed()) {
Andy Huang014ea4c2012-09-25 14:50:54 -07001211 final NewMessagesInfo info = getNewIncomingMessagesInfo(newCursor);
Andy Huangb8331b42012-07-16 19:08:53 -07001212
Andy Huang014ea4c2012-09-25 14:50:54 -07001213 if (info.count > 0) {
1214 // don't immediately render new incoming messages from other
1215 // senders
1216 // (to avoid a new message from losing the user's focus)
1217 LogUtils.i(LOG_TAG, "CONV RENDER: conversation updated"
Andy Huang9d3fd922012-09-26 22:23:58 -07001218 + ", holding cursor for new incoming message (%s)", this);
Andy Huang014ea4c2012-09-25 14:50:54 -07001219 showNewMessageNotification(info);
1220 return;
1221 }
1222
Andy Huang06c03622012-10-22 18:59:45 -07001223 final int oldState = oldCursor.getStateHashCode();
1224 final boolean changed = newCursor.getStateHashCode() != oldState;
Andy Huang233d4352012-10-18 14:00:24 -07001225
Andy Huang014ea4c2012-09-25 14:50:54 -07001226 if (!changed) {
1227 final boolean processedInPlace = processInPlaceUpdates(newCursor, oldCursor);
1228 if (processedInPlace) {
Andy Huang9d3fd922012-09-26 22:23:58 -07001229 LogUtils.i(LOG_TAG, "CONV RENDER: processed update(s) in place (%s)", this);
Andy Huang1ee96b22012-08-24 20:19:53 -07001230 } else {
mindypf4fce122012-09-14 15:55:33 -07001231 LogUtils.i(LOG_TAG, "CONV RENDER: uninteresting update"
Andy Huang9d3fd922012-09-26 22:23:58 -07001232 + ", ignoring this conversation update (%s)", this);
Andy Huang1ee96b22012-08-24 20:19:53 -07001233 }
Andy Huangb8331b42012-07-16 19:08:53 -07001234 return;
Andy Huang06c03622012-10-22 18:59:45 -07001235 } else if (info.countFromSelf == 1) {
1236 // Special-case the very common case of a new cursor that is the same as the old
1237 // one, except that there is a new message from yourself. This happens upon send.
1238 final boolean sameExceptNewLast = newCursor.getStateHashCode(1) == oldState;
1239 if (sameExceptNewLast) {
1240 LogUtils.i(LOG_TAG, "CONV RENDER: update is a single new message from self"
1241 + " (%s)", this);
1242 newCursor.moveToLast();
1243 processNewOutgoingMessage(newCursor.getMessage());
1244 return;
1245 }
Andy Huangb8331b42012-07-16 19:08:53 -07001246 }
Andy Huang6766b6e2012-09-28 12:43:52 -07001247 // cursors are different, and not due to an incoming message. fall
1248 // through and render.
1249 LogUtils.i(LOG_TAG, "CONV RENDER: conversation updated"
1250 + ", but not due to incoming message. rendering. (%s)", this);
Andy Huang06c03622012-10-22 18:59:45 -07001251
1252 if (DEBUG_DUMP_CURSOR_CONTENTS) {
1253 LogUtils.i(LOG_TAG, "old cursor: %s", oldCursor.getDebugDump());
1254 LogUtils.i(LOG_TAG, "new cursor: %s", newCursor.getDebugDump());
1255 }
Andy Huang6766b6e2012-09-28 12:43:52 -07001256 } else {
1257 LogUtils.i(LOG_TAG, "CONV RENDER: initial render. (%s)", this);
Andy Huang243c2362013-03-01 17:50:35 -08001258 timerMark("message cursor load finished");
Andy Huangb8331b42012-07-16 19:08:53 -07001259 }
1260
Mark Wei4071c2f2012-09-26 14:38:38 -07001261 // if layout hasn't happened, delay render
1262 // This is needed in addition to the showConversation() delay to speed
1263 // up rotation and restoration.
1264 if (mConversationContainer.getWidth() == 0) {
1265 mNeedRender = true;
1266 mConversationContainer.addOnLayoutChangeListener(this);
1267 } else {
1268 renderConversation(newCursor);
1269 }
Andy Huangb8331b42012-07-16 19:08:53 -07001270 }
1271
mindypf4fce122012-09-14 15:55:33 -07001272 private NewMessagesInfo getNewIncomingMessagesInfo(MessageCursor newCursor) {
1273 final NewMessagesInfo info = new NewMessagesInfo();
Andy Huangb8331b42012-07-16 19:08:53 -07001274
mindypf4fce122012-09-14 15:55:33 -07001275 int pos = -1;
1276 while (newCursor.moveToPosition(++pos)) {
1277 final Message m = newCursor.getMessage();
1278 if (!mViewState.contains(m)) {
1279 LogUtils.i(LOG_TAG, "conversation diff: found new msg: %s", m.uri);
Andy Huangb8331b42012-07-16 19:08:53 -07001280
Scott Kennedy8960f0a2012-11-07 15:35:50 -08001281 final Address from = getAddress(m.getFrom());
mindypf4fce122012-09-14 15:55:33 -07001282 // distinguish ours from theirs
1283 // new messages from the account owner should not trigger a
1284 // notification
1285 if (mAccount.ownsFromAddress(from.getAddress())) {
1286 LogUtils.i(LOG_TAG, "found message from self: %s", m.uri);
Andy Huang06c03622012-10-22 18:59:45 -07001287 info.countFromSelf++;
mindypf4fce122012-09-14 15:55:33 -07001288 continue;
1289 }
Andy Huangb8331b42012-07-16 19:08:53 -07001290
mindypf4fce122012-09-14 15:55:33 -07001291 info.count++;
Scott Kennedy8960f0a2012-11-07 15:35:50 -08001292 info.senderAddress = m.getFrom();
Andy Huangb8331b42012-07-16 19:08:53 -07001293 }
Andy Huangb8331b42012-07-16 19:08:53 -07001294 }
mindypf4fce122012-09-14 15:55:33 -07001295 return info;
Andy Huangb8331b42012-07-16 19:08:53 -07001296 }
1297
Andy Huang014ea4c2012-09-25 14:50:54 -07001298 private boolean processInPlaceUpdates(MessageCursor newCursor, MessageCursor oldCursor) {
1299 final Set<String> idsOfChangedBodies = Sets.newHashSet();
Andy Huang6b3d0d92012-10-30 15:46:48 -07001300 final List<Integer> changedOverlayPositions = Lists.newArrayList();
1301
Andy Huang014ea4c2012-09-25 14:50:54 -07001302 boolean changed = false;
1303
1304 int pos = 0;
1305 while (true) {
1306 if (!newCursor.moveToPosition(pos) || !oldCursor.moveToPosition(pos)) {
1307 break;
1308 }
1309
1310 final ConversationMessage newMsg = newCursor.getMessage();
1311 final ConversationMessage oldMsg = oldCursor.getMessage();
1312
Scott Kennedy8960f0a2012-11-07 15:35:50 -08001313 if (!TextUtils.equals(newMsg.getFrom(), oldMsg.getFrom()) ||
Andy Huang2a1e8e32012-10-23 18:54:57 -07001314 newMsg.isSending != oldMsg.isSending) {
Andy Huang6b3d0d92012-10-30 15:46:48 -07001315 mAdapter.updateItemsForMessage(newMsg, changedOverlayPositions);
Andy Huang2a1e8e32012-10-23 18:54:57 -07001316 LogUtils.i(LOG_TAG, "msg #%d (%d): detected from/sending change. isSending=%s",
1317 pos, newMsg.id, newMsg.isSending);
Andy Huang014ea4c2012-09-25 14:50:54 -07001318 }
1319
1320 // update changed message bodies in-place
1321 if (!TextUtils.equals(newMsg.bodyHtml, oldMsg.bodyHtml) ||
1322 !TextUtils.equals(newMsg.bodyText, oldMsg.bodyText)) {
1323 // maybe just set a flag to notify JS to re-request changed bodies
1324 idsOfChangedBodies.add('"' + mTemplates.getMessageDomId(newMsg) + '"');
1325 LogUtils.i(LOG_TAG, "msg #%d (%d): detected body change", pos, newMsg.id);
1326 }
1327
1328 pos++;
1329 }
1330
Andy Huang6b3d0d92012-10-30 15:46:48 -07001331
1332 if (!changedOverlayPositions.isEmpty()) {
Andy Huang06c03622012-10-22 18:59:45 -07001333 // notify once after the entire adapter is updated
Andy Huang6b3d0d92012-10-30 15:46:48 -07001334 mConversationContainer.onOverlayModelUpdate(changedOverlayPositions);
1335 changed = true;
Andy Huang06c03622012-10-22 18:59:45 -07001336 }
1337
Andy Huang014ea4c2012-09-25 14:50:54 -07001338 if (!idsOfChangedBodies.isEmpty()) {
1339 mWebView.loadUrl(String.format("javascript:replaceMessageBodies([%s]);",
1340 TextUtils.join(",", idsOfChangedBodies)));
1341 changed = true;
1342 }
1343
1344 return changed;
1345 }
1346
Andy Huang06c03622012-10-22 18:59:45 -07001347 private void processNewOutgoingMessage(ConversationMessage msg) {
1348 mTemplates.reset();
1349 // this method will add some items to mAdapter, but we deliberately want to avoid notifying
1350 // adapter listeners (i.e. ConversationContainer) until onWebContentGeometryChange is next
1351 // called, to prevent N+1 headers rendering with N message bodies.
1352 renderMessage(msg, true /* expanded */, msg.alwaysShowImages);
1353 mTempBodiesHtml = mTemplates.emit();
1354
1355 mViewState.setExpansionState(msg, ExpansionState.EXPANDED);
1356 // FIXME: should the provider set this as initial state?
1357 mViewState.setReadState(msg, false /* read */);
1358
Andy Huang91d782a2012-10-25 12:37:29 -07001359 // From now until the updated spacer geometry is returned, the adapter items are mismatched
1360 // with the existing spacers. Do not let them layout.
1361 mConversationContainer.invalidateSpacerGeometry();
1362
Andy Huang06c03622012-10-22 18:59:45 -07001363 mWebView.loadUrl("javascript:appendMessageHtml();");
1364 }
1365
Paul Westbrookcebcc642012-08-08 10:06:04 -07001366 private class SetCookieTask extends AsyncTask<Void, Void, Void> {
1367 final String mUri;
Paul Westbrookb8361c92012-09-27 10:57:14 -07001368 final Uri mAccountCookieQueryUri;
1369 final ContentResolver mResolver;
Paul Westbrookcebcc642012-08-08 10:06:04 -07001370
Paul Westbrookb8361c92012-09-27 10:57:14 -07001371 SetCookieTask(Context context, Uri baseUri, Uri accountCookieQueryUri) {
1372 mUri = baseUri.toString();
1373 mAccountCookieQueryUri = accountCookieQueryUri;
1374 mResolver = context.getContentResolver();
Paul Westbrookcebcc642012-08-08 10:06:04 -07001375 }
1376
1377 @Override
1378 public Void doInBackground(Void... args) {
Paul Westbrookb8361c92012-09-27 10:57:14 -07001379 // First query for the coookie string from the UI provider
1380 final Cursor cookieCursor = mResolver.query(mAccountCookieQueryUri,
1381 UIProvider.ACCOUNT_COOKIE_PROJECTION, null, null, null);
1382 if (cookieCursor == null) {
1383 return null;
1384 }
1385
1386 try {
1387 if (cookieCursor.moveToFirst()) {
1388 final String cookie = cookieCursor.getString(
1389 cookieCursor.getColumnIndex(UIProvider.AccountCookieColumns.COOKIE));
1390
1391 if (cookie != null) {
1392 final CookieSyncManager csm =
1393 CookieSyncManager.createInstance(getContext());
1394 CookieManager.getInstance().setCookie(mUri, cookie);
1395 csm.sync();
1396 }
1397 }
1398
1399 } finally {
1400 cookieCursor.close();
1401 }
1402
1403
Paul Westbrookcebcc642012-08-08 10:06:04 -07001404 return null;
1405 }
1406 }
mindyp36280f32012-09-09 16:11:23 -07001407
mindyp26d4d2d2012-09-18 17:30:32 -07001408 @Override
mindyp36280f32012-09-09 16:11:23 -07001409 public void onConversationUpdated(Conversation conv) {
1410 final ConversationViewHeader headerView = (ConversationViewHeader) mConversationContainer
1411 .findViewById(R.id.conversation_header);
mindypb2b98ba2012-09-24 14:13:58 -07001412 mConversation = conv;
mindyp9e0b2362012-09-09 16:31:21 -07001413 if (headerView != null) {
1414 headerView.onConversationUpdated(conv);
Vikram Aggarwal51ad9042013-01-17 13:18:09 -08001415 headerView.setSubject(conv.subject);
mindyp9e0b2362012-09-09 16:31:21 -07001416 }
mindyp36280f32012-09-09 16:11:23 -07001417 }
Mark Wei4071c2f2012-09-26 14:38:38 -07001418
1419 @Override
1420 public void onLayoutChange(View v, int left, int top, int right,
1421 int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
1422 boolean sizeChanged = mNeedRender
1423 && mConversationContainer.getWidth() != 0;
1424 if (sizeChanged) {
1425 mNeedRender = false;
1426 mConversationContainer.removeOnLayoutChangeListener(this);
1427 renderConversation(getMessageCursor());
1428 }
1429 }
mindyp1b3cc472012-09-27 11:32:59 -07001430
1431 @Override
1432 public void setMessageDetailsExpanded(MessageHeaderItem i, boolean expanded,
1433 int heightBefore) {
1434 mDiff = (expanded ? 1 : -1) * Math.abs(i.getHeight() - heightBefore);
1435 }
Andy Huang02f9d182012-11-28 22:38:02 -08001436
Andy Huangc1fb9a92013-02-11 13:09:12 -08001437 private class CssScaleInterceptor implements OnScaleGestureListener {
Andy Huang02f9d182012-11-28 22:38:02 -08001438
1439 private float getFocusXWebPx(ScaleGestureDetector detector) {
1440 return (detector.getFocusX() - mSideMarginPx) / mWebView.getInitialScale();
1441 }
1442
1443 private float getFocusYWebPx(ScaleGestureDetector detector) {
1444 return detector.getFocusY() / mWebView.getInitialScale();
1445 }
1446
1447 @Override
1448 public boolean onScale(ScaleGestureDetector detector) {
1449 mWebView.loadUrl(String.format("javascript:onScale(%s, %s, %s);",
1450 detector.getScaleFactor(), getFocusXWebPx(detector),
1451 getFocusYWebPx(detector)));
1452 return false;
1453 }
1454
1455 @Override
1456 public boolean onScaleBegin(ScaleGestureDetector detector) {
1457 mWebView.loadUrl(String.format("javascript:onScaleBegin(%s, %s);",
1458 getFocusXWebPx(detector), getFocusYWebPx(detector)));
1459 return true;
1460 }
1461
1462 @Override
1463 public void onScaleEnd(ScaleGestureDetector detector) {
1464 mWebView.loadUrl(String.format("javascript:onScaleEnd(%s, %s);",
1465 getFocusXWebPx(detector), getFocusYWebPx(detector)));
1466 }
1467
1468 }
1469
Mindy Pereira9b875682012-02-15 18:10:54 -08001470}