CalendarController.java 28.5 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;

RoboErik's avatar
RoboErik committed
19 20
import static android.provider.CalendarContract.EXTRA_EVENT_BEGIN_TIME;
import static android.provider.CalendarContract.EXTRA_EVENT_END_TIME;
21

Erik's avatar
Erik committed
22
import com.android.calendar.event.EditEventActivity;
23
import com.android.calendar.selectcalendars.SelectVisibleCalendarsActivity;
Erik's avatar
Erik committed
24

Erik's avatar
Erik committed
25
import android.accounts.Account;
Michael Chan's avatar
Michael Chan committed
26
import android.app.Activity;
27 28 29
import android.app.SearchManager;
import android.app.SearchableInfo;
import android.content.ComponentName;
Erik's avatar
Erik committed
30
import android.content.ContentResolver;
31
import android.content.ContentUris;
32
import android.content.Context;
33
import android.content.Intent;
Erik's avatar
Erik committed
34
import android.database.Cursor;
35
import android.net.Uri;
Erik's avatar
Erik committed
36
import android.os.AsyncTask;
Erik's avatar
Erik committed
37
import android.os.Bundle;
38 39
import android.provider.CalendarContract.Calendars;
import android.provider.CalendarContract.Events;
Erik's avatar
Erik committed
40
import android.text.TextUtils;
41
import android.text.format.Time;
Michael Chan's avatar
Michael Chan committed
42 43
import android.util.Log;

44 45
import java.util.Iterator;
import java.util.LinkedHashMap;
46
import java.util.LinkedList;
47
import java.util.Map.Entry;
Michael Chan's avatar
Michael Chan committed
48 49
import java.util.WeakHashMap;

Erik's avatar
Erik committed
50
public class CalendarController {
51
    private static final boolean DEBUG = false;
Michael Chan's avatar
Michael Chan committed
52
    private static final String TAG = "CalendarController";
Erik's avatar
Erik committed
53 54
    private static final String REFRESH_SELECTION = Calendars.SYNC_EVENTS + "=?";
    private static final String[] REFRESH_ARGS = new String[] { "1" };
RoboErik's avatar
RoboErik committed
55 56
    private static final String REFRESH_ORDER = Calendars.ACCOUNT_NAME + ","
            + Calendars.ACCOUNT_TYPE;
Michael Chan's avatar
Michael Chan committed
57

Erik's avatar
Erik committed
58 59
    public static final String EVENT_EDIT_ON_LAUNCH = "editMode";

Erik's avatar
Erik committed
60 61 62 63 64
    public static final int MIN_CALENDAR_YEAR = 1970;
    public static final int MAX_CALENDAR_YEAR = 2036;
    public static final int MIN_CALENDAR_WEEK = 0;
    public static final int MAX_CALENDAR_WEEK = 3497; // weeks between 1/1/1970 and 1/1/2037

65
    public static final String EVENT_ATTENDEE_RESPONSE = "attendeeResponse";
66 67
    public static final int ATTENDEE_NO_RESPONSE = -1;

68 69
    private Context mContext;

70 71 72 73 74 75
    // 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>();
76 77
    private LinkedHashMap<Integer, EventHandler> mToBeAddedEventHandlers = new LinkedHashMap<
            Integer, EventHandler>();
Isaac Katzenelson's avatar
Isaac Katzenelson committed
78
    private volatile int mDispatchInProgressCounter = 0;
Michael Chan's avatar
Michael Chan committed
79

80 81 82
    private static WeakHashMap<Context, CalendarController> instances =
        new WeakHashMap<Context, CalendarController>();

83
    private WeakHashMap<Object, Long> filters = new WeakHashMap<Object, Long>(1);
84

85
    private int mViewType = -1;
86
    private int mDetailViewType = -1;
87
    private int mPreviousViewType = -1;
88
    private long mEventId = -1;
89 90
    private Time mTime = new Time();

Erik's avatar
Erik committed
91 92
    private AsyncQueryService mService;

93 94 95 96 97 98 99
    private Runnable mUpdateTimezone = new Runnable() {
        @Override
        public void run() {
            mTime.switchTimezone(Utils.getTimeZone(mContext, this));
        }
    };

100
    /**
Michael Chan's avatar
Michael Chan committed
101
     * One of the event types that are sent to or from the controller
102
     */
Erik's avatar
Erik committed
103
    public interface EventType {
104
        final long CREATE_EVENT = 1L;
105 106

