CalendarController.java 20 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.calendar;

19 20 21
import static android.provider.Calendar.EVENT_BEGIN_TIME;
import static android.provider.Calendar.EVENT_END_TIME;

Erik's avatar
Erik committed
22
import android.accounts.Account;
Michael Chan's avatar
Michael Chan committed
23
import android.app.Activity;
Erik's avatar
Erik committed
24
import android.content.ContentResolver;
25
import android.content.ContentUris;
26
import android.content.Context;
27
import android.content.Intent;
Erik's avatar
Erik committed
28
import android.database.Cursor;
29
import android.net.Uri;
Erik's avatar
Erik committed
30
import android.os.AsyncTask;
Erik's avatar
Erik committed
31 32
import android.os.Bundle;
import android.provider.Calendar.Calendars;
33
import android.provider.Calendar.Events;
Erik's avatar
Erik committed
34
import android.text.TextUtils;
35
import android.text.format.Time;
Michael Chan's avatar
Michael Chan committed
36 37
import android.util.Log;

38 39
import java.util.Iterator;
import java.util.LinkedHashMap;
40
import java.util.LinkedList;
41
import java.util.Map.Entry;
Michael Chan's avatar
Michael Chan committed
42 43
import java.util.WeakHashMap;

Erik's avatar
Erik committed
44
public class CalendarController {
45
    private static final boolean DEBUG = true;
Michael Chan's avatar
Michael Chan committed
46
    private static final String TAG = "CalendarController";
Erik's avatar
Erik committed
47 48 49
    private static final String REFRESH_SELECTION = Calendars.SYNC_EVENTS + "=?";
    private static final String[] REFRESH_ARGS = new String[] { "1" };
    private static final String REFRESH_ORDER = Calendars._SYNC_ACCOUNT + ","
Erik's avatar
Erik committed
50
            + Calendars._SYNC_ACCOUNT_TYPE;
Michael Chan's avatar
Michael Chan committed
51

52 53
    private Context mContext;

54 55 56 57 58 59
    // This uses a LinkedHashMap so that we can replace fragments based on the
    // view id they are being expanded into since we can't guarantee a reference
    // to the handler will be findable
    private LinkedHashMap<Integer,EventHandler> eventHandlers =
            new LinkedHashMap<Integer,EventHandler>(5);
    private LinkedList<Integer> mToBeRemovedEventHandlers = new LinkedList<Integer>();
60
    private boolean mDispatchInProgress;
Michael Chan's avatar
Michael Chan committed
61

62 63 64
    private static WeakHashMap<Context, CalendarController> instances =
        new WeakHashMap<Context, CalendarController>();

65
    private WeakHashMap<Object, Long> filters = new WeakHashMap<Object, Long>(1);
66

67
    private int mViewType = -1;
68
    private int mDetailViewType = -1;
69
    private int mPreviousViewType = -1;
70 71
    private Time mTime = new Time();

Erik's avatar
Erik committed
72 73
    private AsyncQueryService mService;

74
    /**
Michael Chan's avatar
Michael Chan committed
75
     * One of the event types that are sent to or from the controller
76
     */
Erik's avatar
Erik committed
77
    public interface EventType {
78
        final long CREATE_EVENT = 1L;
Michael Chan's avatar
Michael Chan committed
79 80 81 82
        final long VIEW_EVENT = 1L << 1;
        final long EDIT_EVENT = 1L << 2;
        final long DELETE_EVENT = 1L << 3;

83
        final long GO_TO = 1L << 4;
Michael Chan's avatar
Michael Chan committed
84

85 86
        final long LAUNCH_MANAGE_CALENDARS = 1L << 5;
        final long LAUNCH_SETTINGS = 1L << 6;
Erik's avatar
Erik committed
87 88

        final long EVENTS_CHANGED = 1L << 7;
89 90

        final long SEARCH = 1L << 8;
Michael Chan's avatar
Michael Chan committed
91
    }
92 93

