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