Folder.java revision 91f8cef976aba06be9cfa2570692c7b7a96d21f0
1/*******************************************************************************
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.providers;
19
20import android.content.Context;
21import android.content.CursorLoader;
22import android.database.Cursor;
23import android.graphics.drawable.PaintDrawable;
24import android.net.Uri;
25import android.net.Uri.Builder;
26import android.os.Parcel;
27import android.os.Parcelable;
28import android.text.TextUtils;
29import android.view.View;
30
31import com.android.mail.utils.LogUtils;
32
33import com.google.common.collect.ImmutableList;
34import com.google.common.collect.Lists;
35import com.google.common.collect.Maps;
36
37import java.util.ArrayList;
38import java.util.Collection;
39import java.util.Collections;
40import java.util.List;
41import java.util.Map;
42import java.util.regex.Pattern;
43
44/**
45 * A folder is a collection of conversations, and perhaps other folders.
46 */
47public class Folder implements Parcelable, Comparable<Folder> {
48    /**
49     *
50     */
51    private static final String FOLDER_UNINITIALIZED = "Uninitialized!";
52
53    // Try to match the order of members with the order of constants in UIProvider.
54
55    /**
56     * Unique id of this folder.
57     */
58    public int id;
59
60    /**
61     * The content provider URI that returns this folder for this account.
62     */
63    public Uri uri;
64
65    /**
66     * The human visible name for this folder.
67     */
68    public String name;
69
70    /**
71     * The possible capabilities that this folder supports.
72     */
73    public int capabilities;
74
75    /**
76     * Whether or not this folder has children folders.
77     */
78    public boolean hasChildren;
79
80    /**
81     * How large the synchronization window is: how many days worth of data is retained on the
82     * device.
83     */
84    public int syncWindow;
85
86    /**
87     * The content provider URI to return the list of conversations in this
88     * folder.
89     */
90    public Uri conversationListUri;
91
92    /**
93     * The content provider URI to return the list of child folders of this folder.
94     */
95    public Uri childFoldersListUri;
96
97    /**
98     * The number of messages that are unread in this folder.
99     */
100    public int unreadCount;
101
102    /**
103     * The total number of messages in this folder.
104     */
105    public int totalCount;
106
107    /**
108     * The content provider URI to force a refresh of this folder.
109     */
110    public Uri refreshUri;
111
112    /**
113     * The current sync status of the folder
114     */
115    public int syncStatus;
116
117    /**
118     * The result of the last sync for this folder
119     */
120    public int lastSyncResult;
121
122    /**
123     * Folder type. 0 is default.
124     */
125    public int type;
126
127    /**
128     * Icon for this folder; 0 implies no icon.
129     */
130    public long iconResId;
131
132    public String bgColor;
133    public String fgColor;
134
135    /**
136     * The content provider URI to request additional conversations
137     */
138    public Uri loadMoreUri;
139
140    /**
141     * Parent folder of this folder, or null if there is none. This is set as
142     * part of the execution of the application and not obtained or stored via
143     * the provider.
144     */
145    public Folder parent;
146
147    /**
148     * Total number of members that comprise an instance of a folder. This is
149     * the number of members that need to be serialized or parceled.
150     */
151    private static final int NUMBER_MEMBERS = UIProvider.FOLDERS_PROJECTION.length + 1;
152
153    /**
154     * Used only for debugging.
155     */
156    private static final String LOG_TAG = new LogUtils().getLogTag();
157
158    /** An immutable, empty conversation list */
159    public static final Collection<Folder> EMPTY = Collections.emptyList();
160
161    /**
162     * Examples of expected format for the joined folder strings
163     *
164     * Example of a joined folder string:
165     *       630107622^*^^i^*^^i^*^0
166     *       <id>^*^<canonical name>^*^<name>^*^<color index>
167     *
168     * The sqlite queries will return a list of folder strings separated with "^**^"
169     * Example of a query result:
170     *     630107622^*^^i^*^^i^*^0^**^630107626^*^^u^*^^u^*^0^**^630107627^*^^f^*^^f^*^0
171     */
172    private static final String FOLDER_COMPONENT_SEPARATOR = "^*^";
173    private static final Pattern FOLDER_COMPONENT_SEPARATOR_PATTERN =
174            Pattern.compile("\\^\\*\\^");
175
176    public static final String FOLDER_SEPARATOR = "^**^";
177    public static final Pattern FOLDER_SEPARATOR_PATTERN =
178            Pattern.compile("\\^\\*\\*\\^");
179
180    public Folder(Parcel in) {
181        id = in.readInt();
182        uri = in.readParcelable(null);
183        name = in.readString();
184        capabilities = in.readInt();
185        // 1 for true, 0 for false.
186        hasChildren = in.readInt() == 1;
187        syncWindow = in.readInt();
188        conversationListUri = in.readParcelable(null);
189        childFoldersListUri = in.readParcelable(null);
190        unreadCount = in.readInt();
191        totalCount = in.readInt();
192        refreshUri = in.readParcelable(null);
193        syncStatus = in.readInt();
194        lastSyncResult = in.readInt();
195        type = in.readInt();
196        iconResId = in.readLong();
197        bgColor = in.readString();
198        fgColor = in.readString();
199        loadMoreUri = in.readParcelable(null);
200        parent = in.readParcelable(null);
201     }
202
203    public Folder(Cursor cursor) {
204        id = cursor.getInt(UIProvider.FOLDER_ID_COLUMN);
205        uri = Uri.parse(cursor.getString(UIProvider.FOLDER_URI_COLUMN));
206        name = cursor.getString(UIProvider.FOLDER_NAME_COLUMN);
207        capabilities = cursor.getInt(UIProvider.FOLDER_CAPABILITIES_COLUMN);
208        // 1 for true, 0 for false.
209        hasChildren = cursor.getInt(UIProvider.FOLDER_HAS_CHILDREN_COLUMN) == 1;
210        syncWindow = cursor.getInt(UIProvider.FOLDER_SYNC_WINDOW_COLUMN);
211        String convList = cursor.getString(UIProvider.FOLDER_CONVERSATION_LIST_URI_COLUMN);
212        conversationListUri = !TextUtils.isEmpty(convList) ? Uri.parse(convList) : null;
213        String childList = cursor.getString(UIProvider.FOLDER_CHILD_FOLDERS_LIST_COLUMN);
214        childFoldersListUri = (hasChildren && !TextUtils.isEmpty(childList)) ? Uri.parse(childList)
215                : null;
216        unreadCount = cursor.getInt(UIProvider.FOLDER_UNREAD_COUNT_COLUMN);
217        totalCount = cursor.getInt(UIProvider.FOLDER_TOTAL_COUNT_COLUMN);
218        String refresh = cursor.getString(UIProvider.FOLDER_REFRESH_URI_COLUMN);
219        refreshUri = !TextUtils.isEmpty(refresh) ? Uri.parse(refresh) : null;
220        syncStatus = cursor.getInt(UIProvider.FOLDER_SYNC_STATUS_COLUMN);
221        lastSyncResult = cursor.getInt(UIProvider.FOLDER_LAST_SYNC_RESULT_COLUMN);
222        type = cursor.getInt(UIProvider.FOLDER_TYPE_COLUMN);
223        iconResId = cursor.getLong(UIProvider.FOLDER_ICON_RES_ID_COLUMN);
224        bgColor = cursor.getString(UIProvider.FOLDER_BG_COLOR_COLUMN);
225        fgColor = cursor.getString(UIProvider.FOLDER_FG_COLOR_COLUMN);
226        String loadMore = cursor.getString(UIProvider.FOLDER_LOAD_MORE_URI_COLUMN);
227        loadMoreUri = !TextUtils.isEmpty(loadMore) ? Uri.parse(loadMore) : null;
228        parent = null;
229    }
230
231    @Override
232    public void writeToParcel(Parcel dest, int flags) {
233        dest.writeInt(id);
234        dest.writeParcelable(uri, 0);
235        dest.writeString(name);
236        dest.writeInt(capabilities);
237        // 1 for true, 0 for false.
238        dest.writeInt(hasChildren ? 1 : 0);
239        dest.writeInt(syncWindow);
240        dest.writeParcelable(conversationListUri, 0);
241        dest.writeParcelable(childFoldersListUri, 0);
242        dest.writeInt(unreadCount);
243        dest.writeInt(totalCount);
244        dest.writeParcelable(refreshUri, 0);
245        dest.writeInt(syncStatus);
246        dest.writeInt(lastSyncResult);
247        dest.writeInt(type);
248        dest.writeLong(iconResId);
249        dest.writeString(bgColor);
250        dest.writeString(fgColor);
251        dest.writeParcelable(loadMoreUri, 0);
252        dest.writeParcelable(parent, 0);
253    }
254
255    /**
256     * Return a serialized String for this folder.
257     */
258    public synchronized String serialize() {
259        StringBuilder out = new StringBuilder();
260        out.append(id).append(FOLDER_COMPONENT_SEPARATOR);
261        out.append(uri).append(FOLDER_COMPONENT_SEPARATOR);
262        out.append(name).append(FOLDER_COMPONENT_SEPARATOR);
263        out.append(capabilities).append(FOLDER_COMPONENT_SEPARATOR);
264        out.append(hasChildren ? "1": "0").append(FOLDER_COMPONENT_SEPARATOR);
265        out.append(syncWindow).append(FOLDER_COMPONENT_SEPARATOR);
266        out.append(conversationListUri).append(FOLDER_COMPONENT_SEPARATOR);
267        out.append(childFoldersListUri).append(FOLDER_COMPONENT_SEPARATOR);
268        out.append(unreadCount).append(FOLDER_COMPONENT_SEPARATOR);
269        out.append(totalCount).append(FOLDER_COMPONENT_SEPARATOR);
270        out.append(refreshUri).append(FOLDER_COMPONENT_SEPARATOR);
271        out.append(syncStatus).append(FOLDER_COMPONENT_SEPARATOR);
272        out.append(lastSyncResult).append(FOLDER_COMPONENT_SEPARATOR);
273        out.append(type).append(FOLDER_COMPONENT_SEPARATOR);
274        out.append(iconResId).append(FOLDER_COMPONENT_SEPARATOR);
275        out.append(bgColor == null ? "" : bgColor).append(FOLDER_COMPONENT_SEPARATOR);
276        out.append(fgColor == null? "" : fgColor).append(FOLDER_COMPONENT_SEPARATOR);
277        out.append(loadMoreUri).append(FOLDER_COMPONENT_SEPARATOR);
278        out.append(""); //set parent to empty
279        return out.toString();
280    }
281
282    /**
283     * Construct a folder that queries for search results. Do not call on the UI
284     * thread.
285     */
286    public static CursorLoader forSearchResults(Account account, String query, Context context) {
287        if (account.searchUri != null) {
288            Builder searchBuilder = account.searchUri.buildUpon();
289            searchBuilder.appendQueryParameter(UIProvider.SearchQueryParameters.QUERY, query);
290            Uri searchUri = searchBuilder.build();
291            return new CursorLoader(context, searchUri, UIProvider.FOLDERS_PROJECTION, null, null,
292                    null);
293        }
294        return null;
295    }
296
297    public static List<Folder> forFoldersString(String foldersString) {
298        final List<Folder> folders = Lists.newArrayList();
299        if (foldersString == null) {
300            return folders;
301        }
302        for (String folderStr : TextUtils.split(foldersString, FOLDER_SEPARATOR_PATTERN)) {
303            folders.add(new Folder(folderStr));
304        }
305        return folders;
306    }
307
308    /**
309     * Construct a new Folder instance from a previously serialized string.
310     * @param serializedFolder string obtained from {@link #serialize()} on a valid folder.
311     */
312    public Folder(String serializedFolder) {
313        String[] folderMembers = TextUtils.split(serializedFolder,
314                FOLDER_COMPONENT_SEPARATOR_PATTERN);
315        if (folderMembers.length != NUMBER_MEMBERS) {
316            throw new IllegalArgumentException(
317                    "Folder de-serializing failed. Wrong number of members detected."
318                            + folderMembers.length);
319        }
320        id = Integer.valueOf(folderMembers[0]);
321        uri = Uri.parse(folderMembers[1]);
322        name = folderMembers[2];
323        capabilities = Integer.valueOf(folderMembers[3]);
324        // 1 for true, 0 for false
325        hasChildren = folderMembers[4] == "1";
326        syncWindow = Integer.valueOf(folderMembers[5]);
327        String convList = folderMembers[6];
328        conversationListUri = !TextUtils.isEmpty(convList) ? Uri.parse(convList) : null;
329        String childList = folderMembers[7];
330        childFoldersListUri = (hasChildren && !TextUtils.isEmpty(childList)) ? Uri.parse(childList)
331                : null;
332        unreadCount = Integer.valueOf(folderMembers[8]);
333        totalCount = Integer.valueOf(folderMembers[9]);
334        String refresh = folderMembers[10];
335        refreshUri = !TextUtils.isEmpty(refresh) ? Uri.parse(refresh) : null;
336        syncStatus = Integer.valueOf(folderMembers[11]);
337        lastSyncResult = Integer.valueOf(folderMembers[12]);
338        type = Integer.valueOf(folderMembers[13]);
339        iconResId = Long.valueOf(folderMembers[14]);
340        bgColor = folderMembers[15];
341        fgColor = folderMembers[16];
342        String loadMore = folderMembers[17];
343        loadMoreUri = !TextUtils.isEmpty(loadMore) ? Uri.parse(loadMore) : null;
344        parent = null;
345    }
346
347    /**
348     * Constructor that leaves everything uninitialized. For use only by {@link #serialize()}
349     * which is responsible for filling in all the fields
350     */
351    public Folder() {
352        name = FOLDER_UNINITIALIZED;
353    }
354
355    @SuppressWarnings("hiding")
356    public static final Creator<Folder> CREATOR = new Creator<Folder>() {
357        @Override
358        public Folder createFromParcel(Parcel source) {
359            return new Folder(source);
360        }
361
362        @Override
363        public Folder[] newArray(int size) {
364            return new Folder[size];
365        }
366    };
367
368    @Override
369    public int describeContents() {
370        // Return a sort of version number for this parcelable folder. Starting with zero.
371        return 0;
372    }
373
374    @Override
375    public boolean equals(Object o) {
376        if (o == null || !(o instanceof Folder)) {
377            return false;
378        }
379        final Uri otherUri = ((Folder) o).uri;
380        if (uri == null) {
381            return (otherUri == null);
382        }
383        return uri.equals(otherUri);
384    }
385
386    @Override
387    public int hashCode() {
388        return uri == null ? 0 : uri.hashCode();
389    }
390
391    @Override
392    public int compareTo(Folder other) {
393        return name.compareToIgnoreCase(other.name);
394    }
395
396    /**
397     * Create a Folder map from a string of serialized folders. This can only be done on the output
398     * of {@link #serialize(Map)}.
399     * @param serializedFolder A string obtained from {@link #serialize(Map)}
400     * @return a Map of folder name to folder.
401     */
402    public static Map<String, Folder> parseFoldersFromString(String serializedFolder) {
403        LogUtils.d(LOG_TAG, "folder query result: %s", serializedFolder);
404
405        Map<String, Folder> folderMap = Maps.newHashMap();
406        if (serializedFolder == null || serializedFolder == "") {
407            return folderMap;
408        }
409        String[] folderPieces = TextUtils.split(
410                serializedFolder, FOLDER_COMPONENT_SEPARATOR_PATTERN);
411        for (int i = 0, n = folderPieces.length; i < n; i++) {
412            Folder folder = new Folder(folderPieces[i]);
413            if (folder.name != FOLDER_UNINITIALIZED) {
414                folderMap.put(folder.name, folder);
415            }
416        }
417        return folderMap;
418    }
419
420    /**
421     * Returns a boolean indicating whether network activity (sync) is occuring for this folder.
422     */
423    public boolean isSyncInProgress() {
424        return 0 != (syncStatus & (UIProvider.SyncStatus.BACKGROUND_SYNC |
425                UIProvider.SyncStatus.USER_REFRESH |
426                UIProvider.SyncStatus.USER_QUERY |
427                UIProvider.SyncStatus.USER_MORE_RESULTS));
428    }
429
430    /**
431     * Serialize the given list of folders
432     * @param folderMap A valid map of folder names to Folders
433     * @return a string containing a serialized output of folder maps.
434     */
435    public static String serialize(Map<String, Folder> folderMap) {
436        Collection<Folder> folderCollection = folderMap.values();
437        Folder[] folderList = folderCollection.toArray(new Folder[]{} );
438        int numFolders = folderList.length;
439        StringBuilder result = new StringBuilder();
440        for (int i = 0; i < numFolders; i++) {
441          if (i > 0) {
442              result.append(FOLDER_SEPARATOR);
443          }
444          Folder folder = folderList[i];
445          result.append(folder.serialize());
446        }
447        return result.toString();
448    }
449
450    public boolean supportsCapability(int capability) {
451        return (capabilities & capability) != 0;
452    }
453
454    // Show black text on a transparent swatch for system folders, effectively hiding the
455    // swatch (see bug 2431925).
456    public static void setFolderBlockColor(Folder folder, View colorBlock) {
457        final boolean showBg = !TextUtils.isEmpty(folder.bgColor);
458        final int backgroundColor = showBg ? Integer.parseInt(folder.bgColor) : 0;
459        if (folder.iconResId > 0) {
460            colorBlock.setBackgroundResource((int)folder.iconResId);
461        } else if (!showBg) {
462            colorBlock.setBackgroundDrawable(null);
463        } else {
464            PaintDrawable paintDrawable = new PaintDrawable();
465            paintDrawable.getPaint().setColor(backgroundColor);
466            colorBlock.setBackgroundDrawable(paintDrawable);
467        }
468    }
469
470    /**
471     * Return if the type of the folder matches a provider defined folder.
472     */
473    public static boolean isProviderFolder(Folder folder) {
474        int type = folder.type;
475        return type == UIProvider.FolderType.INBOX ||
476               type == UIProvider.FolderType.DRAFT ||
477               type == UIProvider.FolderType.OUTBOX ||
478               type == UIProvider.FolderType.SENT ||
479               type == UIProvider.FolderType.TRASH ||
480               type == UIProvider.FolderType.SPAM;
481    }
482
483    public int getBackgroundColor(int defaultColor) {
484        return TextUtils.isEmpty(bgColor) ? defaultColor : Integer.parseInt(bgColor);
485    }
486
487    public int getForegroundColor(int defaultColor) {
488        return TextUtils.isEmpty(fgColor) ? defaultColor : Integer.parseInt(fgColor);
489    }
490
491    public static String getSerializedFolderString(Folder currentFolder,
492            Collection<Folder> folders) {
493        final Collection<String> folderList = new ArrayList<String>();
494        for (Folder folderEntry : folders) {
495            // If the current folder is a system folder, and the folder entry has the same type
496            // as that system defined folder, don't show it.
497            if (!folderEntry.uri.equals(currentFolder.uri)
498                    && Folder.isProviderFolder(currentFolder)
499                    && folderEntry.type != currentFolder.type) {
500                folderList.add(folderEntry.serialize());
501            }
502        }
503        return TextUtils.join(Folder.FOLDER_SEPARATOR, folderList);
504    }
505
506    /**
507     * Returns a comma separated list of folder URIs for all the folders in the collection.
508     * @param folders
509     * @return
510     */
511    public final static String getUriString(Collection<Folder> folders) {
512        final StringBuilder uris = new StringBuilder();
513        boolean first = true;
514        for (Folder f : folders) {
515            if (first) {
516                first = false;
517            } else {
518                uris.append(',');
519            }
520            uris.append(f.uri.toString());
521        }
522        return uris.toString();
523    }
524
525    /**
526     * Returns true if a conversation assigned to the needle will be assigned to the collection of
527     * folders in the haystack. False otherwise. This method is safe to call with null
528     * arguments.
529     * This method returns true under two circumstances
530     * <ul><li> If the URI of the needle was found in the collection of URIs that comprise the
531     * haystack.
532     * </li><li> If the needle is of the type Inbox, and at least one of the folders in the haystack
533     * are of type Inbox. <em>Rationale</em>: there are special folders that are marked as inbox,
534     * and the user might not have the control to assign conversations to them. This happens for
535     * the Priority Inbox in Gmail. When you assign a conversation to an Inbox folder, it will
536     * continue to appear in the Priority Inbox. However, the URI of Priority Inbox and Inbox will
537     * be different. So a direct equality check is insufficient.
538     * </li></ul>
539     * @param haystack a collection of folders, possibly overlapping
540     * @param needle a folder
541     * @return true if a conversation inside the needle will be in the folders in the haystack.
542     */
543    public final static boolean containerIncludes(Collection<Folder> haystack, Folder needle) {
544        // If the haystack is empty, it cannot contain anything.
545        if (haystack == null || haystack.size() <= 0) {
546            return false;
547        }
548        // The null folder exists everywhere.
549        if (needle == null) {
550            return true;
551        }
552        boolean hasInbox = false;
553        // Get currently active folder info and compare it to the list
554        // these conversations have been given; if they no longer contain
555        // the selected folder, delete them from the list.
556        final Uri toFind = needle.uri;
557        for (Folder f : haystack) {
558            if (toFind.equals(f.uri)) {
559                return true;
560            }
561            hasInbox |= (f.type == UIProvider.FolderType.INBOX);
562        }
563        // Did not find the URI of needle directly. If the needle is an Inbox and one of the folders
564        // was an inbox, then the needle is contained (check Javadoc for explanation).
565        final boolean needleIsInbox = (needle.type == UIProvider.FolderType.INBOX);
566        return needleIsInbox ? hasInbox : false;
567    }
568
569    /**
570     * Returns a collection of a single folder. This method always returns a valid collection
571     * even if the input folder is null.
572     * @param in a folder, possibly null.
573     * @return a collection of the folder.
574     */
575    public static Collection<Folder> listOf(Folder in) {
576        final Collection<Folder> target = (in == null) ? EMPTY : ImmutableList.of(in);
577        return target;
578    }
579}
580