    /**
Michael Chan's avatar
Michael Chan committed
94
     * One of the Agenda/Day/Week/Month view types
95
     */
Erik's avatar
Erik committed
96
    public interface ViewType {
97
        final int DETAIL = -1;
98 99 100 101 102
        final int CURRENT = 0;
        final int AGENDA = 1;
        final int DAY = 2;
        final int WEEK = 3;
        final int MONTH = 4;
Michael Chan's avatar
Michael Chan committed
103 104
    }

Erik's avatar
Erik committed
105
    public static class EventInfo {
106 107 108 109 110 111 112 113 114
        public long eventType; // one of the EventType
        public int viewType; // one of the ViewType
        public long id; // event id
        public Time selectedTime; // the selected time in focus
        public Time startTime; // start of a range of time.
        public Time endTime; // end of a range of time.
        public int x; // x coordinate in the activity space
        public int y; // y coordinate in the activity space
        public String query; // query for a user search
Michael Chan's avatar
Michael Chan committed
115 116
    }

117
    // FRAG_TODO remove unneeded api's
Erik's avatar
Erik committed
118
    public interface EventHandler {
Michael Chan's avatar
Michael Chan committed
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
        long getSupportedEventTypes();
        void handleEvent(EventInfo event);

        /**
         * Returns the time in millis of the selected event in this view.
         * @return the selected time in UTC milliseconds.
         */
        long getSelectedTime();

        /**
         * Changes the view to include the given time.
         * @param time the desired time to view.
         * @animate enable animation
         */
        void goTo(Time time, boolean animate);

        /**
         * Changes the view to include today's date.
         */
        void goToToday();

        /**
         * This is called when the user wants to create a new event and returns
         * true if the new event should default to an all-day event.
         * @return true if the new event should be an all-day event.
         */
        boolean getAllDay();

        /**
Erik's avatar
Erik committed
148 149
         * This notifies the handler that the database has changed and it should
         * update its view.
Michael Chan's avatar
Michael Chan committed
150 151 152 153
         */
        void eventsChanged();
    }

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    /**
     * Creates and/or returns an instance of CalendarController associated with
     * the supplied context. It is best to pass in the current Activity.
     *
     * @param context The activity if at all possible.
     */
    public static CalendarController getInstance(Context context) {
        synchronized (instances) {
            CalendarController controller = instances.get(context);
            if (controller == null) {
                controller = new CalendarController(context);
                instances.put(context, controller);
            }
            return controller;
        }
    }

Erik's avatar
Erik committed
171 172 173 174 175 176 177 178 179 180
    /**
     * Removes an instance when it is no longer needed. This should be called in
     * an activity's onDestroy method.
     *
     * @param context The activity used to create the controller
     */
    public static void removeInstance(Context context) {
        instances.remove(context);
    }

181
    private CalendarController(Context context) {
182
        mContext = context;
183
        mTime.setToNow();
184 185 186
        mDetailViewType = Utils.getSharedPreference(mContext,
                CalendarPreferenceActivity.KEY_DETAILED_VIEW,
                CalendarPreferenceActivity.DEFAULT_DETAILED_VIEW);
Erik's avatar
Erik committed
187 188 189
        mService = new AsyncQueryService(context) {
            @Override
            protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
Erik's avatar
Erik committed
190
                new RefreshInBackground().execute(cursor);
Erik's avatar
Erik committed
191 192
            }
        };
Michael Chan's avatar
Michael Chan committed
193
    }
194 195

    /**
Michael Chan's avatar
Michael Chan committed
196 197 198 199 200
     * Helper for sending New/View/Edit/Delete events
     *
     * @param sender object of the caller
     * @param eventType one of {@link EventType}
     * @param eventId event id
201 202
     * @param startMillis start time
     * @param endMillis end time
Michael Chan's avatar
Michael Chan committed
203 204
     * @param x x coordinate in the activity space
     * @param y y coordinate in the activity space
205
     */
206 207
    public void sendEventRelatedEvent(Object sender, long eventType, long eventId, long startMillis,
            long endMillis, int x, int y) {
Michael Chan's avatar
Michael Chan committed
208 209 210
        EventInfo info = new EventInfo();
        info.eventType = eventType;
        info.id = eventId;
211 212 213 214
        info.startTime = new Time();
        info.startTime.set(startMillis);
        info.endTime = new Time();
        info.endTime.set(endMillis);
Michael Chan's avatar
Michael Chan committed
215 216 217 218
        info.x = x;
        info.y = y;
        this.sendEvent(sender, info);
    }
219 220

    /**
Michael Chan's avatar
Michael Chan committed
221 222 223 224 225 226
     * Helper for sending non-calendar-event events
     *
     * @param sender object of the caller
     * @param eventType one of {@link EventType}
     * @param start start time
     * @param end end time
227
     * @param eventId event id
Michael Chan's avatar
Michael Chan committed
228
     * @param viewType {@link ViewType}
229
     */
