WidgetService.java revision 525eb4024539661766ac06432d91ef999206cc0d
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.ConversationInfo;
25import com.android.mail.providers.Folder;
26import com.android.mail.providers.UIProvider;
27import com.android.mail.providers.UIProvider.ConversationListQueryParameters;
28import com.android.mail.utils.AccountUtils;
29import com.android.mail.utils.DelayedTaskHandler;
30import com.android.mail.utils.LogTag;
31import com.android.mail.utils.LogUtils;
32import com.android.mail.utils.Utils;
33import com.google.android.common.html.parser.HtmlParser;
34import com.google.android.common.html.parser.HtmlTreeBuilder;
35
36import android.app.PendingIntent;
37import android.appwidget.AppWidgetManager;
38import android.content.Context;
39import android.content.CursorLoader;
40import android.content.Intent;
41import android.content.Loader;
42import android.content.Loader.OnLoadCompleteListener;
43import android.content.SharedPreferences;
44import android.content.res.Resources;
45import android.database.Cursor;
46import android.net.Uri;
47import android.os.Looper;
48import android.support.v4.app.TaskStackBuilder;
49import android.text.SpannableString;
50import android.text.SpannableStringBuilder;
51import android.text.TextUtils;
52import android.text.format.DateUtils;
53import android.text.style.CharacterStyle;
54import android.text.style.TextAppearanceSpan;
55import android.view.View;
56import android.widget.RemoteViews;
57import android.widget.RemoteViewsService;
58
59public class WidgetService extends RemoteViewsService {
60    /**
61     * Lock to avoid race condition between widgets.
62     */
63    private static Object sWidgetLock = new Object();
64
65    private static final String LOG_TAG = LogTag.getLogTag();
66
67    @Override
68    public RemoteViewsFactory onGetViewFactory(Intent intent) {
69        return new MailFactory(getApplicationContext(), intent, this);
70    }
71
72
73    protected void configureValidAccountWidget(Context context, RemoteViews remoteViews,
74            int appWidgetId, Account account, Folder folder, String folderName) {
75        configureValidAccountWidget(context, remoteViews, appWidgetId, account, folder, folderName,
76                WidgetService.class);
77    }
78
79    /**
80     * Modifies the remoteView for the given account and folder.
81     */
82    public static void configureValidAccountWidget(Context context, RemoteViews remoteViews,
83            int appWidgetId, Account account, Folder folder, String folderDisplayName,
84            Class<?> widgetService) {
85        remoteViews.setViewVisibility(R.id.widget_folder, View.VISIBLE);
86
87        // If the folder or account name are empty, we don't want to overwrite the valid data that
88        // had been saved previously.  Since the launcher will save the state of the remote views
89        // we should rely on the fact that valid data has been saved.  But we should still log this,
90        // as it shouldn't happen
91        if (TextUtils.isEmpty(folderDisplayName) || TextUtils.isEmpty(account.name)) {
92            LogUtils.e(LOG_TAG, new Error(),
93                    "Empty folder or account name.  account: %s, folder: %s",
94                    account.name, folderDisplayName);
95        }
96        if (!TextUtils.isEmpty(folderDisplayName)) {
97            remoteViews.setTextViewText(R.id.widget_folder, folderDisplayName);
98        }
99        remoteViews.setViewVisibility(R.id.widget_account, View.VISIBLE);
100
101        if (!TextUtils.isEmpty(account.name)) {
102            remoteViews.setTextViewText(R.id.widget_account, account.name);
103        }
104        remoteViews.setViewVisibility(R.id.widget_unread_count, View.VISIBLE);
105        remoteViews.setViewVisibility(R.id.widget_compose, View.VISIBLE);
106        remoteViews.setViewVisibility(R.id.conversation_list, View.VISIBLE);
107        remoteViews.setViewVisibility(R.id.widget_folder_not_synced, View.GONE);
108        remoteViews.setEmptyView(R.id.conversation_list, R.id.empty_conversation_list);
109
110        WidgetService.configureValidWidgetIntents(context, remoteViews, appWidgetId, account,
111                folder, folderDisplayName, widgetService);
112    }
113
114    public static void configureValidWidgetIntents(Context context, RemoteViews remoteViews,
115            int appWidgetId, Account account, Folder folder, String folderDisplayName,
116            Class<?> serviceClass) {
117        remoteViews.setViewVisibility(R.id.widget_configuration, View.GONE);
118
119
120        // Launch an intent to avoid ANRs
121        final Intent intent = new Intent(context, serviceClass);
122        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
123        intent.putExtra(BaseWidgetProvider.EXTRA_ACCOUNT, account.serialize());
124        intent.putExtra(BaseWidgetProvider.EXTRA_FOLDER, Folder.toString(folder));
125        intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
126        remoteViews.setRemoteAdapter(R.id.conversation_list, intent);
127        // Open mail app when click on header
128        final Intent mailIntent = Utils.createViewFolderIntent(folder, account);
129        PendingIntent clickIntent = PendingIntent.getActivity(context, 0, mailIntent,
130                PendingIntent.FLAG_UPDATE_CURRENT);
131        remoteViews.setOnClickPendingIntent(R.id.widget_header, clickIntent);
132
133        // On click intent for Compose
134        final Intent composeIntent = new Intent();
135        composeIntent.setAction(Intent.ACTION_SEND);
136        composeIntent.putExtra(Utils.EXTRA_ACCOUNT, account.serialize());
137        composeIntent.setData(account.composeIntentUri);
138        composeIntent.putExtra(ComposeActivity.EXTRA_FROM_EMAIL_TASK, true);
139        if (account.composeIntentUri != null) {
140            composeIntent.putExtra(Utils.EXTRA_COMPOSE_URI, account.composeIntentUri);
141        }
142
143        // Build a task stack that forces the conversation list on the stack before the compose
144        // activity.
145        final TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
146        clickIntent = taskStackBuilder.addNextIntent(mailIntent)
147                .addNextIntent(composeIntent)
148                .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
149        remoteViews.setOnClickPendingIntent(R.id.widget_compose, clickIntent);
150
151        // On click intent for Conversation
152        final Intent conversationIntent = new Intent();
153        conversationIntent.setAction(Intent.ACTION_VIEW);
154        clickIntent = PendingIntent.getActivity(context, 0, conversationIntent,
155                PendingIntent.FLAG_UPDATE_CURRENT);
156        remoteViews.setPendingIntentTemplate(R.id.conversation_list, clickIntent);
157    }
158
159    /**
160     * Persists the information about the specified widget.
161     */
162    public static void saveWidgetInformation(Context context, int appWidgetId, Account account,
163                Folder folder) {
164        final SharedPreferences.Editor editor =
165                Persistence.getInstance().getPreferences(context).edit();
166        editor.putString(WidgetProvider.WIDGET_ACCOUNT_PREFIX + appWidgetId,
167                createWidgetPreferenceValue(account, folder));
168        editor.apply();
169    }
170
171    private static String createWidgetPreferenceValue(Account account, Folder folder) {
172        return account.uri.toString() +
173                BaseWidgetProvider.ACCOUNT_FOLDER_PREFERENCE_SEPARATOR + folder.uri.toString();
174
175    }
176
177    /**
178     * Returns true if this widget id has been configured and saved.
179     */
180    public boolean isWidgetConfigured(Context context, int appWidgetId, Account account,
181            Folder folder) {
182        if (isAccountValid(context, account)) {
183            return Persistence.getInstance().getPreferences(context).getString(
184                    BaseWidgetProvider.WIDGET_ACCOUNT_PREFIX + appWidgetId, null) != null;
185        }
186        return false;
187    }
188
189    protected boolean isAccountValid(Context context, Account account) {
190        if (account != null) {
191            Account[] accounts = AccountUtils.getSyncingAccounts(context);
192            for (Account existing : accounts) {
193                if (account != null && existing != null && account.uri.equals(existing.uri)) {
194                    return true;
195                }
196            }
197        }
198        return false;
199    }
200
201    /**
202     * Remote Views Factory for Mail Widget.
203     */
204    protected static class MailFactory
205            implements RemoteViewsService.RemoteViewsFactory, OnLoadCompleteListener<Cursor> {
206        private static final int MAX_CONVERSATIONS_COUNT = 25;
207        private static final int MAX_SENDERS_LENGTH = 25;
208
209        private static final int FOLDER_LOADER_ID = 0;
210        private static final int CONVERSATION_CURSOR_LOADER_ID = 1;
211
212        private final Context mContext;
213        private final int mAppWidgetId;
214        private final Account mAccount;
215        private Folder mFolder;
216        private final WidgetConversationViewBuilder mWidgetConversationViewBuilder;
217        private CursorLoader mConversationCursorLoader;
218        private Cursor mConversationCursor;
219        private CursorLoader mFolderLoader;
220        private FolderUpdateHandler mFolderUpdateHandler;
221        private int mFolderCount;
222        private boolean mShouldShowViewMore;
223        private boolean mFolderInformationShown = false;
224        private WidgetService mService;
225        private String mSendersSplitToken;
226        private String mElidedPaddingToken;
227        private TextAppearanceSpan mUnreadStyle;
228        private TextAppearanceSpan mReadStyle;
229
230        public MailFactory(Context context, Intent intent, WidgetService service) {
231            mContext = context;
232            mAppWidgetId = intent.getIntExtra(
233                    AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
234            mAccount = Account.newinstance(intent.getStringExtra(WidgetProvider.EXTRA_ACCOUNT));
235            mFolder = Folder.fromString(intent.getStringExtra(WidgetProvider.EXTRA_FOLDER));
236            mWidgetConversationViewBuilder = new WidgetConversationViewBuilder(context,
237                    mAccount);
238            mService = service;
239        }
240
241        @Override
242        public void onCreate() {
243
244            // Save the map between widgetId and account to preference
245            saveWidgetInformation(mContext, mAppWidgetId, mAccount, mFolder);
246
247            // If the account of this widget has been removed, we want to update the widget to
248            // "Tap to configure" mode.
249            if (!mService.isWidgetConfigured(mContext, mAppWidgetId, mAccount, mFolder)) {
250                BaseWidgetProvider.updateWidget(mContext, mAppWidgetId, mAccount, mFolder);
251            }
252
253            mFolderInformationShown = false;
254
255            // We want to limit the query result to 25 and don't want these queries to cause network
256            // traffic
257            // We also want this cursor to receive notifications on all changes.  Any change that
258            // the user made locally, the default policy of the UI provider is to not send
259            // notifications for.  But in this case, since the widget is not using the
260            // ConversationCursor instance that the UI is using, the widget would not be updated.
261            final Uri.Builder builder = mFolder.conversationListUri.buildUpon();
262            final String maxConversations = Integer.toString(MAX_CONVERSATIONS_COUNT);
263            final Uri widgetConversationQueryUri = builder
264                    .appendQueryParameter(ConversationListQueryParameters.LIMIT, maxConversations)
265                    .appendQueryParameter(ConversationListQueryParameters.USE_NETWORK,
266                            Boolean.FALSE.toString())
267                    .appendQueryParameter(ConversationListQueryParameters.ALL_NOTIFICATIONS,
268                            Boolean.TRUE.toString()).build();
269
270            final Resources res = mContext.getResources();
271            mConversationCursorLoader = new CursorLoader(mContext, widgetConversationQueryUri,
272                    UIProvider.CONVERSATION_PROJECTION, null, null, null);
273            mConversationCursorLoader.registerListener(CONVERSATION_CURSOR_LOADER_ID, this);
274            mConversationCursorLoader.setUpdateThrottle(
275                    res.getInteger(R.integer.widget_refresh_delay_ms));
276            mConversationCursorLoader.startLoading();
277            mSendersSplitToken = res.getString(R.string.senders_split_token);
278            mElidedPaddingToken = res.getString(R.string.elided_padding_token);
279            mFolderLoader = new CursorLoader(mContext, mFolder.uri, UIProvider.FOLDERS_PROJECTION,
280                    null, null, null);
281            mFolderLoader.registerListener(FOLDER_LOADER_ID, this);
282            mFolderUpdateHandler = new FolderUpdateHandler(
283                    res.getInteger(R.integer.widget_folder_refresh_delay_ms));
284            mFolderUpdateHandler.scheduleTask();
285
286        }
287
288        @Override
289        public void onDestroy() {
290            synchronized (sWidgetLock) {
291                if (mConversationCursorLoader != null) {
292                    mConversationCursorLoader.reset();
293                    mConversationCursorLoader.unregisterListener(this);
294                    mConversationCursorLoader = null;
295                }
296
297                // The Loader should close the cursor, so just unset the reference
298                // to it here.
299                mConversationCursor = null;
300            }
301
302            if (mFolderLoader != null) {
303                mFolderLoader.reset();
304                mFolderLoader.unregisterListener(this);
305                mFolderLoader = null;
306            }
307        }
308
309        @Override
310        public void onDataSetChanged() {
311            // We are not using this as signal to requery the cursor.  The query will be started
312            // in the following ways:
313            // 1) The Service is started and the loader is started in onCreate()
314            //       This will happen when the service is not running, and
315            //       AppWidgetManager#notifyAppWidgetViewDataChanged() is called
316            // 2) The service is running, with a previously created loader.  The loader is watching
317            //    for updates from the existing cursor.  If one is seen, the loader will load a new
318            //    cursor in the background.
319            mFolderUpdateHandler.scheduleTask();
320        }
321
322        /**
323         * Returns the number of items should be shown in the widget list.  This method also updates
324         * the boolean that indicates whether the "show more" item should be shown.
325         * @return the number of items to be displayed in the list.
326         */
327        @Override
328        public int getCount() {
329            synchronized (sWidgetLock) {
330                final int count = getConversationCount();
331                final int cursorCount = mConversationCursor != null ?
332                        mConversationCursor.getCount() : 0;
333                mShouldShowViewMore = count < cursorCount || count < mFolderCount;
334                return count + (mShouldShowViewMore ? 1 : 0);
335            }
336        }
337
338        /**
339         * Returns the number of conversations that should be shown in the widget.  This method
340         * doesn't update the boolean that indicates that the "show more" item should be included
341         * in the list.
342         * @return
343         */
344        private int getConversationCount() {
345            synchronized (sWidgetLock) {
346                final int cursorCount = mConversationCursor != null ?
347                        mConversationCursor.getCount() : 0;
348                return Math.min(cursorCount, MAX_CONVERSATIONS_COUNT);
349            }
350        }
351
352        /**
353         * @return the {@link RemoteViews} for a specific position in the list.
354         */
355        @Override
356        public RemoteViews getViewAt(int position) {
357            synchronized (sWidgetLock) {
358                // "View more conversations" view.
359                if (mConversationCursor == null || mConversationCursor.isClosed()
360                        || (mShouldShowViewMore && position >= getConversationCount())) {
361                    return getViewMoreConversationsView();
362                }
363
364                if (!mConversationCursor.moveToPosition(position)) {
365                    // If we ever fail to move to a position, return the
366                    // "View More conversations"
367                    // view.
368                    LogUtils.e(LOG_TAG, "Failed to move to position %d in the cursor.", position);
369                    return getViewMoreConversationsView();
370                }
371
372                Conversation conversation = new Conversation(mConversationCursor);
373                // Split the senders and status from the instructions.
374                SpannableStringBuilder senderBuilder = new SpannableStringBuilder();
375                SpannableStringBuilder statusBuilder = new SpannableStringBuilder();
376
377                if (conversation.conversationInfo != null) {
378                    senderBuilder = ellipsizeStyledSenders(conversation.conversationInfo,
379                            MAX_SENDERS_LENGTH, SendersView.format(mContext,
380                                    conversation.conversationInfo, "", MAX_SENDERS_LENGTH,
381                                    new HtmlParser(), new HtmlTreeBuilder()));
382                } else {
383                    senderBuilder.append(conversation.senders);
384                    senderBuilder.setSpan(conversation.read ? getReadStyle() : getUnreadStyle(), 0,
385                            senderBuilder.length(), 0);
386                }
387                // Get styled date.
388                CharSequence date = DateUtils.getRelativeTimeSpanString(mContext,
389                        conversation.dateMs);
390
391                // Load up our remote view.
392                RemoteViews remoteViews = mWidgetConversationViewBuilder.getStyledView(
393                        statusBuilder, date, conversation, mFolder, senderBuilder,
394                        filterTag(conversation.subject));
395
396                // On click intent.
397                remoteViews.setOnClickFillInIntent(R.id.widget_conversation,
398                        Utils.createViewConversationIntent(conversation, mFolder, mAccount));
399
400                return remoteViews;
401            }
402        }
403
404        private CharacterStyle getUnreadStyle() {
405            if (mUnreadStyle == null) {
406                mUnreadStyle = new TextAppearanceSpan(mContext,
407                        R.style.SendersUnreadTextAppearance);
408            }
409            return CharacterStyle.wrap(mUnreadStyle);
410        }
411
412        private CharacterStyle getReadStyle() {
413            if (mReadStyle == null) {
414                mReadStyle = new TextAppearanceSpan(mContext, R.style.SendersReadTextAppearance);
415            }
416            return CharacterStyle.wrap(mReadStyle);
417        }
418
419        private SpannableStringBuilder ellipsizeStyledSenders(ConversationInfo info, int maxChars,
420                SpannableString[] styledSenders) {
421            SpannableStringBuilder builder = new SpannableStringBuilder();
422            SpannableString prevSender = null;
423            for (SpannableString sender : styledSenders) {
424                if (sender == null) {
425                    LogUtils.e(LOG_TAG, "null sender while iterating over styledSenders");
426                    continue;
427                }
428                CharacterStyle[] spans = sender.getSpans(0, sender.length(), CharacterStyle.class);
429                if (SendersView.sElidedString.equals(sender.toString())) {
430                    prevSender = sender;
431                    sender = copyStyles(spans, mElidedPaddingToken + sender + mElidedPaddingToken);
432                } else if (builder.length() > 0
433                        && (prevSender == null || !SendersView.sElidedString.equals(prevSender
434                                .toString()))) {
435                    prevSender = sender;
436                    sender = copyStyles(spans, mSendersSplitToken + sender);
437                } else {
438                    prevSender = sender;
439                }
440                builder.append(sender);
441            }
442            return builder;
443        }
444
445        private SpannableString copyStyles(CharacterStyle[] spans, CharSequence newText) {
446            SpannableString s = new SpannableString(newText);
447            if (spans != null && spans.length > 0) {
448                s.setSpan(spans[0], 0, s.length(), 0);
449            }
450            return s;
451        }
452
453        /**
454         * @return the "View more conversations" view.
455         */
456        private RemoteViews getViewMoreConversationsView() {
457            RemoteViews view = new RemoteViews(mContext.getPackageName(), R.layout.widget_loading);
458            view.setTextViewText(
459                    R.id.loading_text, mContext.getText(R.string.view_more_conversations));
460            view.setOnClickFillInIntent(R.id.widget_loading,
461                    Utils.createViewFolderIntent(mFolder, mAccount));
462            return view;
463        }
464
465        @Override
466        public RemoteViews getLoadingView() {
467            RemoteViews view = new RemoteViews(mContext.getPackageName(), R.layout.widget_loading);
468            view.setTextViewText(
469                    R.id.loading_text, mContext.getText(R.string.loading_conversation));
470            return view;
471        }
472
473        @Override
474        public int getViewTypeCount() {
475            return 2;
476        }
477
478        @Override
479        public long getItemId(int position) {
480            return position;
481        }
482
483        @Override
484        public boolean hasStableIds() {
485            return false;
486        }
487
488        @Override
489        public void onLoadComplete(Loader<Cursor> loader, Cursor data) {
490            final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
491
492            if (loader == mFolderLoader) {
493                if (!isDataValid(data)) {
494                    return;
495                }
496
497                final int unreadCount = data.getInt(UIProvider.FOLDER_UNREAD_COUNT_COLUMN);
498                final String folderName = data.getString(UIProvider.FOLDER_NAME_COLUMN);
499                mFolderCount = data.getInt(UIProvider.FOLDER_TOTAL_COUNT_COLUMN);
500
501                final RemoteViews remoteViews =
502                        new RemoteViews(mContext.getPackageName(), R.layout.widget);
503
504                if (!mFolderInformationShown && !TextUtils.isEmpty(folderName) &&
505                        !TextUtils.isEmpty(mAccount.name)) {
506                    // We want to do a full update to the widget at least once, as the widget
507                    // manager doesn't cache the state of the remote views when doing a partial
508                    // widget update. This causes the folder name to be shown as blank if the state
509                    // of the widget is restored.
510                    mService.configureValidAccountWidget(
511                            mContext, remoteViews, mAppWidgetId, mAccount, mFolder, folderName);
512                    appWidgetManager.updateAppWidget(mAppWidgetId, remoteViews);
513                    mFolderInformationShown = true;
514                }
515
516                // There is no reason to overwrite a valid non-null folder name with an empty string
517                if (!TextUtils.isEmpty(folderName)) {
518                    remoteViews.setViewVisibility(R.id.widget_folder, View.VISIBLE);
519                    remoteViews.setTextViewText(R.id.widget_folder, folderName);
520                } else {
521                    LogUtils.e(LOG_TAG, "Empty folder name");
522                }
523                if (!TextUtils.isEmpty(mAccount.name)) {
524                    remoteViews.setTextViewText(R.id.widget_account, mAccount.name);
525                }
526                remoteViews.setViewVisibility(R.id.widget_unread_count, View.VISIBLE);
527                remoteViews.setTextViewText(R.id.widget_unread_count,
528                        Utils.getUnreadCountString(mContext, unreadCount));
529
530                appWidgetManager.partiallyUpdateAppWidget(mAppWidgetId, remoteViews);
531            } else if (loader == mConversationCursorLoader) {
532
533                // We want to cache the new cursor
534                synchronized (sWidgetLock) {
535                    if (!isDataValid(data)) {
536                        mConversationCursor = null;
537                    } else {
538                        mConversationCursor = data;
539                    }
540                }
541                appWidgetManager.notifyAppWidgetViewDataChanged(
542                        mAppWidgetId, R.id.conversation_list);
543            }
544        }
545
546        /**
547         * Returns a boolean indicating whether this cursor has valid data.
548         * Note: This seeks to the first position in the cursor
549         */
550        private boolean isDataValid(Cursor cursor) {
551            return cursor != null && !cursor.isClosed() && cursor.moveToFirst();
552        }
553
554        /**
555         * If the subject contains the tag of a mailing-list (text surrounded with []), return the
556         * subject with that tag ellipsized, e.g. "[android-gmail-team] Hello" -> "[andr...] Hello"
557         */
558        private static String filterTag(String subject) {
559            String result = subject;
560            if (subject.length() > 0 && subject.charAt(0) == '[') {
561                int end = subject.indexOf(']');
562                if (end > 0) {
563                    String tag = subject.substring(1, end);
564                    result = "[" + Utils.ellipsize(tag, 7) + "]" + subject.substring(end + 1);
565                }
566            }
567
568            return result;
569        }
570
571        /**
572         * A {@link DelayedTaskHandler} to throttle folder update to a reasonable rate.
573         */
574        private class FolderUpdateHandler extends DelayedTaskHandler {
575            public FolderUpdateHandler(int refreshDelay) {
576                super(Looper.myLooper(), refreshDelay);
577            }
578
579            @Override
580            protected void performTask() {
581                // Start the loader. The cached data will be returned if present.
582                if (mFolderLoader != null) {
583                    mFolderLoader.startLoading();
584                }
585            }
586        }
587    }
588}
589