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