WidgetService.java revision 50e1b09e6e5bb8e1993d98fb14c690de743b53df
1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.android.mail.widget;
17
18import com.android.mail.R;
19import com.android.mail.browse.SendersView;
20import com.android.mail.compose.ComposeActivity;
21import com.android.mail.persistence.Persistence;
22import com.android.mail.providers.Account;
23import com.android.mail.providers.Conversation;
24import com.android.mail.providers.Folder;
25import com.android.mail.providers.UIProvider;
26import com.android.mail.providers.UIProvider.ConversationListQueryParameters;
27import com.android.mail.utils.AccountUtils;
28import com.android.mail.utils.DelayedTaskHandler;
29import com.android.mail.utils.LogTag;
30import com.android.mail.utils.LogUtils;
31import com.android.mail.utils.Utils;
32
33import android.app.PendingIntent;
34import android.appwidget.AppWidgetManager;
35import android.content.ContentResolver;
36import android.content.Context;
37import android.content.CursorLoader;
38import android.content.Intent;
39import android.content.Loader;
40import android.content.Loader.OnLoadCompleteListener;
41import android.content.SharedPreferences;
42import android.content.res.Resources;
43import android.database.Cursor;
44import android.net.Uri;
45import android.os.Looper;
46import android.support.v4.app.TaskStackBuilder;
47import android.text.SpannableStringBuilder;
48import android.text.TextUtils;
49import android.text.format.DateUtils;
50import android.view.View;
51import android.widget.RemoteViews;
52import android.widget.RemoteViewsService;
53
54import org.json.JSONException;
55
56public class WidgetService extends RemoteViewsService {
57    /**
58     * Lock to avoid race condition between widgets.
59     */
60    private static Object sWidgetLock = new Object();
61
62    @Override
63    public RemoteViewsFactory onGetViewFactory(Intent intent) {
64        return new MailFactory(getApplicationContext(), intent, this);
65    }
66
67
68    protected void configureValidAccountWidget(Context context, RemoteViews remoteViews,
69            int appWidgetId, Account account, Folder folder, String folderName) {
70        configureValidAccountWidget(context, remoteViews, appWidgetId, account, folder, folderName,
71                WidgetService.class);
72    }
73
74    /**
75     * Modifies the remoteView for the given account and folder.
76     */
77    public static void configureValidAccountWidget(Context context, RemoteViews remoteViews,
78            int appWidgetId, Account account, Folder folder, String folderDisplayName,
79            Class<?> widgetService) {
80        remoteViews.setViewVisibility(R.id.widget_folder, View.VISIBLE);
81        remoteViews.setTextViewText(R.id.widget_folder, folderDisplayName);
82        remoteViews.setViewVisibility(R.id.widget_account, View.VISIBLE);
83        remoteViews.setTextViewText(R.id.widget_account, account.name);
84        remoteViews.setViewVisibility(R.id.widget_unread_count, View.VISIBLE);
85        remoteViews.setViewVisibility(R.id.widget_compose, View.VISIBLE);
86        remoteViews.setViewVisibility(R.id.conversation_list, View.VISIBLE);
87        remoteViews.setViewVisibility(R.id.widget_folder_not_synced, View.GONE);
88
89        WidgetService.configureValidWidgetIntents(context, remoteViews, appWidgetId, account,
90                folder, folderDisplayName, widgetService);
91    }
92
93    public static void configureValidWidgetIntents(Context context, RemoteViews remoteViews,
94            int appWidgetId, Account account, Folder folder, String folderDisplayName,
95            Class<?> serviceClass) {
96        remoteViews.setViewVisibility(R.id.widget_configuration, View.GONE);
97
98
99        // Launch an intent to avoid ANRs
100        final Intent intent = new Intent(context, serviceClass);
101        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
102        intent.putExtra(BaseWidgetProvider.EXTRA_ACCOUNT, account.serialize());
103        intent.putExtra(BaseWidgetProvider.EXTRA_FOLDER, folder.serialize());
104        intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
105        remoteViews.setRemoteAdapter(R.id.conversation_list, intent);
106        // Open mail app when click on header
107        final Intent mailIntent = Utils.createViewFolderIntent(folder, account);
108        PendingIntent clickIntent = PendingIntent.getActivity(context, 0, mailIntent,
109                PendingIntent.FLAG_UPDATE_CURRENT);
110        remoteViews.setOnClickPendingIntent(R.id.widget_header, clickIntent);
111
112        // On click intent for Compose
113        final Intent composeIntent = new Intent();
114        composeIntent.setAction(Intent.ACTION_SEND);
115        composeIntent.putExtra(Utils.EXTRA_ACCOUNT, account);
116        composeIntent.setData(account.composeIntentUri);
117        composeIntent.putExtra(ComposeActivity.EXTRA_FROM_EMAIL_TASK, true);
118        if (account.composeIntentUri != null) {
119            composeIntent.putExtra(Utils.EXTRA_COMPOSE_URI, account.composeIntentUri);
120        }
121
122        // Build a task stack that forces the conversation list on the stack before the compose
123        // activity.
124        final TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
125        clickIntent = taskStackBuilder.addNextIntent(mailIntent)
126                .addNextIntent(composeIntent)
127                .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
128        remoteViews.setOnClickPendingIntent(R.id.widget_compose, clickIntent);
129
130        // On click intent for Conversation
131        final Intent conversationIntent = new Intent();
132        conversationIntent.setAction(Intent.ACTION_VIEW);
133        clickIntent = PendingIntent.getActivity(context, 0, conversationIntent,
134                PendingIntent.FLAG_UPDATE_CURRENT);
135        remoteViews.setPendingIntentTemplate(R.id.conversation_list, clickIntent);
136    }
137
138    /**
139     * Persists the information about the specified widget.
140     */
141    public static void saveWidgetInformation(Context context, int appWidgetId, Account account,
142                Folder folder) {
143        final SharedPreferences.Editor editor = Persistence.getPreferences(context).edit();
144        editor.putString(WidgetProvider.WIDGET_ACCOUNT_PREFIX + appWidgetId,
145                createWidgetPreferenceValue(account, folder));
146        editor.apply();
147    }
148
149    private static String createWidgetPreferenceValue(Account account, Folder folder) {
150        return account.uri.toString() +
151                BaseWidgetProvider.ACCOUNT_FOLDER_PREFERENCE_SEPARATOR + folder.uri.toString();
152
153    }
154
155    /**
156     * Returns true if this widget id has been configured and saved.
157     */
158    public boolean isWidgetConfigured(Context context, int appWidgetId, Account account,
159            Folder folder) {
160        if (isAccountValid(context, account)) {
161            return Persistence.getPreferences(context).getString(
162                    BaseWidgetProvider.WIDGET_ACCOUNT_PREFIX + appWidgetId, null) != null;
163        }
164        return false;
165    }
166
167    protected boolean isAccountValid(Context context, Account account) {
168        if (account != null) {
169            Account[] accounts = AccountUtils.getSyncingAccounts(context);
170            for (Account existing : accounts) {
171                if (account != null && existing != null && account.uri.equals(existing.uri)) {
172                    return true;
173                }
174            }
175        }
176        return false;
177    }
178
179    /**
180     * Remote Views Factory for Mail Widget.
181     */
182    protected static class MailFactory
183            implements RemoteViewsService.RemoteViewsFactory, OnLoadCompleteListener<Cursor> {
184        private static final int MAX_CONVERSATIONS_COUNT = 25;
185        private static final int MAX_SENDERS_LENGTH = 25;
186
187        private static final int FOLDER_LOADER_ID = 0;
188        private static final int CONVERSATION_CURSOR_LOADER_ID = 1;
189
190        private static final String LOG_TAG = LogTag.getLogTag();
191
192        private final Context mContext;
193        private final int mAppWidgetId;
194        private final Account mAccount;
195        private Folder mFolder;
196        private final WidgetConversationViewBuilder mWidgetConversationViewBuilder;
197        private CursorLoader mConversationCursorLoader;
198        private Cursor mConversationCursor;
199        private CursorLoader mFolderLoader;
200        private FolderUpdateHandler mFolderUpdateHandler;
201        private int mFolderCount;
202        private boolean mShouldShowViewMore;
203        private boolean mFolderInformationShown = false;
204        private ContentResolver mResolver;
205        private WidgetService mService;
206        private int mSenderFormatVersion;
207
208        public MailFactory(Context context, Intent intent, WidgetService service) {
209            mContext = context;
210            mAppWidgetId = intent.getIntExtra(
211                    AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
212            mAccount = Account.newinstance(intent.getStringExtra(WidgetProvider.EXTRA_ACCOUNT));
213            try {
214                mFolder = Folder.fromJSONString(intent.getStringExtra(WidgetProvider.EXTRA_FOLDER));
215            } catch (JSONException e) {
216                mFolder = null;
217                LogUtils.wtf(LOG_TAG, e, "unable to parse folder for widget");
218            }
219            mWidgetConversationViewBuilder = new WidgetConversationViewBuilder(context,
220                    mAccount);
221            mResolver = context.getContentResolver();
222            mService = service;
223        }
224
225        @Override
226        public void onCreate() {
227
228            // Save the map between widgetId and account to preference
229            saveWidgetInformation(mContext, mAppWidgetId, mAccount, mFolder);
230
231            // If the account of this widget has been removed, we want to update the widget to
232            // "Tap to configure" mode.
233            if (!mService.isWidgetConfigured(mContext, mAppWidgetId, mAccount, mFolder)) {
234                BaseWidgetProvider.updateWidget(mContext, mAppWidgetId, mAccount, mFolder);
235            }
236
237            // We want to limit the query result to 25 and don't want these queries to cause network
238            // traffic
239            final Uri.Builder builder = mFolder.conversationListUri.buildUpon();
240            final String maxConversations = Integer.toString(MAX_CONVERSATIONS_COUNT);
241            final Uri widgetConversationQueryUri = builder
242                    .appendQueryParameter(ConversationListQueryParameters.LIMIT, maxConversations)
243                    .appendQueryParameter(ConversationListQueryParameters.USE_NETWORK,
244                            Boolean.FALSE.toString()).build();
245
246            final Resources res = mContext.getResources();
247            mConversationCursorLoader = new CursorLoader(mContext, widgetConversationQueryUri,
248                    UIProvider.CONVERSATION_PROJECTION, null, null, null);
249            mConversationCursorLoader.registerListener(CONVERSATION_CURSOR_LOADER_ID, this);
250            mConversationCursorLoader.setUpdateThrottle(
251                    res.getInteger(R.integer.widget_refresh_delay_ms));
252            mConversationCursorLoader.startLoading();
253
254            mFolderLoader = new CursorLoader(mContext, mFolder.uri, UIProvider.FOLDERS_PROJECTION,
255                    null, null, null);
256            mFolderLoader.registerListener(FOLDER_LOADER_ID, this);
257            mFolderUpdateHandler = new FolderUpdateHandler(
258                    res.getInteger(R.integer.widget_folder_refresh_delay_ms));
259            mFolderUpdateHandler.scheduleTask();
260
261        }
262
263        @Override
264        public void onDestroy() {
265            synchronized (sWidgetLock) {
266                if (mConversationCursorLoader != null) {
267                    mConversationCursorLoader.reset();
268                    mConversationCursorLoader.unregisterListener(this);
269                    mConversationCursorLoader = null;
270                }
271
272                // The Loader should close the cursor, so just unset the reference
273                // to it here.
274                mConversationCursor = null;
275            }
276
277            if (mFolderLoader != null) {
278                mFolderLoader.reset();
279                mFolderLoader.unregisterListener(this);
280                mFolderLoader = null;
281            }
282        }
283
284        @Override
285        public void onDataSetChanged() {
286            // We are not using this as signal to requery the cursor.  The query will be started
287            // in the following ways:
288            // 1) The Service is started and the loader is started in onCreate()
289            //       This will happen when the service is not running, and
290            //       AppWidgetManager#notifyAppWidgetViewDataChanged() is called
291            // 2) The service is running, with a previously created loader.  The loader is watching
292            //    for updates from the existing cursor.  If one is seen, the loader will load a new
293            //    cursor in the background.
294            mFolderUpdateHandler.scheduleTask();
295        }
296
297        /**
298         * Returns the number of items should be shown in the widget list.  This method also updates
299         * the boolean that indicates whether the "show more" item should be shown.
300         * @return the number of items to be displayed in the list.
301         */
302        @Override
303        public int getCount() {
304            synchronized (sWidgetLock) {
305                final int count = getConversationCount();
306                final int cursorCount = mConversationCursor != null ?
307                        mConversationCursor.getCount() : 0;
308                mShouldShowViewMore = count < cursorCount || count < mFolderCount;
309                return count + (mShouldShowViewMore ? 1 : 0);
310            }
311        }
312
313        /**
314         * Returns the number of conversations that should be shown in the widget.  This method
315         * doesn't update the boolean that indicates that the "show more" item should be included
316         * in the list.
317         * @return
318         */
319        private int getConversationCount() {
320            synchronized (sWidgetLock) {
321                final int cursorCount = mConversationCursor != null ?
322                        mConversationCursor.getCount() : 0;
323                return Math.min(cursorCount, MAX_CONVERSATIONS_COUNT);
324            }
325        }
326
327        /**
328         * @return the {@link RemoteViews} for a specific position in the list.
329         */
330        @Override
331        public RemoteViews getViewAt(int position) {
332            synchronized (sWidgetLock) {
333                // "View more conversations" view.
334                if (mConversationCursor == null
335                        || (mShouldShowViewMore && position >= getConversationCount())) {
336                    return getViewMoreConversationsView();
337                }
338
339                if (!mConversationCursor.moveToPosition(position)) {
340                    // If we ever fail to move to a position, return the "View More conversations"
341                    // view.
342                    LogUtils.e(LOG_TAG,
343                            "Failed to move to position %d in the cursor.", position);
344                    return getViewMoreConversationsView();
345                }
346
347                Conversation conversation = new Conversation(mConversationCursor);
348                String senders = conversation.conversationInfo != null ?
349                        conversation.conversationInfo.sendersInfo : conversation.senders;
350                SendersView.SendersInfo sendersInfo = new SendersView.SendersInfo(senders);
351                mSenderFormatVersion = sendersInfo.version;
352                String sendersString = sendersInfo.text;
353                // Split the senders and status from the instructions.
354                SpannableStringBuilder senderBuilder = new SpannableStringBuilder();
355                SpannableStringBuilder statusBuilder = new SpannableStringBuilder();
356
357                if (mSenderFormatVersion == SendersView.MERGED_FORMATTING) {
358                    Utils.getStyledSenderSnippet(mContext, sendersString, senderBuilder,
359                            statusBuilder, MAX_SENDERS_LENGTH, false, false, false);
360                } else {
361                    senderBuilder.append(sendersString);
362                }
363                // Get styled date.
364                CharSequence date = DateUtils.getRelativeTimeSpanString(
365                        mContext, conversation.dateMs);
366
367                // Load up our remote view.
368                RemoteViews remoteViews = mWidgetConversationViewBuilder.getStyledView(
369                        senderBuilder, statusBuilder, date, filterTag(conversation.subject),
370                        conversation.snippet, conversation.rawFolders, conversation.hasAttachments,
371                        conversation.read, mFolder);
372
373                // On click intent.
374                remoteViews.setOnClickFillInIntent(R.id.widget_conversation,
375                        Utils.createViewConversationIntent(conversation, mFolder, mAccount));
376
377                return remoteViews;
378            }
379        }
380
381        /**
382         * @return the "View more conversations" view.
383         */
384        private RemoteViews getViewMoreConversationsView() {
385            RemoteViews view = new RemoteViews(mContext.getPackageName(), R.layout.widget_loading);
386            view.setTextViewText(
387                    R.id.loading_text, mContext.getText(R.string.view_more_conversations));
388            view.setOnClickFillInIntent(R.id.widget_loading,
389                    Utils.createViewFolderIntent(mFolder, mAccount));
390            return view;
391        }
392
393        @Override
394        public RemoteViews getLoadingView() {
395            RemoteViews view = new RemoteViews(mContext.getPackageName(), R.layout.widget_loading);
396            view.setTextViewText(
397                    R.id.loading_text, mContext.getText(R.string.loading_conversation));
398            return view;
399        }
400
401        @Override
402        public int getViewTypeCount() {
403            return 2;
404        }
405
406        @Override
407        public long getItemId(int position) {
408            return position;
409        }
410
411        @Override
412        public boolean hasStableIds() {
413            return false;
414        }
415
416        @Override
417        public void onLoadComplete(Loader<Cursor> loader, Cursor data) {
418            if (!data.moveToFirst()) {
419                return;
420            }
421            final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
422
423            if (loader == mFolderLoader) {
424                final int unreadCount = data.getInt(UIProvider.FOLDER_UNREAD_COUNT_COLUMN);
425                final String folderName = data.getString(UIProvider.FOLDER_NAME_COLUMN);
426                mFolderCount = data.getInt(UIProvider.FOLDER_TOTAL_COUNT_COLUMN);
427
428                final RemoteViews remoteViews =
429                        new RemoteViews(mContext.getPackageName(), R.layout.widget);
430
431                if (!mFolderInformationShown && !TextUtils.isEmpty(folderName)) {
432                    // We want to do a full update to the widget at least once, as the widget
433                    // manager doesn't cache the state of the remote views when doing a partial
434                    // widget update. This causes the folder name to be shown as blank if the state
435                    // of the widget is restored.
436                    mService.configureValidAccountWidget(
437                            mContext, remoteViews, mAppWidgetId, mAccount, mFolder, folderName);
438                    appWidgetManager.updateAppWidget(mAppWidgetId, remoteViews);
439                    mFolderInformationShown = true;
440                }
441
442                remoteViews.setViewVisibility(R.id.widget_folder, View.VISIBLE);
443                remoteViews.setTextViewText(R.id.widget_folder, folderName);
444                remoteViews.setViewVisibility(R.id.widget_unread_count, View.VISIBLE);
445                remoteViews.setTextViewText(
446                        R.id.widget_unread_count, Utils.getUnreadCountString(mContext, unreadCount));
447
448                appWidgetManager.partiallyUpdateAppWidget(mAppWidgetId, remoteViews);
449            } else if (loader == mConversationCursorLoader) {
450                // We want to cache the new cursor
451                synchronized (sWidgetLock) {
452                    mConversationCursor = data;
453                }
454                appWidgetManager.notifyAppWidgetViewDataChanged(
455                        mAppWidgetId, R.id.conversation_list);
456            }
457        }
458
459        /**
460         * If the subject contains the tag of a mailing-list (text surrounded with []), return the
461         * subject with that tag ellipsized, e.g. "[android-gmail-team] Hello" -> "[andr...] Hello"
462         */
463        private static String filterTag(String subject) {
464            String result = subject;
465            if (subject.length() > 0 && subject.charAt(0) == '[') {
466                int end = subject.indexOf(']');
467                if (end > 0) {
468                    String tag = subject.substring(1, end);
469                    result = "[" + Utils.ellipsize(tag, 7) + "]" + subject.substring(end + 1);
470                }
471            }
472
473            return result;
474        }
475
476        /**
477         * A {@link DelayedTaskHandler} to throttle folder update to a reasonable rate.
478         */
479        private class FolderUpdateHandler extends DelayedTaskHandler {
480            public FolderUpdateHandler(int refreshDelay) {
481                super(Looper.myLooper(), refreshDelay);
482            }
483
484            @Override
485            protected void performTask() {
486                // Start the loader. The cached data will be returned if present.
487                if (mFolderLoader != null) {
488                    mFolderLoader.startLoading();
489                }
490            }
491        }
492    }
493}
494