blob: 54bc8f4689df5e827c326d58b0e55608c69d7ca4 [file] [log] [blame]
Mindy Pereira9b875682012-02-15 18:10:54 -08001/*
2 * Copyright (C) 2012 Google Inc.
3 * Licensed to The Android Open Source Project.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package com.android.mail.ui;
19
mindypf4fce122012-09-14 15:55:33 -070020
Paul Westbrookb8361c92012-09-27 10:57:14 -070021import android.content.ContentResolver;
Mindy Pereira9b875682012-02-15 18:10:54 -080022import android.content.Context;
Mindy Pereira8e915722012-02-16 14:42:56 -080023import android.content.Loader;
mindypad0c30d2012-09-25 12:09:13 -070024import android.content.res.Resources;
Mindy Pereira9b875682012-02-15 18:10:54 -080025import android.database.Cursor;
Andy Huang9d3fd922012-09-26 22:23:58 -070026import android.database.DataSetObserver;
Paul Westbrookb8361c92012-09-27 10:57:14 -070027import android.net.Uri;
Paul Westbrookcebcc642012-08-08 10:06:04 -070028import android.os.AsyncTask;
Mindy Pereira9b875682012-02-15 18:10:54 -080029import android.os.Bundle;
mindyp3bcf1802012-09-09 11:17:00 -070030import android.os.SystemClock;
Andy Huang47aa9c92012-07-31 15:37:21 -070031import android.text.TextUtils;
Mindy Pereira9b875682012-02-15 18:10:54 -080032import android.view.LayoutInflater;
33import android.view.View;
Mark Wei4071c2f2012-09-26 14:38:38 -070034import android.view.View.OnLayoutChangeListener;
Mindy Pereira9b875682012-02-15 18:10:54 -080035import android.view.ViewGroup;
Andy Huangf70fc402012-02-17 15:37:42 -080036import android.webkit.ConsoleMessage;
Paul Westbrookcebcc642012-08-08 10:06:04 -070037import android.webkit.CookieManager;
38import android.webkit.CookieSyncManager;
Mindy Pereira974c9662012-09-14 10:02:08 -070039import android.webkit.JavascriptInterface;
Andy Huangf70fc402012-02-17 15:37:42 -080040import android.webkit.WebChromeClient;
41import android.webkit.WebSettings;
Andy Huang17a9cde2012-03-09 18:03:16 -080042import android.webkit.WebView;
43import android.webkit.WebViewClient;
Andy Huang47aa9c92012-07-31 15:37:21 -070044import android.widget.TextView;
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 Huang5ff63742012-03-16 20:30:23 -070048import com.android.mail.browse.ConversationContainer;
Andy Huangadbf3e82012-10-13 13:30:19 -070049import com.android.mail.browse.ConversationContainer.OverlayPosition;
Andy Huang46dfba62012-04-19 01:47:32 -070050import com.android.mail.browse.ConversationOverlayItem;
Andy Huang7bdc3752012-03-25 17:18:19 -070051import com.android.mail.browse.ConversationViewAdapter;
Andy Huang28b7aee2012-08-20 20:27:32 -070052import com.android.mail.browse.ConversationViewAdapter.ConversationAccountController;
Andy Huang46dfba62012-04-19 01:47:32 -070053import com.android.mail.browse.ConversationViewAdapter.MessageFooterItem;
Andy Huang7bdc3752012-03-25 17:18:19 -070054import com.android.mail.browse.ConversationViewAdapter.MessageHeaderItem;
Andy Huang46dfba62012-04-19 01:47:32 -070055import com.android.mail.browse.ConversationViewAdapter.SuperCollapsedBlockItem;
Andy Huang5ff63742012-03-16 20:30:23 -070056import com.android.mail.browse.ConversationViewHeader;
57import com.android.mail.browse.ConversationWebView;
mindypdde3f9f2012-09-10 17:35:35 -070058import com.android.mail.browse.ConversationWebView.ContentSizeChangeListener;
Andy Huang7bdc3752012-03-25 17:18:19 -070059import com.android.mail.browse.MessageCursor;
Andy Huangcd5c5ee2012-08-12 19:03:51 -070060import com.android.mail.browse.MessageCursor.ConversationController;
Andy Huang28b7aee2012-08-20 20:27:32 -070061import com.android.mail.browse.MessageCursor.ConversationMessage;
Andy Huang59e0b182012-08-14 14:32:23 -070062import com.android.mail.browse.MessageHeaderView;
Andy Huang3233bff2012-03-20 19:38:45 -070063import com.android.mail.browse.MessageHeaderView.MessageHeaderViewCallbacks;
Andy Huangadbf3e82012-10-13 13:30:19 -070064import com.android.mail.browse.ScrollIndicatorsView;
Andy Huang46dfba62012-04-19 01:47:32 -070065import com.android.mail.browse.SuperCollapsedBlock;
Andy Huang0b7ed6f2012-07-25 19:23:26 -070066import com.android.mail.browse.WebViewContextMenu;
Mindy Pereira9b875682012-02-15 18:10:54 -080067import com.android.mail.providers.Account;
Andy Huang65fe28f2012-04-06 18:08:53 -070068import com.android.mail.providers.Address;
Mindy Pereira9b875682012-02-15 18:10:54 -080069import com.android.mail.providers.Conversation;
Andy Huangf70fc402012-02-17 15:37:42 -080070import com.android.mail.providers.Message;
Paul Westbrookb8361c92012-09-27 10:57:14 -070071import com.android.mail.providers.UIProvider;
Andy Huangcd5c5ee2012-08-12 19:03:51 -070072import com.android.mail.ui.ConversationViewState.ExpansionState;
Paul Westbrookb334c902012-06-25 11:42:46 -070073import com.android.mail.utils.LogTag;
Mindy Pereira9b875682012-02-15 18:10:54 -080074import com.android.mail.utils.LogUtils;
Andy Huang2e9acfe2012-03-15 22:39:36 -070075import com.android.mail.utils.Utils;
Andy Huang46dfba62012-04-19 01:47:32 -070076import com.google.common.collect.Lists;
Andy Huangb8331b42012-07-16 19:08:53 -070077import com.google.common.collect.Sets;
Andy Huang65fe28f2012-04-06 18:08:53 -070078
Andy Huang46dfba62012-04-19 01:47:32 -070079import java.util.List;
Andy Huangb8331b42012-07-16 19:08:53 -070080import java.util.Set;
Mindy Pereira9b875682012-02-15 18:10:54 -080081
Andy Huangf70fc402012-02-17 15:37:42 -080082
Mindy Pereira9b875682012-02-15 18:10:54 -080083/**
84 * The conversation view UI component.
85 */
mindypf4fce122012-09-14 15:55:33 -070086public final class ConversationViewFragment extends AbstractConversationViewFragment implements
Andy Huang46dfba62012-04-19 01:47:32 -070087 MessageHeaderViewCallbacks,
Andy Huangcd5c5ee2012-08-12 19:03:51 -070088 SuperCollapsedBlock.OnClickListener,
Andy Huang28b7aee2012-08-20 20:27:32 -070089 ConversationController,
Mark Wei4071c2f2012-09-26 14:38:38 -070090 ConversationAccountController,
91 OnLayoutChangeListener {
Mindy Pereira8e915722012-02-16 14:42:56 -080092
Paul Westbrookb334c902012-06-25 11:42:46 -070093 private static final String LOG_TAG = LogTag.getLogTag();
Andy Huang632721e2012-04-11 16:57:26 -070094 public static final String LAYOUT_TAG = "ConvLayout";
Mindy Pereira9b875682012-02-15 18:10:54 -080095
Andy Huang9d3fd922012-09-26 22:23:58 -070096 /**
mindyp1b3cc472012-09-27 11:32:59 -070097 * Difference in the height of the message header whose details have been expanded/collapsed
98 */
99 private int mDiff = 0;
100
101 /**
Andy Huang9d3fd922012-09-26 22:23:58 -0700102 * Default value for {@link #mLoadWaitReason}. Conversation load will happen immediately.
103 */
104 private final int LOAD_NOW = 0;
105 /**
106 * Value for {@link #mLoadWaitReason} that means we are offscreen and waiting for the visible
107 * conversation to finish loading before beginning our load.
108 * <p>
109 * When this value is set, the fragment should register with {@link ConversationListCallbacks}
110 * to know when the visible conversation is loaded. When it is unset, it should unregister.
111 */
112 private final int LOAD_WAIT_FOR_INITIAL_CONVERSATION = 1;
113 /**
114 * Value for {@link #mLoadWaitReason} used when a conversation is too heavyweight to load at
115 * all when not visible (e.g. requires network fetch, or too complex). Conversation load will
116 * wait until this fragment is visible.
117 */
118 private final int LOAD_WAIT_UNTIL_VISIBLE = 2;
mindyp3bcf1802012-09-09 11:17:00 -0700119
Andy Huangf70fc402012-02-17 15:37:42 -0800120 private ConversationContainer mConversationContainer;
Mindy Pereira9b875682012-02-15 18:10:54 -0800121
Andy Huangf70fc402012-02-17 15:37:42 -0800122 private ConversationWebView mWebView;
Mindy Pereira9b875682012-02-15 18:10:54 -0800123
Mark Wei56d83852012-09-19 14:28:50 -0700124 private ScrollIndicatorsView mScrollIndicators;
125
Andy Huang47aa9c92012-07-31 15:37:21 -0700126 private View mNewMessageBar;
127
Andy Huangf70fc402012-02-17 15:37:42 -0800128 private HtmlConversationTemplates mTemplates;
129
Andy Huangf70fc402012-02-17 15:37:42 -0800130 private final MailJsBridge mJsBridge = new MailJsBridge();
131
Andy Huang17a9cde2012-03-09 18:03:16 -0800132 private final WebViewClient mWebViewClient = new ConversationWebViewClient();
133
Andy Huang7bdc3752012-03-25 17:18:19 -0700134 private ConversationViewAdapter mAdapter;
Andy Huang51067132012-03-12 20:08:19 -0700135
136 private boolean mViewsCreated;
Mark Wei4071c2f2012-09-26 14:38:38 -0700137 // True if we attempted to render before the views were laid out
138 // We will render immediately once layout is done
139 private boolean mNeedRender;
Andy Huang51067132012-03-12 20:08:19 -0700140
Andy Huang46dfba62012-04-19 01:47:32 -0700141 /**
142 * Temporary string containing the message bodies of the messages within a super-collapsed
143 * block, for one-time use during block expansion. We cannot easily pass the body HTML
144 * into JS without problematic escaping, so hold onto it momentarily and signal JS to fetch it
145 * using {@link MailJsBridge}.
146 */
147 private String mTempBodiesHtml;
148
Andy Huang632721e2012-04-11 16:57:26 -0700149 private int mMaxAutoLoadMessages;
150
Andy Huang9d3fd922012-09-26 22:23:58 -0700151 /**
152 * If this conversation fragment is not visible, and it's inappropriate to load up front,
153 * this is the reason we are waiting. This flag should be cleared once it's okay to load
154 * the conversation.
155 */
156 private int mLoadWaitReason = LOAD_NOW;
Andy Huang632721e2012-04-11 16:57:26 -0700157
mindyp3bcf1802012-09-09 11:17:00 -0700158 private boolean mEnableContentReadySignal;
Andy Huang28b7aee2012-08-20 20:27:32 -0700159
mindypdde3f9f2012-09-10 17:35:35 -0700160 private ContentSizeChangeListener mWebViewSizeChangeListener;
161
Andy Huange964eee2012-10-02 19:24:58 -0700162 private float mWebViewYPercent;
163
164 /**
165 * Has loadData been called on the WebView yet?
166 */
167 private boolean mWebViewLoadedData;
168
Andy Huang63b3c672012-10-05 19:27:28 -0700169 private long mWebViewLoadStartMs;
170
Andy Huang9d3fd922012-09-26 22:23:58 -0700171 private final DataSetObserver mLoadedObserver = new DataSetObserver() {
172 @Override
173 public void onChanged() {
174 getHandler().post(new FragmentRunnable("delayedConversationLoad") {
175 @Override
176 public void go() {
177 LogUtils.d(LOG_TAG, "CVF load observer fired, this=%s",
178 ConversationViewFragment.this);
179 handleDelayedConversationLoad();
180 }
181 });
182 }
183 };
Andy Huangf70fc402012-02-17 15:37:42 -0800184
Andy Huang30bcfe72012-10-18 18:09:03 -0700185 private final Runnable mOnProgressDismiss = new FragmentRunnable("onProgressDismiss") {
Andy Huang7d4746e2012-10-17 17:03:17 -0700186 @Override
187 public void go() {
188 if (isUserVisible()) {
189 onConversationSeen();
190 }
Andy Huang30bcfe72012-10-18 18:09:03 -0700191 mWebView.onRenderComplete();
Andy Huang7d4746e2012-10-17 17:03:17 -0700192 }
193 };
194
Andy Huangbd544e32012-05-29 15:56:51 -0700195 private static final boolean DEBUG_DUMP_CONVERSATION_HTML = false;
Andy Huang47aa9c92012-07-31 15:37:21 -0700196 private static final boolean DISABLE_OFFSCREEN_LOADING = false;
Andy Huang06c03622012-10-22 18:59:45 -0700197 private static final boolean DEBUG_DUMP_CURSOR_CONTENTS = false;
Andy Huange964eee2012-10-02 19:24:58 -0700198
199 private static final String BUNDLE_KEY_WEBVIEW_Y_PERCENT =
200 ConversationViewFragment.class.getName() + "webview-y-percent";
Andy Huangbd544e32012-05-29 15:56:51 -0700201
Vikram Aggarwal6c511582012-02-27 10:59:47 -0800202 /**
203 * Constructor needs to be public to handle orientation changes and activity lifecycle events.
204 */
Andy Huangf70fc402012-02-17 15:37:42 -0800205 public ConversationViewFragment() {
Vikram Aggarwal6c511582012-02-27 10:59:47 -0800206 super();
Mindy Pereira9b875682012-02-15 18:10:54 -0800207 }
208
209 /**
210 * Creates a new instance of {@link ConversationViewFragment}, initialized
Andy Huang632721e2012-04-11 16:57:26 -0700211 * to display a conversation with other parameters inherited/copied from an existing bundle,
212 * typically one created using {@link #makeBasicArgs}.
213 */
214 public static ConversationViewFragment newInstance(Bundle existingArgs,
215 Conversation conversation) {
216 ConversationViewFragment f = new ConversationViewFragment();
217 Bundle args = new Bundle(existingArgs);
218 args.putParcelable(ARG_CONVERSATION, conversation);
219 f.setArguments(args);
220 return f;
221 }
222
mindypf4fce122012-09-14 15:55:33 -0700223 @Override
Andy Huangadbf3e82012-10-13 13:30:19 -0700224 public void onAccountChanged(Account newAccount, Account oldAccount) {
225 // if overview mode has changed, re-render completely (no need to also update headers)
226 if (isOverviewMode(newAccount) != isOverviewMode(oldAccount)) {
227 setupOverviewMode();
228 final MessageCursor c = getMessageCursor();
229 if (c != null) {
230 renderConversation(c);
231 } else {
232 // Null cursor means this fragment is either waiting to load or in the middle of
233 // loading. Either way, a future render will happen anyway, and the new setting
234 // will take effect when that happens.
235 }
236 return;
237 }
238
mindypf4fce122012-09-14 15:55:33 -0700239 // settings may have been updated; refresh views that are known to
240 // depend on settings
mindypf4fce122012-09-14 15:55:33 -0700241 mAdapter.notifyDataSetChanged();
Andy Huang632721e2012-04-11 16:57:26 -0700242 }
243
Mindy Pereira9b875682012-02-15 18:10:54 -0800244 @Override
245 public void onActivityCreated(Bundle savedInstanceState) {
Andy Huang9d3fd922012-09-26 22:23:58 -0700246 LogUtils.d(LOG_TAG, "IN CVF.onActivityCreated, this=%s visible=%s", this, isUserVisible());
Mindy Pereira9b875682012-02-15 18:10:54 -0800247 super.onActivityCreated(savedInstanceState);
Mark Wei1abfcaf2012-09-27 11:11:07 -0700248
249 if (mActivity == null || mActivity.isFinishing()) {
250 // Activity is finishing, just bail.
251 return;
252 }
253
mindypf4fce122012-09-14 15:55:33 -0700254 Context context = getContext();
255 mTemplates = new HtmlConversationTemplates(context);
Andy Huang59e0b182012-08-14 14:32:23 -0700256
mindypf4fce122012-09-14 15:55:33 -0700257 final FormattedDateBuilder dateBuilder = new FormattedDateBuilder(context);
Andy Huang59e0b182012-08-14 14:32:23 -0700258
Paul Westbrook8081df42012-09-10 15:43:36 -0700259 mAdapter = new ConversationViewAdapter(mActivity, this,
mindypf4fce122012-09-14 15:55:33 -0700260 getLoaderManager(), this, getContactInfoSource(), this,
Paul Westbrook8081df42012-09-10 15:43:36 -0700261 this, mAddressCache, dateBuilder);
Andy Huang51067132012-03-12 20:08:19 -0700262 mConversationContainer.setOverlayAdapter(mAdapter);
263
Andy Huang59e0b182012-08-14 14:32:23 -0700264 // set up snap header (the adapter usually does this with the other ones)
265 final MessageHeaderView snapHeader = mConversationContainer.getSnapHeader();
Andy Huang28b7aee2012-08-20 20:27:32 -0700266 snapHeader.initialize(dateBuilder, this, mAddressCache);
Andy Huang59e0b182012-08-14 14:32:23 -0700267 snapHeader.setCallbacks(this);
mindypf4fce122012-09-14 15:55:33 -0700268 snapHeader.setContactInfoSource(getContactInfoSource());
Andy Huang59e0b182012-08-14 14:32:23 -0700269
Andy Huang632721e2012-04-11 16:57:26 -0700270 mMaxAutoLoadMessages = getResources().getInteger(R.integer.max_auto_load_messages);
271
mindypf4fce122012-09-14 15:55:33 -0700272 mWebView.setOnCreateContextMenuListener(new WebViewContextMenu(getActivity()));
Andy Huang0b7ed6f2012-07-25 19:23:26 -0700273
Andy Huangadbf3e82012-10-13 13:30:19 -0700274 // set this up here instead of onCreateView to ensure the latest Account is loaded
275 setupOverviewMode();
276
Andy Huang9d3fd922012-09-26 22:23:58 -0700277 // Defer the call to initLoader with a Handler.
278 // We want to wait until we know which fragments are present and their final visibility
279 // states before going off and doing work. This prevents extraneous loading from occurring
280 // as the ViewPager shifts about before the initial position is set.
281 //
282 // e.g. click on item #10
283 // ViewPager.setAdapter() actually first loads #0 and #1 under the assumption that #0 is
284 // the initial primary item
285 // Then CPC immediately sets the primary item to #10, which tears down #0/#1 and sets up
286 // #9/#10/#11.
287 getHandler().post(new FragmentRunnable("showConversation") {
288 @Override
289 public void go() {
290 showConversation();
291 }
292 });
Paul Westbrookcebcc642012-08-08 10:06:04 -0700293
294 if (mConversation.conversationBaseUri != null &&
Paul Westbrookb8361c92012-09-27 10:57:14 -0700295 !Utils.isEmpty(mAccount.accoutCookieQueryUri)) {
Paul Westbrookcebcc642012-08-08 10:06:04 -0700296 // Set the cookie for this base url
Paul Westbrookb8361c92012-09-27 10:57:14 -0700297 new SetCookieTask(getContext(), mConversation.conversationBaseUri,
298 mAccount.accoutCookieQueryUri).execute();
Paul Westbrookcebcc642012-08-08 10:06:04 -0700299 }
Mindy Pereira9b875682012-02-15 18:10:54 -0800300 }
301
Mindy Pereira9b875682012-02-15 18:10:54 -0800302 @Override
Andy Huange964eee2012-10-02 19:24:58 -0700303 public void onCreate(Bundle savedState) {
304 super.onCreate(savedState);
305
306 if (savedState != null) {
307 mWebViewYPercent = savedState.getFloat(BUNDLE_KEY_WEBVIEW_Y_PERCENT);
308 }
309 }
310
311 @Override
Mindy Pereira9b875682012-02-15 18:10:54 -0800312 public View onCreateView(LayoutInflater inflater,
313 ViewGroup container, Bundle savedInstanceState) {
Andy Huang839ada22012-07-20 15:48:40 -0700314
Andy Huang632721e2012-04-11 16:57:26 -0700315 View rootView = inflater.inflate(R.layout.conversation_view, container, false);
Andy Huangf70fc402012-02-17 15:37:42 -0800316 mConversationContainer = (ConversationContainer) rootView
317 .findViewById(R.id.conversation_container);
Andy Huang47aa9c92012-07-31 15:37:21 -0700318
319 mNewMessageBar = mConversationContainer.findViewById(R.id.new_message_notification_bar);
320 mNewMessageBar.setOnClickListener(new View.OnClickListener() {
321 @Override
322 public void onClick(View v) {
323 onNewMessageBarClick();
324 }
325 });
326
mindypff282d02012-09-17 10:33:02 -0700327 instantiateProgressIndicators(rootView);
mindyp3bcf1802012-09-09 11:17:00 -0700328
Andy Huang5ff63742012-03-16 20:30:23 -0700329 mWebView = (ConversationWebView) mConversationContainer.findViewById(R.id.webview);
Andy Huangf70fc402012-02-17 15:37:42 -0800330
Andy Huangf70fc402012-02-17 15:37:42 -0800331 mWebView.addJavascriptInterface(mJsBridge, "mail");
mindyp3bcf1802012-09-09 11:17:00 -0700332 // On JB or newer, we use the 'webkitAnimationStart' DOM event to signal load complete
333 // Below JB, try to speed up initial render by having the webview do supplemental draws to
334 // custom a software canvas.
mindypb941fdb2012-09-11 08:28:23 -0700335 // TODO(mindyp):
336 //PAGE READINESS SIGNAL FOR JELLYBEAN AND NEWER
337 // Notify the app on 'webkitAnimationStart' of a simple dummy element with a simple no-op
338 // animation that immediately runs on page load. The app uses this as a signal that the
339 // content is loaded and ready to draw, since WebView delays firing this event until the
340 // layers are composited and everything is ready to draw.
341 // This signal does not seem to be reliable, so just use the old method for now.
mindyp32d911f2012-09-24 15:14:22 -0700342 mEnableContentReadySignal = Utils.isRunningJellybeanOrLater();
mindypafc9b362012-09-25 09:20:47 -0700343 mWebView.setUseSoftwareLayer(!mEnableContentReadySignal);
Andy Huang30bcfe72012-10-18 18:09:03 -0700344 mWebView.onUserVisibilityChanged(isUserVisible());
Andy Huang17a9cde2012-03-09 18:03:16 -0800345 mWebView.setWebViewClient(mWebViewClient);
Andy Huangf70fc402012-02-17 15:37:42 -0800346 mWebView.setWebChromeClient(new WebChromeClient() {
347 @Override
348 public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
349 LogUtils.i(LOG_TAG, "JS: %s (%s:%d)", consoleMessage.message(),
350 consoleMessage.sourceId(), consoleMessage.lineNumber());
351 return true;
352 }
353 });
354
Andy Huang3233bff2012-03-20 19:38:45 -0700355 final WebSettings settings = mWebView.getSettings();
Andy Huangf70fc402012-02-17 15:37:42 -0800356
Mark Wei56d83852012-09-19 14:28:50 -0700357 mScrollIndicators = (ScrollIndicatorsView) rootView.findViewById(R.id.scroll_indicators);
358 mScrollIndicators.setSourceView(mWebView);
359
Andy Huangf70fc402012-02-17 15:37:42 -0800360 settings.setJavaScriptEnabled(true);
Andy Huangf70fc402012-02-17 15:37:42 -0800361
Andy Huangc319b552012-04-25 19:53:50 -0700362 final float fontScale = getResources().getConfiguration().fontScale;
Andy Huangba283732012-06-25 19:14:10 -0700363 final int desiredFontSizePx = getResources()
364 .getInteger(R.integer.conversation_desired_font_size_px);
365 final int unstyledFontSizePx = getResources()
366 .getInteger(R.integer.conversation_unstyled_font_size_px);
Andy Huangc319b552012-04-25 19:53:50 -0700367
Andy Huangba283732012-06-25 19:14:10 -0700368 int textZoom = settings.getTextZoom();
369 // apply a correction to the default body text style to get regular text to the size we want
370 textZoom = textZoom * desiredFontSizePx / unstyledFontSizePx;
371 // then apply any system font scaling
Andy Huangc319b552012-04-25 19:53:50 -0700372 textZoom = (int) (textZoom * fontScale);
373 settings.setTextZoom(textZoom);
374
Andy Huang51067132012-03-12 20:08:19 -0700375 mViewsCreated = true;
Andy Huange964eee2012-10-02 19:24:58 -0700376 mWebViewLoadedData = false;
Andy Huang51067132012-03-12 20:08:19 -0700377
Mindy Pereira9b875682012-02-15 18:10:54 -0800378 return rootView;
379 }
380
381 @Override
382 public void onDestroyView() {
Mindy Pereira9b875682012-02-15 18:10:54 -0800383 super.onDestroyView();
Andy Huang46dfba62012-04-19 01:47:32 -0700384 mConversationContainer.setOverlayAdapter(null);
385 mAdapter = null;
Andy Huang9d3fd922012-09-26 22:23:58 -0700386 resetLoadWaiting(); // be sure to unregister any active load observer
Andy Huang51067132012-03-12 20:08:19 -0700387 mViewsCreated = false;
Mindy Pereira9b875682012-02-15 18:10:54 -0800388 }
389
Andy Huange964eee2012-10-02 19:24:58 -0700390 @Override
391 public void onSaveInstanceState(Bundle outState) {
392 super.onSaveInstanceState(outState);
393
394 outState.putFloat(BUNDLE_KEY_WEBVIEW_Y_PERCENT, calculateScrollYPercent());
395 }
396
397 private float calculateScrollYPercent() {
398 float p;
399 int scrollY = mWebView.getScrollY();
400 int viewH = mWebView.getHeight();
401 int webH = (int) (mWebView.getContentHeight() * mWebView.getScale());
402
403 if (webH == 0 || webH <= viewH) {
404 p = 0;
405 } else if (scrollY + viewH >= webH) {
406 // The very bottom is a special case, it acts as a stronger anchor than the scroll top
407 // at that point.
408 p = 1.0f;
409 } else {
410 p = (float) scrollY / webH;
411 }
412 return p;
413 }
414
Andy Huang9d3fd922012-09-26 22:23:58 -0700415 private void resetLoadWaiting() {
416 if (mLoadWaitReason == LOAD_WAIT_FOR_INITIAL_CONVERSATION) {
417 getListController().unregisterConversationLoadedObserver(mLoadedObserver);
418 }
419 mLoadWaitReason = LOAD_NOW;
420 }
421
Andy Huang5ff63742012-03-16 20:30:23 -0700422 @Override
mindypf4fce122012-09-14 15:55:33 -0700423 protected void markUnread() {
Andy Huang839ada22012-07-20 15:48:40 -0700424 // Ignore unsafe calls made after a fragment is detached from an activity
425 final ControllableActivity activity = (ControllableActivity) getActivity();
426 if (activity == null) {
427 LogUtils.w(LOG_TAG, "ignoring markUnread for conv=%s", mConversation.id);
428 return;
429 }
430
Andy Huang28e31e22012-07-26 16:33:15 -0700431 if (mViewState == null) {
432 LogUtils.i(LOG_TAG, "ignoring markUnread for conv with no view state (%d)",
433 mConversation.id);
434 return;
435 }
Andy Huang839ada22012-07-20 15:48:40 -0700436 activity.getConversationUpdater().markConversationMessagesUnread(mConversation,
Vikram Aggarwal4a878b62012-07-31 15:09:25 -0700437 mViewState.getUnreadMessageUris(), mViewState.getConversationInfo());
Andy Huang839ada22012-07-20 15:48:40 -0700438 }
439
mindypf4fce122012-09-14 15:55:33 -0700440 @Override
441 public void onUserVisibleHintChanged() {
Andy Huang9d3fd922012-09-26 22:23:58 -0700442 final boolean userVisible = isUserVisible();
443
444 if (!userVisible) {
mindyp32d911f2012-09-24 15:14:22 -0700445 dismissLoadingStatus();
Andy Huang9d3fd922012-09-26 22:23:58 -0700446 } else if (mViewsCreated) {
447 if (getMessageCursor() != null) {
448 LogUtils.d(LOG_TAG, "Fragment is now user-visible, onConversationSeen: %s", this);
449 onConversationSeen();
450 } else if (isLoadWaiting()) {
451 LogUtils.d(LOG_TAG, "Fragment is now user-visible, showing conversation: %s", this);
452 handleDelayedConversationLoad();
453 }
Andy Huang632721e2012-04-11 16:57:26 -0700454 }
Andy Huang632721e2012-04-11 16:57:26 -0700455
Andy Huang30bcfe72012-10-18 18:09:03 -0700456 if (mWebView != null) {
457 mWebView.onUserVisibilityChanged(userVisible);
458 }
Andy Huangf8cf5462012-10-17 18:29:14 -0700459 }
460
Andy Huang9d3fd922012-09-26 22:23:58 -0700461 /**
462 * Will either call initLoader now to begin loading, or set {@link #mLoadWaitReason} and do
463 * nothing (in which case you should later call {@link #handleDelayedConversationLoad()}).
464 */
Mindy Pereira9b875682012-02-15 18:10:54 -0800465 private void showConversation() {
Andy Huang9d3fd922012-09-26 22:23:58 -0700466 final int reason;
467
468 if (isUserVisible()) {
469 LogUtils.i(LOG_TAG,
470 "SHOWCONV: CVF is user-visible, immediately loading conversation (%s)", this);
471 reason = LOAD_NOW;
472 } else {
473 final boolean disableOffscreenLoading = DISABLE_OFFSCREEN_LOADING
474 || (mConversation.isRemote
475 || mConversation.getNumMessages() > mMaxAutoLoadMessages);
476
477 // When not visible, we should not immediately load if either this conversation is
478 // too heavyweight, or if the main/initial conversation is busy loading.
479 if (disableOffscreenLoading) {
480 reason = LOAD_WAIT_UNTIL_VISIBLE;
481 LogUtils.i(LOG_TAG, "SHOWCONV: CVF waiting until visible to load (%s)", this);
482 } else if (getListController().isInitialConversationLoading()) {
483 reason = LOAD_WAIT_FOR_INITIAL_CONVERSATION;
484 LogUtils.i(LOG_TAG, "SHOWCONV: CVF waiting for initial to finish (%s)", this);
485 getListController().registerConversationLoadedObserver(mLoadedObserver);
486 } else {
487 LogUtils.i(LOG_TAG,
488 "SHOWCONV: CVF is not visible, but no reason to wait. loading now. (%s)",
489 this);
490 reason = LOAD_NOW;
491 }
Andy Huang632721e2012-04-11 16:57:26 -0700492 }
Andy Huang9d3fd922012-09-26 22:23:58 -0700493
494 mLoadWaitReason = reason;
495 if (mLoadWaitReason == LOAD_NOW) {
496 startConversationLoad();
497 }
498 }
499
500 private void handleDelayedConversationLoad() {
501 resetLoadWaiting();
502 startConversationLoad();
503 }
504
505 private void startConversationLoad() {
mindyp3bcf1802012-09-09 11:17:00 -0700506 mWebView.setVisibility(View.VISIBLE);
mindypf4fce122012-09-14 15:55:33 -0700507 getLoaderManager().initLoader(MESSAGE_LOADER, Bundle.EMPTY, getMessageLoaderCallbacks());
Andy Huang9d3fd922012-09-26 22:23:58 -0700508 if (isUserVisible()) {
Andy Huang5460ce42012-08-16 19:38:27 -0700509 final SubjectDisplayChanger sdc = mActivity.getSubjectDisplayChanger();
510 if (sdc != null) {
511 sdc.setSubject(mConversation.subject);
512 }
513 }
mindyp3bcf1802012-09-09 11:17:00 -0700514 // TODO(mindyp): don't show loading status for a previously rendered
515 // conversation. Ielieve this is better done by making sure don't show loading status
516 // until XX ms have passed without loading completed.
517 showLoadingStatus();
Mindy Pereira8e915722012-02-16 14:42:56 -0800518 }
519
Andy Huang7d4746e2012-10-17 17:03:17 -0700520 private void revealConversation() {
Andy Huang30bcfe72012-10-18 18:09:03 -0700521 dismissLoadingStatus(mOnProgressDismiss);
Andy Huang7d4746e2012-10-17 17:03:17 -0700522 }
523
Andy Huang9d3fd922012-09-26 22:23:58 -0700524 private boolean isLoadWaiting() {
525 return mLoadWaitReason != LOAD_NOW;
526 }
527
Andy Huang51067132012-03-12 20:08:19 -0700528 private void renderConversation(MessageCursor messageCursor) {
mindyp3bcf1802012-09-09 11:17:00 -0700529 final String convHtml = renderMessageBodies(messageCursor, mEnableContentReadySignal);
Andy Huangbd544e32012-05-29 15:56:51 -0700530
531 if (DEBUG_DUMP_CONVERSATION_HTML) {
532 java.io.FileWriter fw = null;
533 try {
534 fw = new java.io.FileWriter("/sdcard/conv" + mConversation.id
535 + ".html");
536 fw.write(convHtml);
537 } catch (java.io.IOException e) {
538 e.printStackTrace();
539 } finally {
540 if (fw != null) {
541 try {
542 fw.close();
543 } catch (java.io.IOException e) {
544 e.printStackTrace();
545 }
546 }
547 }
548 }
549
Andy Huange964eee2012-10-02 19:24:58 -0700550 // save off existing scroll position before re-rendering
551 if (mWebViewLoadedData) {
552 mWebViewYPercent = calculateScrollYPercent();
553 }
554
Andy Huangbd544e32012-05-29 15:56:51 -0700555 mWebView.loadDataWithBaseURL(mBaseUri, convHtml, "text/html", "utf-8", null);
Andy Huange964eee2012-10-02 19:24:58 -0700556 mWebViewLoadedData = true;
Andy Huang63b3c672012-10-05 19:27:28 -0700557 mWebViewLoadStartMs = SystemClock.uptimeMillis();
Andy Huang51067132012-03-12 20:08:19 -0700558 }
559
Andy Huang7bdc3752012-03-25 17:18:19 -0700560 /**
561 * Populate the adapter with overlay views (message headers, super-collapsed blocks, a
562 * conversation header), and return an HTML document with spacer divs inserted for all overlays.
563 *
564 */
mindyp3bcf1802012-09-09 11:17:00 -0700565 private String renderMessageBodies(MessageCursor messageCursor,
566 boolean enableContentReadySignal) {
Andy Huangf70fc402012-02-17 15:37:42 -0800567 int pos = -1;
Andy Huang632721e2012-04-11 16:57:26 -0700568
Andy Huang1ee96b22012-08-24 20:19:53 -0700569 LogUtils.d(LOG_TAG, "IN renderMessageBodies, fragment=%s", this);
Andy Huang7bdc3752012-03-25 17:18:19 -0700570 boolean allowNetworkImages = false;
571
Andy Huangc7543572012-04-03 15:34:29 -0700572 // TODO: re-use any existing adapter item state (expanded, details expanded, show pics)
Andy Huang28b7aee2012-08-20 20:27:32 -0700573
Andy Huang7bdc3752012-03-25 17:18:19 -0700574 // Walk through the cursor and build up an overlay adapter as you go.
575 // Each overlay has an entry in the adapter for easy scroll handling in the container.
576 // Items are not necessarily 1:1 in cursor and adapter because of super-collapsed blocks.
577 // When adding adapter items, also add their heights to help the container later determine
578 // overlay dimensions.
579
Andy Huangdb620fe2012-08-24 15:45:28 -0700580 // When re-rendering, prevent ConversationContainer from laying out overlays until after
581 // the new spacers are positioned by WebView.
582 mConversationContainer.invalidateSpacerGeometry();
583
Andy Huang7bdc3752012-03-25 17:18:19 -0700584 mAdapter.clear();
585
Andy Huang47aa9c92012-07-31 15:37:21 -0700586 // re-evaluate the message parts of the view state, since the messages may have changed
587 // since the previous render
588 final ConversationViewState prevState = mViewState;
589 mViewState = new ConversationViewState(prevState);
590
Andy Huang5ff63742012-03-16 20:30:23 -0700591 // N.B. the units of height for spacers are actually dp and not px because WebView assumes
Andy Huang2e9acfe2012-03-15 22:39:36 -0700592 // a pixel is an mdpi pixel, unless you set device-dpi.
Andy Huang5ff63742012-03-16 20:30:23 -0700593
Andy Huang7bdc3752012-03-25 17:18:19 -0700594 // add a single conversation header item
595 final int convHeaderPos = mAdapter.addConversationHeader(mConversation);
Andy Huang23014702012-07-09 12:50:36 -0700596 final int convHeaderPx = measureOverlayHeight(convHeaderPos);
Andy Huang5ff63742012-03-16 20:30:23 -0700597
Andy Huang256b35c2012-08-22 15:19:13 -0700598 final int sideMarginPx = getResources().getDimensionPixelOffset(
599 R.dimen.conversation_view_margin_side) + getResources().getDimensionPixelOffset(
600 R.dimen.conversation_message_content_margin_side);
601
602 mTemplates.startConversation(mWebView.screenPxToWebPx(sideMarginPx),
603 mWebView.screenPxToWebPx(convHeaderPx));
Andy Huang3233bff2012-03-20 19:38:45 -0700604
Andy Huang46dfba62012-04-19 01:47:32 -0700605 int collapsedStart = -1;
Andy Huang839ada22012-07-20 15:48:40 -0700606 ConversationMessage prevCollapsedMsg = null;
Andy Huang46dfba62012-04-19 01:47:32 -0700607 boolean prevSafeForImages = false;
608
Andy Huangf70fc402012-02-17 15:37:42 -0800609 while (messageCursor.moveToPosition(++pos)) {
Andy Huang839ada22012-07-20 15:48:40 -0700610 final ConversationMessage msg = messageCursor.getMessage();
Andy Huang46dfba62012-04-19 01:47:32 -0700611
Andy Huang3233bff2012-03-20 19:38:45 -0700612 // TODO: save/restore 'show pics' state
613 final boolean safeForImages = msg.alwaysShowImages /* || savedStateSaysSafe */;
614 allowNetworkImages |= safeForImages;
Andy Huang24055282012-03-27 17:37:06 -0700615
Paul Westbrook08098ec2012-08-12 15:30:28 -0700616 final Integer savedExpanded = prevState.getExpansionState(msg);
617 final int expandedState;
Andy Huang839ada22012-07-20 15:48:40 -0700618 if (savedExpanded != null) {
Andy Huang1ee96b22012-08-24 20:19:53 -0700619 if (ExpansionState.isSuperCollapsed(savedExpanded) && messageCursor.isLast()) {
620 // override saved state when this is now the new last message
621 // this happens to the second-to-last message when you discard a draft
622 expandedState = ExpansionState.EXPANDED;
623 } else {
624 expandedState = savedExpanded;
625 }
Andy Huang839ada22012-07-20 15:48:40 -0700626 } else {
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700627 // new messages that are not expanded default to being eligible for super-collapse
Paul Westbrook08098ec2012-08-12 15:30:28 -0700628 expandedState = (!msg.read || msg.starred || messageCursor.isLast()) ?
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700629 ExpansionState.EXPANDED : ExpansionState.SUPER_COLLAPSED;
Andy Huang839ada22012-07-20 15:48:40 -0700630 }
Paul Westbrook08098ec2012-08-12 15:30:28 -0700631 mViewState.setExpansionState(msg, expandedState);
Andy Huangc7543572012-04-03 15:34:29 -0700632
Andy Huang839ada22012-07-20 15:48:40 -0700633 // save off "read" state from the cursor
634 // later, the view may not match the cursor (e.g. conversation marked read on open)
Andy Huang423bea22012-08-21 12:00:49 -0700635 // however, if a previous state indicated this message was unread, trust that instead
636 // so "mark unread" marks all originally unread messages
637 mViewState.setReadState(msg, msg.read && !prevState.isUnread(msg));
Andy Huang839ada22012-07-20 15:48:40 -0700638
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700639 // We only want to consider this for inclusion in the super collapsed block if
640 // 1) The we don't have previous state about this message (The first time that the
641 // user opens a conversation)
642 // 2) The previously saved state for this message indicates that this message is
643 // in the super collapsed block.
644 if (ExpansionState.isSuperCollapsed(expandedState)) {
645 // contribute to a super-collapsed block that will be emitted just before the
646 // next expanded header
647 if (collapsedStart < 0) {
648 collapsedStart = pos;
Andy Huang46dfba62012-04-19 01:47:32 -0700649 }
Andy Huangcd5c5ee2012-08-12 19:03:51 -0700650 prevCollapsedMsg = msg;
651 prevSafeForImages = safeForImages;
652 continue;
Andy Huang46dfba62012-04-19 01:47:32 -0700653 }
Andy Huang24055282012-03-27 17:37:06 -0700654
Andy Huang46dfba62012-04-19 01:47:32 -0700655 // resolve any deferred decisions on previous collapsed items
656 if (collapsedStart >= 0) {
657 if (pos - collapsedStart == 1) {
658 // special-case for a single collapsed message: no need to super-collapse it
659 renderMessage(prevCollapsedMsg, false /* expanded */,
660 prevSafeForImages);
661 } else {
662 renderSuperCollapsedBlock(collapsedStart, pos - 1);
663 }
664 prevCollapsedMsg = null;
665 collapsedStart = -1;
666 }
Andy Huang7bdc3752012-03-25 17:18:19 -0700667
Paul Westbrook08098ec2012-08-12 15:30:28 -0700668 renderMessage(msg, ExpansionState.isExpanded(expandedState), safeForImages);
Mindy Pereira9b875682012-02-15 18:10:54 -0800669 }
Andy Huang3233bff2012-03-20 19:38:45 -0700670
671 mWebView.getSettings().setBlockNetworkImage(!allowNetworkImages);
672
Paul Westbrookcebcc642012-08-08 10:06:04 -0700673 // If the conversation has specified a base uri, use it here, use mBaseUri
674 final String conversationBaseUri = mConversation.conversationBaseUri != null ?
675 mConversation.conversationBaseUri.toString() : mBaseUri;
676 return mTemplates.endConversation(mBaseUri, conversationBaseUri, 320,
Andy Huangadbf3e82012-10-13 13:30:19 -0700677 mWebView.getViewportWidth(), enableContentReadySignal, isOverviewMode(mAccount));
Mindy Pereira9b875682012-02-15 18:10:54 -0800678 }
Mindy Pereira674afa42012-02-17 14:05:24 -0800679
Andy Huang46dfba62012-04-19 01:47:32 -0700680 private void renderSuperCollapsedBlock(int start, int end) {
681 final int blockPos = mAdapter.addSuperCollapsedBlock(start, end);
Andy Huang23014702012-07-09 12:50:36 -0700682 final int blockPx = measureOverlayHeight(blockPos);
683 mTemplates.appendSuperCollapsedHtml(start, mWebView.screenPxToWebPx(blockPx));
Andy Huang46dfba62012-04-19 01:47:32 -0700684 }
685
Andy Huang839ada22012-07-20 15:48:40 -0700686 private void renderMessage(ConversationMessage msg, boolean expanded,
687 boolean safeForImages) {
Andy Huang46dfba62012-04-19 01:47:32 -0700688 final int headerPos = mAdapter.addMessageHeader(msg, expanded);
689 final MessageHeaderItem headerItem = (MessageHeaderItem) mAdapter.getItem(headerPos);
690
691 final int footerPos = mAdapter.addMessageFooter(headerItem);
692
693 // Measure item header and footer heights to allocate spacers in HTML
694 // But since the views themselves don't exist yet, render each item temporarily into
695 // a host view for measurement.
Andy Huang23014702012-07-09 12:50:36 -0700696 final int headerPx = measureOverlayHeight(headerPos);
697 final int footerPx = measureOverlayHeight(footerPos);
Andy Huang46dfba62012-04-19 01:47:32 -0700698
Andy Huang256b35c2012-08-22 15:19:13 -0700699 mTemplates.appendMessageHtml(msg, expanded, safeForImages,
Andy Huang23014702012-07-09 12:50:36 -0700700 mWebView.screenPxToWebPx(headerPx), mWebView.screenPxToWebPx(footerPx));
Andy Huang46dfba62012-04-19 01:47:32 -0700701 }
702
703 private String renderCollapsedHeaders(MessageCursor cursor,
704 SuperCollapsedBlockItem blockToReplace) {
705 final List<ConversationOverlayItem> replacements = Lists.newArrayList();
706
707 mTemplates.reset();
708
Mark Wei2b24e992012-09-10 16:40:07 -0700709 // In devices with non-integral density multiplier, screen pixels translate to non-integral
710 // web pixels. Keep track of the error that occurs when we cast all heights to int
711 float error = 0f;
Andy Huang46dfba62012-04-19 01:47:32 -0700712 for (int i = blockToReplace.getStart(), end = blockToReplace.getEnd(); i <= end; i++) {
713 cursor.moveToPosition(i);
Andy Huang839ada22012-07-20 15:48:40 -0700714 final ConversationMessage msg = cursor.getMessage();
Andy Huang46dfba62012-04-19 01:47:32 -0700715 final MessageHeaderItem header = mAdapter.newMessageHeaderItem(msg,
716 false /* expanded */);
717 final MessageFooterItem footer = mAdapter.newMessageFooterItem(header);
718
Andy Huang23014702012-07-09 12:50:36 -0700719 final int headerPx = measureOverlayHeight(header);
720 final int footerPx = measureOverlayHeight(footer);
Mark Wei2b24e992012-09-10 16:40:07 -0700721 error += mWebView.screenPxToWebPxError(headerPx)
722 + mWebView.screenPxToWebPxError(footerPx);
723
724 // When the error becomes greater than 1 pixel, make the next header 1 pixel taller
725 int correction = 0;
726 if (error >= 1) {
727 correction = 1;
728 error -= 1;
729 }
Andy Huang46dfba62012-04-19 01:47:32 -0700730
Andy Huang256b35c2012-08-22 15:19:13 -0700731 mTemplates.appendMessageHtml(msg, false /* expanded */, msg.alwaysShowImages,
Mark Wei2b24e992012-09-10 16:40:07 -0700732 mWebView.screenPxToWebPx(headerPx) + correction,
733 mWebView.screenPxToWebPx(footerPx));
Andy Huang46dfba62012-04-19 01:47:32 -0700734 replacements.add(header);
735 replacements.add(footer);
Andy Huang839ada22012-07-20 15:48:40 -0700736
Paul Westbrook08098ec2012-08-12 15:30:28 -0700737 mViewState.setExpansionState(msg, ExpansionState.COLLAPSED);
Andy Huang46dfba62012-04-19 01:47:32 -0700738 }
739
740 mAdapter.replaceSuperCollapsedBlock(blockToReplace, replacements);
Andy Huang06c03622012-10-22 18:59:45 -0700741 mAdapter.notifyDataSetChanged();
Andy Huang46dfba62012-04-19 01:47:32 -0700742
743 return mTemplates.emit();
744 }
745
746 private int measureOverlayHeight(int position) {
747 return measureOverlayHeight(mAdapter.getItem(position));
748 }
749
Andy Huang7bdc3752012-03-25 17:18:19 -0700750 /**
Andy Huangb8331b42012-07-16 19:08:53 -0700751 * Measure the height of an adapter view by rendering an adapter item into a temporary
Andy Huang46dfba62012-04-19 01:47:32 -0700752 * host view, and asking the view to immediately measure itself. This method will reuse
Andy Huang7bdc3752012-03-25 17:18:19 -0700753 * a previous adapter view from {@link ConversationContainer}'s scrap views if one was generated
754 * earlier.
755 * <p>
Andy Huang46dfba62012-04-19 01:47:32 -0700756 * After measuring the height, this method also saves the height in the
757 * {@link ConversationOverlayItem} for later use in overlay positioning.
Andy Huang7bdc3752012-03-25 17:18:19 -0700758 *
Andy Huang46dfba62012-04-19 01:47:32 -0700759 * @param convItem adapter item with data to render and measure
Andy Huang23014702012-07-09 12:50:36 -0700760 * @return height of the rendered view in screen px
Andy Huang7bdc3752012-03-25 17:18:19 -0700761 */
Andy Huang46dfba62012-04-19 01:47:32 -0700762 private int measureOverlayHeight(ConversationOverlayItem convItem) {
Andy Huang7bdc3752012-03-25 17:18:19 -0700763 final int type = convItem.getType();
764
765 final View convertView = mConversationContainer.getScrapView(type);
Andy Huangb8331b42012-07-16 19:08:53 -0700766 final View hostView = mAdapter.getView(convItem, convertView, mConversationContainer,
767 true /* measureOnly */);
Andy Huang7bdc3752012-03-25 17:18:19 -0700768 if (convertView == null) {
769 mConversationContainer.addScrapView(type, hostView);
770 }
771
Andy Huang9875bb42012-04-04 20:36:21 -0700772 final int heightPx = mConversationContainer.measureOverlay(hostView);
Andy Huang7bdc3752012-03-25 17:18:19 -0700773 convItem.setHeight(heightPx);
Andy Huang9875bb42012-04-04 20:36:21 -0700774 convItem.markMeasurementValid();
Andy Huang7bdc3752012-03-25 17:18:19 -0700775
Andy Huang23014702012-07-09 12:50:36 -0700776 return heightPx;
Andy Huang7bdc3752012-03-25 17:18:19 -0700777 }
778
Andy Huang5ff63742012-03-16 20:30:23 -0700779 @Override
780 public void onConversationViewHeaderHeightChange(int newHeight) {
Mark Weiab2d9982012-09-25 13:06:17 -0700781 final int h = mWebView.screenPxToWebPx(newHeight);
782
783 mWebView.loadUrl(String.format("javascript:setConversationHeaderSpacerHeight(%s);", h));
Andy Huang5ff63742012-03-16 20:30:23 -0700784 }
785
Andy Huang3233bff2012-03-20 19:38:45 -0700786 // END conversation header callbacks
787
788 // START message header callbacks
789 @Override
Andy Huangc7543572012-04-03 15:34:29 -0700790 public void setMessageSpacerHeight(MessageHeaderItem item, int newSpacerHeightPx) {
791 mConversationContainer.invalidateSpacerGeometry();
792
793 // update message HTML spacer height
Andy Huang23014702012-07-09 12:50:36 -0700794 final int h = mWebView.screenPxToWebPx(newSpacerHeightPx);
795 LogUtils.i(LAYOUT_TAG, "setting HTML spacer h=%dwebPx (%dscreenPx)", h,
796 newSpacerHeightPx);
Vikram Aggarwal5349ce12012-09-24 14:12:40 -0700797 mWebView.loadUrl(String.format("javascript:setMessageHeaderSpacerHeight('%s', %s);",
Andy Huang014ea4c2012-09-25 14:50:54 -0700798 mTemplates.getMessageDomId(item.getMessage()), h));
Andy Huang3233bff2012-03-20 19:38:45 -0700799 }
800
801 @Override
Andy Huangc7543572012-04-03 15:34:29 -0700802 public void setMessageExpanded(MessageHeaderItem item, int newSpacerHeightPx) {
803 mConversationContainer.invalidateSpacerGeometry();
804
805 // show/hide the HTML message body and update the spacer height
Andy Huang23014702012-07-09 12:50:36 -0700806 final int h = mWebView.screenPxToWebPx(newSpacerHeightPx);
807 LogUtils.i(LAYOUT_TAG, "setting HTML spacer expanded=%s h=%dwebPx (%dscreenPx)",
808 item.isExpanded(), h, newSpacerHeightPx);
Vikram Aggarwal5349ce12012-09-24 14:12:40 -0700809 mWebView.loadUrl(String.format("javascript:setMessageBodyVisible('%s', %s, %s);",
Andy Huang014ea4c2012-09-25 14:50:54 -0700810 mTemplates.getMessageDomId(item.getMessage()), item.isExpanded(), h));
Andy Huang839ada22012-07-20 15:48:40 -0700811
Andy Huang014ea4c2012-09-25 14:50:54 -0700812 mViewState.setExpansionState(item.getMessage(),
Paul Westbrook08098ec2012-08-12 15:30:28 -0700813 item.isExpanded() ? ExpansionState.EXPANDED : ExpansionState.COLLAPSED);
Andy Huang3233bff2012-03-20 19:38:45 -0700814 }
815
816 @Override
817 public void showExternalResources(Message msg) {
818 mWebView.getSettings().setBlockNetworkImage(false);
819 mWebView.loadUrl("javascript:unblockImages('" + mTemplates.getMessageDomId(msg) + "');");
820 }
821 // END message header callbacks
Andy Huang5ff63742012-03-16 20:30:23 -0700822
Andy Huang46dfba62012-04-19 01:47:32 -0700823 @Override
824 public void onSuperCollapsedClick(SuperCollapsedBlockItem item) {
mindypf4fce122012-09-14 15:55:33 -0700825 MessageCursor cursor = getMessageCursor();
826 if (cursor == null || !mViewsCreated) {
Andy Huang46dfba62012-04-19 01:47:32 -0700827 return;
828 }
829
mindypf4fce122012-09-14 15:55:33 -0700830 mTempBodiesHtml = renderCollapsedHeaders(cursor, item);
Andy Huang46dfba62012-04-19 01:47:32 -0700831 mWebView.loadUrl("javascript:replaceSuperCollapsedBlock(" + item.getStart() + ")");
832 }
833
Andy Huang47aa9c92012-07-31 15:37:21 -0700834 private void showNewMessageNotification(NewMessagesInfo info) {
835 final TextView descriptionView = (TextView) mNewMessageBar.findViewById(
836 R.id.new_message_description);
837 descriptionView.setText(info.getNotificationText());
838 mNewMessageBar.setVisibility(View.VISIBLE);
839 }
840
841 private void onNewMessageBarClick() {
842 mNewMessageBar.setVisibility(View.GONE);
843
mindypf4fce122012-09-14 15:55:33 -0700844 renderConversation(getMessageCursor()); // mCursor is already up-to-date
845 // per onLoadFinished()
Andy Huang5fbda022012-02-28 18:22:03 -0800846 }
847
Andy Huangadbf3e82012-10-13 13:30:19 -0700848 private static OverlayPosition[] parsePositions(final String[] topArray,
849 final String[] bottomArray) {
850 final int len = topArray.length;
851 final OverlayPosition[] positions = new OverlayPosition[len];
Andy Huangb5078b22012-03-05 19:52:29 -0800852 for (int i = 0; i < len; i++) {
Andy Huangadbf3e82012-10-13 13:30:19 -0700853 positions[i] = new OverlayPosition(
854 Integer.parseInt(topArray[i]), Integer.parseInt(bottomArray[i]));
Andy Huangb5078b22012-03-05 19:52:29 -0800855 }
Andy Huangadbf3e82012-10-13 13:30:19 -0700856 return positions;
Andy Huangb5078b22012-03-05 19:52:29 -0800857 }
858
Andy Huang47aa9c92012-07-31 15:37:21 -0700859 @Override
860 public String toString() {
861 // log extra info at DEBUG level or finer
862 final String s = super.toString();
863 if (!LogUtils.isLoggable(LOG_TAG, LogUtils.DEBUG) || mConversation == null) {
864 return s;
865 }
866 return "(" + s + " subj=" + mConversation.subject + ")";
867 }
868
Andy Huang16174812012-08-16 16:40:35 -0700869 private Address getAddress(String rawFrom) {
870 Address addr = mAddressCache.get(rawFrom);
871 if (addr == null) {
872 addr = Address.getEmailAddress(rawFrom);
873 mAddressCache.put(rawFrom, addr);
874 }
875 return addr;
876 }
877
Andy Huang9d3fd922012-09-26 22:23:58 -0700878 private void ensureContentSizeChangeListener() {
879 if (mWebViewSizeChangeListener == null) {
880 mWebViewSizeChangeListener = new ConversationWebView.ContentSizeChangeListener() {
881 @Override
882 public void onHeightChange(int h) {
883 // When WebKit says the DOM height has changed, re-measure
884 // bodies and re-position their headers.
885 // This is separate from the typical JavaScript DOM change
886 // listeners because cases like NARROW_COLUMNS text reflow do not trigger DOM
887 // events.
888 mWebView.loadUrl("javascript:measurePositions();");
889 }
890 };
891 }
892 mWebView.setContentSizeChangeListener(mWebViewSizeChangeListener);
893 }
894
Andy Huangadbf3e82012-10-13 13:30:19 -0700895 private static boolean isOverviewMode(Account acct) {
896 return acct.settings.conversationViewMode == UIProvider.ConversationViewMode.OVERVIEW;
897 }
898
899 private void setupOverviewMode() {
900 final boolean overviewMode = isOverviewMode(mAccount);
901 final WebSettings settings = mWebView.getSettings();
Andy Huang06def562012-10-14 00:19:11 -0700902 settings.setUseWideViewPort(overviewMode);
Andy Huangadbf3e82012-10-13 13:30:19 -0700903 settings.setSupportZoom(overviewMode);
904 if (overviewMode) {
905 settings.setBuiltInZoomControls(true);
906 settings.setDisplayZoomControls(false);
907 }
908 }
909
Paul Westbrook542fec92012-09-18 14:47:51 -0700910 private class ConversationWebViewClient extends AbstractConversationWebViewClient {
Andy Huang17a9cde2012-03-09 18:03:16 -0800911 @Override
912 public void onPageFinished(WebView view, String url) {
Andy Huang9a8bc1e2012-10-23 19:48:25 -0700913 // Ignore unsafe calls made after a fragment is detached from an activity.
914 // This method needs to, for example, get at the loader manager, which needs
915 // the fragment to be added.
Andy Huangde56e972012-07-26 18:23:08 -0700916 final ControllableActivity activity = (ControllableActivity) getActivity();
Andy Huang9a8bc1e2012-10-23 19:48:25 -0700917 if (!isAdded() || !mViewsCreated) {
Andy Huangde56e972012-07-26 18:23:08 -0700918 LogUtils.i(LOG_TAG, "ignoring CVF.onPageFinished, url=%s fragment=%s", url,
Andy Huangb95da852012-07-18 14:16:58 -0700919 ConversationViewFragment.this);
920 return;
921 }
922
Andy Huang30bcfe72012-10-18 18:09:03 -0700923 LogUtils.i(LOG_TAG, "IN CVF.onPageFinished, url=%s fragment=%s wv=%s t=%sms", url,
924 ConversationViewFragment.this, view,
Andy Huang63b3c672012-10-05 19:27:28 -0700925 (SystemClock.uptimeMillis() - mWebViewLoadStartMs));
Andy Huang632721e2012-04-11 16:57:26 -0700926
Andy Huang9d3fd922012-09-26 22:23:58 -0700927 ensureContentSizeChangeListener();
928
mindyp3bcf1802012-09-09 11:17:00 -0700929 if (!mEnableContentReadySignal) {
Andy Huang7d4746e2012-10-17 17:03:17 -0700930 revealConversation();
mindyp3bcf1802012-09-09 11:17:00 -0700931 }
Andy Huang9d3fd922012-09-26 22:23:58 -0700932
Andy Huang9a8bc1e2012-10-23 19:48:25 -0700933 final Set<String> emailAddresses = Sets.newHashSet();
934 for (Address addr : mAddressCache.values()) {
935 emailAddresses.add(addr.getAddress());
Andy Huangb8331b42012-07-16 19:08:53 -0700936 }
Andy Huang9a8bc1e2012-10-23 19:48:25 -0700937 ContactLoaderCallbacks callbacks = getContactInfoSource();
938 getContactInfoSource().setSenders(emailAddresses);
939 getLoaderManager().restartLoader(CONTACT_LOADER, Bundle.EMPTY, callbacks);
Andy Huang17a9cde2012-03-09 18:03:16 -0800940 }
941
Andy Huangaf5d4e02012-03-19 19:02:12 -0700942 @Override
943 public boolean shouldOverrideUrlLoading(WebView view, String url) {
Paul Westbrook542fec92012-09-18 14:47:51 -0700944 return mViewsCreated && super.shouldOverrideUrlLoading(view, url);
Andy Huangaf5d4e02012-03-19 19:02:12 -0700945 }
Andy Huang17a9cde2012-03-09 18:03:16 -0800946 }
947
Andy Huangf70fc402012-02-17 15:37:42 -0800948 /**
949 * NOTE: all public methods must be listed in the proguard flags so that they can be accessed
950 * via reflection and not stripped.
951 *
952 */
953 private class MailJsBridge {
954
955 @SuppressWarnings("unused")
Mindy Pereira974c9662012-09-14 10:02:08 -0700956 @JavascriptInterface
Andy Huangadbf3e82012-10-13 13:30:19 -0700957 public void onWebContentGeometryChange(final String[] overlayTopStrs,
958 final String[] overlayBottomStrs) {
Andy Huang9a8bc1e2012-10-23 19:48:25 -0700959 getHandler().post(new FragmentRunnable("onWebContentGeometryChange") {
mindyp1b3cc472012-09-27 11:32:59 -0700960
Andy Huang9a8bc1e2012-10-23 19:48:25 -0700961 @Override
962 public void go() {
963 try {
Andy Huang46dfba62012-04-19 01:47:32 -0700964 if (!mViewsCreated) {
mindyp1b3cc472012-09-27 11:32:59 -0700965 LogUtils.d(LOG_TAG, "ignoring webContentGeometryChange because views"
966 + " are gone, %s", ConversationViewFragment.this);
Andy Huang46dfba62012-04-19 01:47:32 -0700967 return;
968 }
Andy Huangadbf3e82012-10-13 13:30:19 -0700969 mConversationContainer.onGeometryChange(
970 parsePositions(overlayTopStrs, overlayBottomStrs));
mindyp1b3cc472012-09-27 11:32:59 -0700971 if (mDiff != 0) {
972 // SCROLL!
973 int scale = (int) (mWebView.getScale() / mWebView.getInitialScale());
974 if (scale > 1) {
975 mWebView.scrollBy(0, (mDiff * (scale - 1)));
976 }
977 mDiff = 0;
978 }
Andy Huang9a8bc1e2012-10-23 19:48:25 -0700979 } catch (Throwable t) {
980 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onWebContentGeometryChange");
Andy Huang46dfba62012-04-19 01:47:32 -0700981 }
Andy Huang9a8bc1e2012-10-23 19:48:25 -0700982 }
983 });
Andy Huang46dfba62012-04-19 01:47:32 -0700984 }
985
986 @SuppressWarnings("unused")
Mindy Pereira974c9662012-09-14 10:02:08 -0700987 @JavascriptInterface
Andy Huang46dfba62012-04-19 01:47:32 -0700988 public String getTempMessageBodies() {
989 try {
990 if (!mViewsCreated) {
991 return "";
Andy Huangf70fc402012-02-17 15:37:42 -0800992 }
Andy Huang46dfba62012-04-19 01:47:32 -0700993
994 final String s = mTempBodiesHtml;
995 mTempBodiesHtml = null;
996 return s;
997 } catch (Throwable t) {
998 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getTempMessageBodies");
999 return "";
1000 }
Andy Huangf70fc402012-02-17 15:37:42 -08001001 }
1002
Andy Huang014ea4c2012-09-25 14:50:54 -07001003 @SuppressWarnings("unused")
1004 @JavascriptInterface
1005 public String getMessageBody(String domId) {
1006 try {
1007 final MessageCursor cursor = getMessageCursor();
1008 if (!mViewsCreated || cursor == null) {
1009 return "";
1010 }
1011
1012 int pos = -1;
1013 while (cursor.moveToPosition(++pos)) {
1014 final ConversationMessage msg = cursor.getMessage();
1015 if (TextUtils.equals(domId, mTemplates.getMessageDomId(msg))) {
1016 return msg.getBodyAsHtml();
1017 }
1018 }
1019
1020 return "";
1021
1022 } catch (Throwable t) {
1023 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getMessageBody");
1024 return "";
1025 }
1026 }
1027
mindyp3bcf1802012-09-09 11:17:00 -07001028 @SuppressWarnings("unused")
Mindy Pereira974c9662012-09-14 10:02:08 -07001029 @JavascriptInterface
mindyp3bcf1802012-09-09 11:17:00 -07001030 public void onContentReady() {
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001031 getHandler().post(new FragmentRunnable("onContentReady") {
1032 @Override
1033 public void go() {
1034 try {
Andy Huang63b3c672012-10-05 19:27:28 -07001035 if (mWebViewLoadStartMs != 0) {
1036 LogUtils.i(LOG_TAG, "IN CVF.onContentReady, f=%s vis=%s t=%sms",
1037 ConversationViewFragment.this,
1038 isUserVisible(),
1039 (SystemClock.uptimeMillis() - mWebViewLoadStartMs));
1040 }
Andy Huang7d4746e2012-10-17 17:03:17 -07001041 revealConversation();
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001042 } catch (Throwable t) {
1043 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.onContentReady");
1044 // Still try to show the conversation.
1045 revealConversation();
mindyp3bcf1802012-09-09 11:17:00 -07001046 }
Andy Huang9a8bc1e2012-10-23 19:48:25 -07001047 }
1048 });
mindyp3bcf1802012-09-09 11:17:00 -07001049 }
Andy Huange964eee2012-10-02 19:24:58 -07001050
1051 @SuppressWarnings("unused")
1052 @JavascriptInterface
1053 public float getScrollYPercent() {
1054 try {
1055 return mWebViewYPercent;
1056 } catch (Throwable t) {
1057 LogUtils.e(LOG_TAG, t, "Error in MailJsBridge.getScrollYPercent");
1058 return 0f;
1059 }
1060 }
Andy Huangf70fc402012-02-17 15:37:42 -08001061 }
1062
Andy Huang47aa9c92012-07-31 15:37:21 -07001063 private class NewMessagesInfo {
1064 int count;
Andy Huang06c03622012-10-22 18:59:45 -07001065 int countFromSelf;
Andy Huang47aa9c92012-07-31 15:37:21 -07001066 String senderAddress;
1067
1068 /**
1069 * Return the display text for the new message notification overlay. It will be formatted
1070 * appropriately for a single new message vs. multiple new messages.
1071 *
1072 * @return display text
1073 */
1074 public String getNotificationText() {
mindypad0c30d2012-09-25 12:09:13 -07001075 Resources res = getResources();
Andy Huang47aa9c92012-07-31 15:37:21 -07001076 if (count > 1) {
mindypad0c30d2012-09-25 12:09:13 -07001077 return res.getString(R.string.new_incoming_messages_many, count);
Andy Huang47aa9c92012-07-31 15:37:21 -07001078 } else {
Andy Huang16174812012-08-16 16:40:35 -07001079 final Address addr = getAddress(senderAddress);
mindypad0c30d2012-09-25 12:09:13 -07001080 return res.getString(R.string.new_incoming_messages_one,
1081 TextUtils.isEmpty(addr.getName()) ? addr.getAddress() : addr.getName());
Andy Huang47aa9c92012-07-31 15:37:21 -07001082 }
Andy Huang47aa9c92012-07-31 15:37:21 -07001083 }
1084 }
1085
mindypf4fce122012-09-14 15:55:33 -07001086 @Override
Andy Huang014ea4c2012-09-25 14:50:54 -07001087 public void onMessageCursorLoadFinished(Loader<Cursor> loader, MessageCursor newCursor,
1088 MessageCursor oldCursor) {
mindypf4fce122012-09-14 15:55:33 -07001089 /*
1090 * what kind of changes affect the MessageCursor? 1. new message(s) 2.
1091 * read/unread state change 3. deleted message, either regular or draft
1092 * 4. updated message, either from self or from others, updated in
1093 * content or state or sender 5. star/unstar of message (technically
1094 * similar to #1) 6. other label change Use MessageCursor.hashCode() to
1095 * sort out interesting vs. no-op cursor updates.
1096 */
Andy Huangb8331b42012-07-16 19:08:53 -07001097
Andy Huang233d4352012-10-18 14:00:24 -07001098 if (oldCursor != null && !oldCursor.isClosed()) {
Andy Huang014ea4c2012-09-25 14:50:54 -07001099 final NewMessagesInfo info = getNewIncomingMessagesInfo(newCursor);
Andy Huangb8331b42012-07-16 19:08:53 -07001100
Andy Huang014ea4c2012-09-25 14:50:54 -07001101 if (info.count > 0) {
1102 // don't immediately render new incoming messages from other
1103 // senders
1104 // (to avoid a new message from losing the user's focus)
1105 LogUtils.i(LOG_TAG, "CONV RENDER: conversation updated"
Andy Huang9d3fd922012-09-26 22:23:58 -07001106 + ", holding cursor for new incoming message (%s)", this);
Andy Huang014ea4c2012-09-25 14:50:54 -07001107 showNewMessageNotification(info);
1108 return;
1109 }
1110
Andy Huang06c03622012-10-22 18:59:45 -07001111 final int oldState = oldCursor.getStateHashCode();
1112 final boolean changed = newCursor.getStateHashCode() != oldState;
Andy Huang233d4352012-10-18 14:00:24 -07001113
Andy Huang014ea4c2012-09-25 14:50:54 -07001114 if (!changed) {
1115 final boolean processedInPlace = processInPlaceUpdates(newCursor, oldCursor);
1116 if (processedInPlace) {
Andy Huang9d3fd922012-09-26 22:23:58 -07001117 LogUtils.i(LOG_TAG, "CONV RENDER: processed update(s) in place (%s)", this);
Andy Huang1ee96b22012-08-24 20:19:53 -07001118 } else {
mindypf4fce122012-09-14 15:55:33 -07001119 LogUtils.i(LOG_TAG, "CONV RENDER: uninteresting update"
Andy Huang9d3fd922012-09-26 22:23:58 -07001120 + ", ignoring this conversation update (%s)", this);
Andy Huang1ee96b22012-08-24 20:19:53 -07001121 }
Andy Huangb8331b42012-07-16 19:08:53 -07001122 return;
Andy Huang06c03622012-10-22 18:59:45 -07001123 } else if (info.countFromSelf == 1) {
1124 // Special-case the very common case of a new cursor that is the same as the old
1125 // one, except that there is a new message from yourself. This happens upon send.
1126 final boolean sameExceptNewLast = newCursor.getStateHashCode(1) == oldState;
1127 if (sameExceptNewLast) {
1128 LogUtils.i(LOG_TAG, "CONV RENDER: update is a single new message from self"
1129 + " (%s)", this);
1130 newCursor.moveToLast();
1131 processNewOutgoingMessage(newCursor.getMessage());
1132 return;
1133 }
Andy Huangb8331b42012-07-16 19:08:53 -07001134 }
Andy Huang6766b6e2012-09-28 12:43:52 -07001135 // cursors are different, and not due to an incoming message. fall
1136 // through and render.
1137 LogUtils.i(LOG_TAG, "CONV RENDER: conversation updated"
1138 + ", but not due to incoming message. rendering. (%s)", this);
Andy Huang06c03622012-10-22 18:59:45 -07001139
1140 if (DEBUG_DUMP_CURSOR_CONTENTS) {
1141 LogUtils.i(LOG_TAG, "old cursor: %s", oldCursor.getDebugDump());
1142 LogUtils.i(LOG_TAG, "new cursor: %s", newCursor.getDebugDump());
1143 }
Andy Huang6766b6e2012-09-28 12:43:52 -07001144 } else {
1145 LogUtils.i(LOG_TAG, "CONV RENDER: initial render. (%s)", this);
Andy Huangb8331b42012-07-16 19:08:53 -07001146 }
1147
Mark Wei4071c2f2012-09-26 14:38:38 -07001148 // if layout hasn't happened, delay render
1149 // This is needed in addition to the showConversation() delay to speed
1150 // up rotation and restoration.
1151 if (mConversationContainer.getWidth() == 0) {
1152 mNeedRender = true;
1153 mConversationContainer.addOnLayoutChangeListener(this);
1154 } else {
1155 renderConversation(newCursor);
1156 }
Andy Huangb8331b42012-07-16 19:08:53 -07001157 }
1158
mindypf4fce122012-09-14 15:55:33 -07001159 private NewMessagesInfo getNewIncomingMessagesInfo(MessageCursor newCursor) {
1160 final NewMessagesInfo info = new NewMessagesInfo();
Andy Huangb8331b42012-07-16 19:08:53 -07001161
mindypf4fce122012-09-14 15:55:33 -07001162 int pos = -1;
1163 while (newCursor.moveToPosition(++pos)) {
1164 final Message m = newCursor.getMessage();
1165 if (!mViewState.contains(m)) {
1166 LogUtils.i(LOG_TAG, "conversation diff: found new msg: %s", m.uri);
Andy Huangb8331b42012-07-16 19:08:53 -07001167
mindypf4fce122012-09-14 15:55:33 -07001168 final Address from = getAddress(m.from);
1169 // distinguish ours from theirs
1170 // new messages from the account owner should not trigger a
1171 // notification
1172 if (mAccount.ownsFromAddress(from.getAddress())) {
1173 LogUtils.i(LOG_TAG, "found message from self: %s", m.uri);
Andy Huang06c03622012-10-22 18:59:45 -07001174 info.countFromSelf++;
mindypf4fce122012-09-14 15:55:33 -07001175 continue;
1176 }
Andy Huangb8331b42012-07-16 19:08:53 -07001177
mindypf4fce122012-09-14 15:55:33 -07001178 info.count++;
1179 info.senderAddress = m.from;
Andy Huangb8331b42012-07-16 19:08:53 -07001180 }
Andy Huangb8331b42012-07-16 19:08:53 -07001181 }
mindypf4fce122012-09-14 15:55:33 -07001182 return info;
Andy Huangb8331b42012-07-16 19:08:53 -07001183 }
1184
Andy Huang014ea4c2012-09-25 14:50:54 -07001185 private boolean processInPlaceUpdates(MessageCursor newCursor, MessageCursor oldCursor) {
1186 final Set<String> idsOfChangedBodies = Sets.newHashSet();
1187 boolean changed = false;
1188
1189 int pos = 0;
1190 while (true) {
1191 if (!newCursor.moveToPosition(pos) || !oldCursor.moveToPosition(pos)) {
1192 break;
1193 }
1194
1195 final ConversationMessage newMsg = newCursor.getMessage();
1196 final ConversationMessage oldMsg = oldCursor.getMessage();
1197
Andy Huang2a1e8e32012-10-23 18:54:57 -07001198 if (!TextUtils.equals(newMsg.from, oldMsg.from) ||
1199 newMsg.isSending != oldMsg.isSending) {
Andy Huang014ea4c2012-09-25 14:50:54 -07001200 mAdapter.updateItemsForMessage(newMsg);
Andy Huang2a1e8e32012-10-23 18:54:57 -07001201 LogUtils.i(LOG_TAG, "msg #%d (%d): detected from/sending change. isSending=%s",
1202 pos, newMsg.id, newMsg.isSending);
Andy Huang014ea4c2012-09-25 14:50:54 -07001203 changed = true;
1204 }
1205
1206 // update changed message bodies in-place
1207 if (!TextUtils.equals(newMsg.bodyHtml, oldMsg.bodyHtml) ||
1208 !TextUtils.equals(newMsg.bodyText, oldMsg.bodyText)) {
1209 // maybe just set a flag to notify JS to re-request changed bodies
1210 idsOfChangedBodies.add('"' + mTemplates.getMessageDomId(newMsg) + '"');
1211 LogUtils.i(LOG_TAG, "msg #%d (%d): detected body change", pos, newMsg.id);
1212 }
1213
1214 pos++;
1215 }
1216
Andy Huang06c03622012-10-22 18:59:45 -07001217 if (changed) {
1218 // notify once after the entire adapter is updated
1219 mAdapter.notifyDataSetChanged();
1220 }
1221
Andy Huang014ea4c2012-09-25 14:50:54 -07001222 if (!idsOfChangedBodies.isEmpty()) {
1223 mWebView.loadUrl(String.format("javascript:replaceMessageBodies([%s]);",
1224 TextUtils.join(",", idsOfChangedBodies)));
1225 changed = true;
1226 }
1227
1228 return changed;
1229 }
1230
Andy Huang06c03622012-10-22 18:59:45 -07001231 private void processNewOutgoingMessage(ConversationMessage msg) {
1232 mTemplates.reset();
1233 // this method will add some items to mAdapter, but we deliberately want to avoid notifying
1234 // adapter listeners (i.e. ConversationContainer) until onWebContentGeometryChange is next
1235 // called, to prevent N+1 headers rendering with N message bodies.
1236 renderMessage(msg, true /* expanded */, msg.alwaysShowImages);
1237 mTempBodiesHtml = mTemplates.emit();
1238
1239 mViewState.setExpansionState(msg, ExpansionState.EXPANDED);
1240 // FIXME: should the provider set this as initial state?
1241 mViewState.setReadState(msg, false /* read */);
1242
Andy Huang91d782a2012-10-25 12:37:29 -07001243 // From now until the updated spacer geometry is returned, the adapter items are mismatched
1244 // with the existing spacers. Do not let them layout.
1245 mConversationContainer.invalidateSpacerGeometry();
1246
Andy Huang06c03622012-10-22 18:59:45 -07001247 mWebView.loadUrl("javascript:appendMessageHtml();");
1248 }
1249
Paul Westbrookcebcc642012-08-08 10:06:04 -07001250 private class SetCookieTask extends AsyncTask<Void, Void, Void> {
1251 final String mUri;
Paul Westbrookb8361c92012-09-27 10:57:14 -07001252 final Uri mAccountCookieQueryUri;
1253 final ContentResolver mResolver;
Paul Westbrookcebcc642012-08-08 10:06:04 -07001254
Paul Westbrookb8361c92012-09-27 10:57:14 -07001255 SetCookieTask(Context context, Uri baseUri, Uri accountCookieQueryUri) {
1256 mUri = baseUri.toString();
1257 mAccountCookieQueryUri = accountCookieQueryUri;
1258 mResolver = context.getContentResolver();
Paul Westbrookcebcc642012-08-08 10:06:04 -07001259 }
1260
1261 @Override
1262 public Void doInBackground(Void... args) {
Paul Westbrookb8361c92012-09-27 10:57:14 -07001263 // First query for the coookie string from the UI provider
1264 final Cursor cookieCursor = mResolver.query(mAccountCookieQueryUri,
1265 UIProvider.ACCOUNT_COOKIE_PROJECTION, null, null, null);
1266 if (cookieCursor == null) {
1267 return null;
1268 }
1269
1270 try {
1271 if (cookieCursor.moveToFirst()) {
1272 final String cookie = cookieCursor.getString(
1273 cookieCursor.getColumnIndex(UIProvider.AccountCookieColumns.COOKIE));
1274
1275 if (cookie != null) {
1276 final CookieSyncManager csm =
1277 CookieSyncManager.createInstance(getContext());
1278 CookieManager.getInstance().setCookie(mUri, cookie);
1279 csm.sync();
1280 }
1281 }
1282
1283 } finally {
1284 cookieCursor.close();
1285 }
1286
1287
Paul Westbrookcebcc642012-08-08 10:06:04 -07001288 return null;
1289 }
1290 }
mindyp36280f32012-09-09 16:11:23 -07001291
mindyp26d4d2d2012-09-18 17:30:32 -07001292 @Override
mindyp36280f32012-09-09 16:11:23 -07001293 public void onConversationUpdated(Conversation conv) {
1294 final ConversationViewHeader headerView = (ConversationViewHeader) mConversationContainer
1295 .findViewById(R.id.conversation_header);
mindypb2b98ba2012-09-24 14:13:58 -07001296 mConversation = conv;
mindyp9e0b2362012-09-09 16:31:21 -07001297 if (headerView != null) {
1298 headerView.onConversationUpdated(conv);
1299 }
mindyp36280f32012-09-09 16:11:23 -07001300 }
Mark Wei4071c2f2012-09-26 14:38:38 -07001301
1302 @Override
1303 public void onLayoutChange(View v, int left, int top, int right,
1304 int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
1305 boolean sizeChanged = mNeedRender
1306 && mConversationContainer.getWidth() != 0;
1307 if (sizeChanged) {
1308 mNeedRender = false;
1309 mConversationContainer.removeOnLayoutChangeListener(this);
1310 renderConversation(getMessageCursor());
1311 }
1312 }
mindyp1b3cc472012-09-27 11:32:59 -07001313
1314 @Override
1315 public void setMessageDetailsExpanded(MessageHeaderItem i, boolean expanded,
1316 int heightBefore) {
1317 mDiff = (expanded ? 1 : -1) * Math.abs(i.getHeight() - heightBefore);
1318 }
Mindy Pereira9b875682012-02-15 18:10:54 -08001319}