Permalink
Browse files

auto import from //depot/cupcake/@135843

  • Loading branch information...
1 parent 11d37e0 commit cf013ece751816a07396845858f1c7037ead464f The Android Open Source Project committed Mar 4, 2009
Showing with 14,555 additions and 0 deletions.
  1. +32 −0 Android.mk
  2. +68 −0 AndroidManifest.xml
  3. 0 MODULE_LICENSE_APACHE2
  4. +190 −0 NOTICE
  5. +127 −0 maketests.py
  6. BIN res/drawable/app_icon.png
  7. BIN res/drawable/app_icon_blank.png
  8. BIN res/drawable/bg_calendar.9.png
  9. BIN res/drawable/bg_calendar_primary.9.png
  10. BIN res/drawable/gadget_date_bg.9.png
  11. BIN res/drawable/strip_cal.9.png
  12. BIN res/drawable/strip_cal_secondary.9.png
  13. BIN res/drawable/white_list_rule_cal.9.png
  14. +182 −0 res/layout-land/gadget_item.xml
  15. +216 −0 res/layout/gadget_item.xml
  16. +26 −0 res/values/colors.xml
  17. +36 −0 res/values/strings.xml
  18. +23 −0 res/xml/gadget_info.xml
  19. +645 −0 src/com/android/providers/calendar/CalendarGadgetProvider.java
  20. +4,024 −0 src/com/android/providers/calendar/CalendarProvider.java
  21. +52 −0 src/com/android/providers/calendar/CalendarReceiver.java
  22. +1,255 −0 src/com/android/providers/calendar/CalendarSyncAdapter.java
  23. +149 −0 src/com/android/providers/calendar/Duration.java
  24. +282 −0 src/com/android/providers/calendar/MetaData.java
  25. +1,160 −0 src/com/android/providers/calendar/RecurrenceProcessor.java
  26. +36 −0 src/com/android/providers/calendar/TimeChangeReceiver.java
  27. +275 −0 src/com/android/providers/calendar/VCal.java
  28. +16 −0 tests/Android.mk
  29. +39 −0 tests/AndroidManifest.xml
  30. +1,410 −0 tests/src/com/android/providers/calendar/CalendarProviderTest.java
  31. +76 −0 tests/src/com/android/providers/calendar/DurationTest.java
  32. +507 −0 tests/src/com/android/providers/calendar/EventRecurrenceTest.java
  33. +272 −0 tests/src/com/android/providers/calendar/ICalendarTest.java
  34. +740 −0 tests/src/com/android/providers/calendar/RRuleTest.java
  35. +2,494 −0 tests/src/com/android/providers/calendar/RecurrenceProcessorTest.java
  36. +169 −0 tests/src/com/android/providers/calendar/TestCalendarSyncAdapter.java
  37. +54 −0 tests/src/com/android/providers/calendar/VCalTest.java