Erik's avatar
Erik committed
230
    public void sendEvent(Object sender, long eventType, Time start, Time end, long eventId,
231
            int viewType) {
Michael Chan's avatar
Michael Chan committed
232 233 234 235 236 237 238 239 240
        EventInfo info = new EventInfo();
        info.eventType = eventType;
        info.startTime = start;
        info.endTime = end;
        info.id = eventId;
        info.viewType = viewType;
        this.sendEvent(sender, info);
    }

Erik's avatar
Erik committed
241
    public void sendEvent(Object sender, final EventInfo event) {
Michael Chan's avatar
Michael Chan committed
242 243
        // TODO Throw exception on invalid events

244 245 246
        if (DEBUG) {
            Log.d(TAG, eventInfoToString(event));
        }
Michael Chan's avatar
Michael Chan committed
247 248 249 250

        Long filteredTypes = filters.get(sender);
        if (filteredTypes != null && (filteredTypes.longValue() & event.eventType) != 0) {
            // Suppress event per filter
251 252 253
            if (DEBUG) {
                Log.d(TAG, "Event suppressed");
            }
Michael Chan's avatar
Michael Chan committed
254 255 256
            return;
        }

257
        mPreviousViewType = mViewType;
Michael Chan's avatar
Michael Chan committed
258

259
        // Fix up view if not specified
260
        if (event.viewType == ViewType.DETAIL) {
261 262
            event.viewType = mDetailViewType;
            mViewType = mDetailViewType;
263
        } else if (event.viewType == ViewType.CURRENT) {
264
            event.viewType = mViewType;
265 266
        } else {
            mViewType = event.viewType;
267 268 269 270

            if (event.viewType == ViewType.AGENDA || event.viewType == ViewType.DAY) {
                mDetailViewType = mViewType;
            }
271 272
        }

273 274 275 276 277 278 279
        // Fix up start time if not specified
        if (event.startTime != null && event.startTime.toMillis(false) != 0) {
            mTime.set(event.startTime);
        }
        event.startTime = mTime;

        boolean handled = false;
280 281 282
        synchronized (this) {
            mDispatchInProgress = true;

283 284 285
            if (DEBUG) {
                Log.d(TAG, "sendEvent: Dispatching to " + eventHandlers.size() + " handlers");
            }
286
            // Dispatch to event handler(s)
287 288 289 290 291
            for (Iterator<Entry<Integer, EventHandler>> handlers =
                    eventHandlers.entrySet().iterator(); handlers.hasNext();) {
                Entry<Integer, EventHandler> entry = handlers.next();
                int key = entry.getKey();
                EventHandler eventHandler = entry.getValue();
292 293
                if (eventHandler != null
                        && (eventHandler.getSupportedEventTypes() & event.eventType) != 0) {
294
                    if (mToBeRemovedEventHandlers.contains(key)) {
295 296 297
                        continue;
                    }
                    eventHandler.handleEvent(event);
298
                    handled = true;
299 300
                }
            }
301

302 303
            // Deregister removed handlers
            if (mToBeRemovedEventHandlers.size() > 0) {
304
                for (Integer zombie : mToBeRemovedEventHandlers) {
305
                    eventHandlers.remove(zombie);
Michael Chan's avatar
Michael Chan committed
306
                }
307
                mToBeRemovedEventHandlers.clear();
Michael Chan's avatar
Michael Chan committed
308
            }
309
            mDispatchInProgress = false;
Michael Chan's avatar
Michael Chan committed
310
        }
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337

        if (!handled) {
            // Launch Calendars, and Settings
            if (event.eventType == EventType.LAUNCH_MANAGE_CALENDARS) {
                launchManageCalendars();
                return;
            } else if (event.eventType == EventType.LAUNCH_SETTINGS) {
                launchSettings();
                return;
            }

            // Create/View/Edit/Delete Event
            long endTime = (event.endTime == null) ? -1 : event.endTime.toMillis(false);
            if (event.eventType == EventType.CREATE_EVENT) {
                launchCreateEvent(event.startTime.toMillis(false), endTime);
                return;
            } else if (event.eventType == EventType.VIEW_EVENT) {
                launchViewEvent(event.id, event.startTime.toMillis(false), endTime);
                return;
            } else if (event.eventType == EventType.EDIT_EVENT) {
                launchEditEvent(event.id, event.startTime.toMillis(false), endTime);
                return;
            } else if (event.eventType == EventType.DELETE_EVENT) {
                launchDeleteEvent(event.id, event.startTime.toMillis(false), endTime);
                return;
            }
        }
Michael Chan's avatar
Michael Chan committed
338 339
    }

