blob: 41a4b3d63c18ed1024720c0ff3676f309e14e775 [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;
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;
Andrew Sapperstein14f93742013-07-25 14:29:56 -070055import com.android.mail.browse.ConversationViewAdapter.BorderItem;
Andy Huang46dfba62012-04-19 01:47:32 -070056import com.android.mail.browse.ConversationViewAdapter.MessageFooterItem;
Andy Huang7bdc3752012-03-25 17:18:19 -070057import com.android.mail.browse.ConversationViewAdapter.MessageHeaderItem;
Andy Huang46dfba62012-04-19 01:47:32 -070058import com.android.mail.browse.ConversationViewAdapter.SuperCollapsedBlockItem;
Andy Huang5ff63742012-03-16 20:30:23 -070059import com.android.mail.browse.ConversationViewHeader;
60import com.android.mail.browse.ConversationWebView;
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -080061import com.android.mail.browse.InlineAttachmentViewIntentBuilderCreator;
62import com.android.mail.browse.InlineAttachmentViewIntentBuilderCreatorHolder;
Andy Huangc1fb9a92013-02-11 13:09:12 -080063import com.android.mail.browse.MailWebView.ContentSizeChangeListener;
Andy Huang7bdc3752012-03-25 17:18:19 -070064import com.android.mail.browse.MessageCursor;
Andy Huang59e0b182012-08-14 14:32:23 -070065import com.android.mail.browse.MessageHeaderView;
Andy Huangadbf3e82012-10-13 13:30:19 -070066import com.android.mail.browse.ScrollIndicatorsView;
Andy Huang46dfba62012-04-19 01:47:32 -070067import com.android.mail.browse.SuperCollapsedBlock;
Andy Huang0b7ed6f2012-07-25 19:23:26 -070068import com.android.mail.browse.WebViewContextMenu;
Paul Westbrookc42ad5e2013-05-09 16:52:15 -070069import com.android.mail.content.ObjectCursor;
Andrew Sapperstein562c5ba2013-10-09 18:31:50 -070070import com.android.mail.print.PrintUtils;
Mindy Pereira9b875682012-02-15 18:10:54 -080071import com.android.mail.providers.Account;
72import com.android.mail.providers.Conversation;
Andy Huangf70fc402012-02-17 15:37:42 -080073import com.android.mail.providers.Message;
Alice Yangf323c042013-10-30 00:15:02 -070074import com.android.mail.providers.Settings;
Paul Westbrookb8361c92012-09-27 10:57:14 -070075import com.android.mail.providers.UIProvider;
Andy Huangcd5c5ee2012-08-12 19:03:51 -070076import com.android.mail.ui.ConversationViewState.ExpansionState;
Andrew Sapperstein376294b2013-06-06 16:04:26 -070077import com.android.mail.utils.ConversationViewUtils;
Paul Westbrookb334c902012-06-25 11:42:46 -070078import com.android.mail.utils.LogTag;
Mindy Pereira9b875682012-02-15 18:10:54 -080079import com.android.mail.utils.LogUtils;
Andy Huang2e9acfe2012-03-15 22:39:36 -070080import com.android.mail.utils.Utils;
Andy Huang543e7092013-04-22 11:44:56 -070081import com.google.common.collect.ImmutableList;
Andy Huang46dfba62012-04-19 01:47:32 -070082import com.google.common.collect.Lists;
Andy Huang05c70c82013-03-14 15:15:50 -070083import com.google.common.collect.Maps;
Andy Huangb8331b42012-07-16 19:08:53 -070084import com.google.common.collect.Sets;
Andy Huang65fe28f2012-04-06 18:08:53 -070085
Scott Kennedyeb9a4bd2012-11-12 10:33:04 -080086import java.util.ArrayList;
Andy Huang46dfba62012-04-19 01:47:32 -070087import java.util.List;
Andy Huang05c70c82013-03-14 15:15:50 -070088import java.util.Map;
Andy Huangb8331b42012-07-16 19:08:53 -070089import java.util.Set;
Mindy Pereira9b875682012-02-15 18:10:54 -080090
91/**
92 * The conversation view UI component.
93 */
Andrew Sapperstein9f957f32013-07-19 15:18:18 -070094public class ConversationViewFragment extends AbstractConversationViewFragment implements
Andrew Sapperstein4ddda2f2013-06-10 11:15:38 -070095 SuperCollapsedBlock.OnClickListener, OnLayoutChangeListener,
96 MessageHeaderView.MessageHeaderViewCallbacks {
Mindy Pereira8e915722012-02-16 14:42:56 -080097
Paul Westbrookb334c902012-06-25 11:42:46 -070098 private static final String LOG_TAG = LogTag.getLogTag();
Andy Huang632721e2012-04-11 16:57:26 -070099 public static final String LAYOUT_TAG = "ConvLayout";
Mindy Pereira9b875682012-02-15 18:10:54 -0800100
Andy Huang9d3fd922012-09-26 22:23:58 -0700101 /**
mindyp1b3cc472012-09-27 11:32:59 -0700102 * Difference in the height of the message header whose details have been expanded/collapsed
103 */
104 private int mDiff = 0;
105
106 /**
Andy Huang9d3fd922012-09-26 22:23:58 -0700107 * Default value for {@link #mLoadWaitReason}. Conversation load will happen immediately.
108 */
109 private final int LOAD_NOW = 0;
110 /**
111 * Value for {@link #mLoadWaitReason} that means we are offscreen and waiting for the visible
112 * conversation to finish loading before beginning our load.
113 * <p>
114 * When this value is set, the fragment should register with {@link ConversationListCallbacks}
115 * to know when the visible conversation is loaded. When it is unset, it should unregister.
116 */
117 private final int LOAD_WAIT_FOR_INITIAL_CONVERSATION = 1;
118 /**
119 * Value for {@link #mLoadWaitReason} used when a conversation is too heavyweight to load at
120 * all when not visible (e.g. requires network fetch, or too complex). Conversation load will
121 * wait until this fragment is visible.
122 */
123 private final int LOAD_WAIT_UNTIL_VISIBLE = 2;
mindyp3bcf1802012-09-09 11:17:00 -0700124
Andrew Sapperstein9f957f32013-07-19 15:18:18 -0700125 protected ConversationContainer mConversationContainer;
Mindy Pereira9b875682012-02-15 18:10:54 -0800126
Andrew Sapperstein9f957f32013-07-19 15:18:18 -0700127 protected ConversationWebView mWebView;
Mindy Pereira9b875682012-02-15 18:10:54 -0800128
Mark Wei56d83852012-09-19 14:28:50 -0700129 private ScrollIndicatorsView mScrollIndicators;
130
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700131 private ConversationViewProgressController mProgressController;
132
Andrew Sapperstein821fa872013-08-21 21:57:39 -0700133 private Button mNewMessageBar;
Andy Huang47aa9c92012-07-31 15:37:21 -0700134
Andrew Sapperstein9f957f32013-07-19 15:18:18 -0700135 protected HtmlConversationTemplates mTemplates;
Andy Huangf70fc402012-02-17 15:37:42 -0800136
Andy Huangf70fc402012-02-17 15:37:42 -0800137 private final MailJsBridge mJsBridge = new MailJsBridge();
138
Andrew Sapperstein9f957f32013-07-19 15:18:18 -0700139 protected ConversationViewAdapter mAdapter;
Andy Huang51067132012-03-12 20:08:19 -0700140
Andrew Sappersteinb1d184d2013-08-09 14:14:31 -0700141 protected boolean mViewsCreated;
Mark Wei4071c2f2012-09-26 14:38:38 -0700142 // True if we attempted to render before the views were laid out
143 // We will render immediately once layout is done
144 private boolean mNeedRender;
Andy Huang51067132012-03-12 20:08:19 -0700145
Andy Huang46dfba62012-04-19 01:47:32 -0700146 /**
147 * Temporary string containing the message bodies of the messages within a super-collapsed
148 * block, for one-time use during block expansion. We cannot easily pass the body HTML
149 * into JS without problematic escaping, so hold onto it momentarily and signal JS to fetch it
150 * using {@link MailJsBridge}.
151 */
152 private String mTempBodiesHtml;
153
Andy Huang632721e2012-04-11 16:57:26 -0700154 private int mMaxAutoLoadMessages;
155
Andrew Sapperstein9f957f32013-07-19 15:18:18 -0700156 protected int mSideMarginPx;
Andy Huang02f9d182012-11-28 22:38:02 -0800157
Andy Huang9d3fd922012-09-26 22:23:58 -0700158 /**
159 * If this conversation fragment is not visible, and it's inappropriate to load up front,
160 * this is the reason we are waiting. This flag should be cleared once it's okay to load
161 * the conversation.
162 */
163 private int mLoadWaitReason = LOAD_NOW;
Andy Huang632721e2012-04-11 16:57:26 -0700164
mindyp3bcf1802012-09-09 11:17:00 -0700165 private boolean mEnableContentReadySignal;
Andy Huang28b7aee2012-08-20 20:27:32 -0700166
mindypdde3f9f2012-09-10 17:35:35 -0700167 private ContentSizeChangeListener mWebViewSizeChangeListener;
168
Andy Huange964eee2012-10-02 19:24:58 -0700169 private float mWebViewYPercent;
170
171 /**
172 * Has loadData been called on the WebView yet?
173 */
174 private boolean mWebViewLoadedData;
175
Andy Huang63b3c672012-10-05 19:27:28 -0700176 private long mWebViewLoadStartMs;
177
Andy Huang05c70c82013-03-14 15:15:50 -0700178 private final Map<String, String> mMessageTransforms = Maps.newHashMap();
179
Andy Huang9d3fd922012-09-26 22:23:58 -0700180 private final DataSetObserver mLoadedObserver = new DataSetObserver() {
181 @Override
182 public void onChanged() {
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700183 getHandler().post(new FragmentRunnable("delayedConversationLoad",
184 ConversationViewFragment.this) {
Andy Huang9d3fd922012-09-26 22:23:58 -0700185 @Override
186 public void go() {
187 LogUtils.d(LOG_TAG, "CVF load observer fired, this=%s",
188 ConversationViewFragment.this);
189 handleDelayedConversationLoad();
190 }
191 });
192 }
193 };
Andy Huangf70fc402012-02-17 15:37:42 -0800194
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700195 private final Runnable mOnProgressDismiss = new FragmentRunnable("onProgressDismiss", this) {
Andy Huang7d4746e2012-10-17 17:03:17 -0700196 @Override
197 public void go() {
Scott Kennedy58192e52013-05-08 16:35:57 -0700198 LogUtils.d(LOG_TAG, "onProgressDismiss go() - isUserVisible() = %b", isUserVisible());
Andy Huang7d4746e2012-10-17 17:03:17 -0700199 if (isUserVisible()) {
200 onConversationSeen();
201 }
Andy Huang30bcfe72012-10-18 18:09:03 -0700202 mWebView.onRenderComplete();
Andy Huang7d4746e2012-10-17 17:03:17 -0700203 }
204 };
205
Andy Huangbd544e32012-05-29 15:56:51 -0700206 private static final boolean DEBUG_DUMP_CONVERSATION_HTML = false;
Andy Huang47aa9c92012-07-31 15:37:21 -0700207 private static final boolean DISABLE_OFFSCREEN_LOADING = false;
Andy Huang06c03622012-10-22 18:59:45 -0700208 private static final boolean DEBUG_DUMP_CURSOR_CONTENTS = false;
Andy Huange964eee2012-10-02 19:24:58 -0700209
210 private static final String BUNDLE_KEY_WEBVIEW_Y_PERCENT =
211 ConversationViewFragment.class.getName() + "webview-y-percent";
Andy Huangbd544e32012-05-29 15:56:51 -0700212
Andrew Sapperstein2fd167d2014-01-28 10:07:38 -0800213 private BidiFormatter mBidiFormatter;
Andrew Sapperstein3af481c2013-10-30 10:29:38 -0700214
Vikram Aggarwal6c511582012-02-27 10:59:47 -0800215 /**
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -0800216 * Contains a mapping between inline image attachments and their local message id.
217 */
218 private Map<String, String> mUrlToMessageIdMap;
219
220 /**
Vikram Aggarwal6c511582012-02-27 10:59:47 -0800221 * Constructor needs to be public to handle orientation changes and activity lifecycle events.
222 */
Paul Westbrookf0ea4842013-08-13 16:41:18 -0700223 public ConversationViewFragment() {}
Mindy Pereira9b875682012-02-15 18:10:54 -0800224
225 /**
226 * Creates a new instance of {@link ConversationViewFragment}, initialized
Andy Huang632721e2012-04-11 16:57:26 -0700227 * to display a conversation with other parameters inherited/copied from an existing bundle,
228 * typically one created using {@link #makeBasicArgs}.
229 */
230 public static ConversationViewFragment newInstance(Bundle existingArgs,
231 Conversation conversation) {
232 ConversationViewFragment f = new ConversationViewFragment();
233 Bundle args = new Bundle(existingArgs);
234 args.putParcelable(ARG_CONVERSATION, conversation);
235 f.setArguments(args);
236 return f;
237 }
238
mindypf4fce122012-09-14 15:55:33 -0700239 @Override
Andy Huangadbf3e82012-10-13 13:30:19 -0700240 public void onAccountChanged(Account newAccount, Account oldAccount) {
241 // if overview mode has changed, re-render completely (no need to also update headers)
242 if (isOverviewMode(newAccount) != isOverviewMode(oldAccount)) {
243 setupOverviewMode();
244 final MessageCursor c = getMessageCursor();
245 if (c != null) {
246 renderConversation(c);
247 } else {
248 // Null cursor means this fragment is either waiting to load or in the middle of
249 // loading. Either way, a future render will happen anyway, and the new setting
250 // will take effect when that happens.
251 }
252 return;
253 }
254
mindypf4fce122012-09-14 15:55:33 -0700255 // settings may have been updated; refresh views that are known to
256 // depend on settings
mindypf4fce122012-09-14 15:55:33 -0700257 mAdapter.notifyDataSetChanged();
Andy Huang632721e2012-04-11 16:57:26 -0700258 }
259
Mindy Pereira9b875682012-02-15 18:10:54 -0800260 @Override
261 public void onActivityCreated(Bundle savedInstanceState) {
Andy Huang9d3fd922012-09-26 22:23:58 -0700262 LogUtils.d(LOG_TAG, "IN CVF.onActivityCreated, this=%s visible=%s", this, isUserVisible());
Mindy Pereira9b875682012-02-15 18:10:54 -0800263 super.onActivityCreated(savedInstanceState);
Mark Wei1abfcaf2012-09-27 11:11:07 -0700264
265 if (mActivity == null || mActivity.isFinishing()) {
266 // Activity is finishing, just bail.
267 return;
268 }
269
mindypf4fce122012-09-14 15:55:33 -0700270 Context context = getContext();
271 mTemplates = new HtmlConversationTemplates(context);
Andy Huang59e0b182012-08-14 14:32:23 -0700272
mindypf4fce122012-09-14 15:55:33 -0700273 final FormattedDateBuilder dateBuilder = new FormattedDateBuilder(context);
Andy Huang59e0b182012-08-14 14:32:23 -0700274
Paul Westbrook8081df42012-09-10 15:43:36 -0700275 mAdapter = new ConversationViewAdapter(mActivity, this,
mindypf4fce122012-09-14 15:55:33 -0700276 getLoaderManager(), this, getContactInfoSource(), this,
Andrew Sapperstein2fd167d2014-01-28 10:07:38 -0800277 this, mAddressCache, dateBuilder, mBidiFormatter);
Andy Huang51067132012-03-12 20:08:19 -0700278 mConversationContainer.setOverlayAdapter(mAdapter);
279
Andy Huang59e0b182012-08-14 14:32:23 -0700280 // set up snap header (the adapter usually does this with the other ones)
Andrew Sapperstein85ea6182013-10-14 18:21:08 -0700281 mConversationContainer.getSnapHeader().initialize(
282 this, mAddressCache, this, getContactInfoSource(),
283 mActivity.getAccountController().getVeiledAddressMatcher());
Andy Huangc1fb9a92013-02-11 13:09:12 -0800284
Andrew Sapperstein90eccf92013-08-22 11:53:23 -0700285 final Resources resources = getResources();
286 mMaxAutoLoadMessages = resources.getInteger(R.integer.max_auto_load_messages);
Andy Huang632721e2012-04-11 16:57:26 -0700287
Andrew Sapperstein90eccf92013-08-22 11:53:23 -0700288 mSideMarginPx = resources.getDimensionPixelOffset(
Andy Huang02f9d182012-11-28 22:38:02 -0800289 R.dimen.conversation_message_content_margin_side);
290
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -0800291 mUrlToMessageIdMap = new ArrayMap<String, String>();
292 final InlineAttachmentViewIntentBuilderCreator creator =
293 InlineAttachmentViewIntentBuilderCreatorHolder.
294 getInlineAttachmentViewIntentCreator();
295 mWebView.setOnCreateContextMenuListener(new WebViewContextMenu(getActivity(),
296 creator.createInlineAttachmentViewIntentBuilder(
297 mUrlToMessageIdMap, mAccount.getEmailAddress(),
298 mConversation != null ? mConversation.id : -1)));
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 &&
Paul Westbrookb8361c92012-09-27 10:57:14 -0700321 !Utils.isEmpty(mAccount.accoutCookieQueryUri)) {
Paul Westbrookcebcc642012-08-08 10:06:04 -0700322 // Set the cookie for this base url
Paul Westbrookb8361c92012-09-27 10:57:14 -0700323 new SetCookieTask(getContext(), mConversation.conversationBaseUri,
324 mAccount.accoutCookieQueryUri).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
Mark Wei56d83852012-09-19 14:28:50 -0700402 mScrollIndicators = (ScrollIndicatorsView) rootView.findViewById(R.id.scroll_indicators);
403 mScrollIndicators.setSourceView(mWebView);
404
Andy Huangf70fc402012-02-17 15:37:42 -0800405 settings.setJavaScriptEnabled(true);
Andy Huangf70fc402012-02-17 15:37:42 -0800406
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700407 ConversationViewUtils.setTextZoom(getResources(), settings);
Andy Huangc319b552012-04-25 19:53:50 -0700408
Andy Huang51067132012-03-12 20:08:19 -0700409 mViewsCreated = true;
Andy Huange964eee2012-10-02 19:24:58 -0700410 mWebViewLoadedData = false;
Andy Huang51067132012-03-12 20:08:19 -0700411
Mindy Pereira9b875682012-02-15 18:10:54 -0800412 return rootView;
413 }
414
Andrew Sapperstein85ea6182013-10-14 18:21:08 -0700415 protected void inflateSnapHeader(ViewGroup topmostOverlay, LayoutInflater inflater) {
416 inflater.inflate(R.layout.conversation_topmost_overlay_items, topmostOverlay, true);
417 }
418
419 protected void setupNewMessageBar() {
420 mNewMessageBar = (Button) mConversationContainer.findViewById(
421 R.id.new_message_notification_bar);
422 mNewMessageBar.setOnClickListener(new View.OnClickListener() {
423 @Override
424 public void onClick(View v) {
425 onNewMessageBarClick();
426 }
427 });
428 }
429
Mindy Pereira9b875682012-02-15 18:10:54 -0800430 @Override
Andy Huangf7ac83f2013-07-15 15:48:31 -0700431 public void onResume() {
432 super.onResume();
433 if (mWebView != null) {
434 mWebView.onResume();
435 }
436 }
437
438 @Override
439 public void onPause() {
440 super.onPause();
441 if (mWebView != null) {
442 mWebView.onPause();
443 }
444 }
445
446 @Override
Mindy Pereira9b875682012-02-15 18:10:54 -0800447 public void onDestroyView() {
Mindy Pereira9b875682012-02-15 18:10:54 -0800448 super.onDestroyView();
Andy Huang46dfba62012-04-19 01:47:32 -0700449 mConversationContainer.setOverlayAdapter(null);
450 mAdapter = null;
Andy Huang9d3fd922012-09-26 22:23:58 -0700451 resetLoadWaiting(); // be sure to unregister any active load observer
Andy Huang51067132012-03-12 20:08:19 -0700452 mViewsCreated = false;
Mindy Pereira9b875682012-02-15 18:10:54 -0800453 }
454
Andy Huange964eee2012-10-02 19:24:58 -0700455 @Override
456 public void onSaveInstanceState(Bundle outState) {
457 super.onSaveInstanceState(outState);
458
459 outState.putFloat(BUNDLE_KEY_WEBVIEW_Y_PERCENT, calculateScrollYPercent());
460 }
461
462 private float calculateScrollYPercent() {
Paul Westbrook1b56a672013-04-19 01:19:05 -0700463 final float p;
464 if (mWebView == null) {
465 // onCreateView hasn't been called, return 0 as the user hasn't scrolled the view.
466 return 0;
467 }
468
469 final int scrollY = mWebView.getScrollY();
470 final int viewH = mWebView.getHeight();
471 final int webH = (int) (mWebView.getContentHeight() * mWebView.getScale());
Andy Huange964eee2012-10-02 19:24:58 -0700472
473 if (webH == 0 || webH <= viewH) {
474 p = 0;
475 } else if (scrollY + viewH >= webH) {
476 // The very bottom is a special case, it acts as a stronger anchor than the scroll top
477 // at that point.
478 p = 1.0f;
479 } else {
480 p = (float) scrollY / webH;
481 }
482 return p;
483 }
484
Andy Huang9d3fd922012-09-26 22:23:58 -0700485 private void resetLoadWaiting() {
486 if (mLoadWaitReason == LOAD_WAIT_FOR_INITIAL_CONVERSATION) {
487 getListController().unregisterConversationLoadedObserver(mLoadedObserver);
488 }
489 mLoadWaitReason = LOAD_NOW;
490 }
491
Andy Huang5ff63742012-03-16 20:30:23 -0700492 @Override
mindypf4fce122012-09-14 15:55:33 -0700493 protected void markUnread() {
Vikram Aggarwald82a31f2013-02-05 15:03:00 -0800494 super.markUnread();
Andy Huang839ada22012-07-20 15:48:40 -0700495 // Ignore unsafe calls made after a fragment is detached from an activity
496 final ControllableActivity activity = (ControllableActivity) getActivity();
497 if (activity == null) {
498 LogUtils.w(LOG_TAG, "ignoring markUnread for conv=%s", mConversation.id);
499 return;
500 }
501
Andy Huang28e31e22012-07-26 16:33:15 -0700502 if (mViewState == null) {
503 LogUtils.i(LOG_TAG, "ignoring markUnread for conv with no view state (%d)",
504 mConversation.id);
505 return;
506 }
Andy Huang839ada22012-07-20 15:48:40 -0700507 activity.getConversationUpdater().markConversationMessagesUnread(mConversation,
Vikram Aggarwal4a878b62012-07-31 15:09:25 -0700508 mViewState.getUnreadMessageUris(), mViewState.getConversationInfo());
Andy Huang839ada22012-07-20 15:48:40 -0700509 }
510
mindypf4fce122012-09-14 15:55:33 -0700511 @Override
512 public void onUserVisibleHintChanged() {
Andy Huang9d3fd922012-09-26 22:23:58 -0700513 final boolean userVisible = isUserVisible();
Scott Kennedy58192e52013-05-08 16:35:57 -0700514 LogUtils.d(LOG_TAG, "ConversationViewFragment#onUserVisibleHintChanged(), userVisible = %b",
515 userVisible);
Andy Huang9d3fd922012-09-26 22:23:58 -0700516
517 if (!userVisible) {
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700518 mProgressController.dismissLoadingStatus();
Andy Huang9d3fd922012-09-26 22:23:58 -0700519 } else if (mViewsCreated) {
Andy Huange6c9fb62013-11-15 09:56:20 -0800520 String loadTag = null;
Andy Huangeeb4a352013-11-21 10:56:27 -0800521 final boolean isInitialLoading;
522 if (mActivity != null) {
523 isInitialLoading = mActivity.getConversationUpdater()
Andy Huange6c9fb62013-11-15 09:56:20 -0800524 .isInitialConversationLoading();
Andy Huangeeb4a352013-11-21 10:56:27 -0800525 } else {
526 isInitialLoading = true;
527 }
Andy Huange6c9fb62013-11-15 09:56:20 -0800528
Andy Huang9d3fd922012-09-26 22:23:58 -0700529 if (getMessageCursor() != null) {
530 LogUtils.d(LOG_TAG, "Fragment is now user-visible, onConversationSeen: %s", this);
Andy Huange6c9fb62013-11-15 09:56:20 -0800531 if (!isInitialLoading) {
532 loadTag = "preloaded";
533 }
Andy Huang9d3fd922012-09-26 22:23:58 -0700534 onConversationSeen();
535 } else if (isLoadWaiting()) {
536 LogUtils.d(LOG_TAG, "Fragment is now user-visible, showing conversation: %s", this);
Andy Huange6c9fb62013-11-15 09:56:20 -0800537 if (!isInitialLoading) {
538 loadTag = "load_deferred";
539 }
Andy Huang9d3fd922012-09-26 22:23:58 -0700540 handleDelayedConversationLoad();
541 }
Andy Huange6c9fb62013-11-15 09:56:20 -0800542
543 if (loadTag != null) {
544 // pager swipes are visibility transitions to 'visible' except during initial
545 // pager load on A) enter conversation mode B) rotate C) 2-pane conv-mode list-tap
546 Analytics.getInstance().sendEvent("pager_swipe", loadTag,
547 getCurrentFolderTypeDesc(), 0);
548 }
Andy Huang632721e2012-04-11 16:57:26 -0700549 }
Andy Huang632721e2012-04-11 16:57:26 -0700550
Andy Huang30bcfe72012-10-18 18:09:03 -0700551 if (mWebView != null) {
552 mWebView.onUserVisibilityChanged(userVisible);
553 }
Andy Huangf8cf5462012-10-17 18:29:14 -0700554 }
555
Andy Huang9d3fd922012-09-26 22:23:58 -0700556 /**
557 * Will either call initLoader now to begin loading, or set {@link #mLoadWaitReason} and do
558 * nothing (in which case you should later call {@link #handleDelayedConversationLoad()}).
559 */
Mindy Pereira9b875682012-02-15 18:10:54 -0800560 private void showConversation() {
Andy Huang9d3fd922012-09-26 22:23:58 -0700561 final int reason;
562
563 if (isUserVisible()) {
564 LogUtils.i(LOG_TAG,
565 "SHOWCONV: CVF is user-visible, immediately loading conversation (%s)", this);
566 reason = LOAD_NOW;
Andy Huang243c2362013-03-01 17:50:35 -0800567 timerMark("CVF.showConversation");
Andy Huang9d3fd922012-09-26 22:23:58 -0700568 } else {
569 final boolean disableOffscreenLoading = DISABLE_OFFSCREEN_LOADING
Alice Yang0b8c0802013-09-16 14:35:18 -0700570 || Utils.isLowRamDevice(getContext())
Andrew Sapperstein606dbd72013-07-30 19:14:23 -0700571 || (mConversation != null && (mConversation.isRemote
572 || mConversation.getNumMessages() > mMaxAutoLoadMessages));
Andy Huang9d3fd922012-09-26 22:23:58 -0700573
574 // When not visible, we should not immediately load if either this conversation is
575 // too heavyweight, or if the main/initial conversation is busy loading.
576 if (disableOffscreenLoading) {
577 reason = LOAD_WAIT_UNTIL_VISIBLE;
578 LogUtils.i(LOG_TAG, "SHOWCONV: CVF waiting until visible to load (%s)", this);
579 } else if (getListController().isInitialConversationLoading()) {
580 reason = LOAD_WAIT_FOR_INITIAL_CONVERSATION;
581 LogUtils.i(LOG_TAG, "SHOWCONV: CVF waiting for initial to finish (%s)", this);
582 getListController().registerConversationLoadedObserver(mLoadedObserver);
583 } else {
584 LogUtils.i(LOG_TAG,
585 "SHOWCONV: CVF is not visible, but no reason to wait. loading now. (%s)",
586 this);
587 reason = LOAD_NOW;
588 }
Andy Huang632721e2012-04-11 16:57:26 -0700589 }
Andy Huang9d3fd922012-09-26 22:23:58 -0700590
591 mLoadWaitReason = reason;
592 if (mLoadWaitReason == LOAD_NOW) {
593 startConversationLoad();
594 }
595 }
596
597 private void handleDelayedConversationLoad() {
598 resetLoadWaiting();
599 startConversationLoad();
600 }
601
602 private void startConversationLoad() {
mindyp3bcf1802012-09-09 11:17:00 -0700603 mWebView.setVisibility(View.VISIBLE);
Andrew Sapperstein606dbd72013-07-30 19:14:23 -0700604 loadContent();
mindyp3bcf1802012-09-09 11:17:00 -0700605 // TODO(mindyp): don't show loading status for a previously rendered
606 // conversation. Ielieve this is better done by making sure don't show loading status
607 // until XX ms have passed without loading completed.
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700608 mProgressController.showLoadingStatus(isUserVisible());
Mindy Pereira8e915722012-02-16 14:42:56 -0800609 }
610
Andrew Sapperstein606dbd72013-07-30 19:14:23 -0700611 /**
612 * Can be overridden in case a subclass needs to load something other than
613 * the messages of a conversation.
614 */
615 protected void loadContent() {
616 getLoaderManager().initLoader(MESSAGE_LOADER, Bundle.EMPTY, getMessageLoaderCallbacks());
617 }
618
Andy Huang7d4746e2012-10-17 17:03:17 -0700619 private void revealConversation() {
Andy Huang243c2362013-03-01 17:50:35 -0800620 timerMark("revealing conversation");
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700621 mProgressController.dismissLoadingStatus(mOnProgressDismiss);
Andy Huang7d4746e2012-10-17 17:03:17 -0700622 }
623
Andy Huang9d3fd922012-09-26 22:23:58 -0700624 private boolean isLoadWaiting() {
625 return mLoadWaitReason != LOAD_NOW;
626 }
627
Andy Huang51067132012-03-12 20:08:19 -0700628 private void renderConversation(MessageCursor messageCursor) {
mindyp3bcf1802012-09-09 11:17:00 -0700629 final String convHtml = renderMessageBodies(messageCursor, mEnableContentReadySignal);
Andy Huang243c2362013-03-01 17:50:35 -0800630 timerMark("rendered conversation");
Andy Huangbd544e32012-05-29 15:56:51 -0700631
632 if (DEBUG_DUMP_CONVERSATION_HTML) {
633 java.io.FileWriter fw = null;
634 try {
Andrew Sappersteinf1566b12013-09-19 15:34:26 -0700635 fw = new java.io.FileWriter(getSdCardFilePath());
Andy Huangbd544e32012-05-29 15:56:51 -0700636 fw.write(convHtml);
637 } catch (java.io.IOException e) {
638 e.printStackTrace();
639 } finally {
640 if (fw != null) {
641 try {
642 fw.close();
643 } catch (java.io.IOException e) {
644 e.printStackTrace();
645 }
646 }
647 }
648 }
649
Andy Huange964eee2012-10-02 19:24:58 -0700650 // save off existing scroll position before re-rendering
651 if (mWebViewLoadedData) {
652 mWebViewYPercent = calculateScrollYPercent();
653 }
654
Andy Huangbd544e32012-05-29 15:56:51 -0700655 mWebView.loadDataWithBaseURL(mBaseUri, convHtml, "text/html", "utf-8", null);
Andy Huange964eee2012-10-02 19:24:58 -0700656 mWebViewLoadedData = true;
Andy Huang63b3c672012-10-05 19:27:28 -0700657 mWebViewLoadStartMs = SystemClock.uptimeMillis();
Andy Huang51067132012-03-12 20:08:19 -0700658 }
659
Andrew Sappersteinf1566b12013-09-19 15:34:26 -0700660 protected String getSdCardFilePath() {
661 return "/sdcard/conv" + mConversation.id + ".html";
662 }
663
Andy Huang7bdc3752012-03-25 17:18:19 -0700664 /**
665 * Populate the adapter with overlay views (message headers, super-collapsed blocks, a
666 * conversation header), and return an HTML document with spacer divs inserted for all overlays.
667 *
668 */
Andrew Sapperstein9f957f32013-07-19 15:18:18 -0700669 protected String renderMessageBodies(MessageCursor messageCursor,
mindyp3bcf1802012-09-09 11:17:00 -0700670 boolean enableContentReadySignal) {
Andy Huangf70fc402012-02-17 15:37:42 -0800671 int pos = -1;
Andy Huang632721e2012-04-11 16:57:26 -0700672
Andy Huang1ee96b22012-08-24 20:19:53 -0700673 LogUtils.d(LOG_TAG, "IN renderMessageBodies, fragment=%s", this);
Andy Huang7bdc3752012-03-25 17:18:19 -0700674 boolean allowNetworkImages = false;
675
Andy Huangc7543572012-04-03 15:34:29 -0700676 // TODO: re-use any existing adapter item state (expanded, details expanded, show pics)
Andy Huang28b7aee2012-08-20 20:27:32 -0700677
Andy Huang7bdc3752012-03-25 17:18:19 -0700678 // Walk through the cursor and build up an overlay adapter as you go.
679 // Each overlay has an entry in the adapter for easy scroll handling in the container.
680 // Items are not necessarily 1:1 in cursor and adapter because of super-collapsed blocks.
681 // When adding adapter items, also add their heights to help the container later determine
682 // overlay dimensions.
683
Andy Huangdb620fe2012-08-24 15:45:28 -0700684 // When re-rendering, prevent ConversationContainer from laying out overlays until after
685 // the new spacers are positioned by WebView.
686 mConversationContainer.invalidateSpacerGeometry();
687
Andy Huang7bdc3752012-03-25 17:18:19 -0700688 mAdapter.clear();
689
Andy Huang47aa9c92012-07-31 15:37:21 -0700690 // re-evaluate the message parts of the view state, since the messages may have changed
691 // since the previous render
692 final ConversationViewState prevState = mViewState;
693 mViewState = new ConversationViewState(prevState);
694
Andy Huang5ff63742012-03-16 20:30:23 -0700695 // N.B. the units of height for spacers are actually dp and not px because WebView assumes
Andy Huang2e9acfe2012-03-15 22:39:36 -0700696 // a pixel is an mdpi pixel, unless you set device-dpi.
Andy Huang5ff63742012-03-16 20:30:23 -0700697
Andy Huang7bdc3752012-03-25 17:18:19 -0700698 // add a single conversation header item
699 final int convHeaderPos = mAdapter.addConversationHeader(mConversation);
Andy Huang23014702012-07-09 12:50:36 -0700700 final int convHeaderPx = measureOverlayHeight(convHeaderPos);
Andy Huang5ff63742012-03-16 20:30:23 -0700701
Andy Huang4dc73232014-02-04 19:58:57 -0800702 mTemplates.startConversation(mWebView.getViewportWidth(),
703 mWebView.screenPxToWebPx(mSideMarginPx), mWebView.screenPxToWebPx(convHeaderPx));
Andy Huang3233bff2012-03-20 19:38:45 -0700704
Andy Huang46dfba62012-04-19 01:47:32 -0700705 int collapsedStart = -1;
Andy Huang839ada22012-07-20 15:48:40 -0700706 ConversationMessage prevCollapsedMsg = null;
Andrew Sappersteine8221482013-10-02 18:14:58 -0700707
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -0800708 final boolean alwaysShowImages = shouldAlwaysShowImages();
Alice Yangf323c042013-10-30 00:15:02 -0700709
Andrew Sappersteine8221482013-10-02 18:14:58 -0700710 boolean prevSafeForImages = alwaysShowImages;
Andy Huang46dfba62012-04-19 01:47:32 -0700711
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700712 // Store the previous expanded state so that the border between
713 // the previous and current message can be properly initialized.
714 int previousExpandedState = ExpansionState.NONE;
Andy Huangf70fc402012-02-17 15:37:42 -0800715 while (messageCursor.moveToPosition(++pos)) {
Andy Huang839ada22012-07-20 15:48:40 -0700716 final ConversationMessage msg = messageCursor.getMessage();
Andy Huang46dfba62012-04-19 01:47:32 -0700717
Andrew Sappersteine8221482013-10-02 18:14:58 -0700718 final boolean safeForImages = alwaysShowImages ||
Scott Kennedy20273842012-11-07 11:16:21 -0800719 msg.alwaysShowImages || prevState.getShouldShowImages(msg);
Andy Huang3233bff2012-03-20 19:38:45 -0700720 allowNetworkImages |= safeForImages;
Andy Huang24055282012-03-27 17:37:06 -0700721
Paul Westbrook08098ec2012-08-12 15:30:28 -0700722 final Integer savedExpanded = prevState.getExpansionState(msg);
723 final int expandedState;
Andy Huang839ada22012-07-20 15:48:40 -0700724 if (savedExpanded != null) {
Andy Huang1ee96b22012-08-24 20:19:53 -0700725 if (ExpansionState.isSuperCollapsed(savedExpanded) && messageCursor.isLast()) {
726 // override saved state when this is now the new last message
727 // this happens to the second-to-last message when you discard a draft
728 expandedState = ExpansionState.EXPANDED;
729 } else {
730 expandedState = savedExpanded;
731 }
Andy Huang839ada22012-07-20 15:48:40 -0700732 } else {
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700733 // new messages that are not expanded default to being eligible for super-collapse
Paul Westbrook08098ec2012-08-12 15:30:28 -0700734 expandedState = (!msg.read || msg.starred || messageCursor.isLast()) ?
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700735 ExpansionState.EXPANDED : ExpansionState.SUPER_COLLAPSED;
Andy Huang839ada22012-07-20 15:48:40 -0700736 }
Scott Kennedy20273842012-11-07 11:16:21 -0800737 mViewState.setShouldShowImages(msg, prevState.getShouldShowImages(msg));
Paul Westbrook08098ec2012-08-12 15:30:28 -0700738 mViewState.setExpansionState(msg, expandedState);
Andy Huangc7543572012-04-03 15:34:29 -0700739
Andy Huang839ada22012-07-20 15:48:40 -0700740 // save off "read" state from the cursor
741 // later, the view may not match the cursor (e.g. conversation marked read on open)
Andy Huang423bea22012-08-21 12:00:49 -0700742 // however, if a previous state indicated this message was unread, trust that instead
743 // so "mark unread" marks all originally unread messages
744 mViewState.setReadState(msg, msg.read && !prevState.isUnread(msg));
Andy Huang839ada22012-07-20 15:48:40 -0700745
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700746 // We only want to consider this for inclusion in the super collapsed block if
747 // 1) The we don't have previous state about this message (The first time that the
748 // user opens a conversation)
749 // 2) The previously saved state for this message indicates that this message is
750 // in the super collapsed block.
751 if (ExpansionState.isSuperCollapsed(expandedState)) {
752 // contribute to a super-collapsed block that will be emitted just before the
753 // next expanded header
754 if (collapsedStart < 0) {
755 collapsedStart = pos;
Andy Huang46dfba62012-04-19 01:47:32 -0700756 }
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700757 prevCollapsedMsg = msg;
758 prevSafeForImages = safeForImages;
Andrew Sapperstein7dc7fa02013-05-08 16:39:31 -0700759
760 // This line puts the from address in the address cache so that
761 // we get the sender image for it if it's in a super-collapsed block.
762 getAddress(msg.getFrom());
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700763 previousExpandedState = expandedState;
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700764 continue;
Andy Huang46dfba62012-04-19 01:47:32 -0700765 }
Andy Huang24055282012-03-27 17:37:06 -0700766
Andy Huang46dfba62012-04-19 01:47:32 -0700767 // resolve any deferred decisions on previous collapsed items
768 if (collapsedStart >= 0) {
769 if (pos - collapsedStart == 1) {
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700770 // Special-case for a single collapsed message: no need to super-collapse it.
771 // Since it is super-collapsed, there is no previous message to be
772 // collapsed and the border above it is the first border.
773 renderMessage(prevCollapsedMsg, false /* previousCollapsed */,
774 false /* expanded */, prevSafeForImages, true /* firstBorder */);
Andy Huang46dfba62012-04-19 01:47:32 -0700775 } else {
776 renderSuperCollapsedBlock(collapsedStart, pos - 1);
777 }
778 prevCollapsedMsg = null;
779 collapsedStart = -1;
780 }
Andy Huang7bdc3752012-03-25 17:18:19 -0700781
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700782 renderMessage(msg, ExpansionState.isCollapsed(previousExpandedState),
783 ExpansionState.isExpanded(expandedState), safeForImages,
Andrew Sappersteine5398802013-07-29 20:55:38 -0700784 pos == 0 /* firstBorder */);
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700785
786 previousExpandedState = expandedState;
Mindy Pereira9b875682012-02-15 18:10:54 -0800787 }
Andy Huang3233bff2012-03-20 19:38:45 -0700788
789 mWebView.getSettings().setBlockNetworkImage(!allowNetworkImages);
790
Andrew Sapperstein2fc67302013-04-29 18:24:56 -0700791 final boolean applyTransforms = shouldApplyTransforms();
Andy Huang57f354c2013-04-11 17:23:40 -0700792
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700793 renderBorder(true /* contiguous */, true /* expanded */,
794 false /* firstBorder */, true /* lastBorder */);
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700795
Andy Huangc1fb9a92013-02-11 13:09:12 -0800796 // If the conversation has specified a base uri, use it here, otherwise use mBaseUri
Andrew Sapperstein68141df2013-08-19 19:07:14 -0700797 return mTemplates.endConversation(mBaseUri, mConversation.getBaseUri(mBaseUri),
Andy Huang2160d532014-02-10 15:43:14 -0800798 mWebView.getViewportWidth(), mWebView.getWidthInDp(mSideMarginPx),
799 enableContentReadySignal, isOverviewMode(mAccount), applyTransforms,
800 applyTransforms);
Mindy Pereira9b875682012-02-15 18:10:54 -0800801 }
Mindy Pereira674afa42012-02-17 14:05:24 -0800802
Andy Huang46dfba62012-04-19 01:47:32 -0700803 private void renderSuperCollapsedBlock(int start, int end) {
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700804 renderBorder(true /* contiguous */, true /* expanded */,
805 true /* firstBorder */, false /* lastBorder */);
Andy Huang46dfba62012-04-19 01:47:32 -0700806 final int blockPos = mAdapter.addSuperCollapsedBlock(start, end);
Andy Huang23014702012-07-09 12:50:36 -0700807 final int blockPx = measureOverlayHeight(blockPos);
808 mTemplates.appendSuperCollapsedHtml(start, mWebView.screenPxToWebPx(blockPx));
Andy Huang46dfba62012-04-19 01:47:32 -0700809 }
810
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700811 protected void renderBorder(
812 boolean contiguous, boolean expanded, boolean firstBorder, boolean lastBorder) {
813 final int blockPos = mAdapter.addBorder(contiguous, expanded, firstBorder, lastBorder);
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700814 final int blockPx = measureOverlayHeight(blockPos);
815 mTemplates.appendBorder(mWebView.screenPxToWebPx(blockPx));
816 }
817
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700818 private void renderMessage(ConversationMessage msg, boolean previousCollapsed,
819 boolean expanded, boolean safeForImages, boolean firstBorder) {
820 renderMessage(msg, previousCollapsed, expanded, safeForImages,
821 true /* renderBorder */, firstBorder);
Andrew Sapperstein1f082232013-07-29 11:16:07 -0700822 }
823
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700824 private void renderMessage(ConversationMessage msg, boolean previousCollapsed,
825 boolean expanded, boolean safeForImages, boolean renderBorder, boolean firstBorder) {
Andrew Sapperstein1f082232013-07-29 11:16:07 -0700826 if (renderBorder) {
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700827 // The border should be collapsed only if both the current
828 // and previous messages are collapsed.
829 renderBorder(true /* contiguous */, !previousCollapsed || expanded,
830 firstBorder, false /* lastBorder */);
Andrew Sapperstein1f082232013-07-29 11:16:07 -0700831 }
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700832
Scott Kennedy20273842012-11-07 11:16:21 -0800833 final int headerPos = mAdapter.addMessageHeader(msg, expanded,
834 mViewState.getShouldShowImages(msg));
Andy Huang46dfba62012-04-19 01:47:32 -0700835 final MessageHeaderItem headerItem = (MessageHeaderItem) mAdapter.getItem(headerPos);
836
837 final int footerPos = mAdapter.addMessageFooter(headerItem);
838
839 // Measure item header and footer heights to allocate spacers in HTML
840 // But since the views themselves don't exist yet, render each item temporarily into
841 // a host view for measurement.
Andy Huang23014702012-07-09 12:50:36 -0700842 final int headerPx = measureOverlayHeight(headerPos);
843 final int footerPx = measureOverlayHeight(footerPos);
Andy Huang46dfba62012-04-19 01:47:32 -0700844
Andy Huang256b35c2012-08-22 15:19:13 -0700845 mTemplates.appendMessageHtml(msg, expanded, safeForImages,
Andy Huang23014702012-07-09 12:50:36 -0700846 mWebView.screenPxToWebPx(headerPx), mWebView.screenPxToWebPx(footerPx));
Andy Huang243c2362013-03-01 17:50:35 -0800847 timerMark("rendered message");
Andy Huang46dfba62012-04-19 01:47:32 -0700848 }
849
850 private String renderCollapsedHeaders(MessageCursor cursor,
851 SuperCollapsedBlockItem blockToReplace) {
852 final List<ConversationOverlayItem> replacements = Lists.newArrayList();
853
854 mTemplates.reset();
855
Alice Yangf323c042013-10-30 00:15:02 -0700856 final boolean alwaysShowImages = (mAccount != null) &&
857 (mAccount.settings.showImages == Settings.ShowImages.ALWAYS);
Andrew Sappersteine8221482013-10-02 18:14:58 -0700858
Mark Wei2b24e992012-09-10 16:40:07 -0700859 // In devices with non-integral density multiplier, screen pixels translate to non-integral
860 // web pixels. Keep track of the error that occurs when we cast all heights to int
861 float error = 0f;
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700862 boolean first = true;
Andy Huang46dfba62012-04-19 01:47:32 -0700863 for (int i = blockToReplace.getStart(), end = blockToReplace.getEnd(); i <= end; i++) {
864 cursor.moveToPosition(i);
Andy Huang839ada22012-07-20 15:48:40 -0700865 final ConversationMessage msg = cursor.getMessage();
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700866
867 final int borderPx;
868 if (first) {
869 borderPx = 0;
870 first = false;
871 } else {
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700872 // When replacing the super-collapsed block,
873 // the border is always collapsed between messages.
874 final BorderItem border = mAdapter.newBorderItem(
875 true /* contiguous */, false /* expanded */);
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700876 borderPx = measureOverlayHeight(border);
877 replacements.add(border);
878 mTemplates.appendBorder(mWebView.screenPxToWebPx(borderPx));
879 }
880
Andrew Sapperstein4ddda2f2013-06-10 11:15:38 -0700881 final MessageHeaderItem header = ConversationViewAdapter.newMessageHeaderItem(
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700882 mAdapter, mAdapter.getDateBuilder(), msg, false /* expanded */,
Andrew Sappersteine8221482013-10-02 18:14:58 -0700883 alwaysShowImages || mViewState.getShouldShowImages(msg));
Andy Huang46dfba62012-04-19 01:47:32 -0700884 final MessageFooterItem footer = mAdapter.newMessageFooterItem(header);
885
Andy Huang23014702012-07-09 12:50:36 -0700886 final int headerPx = measureOverlayHeight(header);
887 final int footerPx = measureOverlayHeight(footer);
Mark Wei2b24e992012-09-10 16:40:07 -0700888 error += mWebView.screenPxToWebPxError(headerPx)
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700889 + mWebView.screenPxToWebPxError(footerPx)
890 + mWebView.screenPxToWebPxError(borderPx);
Mark Wei2b24e992012-09-10 16:40:07 -0700891
892 // When the error becomes greater than 1 pixel, make the next header 1 pixel taller
893 int correction = 0;
894 if (error >= 1) {
895 correction = 1;
896 error -= 1;
897 }
Andy Huang46dfba62012-04-19 01:47:32 -0700898
Andrew Sappersteine8221482013-10-02 18:14:58 -0700899 mTemplates.appendMessageHtml(msg, false /* expanded */,
900 alwaysShowImages || msg.alwaysShowImages,
Mark Wei2b24e992012-09-10 16:40:07 -0700901 mWebView.screenPxToWebPx(headerPx) + correction,
902 mWebView.screenPxToWebPx(footerPx));
Andy Huang46dfba62012-04-19 01:47:32 -0700903 replacements.add(header);
904 replacements.add(footer);
Andy Huang839ada22012-07-20 15:48:40 -0700905
Paul Westbrook08098ec2012-08-12 15:30:28 -0700906 mViewState.setExpansionState(msg, ExpansionState.COLLAPSED);
Andy Huang46dfba62012-04-19 01:47:32 -0700907 }
908
909 mAdapter.replaceSuperCollapsedBlock(blockToReplace, replacements);
Andy Huang06c03622012-10-22 18:59:45 -0700910 mAdapter.notifyDataSetChanged();
Andy Huang46dfba62012-04-19 01:47:32 -0700911
912 return mTemplates.emit();
913 }
914
Andrew Sapperstein9f957f32013-07-19 15:18:18 -0700915 protected int measureOverlayHeight(int position) {
Andy Huang46dfba62012-04-19 01:47:32 -0700916 return measureOverlayHeight(mAdapter.getItem(position));
917 }
918
Andy Huang7bdc3752012-03-25 17:18:19 -0700919 /**
Andy Huangb8331b42012-07-16 19:08:53 -0700920 * Measure the height of an adapter view by rendering an adapter item into a temporary
Andy Huang46dfba62012-04-19 01:47:32 -0700921 * host view, and asking the view to immediately measure itself. This method will reuse
Andy Huang7bdc3752012-03-25 17:18:19 -0700922 * a previous adapter view from {@link ConversationContainer}'s scrap views if one was generated
923 * earlier.
924 * <p>
Andy Huang46dfba62012-04-19 01:47:32 -0700925 * After measuring the height, this method also saves the height in the
926 * {@link ConversationOverlayItem} for later use in overlay positioning.
Andy Huang7bdc3752012-03-25 17:18:19 -0700927 *
Andy Huang46dfba62012-04-19 01:47:32 -0700928 * @param convItem adapter item with data to render and measure
Andy Huang23014702012-07-09 12:50:36 -0700929 * @return height of the rendered view in screen px
Andy Huang7bdc3752012-03-25 17:18:19 -0700930 */
Andy Huang46dfba62012-04-19 01:47:32 -0700931 private int measureOverlayHeight(ConversationOverlayItem convItem) {
Andy Huang7bdc3752012-03-25 17:18:19 -0700932 final int type = convItem.getType();
933
934 final View convertView = mConversationContainer.getScrapView(type);
Andy Huangb8331b42012-07-16 19:08:53 -0700935 final View hostView = mAdapter.getView(convItem, convertView, mConversationContainer,
936 true /* measureOnly */);
Andy Huang7bdc3752012-03-25 17:18:19 -0700937 if (convertView == null) {
938 mConversationContainer.addScrapView(type, hostView);
939 }
940
Andy Huang9875bb42012-04-04 20:36:21 -0700941 final int heightPx = mConversationContainer.measureOverlay(hostView);
Andy Huang7bdc3752012-03-25 17:18:19 -0700942 convItem.setHeight(heightPx);
Andy Huang9875bb42012-04-04 20:36:21 -0700943 convItem.markMeasurementValid();
Andy Huang7bdc3752012-03-25 17:18:19 -0700944
Andy Huang23014702012-07-09 12:50:36 -0700945 return heightPx;
Andy Huang7bdc3752012-03-25 17:18:19 -0700946 }
947
Andy Huang5ff63742012-03-16 20:30:23 -0700948 @Override
949 public void onConversationViewHeaderHeightChange(int newHeight) {
Mark Weiab2d9982012-09-25 13:06:17 -0700950 final int h = mWebView.screenPxToWebPx(newHeight);
951
952 mWebView.loadUrl(String.format("javascript:setConversationHeaderSpacerHeight(%s);", h));
Andy Huang5ff63742012-03-16 20:30:23 -0700953 }
954
Andy Huang3233bff2012-03-20 19:38:45 -0700955 // END conversation header callbacks
956
957 // START message header callbacks
958 @Override
Andy Huangc7543572012-04-03 15:34:29 -0700959 public void setMessageSpacerHeight(MessageHeaderItem item, int newSpacerHeightPx) {
960 mConversationContainer.invalidateSpacerGeometry();
961
962 // update message HTML spacer height
Andy Huang23014702012-07-09 12:50:36 -0700963 final int h = mWebView.screenPxToWebPx(newSpacerHeightPx);
964 LogUtils.i(LAYOUT_TAG, "setting HTML spacer h=%dwebPx (%dscreenPx)", h,
965 newSpacerHeightPx);
Vikram Aggarwal5349ce12012-09-24 14:12:40 -0700966 mWebView.loadUrl(String.format("javascript:setMessageHeaderSpacerHeight('%s', %s);",
Andy Huang014ea4c2012-09-25 14:50:54 -0700967 mTemplates.getMessageDomId(item.getMessage()), h));
Andy Huang3233bff2012-03-20 19:38:45 -0700968 }
969
970 @Override
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700971 public void setMessageExpanded(MessageHeaderItem item, int newSpacerHeightPx,
972 int topBorderHeight, int bottomBorderHeight) {
Andy Huangc7543572012-04-03 15:34:29 -0700973 mConversationContainer.invalidateSpacerGeometry();
974
975 // show/hide the HTML message body and update the spacer height
Andy Huang23014702012-07-09 12:50:36 -0700976 final int h = mWebView.screenPxToWebPx(newSpacerHeightPx);
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700977 final int topHeight = mWebView.screenPxToWebPx(topBorderHeight);
978 final int bottomHeight = mWebView.screenPxToWebPx(bottomBorderHeight);
Andy Huang23014702012-07-09 12:50:36 -0700979 LogUtils.i(LAYOUT_TAG, "setting HTML spacer expanded=%s h=%dwebPx (%dscreenPx)",
980 item.isExpanded(), h, newSpacerHeightPx);
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700981 mWebView.loadUrl(String.format("javascript:setMessageBodyVisible('%s', %s, %s, %s, %s);",
982 mTemplates.getMessageDomId(item.getMessage()), item.isExpanded(),
983 h, topHeight, bottomHeight));
Andy Huang839ada22012-07-20 15:48:40 -0700984
Andy Huang014ea4c2012-09-25 14:50:54 -0700985 mViewState.setExpansionState(item.getMessage(),
Paul Westbrook08098ec2012-08-12 15:30:28 -0700986 item.isExpanded() ? ExpansionState.EXPANDED : ExpansionState.COLLAPSED);
Andy Huang3233bff2012-03-20 19:38:45 -0700987 }
988
989 @Override
Scott Kennedyeb9a4bd2012-11-12 10:33:04 -0800990 public void showExternalResources(final Message msg) {
Scott Kennedy20273842012-11-07 11:16:21 -0800991 mViewState.setShouldShowImages(msg, true);
Andy Huang3233bff2012-03-20 19:38:45 -0700992 mWebView.getSettings().setBlockNetworkImage(false);
Scott Kennedyeb9a4bd2012-11-12 10:33:04 -0800993 mWebView.loadUrl("javascript:unblockImages(['" + mTemplates.getMessageDomId(msg) + "']);");
994 }
995
996 @Override
997 public void showExternalResources(final String senderRawAddress) {
998 mWebView.getSettings().setBlockNetworkImage(false);
999
1000 final Address sender = getAddress(senderRawAddress);
1001 final MessageCursor cursor = getMessageCursor();
1002
1003 final List<String> messageDomIds = new ArrayList<String>();
1004
1005 int pos = -1;
1006 while (cursor.moveToPosition(++pos)) {
1007 final ConversationMessage message = cursor.getMessage();
1008 if (sender.equals(getAddress(message.getFrom()))) {
1009 message.alwaysShowImages = true;
1010
1011 mViewState.setShouldShowImages(message, true);
1012 messageDomIds.add(mTemplates.getMessageDomId(message));
1013 }
1014 }
1015
1016 final String url = String.format(
1017 "javascript:unblockImages(['%s']);", TextUtils.join("','", messageDomIds));
1018 mWebView.loadUrl(url);
Andy Huang3233bff2012-03-20 19:38:45 -07001019 }
Alice Yang1ebc2db2013-03-14 21:21:44 -07001020
1021 @Override
Andy Huang75b52a52013-03-15 15:40:24 -07001022 public boolean supportsMessageTransforms() {
1023 return true;
1024 }
1025
1026 @Override
Alice Yang1ebc2db2013-03-14 21:21:44 -07001027 public String getMessageTransforms(final Message msg) {
1028 final String domId = mTemplates.getMessageDomId(msg);
1029 return (domId == null) ? null : mMessageTransforms.get(domId);
1030 }
1031
Andy Huang3233bff2012-03-20 19:38:45 -07001032 // END message header callbacks
Andy Huang5ff63742012-03-16 20:30:23 -07001033
Andy Huang46dfba62012-04-19 01:47:32 -07001034 @Override
Andrew Sapperstein2fc67302013-04-29 18:24:56 -07001035 public void showUntransformedConversation() {
1036 super.showUntransformedConversation();
1037 renderConversation(getMessageCursor());
1038 }
1039
1040 @Override
Andy Huang46dfba62012-04-19 01:47:32 -07001041 public void onSuperCollapsedClick(SuperCollapsedBlockItem item) {
mindypf4fce122012-09-14 15:55:33 -07001042 MessageCursor cursor = getMessageCursor();
1043 if (cursor == null || !mViewsCreated) {
Andy Huang46dfba62012-04-19 01:47:32 -07001044 return;
1045 }
1046
mindypf4fce122012-09-14 15:55:33 -07001047 mTempBodiesHtml = renderCollapsedHeaders(cursor, item);
Andy Huang46dfba62012-04-19 01:47:32 -07001048 mWebView.loadUrl("javascript:replaceSuperCollapsedBlock(" + item.getStart() + ")");
1049 }
1050
Andy Huang47aa9c92012-07-31 15:37:21 -07001051 private void showNewMessageNotification(NewMessagesInfo info) {
Andrew Sapperstein821fa872013-08-21 21:57:39 -07001052 mNewMessageBar.setText(info.getNotificationText());
Andy Huang47aa9c92012-07-31 15:37:21 -07001053 mNewMessageBar.setVisibility(View.VISIBLE);
1054 }
1055
1056 private void onNewMessageBarClick() {
1057 mNewMessageBar.setVisibility(View.GONE);
1058
mindypf4fce122012-09-14 15:55:33 -07001059 renderConversation(getMessageCursor()); // mCursor is already up-to-date
1060 // per onLoadFinished()
Andy Huang5fbda022012-02-28 18:22:03 -08001061 }
1062
Andy Huangadbf3e82012-10-13 13:30:19 -07001063 private static OverlayPosition[] parsePositions(final String[] topArray,
1064 final String[] bottomArray) {
1065 final int len = topArray.length;
1066 final OverlayPosition[] positions = new OverlayPosition[len];
Andy Huangb5078b22012-03-05 19:52:29 -08001067 for (int i = 0; i < len; i++) {
Andy Huangadbf3e82012-10-13 13:30:19 -07001068 positions[i] = new OverlayPosition(
1069 Integer.parseInt(topArray[i]), Integer.parseInt(bottomArray[i]));
Andy Huangb5078b22012-03-05 19:52:29 -08001070 }
Andy Huangadbf3e82012-10-13 13:30:19 -07001071 return positions;
Andy Huangb5078b22012-03-05 19:52:29 -08001072 }
1073
Andrew Sapperstein9f957f32013-07-19 15:18:18 -07001074 protected Address getAddress(String rawFrom) {
Paul Westbrook0dfae692013-10-02 00:51:29 -07001075 return Utils.getAddress(mAddressCache, rawFrom);
Andy Huang16174812012-08-16 16:40:35 -07001076 }
1077
Andy Huang9d3fd922012-09-26 22:23:58 -07001078 private void ensureContentSizeChangeListener() {
1079 if (mWebViewSizeChangeListener == null) {
Andy Huangc1fb9a92013-02-11 13:09:12 -08001080 mWebViewSizeChangeListener = new ContentSizeChangeListener() {
Andy Huang9d3fd922012-09-26 22:23:58 -07001081 @Override
1082 public void onHeightChange(int h) {
1083 // When WebKit says the DOM height has changed, re-measure
1084 // bodies and re-position their headers.
1085 // This is separate from the typical JavaScript DOM change
1086 // listeners because cases like NARROW_COLUMNS text reflow do not trigger DOM
1087 // events.
1088 mWebView.loadUrl("javascript:measurePositions();");
1089 }
1090 };
1091 }
1092 mWebView.setContentSizeChangeListener(mWebViewSizeChangeListener);
1093 }
1094
Andrew Sapperstein9f957f32013-07-19 15:18:18 -07001095 public static boolean isOverviewMode(Account acct) {
Andy Huangccf67802013-03-15 14:31:57 -07001096 return acct.settings.isOverviewMode();
Andy Huangadbf3e82012-10-13 13:30:19 -07001097 }
1098
1099 private void setupOverviewMode() {
Andy Huang02f9d182012-11-28 22:38:02 -08001100 // for now, overview mode means use the built-in WebView zoom and disable custom scale
1101 // gesture handling
Andy Huangadbf3e82012-10-13 13:30:19 -07001102 final boolean overviewMode = isOverviewMode(mAccount);
1103 final WebSettings settings = mWebView.getSettings();
Andy Huang4dc73232014-02-04 19:58:57 -08001104 final WebSettings.LayoutAlgorithm layout;
Andy Huang06def562012-10-14 00:19:11 -07001105 settings.setUseWideViewPort(overviewMode);
Andy Huang57f354c2013-04-11 17:23:40 -07001106 settings.setSupportZoom(overviewMode);
1107 settings.setBuiltInZoomControls(overviewMode);
Andy Huang4dc73232014-02-04 19:58:57 -08001108 settings.setLoadWithOverviewMode(overviewMode);
Andy Huang57f354c2013-04-11 17:23:40 -07001109 if (overviewMode) {
1110 settings.setDisplayZoomControls(false);
Andy Huang4dc73232014-02-04 19:58:57 -08001111 layout = WebSettings.LayoutAlgorithm.NORMAL;
1112 } else {
1113 layout = WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
Andy Huangadbf3e82012-10-13 13:30:19 -07001114 }
Andy Huang4dc73232014-02-04 19:58:57 -08001115 settings.setLayoutAlgorithm(layout);
Andy Huangadbf3e82012-10-13 13:30:19 -07001116 }
1117
Andrew Sappersteinb1d184d2013-08-09 14:14:31 -07001118 public class ConversationWebViewClient extends AbstractConversationWebViewClient {
Andrew Sapperstein4ddda2f2013-06-10 11:15:38 -07001119 public ConversationWebViewClient(Account account) {
1120 super(account);
Andrew Sapperstein376294b2013-06-06 16:04:26 -07001121 }
1122
Andy Huang17a9cde2012-03-09 18:03:16 -08001123 @Override
1124 public void onPageFinished(WebView view, String url) {
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001125 // Ignore unsafe calls made after a fragment is detached from an activity.
1126 // This method needs to, for example, get at the loader manager, which needs
1127 // the fragment to be added.
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001128 if (!isAdded() || !mViewsCreated) {
Paul Westbrook006e13c2013-07-24 18:40:20 -07001129 LogUtils.d(LOG_TAG, "ignoring CVF.onPageFinished, url=%s fragment=%s", url,
Andy Huangb95da852012-07-18 14:16:58 -07001130 ConversationViewFragment.this);
1131 return;
1132 }
1133
Paul Westbrook006e13c2013-07-24 18:40:20 -07001134 LogUtils.d(LOG_TAG, "IN CVF.onPageFinished, url=%s fragment=%s wv=%s t=%sms", url,
Andy Huang30bcfe72012-10-18 18:09:03 -07001135 ConversationViewFragment.this, view,
Andy Huang63b3c672012-10-05 19:27:28 -07001136 (SystemClock.uptimeMillis() - mWebViewLoadStartMs));
Andy Huang632721e2012-04-11 16:57:26 -07001137
Andy Huang9d3fd922012-09-26 22:23:58 -07001138 ensureContentSizeChangeListener();
1139
mindyp3bcf1802012-09-09 11:17:00 -07001140 if (!mEnableContentReadySignal) {
Andy Huang7d4746e2012-10-17 17:03:17 -07001141 revealConversation();
mindyp3bcf1802012-09-09 11:17:00 -07001142 }
Andy Huang9d3fd922012-09-26 22:23:58 -07001143
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001144 final Set<String> emailAddresses = Sets.newHashSet();
Andy Huang543e7092013-04-22 11:44:56 -07001145 final List<Address> cacheCopy;
1146 synchronized (mAddressCache) {
1147 cacheCopy = ImmutableList.copyOf(mAddressCache.values());
1148 }
1149 for (Address addr : cacheCopy) {
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001150 emailAddresses.add(addr.getAddress());
Andy Huangb8331b42012-07-16 19:08:53 -07001151 }
Andrew Sapperstein4ddda2f2013-06-10 11:15:38 -07001152 final ContactLoaderCallbacks callbacks = getContactInfoSource();
1153 callbacks.setSenders(emailAddresses);
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001154 getLoaderManager().restartLoader(CONTACT_LOADER, Bundle.EMPTY, callbacks);
Andy Huang17a9cde2012-03-09 18:03:16 -08001155 }
1156
Andy Huangaf5d4e02012-03-19 19:02:12 -07001157 @Override
1158 public boolean shouldOverrideUrlLoading(WebView view, String url) {
Paul Westbrook542fec92012-09-18 14:47:51 -07001159 return mViewsCreated && super.shouldOverrideUrlLoading(view, url);
Andy Huangaf5d4e02012-03-19 19:02:12 -07001160 }
Andy Huang17a9cde2012-03-09 18:03:16 -08001161 }
1162
Andy Huangf70fc402012-02-17 15:37:42 -08001163 /**
1164 * NOTE: all public methods must be listed in the proguard flags so that they can be accessed
1165 * via reflection and not stripped.
1166 *
1167 */
1168 private class MailJsBridge {
Mindy Pereira974c9662012-09-14 10:02:08 -07001169 @JavascriptInterface
Andy Huangadbf3e82012-10-13 13:30:19 -07001170 public void onWebContentGeometryChange(final String[] overlayTopStrs,
1171 final String[] overlayBottomStrs) {
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -08001172 try {
1173 getHandler().post(new FragmentRunnable("onWebContentGeometryChange",
1174 ConversationViewFragment.this) {
1175 @Override
1176 public void go() {
Andy Huang46dfba62012-04-19 01:47:32 -07001177 if (!mViewsCreated) {
mindyp1b3cc472012-09-27 11:32:59 -07001178 LogUtils.d(LOG_TAG, "ignoring webContentGeometryChange because views"
1179 + " are gone, %s", ConversationViewFragment.this);
Andy Huang46dfba62012-04-19 01:47:32 -07001180 return;
1181 }
Andy Huangadbf3e82012-10-13 13:30:19 -07001182 mConversationContainer.onGeometryChange(
1183 parsePositions(overlayTopStrs, overlayBottomStrs));
mindyp1b3cc472012-09-27 11:32:59 -07001184 if (mDiff != 0) {
1185 // SCROLL!
1186 int scale = (int) (mWebView.getScale() / mWebView.getInitialScale());
1187 if (scale > 1) {
1188 mWebView.scrollBy(0, (mDiff * (scale - 1)));
1189 }
1190 mDiff = 0;
1191 }
Andy Huang46dfba62012-04-19 01:47:32 -07001192 }
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -08001193 });
1194 } catch (Throwable t) {
1195 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onWebContentGeometryChange");
1196 }
Andy Huang46dfba62012-04-19 01:47:32 -07001197 }
1198
Mindy Pereira974c9662012-09-14 10:02:08 -07001199 @JavascriptInterface
Andy Huang46dfba62012-04-19 01:47:32 -07001200 public String getTempMessageBodies() {
1201 try {
1202 if (!mViewsCreated) {
1203 return "";
Andy Huangf70fc402012-02-17 15:37:42 -08001204 }
Andy Huang46dfba62012-04-19 01:47:32 -07001205
1206 final String s = mTempBodiesHtml;
1207 mTempBodiesHtml = null;
1208 return s;
1209 } catch (Throwable t) {
1210 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getTempMessageBodies");
1211 return "";
1212 }
Andy Huangf70fc402012-02-17 15:37:42 -08001213 }
1214
Andy Huang014ea4c2012-09-25 14:50:54 -07001215 @JavascriptInterface
1216 public String getMessageBody(String domId) {
1217 try {
1218 final MessageCursor cursor = getMessageCursor();
1219 if (!mViewsCreated || cursor == null) {
1220 return "";
1221 }
1222
1223 int pos = -1;
1224 while (cursor.moveToPosition(++pos)) {
1225 final ConversationMessage msg = cursor.getMessage();
1226 if (TextUtils.equals(domId, mTemplates.getMessageDomId(msg))) {
Andy Huang986776b2014-02-19 18:29:43 -08001227 return HtmlConversationTemplates.wrapMessageBody(msg.getBodyAsHtml());
Andy Huang014ea4c2012-09-25 14:50:54 -07001228 }
1229 }
1230
1231 return "";
1232
1233 } catch (Throwable t) {
1234 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getMessageBody");
1235 return "";
1236 }
1237 }
1238
Mindy Pereira974c9662012-09-14 10:02:08 -07001239 @JavascriptInterface
Andy Huang543e7092013-04-22 11:44:56 -07001240 public String getMessageSender(String domId) {
1241 try {
1242 final MessageCursor cursor = getMessageCursor();
1243 if (!mViewsCreated || cursor == null) {
1244 return "";
1245 }
1246
1247 int pos = -1;
1248 while (cursor.moveToPosition(++pos)) {
1249 final ConversationMessage msg = cursor.getMessage();
1250 if (TextUtils.equals(domId, mTemplates.getMessageDomId(msg))) {
1251 return getAddress(msg.getFrom()).getAddress();
1252 }
1253 }
1254
1255 return "";
1256
1257 } catch (Throwable t) {
1258 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getMessageSender");
1259 return "";
1260 }
1261 }
1262
Andy Huang543e7092013-04-22 11:44:56 -07001263 @JavascriptInterface
mindyp3bcf1802012-09-09 11:17:00 -07001264 public void onContentReady() {
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -08001265 try {
1266 getHandler().post(new FragmentRunnable("onContentReady",
1267 ConversationViewFragment.this) {
1268 @Override
1269 public void go() {
1270 try {
1271 if (mWebViewLoadStartMs != 0) {
1272 LogUtils.i(LOG_TAG, "IN CVF.onContentReady, f=%s vis=%s t=%sms",
1273 ConversationViewFragment.this,
1274 isUserVisible(),
1275 (SystemClock.uptimeMillis() - mWebViewLoadStartMs));
1276 }
1277 revealConversation();
1278 } catch (Throwable t) {
1279 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onContentReady");
1280 // Still try to show the conversation.
1281 revealConversation();
Andy Huang63b3c672012-10-05 19:27:28 -07001282 }
mindyp3bcf1802012-09-09 11:17:00 -07001283 }
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -08001284 });
1285 } catch (Throwable t) {
1286 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onContentReady");
1287 }
mindyp3bcf1802012-09-09 11:17:00 -07001288 }
Andy Huange964eee2012-10-02 19:24:58 -07001289
Andy Huange964eee2012-10-02 19:24:58 -07001290 @JavascriptInterface
1291 public float getScrollYPercent() {
1292 try {
1293 return mWebViewYPercent;
1294 } catch (Throwable t) {
1295 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getScrollYPercent");
1296 return 0f;
1297 }
1298 }
Andy Huang05c70c82013-03-14 15:15:50 -07001299
Andy Huang05c70c82013-03-14 15:15:50 -07001300 @JavascriptInterface
1301 public void onMessageTransform(String messageDomId, String transformText) {
Andrew Sappersteinae92e152013-05-03 13:55:18 -07001302 try {
1303 LogUtils.i(LOG_TAG, "TRANSFORM: (%s) %s", messageDomId, transformText);
1304 mMessageTransforms.put(messageDomId, transformText);
1305 onConversationTransformed();
1306 } catch (Throwable t) {
1307 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onMessageTransform");
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -08001308 }
1309 }
1310
1311 @JavascriptInterface
1312 public void onInlineAttachmentsParsed(final String[] urls, final String[] messageIds) {
1313 try {
1314 getHandler().post(new FragmentRunnable("onInlineAttachmentsParsed",
1315 ConversationViewFragment.this) {
1316 @Override
1317 public void go() {
1318 try {
1319 for (int i = 0, size = urls.length; i < size; i++) {
1320 mUrlToMessageIdMap.put(urls[i], messageIds[i]);
1321 }
1322 } catch (ArrayIndexOutOfBoundsException e) {
1323 LogUtils.e(LOG_TAG, e,
1324 "Number of urls does not match number of message ids - %s:%s",
1325 urls.length, messageIds.length);
1326 }
1327 }
1328 });
1329 } catch (Throwable t) {
1330 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onInlineAttachmentsParsed");
Andrew Sappersteinae92e152013-05-03 13:55:18 -07001331 }
Andy Huang05c70c82013-03-14 15:15:50 -07001332 }
Andy Huangf70fc402012-02-17 15:37:42 -08001333 }
1334
Andy Huang47aa9c92012-07-31 15:37:21 -07001335 private class NewMessagesInfo {
1336 int count;
Andy Huang06c03622012-10-22 18:59:45 -07001337 int countFromSelf;
Andy Huang47aa9c92012-07-31 15:37:21 -07001338 String senderAddress;
1339
1340 /**
1341 * Return the display text for the new message notification overlay. It will be formatted
1342 * appropriately for a single new message vs. multiple new messages.
1343 *
1344 * @return display text
1345 */
1346 public String getNotificationText() {
mindypad0c30d2012-09-25 12:09:13 -07001347 Resources res = getResources();
Andy Huang47aa9c92012-07-31 15:37:21 -07001348 if (count > 1) {
Andrew Sapperstein66d69112013-08-23 12:24:44 -07001349 return res.getQuantityString(R.plurals.new_incoming_messages_many, count, count);
Andy Huang47aa9c92012-07-31 15:37:21 -07001350 } else {
Andy Huang16174812012-08-16 16:40:35 -07001351 final Address addr = getAddress(senderAddress);
mindypad0c30d2012-09-25 12:09:13 -07001352 return res.getString(R.string.new_incoming_messages_one,
Andrew Sapperstein2fd167d2014-01-28 10:07:38 -08001353 mBidiFormatter.unicodeWrap(TextUtils.isEmpty(addr.getPersonal())
1354 ? addr.getAddress() : addr.getPersonal()));
Andy Huang47aa9c92012-07-31 15:37:21 -07001355 }
Andy Huang47aa9c92012-07-31 15:37:21 -07001356 }
1357 }
1358
mindypf4fce122012-09-14 15:55:33 -07001359 @Override
Paul Westbrookc42ad5e2013-05-09 16:52:15 -07001360 public void onMessageCursorLoadFinished(Loader<ObjectCursor<ConversationMessage>> loader,
1361 MessageCursor newCursor, MessageCursor oldCursor) {
mindypf4fce122012-09-14 15:55:33 -07001362 /*
1363 * what kind of changes affect the MessageCursor? 1. new message(s) 2.
1364 * read/unread state change 3. deleted message, either regular or draft
1365 * 4. updated message, either from self or from others, updated in
1366 * content or state or sender 5. star/unstar of message (technically
1367 * similar to #1) 6. other label change Use MessageCursor.hashCode() to
1368 * sort out interesting vs. no-op cursor updates.
1369 */
Andy Huangb8331b42012-07-16 19:08:53 -07001370
Andy Huang233d4352012-10-18 14:00:24 -07001371 if (oldCursor != null && !oldCursor.isClosed()) {
Andy Huang014ea4c2012-09-25 14:50:54 -07001372 final NewMessagesInfo info = getNewIncomingMessagesInfo(newCursor);
Andy Huangb8331b42012-07-16 19:08:53 -07001373
Andy Huang014ea4c2012-09-25 14:50:54 -07001374 if (info.count > 0) {
1375 // don't immediately render new incoming messages from other
1376 // senders
1377 // (to avoid a new message from losing the user's focus)
1378 LogUtils.i(LOG_TAG, "CONV RENDER: conversation updated"
Andy Huang9d3fd922012-09-26 22:23:58 -07001379 + ", holding cursor for new incoming message (%s)", this);
Andy Huang014ea4c2012-09-25 14:50:54 -07001380 showNewMessageNotification(info);
1381 return;
1382 }
1383
Andy Huang06c03622012-10-22 18:59:45 -07001384 final int oldState = oldCursor.getStateHashCode();
1385 final boolean changed = newCursor.getStateHashCode() != oldState;
Andy Huang233d4352012-10-18 14:00:24 -07001386
Andy Huang014ea4c2012-09-25 14:50:54 -07001387 if (!changed) {
1388 final boolean processedInPlace = processInPlaceUpdates(newCursor, oldCursor);
1389 if (processedInPlace) {
Andy Huang9d3fd922012-09-26 22:23:58 -07001390 LogUtils.i(LOG_TAG, "CONV RENDER: processed update(s) in place (%s)", this);
Andy Huang1ee96b22012-08-24 20:19:53 -07001391 } else {
mindypf4fce122012-09-14 15:55:33 -07001392 LogUtils.i(LOG_TAG, "CONV RENDER: uninteresting update"
Andy Huang9d3fd922012-09-26 22:23:58 -07001393 + ", ignoring this conversation update (%s)", this);
Andy Huang1ee96b22012-08-24 20:19:53 -07001394 }
Andy Huangb8331b42012-07-16 19:08:53 -07001395 return;
Andy Huang06c03622012-10-22 18:59:45 -07001396 } else if (info.countFromSelf == 1) {
1397 // Special-case the very common case of a new cursor that is the same as the old
1398 // one, except that there is a new message from yourself. This happens upon send.
1399 final boolean sameExceptNewLast = newCursor.getStateHashCode(1) == oldState;
1400 if (sameExceptNewLast) {
1401 LogUtils.i(LOG_TAG, "CONV RENDER: update is a single new message from self"
1402 + " (%s)", this);
1403 newCursor.moveToLast();
1404 processNewOutgoingMessage(newCursor.getMessage());
1405 return;
1406 }
Andy Huangb8331b42012-07-16 19:08:53 -07001407 }
Andy Huang6766b6e2012-09-28 12:43:52 -07001408 // cursors are different, and not due to an incoming message. fall
1409 // through and render.
1410 LogUtils.i(LOG_TAG, "CONV RENDER: conversation updated"
1411 + ", but not due to incoming message. rendering. (%s)", this);
Andy Huang06c03622012-10-22 18:59:45 -07001412
1413 if (DEBUG_DUMP_CURSOR_CONTENTS) {
1414 LogUtils.i(LOG_TAG, "old cursor: %s", oldCursor.getDebugDump());
1415 LogUtils.i(LOG_TAG, "new cursor: %s", newCursor.getDebugDump());
1416 }
Andy Huang6766b6e2012-09-28 12:43:52 -07001417 } else {
1418 LogUtils.i(LOG_TAG, "CONV RENDER: initial render. (%s)", this);
Andy Huang243c2362013-03-01 17:50:35 -08001419 timerMark("message cursor load finished");
Andy Huangb8331b42012-07-16 19:08:53 -07001420 }
1421
Andrew Sapperstein606dbd72013-07-30 19:14:23 -07001422 renderContent(newCursor);
1423 }
1424
1425 protected void renderContent(MessageCursor messageCursor) {
Mark Wei4071c2f2012-09-26 14:38:38 -07001426 // if layout hasn't happened, delay render
1427 // This is needed in addition to the showConversation() delay to speed
1428 // up rotation and restoration.
1429 if (mConversationContainer.getWidth() == 0) {
1430 mNeedRender = true;
1431 mConversationContainer.addOnLayoutChangeListener(this);
1432 } else {
Andrew Sapperstein606dbd72013-07-30 19:14:23 -07001433 renderConversation(messageCursor);
Mark Wei4071c2f2012-09-26 14:38:38 -07001434 }
Andy Huangb8331b42012-07-16 19:08:53 -07001435 }
1436
mindypf4fce122012-09-14 15:55:33 -07001437 private NewMessagesInfo getNewIncomingMessagesInfo(MessageCursor newCursor) {
1438 final NewMessagesInfo info = new NewMessagesInfo();
Andy Huangb8331b42012-07-16 19:08:53 -07001439
mindypf4fce122012-09-14 15:55:33 -07001440 int pos = -1;
1441 while (newCursor.moveToPosition(++pos)) {
1442 final Message m = newCursor.getMessage();
1443 if (!mViewState.contains(m)) {
1444 LogUtils.i(LOG_TAG, "conversation diff: found new msg: %s", m.uri);
Andy Huangb8331b42012-07-16 19:08:53 -07001445
Scott Kennedy8960f0a2012-11-07 15:35:50 -08001446 final Address from = getAddress(m.getFrom());
mindypf4fce122012-09-14 15:55:33 -07001447 // distinguish ours from theirs
1448 // new messages from the account owner should not trigger a
1449 // notification
1450 if (mAccount.ownsFromAddress(from.getAddress())) {
1451 LogUtils.i(LOG_TAG, "found message from self: %s", m.uri);
Andy Huang06c03622012-10-22 18:59:45 -07001452 info.countFromSelf++;
mindypf4fce122012-09-14 15:55:33 -07001453 continue;
1454 }
Andy Huangb8331b42012-07-16 19:08:53 -07001455
mindypf4fce122012-09-14 15:55:33 -07001456 info.count++;
Scott Kennedy8960f0a2012-11-07 15:35:50 -08001457 info.senderAddress = m.getFrom();
Andy Huangb8331b42012-07-16 19:08:53 -07001458 }
Andy Huangb8331b42012-07-16 19:08:53 -07001459 }
mindypf4fce122012-09-14 15:55:33 -07001460 return info;
Andy Huangb8331b42012-07-16 19:08:53 -07001461 }
1462
Andy Huang014ea4c2012-09-25 14:50:54 -07001463 private boolean processInPlaceUpdates(MessageCursor newCursor, MessageCursor oldCursor) {
1464 final Set<String> idsOfChangedBodies = Sets.newHashSet();
Andy Huang6b3d0d92012-10-30 15:46:48 -07001465 final List<Integer> changedOverlayPositions = Lists.newArrayList();
1466
Andy Huang014ea4c2012-09-25 14:50:54 -07001467 boolean changed = false;
1468
1469 int pos = 0;
1470 while (true) {
1471 if (!newCursor.moveToPosition(pos) || !oldCursor.moveToPosition(pos)) {
1472 break;
1473 }
1474
1475 final ConversationMessage newMsg = newCursor.getMessage();
1476 final ConversationMessage oldMsg = oldCursor.getMessage();
1477
Scott Kennedy8960f0a2012-11-07 15:35:50 -08001478 if (!TextUtils.equals(newMsg.getFrom(), oldMsg.getFrom()) ||
Andy Huang2a1e8e32012-10-23 18:54:57 -07001479 newMsg.isSending != oldMsg.isSending) {
Andy Huang6b3d0d92012-10-30 15:46:48 -07001480 mAdapter.updateItemsForMessage(newMsg, changedOverlayPositions);
Andy Huang2a1e8e32012-10-23 18:54:57 -07001481 LogUtils.i(LOG_TAG, "msg #%d (%d): detected from/sending change. isSending=%s",
1482 pos, newMsg.id, newMsg.isSending);
Andy Huang014ea4c2012-09-25 14:50:54 -07001483 }
1484
1485 // update changed message bodies in-place
1486 if (!TextUtils.equals(newMsg.bodyHtml, oldMsg.bodyHtml) ||
1487 !TextUtils.equals(newMsg.bodyText, oldMsg.bodyText)) {
1488 // maybe just set a flag to notify JS to re-request changed bodies
1489 idsOfChangedBodies.add('"' + mTemplates.getMessageDomId(newMsg) + '"');
1490 LogUtils.i(LOG_TAG, "msg #%d (%d): detected body change", pos, newMsg.id);
1491 }
1492
1493 pos++;
1494 }
1495
Andy Huang6b3d0d92012-10-30 15:46:48 -07001496
1497 if (!changedOverlayPositions.isEmpty()) {
Andy Huang06c03622012-10-22 18:59:45 -07001498 // notify once after the entire adapter is updated
Andy Huang6b3d0d92012-10-30 15:46:48 -07001499 mConversationContainer.onOverlayModelUpdate(changedOverlayPositions);
1500 changed = true;
Andy Huang06c03622012-10-22 18:59:45 -07001501 }
1502
Andy Huang014ea4c2012-09-25 14:50:54 -07001503 if (!idsOfChangedBodies.isEmpty()) {
1504 mWebView.loadUrl(String.format("javascript:replaceMessageBodies([%s]);",
1505 TextUtils.join(",", idsOfChangedBodies)));
1506 changed = true;
1507 }
1508
1509 return changed;
1510 }
1511
Andy Huang06c03622012-10-22 18:59:45 -07001512 private void processNewOutgoingMessage(ConversationMessage msg) {
Andrew Sapperstein99ee4562013-08-22 16:19:42 -07001513 // if there are items in the adapter and the last item is a border,
1514 // make the last border no longer be the last border
1515 if (mAdapter.getCount() > 0) {
1516 final ConversationOverlayItem item = mAdapter.getItem(mAdapter.getCount() - 1);
1517 if (item.getType() == ConversationViewAdapter.VIEW_TYPE_BORDER) {
1518 ((BorderItem) item).setIsLastBorder(false);
1519 }
1520 }
Andrew Sappersteincee3c902013-07-31 10:52:02 -07001521
Andy Huang06c03622012-10-22 18:59:45 -07001522 mTemplates.reset();
1523 // this method will add some items to mAdapter, but we deliberately want to avoid notifying
1524 // adapter listeners (i.e. ConversationContainer) until onWebContentGeometryChange is next
1525 // called, to prevent N+1 headers rendering with N message bodies.
Andrew Sappersteincee3c902013-07-31 10:52:02 -07001526
1527 // We can just call previousCollapsed false here since the border
1528 // above the message we're about to render should always show
1529 // (which it also will since the message being render is expanded).
1530 renderMessage(msg, false /* previousCollapsed */, true /* expanded */,
1531 msg.alwaysShowImages, false /* renderBorder */, false /* firstBorder */);
1532 renderBorder(true /* contiguous */, true /* expanded */,
1533 false /* firstBorder */, true /* lastBorder */);
Andy Huang06c03622012-10-22 18:59:45 -07001534 mTempBodiesHtml = mTemplates.emit();
1535
1536 mViewState.setExpansionState(msg, ExpansionState.EXPANDED);
1537 // FIXME: should the provider set this as initial state?
1538 mViewState.setReadState(msg, false /* read */);
1539
Andy Huang91d782a2012-10-25 12:37:29 -07001540 // From now until the updated spacer geometry is returned, the adapter items are mismatched
1541 // with the existing spacers. Do not let them layout.
1542 mConversationContainer.invalidateSpacerGeometry();
1543
Andy Huang06c03622012-10-22 18:59:45 -07001544 mWebView.loadUrl("javascript:appendMessageHtml();");
1545 }
1546
Paul Westbrookcebcc642012-08-08 10:06:04 -07001547 private class SetCookieTask extends AsyncTask<Void, Void, Void> {
1548 final String mUri;
Paul Westbrookb8361c92012-09-27 10:57:14 -07001549 final Uri mAccountCookieQueryUri;
1550 final ContentResolver mResolver;
Paul Westbrookcebcc642012-08-08 10:06:04 -07001551
Paul Westbrookb8361c92012-09-27 10:57:14 -07001552 SetCookieTask(Context context, Uri baseUri, Uri accountCookieQueryUri) {
1553 mUri = baseUri.toString();
1554 mAccountCookieQueryUri = accountCookieQueryUri;
1555 mResolver = context.getContentResolver();
Paul Westbrookcebcc642012-08-08 10:06:04 -07001556 }
1557
1558 @Override
1559 public Void doInBackground(Void... args) {
Paul Westbrookb8361c92012-09-27 10:57:14 -07001560 // First query for the coookie string from the UI provider
1561 final Cursor cookieCursor = mResolver.query(mAccountCookieQueryUri,
1562 UIProvider.ACCOUNT_COOKIE_PROJECTION, null, null, null);
1563 if (cookieCursor == null) {
1564 return null;
1565 }
1566
1567 try {
1568 if (cookieCursor.moveToFirst()) {
1569 final String cookie = cookieCursor.getString(
1570 cookieCursor.getColumnIndex(UIProvider.AccountCookieColumns.COOKIE));
1571
1572 if (cookie != null) {
1573 final CookieSyncManager csm =
1574 CookieSyncManager.createInstance(getContext());
1575 CookieManager.getInstance().setCookie(mUri, cookie);
1576 csm.sync();
1577 }
1578 }
1579
1580 } finally {
1581 cookieCursor.close();
1582 }
1583
1584
Paul Westbrookcebcc642012-08-08 10:06:04 -07001585 return null;
1586 }
1587 }
mindyp36280f32012-09-09 16:11:23 -07001588
mindyp26d4d2d2012-09-18 17:30:32 -07001589 @Override
mindyp36280f32012-09-09 16:11:23 -07001590 public void onConversationUpdated(Conversation conv) {
1591 final ConversationViewHeader headerView = (ConversationViewHeader) mConversationContainer
1592 .findViewById(R.id.conversation_header);
mindypb2b98ba2012-09-24 14:13:58 -07001593 mConversation = conv;
mindyp9e0b2362012-09-09 16:31:21 -07001594 if (headerView != null) {
1595 headerView.onConversationUpdated(conv);
Andrew Sappersteine6bf30d2014-03-13 19:19:26 -07001596 headerView.setSubject(conv.subject);
mindyp9e0b2362012-09-09 16:31:21 -07001597 }
mindyp36280f32012-09-09 16:11:23 -07001598 }
Mark Wei4071c2f2012-09-26 14:38:38 -07001599
1600 @Override
1601 public void onLayoutChange(View v, int left, int top, int right,
1602 int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
1603 boolean sizeChanged = mNeedRender
1604 && mConversationContainer.getWidth() != 0;
1605 if (sizeChanged) {
1606 mNeedRender = false;
1607 mConversationContainer.removeOnLayoutChangeListener(this);
1608 renderConversation(getMessageCursor());
1609 }
1610 }
mindyp1b3cc472012-09-27 11:32:59 -07001611
1612 @Override
James Lemieux7cad2802014-01-09 15:00:53 -08001613 public void setMessageDetailsExpanded(MessageHeaderItem i, boolean expanded, int heightBefore) {
mindyp1b3cc472012-09-27 11:32:59 -07001614 mDiff = (expanded ? 1 : -1) * Math.abs(i.getHeight() - heightBefore);
1615 }
Andy Huang02f9d182012-11-28 22:38:02 -08001616
James Lemieux7cad2802014-01-09 15:00:53 -08001617 /**
1618 * @return {@code true} because either the Print or Print All menu item is shown in GMail
1619 */
1620 @Override
1621 protected boolean shouldShowPrintInOverflow() {
1622 return true;
1623 }
1624
1625 @Override
Andrew Sapperstein5c1692a2013-09-16 11:56:13 -07001626 protected void printConversation() {
Andrew Sapperstein234d3532013-10-29 14:54:04 -07001627 PrintUtils.printConversation(mActivity.getActivityContext(), getMessageCursor(),
1628 mAddressCache, mConversation.getBaseUri(mBaseUri), true /* useJavascript */);
Andrew Sapperstein5c1692a2013-09-16 11:56:13 -07001629 }
Mindy Pereira9b875682012-02-15 18:10:54 -08001630}