blob: 76c4b4e4f22498ade1ea83e58c23877109d25d1b [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
Andy Huang59e0b182012-08-14 14:32:23 -070046import com.android.mail.FormattedDateBuilder;
Mindy Pereira9b875682012-02-15 18:10:54 -080047import com.android.mail.R;
Andy Huange6c9fb62013-11-15 09:56:20 -080048import com.android.mail.analytics.Analytics;
Andy Huang5ff63742012-03-16 20:30:23 -070049import com.android.mail.browse.ConversationContainer;
Andy Huangadbf3e82012-10-13 13:30:19 -070050import com.android.mail.browse.ConversationContainer.OverlayPosition;
Andrew Sapperstein8812d3c2013-06-04 17:06:41 -070051import com.android.mail.browse.ConversationMessage;
Andy Huang46dfba62012-04-19 01:47:32 -070052import com.android.mail.browse.ConversationOverlayItem;
Andy Huang7bdc3752012-03-25 17:18:19 -070053import com.android.mail.browse.ConversationViewAdapter;
Andrew Sapperstein14f93742013-07-25 14:29:56 -070054import com.android.mail.browse.ConversationViewAdapter.BorderItem;
Andy Huang46dfba62012-04-19 01:47:32 -070055import com.android.mail.browse.ConversationViewAdapter.MessageFooterItem;
Andy Huang7bdc3752012-03-25 17:18:19 -070056import com.android.mail.browse.ConversationViewAdapter.MessageHeaderItem;
Andy Huang46dfba62012-04-19 01:47:32 -070057import com.android.mail.browse.ConversationViewAdapter.SuperCollapsedBlockItem;
Andy Huang5ff63742012-03-16 20:30:23 -070058import com.android.mail.browse.ConversationViewHeader;
59import com.android.mail.browse.ConversationWebView;
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -080060import com.android.mail.browse.InlineAttachmentViewIntentBuilderCreator;
61import com.android.mail.browse.InlineAttachmentViewIntentBuilderCreatorHolder;
Andy Huangc1fb9a92013-02-11 13:09:12 -080062import com.android.mail.browse.MailWebView.ContentSizeChangeListener;
Andy Huang7bdc3752012-03-25 17:18:19 -070063import com.android.mail.browse.MessageCursor;
Andy Huang59e0b182012-08-14 14:32:23 -070064import com.android.mail.browse.MessageHeaderView;
Andy Huangadbf3e82012-10-13 13:30:19 -070065import com.android.mail.browse.ScrollIndicatorsView;
Andy Huang46dfba62012-04-19 01:47:32 -070066import com.android.mail.browse.SuperCollapsedBlock;
Andy Huang0b7ed6f2012-07-25 19:23:26 -070067import com.android.mail.browse.WebViewContextMenu;
Paul Westbrookc42ad5e2013-05-09 16:52:15 -070068import com.android.mail.content.ObjectCursor;
Andrew Sapperstein562c5ba2013-10-09 18:31:50 -070069import com.android.mail.print.PrintUtils;
Mindy Pereira9b875682012-02-15 18:10:54 -080070import com.android.mail.providers.Account;
Andy Huang65fe28f2012-04-06 18:08:53 -070071import com.android.mail.providers.Address;
Mindy Pereira9b875682012-02-15 18:10:54 -080072import 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 Sapperstein3af481c2013-10-30 10:29:38 -0700213 private BidiFormatter sBidiFormatter;
214
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,
Paul Westbrook8081df42012-09-10 15:43:36 -0700277 this, mAddressCache, dateBuilder);
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
338 if (sBidiFormatter == null) {
339 sBidiFormatter = BidiFormatter.getInstance();
340 }
Andy Huange964eee2012-10-02 19:24:58 -0700341 }
342
Andrew Sappersteinb1d184d2013-08-09 14:14:31 -0700343 protected ConversationWebViewClient createConversationWebViewClient() {
344 return new ConversationWebViewClient(mAccount);
345 }
346
Andy Huange964eee2012-10-02 19:24:58 -0700347 @Override
Mindy Pereira9b875682012-02-15 18:10:54 -0800348 public View onCreateView(LayoutInflater inflater,
349 ViewGroup container, Bundle savedInstanceState) {
Andy Huang839ada22012-07-20 15:48:40 -0700350
Andy Huang632721e2012-04-11 16:57:26 -0700351 View rootView = inflater.inflate(R.layout.conversation_view, container, false);
Andy Huangf70fc402012-02-17 15:37:42 -0800352 mConversationContainer = (ConversationContainer) rootView
353 .findViewById(R.id.conversation_container);
Andy Huang8f187782012-11-06 17:49:25 -0800354 mConversationContainer.setAccountController(this);
Andy Huang47aa9c92012-07-31 15:37:21 -0700355
Andrew Sapperstein85ea6182013-10-14 18:21:08 -0700356 final ViewGroup topmostOverlay =
357 (ViewGroup) mConversationContainer.findViewById(R.id.conversation_topmost_overlay);
358 inflateSnapHeader(topmostOverlay, inflater);
359 mConversationContainer.setupSnapHeader();
360
361 setupNewMessageBar();
Andy Huang47aa9c92012-07-31 15:37:21 -0700362
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700363 mProgressController = new ConversationViewProgressController(this, getHandler());
364 mProgressController.instantiateProgressIndicators(rootView);
mindyp3bcf1802012-09-09 11:17:00 -0700365
Andy Huang5ff63742012-03-16 20:30:23 -0700366 mWebView = (ConversationWebView) mConversationContainer.findViewById(R.id.webview);
Andy Huangf70fc402012-02-17 15:37:42 -0800367
Andy Huangf70fc402012-02-17 15:37:42 -0800368 mWebView.addJavascriptInterface(mJsBridge, "mail");
mindyp3bcf1802012-09-09 11:17:00 -0700369 // On JB or newer, we use the 'webkitAnimationStart' DOM event to signal load complete
370 // Below JB, try to speed up initial render by having the webview do supplemental draws to
371 // custom a software canvas.
mindypb941fdb2012-09-11 08:28:23 -0700372 // TODO(mindyp):
373 //PAGE READINESS SIGNAL FOR JELLYBEAN AND NEWER
374 // Notify the app on 'webkitAnimationStart' of a simple dummy element with a simple no-op
375 // animation that immediately runs on page load. The app uses this as a signal that the
376 // content is loaded and ready to draw, since WebView delays firing this event until the
377 // layers are composited and everything is ready to draw.
378 // This signal does not seem to be reliable, so just use the old method for now.
Andy Huangf7ac83f2013-07-15 15:48:31 -0700379 final boolean isJBOrLater = Utils.isRunningJellybeanOrLater();
380 final boolean isUserVisible = isUserVisible();
381 mWebView.setUseSoftwareLayer(!isJBOrLater);
382 mEnableContentReadySignal = isJBOrLater && isUserVisible;
383 mWebView.onUserVisibilityChanged(isUserVisible);
Andy Huang17a9cde2012-03-09 18:03:16 -0800384 mWebView.setWebViewClient(mWebViewClient);
Andy Huangc1fb9a92013-02-11 13:09:12 -0800385 final WebChromeClient wcc = new WebChromeClient() {
Andy Huangf70fc402012-02-17 15:37:42 -0800386 @Override
387 public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -0800388 if (consoleMessage.messageLevel() == ConsoleMessage.MessageLevel.ERROR) {
389 LogUtils.wtf(LOG_TAG, "JS: %s (%s:%d) f=%s", consoleMessage.message(),
390 consoleMessage.sourceId(), consoleMessage.lineNumber(),
391 ConversationViewFragment.this);
392 } else {
393 LogUtils.i(LOG_TAG, "JS: %s (%s:%d) f=%s", consoleMessage.message(),
394 consoleMessage.sourceId(), consoleMessage.lineNumber(),
395 ConversationViewFragment.this);
396 }
Andy Huangf70fc402012-02-17 15:37:42 -0800397 return true;
398 }
Andy Huangc1fb9a92013-02-11 13:09:12 -0800399 };
400 mWebView.setWebChromeClient(wcc);
Andy Huangf70fc402012-02-17 15:37:42 -0800401
Andy Huang3233bff2012-03-20 19:38:45 -0700402 final WebSettings settings = mWebView.getSettings();
Andy Huangf70fc402012-02-17 15:37:42 -0800403
Mark Wei56d83852012-09-19 14:28:50 -0700404 mScrollIndicators = (ScrollIndicatorsView) rootView.findViewById(R.id.scroll_indicators);
405 mScrollIndicators.setSourceView(mWebView);
406
Andy Huangf70fc402012-02-17 15:37:42 -0800407 settings.setJavaScriptEnabled(true);
Andy Huangf70fc402012-02-17 15:37:42 -0800408
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700409 ConversationViewUtils.setTextZoom(getResources(), settings);
Andy Huangc319b552012-04-25 19:53:50 -0700410
Andy Huang51067132012-03-12 20:08:19 -0700411 mViewsCreated = true;
Andy Huange964eee2012-10-02 19:24:58 -0700412 mWebViewLoadedData = false;
Andy Huang51067132012-03-12 20:08:19 -0700413
Mindy Pereira9b875682012-02-15 18:10:54 -0800414 return rootView;
415 }
416
Andrew Sapperstein85ea6182013-10-14 18:21:08 -0700417 protected void inflateSnapHeader(ViewGroup topmostOverlay, LayoutInflater inflater) {
418 inflater.inflate(R.layout.conversation_topmost_overlay_items, topmostOverlay, true);
419 }
420
421 protected void setupNewMessageBar() {
422 mNewMessageBar = (Button) mConversationContainer.findViewById(
423 R.id.new_message_notification_bar);
424 mNewMessageBar.setOnClickListener(new View.OnClickListener() {
425 @Override
426 public void onClick(View v) {
427 onNewMessageBarClick();
428 }
429 });
430 }
431
Mindy Pereira9b875682012-02-15 18:10:54 -0800432 @Override
Andy Huangf7ac83f2013-07-15 15:48:31 -0700433 public void onResume() {
434 super.onResume();
435 if (mWebView != null) {
436 mWebView.onResume();
437 }
438 }
439
440 @Override
441 public void onPause() {
442 super.onPause();
443 if (mWebView != null) {
444 mWebView.onPause();
445 }
446 }
447
448 @Override
Mindy Pereira9b875682012-02-15 18:10:54 -0800449 public void onDestroyView() {
Mindy Pereira9b875682012-02-15 18:10:54 -0800450 super.onDestroyView();
Andy Huang46dfba62012-04-19 01:47:32 -0700451 mConversationContainer.setOverlayAdapter(null);
452 mAdapter = null;
Andy Huang9d3fd922012-09-26 22:23:58 -0700453 resetLoadWaiting(); // be sure to unregister any active load observer
Andy Huang51067132012-03-12 20:08:19 -0700454 mViewsCreated = false;
Mindy Pereira9b875682012-02-15 18:10:54 -0800455 }
456
Andy Huange964eee2012-10-02 19:24:58 -0700457 @Override
458 public void onSaveInstanceState(Bundle outState) {
459 super.onSaveInstanceState(outState);
460
461 outState.putFloat(BUNDLE_KEY_WEBVIEW_Y_PERCENT, calculateScrollYPercent());
462 }
463
464 private float calculateScrollYPercent() {
Paul Westbrook1b56a672013-04-19 01:19:05 -0700465 final float p;
466 if (mWebView == null) {
467 // onCreateView hasn't been called, return 0 as the user hasn't scrolled the view.
468 return 0;
469 }
470
471 final int scrollY = mWebView.getScrollY();
472 final int viewH = mWebView.getHeight();
473 final int webH = (int) (mWebView.getContentHeight() * mWebView.getScale());
Andy Huange964eee2012-10-02 19:24:58 -0700474
475 if (webH == 0 || webH <= viewH) {
476 p = 0;
477 } else if (scrollY + viewH >= webH) {
478 // The very bottom is a special case, it acts as a stronger anchor than the scroll top
479 // at that point.
480 p = 1.0f;
481 } else {
482 p = (float) scrollY / webH;
483 }
484 return p;
485 }
486
Andy Huang9d3fd922012-09-26 22:23:58 -0700487 private void resetLoadWaiting() {
488 if (mLoadWaitReason == LOAD_WAIT_FOR_INITIAL_CONVERSATION) {
489 getListController().unregisterConversationLoadedObserver(mLoadedObserver);
490 }
491 mLoadWaitReason = LOAD_NOW;
492 }
493
Andy Huang5ff63742012-03-16 20:30:23 -0700494 @Override
mindypf4fce122012-09-14 15:55:33 -0700495 protected void markUnread() {
Vikram Aggarwald82a31f2013-02-05 15:03:00 -0800496 super.markUnread();
Andy Huang839ada22012-07-20 15:48:40 -0700497 // Ignore unsafe calls made after a fragment is detached from an activity
498 final ControllableActivity activity = (ControllableActivity) getActivity();
499 if (activity == null) {
500 LogUtils.w(LOG_TAG, "ignoring markUnread for conv=%s", mConversation.id);
501 return;
502 }
503
Andy Huang28e31e22012-07-26 16:33:15 -0700504 if (mViewState == null) {
505 LogUtils.i(LOG_TAG, "ignoring markUnread for conv with no view state (%d)",
506 mConversation.id);
507 return;
508 }
Andy Huang839ada22012-07-20 15:48:40 -0700509 activity.getConversationUpdater().markConversationMessagesUnread(mConversation,
Vikram Aggarwal4a878b62012-07-31 15:09:25 -0700510 mViewState.getUnreadMessageUris(), mViewState.getConversationInfo());
Andy Huang839ada22012-07-20 15:48:40 -0700511 }
512
mindypf4fce122012-09-14 15:55:33 -0700513 @Override
514 public void onUserVisibleHintChanged() {
Andy Huang9d3fd922012-09-26 22:23:58 -0700515 final boolean userVisible = isUserVisible();
Scott Kennedy58192e52013-05-08 16:35:57 -0700516 LogUtils.d(LOG_TAG, "ConversationViewFragment#onUserVisibleHintChanged(), userVisible = %b",
517 userVisible);
Andy Huang9d3fd922012-09-26 22:23:58 -0700518
519 if (!userVisible) {
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700520 mProgressController.dismissLoadingStatus();
Andy Huang9d3fd922012-09-26 22:23:58 -0700521 } else if (mViewsCreated) {
Andy Huange6c9fb62013-11-15 09:56:20 -0800522 String loadTag = null;
Andy Huangeeb4a352013-11-21 10:56:27 -0800523 final boolean isInitialLoading;
524 if (mActivity != null) {
525 isInitialLoading = mActivity.getConversationUpdater()
Andy Huange6c9fb62013-11-15 09:56:20 -0800526 .isInitialConversationLoading();
Andy Huangeeb4a352013-11-21 10:56:27 -0800527 } else {
528 isInitialLoading = true;
529 }
Andy Huange6c9fb62013-11-15 09:56:20 -0800530
Andy Huang9d3fd922012-09-26 22:23:58 -0700531 if (getMessageCursor() != null) {
532 LogUtils.d(LOG_TAG, "Fragment is now user-visible, onConversationSeen: %s", this);
Andy Huange6c9fb62013-11-15 09:56:20 -0800533 if (!isInitialLoading) {
534 loadTag = "preloaded";
535 }
Andy Huang9d3fd922012-09-26 22:23:58 -0700536 onConversationSeen();
537 } else if (isLoadWaiting()) {
538 LogUtils.d(LOG_TAG, "Fragment is now user-visible, showing conversation: %s", this);
Andy Huange6c9fb62013-11-15 09:56:20 -0800539 if (!isInitialLoading) {
540 loadTag = "load_deferred";
541 }
Andy Huang9d3fd922012-09-26 22:23:58 -0700542 handleDelayedConversationLoad();
543 }
Andy Huange6c9fb62013-11-15 09:56:20 -0800544
545 if (loadTag != null) {
546 // pager swipes are visibility transitions to 'visible' except during initial
547 // pager load on A) enter conversation mode B) rotate C) 2-pane conv-mode list-tap
548 Analytics.getInstance().sendEvent("pager_swipe", loadTag,
549 getCurrentFolderTypeDesc(), 0);
550 }
Andy Huang632721e2012-04-11 16:57:26 -0700551 }
Andy Huang632721e2012-04-11 16:57:26 -0700552
Andy Huang30bcfe72012-10-18 18:09:03 -0700553 if (mWebView != null) {
554 mWebView.onUserVisibilityChanged(userVisible);
555 }
Andy Huangf8cf5462012-10-17 18:29:14 -0700556 }
557
Andy Huang9d3fd922012-09-26 22:23:58 -0700558 /**
559 * Will either call initLoader now to begin loading, or set {@link #mLoadWaitReason} and do
560 * nothing (in which case you should later call {@link #handleDelayedConversationLoad()}).
561 */
Mindy Pereira9b875682012-02-15 18:10:54 -0800562 private void showConversation() {
Andy Huang9d3fd922012-09-26 22:23:58 -0700563 final int reason;
564
565 if (isUserVisible()) {
566 LogUtils.i(LOG_TAG,
567 "SHOWCONV: CVF is user-visible, immediately loading conversation (%s)", this);
568 reason = LOAD_NOW;
Andy Huang243c2362013-03-01 17:50:35 -0800569 timerMark("CVF.showConversation");
Andy Huang9d3fd922012-09-26 22:23:58 -0700570 } else {
571 final boolean disableOffscreenLoading = DISABLE_OFFSCREEN_LOADING
Alice Yang0b8c0802013-09-16 14:35:18 -0700572 || Utils.isLowRamDevice(getContext())
Andrew Sapperstein606dbd72013-07-30 19:14:23 -0700573 || (mConversation != null && (mConversation.isRemote
574 || mConversation.getNumMessages() > mMaxAutoLoadMessages));
Andy Huang9d3fd922012-09-26 22:23:58 -0700575
576 // When not visible, we should not immediately load if either this conversation is
577 // too heavyweight, or if the main/initial conversation is busy loading.
578 if (disableOffscreenLoading) {
579 reason = LOAD_WAIT_UNTIL_VISIBLE;
580 LogUtils.i(LOG_TAG, "SHOWCONV: CVF waiting until visible to load (%s)", this);
581 } else if (getListController().isInitialConversationLoading()) {
582 reason = LOAD_WAIT_FOR_INITIAL_CONVERSATION;
583 LogUtils.i(LOG_TAG, "SHOWCONV: CVF waiting for initial to finish (%s)", this);
584 getListController().registerConversationLoadedObserver(mLoadedObserver);
585 } else {
586 LogUtils.i(LOG_TAG,
587 "SHOWCONV: CVF is not visible, but no reason to wait. loading now. (%s)",
588 this);
589 reason = LOAD_NOW;
590 }
Andy Huang632721e2012-04-11 16:57:26 -0700591 }
Andy Huang9d3fd922012-09-26 22:23:58 -0700592
593 mLoadWaitReason = reason;
594 if (mLoadWaitReason == LOAD_NOW) {
595 startConversationLoad();
596 }
597 }
598
599 private void handleDelayedConversationLoad() {
600 resetLoadWaiting();
601 startConversationLoad();
602 }
603
604 private void startConversationLoad() {
mindyp3bcf1802012-09-09 11:17:00 -0700605 mWebView.setVisibility(View.VISIBLE);
Andrew Sapperstein606dbd72013-07-30 19:14:23 -0700606 loadContent();
mindyp3bcf1802012-09-09 11:17:00 -0700607 // TODO(mindyp): don't show loading status for a previously rendered
608 // conversation. Ielieve this is better done by making sure don't show loading status
609 // until XX ms have passed without loading completed.
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700610 mProgressController.showLoadingStatus(isUserVisible());
Mindy Pereira8e915722012-02-16 14:42:56 -0800611 }
612
Andrew Sapperstein606dbd72013-07-30 19:14:23 -0700613 /**
614 * Can be overridden in case a subclass needs to load something other than
615 * the messages of a conversation.
616 */
617 protected void loadContent() {
618 getLoaderManager().initLoader(MESSAGE_LOADER, Bundle.EMPTY, getMessageLoaderCallbacks());
619 }
620
Andy Huang7d4746e2012-10-17 17:03:17 -0700621 private void revealConversation() {
Andy Huang243c2362013-03-01 17:50:35 -0800622 timerMark("revealing conversation");
Andrew Sapperstein376294b2013-06-06 16:04:26 -0700623 mProgressController.dismissLoadingStatus(mOnProgressDismiss);
Andy Huang7d4746e2012-10-17 17:03:17 -0700624 }
625
Andy Huang9d3fd922012-09-26 22:23:58 -0700626 private boolean isLoadWaiting() {
627 return mLoadWaitReason != LOAD_NOW;
628 }
629
Andy Huang51067132012-03-12 20:08:19 -0700630 private void renderConversation(MessageCursor messageCursor) {
mindyp3bcf1802012-09-09 11:17:00 -0700631 final String convHtml = renderMessageBodies(messageCursor, mEnableContentReadySignal);
Andy Huang243c2362013-03-01 17:50:35 -0800632 timerMark("rendered conversation");
Andy Huangbd544e32012-05-29 15:56:51 -0700633
634 if (DEBUG_DUMP_CONVERSATION_HTML) {
635 java.io.FileWriter fw = null;
636 try {
Andrew Sappersteinf1566b12013-09-19 15:34:26 -0700637 fw = new java.io.FileWriter(getSdCardFilePath());
Andy Huangbd544e32012-05-29 15:56:51 -0700638 fw.write(convHtml);
639 } catch (java.io.IOException e) {
640 e.printStackTrace();
641 } finally {
642 if (fw != null) {
643 try {
644 fw.close();
645 } catch (java.io.IOException e) {
646 e.printStackTrace();
647 }
648 }
649 }
650 }
651
Andy Huange964eee2012-10-02 19:24:58 -0700652 // save off existing scroll position before re-rendering
653 if (mWebViewLoadedData) {
654 mWebViewYPercent = calculateScrollYPercent();
655 }
656
Andy Huangbd544e32012-05-29 15:56:51 -0700657 mWebView.loadDataWithBaseURL(mBaseUri, convHtml, "text/html", "utf-8", null);
Andy Huange964eee2012-10-02 19:24:58 -0700658 mWebViewLoadedData = true;
Andy Huang63b3c672012-10-05 19:27:28 -0700659 mWebViewLoadStartMs = SystemClock.uptimeMillis();
Andy Huang51067132012-03-12 20:08:19 -0700660 }
661
Andrew Sappersteinf1566b12013-09-19 15:34:26 -0700662 protected String getSdCardFilePath() {
663 return "/sdcard/conv" + mConversation.id + ".html";
664 }
665
Andy Huang7bdc3752012-03-25 17:18:19 -0700666 /**
667 * Populate the adapter with overlay views (message headers, super-collapsed blocks, a
668 * conversation header), and return an HTML document with spacer divs inserted for all overlays.
669 *
670 */
Andrew Sapperstein9f957f32013-07-19 15:18:18 -0700671 protected String renderMessageBodies(MessageCursor messageCursor,
mindyp3bcf1802012-09-09 11:17:00 -0700672 boolean enableContentReadySignal) {
Andy Huangf70fc402012-02-17 15:37:42 -0800673 int pos = -1;
Andy Huang632721e2012-04-11 16:57:26 -0700674
Andy Huang1ee96b22012-08-24 20:19:53 -0700675 LogUtils.d(LOG_TAG, "IN renderMessageBodies, fragment=%s", this);
Andy Huang7bdc3752012-03-25 17:18:19 -0700676 boolean allowNetworkImages = false;
677
Andy Huangc7543572012-04-03 15:34:29 -0700678 // TODO: re-use any existing adapter item state (expanded, details expanded, show pics)
Andy Huang28b7aee2012-08-20 20:27:32 -0700679
Andy Huang7bdc3752012-03-25 17:18:19 -0700680 // Walk through the cursor and build up an overlay adapter as you go.
681 // Each overlay has an entry in the adapter for easy scroll handling in the container.
682 // Items are not necessarily 1:1 in cursor and adapter because of super-collapsed blocks.
683 // When adding adapter items, also add their heights to help the container later determine
684 // overlay dimensions.
685
Andy Huangdb620fe2012-08-24 15:45:28 -0700686 // When re-rendering, prevent ConversationContainer from laying out overlays until after
687 // the new spacers are positioned by WebView.
688 mConversationContainer.invalidateSpacerGeometry();
689
Andy Huang7bdc3752012-03-25 17:18:19 -0700690 mAdapter.clear();
691
Andy Huang47aa9c92012-07-31 15:37:21 -0700692 // re-evaluate the message parts of the view state, since the messages may have changed
693 // since the previous render
694 final ConversationViewState prevState = mViewState;
695 mViewState = new ConversationViewState(prevState);
696
Andy Huang5ff63742012-03-16 20:30:23 -0700697 // N.B. the units of height for spacers are actually dp and not px because WebView assumes
Andy Huang2e9acfe2012-03-15 22:39:36 -0700698 // a pixel is an mdpi pixel, unless you set device-dpi.
Andy Huang5ff63742012-03-16 20:30:23 -0700699
Andy Huang7bdc3752012-03-25 17:18:19 -0700700 // add a single conversation header item
701 final int convHeaderPos = mAdapter.addConversationHeader(mConversation);
Andy Huang23014702012-07-09 12:50:36 -0700702 final int convHeaderPx = measureOverlayHeight(convHeaderPos);
Andy Huang5ff63742012-03-16 20:30:23 -0700703
Andy Huang02f9d182012-11-28 22:38:02 -0800704 mTemplates.startConversation(mWebView.screenPxToWebPx(mSideMarginPx),
Andy Huang256b35c2012-08-22 15:19:13 -0700705 mWebView.screenPxToWebPx(convHeaderPx));
Andy Huang3233bff2012-03-20 19:38:45 -0700706
Andy Huang46dfba62012-04-19 01:47:32 -0700707 int collapsedStart = -1;
Andy Huang839ada22012-07-20 15:48:40 -0700708 ConversationMessage prevCollapsedMsg = null;
Andrew Sappersteine8221482013-10-02 18:14:58 -0700709
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -0800710 final boolean alwaysShowImages = shouldAlwaysShowImages();
Alice Yangf323c042013-10-30 00:15:02 -0700711
Andrew Sappersteine8221482013-10-02 18:14:58 -0700712 boolean prevSafeForImages = alwaysShowImages;
Andy Huang46dfba62012-04-19 01:47:32 -0700713
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700714 // Store the previous expanded state so that the border between
715 // the previous and current message can be properly initialized.
716 int previousExpandedState = ExpansionState.NONE;
Andy Huangf70fc402012-02-17 15:37:42 -0800717 while (messageCursor.moveToPosition(++pos)) {
Andy Huang839ada22012-07-20 15:48:40 -0700718 final ConversationMessage msg = messageCursor.getMessage();
Andy Huang46dfba62012-04-19 01:47:32 -0700719
Andrew Sappersteine8221482013-10-02 18:14:58 -0700720 final boolean safeForImages = alwaysShowImages ||
Scott Kennedy20273842012-11-07 11:16:21 -0800721 msg.alwaysShowImages || prevState.getShouldShowImages(msg);
Andy Huang3233bff2012-03-20 19:38:45 -0700722 allowNetworkImages |= safeForImages;
Andy Huang24055282012-03-27 17:37:06 -0700723
Paul Westbrook08098ec2012-08-12 15:30:28 -0700724 final Integer savedExpanded = prevState.getExpansionState(msg);
725 final int expandedState;
Andy Huang839ada22012-07-20 15:48:40 -0700726 if (savedExpanded != null) {
Andy Huang1ee96b22012-08-24 20:19:53 -0700727 if (ExpansionState.isSuperCollapsed(savedExpanded) && messageCursor.isLast()) {
728 // override saved state when this is now the new last message
729 // this happens to the second-to-last message when you discard a draft
730 expandedState = ExpansionState.EXPANDED;
731 } else {
732 expandedState = savedExpanded;
733 }
Andy Huang839ada22012-07-20 15:48:40 -0700734 } else {
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700735 // new messages that are not expanded default to being eligible for super-collapse
Paul Westbrook08098ec2012-08-12 15:30:28 -0700736 expandedState = (!msg.read || msg.starred || messageCursor.isLast()) ?
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700737 ExpansionState.EXPANDED : ExpansionState.SUPER_COLLAPSED;
Andy Huang839ada22012-07-20 15:48:40 -0700738 }
Scott Kennedy20273842012-11-07 11:16:21 -0800739 mViewState.setShouldShowImages(msg, prevState.getShouldShowImages(msg));
Paul Westbrook08098ec2012-08-12 15:30:28 -0700740 mViewState.setExpansionState(msg, expandedState);
Andy Huangc7543572012-04-03 15:34:29 -0700741
Andy Huang839ada22012-07-20 15:48:40 -0700742 // save off "read" state from the cursor
743 // later, the view may not match the cursor (e.g. conversation marked read on open)
Andy Huang423bea22012-08-21 12:00:49 -0700744 // however, if a previous state indicated this message was unread, trust that instead
745 // so "mark unread" marks all originally unread messages
746 mViewState.setReadState(msg, msg.read && !prevState.isUnread(msg));
Andy Huang839ada22012-07-20 15:48:40 -0700747
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700748 // We only want to consider this for inclusion in the super collapsed block if
749 // 1) The we don't have previous state about this message (The first time that the
750 // user opens a conversation)
751 // 2) The previously saved state for this message indicates that this message is
752 // in the super collapsed block.
753 if (ExpansionState.isSuperCollapsed(expandedState)) {
754 // contribute to a super-collapsed block that will be emitted just before the
755 // next expanded header
756 if (collapsedStart < 0) {
757 collapsedStart = pos;
Andy Huang46dfba62012-04-19 01:47:32 -0700758 }
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700759 prevCollapsedMsg = msg;
760 prevSafeForImages = safeForImages;
Andrew Sapperstein7dc7fa02013-05-08 16:39:31 -0700761
762 // This line puts the from address in the address cache so that
763 // we get the sender image for it if it's in a super-collapsed block.
764 getAddress(msg.getFrom());
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700765 previousExpandedState = expandedState;
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700766 continue;
Andy Huang46dfba62012-04-19 01:47:32 -0700767 }
Andy Huang24055282012-03-27 17:37:06 -0700768
Andy Huang46dfba62012-04-19 01:47:32 -0700769 // resolve any deferred decisions on previous collapsed items
770 if (collapsedStart >= 0) {
771 if (pos - collapsedStart == 1) {
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700772 // Special-case for a single collapsed message: no need to super-collapse it.
773 // Since it is super-collapsed, there is no previous message to be
774 // collapsed and the border above it is the first border.
775 renderMessage(prevCollapsedMsg, false /* previousCollapsed */,
776 false /* expanded */, prevSafeForImages, true /* firstBorder */);
Andy Huang46dfba62012-04-19 01:47:32 -0700777 } else {
778 renderSuperCollapsedBlock(collapsedStart, pos - 1);
779 }
780 prevCollapsedMsg = null;
781 collapsedStart = -1;
782 }
Andy Huang7bdc3752012-03-25 17:18:19 -0700783
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700784 renderMessage(msg, ExpansionState.isCollapsed(previousExpandedState),
785 ExpansionState.isExpanded(expandedState), safeForImages,
Andrew Sappersteine5398802013-07-29 20:55:38 -0700786 pos == 0 /* firstBorder */);
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700787
788 previousExpandedState = expandedState;
Mindy Pereira9b875682012-02-15 18:10:54 -0800789 }
Andy Huang3233bff2012-03-20 19:38:45 -0700790
791 mWebView.getSettings().setBlockNetworkImage(!allowNetworkImages);
792
Andrew Sapperstein2fc67302013-04-29 18:24:56 -0700793 final boolean applyTransforms = shouldApplyTransforms();
Andy Huang57f354c2013-04-11 17:23:40 -0700794
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700795 renderBorder(true /* contiguous */, true /* expanded */,
796 false /* firstBorder */, true /* lastBorder */);
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700797
Andy Huangc1fb9a92013-02-11 13:09:12 -0800798 // If the conversation has specified a base uri, use it here, otherwise use mBaseUri
Andrew Sapperstein68141df2013-08-19 19:07:14 -0700799 return mTemplates.endConversation(mBaseUri, mConversation.getBaseUri(mBaseUri),
Andy Huang5ea5a832013-03-07 16:49:09 -0800800 mWebView.getViewportWidth(), enableContentReadySignal, isOverviewMode(mAccount),
Andy Huang57f354c2013-04-11 17:23:40 -0700801 applyTransforms, applyTransforms);
Mindy Pereira9b875682012-02-15 18:10:54 -0800802 }
Mindy Pereira674afa42012-02-17 14:05:24 -0800803
Andy Huang46dfba62012-04-19 01:47:32 -0700804 private void renderSuperCollapsedBlock(int start, int end) {
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700805 renderBorder(true /* contiguous */, true /* expanded */,
806 true /* firstBorder */, false /* lastBorder */);
Andy Huang46dfba62012-04-19 01:47:32 -0700807 final int blockPos = mAdapter.addSuperCollapsedBlock(start, end);
Andy Huang23014702012-07-09 12:50:36 -0700808 final int blockPx = measureOverlayHeight(blockPos);
809 mTemplates.appendSuperCollapsedHtml(start, mWebView.screenPxToWebPx(blockPx));
Andy Huang46dfba62012-04-19 01:47:32 -0700810 }
811
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700812 protected void renderBorder(
813 boolean contiguous, boolean expanded, boolean firstBorder, boolean lastBorder) {
814 final int blockPos = mAdapter.addBorder(contiguous, expanded, firstBorder, lastBorder);
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700815 final int blockPx = measureOverlayHeight(blockPos);
816 mTemplates.appendBorder(mWebView.screenPxToWebPx(blockPx));
817 }
818
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700819 private void renderMessage(ConversationMessage msg, boolean previousCollapsed,
820 boolean expanded, boolean safeForImages, boolean firstBorder) {
821 renderMessage(msg, previousCollapsed, expanded, safeForImages,
822 true /* renderBorder */, firstBorder);
Andrew Sapperstein1f082232013-07-29 11:16:07 -0700823 }
824
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700825 private void renderMessage(ConversationMessage msg, boolean previousCollapsed,
826 boolean expanded, boolean safeForImages, boolean renderBorder, boolean firstBorder) {
Andrew Sapperstein1f082232013-07-29 11:16:07 -0700827 if (renderBorder) {
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700828 // The border should be collapsed only if both the current
829 // and previous messages are collapsed.
830 renderBorder(true /* contiguous */, !previousCollapsed || expanded,
831 firstBorder, false /* lastBorder */);
Andrew Sapperstein1f082232013-07-29 11:16:07 -0700832 }
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700833
Scott Kennedy20273842012-11-07 11:16:21 -0800834 final int headerPos = mAdapter.addMessageHeader(msg, expanded,
835 mViewState.getShouldShowImages(msg));
Andy Huang46dfba62012-04-19 01:47:32 -0700836 final MessageHeaderItem headerItem = (MessageHeaderItem) mAdapter.getItem(headerPos);
837
838 final int footerPos = mAdapter.addMessageFooter(headerItem);
839
840 // Measure item header and footer heights to allocate spacers in HTML
841 // But since the views themselves don't exist yet, render each item temporarily into
842 // a host view for measurement.
Andy Huang23014702012-07-09 12:50:36 -0700843 final int headerPx = measureOverlayHeight(headerPos);
844 final int footerPx = measureOverlayHeight(footerPos);
Andy Huang46dfba62012-04-19 01:47:32 -0700845
Andy Huang256b35c2012-08-22 15:19:13 -0700846 mTemplates.appendMessageHtml(msg, expanded, safeForImages,
Andy Huang23014702012-07-09 12:50:36 -0700847 mWebView.screenPxToWebPx(headerPx), mWebView.screenPxToWebPx(footerPx));
Andy Huang243c2362013-03-01 17:50:35 -0800848 timerMark("rendered message");
Andy Huang46dfba62012-04-19 01:47:32 -0700849 }
850
851 private String renderCollapsedHeaders(MessageCursor cursor,
852 SuperCollapsedBlockItem blockToReplace) {
853 final List<ConversationOverlayItem> replacements = Lists.newArrayList();
854
855 mTemplates.reset();
856
Alice Yangf323c042013-10-30 00:15:02 -0700857 final boolean alwaysShowImages = (mAccount != null) &&
858 (mAccount.settings.showImages == Settings.ShowImages.ALWAYS);
Andrew Sappersteine8221482013-10-02 18:14:58 -0700859
Mark Wei2b24e992012-09-10 16:40:07 -0700860 // In devices with non-integral density multiplier, screen pixels translate to non-integral
861 // web pixels. Keep track of the error that occurs when we cast all heights to int
862 float error = 0f;
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700863 boolean first = true;
Andy Huang46dfba62012-04-19 01:47:32 -0700864 for (int i = blockToReplace.getStart(), end = blockToReplace.getEnd(); i <= end; i++) {
865 cursor.moveToPosition(i);
Andy Huang839ada22012-07-20 15:48:40 -0700866 final ConversationMessage msg = cursor.getMessage();
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700867
868 final int borderPx;
869 if (first) {
870 borderPx = 0;
871 first = false;
872 } else {
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700873 // When replacing the super-collapsed block,
874 // the border is always collapsed between messages.
875 final BorderItem border = mAdapter.newBorderItem(
876 true /* contiguous */, false /* expanded */);
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700877 borderPx = measureOverlayHeight(border);
878 replacements.add(border);
879 mTemplates.appendBorder(mWebView.screenPxToWebPx(borderPx));
880 }
881
Andrew Sapperstein4ddda2f2013-06-10 11:15:38 -0700882 final MessageHeaderItem header = ConversationViewAdapter.newMessageHeaderItem(
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700883 mAdapter, mAdapter.getDateBuilder(), msg, false /* expanded */,
Andrew Sappersteine8221482013-10-02 18:14:58 -0700884 alwaysShowImages || mViewState.getShouldShowImages(msg));
Andy Huang46dfba62012-04-19 01:47:32 -0700885 final MessageFooterItem footer = mAdapter.newMessageFooterItem(header);
886
Andy Huang23014702012-07-09 12:50:36 -0700887 final int headerPx = measureOverlayHeight(header);
888 final int footerPx = measureOverlayHeight(footer);
Mark Wei2b24e992012-09-10 16:40:07 -0700889 error += mWebView.screenPxToWebPxError(headerPx)
Andrew Sapperstein14f93742013-07-25 14:29:56 -0700890 + mWebView.screenPxToWebPxError(footerPx)
891 + mWebView.screenPxToWebPxError(borderPx);
Mark Wei2b24e992012-09-10 16:40:07 -0700892
893 // When the error becomes greater than 1 pixel, make the next header 1 pixel taller
894 int correction = 0;
895 if (error >= 1) {
896 correction = 1;
897 error -= 1;
898 }
Andy Huang46dfba62012-04-19 01:47:32 -0700899
Andrew Sappersteine8221482013-10-02 18:14:58 -0700900 mTemplates.appendMessageHtml(msg, false /* expanded */,
901 alwaysShowImages || msg.alwaysShowImages,
Mark Wei2b24e992012-09-10 16:40:07 -0700902 mWebView.screenPxToWebPx(headerPx) + correction,
903 mWebView.screenPxToWebPx(footerPx));
Andy Huang46dfba62012-04-19 01:47:32 -0700904 replacements.add(header);
905 replacements.add(footer);
Andy Huang839ada22012-07-20 15:48:40 -0700906
Paul Westbrook08098ec2012-08-12 15:30:28 -0700907 mViewState.setExpansionState(msg, ExpansionState.COLLAPSED);
Andy Huang46dfba62012-04-19 01:47:32 -0700908 }
909
910 mAdapter.replaceSuperCollapsedBlock(blockToReplace, replacements);
Andy Huang06c03622012-10-22 18:59:45 -0700911 mAdapter.notifyDataSetChanged();
Andy Huang46dfba62012-04-19 01:47:32 -0700912
913 return mTemplates.emit();
914 }
915
Andrew Sapperstein9f957f32013-07-19 15:18:18 -0700916 protected int measureOverlayHeight(int position) {
Andy Huang46dfba62012-04-19 01:47:32 -0700917 return measureOverlayHeight(mAdapter.getItem(position));
918 }
919
Andy Huang7bdc3752012-03-25 17:18:19 -0700920 /**
Andy Huangb8331b42012-07-16 19:08:53 -0700921 * Measure the height of an adapter view by rendering an adapter item into a temporary
Andy Huang46dfba62012-04-19 01:47:32 -0700922 * host view, and asking the view to immediately measure itself. This method will reuse
Andy Huang7bdc3752012-03-25 17:18:19 -0700923 * a previous adapter view from {@link ConversationContainer}'s scrap views if one was generated
924 * earlier.
925 * <p>
Andy Huang46dfba62012-04-19 01:47:32 -0700926 * After measuring the height, this method also saves the height in the
927 * {@link ConversationOverlayItem} for later use in overlay positioning.
Andy Huang7bdc3752012-03-25 17:18:19 -0700928 *
Andy Huang46dfba62012-04-19 01:47:32 -0700929 * @param convItem adapter item with data to render and measure
Andy Huang23014702012-07-09 12:50:36 -0700930 * @return height of the rendered view in screen px
Andy Huang7bdc3752012-03-25 17:18:19 -0700931 */
Andy Huang46dfba62012-04-19 01:47:32 -0700932 private int measureOverlayHeight(ConversationOverlayItem convItem) {
Andy Huang7bdc3752012-03-25 17:18:19 -0700933 final int type = convItem.getType();
934
935 final View convertView = mConversationContainer.getScrapView(type);
Andy Huangb8331b42012-07-16 19:08:53 -0700936 final View hostView = mAdapter.getView(convItem, convertView, mConversationContainer,
937 true /* measureOnly */);
Andy Huang7bdc3752012-03-25 17:18:19 -0700938 if (convertView == null) {
939 mConversationContainer.addScrapView(type, hostView);
940 }
941
Andy Huang9875bb42012-04-04 20:36:21 -0700942 final int heightPx = mConversationContainer.measureOverlay(hostView);
Andy Huang7bdc3752012-03-25 17:18:19 -0700943 convItem.setHeight(heightPx);
Andy Huang9875bb42012-04-04 20:36:21 -0700944 convItem.markMeasurementValid();
Andy Huang7bdc3752012-03-25 17:18:19 -0700945
Andy Huang23014702012-07-09 12:50:36 -0700946 return heightPx;
Andy Huang7bdc3752012-03-25 17:18:19 -0700947 }
948
Andy Huang5ff63742012-03-16 20:30:23 -0700949 @Override
950 public void onConversationViewHeaderHeightChange(int newHeight) {
Mark Weiab2d9982012-09-25 13:06:17 -0700951 final int h = mWebView.screenPxToWebPx(newHeight);
952
953 mWebView.loadUrl(String.format("javascript:setConversationHeaderSpacerHeight(%s);", h));
Andy Huang5ff63742012-03-16 20:30:23 -0700954 }
955
Andy Huang3233bff2012-03-20 19:38:45 -0700956 // END conversation header callbacks
957
958 // START message header callbacks
959 @Override
Andy Huangc7543572012-04-03 15:34:29 -0700960 public void setMessageSpacerHeight(MessageHeaderItem item, int newSpacerHeightPx) {
961 mConversationContainer.invalidateSpacerGeometry();
962
963 // update message HTML spacer height
Andy Huang23014702012-07-09 12:50:36 -0700964 final int h = mWebView.screenPxToWebPx(newSpacerHeightPx);
965 LogUtils.i(LAYOUT_TAG, "setting HTML spacer h=%dwebPx (%dscreenPx)", h,
966 newSpacerHeightPx);
Vikram Aggarwal5349ce12012-09-24 14:12:40 -0700967 mWebView.loadUrl(String.format("javascript:setMessageHeaderSpacerHeight('%s', %s);",
Andy Huang014ea4c2012-09-25 14:50:54 -0700968 mTemplates.getMessageDomId(item.getMessage()), h));
Andy Huang3233bff2012-03-20 19:38:45 -0700969 }
970
971 @Override
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700972 public void setMessageExpanded(MessageHeaderItem item, int newSpacerHeightPx,
973 int topBorderHeight, int bottomBorderHeight) {
Andy Huangc7543572012-04-03 15:34:29 -0700974 mConversationContainer.invalidateSpacerGeometry();
975
976 // show/hide the HTML message body and update the spacer height
Andy Huang23014702012-07-09 12:50:36 -0700977 final int h = mWebView.screenPxToWebPx(newSpacerHeightPx);
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700978 final int topHeight = mWebView.screenPxToWebPx(topBorderHeight);
979 final int bottomHeight = mWebView.screenPxToWebPx(bottomBorderHeight);
Andy Huang23014702012-07-09 12:50:36 -0700980 LogUtils.i(LAYOUT_TAG, "setting HTML spacer expanded=%s h=%dwebPx (%dscreenPx)",
981 item.isExpanded(), h, newSpacerHeightPx);
Andrew Sappersteincee3c902013-07-31 10:52:02 -0700982 mWebView.loadUrl(String.format("javascript:setMessageBodyVisible('%s', %s, %s, %s, %s);",
983 mTemplates.getMessageDomId(item.getMessage()), item.isExpanded(),
984 h, topHeight, bottomHeight));
Andy Huang839ada22012-07-20 15:48:40 -0700985
Andy Huang014ea4c2012-09-25 14:50:54 -0700986 mViewState.setExpansionState(item.getMessage(),
Paul Westbrook08098ec2012-08-12 15:30:28 -0700987 item.isExpanded() ? ExpansionState.EXPANDED : ExpansionState.COLLAPSED);
Andy Huang3233bff2012-03-20 19:38:45 -0700988 }
989
990 @Override
Scott Kennedyeb9a4bd2012-11-12 10:33:04 -0800991 public void showExternalResources(final Message msg) {
Scott Kennedy20273842012-11-07 11:16:21 -0800992 mViewState.setShouldShowImages(msg, true);
Andy Huang3233bff2012-03-20 19:38:45 -0700993 mWebView.getSettings().setBlockNetworkImage(false);
Scott Kennedyeb9a4bd2012-11-12 10:33:04 -0800994 mWebView.loadUrl("javascript:unblockImages(['" + mTemplates.getMessageDomId(msg) + "']);");
995 }
996
997 @Override
998 public void showExternalResources(final String senderRawAddress) {
999 mWebView.getSettings().setBlockNetworkImage(false);
1000
1001 final Address sender = getAddress(senderRawAddress);
1002 final MessageCursor cursor = getMessageCursor();
1003
1004 final List<String> messageDomIds = new ArrayList<String>();
1005
1006 int pos = -1;
1007 while (cursor.moveToPosition(++pos)) {
1008 final ConversationMessage message = cursor.getMessage();
1009 if (sender.equals(getAddress(message.getFrom()))) {
1010 message.alwaysShowImages = true;
1011
1012 mViewState.setShouldShowImages(message, true);
1013 messageDomIds.add(mTemplates.getMessageDomId(message));
1014 }
1015 }
1016
1017 final String url = String.format(
1018 "javascript:unblockImages(['%s']);", TextUtils.join("','", messageDomIds));
1019 mWebView.loadUrl(url);
Andy Huang3233bff2012-03-20 19:38:45 -07001020 }
Alice Yang1ebc2db2013-03-14 21:21:44 -07001021
1022 @Override
Andy Huang75b52a52013-03-15 15:40:24 -07001023 public boolean supportsMessageTransforms() {
1024 return true;
1025 }
1026
1027 @Override
Alice Yang1ebc2db2013-03-14 21:21:44 -07001028 public String getMessageTransforms(final Message msg) {
1029 final String domId = mTemplates.getMessageDomId(msg);
1030 return (domId == null) ? null : mMessageTransforms.get(domId);
1031 }
1032
Andy Huang3233bff2012-03-20 19:38:45 -07001033 // END message header callbacks
Andy Huang5ff63742012-03-16 20:30:23 -07001034
Andy Huang46dfba62012-04-19 01:47:32 -07001035 @Override
Andrew Sapperstein2fc67302013-04-29 18:24:56 -07001036 public void showUntransformedConversation() {
1037 super.showUntransformedConversation();
1038 renderConversation(getMessageCursor());
1039 }
1040
1041 @Override
Andy Huang46dfba62012-04-19 01:47:32 -07001042 public void onSuperCollapsedClick(SuperCollapsedBlockItem item) {
mindypf4fce122012-09-14 15:55:33 -07001043 MessageCursor cursor = getMessageCursor();
1044 if (cursor == null || !mViewsCreated) {
Andy Huang46dfba62012-04-19 01:47:32 -07001045 return;
1046 }
1047
mindypf4fce122012-09-14 15:55:33 -07001048 mTempBodiesHtml = renderCollapsedHeaders(cursor, item);
Andy Huang46dfba62012-04-19 01:47:32 -07001049 mWebView.loadUrl("javascript:replaceSuperCollapsedBlock(" + item.getStart() + ")");
1050 }
1051
Andy Huang47aa9c92012-07-31 15:37:21 -07001052 private void showNewMessageNotification(NewMessagesInfo info) {
Andrew Sapperstein821fa872013-08-21 21:57:39 -07001053 mNewMessageBar.setText(info.getNotificationText());
Andy Huang47aa9c92012-07-31 15:37:21 -07001054 mNewMessageBar.setVisibility(View.VISIBLE);
1055 }
1056
1057 private void onNewMessageBarClick() {
1058 mNewMessageBar.setVisibility(View.GONE);
1059
mindypf4fce122012-09-14 15:55:33 -07001060 renderConversation(getMessageCursor()); // mCursor is already up-to-date
1061 // per onLoadFinished()
Andy Huang5fbda022012-02-28 18:22:03 -08001062 }
1063
Andy Huangadbf3e82012-10-13 13:30:19 -07001064 private static OverlayPosition[] parsePositions(final String[] topArray,
1065 final String[] bottomArray) {
1066 final int len = topArray.length;
1067 final OverlayPosition[] positions = new OverlayPosition[len];
Andy Huangb5078b22012-03-05 19:52:29 -08001068 for (int i = 0; i < len; i++) {
Andy Huangadbf3e82012-10-13 13:30:19 -07001069 positions[i] = new OverlayPosition(
1070 Integer.parseInt(topArray[i]), Integer.parseInt(bottomArray[i]));
Andy Huangb5078b22012-03-05 19:52:29 -08001071 }
Andy Huangadbf3e82012-10-13 13:30:19 -07001072 return positions;
Andy Huangb5078b22012-03-05 19:52:29 -08001073 }
1074
Andrew Sapperstein9f957f32013-07-19 15:18:18 -07001075 protected Address getAddress(String rawFrom) {
Paul Westbrook0dfae692013-10-02 00:51:29 -07001076 return Utils.getAddress(mAddressCache, rawFrom);
Andy Huang16174812012-08-16 16:40:35 -07001077 }
1078
Andy Huang9d3fd922012-09-26 22:23:58 -07001079 private void ensureContentSizeChangeListener() {
1080 if (mWebViewSizeChangeListener == null) {
Andy Huangc1fb9a92013-02-11 13:09:12 -08001081 mWebViewSizeChangeListener = new ContentSizeChangeListener() {
Andy Huang9d3fd922012-09-26 22:23:58 -07001082 @Override
1083 public void onHeightChange(int h) {
1084 // When WebKit says the DOM height has changed, re-measure
1085 // bodies and re-position their headers.
1086 // This is separate from the typical JavaScript DOM change
1087 // listeners because cases like NARROW_COLUMNS text reflow do not trigger DOM
1088 // events.
1089 mWebView.loadUrl("javascript:measurePositions();");
1090 }
1091 };
1092 }
1093 mWebView.setContentSizeChangeListener(mWebViewSizeChangeListener);
1094 }
1095
Andrew Sapperstein9f957f32013-07-19 15:18:18 -07001096 public static boolean isOverviewMode(Account acct) {
Andy Huangccf67802013-03-15 14:31:57 -07001097 return acct.settings.isOverviewMode();
Andy Huangadbf3e82012-10-13 13:30:19 -07001098 }
1099
1100 private void setupOverviewMode() {
Andy Huang02f9d182012-11-28 22:38:02 -08001101 // for now, overview mode means use the built-in WebView zoom and disable custom scale
1102 // gesture handling
Andy Huangadbf3e82012-10-13 13:30:19 -07001103 final boolean overviewMode = isOverviewMode(mAccount);
1104 final WebSettings settings = mWebView.getSettings();
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);
1108 if (overviewMode) {
1109 settings.setDisplayZoomControls(false);
Andy Huangadbf3e82012-10-13 13:30:19 -07001110 }
1111 }
1112
Andrew Sappersteinb1d184d2013-08-09 14:14:31 -07001113 public class ConversationWebViewClient extends AbstractConversationWebViewClient {
Andrew Sapperstein4ddda2f2013-06-10 11:15:38 -07001114 public ConversationWebViewClient(Account account) {
1115 super(account);
Andrew Sapperstein376294b2013-06-06 16:04:26 -07001116 }
1117
Andy Huang17a9cde2012-03-09 18:03:16 -08001118 @Override
1119 public void onPageFinished(WebView view, String url) {
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001120 // Ignore unsafe calls made after a fragment is detached from an activity.
1121 // This method needs to, for example, get at the loader manager, which needs
1122 // the fragment to be added.
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001123 if (!isAdded() || !mViewsCreated) {
Paul Westbrook006e13c2013-07-24 18:40:20 -07001124 LogUtils.d(LOG_TAG, "ignoring CVF.onPageFinished, url=%s fragment=%s", url,
Andy Huangb95da852012-07-18 14:16:58 -07001125 ConversationViewFragment.this);
1126 return;
1127 }
1128
Paul Westbrook006e13c2013-07-24 18:40:20 -07001129 LogUtils.d(LOG_TAG, "IN CVF.onPageFinished, url=%s fragment=%s wv=%s t=%sms", url,
Andy Huang30bcfe72012-10-18 18:09:03 -07001130 ConversationViewFragment.this, view,
Andy Huang63b3c672012-10-05 19:27:28 -07001131 (SystemClock.uptimeMillis() - mWebViewLoadStartMs));
Andy Huang632721e2012-04-11 16:57:26 -07001132
Andy Huang9d3fd922012-09-26 22:23:58 -07001133 ensureContentSizeChangeListener();
1134
mindyp3bcf1802012-09-09 11:17:00 -07001135 if (!mEnableContentReadySignal) {
Andy Huang7d4746e2012-10-17 17:03:17 -07001136 revealConversation();
mindyp3bcf1802012-09-09 11:17:00 -07001137 }
Andy Huang9d3fd922012-09-26 22:23:58 -07001138
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001139 final Set<String> emailAddresses = Sets.newHashSet();
Andy Huang543e7092013-04-22 11:44:56 -07001140 final List<Address> cacheCopy;
1141 synchronized (mAddressCache) {
1142 cacheCopy = ImmutableList.copyOf(mAddressCache.values());
1143 }
1144 for (Address addr : cacheCopy) {
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001145 emailAddresses.add(addr.getAddress());
Andy Huangb8331b42012-07-16 19:08:53 -07001146 }
Andrew Sapperstein4ddda2f2013-06-10 11:15:38 -07001147 final ContactLoaderCallbacks callbacks = getContactInfoSource();
1148 callbacks.setSenders(emailAddresses);
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001149 getLoaderManager().restartLoader(CONTACT_LOADER, Bundle.EMPTY, callbacks);
Andy Huang17a9cde2012-03-09 18:03:16 -08001150 }
1151
Andy Huangaf5d4e02012-03-19 19:02:12 -07001152 @Override
1153 public boolean shouldOverrideUrlLoading(WebView view, String url) {
Paul Westbrook542fec92012-09-18 14:47:51 -07001154 return mViewsCreated && super.shouldOverrideUrlLoading(view, url);
Andy Huangaf5d4e02012-03-19 19:02:12 -07001155 }
Andy Huang17a9cde2012-03-09 18:03:16 -08001156 }
1157
Andy Huangf70fc402012-02-17 15:37:42 -08001158 /**
1159 * NOTE: all public methods must be listed in the proguard flags so that they can be accessed
1160 * via reflection and not stripped.
1161 *
1162 */
1163 private class MailJsBridge {
Mindy Pereira974c9662012-09-14 10:02:08 -07001164 @JavascriptInterface
Andy Huangadbf3e82012-10-13 13:30:19 -07001165 public void onWebContentGeometryChange(final String[] overlayTopStrs,
1166 final String[] overlayBottomStrs) {
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -08001167 try {
1168 getHandler().post(new FragmentRunnable("onWebContentGeometryChange",
1169 ConversationViewFragment.this) {
1170 @Override
1171 public void go() {
Andy Huang46dfba62012-04-19 01:47:32 -07001172 if (!mViewsCreated) {
mindyp1b3cc472012-09-27 11:32:59 -07001173 LogUtils.d(LOG_TAG, "ignoring webContentGeometryChange because views"
1174 + " are gone, %s", ConversationViewFragment.this);
Andy Huang46dfba62012-04-19 01:47:32 -07001175 return;
1176 }
Andy Huangadbf3e82012-10-13 13:30:19 -07001177 mConversationContainer.onGeometryChange(
1178 parsePositions(overlayTopStrs, overlayBottomStrs));
mindyp1b3cc472012-09-27 11:32:59 -07001179 if (mDiff != 0) {
1180 // SCROLL!
1181 int scale = (int) (mWebView.getScale() / mWebView.getInitialScale());
1182 if (scale > 1) {
1183 mWebView.scrollBy(0, (mDiff * (scale - 1)));
1184 }
1185 mDiff = 0;
1186 }
Andy Huang46dfba62012-04-19 01:47:32 -07001187 }
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -08001188 });
1189 } catch (Throwable t) {
1190 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onWebContentGeometryChange");
1191 }
Andy Huang46dfba62012-04-19 01:47:32 -07001192 }
1193
Mindy Pereira974c9662012-09-14 10:02:08 -07001194 @JavascriptInterface
Andy Huang46dfba62012-04-19 01:47:32 -07001195 public String getTempMessageBodies() {
1196 try {
1197 if (!mViewsCreated) {
1198 return "";
Andy Huangf70fc402012-02-17 15:37:42 -08001199 }
Andy Huang46dfba62012-04-19 01:47:32 -07001200
1201 final String s = mTempBodiesHtml;
1202 mTempBodiesHtml = null;
1203 return s;
1204 } catch (Throwable t) {
1205 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getTempMessageBodies");
1206 return "";
1207 }
Andy Huangf70fc402012-02-17 15:37:42 -08001208 }
1209
Andy Huang014ea4c2012-09-25 14:50:54 -07001210 @JavascriptInterface
1211 public String getMessageBody(String domId) {
1212 try {
1213 final MessageCursor cursor = getMessageCursor();
1214 if (!mViewsCreated || cursor == null) {
1215 return "";
1216 }
1217
1218 int pos = -1;
1219 while (cursor.moveToPosition(++pos)) {
1220 final ConversationMessage msg = cursor.getMessage();
1221 if (TextUtils.equals(domId, mTemplates.getMessageDomId(msg))) {
1222 return msg.getBodyAsHtml();
1223 }
1224 }
1225
1226 return "";
1227
1228 } catch (Throwable t) {
1229 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getMessageBody");
1230 return "";
1231 }
1232 }
1233
Mindy Pereira974c9662012-09-14 10:02:08 -07001234 @JavascriptInterface
Andy Huang543e7092013-04-22 11:44:56 -07001235 public String getMessageSender(String domId) {
1236 try {
1237 final MessageCursor cursor = getMessageCursor();
1238 if (!mViewsCreated || cursor == null) {
1239 return "";
1240 }
1241
1242 int pos = -1;
1243 while (cursor.moveToPosition(++pos)) {
1244 final ConversationMessage msg = cursor.getMessage();
1245 if (TextUtils.equals(domId, mTemplates.getMessageDomId(msg))) {
1246 return getAddress(msg.getFrom()).getAddress();
1247 }
1248 }
1249
1250 return "";
1251
1252 } catch (Throwable t) {
1253 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getMessageSender");
1254 return "";
1255 }
1256 }
1257
Andy Huang543e7092013-04-22 11:44:56 -07001258 @JavascriptInterface
mindyp3bcf1802012-09-09 11:17:00 -07001259 public void onContentReady() {
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -08001260 try {
1261 getHandler().post(new FragmentRunnable("onContentReady",
1262 ConversationViewFragment.this) {
1263 @Override
1264 public void go() {
1265 try {
1266 if (mWebViewLoadStartMs != 0) {
1267 LogUtils.i(LOG_TAG, "IN CVF.onContentReady, f=%s vis=%s t=%sms",
1268 ConversationViewFragment.this,
1269 isUserVisible(),
1270 (SystemClock.uptimeMillis() - mWebViewLoadStartMs));
1271 }
1272 revealConversation();
1273 } catch (Throwable t) {
1274 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onContentReady");
1275 // Still try to show the conversation.
1276 revealConversation();
Andy Huang63b3c672012-10-05 19:27:28 -07001277 }
mindyp3bcf1802012-09-09 11:17:00 -07001278 }
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -08001279 });
1280 } catch (Throwable t) {
1281 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onContentReady");
1282 }
mindyp3bcf1802012-09-09 11:17:00 -07001283 }
Andy Huange964eee2012-10-02 19:24:58 -07001284
Andy Huange964eee2012-10-02 19:24:58 -07001285 @JavascriptInterface
1286 public float getScrollYPercent() {
1287 try {
1288 return mWebViewYPercent;
1289 } catch (Throwable t) {
1290 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getScrollYPercent");
1291 return 0f;
1292 }
1293 }
Andy Huang05c70c82013-03-14 15:15:50 -07001294
Andy Huang05c70c82013-03-14 15:15:50 -07001295 @JavascriptInterface
1296 public void onMessageTransform(String messageDomId, String transformText) {
Andrew Sappersteinae92e152013-05-03 13:55:18 -07001297 try {
1298 LogUtils.i(LOG_TAG, "TRANSFORM: (%s) %s", messageDomId, transformText);
1299 mMessageTransforms.put(messageDomId, transformText);
1300 onConversationTransformed();
1301 } catch (Throwable t) {
1302 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onMessageTransform");
Andrew Sapperstein8ec43e82013-12-17 18:27:55 -08001303 }
1304 }
1305
1306 @JavascriptInterface
1307 public void onInlineAttachmentsParsed(final String[] urls, final String[] messageIds) {
1308 try {
1309 getHandler().post(new FragmentRunnable("onInlineAttachmentsParsed",
1310 ConversationViewFragment.this) {
1311 @Override
1312 public void go() {
1313 try {
1314 for (int i = 0, size = urls.length; i < size; i++) {
1315 mUrlToMessageIdMap.put(urls[i], messageIds[i]);
1316 }
1317 } catch (ArrayIndexOutOfBoundsException e) {
1318 LogUtils.e(LOG_TAG, e,
1319 "Number of urls does not match number of message ids - %s:%s",
1320 urls.length, messageIds.length);
1321 }
1322 }
1323 });
1324 } catch (Throwable t) {
1325 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onInlineAttachmentsParsed");
Andrew Sappersteinae92e152013-05-03 13:55:18 -07001326 }
Andy Huang05c70c82013-03-14 15:15:50 -07001327 }
Andy Huangf70fc402012-02-17 15:37:42 -08001328 }
1329
Andy Huang47aa9c92012-07-31 15:37:21 -07001330 private class NewMessagesInfo {
1331 int count;
Andy Huang06c03622012-10-22 18:59:45 -07001332 int countFromSelf;
Andy Huang47aa9c92012-07-31 15:37:21 -07001333 String senderAddress;
1334
1335 /**
1336 * Return the display text for the new message notification overlay. It will be formatted
1337 * appropriately for a single new message vs. multiple new messages.
1338 *
1339 * @return display text
1340 */
1341 public String getNotificationText() {
mindypad0c30d2012-09-25 12:09:13 -07001342 Resources res = getResources();
Andy Huang47aa9c92012-07-31 15:37:21 -07001343 if (count > 1) {
Andrew Sapperstein66d69112013-08-23 12:24:44 -07001344 return res.getQuantityString(R.plurals.new_incoming_messages_many, count, count);
Andy Huang47aa9c92012-07-31 15:37:21 -07001345 } else {
Andy Huang16174812012-08-16 16:40:35 -07001346 final Address addr = getAddress(senderAddress);
mindypad0c30d2012-09-25 12:09:13 -07001347 return res.getString(R.string.new_incoming_messages_one,
Andrew Sapperstein3af481c2013-10-30 10:29:38 -07001348 sBidiFormatter.unicodeWrap(TextUtils.isEmpty(addr.getName())
1349 ? addr.getAddress() : addr.getName()));
Andy Huang47aa9c92012-07-31 15:37:21 -07001350 }
Andy Huang47aa9c92012-07-31 15:37:21 -07001351 }
1352 }
1353
mindypf4fce122012-09-14 15:55:33 -07001354 @Override
Paul Westbrookc42ad5e2013-05-09 16:52:15 -07001355 public void onMessageCursorLoadFinished(Loader<ObjectCursor<ConversationMessage>> loader,
1356 MessageCursor newCursor, MessageCursor oldCursor) {
mindypf4fce122012-09-14 15:55:33 -07001357 /*
1358 * what kind of changes affect the MessageCursor? 1. new message(s) 2.
1359 * read/unread state change 3. deleted message, either regular or draft
1360 * 4. updated message, either from self or from others, updated in
1361 * content or state or sender 5. star/unstar of message (technically
1362 * similar to #1) 6. other label change Use MessageCursor.hashCode() to
1363 * sort out interesting vs. no-op cursor updates.
1364 */
Andy Huangb8331b42012-07-16 19:08:53 -07001365
Andy Huang233d4352012-10-18 14:00:24 -07001366 if (oldCursor != null && !oldCursor.isClosed()) {
Andy Huang014ea4c2012-09-25 14:50:54 -07001367 final NewMessagesInfo info = getNewIncomingMessagesInfo(newCursor);
Andy Huangb8331b42012-07-16 19:08:53 -07001368
Andy Huang014ea4c2012-09-25 14:50:54 -07001369 if (info.count > 0) {
1370 // don't immediately render new incoming messages from other
1371 // senders
1372 // (to avoid a new message from losing the user's focus)
1373 LogUtils.i(LOG_TAG, "CONV RENDER: conversation updated"
Andy Huang9d3fd922012-09-26 22:23:58 -07001374 + ", holding cursor for new incoming message (%s)", this);
Andy Huang014ea4c2012-09-25 14:50:54 -07001375 showNewMessageNotification(info);
1376 return;
1377 }
1378
Andy Huang06c03622012-10-22 18:59:45 -07001379 final int oldState = oldCursor.getStateHashCode();
1380 final boolean changed = newCursor.getStateHashCode() != oldState;
Andy Huang233d4352012-10-18 14:00:24 -07001381
Andy Huang014ea4c2012-09-25 14:50:54 -07001382 if (!changed) {
1383 final boolean processedInPlace = processInPlaceUpdates(newCursor, oldCursor);
1384 if (processedInPlace) {
Andy Huang9d3fd922012-09-26 22:23:58 -07001385 LogUtils.i(LOG_TAG, "CONV RENDER: processed update(s) in place (%s)", this);
Andy Huang1ee96b22012-08-24 20:19:53 -07001386 } else {
mindypf4fce122012-09-14 15:55:33 -07001387 LogUtils.i(LOG_TAG, "CONV RENDER: uninteresting update"
Andy Huang9d3fd922012-09-26 22:23:58 -07001388 + ", ignoring this conversation update (%s)", this);
Andy Huang1ee96b22012-08-24 20:19:53 -07001389 }
Andy Huangb8331b42012-07-16 19:08:53 -07001390 return;
Andy Huang06c03622012-10-22 18:59:45 -07001391 } else if (info.countFromSelf == 1) {
1392 // Special-case the very common case of a new cursor that is the same as the old
1393 // one, except that there is a new message from yourself. This happens upon send.
1394 final boolean sameExceptNewLast = newCursor.getStateHashCode(1) == oldState;
1395 if (sameExceptNewLast) {
1396 LogUtils.i(LOG_TAG, "CONV RENDER: update is a single new message from self"
1397 + " (%s)", this);
1398 newCursor.moveToLast();
1399 processNewOutgoingMessage(newCursor.getMessage());
1400 return;
1401 }
Andy Huangb8331b42012-07-16 19:08:53 -07001402 }
Andy Huang6766b6e2012-09-28 12:43:52 -07001403 // cursors are different, and not due to an incoming message. fall
1404 // through and render.
1405 LogUtils.i(LOG_TAG, "CONV RENDER: conversation updated"
1406 + ", but not due to incoming message. rendering. (%s)", this);
Andy Huang06c03622012-10-22 18:59:45 -07001407
1408 if (DEBUG_DUMP_CURSOR_CONTENTS) {
1409 LogUtils.i(LOG_TAG, "old cursor: %s", oldCursor.getDebugDump());
1410 LogUtils.i(LOG_TAG, "new cursor: %s", newCursor.getDebugDump());
1411 }
Andy Huang6766b6e2012-09-28 12:43:52 -07001412 } else {
1413 LogUtils.i(LOG_TAG, "CONV RENDER: initial render. (%s)", this);
Andy Huang243c2362013-03-01 17:50:35 -08001414 timerMark("message cursor load finished");
Andy Huangb8331b42012-07-16 19:08:53 -07001415 }
1416
Andrew Sapperstein606dbd72013-07-30 19:14:23 -07001417 renderContent(newCursor);
1418 }
1419
1420 protected void renderContent(MessageCursor messageCursor) {
Mark Wei4071c2f2012-09-26 14:38:38 -07001421 // if layout hasn't happened, delay render
1422 // This is needed in addition to the showConversation() delay to speed
1423 // up rotation and restoration.
1424 if (mConversationContainer.getWidth() == 0) {
1425 mNeedRender = true;
1426 mConversationContainer.addOnLayoutChangeListener(this);
1427 } else {
Andrew Sapperstein606dbd72013-07-30 19:14:23 -07001428 renderConversation(messageCursor);
Mark Wei4071c2f2012-09-26 14:38:38 -07001429 }
Andy Huangb8331b42012-07-16 19:08:53 -07001430 }
1431
mindypf4fce122012-09-14 15:55:33 -07001432 private NewMessagesInfo getNewIncomingMessagesInfo(MessageCursor newCursor) {
1433 final NewMessagesInfo info = new NewMessagesInfo();
Andy Huangb8331b42012-07-16 19:08:53 -07001434
mindypf4fce122012-09-14 15:55:33 -07001435 int pos = -1;
1436 while (newCursor.moveToPosition(++pos)) {
1437 final Message m = newCursor.getMessage();
1438 if (!mViewState.contains(m)) {
1439 LogUtils.i(LOG_TAG, "conversation diff: found new msg: %s", m.uri);
Andy Huangb8331b42012-07-16 19:08:53 -07001440
Scott Kennedy8960f0a2012-11-07 15:35:50 -08001441 final Address from = getAddress(m.getFrom());
mindypf4fce122012-09-14 15:55:33 -07001442 // distinguish ours from theirs
1443 // new messages from the account owner should not trigger a
1444 // notification
1445 if (mAccount.ownsFromAddress(from.getAddress())) {
1446 LogUtils.i(LOG_TAG, "found message from self: %s", m.uri);
Andy Huang06c03622012-10-22 18:59:45 -07001447 info.countFromSelf++;
mindypf4fce122012-09-14 15:55:33 -07001448 continue;
1449 }
Andy Huangb8331b42012-07-16 19:08:53 -07001450
mindypf4fce122012-09-14 15:55:33 -07001451 info.count++;
Scott Kennedy8960f0a2012-11-07 15:35:50 -08001452 info.senderAddress = m.getFrom();
Andy Huangb8331b42012-07-16 19:08:53 -07001453 }
Andy Huangb8331b42012-07-16 19:08:53 -07001454 }
mindypf4fce122012-09-14 15:55:33 -07001455 return info;
Andy Huangb8331b42012-07-16 19:08:53 -07001456 }
1457
Andy Huang014ea4c2012-09-25 14:50:54 -07001458 private boolean processInPlaceUpdates(MessageCursor newCursor, MessageCursor oldCursor) {
1459 final Set<String> idsOfChangedBodies = Sets.newHashSet();
Andy Huang6b3d0d92012-10-30 15:46:48 -07001460 final List<Integer> changedOverlayPositions = Lists.newArrayList();
1461
Andy Huang014ea4c2012-09-25 14:50:54 -07001462 boolean changed = false;
1463
1464 int pos = 0;
1465 while (true) {
1466 if (!newCursor.moveToPosition(pos) || !oldCursor.moveToPosition(pos)) {
1467 break;
1468 }
1469
1470 final ConversationMessage newMsg = newCursor.getMessage();
1471 final ConversationMessage oldMsg = oldCursor.getMessage();
1472
Scott Kennedy8960f0a2012-11-07 15:35:50 -08001473 if (!TextUtils.equals(newMsg.getFrom(), oldMsg.getFrom()) ||
Andy Huang2a1e8e32012-10-23 18:54:57 -07001474 newMsg.isSending != oldMsg.isSending) {
Andy Huang6b3d0d92012-10-30 15:46:48 -07001475 mAdapter.updateItemsForMessage(newMsg, changedOverlayPositions);
Andy Huang2a1e8e32012-10-23 18:54:57 -07001476 LogUtils.i(LOG_TAG, "msg #%d (%d): detected from/sending change. isSending=%s",
1477 pos, newMsg.id, newMsg.isSending);
Andy Huang014ea4c2012-09-25 14:50:54 -07001478 }
1479
1480 // update changed message bodies in-place
1481 if (!TextUtils.equals(newMsg.bodyHtml, oldMsg.bodyHtml) ||
1482 !TextUtils.equals(newMsg.bodyText, oldMsg.bodyText)) {
1483 // maybe just set a flag to notify JS to re-request changed bodies
1484 idsOfChangedBodies.add('"' + mTemplates.getMessageDomId(newMsg) + '"');
1485 LogUtils.i(LOG_TAG, "msg #%d (%d): detected body change", pos, newMsg.id);
1486 }
1487
1488 pos++;
1489 }
1490
Andy Huang6b3d0d92012-10-30 15:46:48 -07001491
1492 if (!changedOverlayPositions.isEmpty()) {
Andy Huang06c03622012-10-22 18:59:45 -07001493 // notify once after the entire adapter is updated
Andy Huang6b3d0d92012-10-30 15:46:48 -07001494 mConversationContainer.onOverlayModelUpdate(changedOverlayPositions);
1495 changed = true;
Andy Huang06c03622012-10-22 18:59:45 -07001496 }
1497
Andy Huang014ea4c2012-09-25 14:50:54 -07001498 if (!idsOfChangedBodies.isEmpty()) {
1499 mWebView.loadUrl(String.format("javascript:replaceMessageBodies([%s]);",
1500 TextUtils.join(",", idsOfChangedBodies)));
1501 changed = true;
1502 }
1503
1504 return changed;
1505 }
1506
Andy Huang06c03622012-10-22 18:59:45 -07001507 private void processNewOutgoingMessage(ConversationMessage msg) {
Andrew Sapperstein99ee4562013-08-22 16:19:42 -07001508 // if there are items in the adapter and the last item is a border,
1509 // make the last border no longer be the last border
1510 if (mAdapter.getCount() > 0) {
1511 final ConversationOverlayItem item = mAdapter.getItem(mAdapter.getCount() - 1);
1512 if (item.getType() == ConversationViewAdapter.VIEW_TYPE_BORDER) {
1513 ((BorderItem) item).setIsLastBorder(false);
1514 }
1515 }
Andrew Sappersteincee3c902013-07-31 10:52:02 -07001516
Andy Huang06c03622012-10-22 18:59:45 -07001517 mTemplates.reset();
1518 // this method will add some items to mAdapter, but we deliberately want to avoid notifying
1519 // adapter listeners (i.e. ConversationContainer) until onWebContentGeometryChange is next
1520 // called, to prevent N+1 headers rendering with N message bodies.
Andrew Sappersteincee3c902013-07-31 10:52:02 -07001521
1522 // We can just call previousCollapsed false here since the border
1523 // above the message we're about to render should always show
1524 // (which it also will since the message being render is expanded).
1525 renderMessage(msg, false /* previousCollapsed */, true /* expanded */,
1526 msg.alwaysShowImages, false /* renderBorder */, false /* firstBorder */);
1527 renderBorder(true /* contiguous */, true /* expanded */,
1528 false /* firstBorder */, true /* lastBorder */);
Andy Huang06c03622012-10-22 18:59:45 -07001529 mTempBodiesHtml = mTemplates.emit();
1530
1531 mViewState.setExpansionState(msg, ExpansionState.EXPANDED);
1532 // FIXME: should the provider set this as initial state?
1533 mViewState.setReadState(msg, false /* read */);
1534
Andy Huang91d782a2012-10-25 12:37:29 -07001535 // From now until the updated spacer geometry is returned, the adapter items are mismatched
1536 // with the existing spacers. Do not let them layout.
1537 mConversationContainer.invalidateSpacerGeometry();
1538
Andy Huang06c03622012-10-22 18:59:45 -07001539 mWebView.loadUrl("javascript:appendMessageHtml();");
1540 }
1541
Paul Westbrookcebcc642012-08-08 10:06:04 -07001542 private class SetCookieTask extends AsyncTask<Void, Void, Void> {
1543 final String mUri;
Paul Westbrookb8361c92012-09-27 10:57:14 -07001544 final Uri mAccountCookieQueryUri;
1545 final ContentResolver mResolver;
Paul Westbrookcebcc642012-08-08 10:06:04 -07001546
Paul Westbrookb8361c92012-09-27 10:57:14 -07001547 SetCookieTask(Context context, Uri baseUri, Uri accountCookieQueryUri) {
1548 mUri = baseUri.toString();
1549 mAccountCookieQueryUri = accountCookieQueryUri;
1550 mResolver = context.getContentResolver();
Paul Westbrookcebcc642012-08-08 10:06:04 -07001551 }
1552
1553 @Override
1554 public Void doInBackground(Void... args) {
Paul Westbrookb8361c92012-09-27 10:57:14 -07001555 // First query for the coookie string from the UI provider
1556 final Cursor cookieCursor = mResolver.query(mAccountCookieQueryUri,
1557 UIProvider.ACCOUNT_COOKIE_PROJECTION, null, null, null);
1558 if (cookieCursor == null) {
1559 return null;
1560 }
1561
1562 try {
1563 if (cookieCursor.moveToFirst()) {
1564 final String cookie = cookieCursor.getString(
1565 cookieCursor.getColumnIndex(UIProvider.AccountCookieColumns.COOKIE));
1566
1567 if (cookie != null) {
1568 final CookieSyncManager csm =
1569 CookieSyncManager.createInstance(getContext());
1570 CookieManager.getInstance().setCookie(mUri, cookie);
1571 csm.sync();
1572 }
1573 }
1574
1575 } finally {
1576 cookieCursor.close();
1577 }
1578
1579
Paul Westbrookcebcc642012-08-08 10:06:04 -07001580 return null;
1581 }
1582 }
mindyp36280f32012-09-09 16:11:23 -07001583
mindyp26d4d2d2012-09-18 17:30:32 -07001584 @Override
mindyp36280f32012-09-09 16:11:23 -07001585 public void onConversationUpdated(Conversation conv) {
1586 final ConversationViewHeader headerView = (ConversationViewHeader) mConversationContainer
1587 .findViewById(R.id.conversation_header);
mindypb2b98ba2012-09-24 14:13:58 -07001588 mConversation = conv;
mindyp9e0b2362012-09-09 16:31:21 -07001589 if (headerView != null) {
1590 headerView.onConversationUpdated(conv);
Vikram Aggarwal51ad9042013-01-17 13:18:09 -08001591 headerView.setSubject(conv.subject);
mindyp9e0b2362012-09-09 16:31:21 -07001592 }
mindyp36280f32012-09-09 16:11:23 -07001593 }
Mark Wei4071c2f2012-09-26 14:38:38 -07001594
1595 @Override
1596 public void onLayoutChange(View v, int left, int top, int right,
1597 int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
1598 boolean sizeChanged = mNeedRender
1599 && mConversationContainer.getWidth() != 0;
1600 if (sizeChanged) {
1601 mNeedRender = false;
1602 mConversationContainer.removeOnLayoutChangeListener(this);
1603 renderConversation(getMessageCursor());
1604 }
1605 }
mindyp1b3cc472012-09-27 11:32:59 -07001606
1607 @Override
1608 public void setMessageDetailsExpanded(MessageHeaderItem i, boolean expanded,
1609 int heightBefore) {
1610 mDiff = (expanded ? 1 : -1) * Math.abs(i.getHeight() - heightBefore);
1611 }
Andy Huang02f9d182012-11-28 22:38:02 -08001612
Andrew Sapperstein5c1692a2013-09-16 11:56:13 -07001613 protected void printConversation() {
Andrew Sapperstein234d3532013-10-29 14:54:04 -07001614 PrintUtils.printConversation(mActivity.getActivityContext(), getMessageCursor(),
1615 mAddressCache, mConversation.getBaseUri(mBaseUri), true /* useJavascript */);
Andrew Sapperstein5c1692a2013-09-16 11:56:13 -07001616 }
Mindy Pereira9b875682012-02-15 18:10:54 -08001617}