OSDN Git Service

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