ShortcutCursor.java revision fde948e69f59589cf0d217ea414af7947de600bb
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.quicksearchbox; 18 19import android.util.Log; 20 21import java.util.HashSet; 22 23/** 24 * A SuggestionCursor that allows shortcuts to be updated by overlaying 25 * with results from another cursor. 26 */ 27class ShortcutCursor extends ListSuggestionCursor { 28 private static final boolean DBG = true; 29 private static final String TAG = "QSB.ShortcutCursor"; 30 31 // mShortcuts is used to close the underlying cursor when we're closed. 32 private final CursorBackedSuggestionCursor mShortcuts; 33 // mRefreshed contains all the cursors that have been refreshed, so that 34 // they can be closed when ShortcutCursor is closed. 35 private final HashSet<SuggestionCursor> mRefreshed; 36 37 private boolean mClosed; 38 39 public ShortcutCursor(CursorBackedSuggestionCursor shortcuts) { 40 super(shortcuts.getUserQuery()); 41 mShortcuts = shortcuts; 42 mRefreshed = new HashSet<SuggestionCursor>(); 43 int count = shortcuts.getCount(); 44 for (int i = 0; i < count; i++) { 45 shortcuts.moveTo(i); 46 if (shortcuts.getSuggestionSource() != null) { 47 add(new SuggestionPosition(shortcuts)); 48 } 49 } 50 } 51 52 /** 53 * Updates this SuggestionCursor with a refreshed result from another. 54 * Since this modifies the cursor, it should be called on the UI thread. 55 * This class assumes responsibility for closing refreshed. 56 */ 57 public void refresh(Source source, String shortcutId, SuggestionCursor refreshed) { 58 if (DBG) Log.d(TAG, "refresh " + shortcutId); 59 if (mClosed) { 60 if (refreshed != null) { 61 refreshed.close(); 62 } 63 return; 64 } 65 if (refreshed != null) { 66 mRefreshed.add(refreshed); 67 } 68 int count = getCount(); 69 for (int i = 0; i < count; i++) { 70 moveTo(i); 71 if (shortcutId.equals(getShortcutId()) && source.equals(getSuggestionSource())) { 72 if (refreshed != null && refreshed.getCount() > 0) { 73 replaceRow(new SuggestionPosition(refreshed)); 74 } else { 75 removeRow(); 76 } 77 notifyDataSetChanged(); 78 break; 79 } 80 } 81 } 82 83 @Override 84 public void close() { 85 if (DBG) Log.d(TAG, "close()"); 86 if (mClosed) { 87 throw new IllegalStateException("Double close()"); 88 } 89 mClosed = true; 90 mShortcuts.close(); 91 for (SuggestionCursor cursor : mRefreshed) { 92 cursor.close(); 93 } 94 super.close(); 95 } 96}