340 341 342 343 344 345 346 347
    /**
     * Adds or updates an event handler. This uses a LinkedHashMap so that we can
     * replace fragments based on the view id they are being expanded into.
     *
     * @param key The view id or placeholder for this handler
     * @param eventHandler Typically a fragment or activity in the calendar app
     */
    public void registerEventHandler(int key, EventHandler eventHandler) {
348
        synchronized (this) {
349
            eventHandlers.put(key, eventHandler);
350
        }
Michael Chan's avatar
Michael Chan committed
351 352
    }

353
    public void deregisterEventHandler(Integer key) {
354 355 356
        synchronized (this) {
            if (mDispatchInProgress) {
                // To avoid ConcurrencyException, stash away the event handler for now.
357
                mToBeRemovedEventHandlers.add(key);
358
            } else {
359
                eventHandlers.remove(key);
360 361
            }
        }
Michael Chan's avatar
Michael Chan committed
362 363
    }

364
    // FRAG_TODO doesn't work yet
Erik's avatar
Erik committed
365
    public void filterBroadcasts(Object sender, long eventTypes) {
Michael Chan's avatar
Michael Chan committed
366 367 368
        filters.put(sender, eventTypes);
    }

369 370 371 372 373 374 375
    /**
     * @return the time that this controller is currently pointed at
     */
    public long getTime() {
        return mTime.toMillis(false);
    }

376 377 378 379 380 381 382
    public int getViewType() {
        return mViewType;
    }

    public int getPreviousViewType() {
        return mPreviousViewType;
    }
383

384 385
    private void launchManageCalendars() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
386
        intent.setClass(mContext, SelectCalendarsActivity.class);
387
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
388
        mContext.startActivity(intent);
389 390 391 392
    }

    private void launchSettings() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
393
        intent.setClassName(mContext, CalendarPreferenceActivity.class.getName());
394
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
395
        mContext.startActivity(intent);
396 397 398 399
    }

    private void launchCreateEvent(long startMillis, long endMillis) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
400
        intent.setClassName(mContext, EditEventActivity.class.getName());
401 402
        intent.putExtra(EVENT_BEGIN_TIME, startMillis);
        intent.putExtra(EVENT_END_TIME, endMillis);
403
        mContext.startActivity(intent);
404 405 406 407 408 409
    }

    private void launchViewEvent(long eventId, long startMillis, long endMillis) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri eventUri = ContentUris.withAppendedId(Events.CONTENT_URI, eventId);
        intent.setData(eventUri);
410
        intent.setClassName(mContext, EventInfoActivity.class.getName());
411 412
        intent.putExtra(EVENT_BEGIN_TIME, startMillis);
        intent.putExtra(EVENT_END_TIME, endMillis);
413
        mContext.startActivity(intent);
414 415 416 417 418 419 420
    }

    private void launchEditEvent(long eventId, long startMillis, long endMillis) {
        Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, eventId);
        Intent intent = new Intent(Intent.ACTION_EDIT, uri);
        intent.putExtra(EVENT_BEGIN_TIME, startMillis);
        intent.putExtra(EVENT_END_TIME, endMillis);
421 422
        intent.setClass(mContext, EditEventActivity.class);
        mContext.startActivity(intent);
423 424 425 426 427 428 429 430
    }

    private void launchDeleteEvent(long eventId, long startMillis, long endMillis) {
        launchDeleteEventAndFinish(null, eventId, startMillis, endMillis, -1);
    }

    private void launchDeleteEventAndFinish(Activity parentActivity, long eventId, long startMillis,
            long endMillis, int deleteWhich) {
431
        DeleteEventHelper deleteEventHelper = new DeleteEventHelper(mContext, parentActivity,
432 433 434
                parentActivity != null /* exit when done */);
        deleteEventHelper.delete(startMillis, endMillis, eventId, deleteWhich);
    }
435

Erik's avatar
Erik committed
436 437 438 439 440 441 442 443 444 445 446
    public void refreshCalendars() {
        Log.d(TAG, "RefreshCalendars starting");
        // get the account, url, and current sync state
        mService.startQuery(mService.getNextToken(), null, Calendars.CONTENT_URI,
                new String[] {Calendars._ID, // 0
                        Calendars._SYNC_ACCOUNT, // 1
                        Calendars._SYNC_ACCOUNT_TYPE, // 2
                        },
                REFRESH_SELECTION, REFRESH_ARGS, REFRESH_ORDER);
    }