        // Simple view of an event
Michael Chan's avatar
Michael Chan committed
107
        final long VIEW_EVENT = 1L << 1;
108 109 110 111

        // Full detail view in read only mode
        final long VIEW_EVENT_DETAILS = 1L << 2;

Erik's avatar
Erik committed
112
        // full detail view in edit mode
113 114 115
        final long EDIT_EVENT = 1L << 3;

        final long DELETE_EVENT = 1L << 4;
Michael Chan's avatar
Michael Chan committed
116

117
        final long GO_TO = 1L << 5;
Michael Chan's avatar
Michael Chan committed
118

119
        final long LAUNCH_SETTINGS = 1L << 6;
Erik's avatar
Erik committed
120

121
        final long EVENTS_CHANGED = 1L << 7;
122

123
        final long SEARCH = 1L << 8;
124 125

        // User has pressed the home key
126
        final long USER_HOME = 1L << 9;
127 128 129

        // date range has changed, update the title
        final long UPDATE_TITLE = 1L << 10;
130 131 132

        // select which calendars to display
        final long LAUNCH_SELECT_VISIBLE_CALENDARS = 1L << 11;
Michael Chan's avatar
Michael Chan committed
133
    }
134 135

    /**
Michael Chan's avatar
Michael Chan committed
136
     * One of the Agenda/Day/Week/Month view types
137
     */
Erik's avatar
Erik committed
138
    public interface ViewType {
139
        final int DETAIL = -1;
140 141 142 143 144
        final int CURRENT = 0;
        final int AGENDA = 1;
        final int DAY = 2;
        final int WEEK = 3;
        final int MONTH = 4;
145
        final int EDIT = 5;
Michael Chan's avatar
Michael Chan committed
146 147
    }

Erik's avatar
Erik committed
148
    public static class EventInfo {
149 150 151 152 153 154 155 156 157
        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
158
        public ComponentName componentName;  // used in combination with query
159 160 161 162 163 164 165 166 167 168 169 170

        /**
         * For EventType.VIEW_EVENT:
         * It is the default attendee response.
         * Set to {@link #ATTENDEE_NO_RESPONSE}, Calendar.ATTENDEE_STATUS_ACCEPTED,
         * Calendar.ATTENDEE_STATUS_DECLINED, or Calendar.ATTENDEE_STATUS_TENTATIVE.
         * <p>
         * For EventType.GO_TO:
         * Set to {@link #EXTRA_GOTO_TIME} to go to the specified date/time.
         * Set to {@link #EXTRA_GOTO_DATE} to consider the date but ignore the time.
         */
        public long extraLong;
Michael Chan's avatar
Michael Chan committed
171 172
    }

173 174 175 176 177 178 179
    /**
     * Pass to the ExtraLong parameter for EventType.GO_TO to signal the time
     * can be ignored
     */
    public static final long EXTRA_GOTO_DATE = 1;
    public static final long EXTRA_GOTO_TIME = -1;

Erik's avatar
Erik committed
180
    public interface EventHandler {
Michael Chan's avatar
Michael Chan committed
181 182 183 184
        long getSupportedEventTypes();
        void handleEvent(EventInfo event);

