OSDN Git Service

542e0dbb2468e0a61b7099ccd65c01618beb3c07
[android-x86/packages-apps-Calendar.git] / src / com / android / calendar / SelectCalendarsAdapter.java
1 /*
2  * Copyright (C) 2007 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
17 package com.android.calendar;
18
19 import android.accounts.AccountManager;
20 import android.accounts.AuthenticatorDescription;
21 import android.content.AsyncQueryHandler;
22 import android.content.ContentResolver;
23 import android.content.ContentUris;
24 import android.content.ContentValues;
25 import android.content.Context;
26 import android.content.pm.PackageManager;
27 import android.database.Cursor;
28 import android.database.MatrixCursor;
29 import android.net.Uri;
30 import android.provider.Calendar.Calendars;
31 import android.text.TextUtils;
32 import android.util.Log;
33 import android.view.LayoutInflater;
34 import android.view.View;
35 import android.view.ViewGroup;
36 import android.widget.CursorTreeAdapter;
37 import android.widget.TextView;
38
39 import java.util.HashMap;
40 import java.util.Iterator;
41 import java.util.Map;
42
43 public class SelectCalendarsAdapter extends CursorTreeAdapter implements View.OnClickListener {
44
45     private static final String TAG = "Calendar";
46
47     private static final String COLLATE_NOCASE = " COLLATE NOCASE";
48     private static final String IS_PRIMARY = "\"primary\"";
49     private static final String CALENDARS_ORDERBY = IS_PRIMARY + " DESC," + Calendars.DISPLAY_NAME +
50             COLLATE_NOCASE;
51     private static final String ACCOUNT_SELECTION = Calendars._SYNC_ACCOUNT + "=?";
52
53     // The drawables used for the button to change the visible and sync states on a calendar
54     private static final int[] SYNC_VIS_BUTTON_RES = new int[] {
55         R.drawable.widget_show,
56         R.drawable.widget_sync,
57         R.drawable.widget_off
58     };
59
60     private final LayoutInflater mInflater;
61     private final ContentResolver mResolver;
62     private final SelectCalendarsActivity mActivity;
63     private final View mView;
64     private final static Runnable mStopRefreshing = new Runnable() {
65         public void run() {
66             mRefresh = false;
67         }
68     };
69     private Map<String, AuthenticatorDescription> mTypeToAuthDescription
70         = new HashMap<String, AuthenticatorDescription>();
71     protected AuthenticatorDescription[] mAuthDescs;
72
73     // These track changes to the visible (selected) and synced state of calendars
74     private Map<Long, Boolean[]> mCalendarChanges
75         = new HashMap<Long, Boolean[]>();
76     private Map<Long, Boolean[]> mCalendarInitialStates
77         = new HashMap<Long, Boolean[]>();
78     private static final int SELECTED_INDEX = 0;
79     private static final int SYNCED_INDEX = 1;
80     private static final int CHANGES_SIZE = 2;
81
82     // This is for keeping MatrixCursor copies so that we can requery in the background.
83     private static Map<String, Cursor> mChildrenCursors
84         = new HashMap<String, Cursor>();
85
86     private static AsyncCalendarsUpdater mCalendarsUpdater;
87     // This is to keep our update tokens separate from other tokens. Since we cancel old updates
88     // when a new update comes in, we'd like to leave a token space that won't be canceled.
89     private static final int MIN_UPDATE_TOKEN = 1000;
90     private static int mUpdateToken = MIN_UPDATE_TOKEN;
91     // How long to wait between requeries of the calendars to see if anything has changed.
92     private static final int REFRESH_DELAY = 5000;
93     // How long to keep refreshing for
94     private static final int REFRESH_DURATION = 60000;
95     private static boolean mRefresh = true;
96     private int mNumAccounts;
97
98     private static String syncedVisible;
99     private static String syncedNotVisible;
100     private static String notSyncedNotVisible;
101
102     // This is to keep track of whether or not multiple calendars have the same display name
103     private static HashMap<String, Boolean> mIsDuplicateName = new HashMap<String, Boolean>();
104
105     private static final String[] PROJECTION = new String[] {
106       Calendars._ID,
107       Calendars._SYNC_ACCOUNT,
108       Calendars.OWNER_ACCOUNT,
109       Calendars.DISPLAY_NAME,
110       Calendars.COLOR,
111       Calendars.SELECTED,
112       Calendars.SYNC_EVENTS,
113       "(" + Calendars._SYNC_ACCOUNT + "=" + Calendars.OWNER_ACCOUNT + ") AS " + IS_PRIMARY,
114     };
115     //Keep these in sync with the projection
116     private static final int ID_COLUMN = 0;
117     private static final int ACCOUNT_COLUMN = 1;
118     private static final int OWNER_COLUMN = 2;
119     private static final int NAME_COLUMN = 3;
120     private static final int COLOR_COLUMN = 4;
121     private static final int SELECTED_COLUMN = 5;
122     private static final int SYNCED_COLUMN = 6;
123     private static final int PRIMARY_COLUMN = 7;
124
125     private class AsyncCalendarsUpdater extends AsyncQueryHandler {
126
127         public AsyncCalendarsUpdater(ContentResolver cr) {
128             super(cr);
129         }
130
131         @Override
132         protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
133             if(cursor == null) {
134                 return;
135             }
136
137             Cursor currentCursor = mChildrenCursors.get(cookie);
138             // Check if the new cursor has the same content as our old cursor
139             if (currentCursor != null) {
140                 if (Utils.compareCursors(currentCursor, cursor)) {
141                     cursor.close();
142                     return;
143                 }
144             }
145             // If not then make a new matrix cursor for our Map
146             MatrixCursor newCursor = Utils.matrixCursorFromCursor(cursor);
147             cursor.close();
148             // And update our list of duplicated names
149             Utils.checkForDuplicateNames(mIsDuplicateName, newCursor, NAME_COLUMN);
150
151             mChildrenCursors.put((String)cookie, newCursor);
152             try {
153                 setChildrenCursor(token, newCursor);
154                 mActivity.startManagingCursor(newCursor);
155             } catch (NullPointerException e) {
156                 Log.w(TAG, "Adapter expired, try again on the next query: " + e);
157             }
158             // Clean up our old cursor if we had one. We have to do this after setting the new
159             // cursor so that our view doesn't throw on an invalid cursor.
160             if (currentCursor != null) {
161                 mActivity.stopManagingCursor(currentCursor);
162                 currentCursor.close();
163             }
164         }
165     }
166
167
168
169     /**
170      * Method for changing the sync/vis state when a calendar's button is pressed.
171      *
172      * This gets called when the MultiStateButton for a calendar is clicked. It cycles the sync/vis
173      * state for the associated calendar and saves a change of state to a hashmap. It also compares
174      * against the original value and removes any changes from the hashmap if this is back
175      * at its initial state.
176      */
177     public void onClick(View v) {
178         View view = (View)v.getTag();
179         long id = (Long)view.getTag();
180         Uri uri = ContentUris.withAppendedId(Calendars.CONTENT_URI, id);
181         String status = syncedNotVisible;
182         Boolean[] change;
183         Boolean[] initialState = mCalendarInitialStates.get(id);
184         if (mCalendarChanges.containsKey(id)) {
185             change = mCalendarChanges.get(id);
186         } else {
187             change = new Boolean[CHANGES_SIZE];
188             change[SELECTED_INDEX] = initialState[SELECTED_INDEX];
189             change[SYNCED_INDEX] = initialState[SYNCED_INDEX];
190             mCalendarChanges.put(id, change);
191         }
192
193         if (change[SELECTED_INDEX]) {
194             change[SELECTED_INDEX] = false;
195             status = syncedNotVisible;
196         }
197         else if (change[SYNCED_INDEX]) {
198             change[SYNCED_INDEX] = false;
199             status = notSyncedNotVisible;
200         }
201         else
202         {
203             change[SYNCED_INDEX] = true;
204             change[SELECTED_INDEX] = true;
205             status = syncedVisible;
206         }
207         setText(view, R.id.status, status);
208         if (change[SELECTED_INDEX] == initialState[SELECTED_INDEX] &&
209                 change[SYNCED_INDEX] == initialState[SYNCED_INDEX]) {
210             mCalendarChanges.remove(id);
211         }
212     }
213
214     public SelectCalendarsAdapter(Context context, Cursor cursor, SelectCalendarsActivity act) {
215         super(cursor, context);
216         syncedVisible = context.getString(R.string.synced_visible);
217         syncedNotVisible = context.getString(R.string.synced_not_visible);
218         notSyncedNotVisible = context.getString(R.string.not_synced_not_visible);
219
220         mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
221         mResolver = context.getContentResolver();
222         mActivity = act;
223         if (mCalendarsUpdater == null) {
224             mCalendarsUpdater = new AsyncCalendarsUpdater(mResolver);
225         }
226
227         mNumAccounts = cursor.getCount();
228         if(mNumAccounts == 0) {
229             //Should never happen since Calendar requires an account exist to use it.
230             Log.e(TAG, "SelectCalendarsAdapter: No accounts were returned!");
231         }
232         //Collect proper description for account types
233         mAuthDescs = AccountManager.get(context).getAuthenticatorTypes();
234         for (int i = 0; i < mAuthDescs.length; i++) {
235             mTypeToAuthDescription.put(mAuthDescs[i].type, mAuthDescs[i]);
236         }
237         mView = mActivity.getExpandableListView();
238         mRefresh = true;
239     }
240
241     public void startRefreshStopDelay() {
242         mRefresh = true;
243         mView.postDelayed(mStopRefreshing, REFRESH_DURATION);
244     }
245
246     public void cancelRefreshStopDelay() {
247         mView.removeCallbacks(mStopRefreshing);
248     }
249
250     /*
251      * Write back the changes that have been made. The sync code will pick up any changes and
252      * do updates on its own.
253      */
254     public void doSaveAction() {
255         // Cancel the previous operation
256         mCalendarsUpdater.cancelOperation(mUpdateToken);
257         mUpdateToken++;
258         // This is to allow us to do queries and updates with the same AsyncQueryHandler without
259         // accidently canceling queries.
260         if(mUpdateToken < MIN_UPDATE_TOKEN) mUpdateToken = MIN_UPDATE_TOKEN;
261
262         Iterator<Long> changeKeys = mCalendarChanges.keySet().iterator();
263         while (changeKeys.hasNext()) {
264             long id = changeKeys.next();
265             Boolean[] change = mCalendarChanges.get(id);
266             int newSelected = change[SELECTED_INDEX] ? 1 : 0;
267             int newSynced = change[SYNCED_INDEX] ? 1 : 0;
268
269             Uri uri = ContentUris.withAppendedId(Calendars.CONTENT_URI, id);
270             ContentValues values = new ContentValues();
271             values.put(Calendars.SELECTED, newSelected);
272             values.put(Calendars.SYNC_EVENTS, newSynced);
273             mCalendarsUpdater.startUpdate(mUpdateToken, id, uri, values, null, null);
274         }
275     }
276
277     private static void setText(View view, int id, String text) {
278         if (TextUtils.isEmpty(text)) {
279             return;
280         }
281         TextView textView = (TextView) view.findViewById(id);
282         textView.setText(text);
283     }
284
285     /**
286      * Gets the label associated with a particular account type. If none found, return null.
287      * @param accountType the type of account
288      * @return a CharSequence for the label or null if one cannot be found.
289      */
290     protected CharSequence getLabelForType(final String accountType) {
291         CharSequence label = null;
292         if (mTypeToAuthDescription.containsKey(accountType)) {
293              try {
294                  AuthenticatorDescription desc = mTypeToAuthDescription.get(accountType);
295                  Context authContext = mActivity.createPackageContext(desc.packageName, 0);
296                  label = authContext.getResources().getText(desc.labelId);
297              } catch (PackageManager.NameNotFoundException e) {
298                  Log.w(TAG, "No label for account type " + ", type " + accountType);
299              }
300         }
301         return label;
302     }
303
304     @Override
305     protected void bindChildView(View view, Context context, Cursor cursor, boolean isLastChild) {
306         String account = cursor.getString(ACCOUNT_COLUMN);
307         String status = notSyncedNotVisible;
308         int state = 2;
309         int position = cursor.getPosition();
310         long id = cursor.getLong(ID_COLUMN);
311
312         // First see if the user has already changed the state of this calendar
313         Boolean[] initialState = mCalendarChanges.get(id);
314         // if we haven't already started making changes update the initial state in case it changed
315         if (initialState == null) {
316             initialState = new Boolean[CHANGES_SIZE];
317             initialState[SELECTED_INDEX] = cursor.getInt(SELECTED_COLUMN) == 1;
318             initialState[SYNCED_INDEX] = cursor.getInt(SYNCED_COLUMN) == 1;
319             mCalendarInitialStates.put(id, initialState);
320         }
321
322         if(initialState[SYNCED_INDEX]) {
323             if(initialState[SELECTED_INDEX]) {
324                 status = syncedVisible;
325                 state = 0;
326             } else {
327                 status = syncedNotVisible;
328                 state = 1;
329             }
330         }
331
332         view.findViewById(R.id.color)
333             .setBackgroundDrawable(Utils.getColorChip(cursor.getInt(COLOR_COLUMN)));
334         String name = cursor.getString(NAME_COLUMN);
335         String owner = cursor.getString(OWNER_COLUMN);
336         if (mIsDuplicateName.containsKey(name) && mIsDuplicateName.get(name) &&
337                 !name.equalsIgnoreCase(owner)) {
338             name = new StringBuilder(name)
339                     .append(Utils.OPEN_EMAIL_MARKER)
340                     .append(owner)
341                     .append(Utils.CLOSE_EMAIL_MARKER)
342                     .toString();
343         }
344         setText(view, R.id.calendar, name);
345         setText(view, R.id.status, status);
346         MultiStateButton button = (MultiStateButton) view.findViewById(R.id.multiStateButton);
347
348         //Set up the listeners so a click on the button will change the state.
349         //The view already uses the onChildClick method in the activity.
350         button.setTag(view);
351         view.setTag(id);
352         button.setOnClickListener(this);
353         button.setButtonResources(SYNC_VIS_BUTTON_RES);
354         button.setState(state);
355     }
356
357     @Override
358     protected void bindGroupView(View view, Context context, Cursor cursor, boolean isExpanded) {
359         int accountColumn = cursor.getColumnIndexOrThrow(Calendars._SYNC_ACCOUNT);
360         int accountTypeColumn = cursor.getColumnIndexOrThrow(Calendars._SYNC_ACCOUNT_TYPE);
361         String account = cursor.getString(accountColumn);
362         String accountType = cursor.getString(accountTypeColumn);
363         setText(view, R.id.account, account);
364         setText(view, R.id.account_type, getLabelForType(accountType).toString());
365     }
366
367     @Override
368     protected Cursor getChildrenCursor(Cursor groupCursor) {
369         int accountColumn = groupCursor.getColumnIndexOrThrow(Calendars._SYNC_ACCOUNT);
370         String account = groupCursor.getString(accountColumn);
371         //Get all the calendars for just this account.
372         Cursor childCursor = mChildrenCursors.get(account);
373         new RefreshCalendars(groupCursor.getPosition(), account).run();
374         return childCursor;
375     }
376
377     @Override
378     protected View newChildView(Context context, Cursor cursor, boolean isLastChild,
379             ViewGroup parent) {
380         return mInflater.inflate(R.layout.calendar_item, parent, false);
381     }
382
383     @Override
384     protected View newGroupView(Context context, Cursor cursor, boolean isExpanded,
385             ViewGroup parent) {
386         return mInflater.inflate(R.layout.account_item, parent, false);
387     }
388
389     private class RefreshCalendars implements Runnable {
390
391         int mToken;
392         Object mAccount;
393
394         public RefreshCalendars(int token, Object cookie) {
395             mToken = token;
396             mAccount = cookie;
397         }
398
399         public void run() {
400             mCalendarsUpdater.cancelOperation(mToken);
401             // Set up a refresh for some point in the future if we haven't stopped updates yet
402             if(mRefresh) {
403                 mView.postDelayed(new RefreshCalendars(mToken, mAccount), REFRESH_DELAY);
404             }
405             mCalendarsUpdater.startQuery(mToken,
406                     mAccount,
407                     Calendars.CONTENT_URI, PROJECTION,
408                     ACCOUNT_SELECTION,
409                     new String[] { mAccount.toString() } /*selectionArgs*/,
410                     CALENDARS_ORDERBY);
411         }
412     }
413 }