summaryrefslogtreecommitdiffstats
path: root/src/com/cyanogenmod/lockclock/preference/CalendarPreferences.java
blob: d2d3a03c17c164ed3113e9a21bf5fd7db1130203 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/*
 * Copyright (C) 2012 The CyanogenMod Project (DvTonder)
 *
 * 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.cyanogenmod.lockclock.preference;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.MultiSelectListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceScreen;
import android.preference.SwitchPreference;
import android.provider.CalendarContract;

import com.cyanogenmod.lockclock.ClockWidgetProvider;
import com.cyanogenmod.lockclock.ClockWidgetService;
import com.cyanogenmod.lockclock.R;
import com.cyanogenmod.lockclock.misc.Constants;

import java.util.ArrayList;
import java.util.List;

public class CalendarPreferences extends PreferenceFragment implements
    OnSharedPreferenceChangeListener, Preference.OnPreferenceChangeListener {

    private static final int CALENDAR_PERMISSION_REQUEST_CODE = 1;

    private Context mContext;
    private ListPreference mFontColor;
    private ListPreference mEventDetailsFontColor;
    private ListPreference mHighlightFontColor;
    private ListPreference mHighlightDetailsFontColor;
    private SwitchPreference mShowCalendar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getPreferenceManager().setSharedPreferencesName(Constants.PREF_NAME);
        addPreferencesFromResource(R.xml.preferences_calendar);
        mContext = getActivity();

        mFontColor = (ListPreference) findPreference(Constants.CALENDAR_FONT_COLOR);
        mEventDetailsFontColor = (ListPreference) findPreference(Constants.CALENDAR_DETAILS_FONT_COLOR);
        mHighlightFontColor = (ListPreference) findPreference(Constants.CALENDAR_UPCOMING_EVENTS_FONT_COLOR);
        mHighlightDetailsFontColor = (ListPreference) findPreference(Constants.CALENDAR_UPCOMING_EVENTS_DETAILS_FONT_COLOR);
        updateFontColorsSummary();

        mShowCalendar = (SwitchPreference) findPreference(Constants.SHOW_CALENDAR);
        mShowCalendar.setOnPreferenceChangeListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
        if (!hasCalendarPermission()) {
            mShowCalendar.setChecked(false);
        } else {
            updateCalendars();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
        Preference pref = findPreference(key);
        if (pref instanceof ListPreference) {
            ListPreference listPref = (ListPreference) pref;
            pref.setSummary(listPref.getEntry());
        }
        Intent updateIntent = new Intent(mContext, ClockWidgetProvider.class);
        updateIntent.setAction(ClockWidgetService.ACTION_REFRESH_CALENDAR);
        mContext.sendBroadcast(updateIntent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        if (requestCode == CALENDAR_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // We only get here if user tried to enable the preference,
                // hence safe to turn it on after permission is granted
                mShowCalendar.setChecked(true);
                updateCalendars();
            }
        }
    }

    private boolean hasCalendarPermission() {
        return mContext.checkSelfPermission(Manifest.permission.READ_CALENDAR)
                == PackageManager.PERMISSION_GRANTED;
    }

    private void updateCalendars() {
        if (!hasCalendarPermission()) {
            return;
        }
        // The calendar list entries and values are determined at run time, not in XML
        MultiSelectListPreference calendarList =
                (MultiSelectListPreference) findPreference(Constants.CALENDAR_LIST);
        CalendarEntries calEntries = CalendarEntries.findCalendars(getActivity());
        calendarList.setEntries(calEntries.getEntries());
        calendarList.setEntryValues(calEntries.getEntryValues());
    }

    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        if (preference == mShowCalendar) {
            if (hasCalendarPermission()) {
                updateCalendars();
            } else {
                Boolean enabled = (Boolean) newValue;
                if (enabled) {
                    String[] permissions = new String[]{Manifest.permission.READ_CALENDAR};
                    requestPermissions(permissions, CALENDAR_PERMISSION_REQUEST_CODE);
                    return false;
                }
            }
        }
        return true;
    }

    //===============================================================================================
    // Utility classes and supporting methods
    //===============================================================================================

    private static class CalendarEntries {
        private final CharSequence[] mEntries;
        private final CharSequence[] mEntryValues;
        private static Uri uri = CalendarContract.Calendars.CONTENT_URI;

        // Calendar projection array
        private static String[] projection = new String[] {
               CalendarContract.Calendars._ID,
               CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
        };

        // The indices for the projection array
        private static final int CALENDAR_ID_INDEX = 0;
        private static final int DISPLAY_NAME_INDEX = 1;

        static CalendarEntries findCalendars(Context context) {
            List<CharSequence> entries = new ArrayList<>();
            List<CharSequence> entryValues = new ArrayList<>();
            ContentResolver cr = context.getContentResolver();

            Cursor calendarCursor = cr.query(uri, projection, null, null, null);
            if (calendarCursor != null) {
                calendarCursor.moveToFirst();
                while (!calendarCursor.isAfterLast()) {
                    entryValues.add(calendarCursor.getString(CALENDAR_ID_INDEX));
                    entries.add(calendarCursor.getString(DISPLAY_NAME_INDEX));
                    calendarCursor.moveToNext();
                }
                calendarCursor.close();
            }

            return new CalendarEntries(entries, entryValues);
        }

        private CalendarEntries(List<CharSequence> mEntries, List<CharSequence> mEntryValues) {
            this.mEntries = mEntries.toArray(new CharSequence[mEntries.size()]);
            this.mEntryValues = mEntryValues.toArray(new CharSequence[mEntryValues.size()]);
        }

        CharSequence[] getEntries() {
            return mEntries;
        }

        CharSequence[] getEntryValues() {
            return mEntryValues;
        }
    }

    private void updateFontColorsSummary() {
        if (mFontColor != null) {
            mFontColor.setSummary(mFontColor.getEntry());
        }
        if (mEventDetailsFontColor != null) {
            mEventDetailsFontColor.setSummary(mEventDetailsFontColor.getEntry());
        }
        if (mHighlightFontColor != null) {
            mHighlightFontColor.setSummary(mHighlightFontColor.getEntry());
        }
        if (mHighlightDetailsFontColor != null) {
            mHighlightDetailsFontColor.setSummary(mHighlightDetailsFontColor.getEntry());
        }
    }
}