        /**
Erik's avatar
Erik committed
185 186
         * This notifies the handler that the database has changed and it should
         * update its view.
Michael Chan's avatar
Michael Chan committed
187 188 189 190
         */
        void eventsChanged();
    }

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
    /**
     * 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
208 209 210 211 212 213 214 215 216 217
    /**
     * 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);
    }

218
    private CalendarController(Context context) {
219
        mContext = context;
220
        mUpdateTimezone.run();
221
        mTime.setToNow();
222
        mDetailViewType = Utils.getSharedPreference(mContext,
223 224
                GeneralPreferences.KEY_DETAILED_VIEW,
                GeneralPreferences.DEFAULT_DETAILED_VIEW);
Erik's avatar
Erik committed
225 226 227
        mService = new AsyncQueryService(context) {
            @Override
            protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
Erik's avatar
Erik committed
228
                new RefreshInBackground().execute(cursor);
Erik's avatar
Erik committed
229 230
            }
        };
Michael Chan's avatar
Michael Chan committed
231
    }
232

233
    public void sendEventRelatedEvent(Object sender, long eventType, long eventId, long startMillis,
234
            long endMillis, int x, int y, long selectedMillis) {
235
        sendEventRelatedEventWithResponse(sender, eventType, eventId, startMillis, endMillis, x, y,
236
                CalendarController.ATTENDEE_NO_RESPONSE, selectedMillis);
237 238
    }

239
    /**
Michael Chan's avatar
Michael Chan committed
240 241 242 243 244
     * Helper for sending New/View/Edit/Delete events
     *
     * @param sender object of the caller
     * @param eventType one of {@link EventType}
     * @param eventId event id
245 246
     * @param startMillis start time
     * @param endMillis end time
Michael Chan's avatar
Michael Chan committed
247 248
     * @param x x coordinate in the activity space
     * @param y y coordinate in the activity space
249 250
     * @param extraLong default response value for the "simple event view". Use
     *            CalendarController.ATTENDEE_NO_RESPONSE for no response.
251
     * @param selectedMillis The time to specify as selected
252
     */
253
    public void sendEventRelatedEventWithResponse(Object sender, long eventType, long eventId,
254
            long startMillis, long endMillis, int x, int y, long extraLong, long selectedMillis) {
Michael Chan's avatar
Michael Chan committed
255 256
        EventInfo info = new EventInfo();
        info.eventType = eventType;
Erik's avatar
Erik committed
257
        if (eventType == EventType.EDIT_EVENT || eventType == EventType.VIEW_EVENT_DETAILS) {
Erik's avatar
Erik committed
258
            info.viewType = ViewType.CURRENT;
259
        }
Michael Chan's avatar
Michael Chan committed
260
        info.id = eventId;
261
        info.startTime = new Time(Utils.getTimeZone(mContext, mUpdateTimezone));
262
        info.startTime.set(startMillis);
263
        if (selectedMillis != -1) {
264
            info.selectedTime = new Time(Utils.getTimeZone(mContext, mUpdateTimezone));
265 266 267 268
            info.selectedTime.set(selectedMillis);
        } else {
            info.selectedTime = info.startTime;
        }
269
        info.endTime = new Time(Utils.getTimeZone(mContext, mUpdateTimezone));
270
        info.endTime.set(endMillis);
Michael Chan's avatar
Michael Chan committed
271 272
        info.x = x;
        info.y = y;
273
        info.extraLong = extraLong;
Michael Chan's avatar
Michael Chan committed
274 275
        this.sendEvent(sender, info);
    }
276 277

    /**
Michael Chan's avatar
Michael Chan committed
278 279 280 281 282 283
     * 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
284
     * @param eventId event id
Michael Chan's avatar
Michael Chan committed
285
     * @param viewType {@link ViewType}
286
     */
Erik's avatar
Erik committed
287
    public void sendEvent(Object sender, long eventType, Time start, Time end, long eventId,
288
            int viewType) {
289 290
        sendEvent(sender, eventType, start, end, start, eventId, viewType, EXTRA_GOTO_TIME, null,
                null);
291 292 293
    }

