blob: 5d54b94bc4a7bc6fb37334a9033d0d6c6b981339 [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
Paul Westbrookb8361c92012-09-27 10:57:14 -070020import android.content.ContentResolver;
Mindy Pereira9b875682012-02-15 18:10:54 -080021import android.content.Context;
Mindy Pereira8e915722012-02-16 14:42:56 -080022import android.content.Loader;
mindypad0c30d2012-09-25 12:09:13 -070023import android.content.res.Resources;
Mindy Pereira9b875682012-02-15 18:10:54 -080024import android.database.Cursor;
Andy Huang9d3fd922012-09-26 22:23:58 -070025import android.database.DataSetObserver;
Paul Westbrookb8361c92012-09-27 10:57:14 -070026import android.net.Uri;
Paul Westbrookcebcc642012-08-08 10:06:04 -070027import android.os.AsyncTask;
Mindy Pereira9b875682012-02-15 18:10:54 -080028import android.os.Bundle;
mindyp3bcf1802012-09-09 11:17:00 -070029import android.os.SystemClock;
Andrew Sapperstein3af481c2013-10-30 10:29:38 -070030import android.support.v4.text.BidiFormatter;
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -080031import android.support.v4.util.ArrayMap;
Andy Huang47aa9c92012-07-31 15:37:21 -070032import android.text.TextUtils;
Mindy Pereira9b875682012-02-15 18:10:54 -080033import android.view.LayoutInflater;
Andy Huangc1fb9a92013-02-11 13:09:12 -080034import android.view.View;
Mark Wei4071c2f2012-09-26 14:38:38 -070035import android.view.View.OnLayoutChangeListener;
Mindy Pereira9b875682012-02-15 18:10:54 -080036import android.view.ViewGroup;
Andy Huangf70fc402012-02-17 15:37:42 -080037import android.webkit.ConsoleMessage;
Paul Westbrookcebcc642012-08-08 10:06:04 -070038import android.webkit.CookieManager;
39import android.webkit.CookieSyncManager;
Mindy Pereira974c9662012-09-14 10:02:08 -070040import android.webkit.JavascriptInterface;
Andy Huangf70fc402012-02-17 15:37:42 -080041import android.webkit.WebChromeClient;
42import android.webkit.WebSettings;
Andy Huang17a9cde2012-03-09 18:03:16 -080043import android.webkit.WebView;
Andrew Sapperstein821fa872013-08-21 21:57:39 -070044import android.widget.Button;
Mindy Pereira9b875682012-02-15 18:10:54 -080045
Tony Mantler821e5782014-01-06 15:33:43 -080046import com.android.emailcommon.mail.Address;
Andy Huang59e0b182012-08-14 14:32:23 -070047import com.android.mail.FormattedDateBuilder;
Mindy Pereira9b875682012-02-15 18:10:54 -080048import com.android.mail.R;
Andy Huange6c9fb62013-11-15 09:56:20 -080049import com.android.mail.analytics.Analytics;
Jin Cao72953f22014-04-15 18:23:37 -070050import com.android.mail.analytics.AnalyticsTimer;
Andy Huang5ff63742012-03-16 20:30:23 -070051import com.android.mail.browse.ConversationContainer;
Andy Huangadbf3e82012-10-13 13:30:19 -070052import com.android.mail.browse.ConversationContainer.OverlayPosition;
Andrew Sapperstein8812d3c2013-06-04 17:06:41 -070053import com.android.mail.browse.ConversationMessage;
Andy Huang46dfba62012-04-19 01:47:32 -070054import com.android.mail.browse.ConversationOverlayItem;
Andy Huang7bdc3752012-03-25 17:18:19 -070055import com.android.mail.browse.ConversationViewAdapter;
Andrew Sapperstein14f93742013-07-25 14:29:56 -070056import com.android.mail.browse.ConversationViewAdapter.BorderItem;
Andy Huang46dfba62012-04-19 01:47:32 -070057import com.android.mail.browse.ConversationViewAdapter.MessageFooterItem;
Andy Huang7bdc3752012-03-25 17:18:19 -070058import com.android.mail.browse.ConversationViewAdapter.MessageHeaderItem;
Andy Huang46dfba62012-04-19 01:47:32 -070059import com.android.mail.browse.ConversationViewAdapter.SuperCollapsedBlockItem;
Andy Huang5ff63742012-03-16 20:30:23 -070060import com.android.mail.browse.ConversationViewHeader;
61import com.android.mail.browse.ConversationWebView;
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -080062import com.android.mail.browse.InlineAttachmentViewIntentBuilderCreator;
63import com.android.mail.browse.InlineAttachmentViewIntentBuilderCreatorHolder;
Andy Huangc1fb9a92013-02-11 13:09:12 -080064import com.android.mail.browse.MailWebView.ContentSizeChangeListener;
Andy Huang7bdc3752012-03-25 17:18:19 -070065import com.android.mail.browse.MessageCursor;
Andy Huang59e0b182012-08-14 14:32:23 -070066import com.android.mail.browse.MessageHeaderView;
Andy Huangadbf3e82012-10-13 13:30:19 -070067import com.android.mail.browse.ScrollIndicatorsView;
Andy Huang46dfba62012-04-19 01:47:32 -070068import com.android.mail.browse.SuperCollapsedBlock;
Andy Huang0b7ed6f2012-07-25 19:23:26 -070069import com.android.mail.browse.WebViewContextMenu;
Paul Westbrookc42ad5e2013-05-09 16:52:15 -070070import com.android.mail.content.ObjectCursor;
Andrew Sapperstein562c5ba2013-10-09 18:31:50 -070071import com.android.mail.print.PrintUtils;
Mindy Pereira9b875682012-02-15 18:10:54 -080072import com.android.mail.providers.Account;
73import com.android.mail.providers.Conversation;
Andy Huangf70fc402012-02-17 15:37:42 -080074import com.android.mail.providers.Message;
Alice Yangf323c042013-10-30 00:15:02 -070075import com.android.mail.providers.Settings;
Paul Westbrookb8361c92012-09-27 10:57:14 -070076import com.android.mail.providers.UIProvider;
Andy Huangcd5c5ee2012-08-12 19:03:51 -070077import com.android.mail.ui.ConversationViewState.ExpansionState;
Andrew Sapperstein376294b2013-06-06 16:04:26 -070078import com.android.mail.utils.ConversationViewUtils;
Paul Westbrookb334c902012-06-25 11:42:46 -070079import com.android.mail.utils.LogTag;
Mindy Pereira9b875682012-02-15 18:10:54 -080080import com.android.mail.utils.LogUtils;
Andy Huang2e9acfe2012-03-15 22:39:36 -070081import com.android.mail.utils.Utils;
Andy Huang543e7092013-04-22 11:44:56 -070082import com.google.common.collect.ImmutableList;
Andy Huang46dfba62012-04-19 01:47:32 -070083import com.google.common.collect.Lists;
Andy Huang05c70c82013-03-14 15:15:50 -070084import com.google.common.collect.Maps;
Andy Huangb8331b42012-07-16 19:08:53 -070085import com.google.common.collect.Sets;
Andy Huang65fe28f2012-04-06 18:08:53 -070086
Scott Kennedyeb9a4bd2012-11-12 10:33:04 -080087import java.util.ArrayList;
Andy Huang46dfba62012-04-19 01:47:32 -070088import java.util.List;
Andy Huang05c70c82013-03-14 15:15:50 -070089import java.util.Map;
Andy Huangb8331b42012-07-16 19:08:53 -070090import java.util.Set;
Mindy Pereira9b875682012-02-15 18:10:54 -080091
92/**
93 * The conversation view UI component.
94 */
Andrew Sapperstein9f957f32013-07-19 15:18:18 -070095public class ConversationViewFragment extends AbstractConversationViewFragment implements
Andrew Sapperstein4ddda2f2013-06-10 11:15:38 -070096 SuperCollapsedBlock.OnClickListener, OnLayoutChangeListener,
Andy Huang3c6fd442014-03-24 19:56:46 -070097 MessageHeaderView.MessageHeaderViewCallbacks, WebViewContextMenu.Callbacks {
Mindy Pereira8e915722012-02-16 14:42:56 -080098
Paul Westbrookb334c902012-06-25 11:42:46 -070099 private static final String LOG_TAG = LogTag.getLogTag();
Andy Huang632721e2012-04-11 16:57:26 -0700100 public static final String LAYOUT_TAG = "ConvLayout";
Mindy Pereira9b875682012-02-15 18:10:54 -0800101
Andy Huang9d3fd922012-09-26 22:23:58 -0700102 /**
mindyp1b3cc472012-09-27 11:32:59 -0700103 * Difference in the height of the message header whose details have been expanded/collapsed
104 */
105 private int mDiff = 0;
106
107 /**
Andy Huang9d3fd922012-09-26 22:23:58 -0700108 * Default value for {@link #mLoadWaitReason}. Conversation load will happen immediately.
109 */
110 private final int LOAD_NOW = 0;
111 /**
112 * Value for {@link #mLoadWaitReason} that means we are offscreen and waiting for the visible
113 * conversation to finish loading before beginning our load.
114 * <p>
115 * When this value is set, the fragment should register with {@link ConversationListCallbacks}
116 * to know when the visible conversation is loaded. When it is unset, it should unregister.
117 */
118 private final int LOAD_WAIT_FOR_INITIAL_CONVERSATION = 1;
119 /**
120 * Value for {@link #mLoadWaitReason} used when a conversation is too heavyweight to load at
121 * all when not visible (e.g. requires network fetch, or too complex). Conversation load will
122 * wait until this fragment is visible.
123 */
124 private final int LOAD_WAIT_UNTIL_VISIBLE = 2;
mindyp3bcf1802012-09-09 11:17:00 -0700125
Andrew Sapperstein9f957f32013-07-19 15:18:18 -0700126 protected ConversationContainer mConversationContainer;
Mindy Pereira9b875682012-02-15 18:10:54 -0800127
Andrew Sapperstein9f957f32013-07-19 15:18:18 -0700128 protected ConversationWebView mWebView;
Mindy Pereira9b875682012-02-15 18:10:54 -0800129
Andrew Sappersteina7fa9bf2014-03-29 13:33:04 -0700130 private ConversationViewProgressController mProgressController;
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700131
Andrew Sapperstein821fa872013-08-21 21:57:39 -0700132 private Button mNewMessageBar;
Andy Huang47aa9c92012-07-31 15:37:21 -0700133
Andrew Sapperstein9f957f32013-07-19 15:18:18 -0700134 protected HtmlConversationTemplates mTemplates;
Andy Huangf70fc402012-02-17 15:37:42 -0800135
Andy Huangf70fc402012-02-17 15:37:42 -0800136 private final MailJsBridge mJsBridge = new MailJsBridge();
137
Andrew Sapperstein9f957f32013-07-19 15:18:18 -0700138 protected ConversationViewAdapter mAdapter;
Andy Huang51067132012-03-12 20:08:19 -0700139
Andrew Sappersteinb1d184d2013-08-09 14:14:31 -0700140 protected 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
Andrew Sapperstein9f957f32013-07-19 15:18:18 -0700155 protected int mSideMarginPx;
Andy Huang02f9d182012-11-28 22:38:02 -0800156
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() {
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700182 getHandler().post(new FragmentRunnable("delayedConversationLoad",
183 ConversationViewFragment.this) {
Andy Huang9d3fd922012-09-26 22:23:58 -0700184 @Override
185 public void go() {
186 LogUtils.d(LOG_TAG, "CVF load observer fired, this=%s",
187 ConversationViewFragment.this);
188 handleDelayedConversationLoad();
189 }
190 });
191 }
192 };
Andy Huangf70fc402012-02-17 15:37:42 -0800193
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700194 private final Runnable mOnProgressDismiss = new FragmentRunnable("onProgressDismiss", this) {
Andy Huang7d4746e2012-10-17 17:03:17 -0700195 @Override
196 public void go() {
Scott Kennedy58192e52013-05-08 16:35:57 -0700197 LogUtils.d(LOG_TAG, "onProgressDismiss go() - isUserVisible() = %b", isUserVisible());
Andy Huang7d4746e2012-10-17 17:03:17 -0700198 if (isUserVisible()) {
199 onConversationSeen();
200 }
Andy Huang30bcfe72012-10-18 18:09:03 -0700201 mWebView.onRenderComplete();
Andy Huang7d4746e2012-10-17 17:03:17 -0700202 }
203 };
204
Andy Huangbd544e32012-05-29 15:56:51 -0700205 private static final boolean DEBUG_DUMP_CONVERSATION_HTML = false;
Andy Huang47aa9c92012-07-31 15:37:21 -0700206 private static final boolean DISABLE_OFFSCREEN_LOADING = false;
Andy Huang06c03622012-10-22 18:59:45 -0700207 private static final boolean DEBUG_DUMP_CURSOR_CONTENTS = false;
Andy Huange964eee2012-10-02 19:24:58 -0700208
209 private static final String BUNDLE_KEY_WEBVIEW_Y_PERCENT =
210 ConversationViewFragment.class.getName() + "webview-y-percent";
Andy Huangbd544e32012-05-29 15:56:51 -0700211
Andrew Sapperstein2fd167d2014-01-28 10:07:38 -0800212 private BidiFormatter mBidiFormatter;
Andrew Sapperstein3af481c2013-10-30 10:29:38 -0700213
Vikram Aggarwal6c511582012-02-27 10:59:47 -0800214 /**
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -0800215 * Contains a mapping between inline image attachments and their local message id.
216 */
217 private Map<String, String> mUrlToMessageIdMap;
218
219 /**
Vikram Aggarwal6c511582012-02-27 10:59:47 -0800220 * Constructor needs to be public to handle orientation changes and activity lifecycle events.
221 */
Paul Westbrookf0ea4842013-08-13 16:41:18 -0700222 public ConversationViewFragment() {}
Mindy Pereira9b875682012-02-15 18:10:54 -0800223
224 /**
225 * Creates a new instance of {@link ConversationViewFragment}, initialized
Andy Huang632721e2012-04-11 16:57:26 -0700226 * to display a conversation with other parameters inherited/copied from an existing bundle,
227 * typically one created using {@link #makeBasicArgs}.
228 */
229 public static ConversationViewFragment newInstance(Bundle existingArgs,
230 Conversation conversation) {
231 ConversationViewFragment f = new ConversationViewFragment();
232 Bundle args = new Bundle(existingArgs);
233 args.putParcelable(ARG_CONVERSATION, conversation);
234 f.setArguments(args);
235 return f;
236 }
237
mindypf4fce122012-09-14 15:55:33 -0700238 @Override
Andy Huangadbf3e82012-10-13 13:30:19 -0700239 public void onAccountChanged(Account newAccount, Account oldAccount) {
240 // if overview mode has changed, re-render completely (no need to also update headers)
241 if (isOverviewMode(newAccount) != isOverviewMode(oldAccount)) {
242 setupOverviewMode();
243 final MessageCursor c = getMessageCursor();
244 if (c != null) {
245 renderConversation(c);
246 } else {
247 // Null cursor means this fragment is either waiting to load or in the middle of
248 // loading. Either way, a future render will happen anyway, and the new setting
249 // will take effect when that happens.
250 }
251 return;
252 }
253
mindypf4fce122012-09-14 15:55:33 -0700254 // settings may have been updated; refresh views that are known to
255 // depend on settings
mindypf4fce122012-09-14 15:55:33 -0700256 mAdapter.notifyDataSetChanged();
Andy Huang632721e2012-04-11 16:57:26 -0700257 }
258
Mindy Pereira9b875682012-02-15 18:10:54 -0800259 @Override
260 public void onActivityCreated(Bundle savedInstanceState) {
Andy Huang9d3fd922012-09-26 22:23:58 -0700261 LogUtils.d(LOG_TAG, "IN CVF.onActivityCreated, this=%s visible=%s", this, isUserVisible());
Mindy Pereira9b875682012-02-15 18:10:54 -0800262 super.onActivityCreated(savedInstanceState);
Mark Wei1abfcaf2012-09-27 11:11:07 -0700263
264 if (mActivity == null || mActivity.isFinishing()) {
265 // Activity is finishing, just bail.
266 return;
267 }
268
mindypf4fce122012-09-14 15:55:33 -0700269 Context context = getContext();
270 mTemplates = new HtmlConversationTemplates(context);
Andy Huang59e0b182012-08-14 14:32:23 -0700271
mindypf4fce122012-09-14 15:55:33 -0700272 final FormattedDateBuilder dateBuilder = new FormattedDateBuilder(context);
Andy Huang59e0b182012-08-14 14:32:23 -0700273
Paul Westbrook8081df42012-09-10 15:43:36 -0700274 mAdapter = new ConversationViewAdapter(mActivity, this,
mindypf4fce122012-09-14 15:55:33 -0700275 getLoaderManager(), this, getContactInfoSource(), this,
Andrew Sapperstein2fd167d2014-01-28 10:07:38 -0800276 this, mAddressCache, dateBuilder, mBidiFormatter);
Andy Huang51067132012-03-12 20:08:19 -0700277 mConversationContainer.setOverlayAdapter(mAdapter);
278
Andy Huang59e0b182012-08-14 14:32:23 -0700279 // set up snap header (the adapter usually does this with the other ones)
Andrew Sapperstein85ea6182013-10-14 18:21:08 -0700280 mConversationContainer.getSnapHeader().initialize(
281 this, mAddressCache, this, getContactInfoSource(),
282 mActivity.getAccountController().getVeiledAddressMatcher());
Andy Huangc1fb9a92013-02-11 13:09:12 -0800283
Andrew Sapperstein90eccf92013-08-22 11:53:23 -0700284 final Resources resources = getResources();
285 mMaxAutoLoadMessages = resources.getInteger(R.integer.max_auto_load_messages);
Andy Huang632721e2012-04-11 16:57:26 -0700286
Andrew Sapperstein90eccf92013-08-22 11:53:23 -0700287 mSideMarginPx = resources.getDimensionPixelOffset(
Andy Huang02f9d182012-11-28 22:38:02 -0800288 R.dimen.conversation_message_content_margin_side);
289
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -0800290 mUrlToMessageIdMap = new ArrayMap<String, String>();
291 final InlineAttachmentViewIntentBuilderCreator creator =
292 InlineAttachmentViewIntentBuilderCreatorHolder.
293 getInlineAttachmentViewIntentCreator();
Andy Huang3c6fd442014-03-24 19:56:46 -0700294 final WebViewContextMenu contextMenu = new WebViewContextMenu(getActivity(),
295 creator.createInlineAttachmentViewIntentBuilder(mAccount.getEmailAddress(),
296 mConversation != null ? mConversation.id : -1));
297 contextMenu.setCallbacks(this);
298 mWebView.setOnCreateContextMenuListener(contextMenu);
Andy Huang0b7ed6f2012-07-25 19:23:26 -0700299
Andy Huangadbf3e82012-10-13 13:30:19 -0700300 // set this up here instead of onCreateView to ensure the latest Account is loaded
301 setupOverviewMode();
302
Andy Huang9d3fd922012-09-26 22:23:58 -0700303 // Defer the call to initLoader with a Handler.
304 // We want to wait until we know which fragments are present and their final visibility
305 // states before going off and doing work. This prevents extraneous loading from occurring
306 // as the ViewPager shifts about before the initial position is set.
307 //
308 // e.g. click on item #10
309 // ViewPager.setAdapter() actually first loads #0 and #1 under the assumption that #0 is
310 // the initial primary item
311 // Then CPC immediately sets the primary item to #10, which tears down #0/#1 and sets up
312 // #9/#10/#11.
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700313 getHandler().post(new FragmentRunnable("showConversation", this) {
Andy Huang9d3fd922012-09-26 22:23:58 -0700314 @Override
315 public void go() {
316 showConversation();
317 }
318 });
Paul Westbrookcebcc642012-08-08 10:06:04 -0700319
Andrew Sapperstein606dbd72013-07-30 19:14:23 -0700320 if (mConversation != null && mConversation.conversationBaseUri != null &&
Andrew Sappersteinf59d01c2014-02-20 10:27:06 -0800321 !Utils.isEmpty(mAccount.accountCookieQueryUri)) {
Paul Westbrookcebcc642012-08-08 10:06:04 -0700322 // Set the cookie for this base url
Andrew Sappersteinf59d01c2014-02-20 10:27:06 -0800323 new SetCookieTask(getContext(), mConversation.conversationBaseUri.toString(),
324 mAccount.accountCookieQueryUri).execute();
Paul Westbrookcebcc642012-08-08 10:06:04 -0700325 }
Mindy Pereira9b875682012-02-15 18:10:54 -0800326 }
327
Mindy Pereira9b875682012-02-15 18:10:54 -0800328 @Override
Andy Huange964eee2012-10-02 19:24:58 -0700329 public void onCreate(Bundle savedState) {
330 super.onCreate(savedState);
331
Andrew Sappersteinb1d184d2013-08-09 14:14:31 -0700332 mWebViewClient = createConversationWebViewClient();
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700333
Andy Huange964eee2012-10-02 19:24:58 -0700334 if (savedState != null) {
335 mWebViewYPercent = savedState.getFloat(BUNDLE_KEY_WEBVIEW_Y_PERCENT);
336 }
Andrew Sapperstein3af481c2013-10-30 10:29:38 -0700337
Andrew Sapperstein2fd167d2014-01-28 10:07:38 -0800338 mBidiFormatter = BidiFormatter.getInstance();
Andy Huange964eee2012-10-02 19:24:58 -0700339 }
340
Andrew Sappersteinb1d184d2013-08-09 14:14:31 -0700341 protected ConversationWebViewClient createConversationWebViewClient() {
342 return new ConversationWebViewClient(mAccount);
343 }
344
Andy Huange964eee2012-10-02 19:24:58 -0700345 @Override
Mindy Pereira9b875682012-02-15 18:10:54 -0800346 public View onCreateView(LayoutInflater inflater,
347 ViewGroup container, Bundle savedInstanceState) {
Andy Huang839ada22012-07-20 15:48:40 -0700348
Andy Huang632721e2012-04-11 16:57:26 -0700349 View rootView = inflater.inflate(R.layout.conversation_view, container, false);
Andy Huangf70fc402012-02-17 15:37:42 -0800350 mConversationContainer = (ConversationContainer) rootView
351 .findViewById(R.id.conversation_container);
Andy Huang8f187782012-11-06 17:49:25 -0800352 mConversationContainer.setAccountController(this);
Andy Huang47aa9c92012-07-31 15:37:21 -0700353
Andrew Sapperstein85ea6182013-10-14 18:21:08 -0700354 final ViewGroup topmostOverlay =
355 (ViewGroup) mConversationContainer.findViewById(R.id.conversation_topmost_overlay);
356 inflateSnapHeader(topmostOverlay, inflater);
357 mConversationContainer.setupSnapHeader();
358
359 setupNewMessageBar();
Andy Huang47aa9c92012-07-31 15:37:21 -0700360
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700361 mProgressController = new ConversationViewProgressController(this, getHandler());
362 mProgressController.instantiateProgressIndicators(rootView);
mindyp3bcf1802012-09-09 11:17:00 -0700363
Andy Huang5ff63742012-03-16 20:30:23 -0700364 mWebView = (ConversationWebView) mConversationContainer.findViewById(R.id.webview);
Andy Huangf70fc402012-02-17 15:37:42 -0800365
Andy Huangf70fc402012-02-17 15:37:42 -0800366 mWebView.addJavascriptInterface(mJsBridge, "mail");
mindyp3bcf1802012-09-09 11:17:00 -0700367 // On JB or newer, we use the 'webkitAnimationStart' DOM event to signal load complete
368 // Below JB, try to speed up initial render by having the webview do supplemental draws to
369 // custom a software canvas.
mindypb941fdb2012-09-11 08:28:23 -0700370 // TODO(mindyp):
371 //PAGE READINESS SIGNAL FOR JELLYBEAN AND NEWER
372 // Notify the app on 'webkitAnimationStart' of a simple dummy element with a simple no-op
373 // animation that immediately runs on page load. The app uses this as a signal that the
374 // content is loaded and ready to draw, since WebView delays firing this event until the
375 // layers are composited and everything is ready to draw.
376 // This signal does not seem to be reliable, so just use the old method for now.
Andy Huangf7ac83f2013-07-15 15:48:31 -0700377 final boolean isJBOrLater = Utils.isRunningJellybeanOrLater();
378 final boolean isUserVisible = isUserVisible();
379 mWebView.setUseSoftwareLayer(!isJBOrLater);
380 mEnableContentReadySignal = isJBOrLater && isUserVisible;
381 mWebView.onUserVisibilityChanged(isUserVisible);
Andy Huang17a9cde2012-03-09 18:03:16 -0800382 mWebView.setWebViewClient(mWebViewClient);
Andy Huangc1fb9a92013-02-11 13:09:12 -0800383 final WebChromeClient wcc = new WebChromeClient() {
Andy Huangf70fc402012-02-17 15:37:42 -0800384 @Override
385 public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -0800386 if (consoleMessage.messageLevel() == ConsoleMessage.MessageLevel.ERROR) {
387 LogUtils.wtf(LOG_TAG, "JS: %s (%s:%d) f=%s", consoleMessage.message(),
388 consoleMessage.sourceId(), consoleMessage.lineNumber(),
389 ConversationViewFragment.this);
390 } else {
391 LogUtils.i(LOG_TAG, "JS: %s (%s:%d) f=%s", consoleMessage.message(),
392 consoleMessage.sourceId(), consoleMessage.lineNumber(),
393 ConversationViewFragment.this);
394 }
Andy Huangf70fc402012-02-17 15:37:42 -0800395 return true;
396 }
Andy Huangc1fb9a92013-02-11 13:09:12 -0800397 };
398 mWebView.setWebChromeClient(wcc);
Andy Huangf70fc402012-02-17 15:37:42 -0800399
Andy Huang3233bff2012-03-20 19:38:45 -0700400 final WebSettings settings = mWebView.getSettings();
Andy Huangf70fc402012-02-17 15:37:42 -0800401
Greg Bullockf50aafa2014-03-22 02:17:00 +0100402 final ScrollIndicatorsView scrollIndicators =
403 (ScrollIndicatorsView) rootView.findViewById(R.id.scroll_indicators);
404 scrollIndicators.setSourceView(mWebView);
Mark Wei56d83852012-09-19 14:28:50 -0700405
Andy Huangf70fc402012-02-17 15:37:42 -0800406 settings.setJavaScriptEnabled(true);
Andy Huangf70fc402012-02-17 15:37:42 -0800407
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700408 ConversationViewUtils.setTextZoom(getResources(), settings);
Andy Huangc319b552012-04-25 19:53:50 -0700409
Andy Huang51067132012-03-12 20:08:19 -0700410 mViewsCreated = true;
Andy Huange964eee2012-10-02 19:24:58 -0700411 mWebViewLoadedData = false;
Andy Huang51067132012-03-12 20:08:19 -0700412
Mindy Pereira9b875682012-02-15 18:10:54 -0800413 return rootView;
414 }
415
Andrew Sapperstein85ea6182013-10-14 18:21:08 -0700416 protected void inflateSnapHeader(ViewGroup topmostOverlay, LayoutInflater inflater) {
417 inflater.inflate(R.layout.conversation_topmost_overlay_items, topmostOverlay, true);
418 }
419
420 protected void setupNewMessageBar() {
421 mNewMessageBar = (Button) mConversationContainer.findViewById(
422 R.id.new_message_notification_bar);
423 mNewMessageBar.setOnClickListener(new View.OnClickListener() {
424 @Override
425 public void onClick(View v) {
426 onNewMessageBarClick();
427 }
428 });
429 }
430
Mindy Pereira9b875682012-02-15 18:10:54 -0800431 @Override
Andy Huangf7ac83f2013-07-15 15:48:31 -0700432 public void onResume() {
433 super.onResume();
434 if (mWebView != null) {
435 mWebView.onResume();
436 }
437 }
438
439 @Override
440 public void onPause() {
441 super.onPause();
442 if (mWebView != null) {
443 mWebView.onPause();
444 }
445 }
446
447 @Override
Mindy Pereira9b875682012-02-15 18:10:54 -0800448 public void onDestroyView() {
Mindy Pereira9b875682012-02-15 18:10:54 -0800449 super.onDestroyView();
Andy Huang46dfba62012-04-19 01:47:32 -0700450 mConversationContainer.setOverlayAdapter(null);
451 mAdapter = null;
Andy Huang9d3fd922012-09-26 22:23:58 -0700452 resetLoadWaiting(); // be sure to unregister any active load observer
Andy Huang51067132012-03-12 20:08:19 -0700453 mViewsCreated = false;
Mindy Pereira9b875682012-02-15 18:10:54 -0800454 }
455
Andy Huange964eee2012-10-02 19:24:58 -0700456 @Override
457 public void onSaveInstanceState(Bundle outState) {
458 super.onSaveInstanceState(outState);
459
460 outState.putFloat(BUNDLE_KEY_WEBVIEW_Y_PERCENT, calculateScrollYPercent());
461 }
462
463 private float calculateScrollYPercent() {
Paul Westbrook1b56a672013-04-19 01:19:05 -0700464 final float p;
465 if (mWebView == null) {
466 // onCreateView hasn't been called, return 0 as the user hasn't scrolled the view.
467 return 0;
468 }
469
470 final int scrollY = mWebView.getScrollY();
471 final int viewH = mWebView.getHeight();
472 final int webH = (int) (mWebView.getContentHeight() * mWebView.getScale());
Andy Huange964eee2012-10-02 19:24:58 -0700473
474 if (webH == 0 || webH <= viewH) {
475 p = 0;
476 } else if (scrollY + viewH >= webH) {
477 // The very bottom is a special case, it acts as a stronger anchor than the scroll top
478 // at that point.
479 p = 1.0f;
480 } else {
481 p = (float) scrollY / webH;
482 }
483 return p;
484 }
485
Andy Huang9d3fd922012-09-26 22:23:58 -0700486 private void resetLoadWaiting() {
487 if (mLoadWaitReason == LOAD_WAIT_FOR_INITIAL_CONVERSATION) {
488 getListController().unregisterConversationLoadedObserver(mLoadedObserver);
489 }
490 mLoadWaitReason = LOAD_NOW;
491 }
492
Andy Huang5ff63742012-03-16 20:30:23 -0700493 @Override
mindypf4fce122012-09-14 15:55:33 -0700494 protected void markUnread() {
Vikram Aggarwald82a31f2013-02-05 15:03:00 -0800495 super.markUnread();
Andy Huang839ada22012-07-20 15:48:40 -0700496 // Ignore unsafe calls made after a fragment is detached from an activity
497 final ControllableActivity activity = (ControllableActivity) getActivity();
498 if (activity == null) {
499 LogUtils.w(LOG_TAG, "ignoring markUnread for conv=%s", mConversation.id);
500 return;
501 }
502
Andy Huang28e31e22012-07-26 16:33:15 -0700503 if (mViewState == null) {
504 LogUtils.i(LOG_TAG, "ignoring markUnread for conv with no view state (%d)",
505 mConversation.id);
506 return;
507 }
Andy Huang839ada22012-07-20 15:48:40 -0700508 activity.getConversationUpdater().markConversationMessagesUnread(mConversation,
Vikram Aggarwal4a878b62012-07-31 15:09:25 -0700509 mViewState.getUnreadMessageUris(), mViewState.getConversationInfo());
Andy Huang839ada22012-07-20 15:48:40 -0700510 }
511
mindypf4fce122012-09-14 15:55:33 -0700512 @Override
513 public void onUserVisibleHintChanged() {
Andy Huang9d3fd922012-09-26 22:23:58 -0700514 final boolean userVisible = isUserVisible();
Scott Kennedy58192e52013-05-08 16:35:57 -0700515 LogUtils.d(LOG_TAG, "ConversationViewFragment#onUserVisibleHintChanged(), userVisible = %b",
516 userVisible);
Andy Huang9d3fd922012-09-26 22:23:58 -0700517
518 if (!userVisible) {
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700519 mProgressController.dismissLoadingStatus();
Andy Huang9d3fd922012-09-26 22:23:58 -0700520 } else if (mViewsCreated) {
Andy Huange6c9fb62013-11-15 09:56:20 -0800521 String loadTag = null;
Andy Huangeeb4a352013-11-21 10:56:27 -0800522 final boolean isInitialLoading;
523 if (mActivity != null) {
524 isInitialLoading = mActivity.getConversationUpdater()
Andy Huange6c9fb62013-11-15 09:56:20 -0800525 .isInitialConversationLoading();
Andy Huangeeb4a352013-11-21 10:56:27 -0800526 } else {
527 isInitialLoading = true;
528 }
Andy Huange6c9fb62013-11-15 09:56:20 -0800529
Andy Huang9d3fd922012-09-26 22:23:58 -0700530 if (getMessageCursor() != null) {
531 LogUtils.d(LOG_TAG, "Fragment is now user-visible, onConversationSeen: %s", this);
Andy Huange6c9fb62013-11-15 09:56:20 -0800532 if (!isInitialLoading) {
533 loadTag = "preloaded";
534 }
Andy Huang9d3fd922012-09-26 22:23:58 -0700535 onConversationSeen();
536 } else if (isLoadWaiting()) {
537 LogUtils.d(LOG_TAG, "Fragment is now user-visible, showing conversation: %s", this);
Andy Huange6c9fb62013-11-15 09:56:20 -0800538 if (!isInitialLoading) {
539 loadTag = "load_deferred";
540 }
Andy Huang9d3fd922012-09-26 22:23:58 -0700541 handleDelayedConversationLoad();
542 }
Andy Huange6c9fb62013-11-15 09:56:20 -0800543
544 if (loadTag != null) {
545 // pager swipes are visibility transitions to 'visible' except during initial
546 // pager load on A) enter conversation mode B) rotate C) 2-pane conv-mode list-tap
547 Analytics.getInstance().sendEvent("pager_swipe", loadTag,
548 getCurrentFolderTypeDesc(), 0);
549 }
Andy Huang632721e2012-04-11 16:57:26 -0700550 }
Andy Huang632721e2012-04-11 16:57:26 -0700551
Andy Huang30bcfe72012-10-18 18:09:03 -0700552 if (mWebView != null) {
553 mWebView.onUserVisibilityChanged(userVisible);
554 }
Andy Huangf8cf5462012-10-17 18:29:14 -0700555 }
556
Andy Huang9d3fd922012-09-26 22:23:58 -0700557 /**
558 * Will either call initLoader now to begin loading, or set {@link #mLoadWaitReason} and do
559 * nothing (in which case you should later call {@link #handleDelayedConversationLoad()}).
560 */
Mindy Pereira9b875682012-02-15 18:10:54 -0800561 private void showConversation() {
Andy Huang9d3fd922012-09-26 22:23:58 -0700562 final int reason;
563
564 if (isUserVisible()) {
565 LogUtils.i(LOG_TAG,
566 "SHOWCONV: CVF is user-visible, immediately loading conversation (%s)", this);
567 reason = LOAD_NOW;
Andy Huang243c2362013-03-01 17:50:35 -0800568 timerMark("CVF.showConversation");
Andy Huang9d3fd922012-09-26 22:23:58 -0700569 } else {
570 final boolean disableOffscreenLoading = DISABLE_OFFSCREEN_LOADING
Alice Yang0b8c0802013-09-16 14:35:18 -0700571 || Utils.isLowRamDevice(getContext())
Andrew Sapperstein606dbd72013-07-30 19:14:23 -0700572 || (mConversation != null && (mConversation.isRemote
573 || mConversation.getNumMessages() > mMaxAutoLoadMessages));
Andy Huang9d3fd922012-09-26 22:23:58 -0700574
575 // When not visible, we should not immediately load if either this conversation is
576 // too heavyweight, or if the main/initial conversation is busy loading.
577 if (disableOffscreenLoading) {
578 reason = LOAD_WAIT_UNTIL_VISIBLE;
579 LogUtils.i(LOG_TAG, "SHOWCONV: CVF waiting until visible to load (%s)", this);
580 } else if (getListController().isInitialConversationLoading()) {
581 reason = LOAD_WAIT_FOR_INITIAL_CONVERSATION;
582 LogUtils.i(LOG_TAG, "SHOWCONV: CVF waiting for initial to finish (%s)", this);
583 getListController().registerConversationLoadedObserver(mLoadedObserver);
584 } else {
585 LogUtils.i(LOG_TAG,
586 "SHOWCONV: CVF is not visible, but no reason to wait. loading now. (%s)",
587 this);
588 reason = LOAD_NOW;
589 }
Andy Huang632721e2012-04-11 16:57:26 -0700590 }
Andy Huang9d3fd922012-09-26 22:23:58 -0700591
592 mLoadWaitReason = reason;
593 if (mLoadWaitReason == LOAD_NOW) {
594 startConversationLoad();
595 }
596 }
597
598 private void handleDelayedConversationLoad() {
599 resetLoadWaiting();
600 startConversationLoad();
601 }
602
603 private void startConversationLoad() {
mindyp3bcf1802012-09-09 11:17:00 -0700604 mWebView.setVisibility(View.VISIBLE);
Andrew Sapperstein606dbd72013-07-30 19:14:23 -0700605 loadContent();
mindyp3bcf1802012-09-09 11:17:00 -0700606 // TODO(mindyp): don't show loading status for a previously rendered
607 // conversation. Ielieve this is better done by making sure don't show loading status
608 // until XX ms have passed without loading completed.
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700609 mProgressController.showLoadingStatus(isUserVisible());
Mindy Pereira8e915722012-02-16 14:42:56 -0800610 }
611
Andrew Sapperstein606dbd72013-07-30 19:14:23 -0700612 /**
613 * Can be overridden in case a subclass needs to load something other than
614 * the messages of a conversation.
615 */
616 protected void loadContent() {
617 getLoaderManager().initLoader(MESSAGE_LOADER, Bundle.EMPTY, getMessageLoaderCallbacks());
618 }
619
Andy Huang7d4746e2012-10-17 17:03:17 -0700620 private void revealConversation() {
Andy Huang243c2362013-03-01 17:50:35 -0800621 timerMark("revealing conversation");
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700622 mProgressController.dismissLoadingStatus(mOnProgressDismiss);
Jin Cao72953f22014-04-15 18:23:37 -0700623 if (isUserVisible()) {
624 AnalyticsTimer.getInstance().logDuration(AnalyticsTimer.OPEN_CONV_VIEW_FROM_LIST,
625 true /* isDestructive */, "open_conversation", "from_list", null);
626 }
Andy Huang7d4746e2012-10-17 17:03:17 -0700627 }
628
Andy Huang9d3fd922012-09-26 22:23:58 -0700629 private boolean isLoadWaiting() {
630 return mLoadWaitReason != LOAD_NOW;
631 }
632
Andy Huang51067132012-03-12 20:08:19 -0700633 private void renderConversation(MessageCursor messageCursor) {
mindyp3bcf1802012-09-09 11:17:00 -0700634 final String convHtml = renderMessageBodies(messageCursor, mEnableContentReadySignal);
Andy Huang243c2362013-03-01 17:50:35 -0800635 timerMark("rendered conversation");
Andy Huangbd544e32012-05-29 15:56:51 -0700636
637 if (DEBUG_DUMP_CONVERSATION_HTML) {
638 java.io.FileWriter fw = null;
639 try {
Andrew Sappersteinf1566b12013-09-19 15:34:26 -0700640 fw = new java.io.FileWriter(getSdCardFilePath());
Andy Huangbd544e32012-05-29 15:56:51 -0700641 fw.write(convHtml);
642 } catch (java.io.IOException e) {
643 e.printStackTrace();
644 } finally {
645 if (fw != null) {
646 try {
647 fw.close();
648 } catch (java.io.IOException e) {
649 e.printStackTrace();
650 }
651 }
652 }
653 }
654
Andy Huange964eee2012-10-02 19:24:58 -0700655 // save off existing scroll position before re-rendering
656 if (mWebViewLoadedData) {
657 mWebViewYPercent = calculateScrollYPercent();
658 }
659
Andy Huangbd544e32012-05-29 15:56:51 -0700660 mWebView.loadDataWithBaseURL(mBaseUri, convHtml, "text/html", "utf-8", null);
Andy Huange964eee2012-10-02 19:24:58 -0700661 mWebViewLoadedData = true;
Andy Huang63b3c672012-10-05 19:27:28 -0700662 mWebViewLoadStartMs = SystemClock.uptimeMillis();
Andy Huang51067132012-03-12 20:08:19 -0700663 }
664
Andrew Sappersteinf1566b12013-09-19 15:34:26 -0700665 protected String getSdCardFilePath() {
666 return "/sdcard/conv" + mConversation.id + ".html";
667 }
668
Andy Huang7bdc3752012-03-25 17:18:19 -0700669 /**
670 * Populate the adapter with overlay views (message headers, super-collapsed blocks, a
671 * conversation header), and return an HTML document with spacer divs inserted for all overlays.
672 *
673 */
Andrew Sapperstein9f957f32013-07-19 15:18:18 -0700674 protected String renderMessageBodies(MessageCursor messageCursor,
mindyp3bcf1802012-09-09 11:17:00 -0700675 boolean enableContentReadySignal) {
Andy Huangf70fc402012-02-17 15:37:42 -0800676 int pos = -1;
Andy Huang632721e2012-04-11 16:57:26 -0700677
Andy Huang1ee96b22012-08-24 20:19:53 -0700678 LogUtils.d(LOG_TAG, "IN renderMessageBodies, fragment=%s", this);
Andy Huang7bdc3752012-03-25 17:18:19 -0700679 boolean allowNetworkImages = false;
680
Andy Huangc7543572012-04-03 15:34:29 -0700681 // TODO: re-use any existing adapter item state (expanded, details expanded, show pics)
Andy Huang28b7aee2012-08-20 20:27:32 -0700682
Andy Huang7bdc3752012-03-25 17:18:19 -0700683 // Walk through the cursor and build up an overlay adapter as you go.
684 // Each overlay has an entry in the adapter for easy scroll handling in the container.
685 // Items are not necessarily 1:1 in cursor and adapter because of super-collapsed blocks.
686 // When adding adapter items, also add their heights to help the container later determine
687 // overlay dimensions.
688
Andy Huangdb620fe2012-08-24 15:45:28 -0700689 // When re-rendering, prevent ConversationContainer from laying out overlays until after
690 // the new spacers are positioned by WebView.
691 mConversationContainer.invalidateSpacerGeometry();
692
Andy Huang7bdc3752012-03-25 17:18:19 -0700693 mAdapter.clear();
694
Andy Huang47aa9c92012-07-31 15:37:21 -0700695 // re-evaluate the message parts of the view state, since the messages may have changed
696 // since the previous render
697 final ConversationViewState prevState = mViewState;
698 mViewState = new ConversationViewState(prevState);
699
Andy Huang5ff63742012-03-16 20:30:23 -0700700 // N.B. the units of height for spacers are actually dp and not px because WebView assumes
Andy Huang2e9acfe2012-03-15 22:39:36 -0700701 // a pixel is an mdpi pixel, unless you set device-dpi.
Andy Huang5ff63742012-03-16 20:30:23 -0700702
Andy Huang7bdc3752012-03-25 17:18:19 -0700703 // add a single conversation header item
704 final int convHeaderPos = mAdapter.addConversationHeader(mConversation);
Andy Huang23014702012-07-09 12:50:36 -0700705 final int convHeaderPx = measureOverlayHeight(convHeaderPos);
Andy Huang5ff63742012-03-16 20:30:23 -0700706
Andy Huang4dc73232014-02-04 19:58:57 -0800707 mTemplates.startConversation(mWebView.getViewportWidth(),
708 mWebView.screenPxToWebPx(mSideMarginPx), mWebView.screenPxToWebPx(convHeaderPx));
Andy Huang3233bff2012-03-20 19:38:45 -0700709
Andy Huang46dfba62012-04-19 01:47:32 -0700710 int collapsedStart = -1;
Andy Huang839ada22012-07-20 15:48:40 -0700711 ConversationMessage prevCollapsedMsg = null;
Andrew Sappersteine8221482013-10-02 18:14:58 -0700712
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -0800713 final boolean alwaysShowImages = shouldAlwaysShowImages();
Alice Yangf323c042013-10-30 00:15:02 -0700714
Andrew Sappersteine8221482013-10-02 18:14:58 -0700715 boolean prevSafeForImages = alwaysShowImages;
Andy Huang46dfba62012-04-19 01:47:32 -0700716
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700717 // Store the previous expanded state so that the border between
718 // the previous and current message can be properly initialized.
719 int previousExpandedState = ExpansionState.NONE;
Andy Huangf70fc402012-02-17 15:37:42 -0800720 while (messageCursor.moveToPosition(++pos)) {
Andy Huang839ada22012-07-20 15:48:40 -0700721 final ConversationMessage msg = messageCursor.getMessage();
Andy Huang46dfba62012-04-19 01:47:32 -0700722
Andrew Sappersteine8221482013-10-02 18:14:58 -0700723 final boolean safeForImages = alwaysShowImages ||
Scott Kennedy20273842012-11-07 11:16:21 -0800724 msg.alwaysShowImages || prevState.getShouldShowImages(msg);
Andy Huang3233bff2012-03-20 19:38:45 -0700725 allowNetworkImages |= safeForImages;
Andy Huang24055282012-03-27 17:37:06 -0700726
Paul Westbrook08098ec2012-08-12 15:30:28 -0700727 final Integer savedExpanded = prevState.getExpansionState(msg);
728 final int expandedState;
Andy Huang839ada22012-07-20 15:48:40 -0700729 if (savedExpanded != null) {
Andy Huang1ee96b22012-08-24 20:19:53 -0700730 if (ExpansionState.isSuperCollapsed(savedExpanded) && messageCursor.isLast()) {
731 // override saved state when this is now the new last message
732 // this happens to the second-to-last message when you discard a draft
733 expandedState = ExpansionState.EXPANDED;
734 } else {
735 expandedState = savedExpanded;
736 }
Andy Huang839ada22012-07-20 15:48:40 -0700737 } else {
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700738 // new messages that are not expanded default to being eligible for super-collapse
Paul Westbrook08098ec2012-08-12 15:30:28 -0700739 expandedState = (!msg.read || msg.starred || messageCursor.isLast()) ?
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700740 ExpansionState.EXPANDED : ExpansionState.SUPER_COLLAPSED;
Andy Huang839ada22012-07-20 15:48:40 -0700741 }
Scott Kennedy20273842012-11-07 11:16:21 -0800742 mViewState.setShouldShowImages(msg, prevState.getShouldShowImages(msg));
Paul Westbrook08098ec2012-08-12 15:30:28 -0700743 mViewState.setExpansionState(msg, expandedState);
Andy Huangc7543572012-04-03 15:34:29 -0700744
Andy Huang839ada22012-07-20 15:48:40 -0700745 // save off "read" state from the cursor
746 // later, the view may not match the cursor (e.g. conversation marked read on open)
Andy Huang423bea22012-08-21 12:00:49 -0700747 // however, if a previous state indicated this message was unread, trust that instead
748 // so "mark unread" marks all originally unread messages
749 mViewState.setReadState(msg, msg.read && !prevState.isUnread(msg));
Andy Huang839ada22012-07-20 15:48:40 -0700750
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700751 // We only want to consider this for inclusion in the super collapsed block if
752 // 1) The we don't have previous state about this message (The first time that the
753 // user opens a conversation)
754 // 2) The previously saved state for this message indicates that this message is
755 // in the super collapsed block.
756 if (ExpansionState.isSuperCollapsed(expandedState)) {
757 // contribute to a super-collapsed block that will be emitted just before the
758 // next expanded header
759 if (collapsedStart < 0) {
760 collapsedStart = pos;
Andy Huang46dfba62012-04-19 01:47:32 -0700761 }
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700762 prevCollapsedMsg = msg;
763 prevSafeForImages = safeForImages;
Andrew Sapperstein7dc7fa02013-05-08 16:39:31 -0700764
765 // This line puts the from address in the address cache so that
766 // we get the sender image for it if it's in a super-collapsed block.
767 getAddress(msg.getFrom());
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700768 previousExpandedState = expandedState;
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700769 continue;
Andy Huang46dfba62012-04-19 01:47:32 -0700770 }
Andy Huang24055282012-03-27 17:37:06 -0700771
Andy Huang46dfba62012-04-19 01:47:32 -0700772 // resolve any deferred decisions on previous collapsed items
773 if (collapsedStart >= 0) {
774 if (pos - collapsedStart == 1) {
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700775 // Special-case for a single collapsed message: no need to super-collapse it.
776 // Since it is super-collapsed, there is no previous message to be
777 // collapsed and the border above it is the first border.
778 renderMessage(prevCollapsedMsg, false /* previousCollapsed */,
779 false /* expanded */, prevSafeForImages, true /* firstBorder */);
Andy Huang46dfba62012-04-19 01:47:32 -0700780 } else {
781 renderSuperCollapsedBlock(collapsedStart, pos - 1);
782 }
783 prevCollapsedMsg = null;
784 collapsedStart = -1;
785 }
Andy Huang7bdc3752012-03-25 17:18:19 -0700786
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700787 renderMessage(msg, ExpansionState.isCollapsed(previousExpandedState),
788 ExpansionState.isExpanded(expandedState), safeForImages,
Andrew Sappersteine5398802013-07-29 20:55:38 -0700789 pos == 0 /* firstBorder */);
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700790
791 previousExpandedState = expandedState;
Mindy Pereira9b875682012-02-15 18:10:54 -0800792 }
Andy Huang3233bff2012-03-20 19:38:45 -0700793
794 mWebView.getSettings().setBlockNetworkImage(!allowNetworkImages);
795
Andrew Sapperstein2fc67302013-04-29 18:24:56 -0700796 final boolean applyTransforms = shouldApplyTransforms();
Andy Huang57f354c2013-04-11 17:23:40 -0700797
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700798 renderBorder(true /* contiguous */, true /* expanded */,
799 false /* firstBorder */, true /* lastBorder */);
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700800
Andy Huangc1fb9a92013-02-11 13:09:12 -0800801 // If the conversation has specified a base uri, use it here, otherwise use mBaseUri
Andrew Sapperstein68141df2013-08-19 19:07:14 -0700802 return mTemplates.endConversation(mBaseUri, mConversation.getBaseUri(mBaseUri),
Andy Huang2160d532014-02-10 15:43:14 -0800803 mWebView.getViewportWidth(), mWebView.getWidthInDp(mSideMarginPx),
804 enableContentReadySignal, isOverviewMode(mAccount), applyTransforms,
805 applyTransforms);
Mindy Pereira9b875682012-02-15 18:10:54 -0800806 }
Mindy Pereira674afa42012-02-17 14:05:24 -0800807
Andy Huang46dfba62012-04-19 01:47:32 -0700808 private void renderSuperCollapsedBlock(int start, int end) {
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700809 renderBorder(true /* contiguous */, true /* expanded */,
810 true /* firstBorder */, false /* lastBorder */);
Andy Huang46dfba62012-04-19 01:47:32 -0700811 final int blockPos = mAdapter.addSuperCollapsedBlock(start, end);
Andy Huang23014702012-07-09 12:50:36 -0700812 final int blockPx = measureOverlayHeight(blockPos);
813 mTemplates.appendSuperCollapsedHtml(start, mWebView.screenPxToWebPx(blockPx));
Andy Huang46dfba62012-04-19 01:47:32 -0700814 }
815
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700816 protected void renderBorder(
817 boolean contiguous, boolean expanded, boolean firstBorder, boolean lastBorder) {
818 final int blockPos = mAdapter.addBorder(contiguous, expanded, firstBorder, lastBorder);
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700819 final int blockPx = measureOverlayHeight(blockPos);
820 mTemplates.appendBorder(mWebView.screenPxToWebPx(blockPx));
821 }
822
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700823 private void renderMessage(ConversationMessage msg, boolean previousCollapsed,
824 boolean expanded, boolean safeForImages, boolean firstBorder) {
825 renderMessage(msg, previousCollapsed, expanded, safeForImages,
826 true /* renderBorder */, firstBorder);
Andrew Sapperstein1f082232013-07-29 11:16:07 -0700827 }
828
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700829 private void renderMessage(ConversationMessage msg, boolean previousCollapsed,
830 boolean expanded, boolean safeForImages, boolean renderBorder, boolean firstBorder) {
Andrew Sapperstein1f082232013-07-29 11:16:07 -0700831 if (renderBorder) {
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700832 // The border should be collapsed only if both the current
833 // and previous messages are collapsed.
834 renderBorder(true /* contiguous */, !previousCollapsed || expanded,
835 firstBorder, false /* lastBorder */);
Andrew Sapperstein1f082232013-07-29 11:16:07 -0700836 }
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700837
Scott Kennedy20273842012-11-07 11:16:21 -0800838 final int headerPos = mAdapter.addMessageHeader(msg, expanded,
839 mViewState.getShouldShowImages(msg));
Andy Huang46dfba62012-04-19 01:47:32 -0700840 final MessageHeaderItem headerItem = (MessageHeaderItem) mAdapter.getItem(headerPos);
841
842 final int footerPos = mAdapter.addMessageFooter(headerItem);
843
844 // Measure item header and footer heights to allocate spacers in HTML
845 // But since the views themselves don't exist yet, render each item temporarily into
846 // a host view for measurement.
Andy Huang23014702012-07-09 12:50:36 -0700847 final int headerPx = measureOverlayHeight(headerPos);
848 final int footerPx = measureOverlayHeight(footerPos);
Andy Huang46dfba62012-04-19 01:47:32 -0700849
Andy Huang256b35c2012-08-22 15:19:13 -0700850 mTemplates.appendMessageHtml(msg, expanded, safeForImages,
Andy Huang23014702012-07-09 12:50:36 -0700851 mWebView.screenPxToWebPx(headerPx), mWebView.screenPxToWebPx(footerPx));
Andy Huang243c2362013-03-01 17:50:35 -0800852 timerMark("rendered message");
Andy Huang46dfba62012-04-19 01:47:32 -0700853 }
854
855 private String renderCollapsedHeaders(MessageCursor cursor,
856 SuperCollapsedBlockItem blockToReplace) {
857 final List<ConversationOverlayItem> replacements = Lists.newArrayList();
858
859 mTemplates.reset();
860
Alice Yangf323c042013-10-30 00:15:02 -0700861 final boolean alwaysShowImages = (mAccount != null) &&
862 (mAccount.settings.showImages == Settings.ShowImages.ALWAYS);
Andrew Sappersteine8221482013-10-02 18:14:58 -0700863
Mark Wei2b24e992012-09-10 16:40:07 -0700864 // In devices with non-integral density multiplier, screen pixels translate to non-integral
865 // web pixels. Keep track of the error that occurs when we cast all heights to int
866 float error = 0f;
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700867 boolean first = true;
Andy Huang46dfba62012-04-19 01:47:32 -0700868 for (int i = blockToReplace.getStart(), end = blockToReplace.getEnd(); i <= end; i++) {
869 cursor.moveToPosition(i);
Andy Huang839ada22012-07-20 15:48:40 -0700870 final ConversationMessage msg = cursor.getMessage();
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700871
872 final int borderPx;
873 if (first) {
874 borderPx = 0;
875 first = false;
876 } else {
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700877 // When replacing the super-collapsed block,
878 // the border is always collapsed between messages.
879 final BorderItem border = mAdapter.newBorderItem(
880 true /* contiguous */, false /* expanded */);
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700881 borderPx = measureOverlayHeight(border);
882 replacements.add(border);
883 mTemplates.appendBorder(mWebView.screenPxToWebPx(borderPx));
884 }
885
Andrew Sapperstein4ddda2f2013-06-10 11:15:38 -0700886 final MessageHeaderItem header = ConversationViewAdapter.newMessageHeaderItem(
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700887 mAdapter, mAdapter.getDateBuilder(), msg, false /* expanded */,
Andrew Sappersteine8221482013-10-02 18:14:58 -0700888 alwaysShowImages || mViewState.getShouldShowImages(msg));
Andy Huang46dfba62012-04-19 01:47:32 -0700889 final MessageFooterItem footer = mAdapter.newMessageFooterItem(header);
890
Andy Huang23014702012-07-09 12:50:36 -0700891 final int headerPx = measureOverlayHeight(header);
892 final int footerPx = measureOverlayHeight(footer);
Mark Wei2b24e992012-09-10 16:40:07 -0700893 error += mWebView.screenPxToWebPxError(headerPx)
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700894 + mWebView.screenPxToWebPxError(footerPx)
895 + mWebView.screenPxToWebPxError(borderPx);
Mark Wei2b24e992012-09-10 16:40:07 -0700896
897 // When the error becomes greater than 1 pixel, make the next header 1 pixel taller
898 int correction = 0;
899 if (error >= 1) {
900 correction = 1;
901 error -= 1;
902 }
Andy Huang46dfba62012-04-19 01:47:32 -0700903
Andrew Sappersteine8221482013-10-02 18:14:58 -0700904 mTemplates.appendMessageHtml(msg, false /* expanded */,
905 alwaysShowImages || msg.alwaysShowImages,
Mark Wei2b24e992012-09-10 16:40:07 -0700906 mWebView.screenPxToWebPx(headerPx) + correction,
907 mWebView.screenPxToWebPx(footerPx));
Andy Huang46dfba62012-04-19 01:47:32 -0700908 replacements.add(header);
909 replacements.add(footer);
Andy Huang839ada22012-07-20 15:48:40 -0700910
Paul Westbrook08098ec2012-08-12 15:30:28 -0700911 mViewState.setExpansionState(msg, ExpansionState.COLLAPSED);
Andy Huang46dfba62012-04-19 01:47:32 -0700912 }
913
914 mAdapter.replaceSuperCollapsedBlock(blockToReplace, replacements);
Andy Huang06c03622012-10-22 18:59:45 -0700915 mAdapter.notifyDataSetChanged();
Andy Huang46dfba62012-04-19 01:47:32 -0700916
917 return mTemplates.emit();
918 }
919
Andrew Sapperstein9f957f32013-07-19 15:18:18 -0700920 protected int measureOverlayHeight(int position) {
Andy Huang46dfba62012-04-19 01:47:32 -0700921 return measureOverlayHeight(mAdapter.getItem(position));
922 }
923
Andy Huang7bdc3752012-03-25 17:18:19 -0700924 /**
Andy Huangb8331b42012-07-16 19:08:53 -0700925 * Measure the height of an adapter view by rendering an adapter item into a temporary
Andy Huang46dfba62012-04-19 01:47:32 -0700926 * host view, and asking the view to immediately measure itself. This method will reuse
Andy Huang7bdc3752012-03-25 17:18:19 -0700927 * a previous adapter view from {@link ConversationContainer}'s scrap views if one was generated
928 * earlier.
929 * <p>
Andy Huang46dfba62012-04-19 01:47:32 -0700930 * After measuring the height, this method also saves the height in the
931 * {@link ConversationOverlayItem} for later use in overlay positioning.
Andy Huang7bdc3752012-03-25 17:18:19 -0700932 *
Andy Huang46dfba62012-04-19 01:47:32 -0700933 * @param convItem adapter item with data to render and measure
Andy Huang23014702012-07-09 12:50:36 -0700934 * @return height of the rendered view in screen px
Andy Huang7bdc3752012-03-25 17:18:19 -0700935 */
Andy Huang46dfba62012-04-19 01:47:32 -0700936 private int measureOverlayHeight(ConversationOverlayItem convItem) {
Andy Huang7bdc3752012-03-25 17:18:19 -0700937 final int type = convItem.getType();
938
939 final View convertView = mConversationContainer.getScrapView(type);
Andy Huangb8331b42012-07-16 19:08:53 -0700940 final View hostView = mAdapter.getView(convItem, convertView, mConversationContainer,
941 true /* measureOnly */);
Andy Huang7bdc3752012-03-25 17:18:19 -0700942 if (convertView == null) {
943 mConversationContainer.addScrapView(type, hostView);
944 }
945
Andy Huang9875bb42012-04-04 20:36:21 -0700946 final int heightPx = mConversationContainer.measureOverlay(hostView);
Andy Huang7bdc3752012-03-25 17:18:19 -0700947 convItem.setHeight(heightPx);
Andy Huang9875bb42012-04-04 20:36:21 -0700948 convItem.markMeasurementValid();
Andy Huang7bdc3752012-03-25 17:18:19 -0700949
Andy Huang23014702012-07-09 12:50:36 -0700950 return heightPx;
Andy Huang7bdc3752012-03-25 17:18:19 -0700951 }
952
Andy Huang5ff63742012-03-16 20:30:23 -0700953 @Override
954 public void onConversationViewHeaderHeightChange(int newHeight) {
Mark Weiab2d9982012-09-25 13:06:17 -0700955 final int h = mWebView.screenPxToWebPx(newHeight);
956
957 mWebView.loadUrl(String.format("javascript:setConversationHeaderSpacerHeight(%s);", h));
Andy Huang5ff63742012-03-16 20:30:23 -0700958 }
959
Andy Huang3233bff2012-03-20 19:38:45 -0700960 // END conversation header callbacks
961
962 // START message header callbacks
963 @Override
Andy Huangc7543572012-04-03 15:34:29 -0700964 public void setMessageSpacerHeight(MessageHeaderItem item, int newSpacerHeightPx) {
965 mConversationContainer.invalidateSpacerGeometry();
966
967 // update message HTML spacer height
Andy Huang23014702012-07-09 12:50:36 -0700968 final int h = mWebView.screenPxToWebPx(newSpacerHeightPx);
969 LogUtils.i(LAYOUT_TAG, "setting HTML spacer h=%dwebPx (%dscreenPx)", h,
970 newSpacerHeightPx);
Vikram Aggarwal5349ce12012-09-24 14:12:40 -0700971 mWebView.loadUrl(String.format("javascript:setMessageHeaderSpacerHeight('%s', %s);",
Andy Huang014ea4c2012-09-25 14:50:54 -0700972 mTemplates.getMessageDomId(item.getMessage()), h));
Andy Huang3233bff2012-03-20 19:38:45 -0700973 }
974
975 @Override
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700976 public void setMessageExpanded(MessageHeaderItem item, int newSpacerHeightPx,
977 int topBorderHeight, int bottomBorderHeight) {
Andy Huangc7543572012-04-03 15:34:29 -0700978 mConversationContainer.invalidateSpacerGeometry();
979
980 // show/hide the HTML message body and update the spacer height
Andy Huang23014702012-07-09 12:50:36 -0700981 final int h = mWebView.screenPxToWebPx(newSpacerHeightPx);
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700982 final int topHeight = mWebView.screenPxToWebPx(topBorderHeight);
983 final int bottomHeight = mWebView.screenPxToWebPx(bottomBorderHeight);
Andy Huang23014702012-07-09 12:50:36 -0700984 LogUtils.i(LAYOUT_TAG, "setting HTML spacer expanded=%s h=%dwebPx (%dscreenPx)",
985 item.isExpanded(), h, newSpacerHeightPx);
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700986 mWebView.loadUrl(String.format("javascript:setMessageBodyVisible('%s', %s, %s, %s, %s);",
987 mTemplates.getMessageDomId(item.getMessage()), item.isExpanded(),
988 h, topHeight, bottomHeight));
Andy Huang839ada22012-07-20 15:48:40 -0700989
Andy Huang014ea4c2012-09-25 14:50:54 -0700990 mViewState.setExpansionState(item.getMessage(),
Paul Westbrook08098ec2012-08-12 15:30:28 -0700991 item.isExpanded() ? ExpansionState.EXPANDED : ExpansionState.COLLAPSED);
Andy Huang3233bff2012-03-20 19:38:45 -0700992 }
993
994 @Override
Scott Kennedyeb9a4bd2012-11-12 10:33:04 -0800995 public void showExternalResources(final Message msg) {
Scott Kennedy20273842012-11-07 11:16:21 -0800996 mViewState.setShouldShowImages(msg, true);
Andy Huang3233bff2012-03-20 19:38:45 -0700997 mWebView.getSettings().setBlockNetworkImage(false);
Scott Kennedyeb9a4bd2012-11-12 10:33:04 -0800998 mWebView.loadUrl("javascript:unblockImages(['" + mTemplates.getMessageDomId(msg) + "']);");
999 }
1000
1001 @Override
1002 public void showExternalResources(final String senderRawAddress) {
1003 mWebView.getSettings().setBlockNetworkImage(false);
1004
1005 final Address sender = getAddress(senderRawAddress);
1006 final MessageCursor cursor = getMessageCursor();
1007
1008 final List<String> messageDomIds = new ArrayList<String>();
1009
1010 int pos = -1;
1011 while (cursor.moveToPosition(++pos)) {
1012 final ConversationMessage message = cursor.getMessage();
1013 if (sender.equals(getAddress(message.getFrom()))) {
1014 message.alwaysShowImages = true;
1015
1016 mViewState.setShouldShowImages(message, true);
1017 messageDomIds.add(mTemplates.getMessageDomId(message));
1018 }
1019 }
1020
1021 final String url = String.format(
1022 "javascript:unblockImages(['%s']);", TextUtils.join("','", messageDomIds));
1023 mWebView.loadUrl(url);
Andy Huang3233bff2012-03-20 19:38:45 -07001024 }
Alice Yang1ebc2db2013-03-14 21:21:44 -07001025
1026 @Override
Andy Huang75b52a52013-03-15 15:40:24 -07001027 public boolean supportsMessageTransforms() {
1028 return true;
1029 }
1030
1031 @Override
Alice Yang1ebc2db2013-03-14 21:21:44 -07001032 public String getMessageTransforms(final Message msg) {
1033 final String domId = mTemplates.getMessageDomId(msg);
1034 return (domId == null) ? null : mMessageTransforms.get(domId);
1035 }
1036
Andy Huang3233bff2012-03-20 19:38:45 -07001037 // END message header callbacks
Andy Huang5ff63742012-03-16 20:30:23 -07001038
Andy Huang46dfba62012-04-19 01:47:32 -07001039 @Override
Andrew Sapperstein2fc67302013-04-29 18:24:56 -07001040 public void showUntransformedConversation() {
1041 super.showUntransformedConversation();
1042 renderConversation(getMessageCursor());
1043 }
1044
1045 @Override
Andy Huang46dfba62012-04-19 01:47:32 -07001046 public void onSuperCollapsedClick(SuperCollapsedBlockItem item) {
mindypf4fce122012-09-14 15:55:33 -07001047 MessageCursor cursor = getMessageCursor();
1048 if (cursor == null || !mViewsCreated) {
Andy Huang46dfba62012-04-19 01:47:32 -07001049 return;
1050 }
1051
mindypf4fce122012-09-14 15:55:33 -07001052 mTempBodiesHtml = renderCollapsedHeaders(cursor, item);
Andy Huang46dfba62012-04-19 01:47:32 -07001053 mWebView.loadUrl("javascript:replaceSuperCollapsedBlock(" + item.getStart() + ")");
1054 }
1055
Andy Huang47aa9c92012-07-31 15:37:21 -07001056 private void showNewMessageNotification(NewMessagesInfo info) {
Andrew Sapperstein821fa872013-08-21 21:57:39 -07001057 mNewMessageBar.setText(info.getNotificationText());
Andy Huang47aa9c92012-07-31 15:37:21 -07001058 mNewMessageBar.setVisibility(View.VISIBLE);
1059 }
1060
1061 private void onNewMessageBarClick() {
1062 mNewMessageBar.setVisibility(View.GONE);
1063
mindypf4fce122012-09-14 15:55:33 -07001064 renderConversation(getMessageCursor()); // mCursor is already up-to-date
1065 // per onLoadFinished()
Andy Huang5fbda022012-02-28 18:22:03 -08001066 }
1067
Andy Huangadbf3e82012-10-13 13:30:19 -07001068 private static OverlayPosition[] parsePositions(final String[] topArray,
1069 final String[] bottomArray) {
1070 final int len = topArray.length;
1071 final OverlayPosition[] positions = new OverlayPosition[len];
Andy Huangb5078b22012-03-05 19:52:29 -08001072 for (int i = 0; i < len; i++) {
Andy Huangadbf3e82012-10-13 13:30:19 -07001073 positions[i] = new OverlayPosition(
1074 Integer.parseInt(topArray[i]), Integer.parseInt(bottomArray[i]));
Andy Huangb5078b22012-03-05 19:52:29 -08001075 }
Andy Huangadbf3e82012-10-13 13:30:19 -07001076 return positions;
Andy Huangb5078b22012-03-05 19:52:29 -08001077 }
1078
Andrew Sapperstein9f957f32013-07-19 15:18:18 -07001079 protected Address getAddress(String rawFrom) {
Paul Westbrook0dfae692013-10-02 00:51:29 -07001080 return Utils.getAddress(mAddressCache, rawFrom);
Andy Huang16174812012-08-16 16:40:35 -07001081 }
1082
Andy Huang9d3fd922012-09-26 22:23:58 -07001083 private void ensureContentSizeChangeListener() {
1084 if (mWebViewSizeChangeListener == null) {
Andy Huangc1fb9a92013-02-11 13:09:12 -08001085 mWebViewSizeChangeListener = new ContentSizeChangeListener() {
Andy Huang9d3fd922012-09-26 22:23:58 -07001086 @Override
1087 public void onHeightChange(int h) {
1088 // When WebKit says the DOM height has changed, re-measure
1089 // bodies and re-position their headers.
1090 // This is separate from the typical JavaScript DOM change
1091 // listeners because cases like NARROW_COLUMNS text reflow do not trigger DOM
1092 // events.
1093 mWebView.loadUrl("javascript:measurePositions();");
1094 }
1095 };
1096 }
1097 mWebView.setContentSizeChangeListener(mWebViewSizeChangeListener);
1098 }
1099
Andrew Sapperstein9f957f32013-07-19 15:18:18 -07001100 public static boolean isOverviewMode(Account acct) {
Andy Huangccf67802013-03-15 14:31:57 -07001101 return acct.settings.isOverviewMode();
Andy Huangadbf3e82012-10-13 13:30:19 -07001102 }
1103
1104 private void setupOverviewMode() {
Andy Huang02f9d182012-11-28 22:38:02 -08001105 // for now, overview mode means use the built-in WebView zoom and disable custom scale
1106 // gesture handling
Andy Huangadbf3e82012-10-13 13:30:19 -07001107 final boolean overviewMode = isOverviewMode(mAccount);
1108 final WebSettings settings = mWebView.getSettings();
Andy Huang4dc73232014-02-04 19:58:57 -08001109 final WebSettings.LayoutAlgorithm layout;
Andy Huang06def562012-10-14 00:19:11 -07001110 settings.setUseWideViewPort(overviewMode);
Andy Huang57f354c2013-04-11 17:23:40 -07001111 settings.setSupportZoom(overviewMode);
1112 settings.setBuiltInZoomControls(overviewMode);
Andy Huang4dc73232014-02-04 19:58:57 -08001113 settings.setLoadWithOverviewMode(overviewMode);
Andy Huang57f354c2013-04-11 17:23:40 -07001114 if (overviewMode) {
1115 settings.setDisplayZoomControls(false);
Andy Huang4dc73232014-02-04 19:58:57 -08001116 layout = WebSettings.LayoutAlgorithm.NORMAL;
1117 } else {
1118 layout = WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
Andy Huangadbf3e82012-10-13 13:30:19 -07001119 }
Andy Huang4dc73232014-02-04 19:58:57 -08001120 settings.setLayoutAlgorithm(layout);
Andy Huangadbf3e82012-10-13 13:30:19 -07001121 }
1122
Andy Huang3c6fd442014-03-24 19:56:46 -07001123 @Override
1124 public Message getMessageForClickedUrl(String url) {
1125 final String domMessageId = mUrlToMessageIdMap.get(url);
1126 if (domMessageId == null) {
1127 return null;
1128 }
1129 final String messageId = mTemplates.getMessageIdForDomId(domMessageId);
1130 return getMessageCursor().getMessageForId(Long.parseLong(messageId));
1131 }
1132
Andrew Sappersteinb1d184d2013-08-09 14:14:31 -07001133 public class ConversationWebViewClient extends AbstractConversationWebViewClient {
Andrew Sapperstein4ddda2f2013-06-10 11:15:38 -07001134 public ConversationWebViewClient(Account account) {
1135 super(account);
Andrew Sapperstein376294b2013-06-06 16:04:26 -07001136 }
1137
Andy Huang17a9cde2012-03-09 18:03:16 -08001138 @Override
1139 public void onPageFinished(WebView view, String url) {
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001140 // Ignore unsafe calls made after a fragment is detached from an activity.
1141 // This method needs to, for example, get at the loader manager, which needs
1142 // the fragment to be added.
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001143 if (!isAdded() || !mViewsCreated) {
Paul Westbrook006e13c2013-07-24 18:40:20 -07001144 LogUtils.d(LOG_TAG, "ignoring CVF.onPageFinished, url=%s fragment=%s", url,
Andy Huangb95da852012-07-18 14:16:58 -07001145 ConversationViewFragment.this);
1146 return;
1147 }
1148
Paul Westbrook006e13c2013-07-24 18:40:20 -07001149 LogUtils.d(LOG_TAG, "IN CVF.onPageFinished, url=%s fragment=%s wv=%s t=%sms", url,
Andy Huang30bcfe72012-10-18 18:09:03 -07001150 ConversationViewFragment.this, view,
Andy Huang63b3c672012-10-05 19:27:28 -07001151 (SystemClock.uptimeMillis() - mWebViewLoadStartMs));
Andy Huang632721e2012-04-11 16:57:26 -07001152
Andy Huang9d3fd922012-09-26 22:23:58 -07001153 ensureContentSizeChangeListener();
1154
mindyp3bcf1802012-09-09 11:17:00 -07001155 if (!mEnableContentReadySignal) {
Andy Huang7d4746e2012-10-17 17:03:17 -07001156 revealConversation();
mindyp3bcf1802012-09-09 11:17:00 -07001157 }
Andy Huang9d3fd922012-09-26 22:23:58 -07001158
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001159 final Set<String> emailAddresses = Sets.newHashSet();
Andy Huang543e7092013-04-22 11:44:56 -07001160 final List<Address> cacheCopy;
1161 synchronized (mAddressCache) {
1162 cacheCopy = ImmutableList.copyOf(mAddressCache.values());
1163 }
1164 for (Address addr : cacheCopy) {
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001165 emailAddresses.add(addr.getAddress());
Andy Huangb8331b42012-07-16 19:08:53 -07001166 }
Andrew Sapperstein4ddda2f2013-06-10 11:15:38 -07001167 final ContactLoaderCallbacks callbacks = getContactInfoSource();
1168 callbacks.setSenders(emailAddresses);
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001169 getLoaderManager().restartLoader(CONTACT_LOADER, Bundle.EMPTY, callbacks);
Andy Huang17a9cde2012-03-09 18:03:16 -08001170 }
1171
Andy Huangaf5d4e02012-03-19 19:02:12 -07001172 @Override
1173 public boolean shouldOverrideUrlLoading(WebView view, String url) {
Paul Westbrook542fec92012-09-18 14:47:51 -07001174 return mViewsCreated && super.shouldOverrideUrlLoading(view, url);
Andy Huangaf5d4e02012-03-19 19:02:12 -07001175 }
Andy Huang17a9cde2012-03-09 18:03:16 -08001176 }
1177
Andy Huangf70fc402012-02-17 15:37:42 -08001178 /**
1179 * NOTE: all public methods must be listed in the proguard flags so that they can be accessed
1180 * via reflection and not stripped.
1181 *
1182 */
1183 private class MailJsBridge {
Mindy Pereira974c9662012-09-14 10:02:08 -07001184 @JavascriptInterface
Andy Huangadbf3e82012-10-13 13:30:19 -07001185 public void onWebContentGeometryChange(final String[] overlayTopStrs,
1186 final String[] overlayBottomStrs) {
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -08001187 try {
1188 getHandler().post(new FragmentRunnable("onWebContentGeometryChange",
1189 ConversationViewFragment.this) {
1190 @Override
1191 public void go() {
Andy Huang46dfba62012-04-19 01:47:32 -07001192 if (!mViewsCreated) {
mindyp1b3cc472012-09-27 11:32:59 -07001193 LogUtils.d(LOG_TAG, "ignoring webContentGeometryChange because views"
1194 + " are gone, %s", ConversationViewFragment.this);
Andy Huang46dfba62012-04-19 01:47:32 -07001195 return;
1196 }
Andy Huangadbf3e82012-10-13 13:30:19 -07001197 mConversationContainer.onGeometryChange(
1198 parsePositions(overlayTopStrs, overlayBottomStrs));
mindyp1b3cc472012-09-27 11:32:59 -07001199 if (mDiff != 0) {
1200 // SCROLL!
1201 int scale = (int) (mWebView.getScale() / mWebView.getInitialScale());
1202 if (scale > 1) {
1203 mWebView.scrollBy(0, (mDiff * (scale - 1)));
1204 }
1205 mDiff = 0;
1206 }
Andy Huang46dfba62012-04-19 01:47:32 -07001207 }
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -08001208 });
1209 } catch (Throwable t) {
1210 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onWebContentGeometryChange");
1211 }
Andy Huang46dfba62012-04-19 01:47:32 -07001212 }
1213
Mindy Pereira974c9662012-09-14 10:02:08 -07001214 @JavascriptInterface
Andy Huang46dfba62012-04-19 01:47:32 -07001215 public String getTempMessageBodies() {
1216 try {
1217 if (!mViewsCreated) {
1218 return "";
Andy Huangf70fc402012-02-17 15:37:42 -08001219 }
Andy Huang46dfba62012-04-19 01:47:32 -07001220
1221 final String s = mTempBodiesHtml;
1222 mTempBodiesHtml = null;
1223 return s;
1224 } catch (Throwable t) {
1225 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getTempMessageBodies");
1226 return "";
1227 }
Andy Huangf70fc402012-02-17 15:37:42 -08001228 }
1229
Andy Huang014ea4c2012-09-25 14:50:54 -07001230 @JavascriptInterface
1231 public String getMessageBody(String domId) {
1232 try {
1233 final MessageCursor cursor = getMessageCursor();
1234 if (!mViewsCreated || cursor == null) {
1235 return "";
1236 }
1237
1238 int pos = -1;
1239 while (cursor.moveToPosition(++pos)) {
1240 final ConversationMessage msg = cursor.getMessage();
1241 if (TextUtils.equals(domId, mTemplates.getMessageDomId(msg))) {
Andy Huang986776b2014-02-19 18:29:43 -08001242 return HtmlConversationTemplates.wrapMessageBody(msg.getBodyAsHtml());
Andy Huang014ea4c2012-09-25 14:50:54 -07001243 }
1244 }
1245
1246 return "";
1247
1248 } catch (Throwable t) {
1249 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getMessageBody");
1250 return "";
1251 }
1252 }
1253
Mindy Pereira974c9662012-09-14 10:02:08 -07001254 @JavascriptInterface
Andy Huang543e7092013-04-22 11:44:56 -07001255 public String getMessageSender(String domId) {
1256 try {
1257 final MessageCursor cursor = getMessageCursor();
1258 if (!mViewsCreated || cursor == null) {
1259 return "";
1260 }
1261
1262 int pos = -1;
1263 while (cursor.moveToPosition(++pos)) {
1264 final ConversationMessage msg = cursor.getMessage();
1265 if (TextUtils.equals(domId, mTemplates.getMessageDomId(msg))) {
1266 return getAddress(msg.getFrom()).getAddress();
1267 }
1268 }
1269
1270 return "";
1271
1272 } catch (Throwable t) {
1273 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getMessageSender");
1274 return "";
1275 }
1276 }
1277
Andy Huang543e7092013-04-22 11:44:56 -07001278 @JavascriptInterface
mindyp3bcf1802012-09-09 11:17:00 -07001279 public void onContentReady() {
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -08001280 try {
1281 getHandler().post(new FragmentRunnable("onContentReady",
1282 ConversationViewFragment.this) {
1283 @Override
1284 public void go() {
1285 try {
1286 if (mWebViewLoadStartMs != 0) {
1287 LogUtils.i(LOG_TAG, "IN CVF.onContentReady, f=%s vis=%s t=%sms",
1288 ConversationViewFragment.this,
1289 isUserVisible(),
1290 (SystemClock.uptimeMillis() - mWebViewLoadStartMs));
1291 }
1292 revealConversation();
1293 } catch (Throwable t) {
1294 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onContentReady");
1295 // Still try to show the conversation.
1296 revealConversation();
Andy Huang63b3c672012-10-05 19:27:28 -07001297 }
mindyp3bcf1802012-09-09 11:17:00 -07001298 }
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -08001299 });
1300 } catch (Throwable t) {
1301 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onContentReady");
1302 }
mindyp3bcf1802012-09-09 11:17:00 -07001303 }
Andy Huange964eee2012-10-02 19:24:58 -07001304
Andy Huange964eee2012-10-02 19:24:58 -07001305 @JavascriptInterface
1306 public float getScrollYPercent() {
1307 try {
1308 return mWebViewYPercent;
1309 } catch (Throwable t) {
1310 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getScrollYPercent");
1311 return 0f;
1312 }
1313 }
Andy Huang05c70c82013-03-14 15:15:50 -07001314
Andy Huang05c70c82013-03-14 15:15:50 -07001315 @JavascriptInterface
1316 public void onMessageTransform(String messageDomId, String transformText) {
Andrew Sappersteinae92e152013-05-03 13:55:18 -07001317 try {
1318 LogUtils.i(LOG_TAG, "TRANSFORM: (%s) %s", messageDomId, transformText);
1319 mMessageTransforms.put(messageDomId, transformText);
1320 onConversationTransformed();
1321 } catch (Throwable t) {
1322 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onMessageTransform");
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -08001323 }
1324 }
1325
1326 @JavascriptInterface
1327 public void onInlineAttachmentsParsed(final String[] urls, final String[] messageIds) {
1328 try {
1329 getHandler().post(new FragmentRunnable("onInlineAttachmentsParsed",
1330 ConversationViewFragment.this) {
1331 @Override
1332 public void go() {
1333 try {
1334 for (int i = 0, size = urls.length; i < size; i++) {
1335 mUrlToMessageIdMap.put(urls[i], messageIds[i]);
1336 }
1337 } catch (ArrayIndexOutOfBoundsException e) {
1338 LogUtils.e(LOG_TAG, e,
1339 "Number of urls does not match number of message ids - %s:%s",
1340 urls.length, messageIds.length);
1341 }
1342 }
1343 });
1344 } catch (Throwable t) {
1345 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onInlineAttachmentsParsed");
Andrew Sappersteinae92e152013-05-03 13:55:18 -07001346 }
Andy Huang05c70c82013-03-14 15:15:50 -07001347 }
Andy Huangf70fc402012-02-17 15:37:42 -08001348 }
1349
Andy Huang47aa9c92012-07-31 15:37:21 -07001350 private class NewMessagesInfo {
1351 int count;
Andy Huang06c03622012-10-22 18:59:45 -07001352 int countFromSelf;
Andy Huang47aa9c92012-07-31 15:37:21 -07001353 String senderAddress;
1354
1355 /**
1356 * Return the display text for the new message notification overlay. It will be formatted
1357 * appropriately for a single new message vs. multiple new messages.
1358 *
1359 * @return display text
1360 */
1361 public String getNotificationText() {
mindypad0c30d2012-09-25 12:09:13 -07001362 Resources res = getResources();
Andy Huang47aa9c92012-07-31 15:37:21 -07001363 if (count > 1) {
Andrew Sapperstein66d69112013-08-23 12:24:44 -07001364 return res.getQuantityString(R.plurals.new_incoming_messages_many, count, count);
Andy Huang47aa9c92012-07-31 15:37:21 -07001365 } else {
Andy Huang16174812012-08-16 16:40:35 -07001366 final Address addr = getAddress(senderAddress);
mindypad0c30d2012-09-25 12:09:13 -07001367 return res.getString(R.string.new_incoming_messages_one,
Andrew Sapperstein2fd167d2014-01-28 10:07:38 -08001368 mBidiFormatter.unicodeWrap(TextUtils.isEmpty(addr.getPersonal())
1369 ? addr.getAddress() : addr.getPersonal()));
Andy Huang47aa9c92012-07-31 15:37:21 -07001370 }
Andy Huang47aa9c92012-07-31 15:37:21 -07001371 }
1372 }
1373
mindypf4fce122012-09-14 15:55:33 -07001374 @Override
Paul Westbrookc42ad5e2013-05-09 16:52:15 -07001375 public void onMessageCursorLoadFinished(Loader<ObjectCursor<ConversationMessage>> loader,
1376 MessageCursor newCursor, MessageCursor oldCursor) {
mindypf4fce122012-09-14 15:55:33 -07001377 /*
1378 * what kind of changes affect the MessageCursor? 1. new message(s) 2.
1379 * read/unread state change 3. deleted message, either regular or draft
1380 * 4. updated message, either from self or from others, updated in
1381 * content or state or sender 5. star/unstar of message (technically
1382 * similar to #1) 6. other label change Use MessageCursor.hashCode() to
1383 * sort out interesting vs. no-op cursor updates.
1384 */
Andy Huangb8331b42012-07-16 19:08:53 -07001385
Andy Huang233d4352012-10-18 14:00:24 -07001386 if (oldCursor != null && !oldCursor.isClosed()) {
Andy Huang014ea4c2012-09-25 14:50:54 -07001387 final NewMessagesInfo info = getNewIncomingMessagesInfo(newCursor);
Andy Huangb8331b42012-07-16 19:08:53 -07001388
Andy Huang014ea4c2012-09-25 14:50:54 -07001389 if (info.count > 0) {
1390 // don't immediately render new incoming messages from other
1391 // senders
1392 // (to avoid a new message from losing the user's focus)
1393 LogUtils.i(LOG_TAG, "CONV RENDER: conversation updated"
Andy Huang9d3fd922012-09-26 22:23:58 -07001394 + ", holding cursor for new incoming message (%s)", this);
Andy Huang014ea4c2012-09-25 14:50:54 -07001395 showNewMessageNotification(info);
1396 return;
1397 }
1398
Andy Huang06c03622012-10-22 18:59:45 -07001399 final int oldState = oldCursor.getStateHashCode();
1400 final boolean changed = newCursor.getStateHashCode() != oldState;
Andy Huang233d4352012-10-18 14:00:24 -07001401
Andy Huang014ea4c2012-09-25 14:50:54 -07001402 if (!changed) {
1403 final boolean processedInPlace = processInPlaceUpdates(newCursor, oldCursor);
1404 if (processedInPlace) {
Andy Huang9d3fd922012-09-26 22:23:58 -07001405 LogUtils.i(LOG_TAG, "CONV RENDER: processed update(s) in place (%s)", this);
Andy Huang1ee96b22012-08-24 20:19:53 -07001406 } else {
mindypf4fce122012-09-14 15:55:33 -07001407 LogUtils.i(LOG_TAG, "CONV RENDER: uninteresting update"
Andy Huang9d3fd922012-09-26 22:23:58 -07001408 + ", ignoring this conversation update (%s)", this);
Andy Huang1ee96b22012-08-24 20:19:53 -07001409 }
Andy Huangb8331b42012-07-16 19:08:53 -07001410 return;
Andy Huang06c03622012-10-22 18:59:45 -07001411 } else if (info.countFromSelf == 1) {
1412 // Special-case the very common case of a new cursor that is the same as the old
1413 // one, except that there is a new message from yourself. This happens upon send.
1414 final boolean sameExceptNewLast = newCursor.getStateHashCode(1) == oldState;
1415 if (sameExceptNewLast) {
1416 LogUtils.i(LOG_TAG, "CONV RENDER: update is a single new message from self"
1417 + " (%s)", this);
1418 newCursor.moveToLast();
1419 processNewOutgoingMessage(newCursor.getMessage());
1420 return;
1421 }
Andy Huangb8331b42012-07-16 19:08:53 -07001422 }
Andy Huang6766b6e2012-09-28 12:43:52 -07001423 // cursors are different, and not due to an incoming message. fall
1424 // through and render.
1425 LogUtils.i(LOG_TAG, "CONV RENDER: conversation updated"
1426 + ", but not due to incoming message. rendering. (%s)", this);
Andy Huang06c03622012-10-22 18:59:45 -07001427
1428 if (DEBUG_DUMP_CURSOR_CONTENTS) {
1429 LogUtils.i(LOG_TAG, "old cursor: %s", oldCursor.getDebugDump());
1430 LogUtils.i(LOG_TAG, "new cursor: %s", newCursor.getDebugDump());
1431 }
Andy Huang6766b6e2012-09-28 12:43:52 -07001432 } else {
1433 LogUtils.i(LOG_TAG, "CONV RENDER: initial render. (%s)", this);
Andy Huang243c2362013-03-01 17:50:35 -08001434 timerMark("message cursor load finished");
Andy Huangb8331b42012-07-16 19:08:53 -07001435 }
1436
Andrew Sapperstein606dbd72013-07-30 19:14:23 -07001437 renderContent(newCursor);
1438 }
1439
1440 protected void renderContent(MessageCursor messageCursor) {
Mark Wei4071c2f2012-09-26 14:38:38 -07001441 // if layout hasn't happened, delay render
1442 // This is needed in addition to the showConversation() delay to speed
1443 // up rotation and restoration.
1444 if (mConversationContainer.getWidth() == 0) {
1445 mNeedRender = true;
1446 mConversationContainer.addOnLayoutChangeListener(this);
1447 } else {
Andrew Sapperstein606dbd72013-07-30 19:14:23 -07001448 renderConversation(messageCursor);
Mark Wei4071c2f2012-09-26 14:38:38 -07001449 }
Andy Huangb8331b42012-07-16 19:08:53 -07001450 }
1451
mindypf4fce122012-09-14 15:55:33 -07001452 private NewMessagesInfo getNewIncomingMessagesInfo(MessageCursor newCursor) {
1453 final NewMessagesInfo info = new NewMessagesInfo();
Andy Huangb8331b42012-07-16 19:08:53 -07001454
mindypf4fce122012-09-14 15:55:33 -07001455 int pos = -1;
1456 while (newCursor.moveToPosition(++pos)) {
1457 final Message m = newCursor.getMessage();
1458 if (!mViewState.contains(m)) {
1459 LogUtils.i(LOG_TAG, "conversation diff: found new msg: %s", m.uri);
Andy Huangb8331b42012-07-16 19:08:53 -07001460
Scott Kennedy8960f0a2012-11-07 15:35:50 -08001461 final Address from = getAddress(m.getFrom());
mindypf4fce122012-09-14 15:55:33 -07001462 // distinguish ours from theirs
1463 // new messages from the account owner should not trigger a
1464 // notification
1465 if (mAccount.ownsFromAddress(from.getAddress())) {
1466 LogUtils.i(LOG_TAG, "found message from self: %s", m.uri);
Andy Huang06c03622012-10-22 18:59:45 -07001467 info.countFromSelf++;
mindypf4fce122012-09-14 15:55:33 -07001468 continue;
1469 }
Andy Huangb8331b42012-07-16 19:08:53 -07001470
mindypf4fce122012-09-14 15:55:33 -07001471 info.count++;
Scott Kennedy8960f0a2012-11-07 15:35:50 -08001472 info.senderAddress = m.getFrom();
Andy Huangb8331b42012-07-16 19:08:53 -07001473 }
Andy Huangb8331b42012-07-16 19:08:53 -07001474 }
mindypf4fce122012-09-14 15:55:33 -07001475 return info;
Andy Huangb8331b42012-07-16 19:08:53 -07001476 }
1477
Andy Huang014ea4c2012-09-25 14:50:54 -07001478 private boolean processInPlaceUpdates(MessageCursor newCursor, MessageCursor oldCursor) {
1479 final Set<String> idsOfChangedBodies = Sets.newHashSet();
Andy Huang6b3d0d92012-10-30 15:46:48 -07001480 final List<Integer> changedOverlayPositions = Lists.newArrayList();
1481
Andy Huang014ea4c2012-09-25 14:50:54 -07001482 boolean changed = false;
1483
1484 int pos = 0;
1485 while (true) {
1486 if (!newCursor.moveToPosition(pos) || !oldCursor.moveToPosition(pos)) {
1487 break;
1488 }
1489
1490 final ConversationMessage newMsg = newCursor.getMessage();
1491 final ConversationMessage oldMsg = oldCursor.getMessage();
1492
Jin Cao2ef5f082014-03-31 14:52:38 -07001493 // We are going to update the data in the adapter whenever any input fields change.
1494 // This ensures that the Message object that ComposeActivity uses will be correctly
1495 // aligned with the most up-to-date data.
1496 if (!newMsg.isEqual(oldMsg)) {
Andy Huang6b3d0d92012-10-30 15:46:48 -07001497 mAdapter.updateItemsForMessage(newMsg, changedOverlayPositions);
Jin Cao2ef5f082014-03-31 14:52:38 -07001498 LogUtils.i(LOG_TAG, "msg #%d (%d): detected field(s) change. isSending=%s",
Andy Huang2a1e8e32012-10-23 18:54:57 -07001499 pos, newMsg.id, newMsg.isSending);
Andy Huang014ea4c2012-09-25 14:50:54 -07001500 }
1501
1502 // update changed message bodies in-place
1503 if (!TextUtils.equals(newMsg.bodyHtml, oldMsg.bodyHtml) ||
1504 !TextUtils.equals(newMsg.bodyText, oldMsg.bodyText)) {
1505 // maybe just set a flag to notify JS to re-request changed bodies
1506 idsOfChangedBodies.add('"' + mTemplates.getMessageDomId(newMsg) + '"');
1507 LogUtils.i(LOG_TAG, "msg #%d (%d): detected body change", pos, newMsg.id);
1508 }
1509
1510 pos++;
1511 }
1512
Andy Huang6b3d0d92012-10-30 15:46:48 -07001513
1514 if (!changedOverlayPositions.isEmpty()) {
Andy Huang06c03622012-10-22 18:59:45 -07001515 // notify once after the entire adapter is updated
Andy Huang6b3d0d92012-10-30 15:46:48 -07001516 mConversationContainer.onOverlayModelUpdate(changedOverlayPositions);
1517 changed = true;
Andy Huang06c03622012-10-22 18:59:45 -07001518 }
1519
Andy Huang014ea4c2012-09-25 14:50:54 -07001520 if (!idsOfChangedBodies.isEmpty()) {
1521 mWebView.loadUrl(String.format("javascript:replaceMessageBodies([%s]);",
1522 TextUtils.join(",", idsOfChangedBodies)));
1523 changed = true;
1524 }
1525
1526 return changed;
1527 }
1528
Andy Huang06c03622012-10-22 18:59:45 -07001529 private void processNewOutgoingMessage(ConversationMessage msg) {
Andrew Sapperstein99ee4562013-08-22 16:19:42 -07001530 // if there are items in the adapter and the last item is a border,
1531 // make the last border no longer be the last border
1532 if (mAdapter.getCount() > 0) {
1533 final ConversationOverlayItem item = mAdapter.getItem(mAdapter.getCount() - 1);
1534 if (item.getType() == ConversationViewAdapter.VIEW_TYPE_BORDER) {
1535 ((BorderItem) item).setIsLastBorder(false);
1536 }
1537 }
Andrew Sappersteincee3c902013-07-31 10:52:02 -07001538
Andy Huang06c03622012-10-22 18:59:45 -07001539 mTemplates.reset();
1540 // this method will add some items to mAdapter, but we deliberately want to avoid notifying
1541 // adapter listeners (i.e. ConversationContainer) until onWebContentGeometryChange is next
1542 // called, to prevent N+1 headers rendering with N message bodies.
Andrew Sappersteincee3c902013-07-31 10:52:02 -07001543
1544 // We can just call previousCollapsed false here since the border
1545 // above the message we're about to render should always show
1546 // (which it also will since the message being render is expanded).
1547 renderMessage(msg, false /* previousCollapsed */, true /* expanded */,
1548 msg.alwaysShowImages, false /* renderBorder */, false /* firstBorder */);
1549 renderBorder(true /* contiguous */, true /* expanded */,
1550 false /* firstBorder */, true /* lastBorder */);
Andy Huang06c03622012-10-22 18:59:45 -07001551 mTempBodiesHtml = mTemplates.emit();
1552
1553 mViewState.setExpansionState(msg, ExpansionState.EXPANDED);
1554 // FIXME: should the provider set this as initial state?
1555 mViewState.setReadState(msg, false /* read */);
1556
Andy Huang91d782a2012-10-25 12:37:29 -07001557 // From now until the updated spacer geometry is returned, the adapter items are mismatched
1558 // with the existing spacers. Do not let them layout.
1559 mConversationContainer.invalidateSpacerGeometry();
1560
Andy Huang06c03622012-10-22 18:59:45 -07001561 mWebView.loadUrl("javascript:appendMessageHtml();");
1562 }
1563
Andrew Sappersteinf59d01c2014-02-20 10:27:06 -08001564 private static class SetCookieTask extends AsyncTask<Void, Void, Void> {
1565 private final Context mContext;
1566 private final String mUri;
1567 private final Uri mAccountCookieQueryUri;
1568 private final ContentResolver mResolver;
Paul Westbrookcebcc642012-08-08 10:06:04 -07001569
Andrew Sappersteinf59d01c2014-02-20 10:27:06 -08001570 /* package */ SetCookieTask(Context context, String baseUri, Uri accountCookieQueryUri) {
1571 mContext = context;
1572 mUri = baseUri;
Paul Westbrookb8361c92012-09-27 10:57:14 -07001573 mAccountCookieQueryUri = accountCookieQueryUri;
1574 mResolver = context.getContentResolver();
Paul Westbrookcebcc642012-08-08 10:06:04 -07001575 }
1576
1577 @Override
1578 public Void doInBackground(Void... args) {
Andrew Sappersteinf59d01c2014-02-20 10:27:06 -08001579 // First query for the cookie string from the UI provider
Paul Westbrookb8361c92012-09-27 10:57:14 -07001580 final Cursor cookieCursor = mResolver.query(mAccountCookieQueryUri,
1581 UIProvider.ACCOUNT_COOKIE_PROJECTION, null, null, null);
1582 if (cookieCursor == null) {
1583 return null;
1584 }
1585
1586 try {
1587 if (cookieCursor.moveToFirst()) {
1588 final String cookie = cookieCursor.getString(
1589 cookieCursor.getColumnIndex(UIProvider.AccountCookieColumns.COOKIE));
1590
1591 if (cookie != null) {
1592 final CookieSyncManager csm =
Andrew Sappersteinf59d01c2014-02-20 10:27:06 -08001593 CookieSyncManager.createInstance(mContext);
Paul Westbrookb8361c92012-09-27 10:57:14 -07001594 CookieManager.getInstance().setCookie(mUri, cookie);
1595 csm.sync();
1596 }
1597 }
1598
1599 } finally {
1600 cookieCursor.close();
1601 }
1602
1603
Paul Westbrookcebcc642012-08-08 10:06:04 -07001604 return null;
1605 }
1606 }
mindyp36280f32012-09-09 16:11:23 -07001607
mindyp26d4d2d2012-09-18 17:30:32 -07001608 @Override
mindyp36280f32012-09-09 16:11:23 -07001609 public void onConversationUpdated(Conversation conv) {
1610 final ConversationViewHeader headerView = (ConversationViewHeader) mConversationContainer
1611 .findViewById(R.id.conversation_header);
mindypb2b98ba2012-09-24 14:13:58 -07001612 mConversation = conv;
mindyp9e0b2362012-09-09 16:31:21 -07001613 if (headerView != null) {
1614 headerView.onConversationUpdated(conv);
Andrew Sappersteine6bf30d2014-03-13 19:19:26 -07001615 headerView.setSubject(conv.subject);
mindyp9e0b2362012-09-09 16:31:21 -07001616 }
mindyp36280f32012-09-09 16:11:23 -07001617 }
Mark Wei4071c2f2012-09-26 14:38:38 -07001618
1619 @Override
1620 public void onLayoutChange(View v, int left, int top, int right,
1621 int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
1622 boolean sizeChanged = mNeedRender
1623 && mConversationContainer.getWidth() != 0;
1624 if (sizeChanged) {
1625 mNeedRender = false;
1626 mConversationContainer.removeOnLayoutChangeListener(this);
1627 renderConversation(getMessageCursor());
1628 }
1629 }
mindyp1b3cc472012-09-27 11:32:59 -07001630
1631 @Override
James Lemieux7cad2802014-01-09 15:00:53 -08001632 public void setMessageDetailsExpanded(MessageHeaderItem i, boolean expanded, int heightBefore) {
mindyp1b3cc472012-09-27 11:32:59 -07001633 mDiff = (expanded ? 1 : -1) * Math.abs(i.getHeight() - heightBefore);
1634 }
Andy Huang02f9d182012-11-28 22:38:02 -08001635
James Lemieux7cad2802014-01-09 15:00:53 -08001636 /**
1637 * @return {@code true} because either the Print or Print All menu item is shown in GMail
1638 */
1639 @Override
1640 protected boolean shouldShowPrintInOverflow() {
1641 return true;
1642 }
1643
1644 @Override
Andrew Sapperstein5c1692a2013-09-16 11:56:13 -07001645 protected void printConversation() {
Andrew Sapperstein234d3532013-10-29 14:54:04 -07001646 PrintUtils.printConversation(mActivity.getActivityContext(), getMessageCursor(),
1647 mAddressCache, mConversation.getBaseUri(mBaseUri), true /* useJavascript */);
Andrew Sapperstein5c1692a2013-09-16 11:56:13 -07001648 }
Mindy Pereira9b875682012-02-15 18:10:54 -08001649}