WidgetService.java revision f9568dcc8ebf8d975c9a9c136fe2b15f58fc8930
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 = Persistence.getPreferences(context).edit();
165        editor.putString(WidgetProvider.WIDGET_ACCOUNT_PREFIX + appWidgetId,
166                createWidgetPreferenceValue(account, folder));
167        editor.apply();
168    }
169
170    private static String createWidgetPreferenceValue(Account account, Folder folder) {
171        return account.uri.toString() +
172                BaseWidgetProvider.ACCOUNT_FOLDER_PREFERENCE_SEPARATOR + folder.uri.toString();
173
174    }
175
176    /**
177     * Returns true if this widget id has been configured and saved.
178     */
179    public boolean isWidgetConfigured(Context context, int appWidgetId, Account account,
180            Folder folder) {
181        if (isAccountValid(context, account)) {
182            return Persistence.getPreferences(context).getString(
183                    BaseWidgetProvider.WIDGET_ACCOUNT_PREFIX + appWidgetId, null) != null;
184        }
185        return false;
186    }
187
188    protected boolean isAccountValid(Context context, Account account) {
189        if (account != null) {
190            Account[] accounts = AccountUtils.getSyncingAccounts(context);
191            for (Account existing : accounts) {
192                if (account != null && existing != null && account.uri.equals(existing.uri)) {
193                    return true;
194                }
195            }
196        }
197        return false;
198    }
199
200    /**
201     * Remote Views Factory for Mail Widget.
202     */
203    protected static class MailFactory
204            implements RemoteViewsService.RemoteViewsFactory, OnLoadCompleteListener<Cursor> {
205        private static final int MAX_CONVERSATIONS_COUNT = 25;
206        private static final int MAX_SENDERS_LENGTH = 25;
207
208        private static final int FOLDER_LOADER_ID = 0;
209        private static final int CONVERSATION_CURSOR_LOADER_ID = 1;
210
211        private final Context mContext;
212        private final int mAppWidgetId;
213        private final Account mAccount;
214        private Folder mFolder;
215        private final WidgetConversationViewBuilder mWidgetConversationViewBuilder;
216        private CursorLoader mConversationCursorLoader;
217        private Cursor mConversationCursor;
218        private CursorLoader mFolderLoader;
219        private FolderUpdateHandler mFolderUpdateHandler;
220        private int mFolderCount;
221        private boolean mShouldShowViewMore;
222        private boolean mFolderInformationShown = false;
223        private WidgetService mService;
224        private String mSendersSplitToken;
225        private String mElidedPaddingToken;
226        private TextAppearanceSpan mUnreadStyle;
227        private TextAppearanceSpan mReadStyle;
228
229        public MailFactory(Context context, Intent intent, WidgetService service) {
230            mContext = context;
231            mAppWidgetId = intent.getIntExtra(
232                    AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
233            mAccount = Account.newinstance(intent.getStringExtra(WidgetProvider.EXTRA_ACCOUNT));
234            mFolder = Folder.fromString(intent.getStringExtra(WidgetProvider.EXTRA_FOLDER));
235            mWidgetConversationViewBuilder = new WidgetConversationViewBuilder(context,
236                    mAccount);
237            mService = service;
238        }
239
240        @Override
241        public void onCreate() {
242
243            // Save the map between widgetId and account to preference
244            saveWidgetInformation(mContext, mAppWidgetId, mAccount, mFolder);
245
246            // If the account of this widget has been removed, we want to update the widget to
247            // "Tap to configure" mode.
248            if (!mService.isWidgetConfigured(mContext, mAppWidgetId, mAccount, mFolder)) {
249                BaseWidgetProvider.updateWidget(mContext, mAppWidgetId, mAccount, mFolder);
250            }
251
252            mFolderInformationShown = false;
253
254            // We want to limit the query result to 25 and don't want these queries to cause network
255            // traffic
256            // We also want this cursor to receive notifications on all changes.  Any change that
257            // the user made locally, the default policy of the UI provider is to not send
258            // notifications for.  But in this case, since the widget is not using the
259            // ConversationCursor instance that the UI is using, the widget would not be updated.
260            final Uri.Builder builder = mFolder.conversationListUri.buildUpon();
261            final String maxConversations = Integer.toString(MAX_CONVERSATIONS_COUNT);
262            final Uri widgetConversationQueryUri = builder
263                    .appendQueryParameter(ConversationListQueryParameters.LIMIT, maxConversations)
264                    .appendQueryParameter(ConversationListQueryParameters.USE_NETWORK,
265                            Boolean.FALSE.toString())
266                    .appendQueryParameter(ConversationListQueryParameters.ALL_NOTIFICATIONS,
267                            Boolean.TRUE.toString()).build();
268
269            final Resources res = mContext.getResources();
270            mConversationCursorLoader = new CursorLoader(mContext, widgetConversationQueryUri,
271                    UIProvider.CONVERSATION_PROJECTION, null, null, null);
272            mConversationCursorLoader.registerListener(CONVERSATION_CURSOR_LOADER_ID, this);
273            mConversationCursorLoader.setUpdateThrottle(
274                    res.getInteger(R.integer.widget_refresh_delay_ms));
275            mConversationCursorLoader.startLoading();
276            mSendersSplitToken = res.getString(R.string.senders_split_token);
277            mElidedPaddingToken = res.getString(R.string.elided_padding_token);
278            mFolderLoader = new CursorLoader(mContext, mFolder.uri, UIProvider.FOLDERS_PROJECTION,
279                    null, null, null);
280            mFolderLoader.registerListener(FOLDER_LOADER_ID, this);
281            mFolderUpdateHandler = new FolderUpdateHandler(
282                    res.getInteger(R.integer.widget_folder_refresh_delay_ms));
283            mFolderUpdateHandler.scheduleTask();
284
285        }
286
287        @Override
288        public void onDestroy() {
289            synchronized (sWidgetLock) {
290                if (mConversationCursorLoader != null) {
291                    mConversationCursorLoader.reset();
292                    mConversationCursorLoader.unregisterListener(this);
293                    mConversationCursorLoader = null;
294                }
295
296                // The Loader should close the cursor, so just unset the reference
297                // to it here.
298                mConversationCursor = null;
299            }
300
301            if (mFolderLoader != null) {
302                mFolderLoader.reset();
303                mFolderLoader.unregisterListener(this);
304                mFolderLoader = null;
305            }
306        }
307
308        @Override
309        public void onDataSetChanged() {
310            // We are not using this as signal to requery the cursor.  The query will be started
311            // in the following ways:
312            // 1) The Service is started and the loader is started in onCreate()
313            //       This will happen when the service is not running, and
314            //       AppWidgetManager#notifyAppWidgetViewDataChanged() is called
315            // 2) The service is running, with a previously created loader.  The loader is watching
316            //    for updates from the existing cursor.  If one is seen, the loader will load a new
317            //    cursor in the background.
318            mFolderUpdateHandler.scheduleTask();
319        }
320
321        /**
322         * Returns the number of items should be shown in the widget list.  This method also updates
323         * the boolean that indicates whether the "show more" item should be shown.
324         * @return the number of items to be displayed in the list.
325         */
326        @Override
327        public int getCount() {
328            synchronized (sWidgetLock) {
329                final int count = getConversationCount();
330                final int cursorCount = mConversationCursor != null ?
331                        mConversationCursor.getCount() : 0;
332                mShouldShowViewMore = count < cursorCount || count < mFolderCount;
333                return count + (mShouldShowViewMore ? 1 : 0);
334            }
335        }
336
337        /**
338         * Returns the number of conversations that should be shown in the widget.  This method
339         * doesn't update the boolean that indicates that the "show more" item should be included
340         * in the list.
341         * @return
342         */
343        private int getConversationCount() {
344            synchronized (sWidgetLock) {
345                final int cursorCount = mConversationCursor != null ?
346                        mConversationCursor.getCount() : 0;
347                return Math.min(cursorCount, MAX_CONVERSATIONS_COUNT);
348            }
349        }
350
351        /**
352         * @return the {@link RemoteViews} for a specific position in the list.
353         */
354        @Override
355        public RemoteViews getViewAt(int position) {
356            synchronized (sWidgetLock) {
357                // "View more conversations" view.
358                if (mConversationCursor == null || mConversationCursor.isClosed()
359                        || (mShouldShowViewMore && position >= getConversationCount())) {
360                    return getViewMoreConversationsView();
361                }
362
363                if (!mConversationCursor.moveToPosition(position)) {
364                    // If we ever fail to move to a position, return the
365                    // "View More conversations"
366                    // view.
367                    LogUtils.e(LOG_TAG, "Failed to move to position %d in the cursor.", position);
368                    return getViewMoreConversationsView();
369                }
370
371                Conversation conversation = new Conversation(mConversationCursor);
372                // Split the senders and status from the instructions.
373                SpannableStringBuilder senderBuilder = new SpannableStringBuilder();
374                SpannableStringBuilder statusBuilder = new SpannableStringBuilder();
375
376                if (conversation.conversationInfo != null) {
377                    senderBuilder = ellipsizeStyledSenders(conversation.conversationInfo,
378                            MAX_SENDERS_LENGTH, SendersView.format(mContext,
379                                    conversation.conversationInfo, "", MAX_SENDERS_LENGTH,
380                                    new HtmlParser(), new HtmlTreeBuilder()));
381                } else {
382                    senderBuilder.append(conversation.senders);
383                    senderBuilder.setSpan(conversation.read ? getReadStyle() : getUnreadStyle(), 0,
384                            senderBuilder.length(), 0);
385                }
386                // Get styled date.
387                CharSequence date = DateUtils.getRelativeTimeSpanString(mContext,
388                        conversation.dateMs);
389
390                // Load up our remote view.
391                RemoteViews remoteViews = mWidgetConversationViewBuilder.getStyledView(
392                        statusBuilder, date, conversation, mFolder, senderBuilder,
393                        filterTag(conversation.subject));
394
395                // On click intent.
396                remoteViews.setOnClickFillInIntent(R.id.widget_conversation,
397                        Utils.createViewConversationIntent(conversation, mFolder, mAccount));
398
399                return remoteViews;
400            }
401        }
402
403        private CharacterStyle getUnreadStyle() {
404            if (mUnreadStyle == null) {
405                mUnreadStyle = new TextAppearanceSpan(mContext,
406                        R.style.SendersUnreadTextAppearance);
407            }
408            return CharacterStyle.wrap(mUnreadStyle);
409        }
410
411        private CharacterStyle getReadStyle() {
412            if (mReadStyle == null) {
413                mReadStyle = new TextAppearanceSpan(mContext, R.style.SendersReadTextAppearance);
414            }
415            return CharacterStyle.wrap(mReadStyle);
416        }
417
418        private SpannableStringBuilder ellipsizeStyledSenders(ConversationInfo info, int maxChars,
419                SpannableString[] styledSenders) {
420            SpannableStringBuilder builder = new SpannableStringBuilder();
421            SpannableString prevSender = null;
422            for (SpannableString sender : styledSenders) {
423                if (sender == null) {
424                    LogUtils.e(LOG_TAG, "null sender while iterating over styledSenders");
425                    continue;
426                }
427                CharacterStyle[] spans = sender.getSpans(0, sender.length(), CharacterStyle.class);
428                if (SendersView.sElidedString.equals(sender.toString())) {
429                    prevSender = sender;
430                    sender = copyStyles(spans, mElidedPaddingToken + sender + mElidedPaddingToken);
431                } else if (builder.length() > 0
432                        && (prevSender == null || !SendersView.sElidedString.equals(prevSender
433                                .toString()))) {
434                    prevSender = sender;
435                    sender = copyStyles(spans, mSendersSplitToken + sender);
436                } else {
437                    prevSender = sender;
438                }
439                builder.append(sender);
440            }
441            return builder;
442        }
443
444        private SpannableString copyStyles(CharacterStyle[] spans, CharSequence newText) {
445            SpannableString s = new SpannableString(newText);
446            if (spans != null && spans.length > 0) {
447                s.setSpan(spans[0], 0, s.length(), 0);
448            }
449            return s;
450        }
451
452        /**
453         * @return the "View more conversations" view.
454         */
455        private RemoteViews getViewMoreConversationsView() {
456            RemoteViews view = new RemoteViews(mContext.getPackageName(), R.layout.widget_loading);
457            view.setTextViewText(
458                    R.id.loading_text, mContext.getText(R.string.view_more_conversations));
459            view.setOnClickFillInIntent(R.id.widget_loading,
460                    Utils.createViewFolderIntent(mFolder, mAccount));
461            return view;
462        }
463
464        @Override
465        public RemoteViews getLoadingView() {
466            RemoteViews view = new RemoteViews(mContext.getPackageName(), R.layout.widget_loading);
467            view.setTextViewText(
468                    R.id.loading_text, mContext.getText(R.string.loading_conversation));
469            return view;
470        }
471
472        @Override
473        public int getViewTypeCount() {
474            return 2;
475        }
476
477        @Override
478        public long getItemId(int position) {
479            return position;
480        }
481
482        @Override
483        public boolean hasStableIds() {
484            return false;
485        }
486
487        @Override
488        public void onLoadComplete(Loader<Cursor> loader, Cursor data) {
489            final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
490
491            if (loader == mFolderLoader) {
492                if (!isDataValid(data)) {
493                    return;
494                }
495
496                final int unreadCount = data.getInt(UIProvider.FOLDER_UNREAD_COUNT_COLUMN);
497                final String folderName = data.getString(UIProvider.FOLDER_NAME_COLUMN);
498                mFolderCount = data.getInt(UIProvider.FOLDER_TOTAL_COUNT_COLUMN);
499
500                final RemoteViews remoteViews =
501                        new RemoteViews(mContext.getPackageName(), R.layout.widget);
502
503                if (!mFolderInformationShown && !TextUtils.isEmpty(folderName) &&
504                        !TextUtils.isEmpty(mAccount.name)) {
505                    // We want to do a full update to the widget at least once, as the widget
506                    // manager doesn't cache the state of the remote views when doing a partial
507                    // widget update. This causes the folder name to be shown as blank if the state
508                    // of the widget is restored.
509                    mService.configureValidAccountWidget(
510                            mContext, remoteViews, mAppWidgetId, mAccount, mFolder, folderName);
511                    appWidgetManager.updateAppWidget(mAppWidgetId, remoteViews);
512                    mFolderInformationShown = true;
513                }
514
515                // There is no reason to overwrite a valid non-null folder name with an empty string
516                if (!TextUtils.isEmpty(folderName)) {
517                    remoteViews.setViewVisibility(R.id.widget_folder, View.VISIBLE);
518                    remoteViews.setTextViewText(R.id.widget_folder, folderName);
519                } else {
520                    LogUtils.e(LOG_TAG, "Empty folder name");
521                }
522                if (!TextUtils.isEmpty(mAccount.name)) {
523                    remoteViews.setTextViewText(R.id.widget_account, mAccount.name);
524                }
525                remoteViews.setViewVisibility(R.id.widget_unread_count, View.VISIBLE);
526                remoteViews.setTextViewText(R.id.widget_unread_count,
527                        Utils.getUnreadCountString(mContext, unreadCount));
528
529                appWidgetManager.partiallyUpdateAppWidget(mAppWidgetId, remoteViews);
530            } else if (loader == mConversationCursorLoader) {
531
532                // We want to cache the new cursor
533                synchronized (sWidgetLock) {
534                    if (!isDataValid(data)) {
535                        mConversationCursor = null;
536                    } else {
537                        mConversationCursor = data;
538                    }
539                }
540                appWidgetManager.notifyAppWidgetViewDataChanged(
541                        mAppWidgetId, R.id.conversation_list);
542            }
543        }
544
545        /**
546         * Returns a boolean indicating whether this cursor has valid data.
547         * Note: This seeks to the first position in the cursor
548         */
549        private boolean isDataValid(Cursor cursor) {
550            return cursor != null && !cursor.isClosed() && cursor.moveToFirst();
551        }
552
553        /**
554         * If the subject contains the tag of a mailing-list (text surrounded with []), return the
555         * subject with that tag ellipsized, e.g. "[android-gmail-team] Hello" -> "[andr...] Hello"
556         */
557        private static String filterTag(String subject) {
558            String result = subject;
559            if (subject.length() > 0 && subject.charAt(0) == '[') {
560                int end = subject.indexOf(']');
561                if (end > 0) {
562                    String tag = subject.substring(1, end);
563                    result = "[" + Utils.ellipsize(tag, 7) + "]" + subject.substring(end + 1);
564                }
565            }
566
567            return result;
568        }
569
570        /**
571         * A {@link DelayedTaskHandler} to throttle folder update to a reasonable rate.
572         */
573        private class FolderUpdateHandler extends DelayedTaskHandler {
574            public FolderUpdateHandler(int refreshDelay) {
575                super(Looper.myLooper(), refreshDelay);
576            }
577
578            @Override
579            protected void performTask() {
580                // Start the loader. The cached data will be returned if present.
581                if (mFolderLoader != null) {
582                    mFolderLoader.startLoading();
583                }
584            }
585        }
586    }
587}
588