    /**
294
     * sendEvent() variant with extraLong, search query, and search component name.
295 296
     */
    public void sendEvent(Object sender, long eventType, Time start, Time end, long eventId,
297
            int viewType, long extraLong, String query, ComponentName componentName) {
298 299 300 301 302 303
        sendEvent(sender, eventType, start, end, start, eventId, viewType, extraLong, query,
                componentName);
    }

    public void sendEvent(Object sender, long eventType, Time start, Time end, Time selected,
            long eventId, int viewType, long extraLong, String query, ComponentName componentName) {
Michael Chan's avatar
Michael Chan committed
304 305 306
        EventInfo info = new EventInfo();
        info.eventType = eventType;
        info.startTime = start;
307
        info.selectedTime = selected;
Michael Chan's avatar
Michael Chan committed
308 309 310
        info.endTime = end;
        info.id = eventId;
        info.viewType = viewType;
311 312
        info.query = query;
        info.componentName = componentName;
313
        info.extraLong = extraLong;
Michael Chan's avatar
Michael Chan committed
314 315 316
        this.sendEvent(sender, info);
    }

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

320 321 322
        if (DEBUG) {
            Log.d(TAG, eventInfoToString(event));
        }
Michael Chan's avatar
Michael Chan committed
323 324 325 326

        Long filteredTypes = filters.get(sender);
        if (filteredTypes != null && (filteredTypes.longValue() & event.eventType) != 0) {
            // Suppress event per filter
327 328 329
            if (DEBUG) {
                Log.d(TAG, "Event suppressed");
            }
Michael Chan's avatar
Michael Chan committed
330 331 332
            return;
        }

333
        mPreviousViewType = mViewType;
Michael Chan's avatar
Michael Chan committed
334

335
        // Fix up view if not specified
336
        if (event.viewType == ViewType.DETAIL) {
337 338
            event.viewType = mDetailViewType;
            mViewType = mDetailViewType;
339
        } else if (event.viewType == ViewType.CURRENT) {
340
            event.viewType = mViewType;
341
        } else if (event.viewType != ViewType.EDIT) {
342
            mViewType = event.viewType;
343

344 345
            if (event.viewType == ViewType.AGENDA || event.viewType == ViewType.DAY
                    || (Utils.getAllowWeekForDetailView() && event.viewType == ViewType.WEEK)) {
346 347
                mDetailViewType = mViewType;
            }
348 349
        }

350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
        if (DEBUG) {
            Log.e(TAG, "vvvvvvvvvvvvvvv");
            Log.e(TAG, "Start  " + (event.startTime == null ? "null" : event.startTime.toString()));
            Log.e(TAG, "End    " + (event.endTime == null ? "null" : event.endTime.toString()));
            Log.e(TAG, "Select " + (event.selectedTime == null ? "null" : event.selectedTime.toString()));
            Log.e(TAG, "mTime  " + (mTime == null ? "null" : mTime.toString()));
        }

        long startMillis = 0;
        if (event.startTime != null) {
            startMillis = event.startTime.toMillis(false);
        }

