MailboxListFragment.java revision 3de5fd026dc702d2cafc55b0a61039d4f582d932
1/* 2 * Copyright (C) 2010 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 */ 16 17package com.android.email.activity; 18 19import com.android.email.Controller; 20import com.android.email.Email; 21import com.android.email.R; 22import com.android.email.RefreshManager; 23import com.android.email.provider.EmailProvider; 24import com.android.emailcommon.Logging; 25import com.android.emailcommon.provider.EmailContent.Mailbox; 26import com.android.emailcommon.provider.EmailContent.Message; 27import com.android.emailcommon.utility.EmailAsyncTask; 28import com.android.emailcommon.utility.Utility; 29 30import android.app.Activity; 31import android.app.ListFragment; 32import android.app.LoaderManager; 33import android.app.LoaderManager.LoaderCallbacks; 34import android.content.ClipData; 35import android.content.ClipDescription; 36import android.content.Loader; 37import android.content.res.Resources; 38import android.database.Cursor; 39import android.graphics.Rect; 40import android.graphics.drawable.Drawable; 41import android.net.Uri; 42import android.os.Bundle; 43import android.os.Parcelable; 44import android.util.Log; 45import android.view.DragEvent; 46import android.view.LayoutInflater; 47import android.view.View; 48import android.view.View.OnDragListener; 49import android.view.ViewGroup; 50import android.widget.AdapterView; 51import android.widget.AdapterView.OnItemClickListener; 52import android.widget.ListView; 53 54import java.security.InvalidParameterException; 55import java.util.Timer; 56import java.util.TimerTask; 57 58/** 59 * This fragment presents a list of mailboxes for a given account. The "API" includes the 60 * following elements which must be provided by the host Activity. 61 * 62 * - call bindActivityInfo() to provide the account ID and set callbacks 63 * - provide callbacks for onOpen and onRefresh 64 * - pass-through implementations of onCreateContextMenu() and onContextItemSelected() (temporary) 65 * 66 * TODO Restoring ListView state -- don't do this when changing accounts 67 * TODO Restoring scroll position on screen rotation is broken. 68 * TODO Remove clearContent -> most probably this is the cause for the scroll position not being 69 * restored issue. 70 */ 71public class MailboxListFragment extends ListFragment implements OnItemClickListener, 72 OnDragListener { 73 private static final String TAG = "MailboxListFragment"; 74 private static final String BUNDLE_KEY_SELECTED_MAILBOX_ID 75 = "MailboxListFragment.state.selected_mailbox_id"; 76 private static final String BUNDLE_LIST_STATE = "MailboxListFragment.state.listState"; 77 private static final boolean DEBUG_DRAG_DROP = false; // MUST NOT SUBMIT SET TO TRUE 78 /** While in drag-n-drop, amount of time before it auto expands; in ms */ 79 private static final long AUTO_EXPAND_DELAY = 750L; 80 81 /** No drop target is available where the user is currently hovering over */ 82 private static final int NO_DROP_TARGET = -1; 83 // Total height of the top and bottom scroll zones, in pixels 84 private static final int SCROLL_ZONE_SIZE = 64; 85 // The amount of time to scroll by one pixel, in ms 86 private static final int SCROLL_SPEED = 4; 87 88 /** Arbitrary number for use with the loader manager */ 89 private static final int MAILBOX_LOADER_ID = 1; 90 91 /** Argument name(s) */ 92 private static final String ARG_ACCOUNT_ID = "accountId"; 93 private static final String ARG_PARENT_MAILBOX_ID = "parentMailboxId"; 94 95 // TODO Clean up usage of mailbox ID. We use both '-1' and '0' to mean "not selected". To 96 // confuse matters, the database uses '-1' for "no mailbox" and '0' for "invalid mailbox". 97 // Once legacy accounts properly support nested folders, we need to make sure we're only 98 // ever using '-1'. 99 // STOPSHIP Change value to '-1' when legacy protocols support folders 100 private final static long DEFAULT_MAILBOX_ID = 0; 101 102 /** Timer to auto-expand folder lists during drag-n-drop */ 103 private static final Timer sDragTimer = new Timer(); 104 /** Rectangle used for hit testing children */ 105 private static final Rect sTouchFrame = new Rect(); 106 107 private RefreshManager mRefreshManager; 108 109 // UI Support 110 private Activity mActivity; 111 private MailboxesAdapter mListAdapter; 112 private Callback mCallback = EmptyCallback.INSTANCE; 113 114 private ListView mListView; 115 116 private boolean mResumed; 117 118 // Colors used for drop targets 119 private static Integer sDropTrashColor; 120 private static Drawable sDropActiveDrawable; 121 122 private long mLastLoadedAccountId = -1; 123 private long mAccountId = -1; 124 private long mParentMailboxId = DEFAULT_MAILBOX_ID; 125 private long mSelectedMailboxId = -1; 126 /** The ID of the mailbox that we have been asked to load */ 127 private long mLoadedMailboxId = -1; 128 129 private boolean mOpenRequested; 130 131 // True if a drag is currently in progress 132 private boolean mDragInProgress; 133 /** Mailbox ID of the item being dragged. Used to determine valid drop targets. */ 134 private long mDragItemMailboxId = -1; 135 /** A unique identifier for the drop target. May be {@link #NO_DROP_TARGET}. */ 136 private int mDropTargetId = NO_DROP_TARGET; 137 // The mailbox list item view that the user's finger is hovering over 138 private MailboxListItem mDropTargetView; 139 // Lazily instantiated height of a mailbox list item (-1 is a sentinel for 'not initialized') 140 private int mDragItemHeight = -1; 141 /** Task that actually does the work to auto-expand folder lists during drag-n-drop */ 142 private TimerTask mDragTimerTask; 143 // True if we are currently scrolling under the drag item 144 private boolean mTargetScrolling; 145 146 private Parcelable mSavedListState; 147 148 private final MailboxesAdapter.Callback mMailboxesAdapterCallback = 149 new MailboxesAdapter.Callback() { 150 @Override 151 public void onBind(MailboxListItem listItem) { 152 listItem.setDropTargetBackground(mDragInProgress, mDragItemMailboxId); 153 } 154 }; 155 156 /** 157 * Callback interface that owning activities must implement 158 */ 159 public interface Callback { 160 /** 161 * STOPSHIP split this into separate callbacks. 162 * - Drill in to a mailbox and open a mailbox (= show message list) are different operations 163 * on the phone 164 * - Regular navigation and navigation for D&D are different; the latter case we probably 165 * want to go back to the original mailbox afterwards. (Need another callback for this) 166 * 167 * Called when any mailbox (even a combined mailbox) is selected. 168 * @param accountId 169 * The ID of the account for which a mailbox was selected 170 * @param mailboxId 171 * The ID of the selected mailbox. This may be real mailbox ID [e.g. a number > 0], 172 * or a special mailbox ID 173 * [e.g. {@link MessageListXLFragmentManager#NO_MAILBOX} for "All Folders" to open 174 * the root folders, {@link Mailbox#QUERY_ALL_INBOXES}, etc...]. 175 * @param navigate navigate to the mailbox. 176 * @param dragDrop true if D&D is in progress. 177 */ 178 public void onMailboxSelected(long accountId, long mailboxId, boolean navigate, 179 boolean dragDrop); 180 181 /** Called when an account is selected on the combined view. */ 182 public void onAccountSelected(long accountId); 183 184 /** 185 * Called when the list updates to propagate the current mailbox name and the unread count 186 * for it. 187 * 188 * Note the reason why it's separated from onMailboxSelected is because this needs to be 189 * reported when the unread count changes without changing the current mailbox. 190 */ 191 public void onCurrentMailboxUpdated(long mailboxId, String mailboxName, int unreadCount); 192 } 193 194 private static class EmptyCallback implements Callback { 195 public static final Callback INSTANCE = new EmptyCallback(); 196 @Override public void onMailboxSelected(long accountId, long mailboxId, boolean navigate, 197 boolean dragDrop) { 198 } 199 @Override public void onAccountSelected(long accountId) { } 200 @Override public void onCurrentMailboxUpdated(long mailboxId, String mailboxName, 201 int unreadCount) { } 202 } 203 204 /** 205 * Returns the index of the view located at the specified coordinates in the given list. 206 * If the coordinates are outside of the list, {@code NO_DROP_TARGET} is returned. 207 */ 208 private static int pointToIndex(ListView list, int x, int y) { 209 final int count = list.getChildCount(); 210 for (int i = count - 1; i >= 0; i--) { 211 final View child = list.getChildAt(i); 212 if (child.getVisibility() == View.VISIBLE) { 213 child.getHitRect(sTouchFrame); 214 if (sTouchFrame.contains(x, y)) { 215 return i; 216 } 217 } 218 } 219 return NO_DROP_TARGET; 220 } 221 222 /** 223 * Create a new instance with initialization parameters. 224 * 225 * This fragment should be created only with this method. (Arguments should always be set.) 226 */ 227 public static MailboxListFragment newInstance(long accountId, long parentMailboxId) { 228 final MailboxListFragment instance = new MailboxListFragment(); 229 final Bundle args = new Bundle(); 230 args.putLong(ARG_ACCOUNT_ID, accountId); 231 args.putLong(ARG_PARENT_MAILBOX_ID, parentMailboxId); 232 instance.setArguments(args); 233 return instance; 234 } 235 236 /** 237 * Called to do initial creation of a fragment. This is called after 238 * {@link #onAttach(Activity)} and before {@link #onActivityCreated(Bundle)}. 239 */ 240 @Override 241 public void onCreate(Bundle savedInstanceState) { 242 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 243 Log.d(Logging.LOG_TAG, "MailboxListFragment onCreate"); 244 } 245 super.onCreate(savedInstanceState); 246 247 mActivity = getActivity(); 248 mRefreshManager = RefreshManager.getInstance(mActivity); 249 mListAdapter = new MailboxFragmentAdapter(mActivity, mMailboxesAdapterCallback); 250 if (savedInstanceState != null) { 251 restoreInstanceState(savedInstanceState); 252 } 253 if (sDropTrashColor == null) { 254 Resources res = getResources(); 255 sDropTrashColor = res.getColor(R.color.mailbox_drop_destructive_bg_color); 256 sDropActiveDrawable = res.getDrawable(R.drawable.list_activated_holo); 257 } 258 } 259 260 @Override 261 public View onCreateView( 262 LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 263 return inflater.inflate(R.layout.mailbox_list_fragment, container, false); 264 } 265 266 @Override 267 public void onActivityCreated(Bundle savedInstanceState) { 268 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 269 Log.d(Logging.LOG_TAG, "MailboxListFragment onActivityCreated"); 270 } 271 super.onActivityCreated(savedInstanceState); 272 273 mListView = getListView(); 274 mListView.setOnItemClickListener(this); 275 mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 276 mListView.setOnDragListener(this); 277 registerForContextMenu(mListView); 278 279 final Bundle args = getArguments(); 280 // STOPSHIP remove the check. Right now it's needed for the obsolete phone activities. 281 if (args != null) { 282 openMailboxes(args.getLong(ARG_ACCOUNT_ID), args.getLong(ARG_PARENT_MAILBOX_ID)); 283 } 284 } 285 286 public void setCallback(Callback callback) { 287 mCallback = (callback == null) ? EmptyCallback.INSTANCE : callback; 288 } 289 290 private void clearContent() { 291 getLoaderManager().destroyLoader(MAILBOX_LOADER_ID); 292 293 mLastLoadedAccountId = -1; 294 mAccountId = -1; 295 mParentMailboxId = DEFAULT_MAILBOX_ID; 296 mSelectedMailboxId = -1; 297 mLoadedMailboxId = -1; 298 299 mOpenRequested = false; 300 mDropTargetId = NO_DROP_TARGET; 301 mDropTargetView = null; 302 303 if (mListAdapter != null) { 304 mListAdapter.swapCursor(null); 305 } 306 setListShownNoAnimation(false); 307 } 308 309 /** 310 * Opens the top-level mailboxes for the given account ID. If the account is currently 311 * loaded, the list of top-level mailbox will not be reloaded unless <code>forceReload</code> 312 * is <code>true</code>. 313 * @param accountId The ID of the account we want to view 314 * @param parentMailboxId The ID of the parent mailbox. Use -1 to open the root. 315 * Otherwise, only load the list of top-level mailboxes if the account changes. 316 */ 317 // STOPSHIP Make it private once phone activities are gone 318 void openMailboxes(long accountId, long parentMailboxId) { 319 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 320 Log.d(Logging.LOG_TAG, "MailboxListFragment openMailboxes"); 321 } 322 if (accountId == -1) { 323 throw new InvalidParameterException(); 324 } 325 // Normalize -- STOPSHIP should be removed when DEFAULT_MAILBOX_ID becomes -1. 326 if (parentMailboxId == -1) { 327 parentMailboxId = DEFAULT_MAILBOX_ID; 328 } 329 330 if ((mAccountId == accountId) && (mParentMailboxId == parentMailboxId)) { 331 return; 332 } 333 clearContent(); 334 mOpenRequested = true; 335 mAccountId = accountId; 336 mParentMailboxId = parentMailboxId; 337 if (mResumed) { 338 startLoading(); 339 } 340 } 341 342 /** 343 * Returns whether or not the specified mailbox can be navigated to. 344 */ 345 private boolean isNavigable(long mailboxId) { 346 final int count = mListView.getCount(); 347 for (int i = 0; i < count; i++) { 348 final MailboxListItem item = (MailboxListItem) mListView.getChildAt(i); 349 if (item.mMailboxId != mailboxId) { 350 continue; 351 } 352 return item.isNavigable(); 353 } 354 return false; 355 } 356 357 /** 358 * Sets the selected mailbox to the given ID. Sub-folders will not be loaded. 359 * @param mailboxId The ID of the mailbox to select. 360 */ 361 public void setSelectedMailbox(long mailboxId) { 362 mSelectedMailboxId = mailboxId; 363 if (mResumed) { 364 highlightSelectedMailbox(true); 365 } 366 } 367 368 /** 369 * Called when the Fragment is visible to the user. 370 */ 371 @Override 372 public void onStart() { 373 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 374 Log.d(Logging.LOG_TAG, "MailboxListFragment onStart"); 375 } 376 super.onStart(); 377 } 378 379 /** 380 * Called when the fragment is visible to the user and actively running. 381 */ 382 @Override 383 public void onResume() { 384 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 385 Log.d(Logging.LOG_TAG, "MailboxListFragment onResume"); 386 } 387 super.onResume(); 388 mResumed = true; 389 390 // If we're recovering from the stopped state, we don't have to reload. 391 // (when mOpenRequested = false) 392 if (mAccountId != -1 && mOpenRequested) { 393 startLoading(); 394 } 395 } 396 397 @Override 398 public void onPause() { 399 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 400 Log.d(Logging.LOG_TAG, "MailboxListFragment onPause"); 401 } 402 mResumed = false; 403 super.onPause(); 404 mSavedListState = getListView().onSaveInstanceState(); 405 } 406 407 /** 408 * Called when the Fragment is no longer started. 409 */ 410 @Override 411 public void onStop() { 412 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 413 Log.d(Logging.LOG_TAG, "MailboxListFragment onStop"); 414 } 415 super.onStop(); 416 } 417 418 /** 419 * Called when the fragment is no longer in use. 420 */ 421 @Override 422 public void onDestroy() { 423 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 424 Log.d(Logging.LOG_TAG, "MailboxListFragment onDestroy"); 425 } 426 super.onDestroy(); 427 } 428 429 @Override 430 public void onSaveInstanceState(Bundle outState) { 431 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 432 Log.d(Logging.LOG_TAG, "MailboxListFragment onSaveInstanceState"); 433 } 434 super.onSaveInstanceState(outState); 435 outState.putLong(BUNDLE_KEY_SELECTED_MAILBOX_ID, mSelectedMailboxId); 436 outState.putParcelable(BUNDLE_LIST_STATE, getListView().onSaveInstanceState()); 437 } 438 439 private void restoreInstanceState(Bundle savedInstanceState) { 440 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 441 Log.d(Logging.LOG_TAG, "MailboxListFragment restoreInstanceState"); 442 } 443 mSelectedMailboxId = savedInstanceState.getLong(BUNDLE_KEY_SELECTED_MAILBOX_ID); 444 mSavedListState = savedInstanceState.getParcelable(BUNDLE_LIST_STATE); 445 } 446 447 private void startLoading() { 448 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 449 Log.d(Logging.LOG_TAG, "MailboxListFragment startLoading"); 450 } 451 mOpenRequested = false; 452 // Clear the list. (ListFragment will show the "Loading" animation) 453 setListShown(false); 454 455 // If we've already loaded for a different account OR if we've loaded for a different 456 // mailbox, discard the previous result and load again. 457 boolean saveListState = true; 458 final LoaderManager lm = getLoaderManager(); 459 long lastLoadedMailboxId = mLoadedMailboxId; 460 mLoadedMailboxId = mParentMailboxId; 461 if ((lastLoadedMailboxId != mParentMailboxId) || 462 ((mLastLoadedAccountId != -1) && (mLastLoadedAccountId != mAccountId))) { 463 lm.destroyLoader(MAILBOX_LOADER_ID); 464 saveListState = false; 465 refreshMailboxListIfStale(); 466 } 467 /** 468 * Don't use {@link LoaderManager#restartLoader(int, Bundle, LoaderCallbacks)}, because 469 * we want to reuse the previous result if the Loader has been retained. 470 */ 471 lm.initLoader(MAILBOX_LOADER_ID, null, 472 new MailboxListLoaderCallbacks(saveListState, mLoadedMailboxId)); 473 } 474 475 // TODO This class probably should be made static. There are many calls into the enclosing 476 // class and we need to be cautious about what we call while in these callbacks 477 private class MailboxListLoaderCallbacks implements LoaderCallbacks<Cursor> { 478 private boolean mSaveListState; 479 private final long mMailboxId; 480 481 public MailboxListLoaderCallbacks(boolean saveListState, long mailboxId) { 482 mSaveListState = saveListState; 483 mMailboxId = mailboxId; 484 } 485 486 @Override 487 public Loader<Cursor> onCreateLoader(int id, Bundle args) { 488 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 489 Log.d(Logging.LOG_TAG, "MailboxListFragment onCreateLoader"); 490 } 491 return MailboxFragmentAdapter.createLoader(getActivity(), mAccountId, mMailboxId); 492 } 493 494 @Override 495 public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { 496 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 497 Log.d(Logging.LOG_TAG, "MailboxListFragment onLoadFinished"); 498 } 499 if (mMailboxId != mLoadedMailboxId) { 500 return; 501 } 502 mLastLoadedAccountId = mAccountId; 503 504 // Save list view state (primarily scroll position) 505 final ListView lv = getListView(); 506 final Parcelable listState; 507 if (!mSaveListState) { 508 listState = null; // Don't preserve list state 509 } else if (mSavedListState != null) { 510 listState = mSavedListState; 511 mSavedListState = null; 512 } else { 513 listState = lv.onSaveInstanceState(); 514 } 515 516 if (cursor.getCount() == 0) { 517 // If there's no row, don't set it to the ListView. 518 // Instead use setListShown(false) to make ListFragment show progress icon. 519 mListAdapter.swapCursor(null); 520 setListShown(false); 521 } else { 522 // Set the adapter. 523 mListAdapter.swapCursor(cursor); 524 setListAdapter(mListAdapter); 525 setListShown(true); 526 527 // We want to make selection visible only when account is changing.. 528 // i.e. Refresh caused by content changed events shouldn't scroll the list. 529 highlightSelectedMailbox(!mSaveListState); 530 } 531 532 // List has been reloaded; clear any drop target information 533 mDropTargetId = NO_DROP_TARGET; 534 mDropTargetView = null; 535 536 // Restore the state 537 if (listState != null) { 538 lv.onRestoreInstanceState(listState); 539 } 540 541 // Clear this for next reload triggered by content changed events. 542 mSaveListState = true; 543 } 544 545 @Override 546 public void onLoaderReset(Loader<Cursor> loader) { 547 if (mMailboxId != mLoadedMailboxId) { 548 return; 549 } 550 mListAdapter.swapCursor(null); 551 } 552 } 553 554 public void onItemClick(AdapterView<?> parent, View view, int position, 555 long idDontUseIt /* see MailboxesAdapter */ ) { 556 final long id = mListAdapter.getId(position); 557 if (mListAdapter.isAccountRow(position)) { 558 mCallback.onAccountSelected(id); 559 } else { 560 // STOPSHIP On phone, we need a way to open a message list without navigating to the 561 // mailbox. 562 mCallback.onMailboxSelected(mAccountId, id, isNavigable(id), false); 563 } 564 } 565 566 public void onRefresh() { 567 if (mAccountId != -1) { 568 mRefreshManager.refreshMailboxList(mAccountId); 569 } 570 } 571 572 private void refreshMailboxListIfStale() { 573 if (mRefreshManager.isMailboxListStale(mAccountId)) { 574 mRefreshManager.refreshMailboxList(mAccountId); 575 } 576 } 577 578 /** 579 * Highlight the selected mailbox. 580 */ 581 private void highlightSelectedMailbox(boolean ensureSelectionVisible) { 582 String mailboxName = ""; 583 int unreadCount = 0; 584 if (mSelectedMailboxId == -1) { 585 // No mailbox selected 586 mListView.clearChoices(); 587 } else { 588 // TODO Don't mix list view & list adapter indices. This is a recipe for disaster. 589 final int count = mListView.getCount(); 590 for (int i = 0; i < count; i++) { 591 if (mListAdapter.getId(i) != mSelectedMailboxId) { 592 continue; 593 } 594 mListView.setItemChecked(i, true); 595 if (ensureSelectionVisible) { 596 Utility.listViewSmoothScrollToPosition(getActivity(), mListView, i); 597 } 598 mailboxName = mListAdapter.getDisplayName(mActivity, i); 599 unreadCount = mListAdapter.getUnreadCount(i); 600 break; 601 } 602 } 603 mCallback.onCurrentMailboxUpdated(mSelectedMailboxId, mailboxName, unreadCount); 604 } 605 606 // Drag & Drop handling 607 608 /** 609 * Update all of the list's child views with the proper target background (for now, orange if 610 * a valid target, except red if the trash; standard background otherwise) 611 */ 612 private void updateChildViews() { 613 int itemCount = mListView.getChildCount(); 614 // Lazily initialize the height of our list items 615 if (itemCount > 0 && mDragItemHeight < 0) { 616 mDragItemHeight = mListView.getChildAt(0).getHeight(); 617 } 618 for (int i = 0; i < itemCount; i++) { 619 MailboxListItem item = (MailboxListItem)mListView.getChildAt(i); 620 item.setDropTargetBackground(mDragInProgress, mDragItemMailboxId); 621 } 622 } 623 624 /** 625 * Starts the timer responsible for auto-selecting mailbox items while in drag-n-drop. 626 * If there is already an active task, we first try to cancel it. There are only two 627 * reasons why a new timer may not be started. First, if we are unable to cancel a 628 * previous timer, we must assume that a new mailbox has already been loaded. Second, 629 * if the target item is not permitted to be auto selected. 630 * @param newTarget The drag target that needs to be auto selected 631 */ 632 private void startDragTimer(final MailboxListItem newTarget) { 633 boolean canceledInTime = mDragTimerTask == null || stopDragTimer(); 634 if (canceledInTime 635 && newTarget != null 636 && newTarget.isNavigable() 637 && newTarget.isDropTarget(mDragItemMailboxId)) { 638 mDragTimerTask = new TimerTask() { 639 @Override 640 public void run() { 641 mActivity.runOnUiThread(new Runnable() { 642 @Override 643 public void run() { 644 stopDragTimer(); 645 // STOPSHIP Revisit this -- probably we need a different callback 646 // so that when D&D finishes we can go back to the original mailbox. 647 mCallback.onMailboxSelected(mAccountId, newTarget.mMailboxId, true, 648 true); 649 } 650 }); 651 } 652 }; 653 sDragTimer.schedule(mDragTimerTask, AUTO_EXPAND_DELAY); 654 } 655 } 656 657 /** 658 * Stops the timer responsible for auto-selecting mailbox items while in drag-n-drop. 659 * If the timer is not active, nothing will happen. 660 * @return Whether or not the timer was interrupted. {@link TimerTask#cancel()}. 661 */ 662 private boolean stopDragTimer() { 663 boolean timerInterrupted = false; 664 synchronized (sDragTimer) { 665 if (mDragTimerTask != null) { 666 timerInterrupted = mDragTimerTask.cancel(); 667 mDragTimerTask = null; 668 } 669 } 670 return timerInterrupted; 671 } 672 673 /** 674 * Called when the user has dragged outside of the mailbox list area. 675 */ 676 private void onDragExited() { 677 // Reset the background of the current target 678 if (mDropTargetView != null) { 679 mDropTargetView.setDropTargetBackground(mDragInProgress, mDragItemMailboxId); 680 mDropTargetView = null; 681 } 682 mDropTargetId = NO_DROP_TARGET; 683 stopDragTimer(); 684 stopScrolling(); 685 } 686 687 /** 688 * Called while dragging; highlight possible drop targets, and auto scroll the list. 689 */ 690 private void onDragLocation(DragEvent event) { 691 // TODO The list may be changing while in drag-n-drop; temporarily suspend drag-n-drop 692 // if the list is being updated [i.e. navigated to another mailbox] 693 if (mDragItemHeight <= 0) { 694 // This shouldn't be possible, but avoid NPE 695 Log.w(TAG, "drag item height is not set"); 696 return; 697 } 698 // Find out which item we're in and highlight as appropriate 699 final int rawTouchX = (int) event.getX(); 700 final int rawTouchY = (int) event.getY(); 701 final int viewIndex = pointToIndex(mListView, rawTouchX, rawTouchY); 702 int targetId = viewIndex; 703 if (targetId != mDropTargetId) { 704 if (DEBUG_DRAG_DROP) { 705 Log.d(TAG, "=== Target changed; oldId: " + mDropTargetId + ", newId: " + targetId); 706 } 707 // Remove highlight the current target; if there was one 708 if (mDropTargetView != null) { 709 mDropTargetView.setDropTargetBackground(true, mDragItemMailboxId); 710 mDropTargetView = null; 711 } 712 // Get the new target mailbox view 713 final MailboxListItem newTarget = (MailboxListItem) mListView.getChildAt(viewIndex); 714 if (newTarget == null) { 715 // In any event, we're no longer dragging in the list view if newTarget is null 716 if (DEBUG_DRAG_DROP) { 717 Log.d(TAG, "=== Drag off the list"); 718 } 719 final int childCount = mListView.getChildCount(); 720 if (viewIndex >= childCount) { 721 // Touching beyond the end of the list; may happen for small lists 722 onDragExited(); 723 return; 724 } else { 725 // We should never get here 726 Log.w(TAG, "null view; idx: " + viewIndex + ", cnt: " + childCount); 727 } 728 } else if (newTarget.mMailboxType == Mailbox.TYPE_TRASH) { 729 if (DEBUG_DRAG_DROP) { 730 Log.d(TAG, "=== Trash mailbox; id: " + newTarget.mMailboxId); 731 } 732 newTarget.setBackgroundColor(sDropTrashColor); 733 } else if (newTarget.isDropTarget(mDragItemMailboxId)) { 734 if (DEBUG_DRAG_DROP) { 735 Log.d(TAG, "=== Target mailbox; id: " + newTarget.mMailboxId); 736 } 737 newTarget.setBackgroundDrawable(sDropActiveDrawable); 738 } else { 739 if (DEBUG_DRAG_DROP) { 740 Log.d(TAG, "=== Non-droppable mailbox; id: " + newTarget.mMailboxId); 741 } 742 newTarget.setDropTargetBackground(true, mDragItemMailboxId); 743 targetId = NO_DROP_TARGET; 744 } 745 // Save away our current position and view 746 mDropTargetId = targetId; 747 mDropTargetView = newTarget; 748 startDragTimer(newTarget); 749 } 750 751 // This is a quick-and-dirty implementation of drag-under-scroll; something like this 752 // should eventually find its way into the framework 753 int scrollDiff = rawTouchY - (mListView.getHeight() - SCROLL_ZONE_SIZE); 754 boolean scrollDown = (scrollDiff > 0); 755 boolean scrollUp = (SCROLL_ZONE_SIZE > rawTouchY); 756 if (!mTargetScrolling && scrollDown) { 757 int itemsToScroll = mListView.getCount() - mListView.getLastVisiblePosition(); 758 int pixelsToScroll = (itemsToScroll + 1) * mDragItemHeight; 759 mListView.smoothScrollBy(pixelsToScroll, pixelsToScroll * SCROLL_SPEED); 760 if (DEBUG_DRAG_DROP) { 761 Log.d(TAG, "=== Start scrolling list down"); 762 } 763 mTargetScrolling = true; 764 } else if (!mTargetScrolling && scrollUp) { 765 int pixelsToScroll = (mListView.getFirstVisiblePosition() + 1) * mDragItemHeight; 766 mListView.smoothScrollBy(-pixelsToScroll, pixelsToScroll * SCROLL_SPEED); 767 if (DEBUG_DRAG_DROP) { 768 Log.d(TAG, "=== Start scrolling list up"); 769 } 770 mTargetScrolling = true; 771 } else if (!scrollUp && !scrollDown) { 772 stopScrolling(); 773 } 774 } 775 776 /** 777 * Indicate that scrolling has stopped 778 */ 779 private void stopScrolling() { 780 if (mTargetScrolling) { 781 mTargetScrolling = false; 782 if (DEBUG_DRAG_DROP) { 783 Log.d(TAG, "=== Stop scrolling list"); 784 } 785 // Stop the scrolling 786 mListView.smoothScrollBy(0, 0); 787 } 788 } 789 790 private void onDragEnded() { 791 stopDragTimer(); 792 if (mDragInProgress) { 793 mDragInProgress = false; 794 // Reenable updates to the view and redraw (in case it changed) 795 MailboxesAdapter.enableUpdates(true); 796 mListAdapter.notifyDataSetChanged(); 797 // Stop highlighting targets 798 updateChildViews(); 799 // Stop any scrolling that was going on 800 stopScrolling(); 801 } 802 } 803 804 private boolean onDragStarted(DragEvent event) { 805 // We handle dropping of items with our email mime type 806 // If the mime type has a mailbox id appended, that is the mailbox of the item 807 // being draged 808 ClipDescription description = event.getClipDescription(); 809 int mimeTypeCount = description.getMimeTypeCount(); 810 for (int i = 0; i < mimeTypeCount; i++) { 811 String mimeType = description.getMimeType(i); 812 if (mimeType.startsWith(EmailProvider.EMAIL_MESSAGE_MIME_TYPE)) { 813 if (DEBUG_DRAG_DROP) { 814 Log.d(TAG, "=== Drag started"); 815 } 816 mDragItemMailboxId = -1; 817 // See if we find a mailbox id here 818 int dash = mimeType.lastIndexOf('-'); 819 if (dash > 0) { 820 try { 821 mDragItemMailboxId = Long.parseLong(mimeType.substring(dash + 1)); 822 } catch (NumberFormatException e) { 823 // Ignore; we just won't know the mailbox 824 } 825 } 826 mDragInProgress = true; 827 // Stop the list from updating 828 MailboxesAdapter.enableUpdates(false); 829 // Update the backgrounds of our child views to highlight drop targets 830 updateChildViews(); 831 return true; 832 } 833 } 834 return false; 835 } 836 837 /** 838 * Perform a "drop" action. If the user is not on top of a valid drop target, no action 839 * is performed. 840 * @return {@code true} if the drop action was performed. Otherwise {@code false}. 841 */ 842 private boolean onDrop(DragEvent event) { 843 stopDragTimer(); 844 stopScrolling(); 845 // If we're not on a target, we're done 846 if (mDropTargetId == NO_DROP_TARGET) { 847 return false; 848 } 849 final Controller controller = Controller.getInstance(mActivity); 850 ClipData clipData = event.getClipData(); 851 int count = clipData.getItemCount(); 852 if (DEBUG_DRAG_DROP) { 853 Log.d(TAG, "=== Dropping " + count + " items."); 854 } 855 // Extract the messageId's to move from the ClipData (set up in MessageListItem) 856 final long[] messageIds = new long[count]; 857 for (int i = 0; i < count; i++) { 858 Uri uri = clipData.getItemAt(i).getUri(); 859 String msgNum = uri.getPathSegments().get(1); 860 long id = Long.parseLong(msgNum); 861 messageIds[i] = id; 862 } 863 final MailboxListItem targetItem = mDropTargetView; 864 // Call either deleteMessage or moveMessage, depending on the target 865 EmailAsyncTask.runAsyncSerial(new Runnable() { 866 @Override 867 public void run() { 868 if (targetItem.mMailboxType == Mailbox.TYPE_TRASH) { 869 for (long messageId: messageIds) { 870 // TODO Get this off UI thread (put in clip) 871 Message msg = Message.restoreMessageWithId(mActivity, messageId); 872 if (msg != null) { 873 controller.deleteMessage(messageId, msg.mAccountKey); 874 } 875 } 876 } else { 877 controller.moveMessage(messageIds, targetItem.mMailboxId); 878 } 879 } 880 }); 881 return true; 882 } 883 884 @Override 885 public boolean onDrag(View view, DragEvent event) { 886 boolean result = false; 887 switch (event.getAction()) { 888 case DragEvent.ACTION_DRAG_STARTED: 889 result = onDragStarted(event); 890 break; 891 case DragEvent.ACTION_DRAG_ENTERED: 892 // The drag has entered the ListView window 893 if (DEBUG_DRAG_DROP) { 894 Log.d(TAG, "=== Drag entered; targetId: " + mDropTargetId); 895 } 896 break; 897 case DragEvent.ACTION_DRAG_EXITED: 898 // The drag has left the building 899 if (DEBUG_DRAG_DROP) { 900 Log.d(TAG, "=== Drag exited; targetId: " + mDropTargetId); 901 } 902 onDragExited(); 903 break; 904 case DragEvent.ACTION_DRAG_ENDED: 905 // The drag is over 906 if (DEBUG_DRAG_DROP) { 907 Log.d(TAG, "=== Drag ended"); 908 } 909 onDragEnded(); 910 break; 911 case DragEvent.ACTION_DRAG_LOCATION: 912 // We're moving around within our window; handle scroll, if necessary 913 onDragLocation(event); 914 break; 915 case DragEvent.ACTION_DROP: 916 // The drag item was dropped 917 if (DEBUG_DRAG_DROP) { 918 Log.d(TAG, "=== Drop"); 919 } 920 result = onDrop(event); 921 break; 922 default: 923 break; 924 } 925 return result; 926 } 927} 928