View
32 Android.mk
@@ -0,0 +1,32 @@
+#
+# Copyright (C) 2008 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.
+#
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := user
+
+LOCAL_SRC_FILES := $(call all-java-files-under,src)
+
+# We depend on googlelogin-client also, but that is already
+# being included by google-framework
+LOCAL_STATIC_JAVA_LIBRARIES := google-framework
+
+LOCAL_PACKAGE_NAME := CalendarProvider
+
+include $(BUILD_PACKAGE)
+
+# Use the following include to make our test apk.
+include $(call all-makefiles-under,$(LOCAL_PATH))
View
68 AndroidManifest.xml
@@ -0,0 +1,68 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2008 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.android.providers.calendar"
+ android:sharedUserId="android.uid.calendar">
+
+ <uses-permission android:name="android.permission.READ_CALENDAR" />
+ <uses-permission android:name="android.permission.WRITE_CALENDAR" />
+ <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
+ <uses-permission android:name="com.google.android.googleapps.permission.GOOGLE_AUTH" />
+ <uses-permission android:name="com.google.android.googleapps.permission.GOOGLE_AUTH.cl" />
+ <uses-permission android:name="android.permission.GET_ACCOUNTS" />
+ <uses-permission android:name="android.permission.READ_SYNC_STATS" />
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.SUBSCRIBED_FEEDS_READ" />
+ <uses-permission android:name="android.permission.SUBSCRIBED_FEEDS_WRITE" />
+
+ <application android:process="com.android.calendar"
+ android:label="Calendar Storage"
+ android:icon="@drawable/app_icon">
+ <!-- TODO: Remove dependency of application on the test runner
+ (android.test) library. -->
+ <uses-library android:name="android.test.runner" />
+ <provider android:name="CalendarProvider" android:authorities="calendar"
+ android:syncable="true" android:multiprocess="false"
+ android:readPermission="android.permission.READ_CALENDAR"
+ android:writePermission="android.permission.WRITE_CALENDAR" />
+ <activity android:name="CalendarContentProviderTests" android:label="Calendar Content Provider">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.UNIT_TEST" />
+ </intent-filter>
+ </activity>
+ <receiver android:name="CalendarReceiver">
+ <intent-filter>
+ <action android:name="android.intent.action.BOOT_COMPLETED" />
+ </intent-filter>
+ </receiver>
+ <receiver android:name=".CalendarGadgetProvider" android:label="@string/gadget_title">
+ <intent-filter>
+ <action android:name="android.gadget.action.GADGET_UPDATE" />
+ <action android:name="com.android.calendar.GADGET_UPDATE" />
+ </intent-filter>
+ <meta-data android:name="android.gadget.provider" android:resource="@xml/gadget_info" />
+ </receiver>
+ <receiver android:name=".TimeChangeReceiver" android:enabled="false">
+ <intent-filter>
+ <action android:name="android.intent.action.TIMEZONE_CHANGED" />
+ <action android:name="android.intent.action.TIME_SET" />
+ <action android:name="android.intent.action.DATE_CHANGED" />
+ </intent-filter>
+ </receiver>
+ </application>
+</manifest>
View
0 MODULE_LICENSE_APACHE2
No changes.
View
190 NOTICE
@@ -0,0 +1,190 @@
+
+ Copyright (c) 2005-2008, 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.
+
+ 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.
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
View
127 maketests.py
@@ -0,0 +1,127 @@
+#
+# Usage: Fill in the configuration variables. It will download the feed
+# for it, parse it, and print out test cases to add to the unit test.
+#
+
+EMAIL = "onoratoj@gmail.com"
+PRIVATE_COOKIE = "432802670aefa458daf036597ec8136b"
+START_DATE = ("2006","01","01")
+END_DATE = ("2009","01","01")
+
+
+
+import sys, urllib, re
+from xml.dom import minidom
+
+def fmt(n):
+ if n < 10:
+ return "0" + str(n)
+ else:
+ return str(n)
+
+def makeDate(d):
+ return d[0] + "-" + d[1] + "-" + d[2]
+
+def makeZDate(d):
+ return d[0] + d[1] + d[2] + "T000000Z"
+
+url = "http://www.google.com/calendar/feeds/onoratoj@gmail.com/private-" \
+ + PRIVATE_COOKIE + "/composite?start-min=" + makeDate(START_DATE) \
+ + "&start-max=" + makeDate(END_DATE)
+
+#data = open("out.xml")
+data = urllib.urlopen(url)
+
+DTSTART_TZID = re.compile("DTSTART;TZID=(.*):(.*)")
+DTSTART = re.compile("DTSTART:(.*)")
+DURATION = re.compile("DURATION:(.*)")
+RRULE = re.compile("RRULE:(.*)")
+TIME = re.compile("(....)-(..)-(..)T(..):(..):(..)....([+-])(..):(..)")
+TIMEZ = re.compile("(....)-(..)-(..)T(..):(..):(..)....Z")
+
+def stripTimezone(str):
+ lines = str.split("\n")
+ drop = False
+ result = []
+ for line in lines:
+ if line == "BEGIN:VTIMEZONE":
+ drop = True
+ if not drop:
+ result.append(line)
+ if line == "END:VTIMEZONE":
+ drop = False
+ return result
+
+def fixInstance(s):
+ m = TIME.match(s[0])
+ if m:
+ if m.group(7) == "+":
+ sign = -1
+ else:
+ sign = 1
+ hour = int(m.group(4)) + (sign * int(m.group(8)))
+ return m.group(1) + m.group(2) + m.group(3) + "T" + fmt(hour) \
+ + m.group(5) + m.group(6) + "Z"
+ m = TIMEZ.match(s[0])
+ if m:
+ return m.group(1) + m.group(2) + m.group(3) + "T" + m.group(4) \
+ + m.group(5) + m.group(6) + "Z"
+ return s[0]
+
+dom = minidom.parse(data)
+root = dom.documentElement
+
+entries = root.getElementsByTagName("entry")
+
+for entry in entries:
+ recurrences = entry.getElementsByTagName("gd:recurrence")
+ dtstart = ""
+ tzid = ""
+ duration = ""
+ rrule = ""
+ if len(recurrences) > 0:
+ recurrence = recurrences[0]
+ s = ""
+ for c in recurrence.childNodes:
+ s = s + c.nodeValue
+ lines = stripTimezone(s)
+ for s in lines:
+ re_dtstart = DTSTART_TZID.match(s)
+ if re_dtstart:
+ dtstart = re_dtstart.group(2)
+ tzid = re_dtstart.group(1)
+ re_dtstart = DTSTART.match(s)
+ if re_dtstart:
+ dtstart = re_dtstart.group(1)
+ re_duration = DURATION.match(s)
+ if re_duration:
+ duration = re_duration.group(1)
+ re_rrule = RRULE.match(s)
+ if re_rrule:
+ rrule = re_rrule.group(1)
+ whens = entry.getElementsByTagName("gd:when")
+ instances = []
+ for w in whens:
+ startTime = w.getAttribute("startTime")
+ endTime = w.getAttribute("endTime")
+ instances.append((startTime,endTime))
+
+ instances = map(fixInstance, instances)
+ instances.sort()
+ if dtstart != "":
+ title = ""
+ for c in entry.getElementsByTagName('title')[0].childNodes:
+ title = title + c.nodeValue
+
+ print " // " + title
+ print " test(\"" + dtstart + "\","
+ print " \"" + rrule + "\","
+ print " \"" + makeZDate(START_DATE) \
+ + "\", \"" + makeZDate(END_DATE) + "\","
+ print " new String[] {"
+ for i in instances:
+ print " \"" + i + "\","
+ print " });"
+ print
+
+
View
BIN res/drawable/app_icon.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN res/drawable/app_icon_blank.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN res/drawable/bg_calendar.9.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN res/drawable/bg_calendar_primary.9.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN res/drawable/gadget_date_bg.9.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN res/drawable/strip_cal.9.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN res/drawable/strip_cal_secondary.9.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN res/drawable/white_list_rule_cal.9.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
182 res/layout-land/gadget_item.xml
@@ -0,0 +1,182 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2009 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.
+-->
+
+
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/gadget"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:paddingBottom="6dip"
+ android:background="@drawable/bg_calendar"
+ >
+
+ <TextView
+ android:id="@+id/no_events"
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent"
+ android:paddingTop="6dip"
+ android:gravity="center"
+ android:textStyle="bold"
+ android:textSize="16sp"
+ android:text="@string/gadget_no_events"
+ android:textColor="@color/gadget_no_events"
+ />
+
+ <FrameLayout
+ android:id="@+id/landscape_hidden"
+ android:layout_width="0dip"
+ android:layout_height="0dip"
+ android:visibility="gone"
+ >
+
+ <TextView
+ android:id="@+id/secondary_card"
+ android:layout_width="0dip"
+ android:layout_height="0dip"
+ />
+
+ <TextView
+ android:id="@+id/stub_when"
+ android:layout_width="0dip"
+ android:layout_height="0dip"
+ />
+
+ <TextView
+ android:id="@+id/stub_title"
+ android:layout_width="0dip"
+ android:layout_height="0dip"
+ />
+
+ <TextView
+ android:id="@+id/stub_where"
+ android:layout_width="0dip"
+ android:layout_height="0dip"
+ />
+
+ <TextView
+ android:id="@+id/secondary_when"
+ android:layout_width="0dip"
+ android:layout_height="0dip"
+ android:background="@drawable/strip_cal_secondary"
+ />
+
+ <TextView
+ android:id="@+id/secondary_title"
+ android:layout_width="0dip"
+ android:layout_height="0dip"
+ />
+
+ <ImageView
+ android:id="@+id/divider"
+ android:layout_width="0dip"
+ android:layout_height="0dip"
+ android:background="@drawable/white_list_rule_cal"
+ />
+
+ <TextView
+ android:id="@+id/title2"
+ android:layout_width="0dip"
+ android:layout_height="0dip"
+ />
+
+ </FrameLayout>
+
+ <RelativeLayout
+ android:id="@+id/primary_card"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:layout_alignParentTop="true"
+ android:paddingLeft="3dip"
+ android:paddingRight="3dip"
+ android:paddingTop="3dip"
+ android:paddingBottom="8dip"
+ android:background="@drawable/bg_calendar_primary"
+ android:orientation="vertical"
+ android:visibility="gone"
+ >
+
+ <TextView
+ android:id="@+id/when"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:paddingRight="8dip"
+ android:paddingLeft="8dip"
+ android:paddingTop="1dip"
+ android:paddingBottom="1dip"
+ android:gravity="center_vertical"
+ android:background="@drawable/strip_cal"
+ android:textStyle="bold"
+ android:textSize="11sp"
+ android:textColor="@color/gadget_when"
+ android:singleLine="true"
+ />
+
+ <TextView
+ android:id="@+id/icon"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_below="@id/when"
+ android:layout_alignParentRight="true"
+ android:background="@drawable/gadget_date_bg"
+ android:textStyle="bold"
+ android:textSize="18sp"
+ android:gravity="center"
+ android:paddingLeft="8dip"
+ android:paddingRight="7dip"
+ android:paddingTop="3dip"
+ android:paddingBottom="3dip"
+ android:layout_marginRight="5dip"
+ android:layout_marginTop="4dip"
+ android:layout_marginBottom="4dip"
+ android:textColor="#59b4f4"
+ android:shadowColor="#ffff"
+ android:shadowRadius="2.75"
+ android:minWidth="32dip"
+ />
+
+ <TextView
+ android:id="@+id/title"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:layout_alignParentLeft="true"
+ android:layout_below="@id/when"
+ android:layout_toLeftOf="@id/icon"
+ android:paddingRight="8dip"
+ android:paddingLeft="8dip"
+ android:textStyle="bold"
+ android:textSize="16sp"
+ android:textColor="@color/gadget_title"
+ android:singleLine="true"
+ />
+
+ <TextView
+ android:id="@+id/where"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:layout_below="@id/title"
+ android:layout_toLeftOf="@id/icon"
+ android:layout_alignParentLeft="true"
+ android:paddingRight="8dip"
+ android:paddingLeft="8dip"
+ android:textSize="11sp"
+ android:textColor="@color/gadget_where"
+ android:singleLine="true"
+ />
+
+ </RelativeLayout>
+
+</RelativeLayout>
+
View
216 res/layout/gadget_item.xml
@@ -0,0 +1,216 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2009 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.
+-->
+
+
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/gadget"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:paddingBottom="6dip"
+ android:background="@drawable/bg_calendar"
+ >
+
+ <TextView
+ android:id="@+id/no_events"
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent"
+ android:paddingTop="6dip"
+ android:gravity="center"
+ android:textStyle="bold"
+ android:textSize="16sp"
+ android:text="@string/gadget_no_events"
+ android:textColor="@color/gadget_no_events"
+ />
+
+ <LinearLayout
+ android:id="@+id/secondary_card"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginLeft="3dip"
+ android:layout_marginRight="3dip"
+ android:orientation="vertical"
+ android:visibility="gone"
+ >
+
+ <TextView
+ android:id="@+id/stub_when"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:textStyle="bold"
+ android:textSize="11sp"
+ android:paddingTop="8dip"
+ android:visibility="invisible"
+ />
+
+ <TextView
+ android:id="@+id/stub_title"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:textStyle="bold"
+ android:textSize="16sp"
+ android:visibility="invisible"
+ />
+
+ <TextView
+ android:id="@+id/stub_where"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:textSize="11sp"
+ android:visibility="invisible"
+ />
+
+ <TextView
+ android:id="@+id/secondary_when"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:paddingLeft="8dip"
+ android:paddingRight="8dip"
+ android:paddingTop="1dip"
+ android:paddingBottom="1dip"
+ android:gravity="center_vertical"
+ android:background="@drawable/strip_cal_secondary"
+ android:textStyle="bold"
+ android:textSize="11sp"
+ android:textColor="@color/gadget_when"
+ android:singleLine="true"
+ />
+
+ <TextView
+ android:id="@+id/secondary_title"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:paddingLeft="8dip"
+ android:paddingRight="8dip"
+ android:textSize="11sp"
+ android:textColor="@color/gadget_title"
+ android:singleLine="true"
+ />
+
+ </LinearLayout>
+
+ <RelativeLayout
+ android:id="@+id/primary_card"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:layout_alignParentTop="true"
+ android:paddingLeft="3dip"
+ android:paddingRight="3dip"
+ android:paddingTop="3dip"
+ android:paddingBottom="8dip"
+ android:background="@drawable/bg_calendar_primary"
+ android:orientation="vertical"
+ android:visibility="gone"
+ >
+
+ <TextView
+ android:id="@+id/when"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:paddingRight="8dip"
+ android:paddingLeft="8dip"
+ android:paddingTop="1dip"
+ android:paddingBottom="1dip"
+ android:gravity="center_vertical"
+ android:background="@drawable/strip_cal"
+ android:textStyle="bold"
+ android:textSize="11sp"
+ android:textColor="@color/gadget_when"
+ android:singleLine="true"
+ />
+
+ <TextView
+ android:id="@+id/icon"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_below="@id/when"
+ android:layout_alignParentRight="true"
+ android:background="@drawable/gadget_date_bg"
+ android:textStyle="bold"
+ android:textSize="18sp"
+ android:gravity="center"
+ android:paddingLeft="8dip"
+ android:paddingRight="7dip"
+ android:paddingTop="3dip"
+ android:paddingBottom="3dip"
+ android:layout_marginRight="5dip"
+ android:layout_marginTop="4dip"
+ android:layout_marginBottom="4dip"
+ android:textColor="#59b4f4"
+ android:shadowColor="#ffff"
+ android:shadowRadius="2.75"
+ android:minWidth="32dip"
+ />
+
+ <TextView
+ android:id="@+id/title"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:layout_alignParentLeft="true"
+ android:layout_below="@id/when"
+ android:layout_toLeftOf="@id/icon"
+ android:paddingRight="8dip"
+ android:paddingLeft="8dip"
+ android:textStyle="bold"
+ android:textSize="16sp"
+ android:textColor="@color/gadget_title"
+ android:singleLine="true"
+ />
+
+ <TextView
+ android:id="@+id/where"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:layout_below="@id/title"
+ android:layout_toLeftOf="@id/icon"
+ android:layout_alignParentLeft="true"
+ android:paddingRight="8dip"
+ android:paddingLeft="8dip"
+ android:textSize="11sp"
+ android:textColor="@color/gadget_where"
+ android:singleLine="true"
+ />
+
+ <ImageView
+ android:id="@+id/divider"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:layout_below="@id/icon"
+ android:layout_alignParentLeft="true"
+ android:layout_marginTop="4dip"
+ android:layout_marginBottom="2dip"
+ android:layout_marginLeft="16dip"
+ android:layout_marginRight="16dip"
+ android:background="@drawable/white_list_rule_cal"
+ />
+
+ <TextView
+ android:id="@+id/title2"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:layout_below="@id/divider"
+ android:layout_alignParentLeft="true"
+ android:paddingRight="8dip"
+ android:paddingLeft="8dip"
+ android:textStyle="bold"
+ android:textSize="11sp"
+ android:textColor="@color/gadget_title"
+ android:singleLine="true"
+ />
+
+ </RelativeLayout>
+
+</RelativeLayout>
+
View
26 res/values/colors.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2009 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.
+-->
+
+<resources>
+ <color name="gadget_when">#ffffffff</color>
+ <color name="gadget_reminder">#ffffffff</color>
+ <color name="gadget_title">#ff000000</color>
+ <color name="gadget_where">#ff000000</color>
+ <color name="gadget_calendar">#ff000000</color>
+
+ <color name="gadget_no_events">#bb000000</color>
+</resources>
+
View
36 res/values/strings.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2009 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.
+-->
+
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+
+ <!-- Title for calendar gadget when displayed in list of all other gadgets -->
+ <string name="gadget_title">Calendar</string>
+
+ <!-- Title of event when no explicit title is specified by the user -->
+ <string name="no_title_label">(No subject)</string>
+
+ <!-- Shown in gadget when additional events are available for display, but no room remaining -->
+ <plurals name="gadget_more_events">
+ <!-- additional events message for 1 event -->
+ <item quantity="one">1 more event</item>
+ <!-- additional events message for multiple events -->
+ <item quantity="other"><xliff:g id="number">%d</xliff:g> more events</item>
+ </plurals>
+
+ <!-- Caption to show on gadget when there are no upcoming calendar events -->
+ <string name="gadget_no_events">No upcoming calendar events</string>
+
+</resources>
View
23 res/xml/gadget_info.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2009 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.
+-->
+
+<gadget-provider xmlns:android="http://schemas.android.com/apk/res/android"
+ android:minWidth="294dip"
+ android:minHeight="72dip"
+ android:updatePeriodMillis="0"
+ android:initialLayout="@layout/gadget_item"
+ >
+</gadget-provider>
View
645 src/com/android/providers/calendar/CalendarGadgetProvider.java
@@ -0,0 +1,645 @@
+/*
+ * Copyright (C) 2009 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.providers.calendar;
+
+import android.app.AlarmManager;
+import android.app.PendingIntent;
+import android.content.ComponentName;
+import android.content.ContentResolver;
+import android.content.ContentUris;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.res.Resources;
+import android.database.Cursor;
+import android.gadget.GadgetManager;
+import android.gadget.GadgetProvider;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.Canvas;
+import android.graphics.Paint;
+import android.graphics.PorterDuff;
+import android.net.Uri;
+import android.provider.Calendar.Attendees;
+import android.provider.Calendar.Calendars;
+import android.provider.Calendar.Instances;
+import android.text.format.DateFormat;
+import android.text.format.DateUtils;
+import android.text.format.Time;
+import android.util.Log;
+import android.view.View;
+import android.widget.RemoteViews;
+
+import java.util.TimeZone;
+
+/**
+ * Simple gadget to show next upcoming calendar event.
+ */
+public class CalendarGadgetProvider extends GadgetProvider {
+ static final String TAG = "CalendarGadgetProvider";
+ static final boolean LOGD = true;
+
+ static final String EVENT_SORT_ORDER = "startDay ASC, allDay DESC, begin ASC";
+
+ static final String[] EVENT_PROJECTION = new String[] {
+ Instances.ALL_DAY,
+ Instances.BEGIN,
+ Instances.END,
+ Instances.COLOR,
+ Instances.TITLE,
+ Instances.RRULE,
+ Instances.HAS_ALARM,
+ Instances.EVENT_LOCATION,
+ Instances.CALENDAR_ID,
+ Instances.EVENT_ID,
+ };
+
+ static final int INDEX_ALL_DAY = 0;
+ static final int INDEX_BEGIN = 1;
+ static final int INDEX_END = 2;
+ static final int INDEX_COLOR = 3;
+ static final int INDEX_TITLE = 4;
+ static final int INDEX_RRULE = 5;
+ static final int INDEX_HAS_ALARM = 6;
+ static final int INDEX_EVENT_LOCATION = 7;
+ static final int INDEX_CALENDAR_ID = 8;
+ static final int INDEX_EVENT_ID = 9;
+
+ static final long SEARCH_DURATION = DateUtils.WEEK_IN_MILLIS;
+
+ static final long UPDATE_NO_EVENTS = DateUtils.HOUR_IN_MILLIS * 6;
+
+ static final String ACTION_CALENDAR_GADGET_UPDATE = "com.android.calendar.GADGET_UPDATE";
+
+ static final String PACKAGE_DETAIL = "com.android.calendar";
+ static final String CLASS_DETAIL = "com.android.calendar.AgendaActivity";
+
+ static final ComponentName THIS_GADGET =
+ new ComponentName("com.android.providers.calendar",
+ "com.android.providers.calendar.CalendarGadgetProvider");
+
+ private static CalendarGadgetProvider sInstance;
+
+ static synchronized CalendarGadgetProvider getInstance() {
+ if (sInstance == null) {
+ sInstance = new CalendarGadgetProvider();
+ }
+ return sInstance;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ // Handle calendar-specific updates ourselves because they might be
+ // coming in without extras, which GadgetProvider then blocks.
+ final String action = intent.getAction();
+ if (ACTION_CALENDAR_GADGET_UPDATE.equals(action)) {
+ performUpdate(context, null, -1);
+ } else {
+ super.onReceive(context, intent);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void onEnabled(Context context) {
+ // Enable updates for timezone and date changes
+ PackageManager pm = context.getPackageManager();
+ pm.setComponentEnabledSetting(
+ new ComponentName(context, TimeChangeReceiver.class),
+ PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
+ PackageManager.DONT_KILL_APP);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void onDisabled(Context context) {
+ // Unsubscribe from all AlarmManager updates
+ AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
+ PendingIntent pendingUpdate = getUpdateIntent(context);
+ am.cancel(pendingUpdate);
+
+ // Disable updates for timezone and date changes
+ PackageManager pm = context.getPackageManager();
+ pm.setComponentEnabledSetting(
+ new ComponentName(context, TimeChangeReceiver.class),
+ PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
+ PackageManager.DONT_KILL_APP);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void onUpdate(Context context, GadgetManager gadgetManager, int[] gadgetIds) {
+ performUpdate(context, gadgetIds, -1);
+ }
+
+ /**
+ * Check against {@link GadgetManager} if there are any instances of this gadget.
+ */
+ private boolean hasInstances(Context context) {
+ GadgetManager gadgetManager = GadgetManager.getInstance(context);
+ int[] gadgetIds = gadgetManager.getGadgetIds(THIS_GADGET);
+ return (gadgetIds.length > 0);
+ }
+
+ /**
+ * The {@link CalendarProvider} has been updated, which means we should push
+ * updates to any gadgets, if they exist.
+ *
+ * @param changedEventId Specific event known to be changed, otherwise -1.
+ * If present, we use it to decide if an update is necessary.
+ */
+ void providerUpdated(Context context, long changedEventId) {
+ if (hasInstances(context)) {
+ performUpdate(context, null, changedEventId);
+ }
+ }
+
+ /**
+ * {@link TimeChangeReceiver} has triggered that the time changed.
+ */
+ void timeUpdated(Context context) {
+ if (hasInstances(context)) {
+ performUpdate(context, null, -1);
+ }
+ }
+
+ /**
+ * Process and push out an update for the given gadgetIds.
+ *
+ * @param context Context to use when creating gadget.
+ * @param gadgetIds List of specific gadgetIds to update, or null for all.
+ * @param changedEventId Specific event known to be changed, otherwise -1.
+ * If present, we use it to decide if an update is necessary.
+ */
+ private void performUpdate(Context context, int[] gadgetIds, long changedEventId) {
+ ContentResolver resolver = context.getContentResolver();
+
+ Cursor cursor = null;
+ RemoteViews views = null;
+ long triggerTime = -1;
+
+ try {
+ cursor = getUpcomingInstancesCursor(resolver, SEARCH_DURATION);
+ if (cursor != null) {
+ MarkedEvents events = buildMarkedEvents(cursor, changedEventId);
+
+ boolean shouldUpdate = true;
+ if (changedEventId != -1) {
+ shouldUpdate = events.watchFound;
+ }
+
+ if (events.primaryCount == 0) {
+ views = getGadgetNoEvents(context);
+ } else if (shouldUpdate) {
+ views = getGadgetUpdate(context, cursor, events);
+ triggerTime = calculateUpdateTime(context, cursor, events);
+ }
+ } else {
+ views = getGadgetNoEvents(context);
+ }
+ } finally {
+ if (cursor != null) {
+ cursor.close();
+ }
+ }
+
+ // Bail out early if no update built
+ if (views == null) {
+ if (LOGD) Log.d(TAG, "Didn't build update, possibly because changedEventId=" + changedEventId);
+ return;
+ }
+
+ GadgetManager gm = GadgetManager.getInstance(context);
+ if (gadgetIds != null) {
+ gm.updateGadget(gadgetIds, views);
+ } else {
+ ComponentName thisGadget = new ComponentName(context, CalendarGadgetProvider.class);
+ gm.updateGadget(thisGadget, views);
+ }
+
+ // Schedule an alarm to wake ourselves up for the next update. We also cancel
+ // all existing wake-ups because PendingIntents don't match against extras.
+
+ // If no next-update calculated, or bad trigger time in past, schedule
+ // update about six hours from now.
+ long now = System.currentTimeMillis();
+ if (triggerTime == -1 || triggerTime < now) {
+ if (LOGD) Log.w(TAG, "Encountered bad trigger time " + formatDebugTime(triggerTime));
+ triggerTime = now + UPDATE_NO_EVENTS;
+ }
+
+ AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
+ PendingIntent pendingUpdate = getUpdateIntent(context);
+
+ am.cancel(pendingUpdate);
+ am.set(AlarmManager.RTC, triggerTime, pendingUpdate);
+
+ if (LOGD) Log.d(TAG, "Scheduled next update at " + formatDebugTime(triggerTime));
+ }
+
+ /**
+ * Build the {@link PendingIntent} used to trigger an update of all calendar
+ * gadgets. Uses {@link ACTION_CALENDAR_GADGET_UPDATE} to directly target
+ * all gadgets instead of using {@link GadgetManager#EXTRA_GADGET_IDS}.
+ */
+ private PendingIntent getUpdateIntent(Context context) {
+ Intent updateIntent = new Intent(ACTION_CALENDAR_GADGET_UPDATE);
+ updateIntent.setComponent(new ComponentName(context, CalendarGadgetProvider.class));
+ return PendingIntent.getBroadcast(context, 0 /* no requestCode */,
+ updateIntent, 0 /* no flags */);
+ }
+
+ /**
+ * Format given time for debugging output.
+ */
+ private String formatDebugTime(long unixTime) {
+ Time time = new Time();
+ time.set(unixTime);
+
+ long delta = unixTime - System.currentTimeMillis();
+ if (delta > DateUtils.MINUTE_IN_MILLIS) {
+ delta /= DateUtils.MINUTE_IN_MILLIS;
+ return String.format("[%d] %s (%+d mins)", unixTime, time.format("%H:%M:%S"), delta);
+ } else {
+ delta /= DateUtils.SECOND_IN_MILLIS;
+ return String.format("[%d] %s (%+d secs)", unixTime, time.format("%H:%M:%S"), delta);
+ }
+ }
+
+ /**
+ * Convert given UTC time into current local time.
+ *
+ * @param recycle Time object to recycle, otherwise null.
+ * @param utcTime Time to convert, in UTC.
+ */
+ private long convertUtcToLocal(Time recycle, long utcTime) {
+ if (recycle == null) {
+ recycle = new Time();
+ }
+ recycle.timezone = Time.TIMEZONE_UTC;
+ recycle.set(utcTime);
+ recycle.timezone = TimeZone.getDefault().getID();
+ return recycle.normalize(true);
+ }
+
+ /**
+ * Figure out the next time we should push gadget updates. This is based on
+ * the time calculated by {@link #getEventFlip(Cursor, int)}.
+ */
+ private long calculateUpdateTime(Context context, Cursor cursor, MarkedEvents events) {
+ long result = -1;
+ if (events.primaryRow != -1) {
+ cursor.moveToPosition(events.primaryRow);
+ long start = cursor.getLong(INDEX_BEGIN);
+ long end = cursor.getLong(INDEX_END);
+ boolean allDay = cursor.getInt(INDEX_ALL_DAY) != 0;
+
+ // Adjust all-day times into local timezone
+ if (allDay) {
+ final Time recycle = new Time();
+ start = convertUtcToLocal(recycle, start);
+ end = convertUtcToLocal(recycle, end);
+ }
+
+ result = getEventFlip(cursor, start, end, allDay);
+ }
+ return result;
+ }
+
+ /**
+ * Calculate flipping point for the given event; when we should hide this
+ * event and show the next one. This is usually half-way through the event.
+ *
+ * @param start Event start time in local timezone.
+ * @param end Event end time in local timezone.
+ */
+ private long getEventFlip(Cursor cursor, long start, long end, boolean allDay) {
+ if (allDay) {
+ return start;
+ } else {
+ return (start + end) / 2;
+ }
+ }
+
+ /**
+ * Build a set of {@link RemoteViews} that describes how to update any
+ * gadget for a specific event instance.
+ *
+ * @param cursor Valid cursor on {@link Instances#CONTENT_URI}
+ * @param events {@link MarkedEvents} parsed from the cursor
+ */
+ private RemoteViews getGadgetUpdate(Context context, Cursor cursor, MarkedEvents events) {
+ Resources res = context.getResources();
+ ContentResolver resolver = context.getContentResolver();
+
+ RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.gadget_item);
+
+ // Clicking on gadget launches the agenda view in Calendar
+ Intent agendaIntent = new Intent();
+ agendaIntent.setComponent(new ComponentName(PACKAGE_DETAIL, CLASS_DETAIL));
+ PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 /* no requestCode */,
+ agendaIntent, 0 /* no flags */);
+
+ views.setOnClickPendingIntent(R.id.gadget, pendingIntent);
+
+ Time time = new Time();
+ time.setToNow();
+ int yearDay = time.yearDay;
+ int dateNumber = time.monthDay;
+
+ // Set calendar icon with actual date
+ views.setTextViewText(R.id.icon, Integer.toString(dateNumber));
+ views.setViewVisibility(R.id.icon, View.VISIBLE);
+ views.setViewVisibility(R.id.no_events, View.GONE);
+
+ // Fill primary event details
+ if (events.primaryRow != -1) {
+ views.setViewVisibility(R.id.primary_card, View.VISIBLE);
+ cursor.moveToPosition(events.primaryRow);
+
+ // Color stripe
+ int colorFilter = cursor.getInt(INDEX_COLOR);
+ views.setDrawableParameters(R.id.when, true, -1, colorFilter,
+ PorterDuff.Mode.SRC_IN, -1);
+ views.setTextColor(R.id.title, colorFilter);
+ views.setTextColor(R.id.where, colorFilter);
+ views.setDrawableParameters(R.id.divider, true, -1, colorFilter,
+ PorterDuff.Mode.SRC_IN, -1);
+ views.setTextColor(R.id.title2, colorFilter);
+
+ // When
+ long start = cursor.getLong(INDEX_BEGIN);
+ boolean allDay = cursor.getInt(INDEX_ALL_DAY) != 0;
+
+ int flags;
+ String whenString;
+ if (allDay) {
+ flags = DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_UTC
+ | DateUtils.FORMAT_SHOW_DATE;
+ } else {
+ flags = DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_TIME;
+
+ // Show date if different from today
+ time.set(start);
+ if (yearDay != time.yearDay) {
+ flags = flags | DateUtils.FORMAT_SHOW_DATE;
+ }
+ }
+ if (DateFormat.is24HourFormat(context)) {
+ flags |= DateUtils.FORMAT_24HOUR;
+ }
+ whenString = DateUtils.formatDateRange(context, start, start, flags);
+ views.setTextViewText(R.id.when, whenString);
+
+ // What
+ String titleString = cursor.getString(INDEX_TITLE);
+ if (titleString == null || titleString.length() == 0) {
+ titleString = context.getString(R.string.no_title_label);
+ }
+ views.setTextViewText(R.id.title, titleString);
+
+ // Where
+ String whereString = cursor.getString(INDEX_EVENT_LOCATION);
+ if (whereString != null && whereString.length() > 0) {
+ views.setViewVisibility(R.id.where, View.VISIBLE);
+ views.setViewVisibility(R.id.stub_where, View.INVISIBLE);
+ views.setTextViewText(R.id.where, whereString);
+ } else {
+ views.setViewVisibility(R.id.where, View.GONE);
+ views.setViewVisibility(R.id.stub_where, View.GONE);
+ }
+ }
+
+ // Fill other primary events, if present
+ if (events.primaryConflictRow != -1) {
+ views.setViewVisibility(R.id.divider, View.VISIBLE);
+ views.setViewVisibility(R.id.title2, View.VISIBLE);
+
+ if (events.primaryCount > 2) {
+ // If more than two primary conflicts, format multiple message
+ int count = events.primaryCount - 1;
+ String titleString = String.format(res.getQuantityString(
+ R.plurals.gadget_more_events, count), count);
+ views.setTextViewText(R.id.title2, titleString);
+ } else {
+ cursor.moveToPosition(events.primaryConflictRow);
+
+ // What
+ String titleString = cursor.getString(INDEX_TITLE);
+ if (titleString == null || titleString.length() == 0) {
+ titleString = context.getString(R.string.no_title_label);
+ }
+ views.setTextViewText(R.id.title2, titleString);
+ }
+ } else {
+ views.setViewVisibility(R.id.divider, View.GONE);
+ views.setViewVisibility(R.id.title2, View.GONE);
+ }
+
+ // Fill secondary event
+ if (events.secondaryRow != -1) {
+ views.setViewVisibility(R.id.secondary_card, View.VISIBLE);
+ views.setViewVisibility(R.id.secondary_when, View.VISIBLE);
+ views.setViewVisibility(R.id.secondary_title, View.VISIBLE);
+
+ cursor.moveToPosition(events.secondaryRow);
+
+ // Color stripe
+ int colorFilter = cursor.getInt(INDEX_COLOR);
+ views.setDrawableParameters(R.id.secondary_when, true, -1, colorFilter,
+ PorterDuff.Mode.SRC_IN, -1);
+ views.setTextColor(R.id.secondary_title, colorFilter);
+
+ // When
+ long start = cursor.getLong(INDEX_BEGIN);
+ boolean allDay = cursor.getInt(INDEX_ALL_DAY) != 0;
+
+ int flags;
+ String whenString;
+ if (allDay) {
+ flags = DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_UTC
+ | DateUtils.FORMAT_SHOW_DATE;
+ } else {
+ flags = DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_TIME;
+
+ // Show date if different from today
+ time.set(start);
+ if (yearDay != time.yearDay) {
+ flags = flags | DateUtils.FORMAT_SHOW_DATE;
+ }
+ }
+ if (DateFormat.is24HourFormat(context)) {
+ flags |= DateUtils.FORMAT_24HOUR;
+ }
+ whenString = DateUtils.formatDateRange(context, start, start, flags);
+ views.setTextViewText(R.id.secondary_when, whenString);
+
+ if (events.secondaryCount > 1) {
+ // If more than two secondary conflicts, format multiple message
+ int count = events.secondaryCount;
+ String titleString = String.format(res.getQuantityString(
+ R.plurals.gadget_more_events, count), count);
+ views.setTextViewText(R.id.secondary_title, titleString);
+ } else {
+ // What
+ String titleString = cursor.getString(INDEX_TITLE);
+ if (titleString == null || titleString.length() == 0) {
+ titleString = context.getString(R.string.no_title_label);
+ }
+ views.setTextViewText(R.id.secondary_title, titleString);
+ }
+ } else {
+ views.setViewVisibility(R.id.secondary_when, View.GONE);
+ views.setViewVisibility(R.id.secondary_title, View.GONE);
+ }
+
+ return views;
+ }
+
+ /**
+ * Build a set of {@link RemoteViews} that describes an error state.
+ */
+ private RemoteViews getGadgetNoEvents(Context context) {
+ RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.gadget_item);
+
+ views.setViewVisibility(R.id.no_events, View.VISIBLE);
+
+ views.setViewVisibility(R.id.primary_card, View.GONE);
+ views.setViewVisibility(R.id.secondary_card, View.GONE);
+
+ // Clicking on gadget launches the agenda view in Calendar
+ Intent agendaIntent = new Intent();
+ agendaIntent.setComponent(new ComponentName(PACKAGE_DETAIL, CLASS_DETAIL));
+ PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 /* no requestCode */,
+ agendaIntent, 0 /* no flags */);
+
+ views.setOnClickPendingIntent(R.id.gadget, pendingIntent);
+
+ return views;
+ }
+
+ private static class MarkedEvents {
+ long primaryTime = -1;
+ int primaryRow = -1;
+ int primaryConflictRow = -1;
+ int primaryCount = 0;
+ long secondaryTime = -1;
+ int secondaryRow = -1;
+ int secondaryCount = 0;
+ boolean watchFound = false;
+ }
+
+ /**
+ * Walk the given instances cursor and build a list of marked events to be
+ * used when updating the gadget. This structure is also used to check if
+ * updates are needed.
+ *
+ * @param cursor Valid cursor across {@link Instances#CONTENT_URI}.
+ * @param watchEventId Specific event to watch for, setting
+ * {@link MarkedEvents#watchFound} if found during marking.
+ */
+ private MarkedEvents buildMarkedEvents(Cursor cursor, long watchEventId) {
+ MarkedEvents events = new MarkedEvents();
+ long now = System.currentTimeMillis();
+ final Time recycle = new Time();
+
+ cursor.moveToPosition(-1);
+ while (cursor.moveToNext()) {
+ int row = cursor.getPosition();
+ long eventId = cursor.getLong(INDEX_EVENT_ID);
+ long start = cursor.getLong(INDEX_BEGIN);
+ long end = cursor.getLong(INDEX_END);
+ boolean allDay = cursor.getInt(INDEX_ALL_DAY) != 0;
+
+ // Adjust all-day times into local timezone
+ if (allDay) {
+ start = convertUtcToLocal(recycle, start);
+ end = convertUtcToLocal(recycle, end);
+ }
+
+ // Skip events that have already passed their flip times
+ long eventFlip = getEventFlip(cursor, start, end, allDay);
+ if (LOGD) Log.d(TAG, "Calculated flip time " + formatDebugTime(eventFlip));
+ if (eventFlip < now) {
+ continue;
+ }
+
+ // Mark if we've encountered the watched event
+ if (eventId == watchEventId) {
+ events.watchFound = true;
+ }
+
+ if (events.primaryRow == -1) {
+ // Found first event
+ events.primaryRow = row;
+ events.primaryTime = start;
+ events.primaryCount = 1;
+ } else if (events.primaryTime == start) {
+ // Found conflicting primary event
+ if (events.primaryConflictRow == -1) {
+ events.primaryConflictRow = row;
+ }
+ events.primaryCount += 1;
+ } else if (events.secondaryRow == -1) {
+ // Found second event
+ events.secondaryRow = row;
+ events.secondaryTime = start;
+ events.secondaryCount = 1;
+ } else if (events.secondaryTime == start) {
+ // Found conflicting secondary event
+ events.secondaryCount += 1;
+ } else {
+ // Nothing interesting about this event, so bail out
+ break;
+ }
+ }
+ return events;
+ }
+
+ /**
+ * Query across all calendars for upcoming event instances from now until
+ * some time in the future.
+ *
+ * @param searchDuration Distance into the future to look for event
+ * instances, in milliseconds.
+ */
+ private Cursor getUpcomingInstancesCursor(ContentResolver resolver, long searchDuration) {
+ // Search for events from now until some time in the future
+ long start = System.currentTimeMillis();
+ long end = start + searchDuration;
+
+ Uri uri = Uri.withAppendedPath(Instances.CONTENT_URI,
+ String.format("%d/%d", start, end));
+
+ String selection = String.format("%s=1 AND %s!=%d",
+ Calendars.SELECTED, Instances.SELF_ATTENDEE_STATUS,
+ Attendees.ATTENDEE_STATUS_DECLINED);
+
+ return resolver.query(uri, EVENT_PROJECTION, selection, null,
+ EVENT_SORT_ORDER);
+ }
+
+}
View
4,024 src/com/android/providers/calendar/CalendarProvider.java
4,024 additions, 0 deletions not shown because the diff is too large. Please use a local Git client to view these changes.
View
52 src/com/android/providers/calendar/CalendarReceiver.java
@@ -0,0 +1,52 @@
+/*
+** Copyright 2006, 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,
+** See the License for the specific language governing permissions and
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** limitations under the License.
+*/
+
+package com.android.providers.calendar;
+
+import android.content.BroadcastReceiver;
+import android.content.ContentProvider;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.IContentProvider;
+import android.content.Intent;
+
+/**
+ * This IntentReceiver executes when the boot completes and ensures that
+ * the Calendar provider has started and then initializes the alarm
+ * scheduler for the Calendar provider. This needs to be done after
+ * the boot completes because the alarm manager may not have been started
+ * yet.
+ */
+public class CalendarReceiver extends BroadcastReceiver {
+
+ static final String SCHEDULE = "com.android.providers.calendar.SCHEDULE_ALARM";
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ String action = intent.getAction();
+ ContentResolver cr = context.getContentResolver();
+ CalendarProvider provider;
+ IContentProvider icp = cr.acquireProvider("calendar");
+ provider = (CalendarProvider) ContentProvider.
+ coerceToLocalContentProvider(icp);
+ if (action.equals(SCHEDULE)) {
+ provider.scheduleNextAlarm(false /* do not remove alarms */);
+ } else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
+ provider.bootCompleted();
+ }
+ cr.releaseProvider(icp);
+ }
+}
View
1,255 src/com/android/providers/calendar/CalendarSyncAdapter.java
@@ -0,0 +1,1255 @@
+/*
+**
+** Copyright 2006, 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,
+** See the License for the specific language governing permissions and
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** limitations under the License.
+*/
+
+package com.android.providers.calendar;
+
+import com.google.android.gdata.client.AndroidGDataClient;
+import com.google.android.gdata.client.AndroidXmlParserFactory;
+import com.google.android.providers.AbstractGDataSyncAdapter;
+import com.google.wireless.gdata.calendar.client.CalendarClient;
+import com.google.wireless.gdata.calendar.data.EventEntry;
+import com.google.wireless.gdata.calendar.data.EventsFeed;
+import com.google.wireless.gdata.calendar.data.Reminder;
+import com.google.wireless.gdata.calendar.data.When;
+import com.google.wireless.gdata.calendar.data.Who;
+import com.google.wireless.gdata.calendar.parser.xml.XmlCalendarGDataParserFactory;
+import com.google.wireless.gdata.client.GDataServiceClient;
+import com.google.wireless.gdata.client.QueryParams;
+import com.google.wireless.gdata.data.Entry;
+import com.google.wireless.gdata.data.Feed;
+import com.google.wireless.gdata.data.StringUtils;
+import com.google.wireless.gdata.parser.ParseException;
+
+import android.content.ContentProvider;
+import android.content.ContentResolver;
+import android.content.ContentUris;
+import android.content.ContentValues;
+import android.content.Context;
+import android.content.SyncContext;
+import android.content.SyncResult;
+import android.content.SyncableContentProvider;
+import android.database.Cursor;
+import android.database.CursorJoiner;
+import android.net.Uri;
+import android.os.Bundle;
+import android.os.SystemProperties;
+import android.pim.ICalendar;
+import android.pim.RecurrenceSet;
+import android.provider.Calendar;
+import android.provider.SubscribedFeeds;
+import android.provider.SyncConstValue;
+import android.provider.Calendar.Calendars;
+import android.provider.Calendar.Events;
+import android.text.TextUtils;
+import android.text.format.Time;
+import android.util.Config;
+import android.util.Log;
+
+import java.util.Enumeration;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Vector;
+
+/**
+ * SyncAdapter for Google Calendar. Fetches the list of the user's calendars,
+ * and for each calendar that is marked as &quot;selected&quot; in the web
+ * interface, syncs that calendar.
+ */
+public final class CalendarSyncAdapter extends AbstractGDataSyncAdapter {
+
+ private static final String SELECT_BY_ACCOUNT = Calendars._SYNC_ACCOUNT + "=?";
+ private static final String SELECT_BY_ACCOUNT_AND_FEED =
+ SELECT_BY_ACCOUNT + " AND " + Calendars.URL + "=?";
+
+ private static final String[] CALENDAR_KEY_COLUMNS =
+ new String[]{Calendars._SYNC_ACCOUNT, Calendars.URL};
+ private static final String CALENDAR_KEY_SORT_ORDER =
+ Calendars._SYNC_ACCOUNT + "," + Calendars.URL;
+ private static final String[] FEEDS_KEY_COLUMNS =
+ new String[]{SubscribedFeeds.Feeds._SYNC_ACCOUNT, SubscribedFeeds.Feeds.FEED};
+ private static final String FEEDS_KEY_SORT_ORDER =
+ SubscribedFeeds.Feeds._SYNC_ACCOUNT + ", " + SubscribedFeeds.Feeds.FEED;
+
+ public static class SyncInfo {
+ // public String feedUrl;
+ public long calendarId;
+ public String calendarTimezone;
+ }
+
+ private static final String TAG = "Sync";
+ private static final Integer sTentativeStatus = Events.STATUS_TENTATIVE;
+ private static final Integer sConfirmedStatus = Events.STATUS_CONFIRMED;
+ private static final Integer sCanceledStatus = Events.STATUS_CANCELED;
+
+ private final CalendarClient mCalendarClient;
+
+ private ContentResolver mContentResolver;
+
+ private static final String[] CALENDARS_PROJECTION = new String[] {
+ Calendars._ID, // 0
+ Calendars.SELECTED, // 1
+ Calendars._SYNC_TIME, // 2
+ Calendars.URL, // 3
+ Calendars.DISPLAY_NAME, // 4
+ Calendars.TIMEZONE, // 5
+ Calendars.SYNC_EVENTS // 6
+ };
+
+ // Counters for sync event logging
+ private static int mServerDiffs;
+ private static int mRefresh;
+
+ protected CalendarSyncAdapter(Context context, SyncableContentProvider provider) {
+ super(context, provider);
+ mCalendarClient = new CalendarClient(
+ new AndroidGDataClient(context),
+ new XmlCalendarGDataParserFactory(new AndroidXmlParserFactory()));
+ }
+
+ @Override
+ protected Object createSyncInfo() {
+ return new SyncInfo();
+ }
+
+ @Override
+ protected Entry newEntry() {
+ return new EventEntry();
+ }
+
+ @Override
+ protected Cursor getCursorForTable(ContentProvider cp, Class entryClass) {
+ if (entryClass != EventEntry.class) {
+ throw new IllegalArgumentException("unexpected entry class, " + entryClass.getName());
+ }
+ return cp.query(Calendar.Events.CONTENT_URI, null, null, null, null);
+ }
+
+ @Override
+ protected Cursor getCursorForDeletedTable(ContentProvider cp, Class entryClass) {
+ if (entryClass != EventEntry.class) {
+ throw new IllegalArgumentException("unexpected entry class, " + entryClass.getName());
+ }
+ return cp.query(Calendar.Events.DELETED_CONTENT_URI, null, null, null, null);
+ }
+
+ @Override
+ protected String cursorToEntry(SyncContext context, Cursor c, Entry entry,
+ Object info) throws ParseException {
+ EventEntry event = (EventEntry) entry;
+ SyncInfo syncInfo = (SyncInfo) info;
+
+ String feedUrl = c.getString(c.getColumnIndex(Calendars.URL));
+
+ // update the sync info. this will be used later when we update the
+ // provider with the results of sending this entry to the calendar
+ // server.
+ syncInfo.calendarId = c.getLong(c.getColumnIndex(Events.CALENDAR_ID));
+ syncInfo.calendarTimezone =
+ c.getString(c.getColumnIndex(Events.EVENT_TIMEZONE));
+ if (TextUtils.isEmpty(syncInfo.calendarTimezone)) {
+ // if the event timezone is not set -- e.g., when we're creating an
+ // event on the device -- we will use the timezone for the calendar.
+ syncInfo.calendarTimezone =
+ c.getString(c.getColumnIndex(Events.TIMEZONE));
+ }
+
+ // id
+ event.setId(c.getString(c.getColumnIndex(Events._SYNC_ID)));
+ event.setEditUri(c.getString(c.getColumnIndex(Events._SYNC_VERSION)));
+
+ // status
+ byte status;
+ int localStatus = c.getInt(c.getColumnIndex(Events.STATUS));
+ switch (localStatus) {
+ case Events.STATUS_CANCELED:
+ status = EventEntry.STATUS_CANCELED;
+ break;
+ case Events.STATUS_CONFIRMED:
+ status = EventEntry.STATUS_CONFIRMED;
+ break;
+ case Events.STATUS_TENTATIVE:
+ status = EventEntry.STATUS_TENTATIVE;
+ break;
+ default:
+ // should not happen
+ status = EventEntry.STATUS_TENTATIVE;
+ break;
+ }
+ event.setStatus(status);
+
+ // visibility
+ byte visibility;
+ int localVisibility = c.getInt(c.getColumnIndex(Events.VISIBILITY));
+ switch (localVisibility) {
+ case Events.VISIBILITY_DEFAULT:
+ visibility = EventEntry.VISIBILITY_DEFAULT;
+ break;
+ case Events.VISIBILITY_CONFIDENTIAL:
+ visibility = EventEntry.VISIBILITY_CONFIDENTIAL;
+ break;
+ case Events.VISIBILITY_PRIVATE:
+ visibility = EventEntry.VISIBILITY_PRIVATE;
+ break;
+ case Events.VISIBILITY_PUBLIC:
+ visibility = EventEntry.VISIBILITY_PUBLIC;
+ break;
+ default:
+ // should not happen
+ Log.e(TAG, "Unexpected value for visibility: " + localVisibility
+ + "; using default visibility.");
+ visibility = EventEntry.VISIBILITY_DEFAULT;
+ break;
+ }
+ event.setVisibility(visibility);
+
+ byte transparency;
+ int localTransparency = c.getInt(c.getColumnIndex(Events.TRANSPARENCY));
+ switch (localTransparency) {
+ case Events.TRANSPARENCY_OPAQUE:
+ transparency = EventEntry.TRANSPARENCY_OPAQUE;
+ break;
+ case Events.TRANSPARENCY_TRANSPARENT:
+ transparency = EventEntry.TRANSPARENCY_TRANSPARENT;
+ break;
+ default:
+ // should not happen
+ Log.e(TAG, "Unexpected value for transparency: " + localTransparency
+ + "; using opaque transparency.");
+ transparency = EventEntry.TRANSPARENCY_OPAQUE;
+ break;
+ }
+ event.setTransparency(transparency);
+
+ // could set the html uri, but there's no need to, since it should not be edited.
+
+ // title
+ event.setTitle(c.getString(c.getColumnIndex(Events.TITLE)));
+
+ // description
+ event.setContent(c.getString(c.getColumnIndex(Events.DESCRIPTION)));
+
+ // where
+ event.setWhere(c.getString(c.getColumnIndex(Events.EVENT_LOCATION)));
+
+ // attendees
+ long eventId = c.getInt(c.getColumnIndex(Events._SYNC_LOCAL_ID));
+ addAttendeesToEntry(eventId, event);
+
+ // comment uri
+ event.setCommentsUri(c.getString(c.getColumnIndexOrThrow(Events.COMMENTS_URI)));
+
+ Time utc = new Time(Time.TIMEZONE_UTC);
+
+ boolean allDay = c.getInt(c.getColumnIndex(Events.ALL_DAY)) != 0;
+
+ String startTime = null;
+ String endTime = null;
+ // start time
+ int dtstartColumn = c.getColumnIndex(Events.DTSTART);
+ if (!c.isNull(dtstartColumn)) {
+ long dtstart = c.getLong(dtstartColumn);
+ utc.set(dtstart);
+ startTime = utc.format3339(allDay);
+ }
+
+ // end time
+ int dtendColumn = c.getColumnIndex(Events.DTEND);
+ if (!c.isNull(dtendColumn)) {
+ long dtend = c.getLong(dtendColumn);
+ utc.set(dtend);
+ endTime = utc.format3339(allDay);
+ }
+
+ When when = new When(startTime, endTime);
+ event.addWhen(when);
+
+ // reminders
+ Integer hasReminder = c.getInt(c.getColumnIndex(Events.HAS_ALARM));
+ if (hasReminder != null && hasReminder.intValue() != 0) {
+ addRemindersToEntry(eventId, event);
+ }
+
+ // extendedProperties
+ Integer hasExtendedProperties = c.getInt(c.getColumnIndex(Events.HAS_EXTENDED_PROPERTIES));
+ if (hasExtendedProperties != null && hasExtendedProperties.intValue() != 0) {
+ addExtendedPropertiesToEntry(eventId, event);
+ }
+
+ long originalStartTime = -1;
+ String originalId = c.getString(c.getColumnIndex(Events.ORIGINAL_EVENT));
+ int originalStartTimeIndex = c.getColumnIndex(Events.ORIGINAL_INSTANCE_TIME);
+ if (!c.isNull(originalStartTimeIndex)) {
+ originalStartTime = c.getLong(originalStartTimeIndex);
+ }
+ if ((originalStartTime != -1) && !TextUtils.isEmpty(originalId)) {
+ // We need to use the "originalAllDay" field for the original event
+ // in order to format the "originalStartTime" correctly.
+ boolean originalAllDay = c.getInt(c.getColumnIndex(Events.ORIGINAL_ALL_DAY)) != 0;
+
+ Time originalTime = new Time(c.getString(c.getColumnIndex(Events.EVENT_TIMEZONE)));
+ originalTime.set(originalStartTime);
+
+ utc.set(originalStartTime);
+ event.setOriginalEventStartTime(utc.format3339(originalAllDay));
+ event.setOriginalEventId(originalId);
+ }
+
+ // recurrences.
+ ICalendar.Component component = new ICalendar.Component("DUMMY",
+ null /* parent */);
+ if (RecurrenceSet.populateComponent(c, component)) {
+ addRecurrenceToEntry(component, event);
+ }
+
+ // if this is a new entry, return the feed url. otherwise, return null; the edit url is
+ // already in the entry.
+ if (event.getEditUri() == null) {
+ return feedUrl;
+ } else {
+ return null;
+ }
+ }
+
+ private void addAttendeesToEntry(long eventId, EventEntry event)
+ throws ParseException {
+ Cursor c = getContext().getContentResolver().query(
+ Calendar.Attendees.CONTENT_URI, null, "event_id=" + eventId, null, null);
+
+ try {
+ int nameIndex = c.getColumnIndexOrThrow(Calendar.Attendees.ATTENDEE_NAME);
+ int emailIndex = c.getColumnIndexOrThrow(Calendar.Attendees.ATTENDEE_EMAIL);
+ int statusIndex = c.getColumnIndexOrThrow(Calendar.Attendees.ATTENDEE_STATUS);
+ int typeIndex = c.getColumnIndexOrThrow(Calendar.Attendees.ATTENDEE_TYPE);
+ int relIndex = c.getColumnIndexOrThrow(Calendar.Attendees.ATTENDEE_RELATIONSHIP);
+
+
+
+ while (c.moveToNext()) {
+ Who who = new Who();
+ who.setValue(c.getString(nameIndex));
+ who.setEmail(c.getString(emailIndex));
+ int status = c.getInt(statusIndex);
+ switch (status) {
+ case Calendar.Attendees.ATTENDEE_STATUS_NONE:
+ who.setStatus(Who.STATUS_NONE);
+ break;
+ case Calendar.Attendees.ATTENDEE_STATUS_ACCEPTED:
+ who.setStatus(Who.STATUS_ACCEPTED);
+ break;
+ case Calendar.Attendees.ATTENDEE_STATUS_DECLINED:
+ who.setStatus(Who.STATUS_DECLINED);
+ break;
+ case Calendar.Attendees.ATTENDEE_STATUS_INVITED:
+ who.setStatus(Who.STATUS_INVITED);
+ break;
+ case Calendar.Attendees.ATTENDEE_STATUS_TENTATIVE:
+ who.setStatus(Who.STATUS_TENTATIVE);
+ break;
+ default:
+ Log.e(TAG, "Unknown attendee status: " + status);
+ who.setStatus(Who.STATUS_NONE);
+ break;
+ }
+ int type = c.getInt(typeIndex);
+ switch (type) {
+ case Calendar.Attendees.TYPE_NONE:
+ who.setType(Who.TYPE_NONE);
+ break;
+ case Calendar.Attendees.TYPE_REQUIRED:
+ who.setType(Who.TYPE_REQUIRED);
+ break;
+ case Calendar.Attendees.TYPE_OPTIONAL:
+ who.setType(Who.TYPE_OPTIONAL);
+ break;
+ default:
+ Log.e(TAG, "Unknown attendee type: " + type);
+ who.setType(Who.TYPE_NONE);
+ break;
+ }
+ int rel = c.getInt(relIndex);
+ switch (rel) {
+ case Calendar.Attendees.RELATIONSHIP_NONE:
+ who.setRelationship(Who.RELATIONSHIP_NONE);
+ break;
+ case Calendar.Attendees.RELATIONSHIP_ATTENDEE:
+ who.setRelationship(Who.RELATIONSHIP_ATTENDEE);
+ break;
+ case Calendar.Attendees.RELATIONSHIP_ORGANIZER:
+ who.setRelationship(Who.RELATIONSHIP_ORGANIZER);
+ break;
+ case Calendar.Attendees.RELATIONSHIP_SPEAKER:
+ who.setRelationship(Who.RELATIONSHIP_SPEAKER);
+ break;
+ case Calendar.Attendees.RELATIONSHIP_PERFORMER:
+ who.setRelationship(Who.RELATIONSHIP_PERFORMER);
+ break;
+ default:
+ Log.e(TAG, "Unknown attendee relationship: " + rel);
+ who.setRelationship(Who.RELATIONSHIP_NONE);
+ break;
+ }
+ event.addAttendee(who);
+ }
+ } finally {
+ c.close();
+ }
+ }
+
+ private void addRemindersToEntry(long eventId, EventEntry event)
+ throws ParseException {
+ Cursor c = getContext().getContentResolver().query(
+ Calendar.Reminders.CONTENT_URI, null,
+ "event_id=" + eventId, null, null);
+
+ try {
+ int methodIndex = c.getColumnIndex(Calendar.Reminders.METHOD);
+ int minutesIndex = c.getColumnIndex(Calendar.Reminders.MINUTES);
+
+ while (c.moveToNext()) {
+ Reminder reminder = new Reminder();
+ reminder.setMinutes(c.getInt(minutesIndex));
+ int method = c.getInt(methodIndex);
+ switch(method) {
+ case Calendar.Reminders.METHOD_DEFAULT:
+ reminder.setMethod(Reminder.METHOD_DEFAULT);
+ break;
+ case Calendar.Reminders.METHOD_ALERT:
+ reminder.setMethod(Reminder.METHOD_ALERT);
+ break;
+ case Calendar.Reminders.METHOD_EMAIL:
+ reminder.setMethod(Reminder.METHOD_EMAIL);
+ break;
+ case Calendar.Reminders.METHOD_SMS:
+ reminder.setMethod(Reminder.METHOD_SMS);
+ break;
+ default:
+ throw new ParseException("illegal method, " + method);
+ }
+ event.addReminder(reminder);
+ }
+ } finally {
+ c.close();
+ }
+ }
+
+ private void addExtendedPropertiesToEntry(long eventId, EventEntry event)
+ throws ParseException {
+ Cursor c = getContext().getContentResolver().query(
+ Calendar.ExtendedProperties.CONTENT_URI, null,
+ "event_id=" + eventId, null, null);
+
+ try {
+ int nameIndex = c.getColumnIndex(Calendar.ExtendedProperties.NAME);
+ int valueIndex = c.getColumnIndex(Calendar.ExtendedProperties.VALUE);
+
+ while (c.moveToNext()) {
+ String name = c.getString(nameIndex);
+ String value = c.getString(valueIndex);
+ event.addExtendedProperty(name, value);
+ }
+ } finally {
+ c.close();
+ }
+ }
+
+ private void addRecurrenceToEntry(ICalendar.Component component,
+ EventEntry event) {
+ // serialize the component into a Google Calendar recurrence string
+ // we don't serialize the entire component, since we have a dummy
+ // wrapper (BEGIN:DUMMY, END:DUMMY).
+ StringBuilder sb = new StringBuilder();
+
+ // append the properties
+ boolean first = true;
+ for (String propertyName : component.getPropertyNames()) {
+ for (ICalendar.Property property :
+ component.getProperties(propertyName)) {
+ if (first) {
+ first = false;
+ } else {
+ sb.append("\n");
+ }
+ property.toString(sb);
+ }
+ }
+
+ // append the sub-components
+ List<ICalendar.Component> children = component.getComponents();
+ if (children != null) {
+ for (ICalendar.Component child : children) {
+ if (first) {
+ first = false;
+ } else {
+ sb.append("\n");
+ }
+ child.toString(sb);
+ }
+ }
+ event.setRecurrence(sb.toString());
+ }
+
+ @Override
+ protected void deletedCursorToEntry(SyncContext context, Cursor c, Entry entry) {
+ EventEntry event = (EventEntry) entry;
+ event.setId(c.getString(c.getColumnIndex(Events._SYNC_ID)));
+ event.setEditUri(c.getString(c.getColumnIndex(Events._SYNC_VERSION)));
+ event.setStatus(EventEntry.STATUS_CANCELED);
+ }
+
+ protected boolean handleAllDeletedUnavailable(GDataSyncData syncData, String feed) {
+ syncData.feedData.remove(feed);
+ getContext().getContentResolver().delete(Calendar.Calendars.CONTENT_URI,
+ Calendar.Calendars._SYNC_ACCOUNT + "=? AND " + Calendar.Calendars.URL + "=?",
+ new String[]{getAccount(), feed});
+ return true;
+ }
+
+ @Override
+ public void onSyncStarting(SyncContext context, String account, boolean forced,
+ SyncResult result) {
+ mContentResolver = getContext().getContentResolver();
+ mServerDiffs = 0;
+ mRefresh = 0;
+ super.onSyncStarting(context, account, forced, result);
+ }
+
+ private void deletedEntryToContentValues(Long syncLocalId, EventEntry event,
+ ContentValues values) {
+ // see #deletedCursorToEntry. this deletion cannot be an exception to a recurrence (e.g.,
+ // deleting an instance of a repeating event) -- new recurrence exceptions would be
+ // insertions.
+ values.clear();
+
+ // Base sync info
+ values.put(Events._SYNC_LOCAL_ID, syncLocalId);
+ values.put(Events._SYNC_ID, event.getId());
+ values.put(Events._SYNC_VERSION, event.getEditUri());
+ }
+
+ /**
+ * Clear out the map and stuff an Entry into it in a format that can
+ * be inserted into a content provider.
+ *
+ * @return ENTRY_OK, ENTRY_DELETED, or ENTRY_INVALID
+ */
+ private int entryToContentValues(EventEntry event, Long syncLocalId,