        // Set mTime if selectedTime is set
        if (event.selectedTime != null && event.selectedTime.toMillis(false) != 0) {
            mTime.set(event.selectedTime);
        } else {
            if (startMillis != 0) {
                // selectedTime is not set so set mTime to startTime iff it is not
                // within start and end times
                long mtimeMillis = mTime.toMillis(false);
                if (mtimeMillis < startMillis
                        || (event.endTime != null && mtimeMillis > event.endTime.toMillis(false))) {
                    mTime.set(event.startTime);
                }
            }
            event.selectedTime = mTime;
        }

379
        // Fix up start time if not specified
380 381 382 383 384 385 386 387 388
        if (startMillis == 0) {
            event.startTime = mTime;
        }
        if (DEBUG) {
            Log.e(TAG, "Start  " + (event.startTime == null ? "null" : event.startTime.toString()));
            Log.e(TAG, "End    " + (event.endTime == null ? "null" : event.endTime.toString()));
            Log.e(TAG, "Select " + (event.selectedTime == null ? "null" : event.selectedTime.toString()));
            Log.e(TAG, "mTime  " + (mTime == null ? "null" : mTime.toString()));
            Log.e(TAG, "^^^^^^^^^^^^^^^");
389 390
        }

391
        // Store the eventId if we're entering edit event
Erik's avatar
Erik committed
392 393 394
        if ((event.eventType
                & (EventType.CREATE_EVENT | EventType.EDIT_EVENT | EventType.VIEW_EVENT_DETAILS))
                != 0) {
395 396 397 398 399 400 401
            if (event.id > 0) {
                mEventId = event.id;
            } else {
                mEventId = -1;
            }
        }

402
        boolean handled = false;
403
        synchronized (this) {
Isaac Katzenelson's avatar
Isaac Katzenelson committed
404
            mDispatchInProgressCounter ++;
405

406 407 408
            if (DEBUG) {
                Log.d(TAG, "sendEvent: Dispatching to " + eventHandlers.size() + " handlers");
            }
409
            // Dispatch to event handler(s)
410 411 412 413 414
            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();
415 416
                if (eventHandler != null
                        && (eventHandler.getSupportedEventTypes() & event.eventType) != 0) {
417
                    if (mToBeRemovedEventHandlers.contains(key)) {
418 419 420
                        continue;
                    }
                    eventHandler.handleEvent(event);
421
                    handled = true;
422 423
                }
            }
424

Isaac Katzenelson's avatar
Isaac Katzenelson committed
425
            mDispatchInProgressCounter --;
426

Isaac Katzenelson's avatar
Isaac Katzenelson committed
427 428 429 430 431 432 433 434
            if (mDispatchInProgressCounter == 0) {

                // Deregister removed handlers
                if (mToBeRemovedEventHandlers.size() > 0) {
                    for (Integer zombie : mToBeRemovedEventHandlers) {
                        eventHandlers.remove(zombie);
                    }
                    mToBeRemovedEventHandlers.clear();
Michael Chan's avatar
Michael Chan committed
435
                }
Isaac Katzenelson's avatar
Isaac Katzenelson committed
436 437 438 439 440
                // Add new handlers
                if (mToBeAddedEventHandlers.size() > 0) {
                    for (Entry<Integer, EventHandler> food : mToBeAddedEventHandlers.entrySet()) {
                        eventHandlers.put(food.getKey(), food.getValue());
                    }
441 442
                }
            }
Michael Chan's avatar
Michael Chan committed
443
        }
444 445

        if (!handled) {
446 447
            // Launch Settings
            if (event.eventType == EventType.LAUNCH_SETTINGS) {
448 449 450 451
                launchSettings();
                return;
            }

452 453 454 455 456 457
            // Launch Calendar Visible Selector
            if (event.eventType == EventType.LAUNCH_SELECT_VISIBLE_CALENDARS) {
                launchSelectVisibleCalendars();
                return;
            }

458 459 460 461 462 463 464 465 466
            // 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) {
Erik's avatar
Erik committed
467 468 469 470
                launchEditEvent(event.id, event.startTime.toMillis(false), endTime, true);
                return;
            } else if (event.eventType == EventType.VIEW_EVENT_DETAILS) {
                launchEditEvent(event.id, event.startTime.toMillis(false), endTime, false);
471 472 473 474
                return;
            } else if (event.eventType == EventType.DELETE_EVENT) {
                launchDeleteEvent(event.id, event.startTime.toMillis(false), endTime);
                return;
475 476 477
            } else if (event.eventType == EventType.SEARCH) {
                launchSearch(event.id, event.query, event.componentName);
                return;
478 479
            }
        }
Michael Chan's avatar
Michael Chan committed
480 481
    }