Erik's avatar
Erik committed
447 448 449 450 451 452 453 454 455 456 457 458 459
    private class RefreshInBackground extends AsyncTask<Cursor, Integer, Integer> {
        /* (non-Javadoc)
         * @see android.os.AsyncTask#doInBackground(Params[])
         */
        @Override
        protected Integer doInBackground(Cursor... params) {
            if (params.length != 1) {
                return null;
            }
            Cursor cursor = params[0];
            if (cursor == null) {
                return null;
            }
Erik's avatar
Erik committed
460

Erik's avatar
Erik committed
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
            String previousAccount = null;
            String previousType = null;
            Log.d(TAG, "Refreshing " + cursor.getCount() + " calendars");
            try {
                while (cursor.moveToNext()) {
                    Account account = null;
                    String accountName = cursor.getString(1);
                    String accountType = cursor.getString(2);
                    // Only need to schedule one sync per account and they're
                    // ordered by account,type
                    if (TextUtils.equals(accountName, previousAccount) &&
                            TextUtils.equals(accountType, previousType)) {
                        continue;
                    }
                    previousAccount = accountName;
                    previousType = accountType;
                    account = new Account(accountName, accountType);
                    scheduleSync(account, false /* two-way sync */, null);
Erik's avatar
Erik committed
479
                }
Erik's avatar
Erik committed
480 481
            } finally {
                cursor.close();
Erik's avatar
Erik committed
482
            }
Erik's avatar
Erik committed
483
            return null;
Erik's avatar
Erik committed
484 485
        }

Erik's avatar
Erik committed
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
        /**
         * Schedule a calendar sync for the account.
         * @param account the account for which to schedule a sync
         * @param uploadChangesOnly if set, specify that the sync should only send
         *   up local changes.  This is typically used for a local sync, a user override of
         *   too many deletions, or a sync after a calendar is unselected.
         * @param url the url feed for the calendar to sync (may be null, in which case a poll of
         *   all feeds is done.)
         */
        void scheduleSync(Account account, boolean uploadChangesOnly, String url) {
            Bundle extras = new Bundle();
            if (uploadChangesOnly) {
                extras.putBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, uploadChangesOnly);
            }
            if (url != null) {
                extras.putString("feed", url);
                extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
            }
            ContentResolver.requestSync(account, Calendars.CONTENT_URI.getAuthority(), extras);
Erik's avatar
Erik committed
505 506 507
        }
    }

508 509 510 511
    private String eventInfoToString(EventInfo eventInfo) {
        String tmp = "Unknown";

        StringBuilder builder = new StringBuilder();
512
        if ((eventInfo.eventType & EventType.GO_TO) != 0) {
513 514 515 516 517 518 519 520 521 522 523 524 525
            tmp = "Go to time/event";
        } else if ((eventInfo.eventType & EventType.CREATE_EVENT) != 0) {
            tmp = "New event";
        } else if ((eventInfo.eventType & EventType.VIEW_EVENT) != 0) {
            tmp = "View event";
        } else if ((eventInfo.eventType & EventType.EDIT_EVENT) != 0) {
            tmp = "Edit event";
        } else if ((eventInfo.eventType & EventType.DELETE_EVENT) != 0) {
            tmp = "Delete event";
        } else if ((eventInfo.eventType & EventType.LAUNCH_MANAGE_CALENDARS) != 0) {
            tmp = "Launch select calendar";
        } else if ((eventInfo.eventType & EventType.LAUNCH_SETTINGS) != 0) {
            tmp = "Launch settings";
526 527
        } else if ((eventInfo.eventType & EventType.EVENTS_CHANGED) != 0) {
            tmp = "Refresh events";
528 529
        } else if ((eventInfo.eventType & EventType.SEARCH) != 0) {
            tmp = "Search";
530 531 532 533
        }
        builder.append(tmp);
        builder.append(": id=");
        builder.append(eventInfo.id);
534 535 536
        builder.append(", selected=");
        builder.append(eventInfo.selectedTime);
        builder.append(", start=");
537
        builder.append(eventInfo.startTime);
538
        builder.append(", end=");
539 540 541 542 543 544 545 546 547
        builder.append(eventInfo.endTime);
        builder.append(", viewType=");
        builder.append(eventInfo.viewType);
        builder.append(", x=");
        builder.append(eventInfo.x);
        builder.append(", y=");
        builder.append(eventInfo.y);
        return builder.toString();
    }
548
}