482 483 484 485 486 487 488 489
    /**
     * 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) {
490
        synchronized (this) {
Isaac Katzenelson's avatar
Isaac Katzenelson committed
491
            if (mDispatchInProgressCounter > 0) {
492 493 494 495
                mToBeAddedEventHandlers.put(key, eventHandler);
            } else {
                eventHandlers.put(key, eventHandler);
            }
496
        }
Michael Chan's avatar
Michael Chan committed
497 498
    }

499
    public void deregisterEventHandler(Integer key) {
500
        synchronized (this) {
Isaac Katzenelson's avatar
Isaac Katzenelson committed
501
            if (mDispatchInProgressCounter > 0) {
502
                // To avoid ConcurrencyException, stash away the event handler for now.
503
                mToBeRemovedEventHandlers.add(key);
504
            } else {
505
                eventHandlers.remove(key);
506 507
            }
        }
Michael Chan's avatar
Michael Chan committed
508 509
    }

510
    // FRAG_TODO doesn't work yet
Erik's avatar
Erik committed
511
    public void filterBroadcasts(Object sender, long eventTypes) {
Michael Chan's avatar
Michael Chan committed
512 513 514
        filters.put(sender, eventTypes);
    }

515 516 517 518 519 520 521
    /**
     * @return the time that this controller is currently pointed at
     */
    public long getTime() {
        return mTime.toMillis(false);
    }

Erik's avatar
Erik committed
522 523 524 525 526 527 528 529 530
    /**
     * Set the time this controller is currently pointed at
     *
     * @param millisTime Time since epoch in millis
     */
    public void setTime(long millisTime) {
        mTime.set(millisTime);
    }

531 532 533 534 535 536 537
    /**
     * @return the last event ID the edit view was launched with
     */
    public long getEventId() {
        return mEventId;
    }

538 539 540 541 542 543 544
    public int getViewType() {
        return mViewType;
    }

    public int getPreviousViewType() {
        return mPreviousViewType;
    }
545

546 547 548 549 550 551 552
    private void launchSelectVisibleCalendars() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setClassName(mContext, SelectVisibleCalendarsActivity.class.getName());
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        mContext.startActivity(intent);
    }

553 554
    private void launchSettings() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
555
        intent.setClassName(mContext, CalendarSettingsActivity.class.getName());
556
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
557
        mContext.startActivity(intent);
558 559 560 561
    }

    private void launchCreateEvent(long startMillis, long endMillis) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
562
        intent.setClassName(mContext, EditEventActivity.class.getName());
RoboErik's avatar
RoboErik committed
563 564
        intent.putExtra(EXTRA_EVENT_BEGIN_TIME, startMillis);
        intent.putExtra(EXTRA_EVENT_END_TIME, endMillis);
565
        mEventId = -1;
566
        mContext.startActivity(intent);
567 568 569 570 571 572
    }

    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);
573
//        intent.setClassName(mContext, EventInfoActivity.class.getName());
RoboErik's avatar
RoboErik committed
574 575
        intent.putExtra(EXTRA_EVENT_BEGIN_TIME, startMillis);
        intent.putExtra(EXTRA_EVENT_END_TIME, endMillis);
576
        mContext.startActivity(intent);
577 578
    }

Erik's avatar
Erik committed
579
    private void launchEditEvent(long eventId, long startMillis, long endMillis, boolean edit) {
580 581
        Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, eventId);
        Intent intent = new Intent(Intent.ACTION_EDIT, uri);
RoboErik's avatar
RoboErik committed
582 583
        intent.putExtra(EXTRA_EVENT_BEGIN_TIME, startMillis);
        intent.putExtra(EXTRA_EVENT_END_TIME, endMillis);
584
        intent.setClass(mContext, EditEventActivity.class);
Erik's avatar
Erik committed
585
        intent.putExtra(EVENT_EDIT_ON_LAUNCH, edit);
586
        mEventId = eventId;
587
        mContext.startActivity(intent);
588 589
    }

590 591 592 593 594 595 596
//    private void launchAlerts() {
//        Intent intent = new Intent();
//        intent.setClass(mContext, AlertActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        mContext.startActivity(intent);
//    }

597 598 599 600 601 602
    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) {
603
        DeleteEventHelper deleteEventHelper = new DeleteEventHelper(mContext, parentActivity,
604 605 606
                parentActivity != null /* exit when done */);
        deleteEventHelper.delete(startMillis, endMillis, eventId, deleteWhich);
    }
607

608 609 610 611 612 613 614 615 616 617
    private void launchSearch(long eventId, String query, ComponentName componentName) {
        final SearchManager searchManager =
                (SearchManager)mContext.getSystemService(Context.SEARCH_SERVICE);
        final SearchableInfo searchableInfo = searchManager.getSearchableInfo(componentName);
        final Intent intent = new Intent(Intent.ACTION_SEARCH);
        intent.putExtra(SearchManager.QUERY, query);
        intent.setComponent(searchableInfo.getSearchActivity());
        mContext.startActivity(intent);
    }

Erik's avatar
Erik committed
618 619 620 621 622
    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
RoboErik's avatar
RoboErik committed
623 624
                        Calendars.ACCOUNT_NAME, // 1
                        Calendars.ACCOUNT_TYPE, // 2
Erik's avatar
Erik committed
625 626 627 628
                        },
                REFRESH_SELECTION, REFRESH_ARGS, REFRESH_ORDER);
    }

629 630 631 632 633
    // Forces the viewType. Should only be used for initialization.
    public void setViewType(int viewType) {
        mViewType = viewType;
    }

634 635 636 637 638
    // Sets the eventId. Should only be used for initialization.
    public void setEventId(long eventId) {
        mEventId = eventId;
    }

Erik's avatar
Erik committed
639 640 641 642 643 644 645 646 647 648 649 650 651
    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
652

Erik's avatar
Erik committed
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
            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
671
                }
Erik's avatar
Erik committed
672 673
            } finally {
                cursor.close();
Erik's avatar
Erik committed
674
            }
Erik's avatar
Erik committed
675
            return null;
Erik's avatar
Erik committed
676 677
        }

Erik's avatar
Erik committed
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
        /**
         * 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
697 698 699
        }
    }

700 701 702 703
    private String eventInfoToString(EventInfo eventInfo) {
        String tmp = "Unknown";

        StringBuilder builder = new StringBuilder();
704
        if ((eventInfo.eventType & EventType.GO_TO) != 0) {
705 706 707 708 709
            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";
710 711
        } else if ((eventInfo.eventType & EventType.VIEW_EVENT_DETAILS) != 0) {
            tmp = "View details";
712 713 714 715
        } else if ((eventInfo.eventType & EventType.EDIT_EVENT) != 0) {
            tmp = "Edit event";
        } else if ((eventInfo.eventType & EventType.DELETE_EVENT) != 0) {
            tmp = "Delete event";
716 717
        } else if ((eventInfo.eventType & EventType.LAUNCH_SELECT_VISIBLE_CALENDARS) != 0) {
            tmp = "Launch select visible calendars";
718 719
        } else if ((eventInfo.eventType & EventType.LAUNCH_SETTINGS) != 0) {
            tmp = "Launch settings";
720 721
        } else if ((eventInfo.eventType & EventType.EVENTS_CHANGED) != 0) {
            tmp = "Refresh events";
722 723
        } else if ((eventInfo.eventType & EventType.SEARCH) != 0) {
            tmp = "Search";
724 725 726 727
        } else if ((eventInfo.eventType & EventType.USER_HOME) != 0) {
            tmp = "Gone home";
        } else if ((eventInfo.eventType & EventType.UPDATE_TITLE) != 0) {
            tmp = "Update title";
728 729 730 731
        }
        builder.append(tmp);
        builder.append(": id=");
        builder.append(eventInfo.id);
732 733 734
        builder.append(", selected=");
        builder.append(eventInfo.selectedTime);
        builder.append(", start=");
735
        builder.append(eventInfo.startTime);
736
        builder.append(", end=");
737 738 739 740 741 742 743 744 745
        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();
    }
746
}