OSDN Git Service

Unbundle the DeskClock.
[android-x86/packages-apps-DeskClock.git] / src / com / android / deskclock / DeskClock.java
1 /*
2  * Copyright (C) 2009 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.android.deskclock;
18
19 import android.app.Activity;
20 import android.app.AlarmManager;
21 import android.app.AlertDialog;
22 import android.app.PendingIntent;
23 import android.content.BroadcastReceiver;
24 import android.content.Context;
25 import android.content.DialogInterface;
26 import android.content.Intent;
27 import android.content.IntentFilter;
28 import android.content.SharedPreferences;
29 import android.content.pm.PackageManager;
30 import android.content.res.Configuration;
31 import android.content.res.Resources;
32 import android.database.ContentObserver;
33 import android.database.Cursor;
34 import android.graphics.Rect;
35 import android.graphics.drawable.BitmapDrawable;
36 import android.graphics.drawable.ColorDrawable;
37 import android.graphics.drawable.Drawable;
38 import android.net.Uri;
39 import android.os.Bundle;
40 import android.os.Handler;
41 import android.os.Message;
42 import android.os.SystemClock;
43 import android.os.PowerManager;
44 import android.provider.Settings;
45 import android.text.TextUtils;
46 import android.text.format.DateFormat;
47 import android.util.DisplayMetrics;
48 import android.util.Log;
49 import android.view.ContextMenu.ContextMenuInfo;
50 import android.view.ContextMenu;
51 import android.view.LayoutInflater;
52 import android.view.Menu;
53 import android.view.MenuInflater;
54 import android.view.MenuItem;
55 import android.view.MotionEvent;
56 import android.view.View.OnClickListener;
57 import android.view.View.OnCreateContextMenuListener;
58 import android.view.View;
59 import android.view.ViewGroup;
60 import android.view.ViewTreeObserver;
61 import android.view.ViewTreeObserver.OnGlobalFocusChangeListener;
62 import android.view.Window;
63 import android.view.WindowManager;
64 import android.view.animation.Animation;
65 import android.view.animation.AnimationUtils;
66 import android.view.animation.TranslateAnimation;
67 import android.widget.AbsoluteLayout;
68 import android.widget.AdapterView.AdapterContextMenuInfo;
69 import android.widget.AdapterView.OnItemClickListener;
70 import android.widget.AdapterView;
71 import android.widget.Button;
72 import android.widget.CheckBox;
73 import android.widget.ImageButton;
74 import android.widget.ImageView;
75 import android.widget.TextView;
76
77 import static android.os.BatteryManager.BATTERY_STATUS_CHARGING;
78 import static android.os.BatteryManager.BATTERY_STATUS_FULL;
79 import static android.os.BatteryManager.BATTERY_STATUS_UNKNOWN;
80
81 import java.io.IOException;
82 import java.io.InputStream;
83 import java.util.Calendar;
84 import java.util.Date;
85 import java.util.Locale;
86 import java.util.Random;
87
88 /**
89  * DeskClock clock view for desk docks.
90  */
91 public class DeskClock extends Activity {
92     private static final boolean DEBUG = false;
93
94     private static final String LOG_TAG = "DeskClock";
95
96     // Package ID of the music player.
97     private static final String MUSIC_PACKAGE_ID = "com.android.music";
98
99     // Alarm action for midnight (so we can update the date display).
100     private static final String ACTION_MIDNIGHT = "com.android.deskclock.MIDNIGHT";
101
102     // Interval between forced polls of the weather widget.
103     private final long QUERY_WEATHER_DELAY = 60 * 60 * 1000; // 1 hr
104
105     // Delay before engaging the burn-in protection mode (green-on-black).
106     private final long SCREEN_SAVER_TIMEOUT = 5 * 60 * 1000; // 5 min
107
108     // Repositioning delay in screen saver.
109     private final long SCREEN_SAVER_MOVE_DELAY = 60 * 1000; // 1 min
110
111     // Color to use for text & graphics in screen saver mode.
112     private final int SCREEN_SAVER_COLOR = 0xFF308030;
113     private final int SCREEN_SAVER_COLOR_DIM = 0xFF183018;
114
115     // Opacity of black layer between clock display and wallpaper.
116     private final float DIM_BEHIND_AMOUNT_NORMAL = 0.4f;
117     private final float DIM_BEHIND_AMOUNT_DIMMED = 0.8f; // higher contrast when display dimmed
118
119     // Internal message IDs.
120     private final int QUERY_WEATHER_DATA_MSG     = 0x1000;
121     private final int UPDATE_WEATHER_DISPLAY_MSG = 0x1001;
122     private final int SCREEN_SAVER_TIMEOUT_MSG   = 0x2000;
123     private final int SCREEN_SAVER_MOVE_MSG      = 0x2001;
124
125     // Weather widget query information.
126     private static final String GENIE_PACKAGE_ID = "com.google.android.apps.genie.geniewidget";
127     private static final String WEATHER_CONTENT_AUTHORITY = GENIE_PACKAGE_ID + ".weather";
128     private static final String WEATHER_CONTENT_PATH = "/weather/current";
129     private static final String[] WEATHER_CONTENT_COLUMNS = new String[] {
130             "location",
131             "timestamp",
132             "temperature",
133             "highTemperature",
134             "lowTemperature",
135             "iconUrl",
136             "iconResId",
137             "description",
138         };
139
140     private static final String ACTION_GENIE_REFRESH = "com.google.android.apps.genie.REFRESH";
141
142     // State variables follow.
143     private DigitalClock mTime;
144     private TextView mDate;
145
146     private TextView mNextAlarm = null;
147     private TextView mBatteryDisplay;
148
149     private TextView mWeatherCurrentTemperature;
150     private TextView mWeatherHighTemperature;
151     private TextView mWeatherLowTemperature;
152     private TextView mWeatherLocation;
153     private ImageView mWeatherIcon;
154
155     private String mWeatherCurrentTemperatureString;
156     private String mWeatherHighTemperatureString;
157     private String mWeatherLowTemperatureString;
158     private String mWeatherLocationString;
159     private Drawable mWeatherIconDrawable;
160
161     private Resources mGenieResources = null;
162
163     private boolean mDimmed = false;
164     private boolean mScreenSaverMode = false;
165
166     private String mDateFormat;
167
168     private int mBatteryLevel = -1;
169     private boolean mPluggedIn = false;
170
171     private boolean mLaunchedFromDock = false;
172
173     private Random mRNG;
174
175     private PendingIntent mMidnightIntent;
176
177     private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
178         @Override
179         public void onReceive(Context context, Intent intent) {
180             final String action = intent.getAction();
181             if (DEBUG) Log.d(LOG_TAG, "mIntentReceiver.onReceive: action=" + action + ", intent=" + intent);
182             if (Intent.ACTION_DATE_CHANGED.equals(action) || ACTION_MIDNIGHT.equals(action)) {
183                 refreshDate();
184             } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
185                 handleBatteryUpdate(
186                     intent.getIntExtra("status", BATTERY_STATUS_UNKNOWN),
187                     intent.getIntExtra("level", 0));
188             } else if (Intent.ACTION_DOCK_EVENT.equals(action)) {
189                 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, -1);
190                 if (DEBUG) Log.d(LOG_TAG, "ACTION_DOCK_EVENT, state=" + state);
191                 if (state == Intent.EXTRA_DOCK_STATE_UNDOCKED) {
192                     if (mLaunchedFromDock) {
193                         // moveTaskToBack(false);
194                         finish();
195                     }
196                     mLaunchedFromDock = false;
197                 }
198             }
199         }
200     };
201
202     private final Handler mHandy = new Handler() {
203         @Override
204         public void handleMessage(Message m) {
205             if (m.what == QUERY_WEATHER_DATA_MSG) {
206                 new Thread() { public void run() { queryWeatherData(); } }.start();
207                 scheduleWeatherQueryDelayed(QUERY_WEATHER_DELAY);
208             } else if (m.what == UPDATE_WEATHER_DISPLAY_MSG) {
209                 updateWeatherDisplay();
210             } else if (m.what == SCREEN_SAVER_TIMEOUT_MSG) {
211                 saveScreen();
212             } else if (m.what == SCREEN_SAVER_MOVE_MSG) {
213                 moveScreenSaver();
214             }
215         }
216     };
217
218     private final ContentObserver mContentObserver = new ContentObserver(mHandy) {
219         @Override
220         public void onChange(boolean selfChange) {
221             if (DEBUG) Log.d(LOG_TAG, "content observer notified that weather changed");
222             refreshWeather();
223         }
224     };
225
226
227     private void moveScreenSaver() {
228         moveScreenSaverTo(-1,-1);
229     }
230     private void moveScreenSaverTo(int x, int y) {
231         if (!mScreenSaverMode) return;
232
233         final View saver_view = findViewById(R.id.saver_view);
234
235         DisplayMetrics metrics = new DisplayMetrics();
236         getWindowManager().getDefaultDisplay().getMetrics(metrics);
237
238         if (x < 0 || y < 0) {
239             int myWidth = saver_view.getMeasuredWidth();
240             int myHeight = saver_view.getMeasuredHeight();
241             x = (int)(mRNG.nextFloat()*(metrics.widthPixels - myWidth));
242             y = (int)(mRNG.nextFloat()*(metrics.heightPixels - myHeight));
243         }
244
245         if (DEBUG) Log.d(LOG_TAG, String.format("screen saver: %d: jumping to (%d,%d)",
246                 System.currentTimeMillis(), x, y));
247
248         saver_view.setLayoutParams(new AbsoluteLayout.LayoutParams(
249             ViewGroup.LayoutParams.WRAP_CONTENT,
250             ViewGroup.LayoutParams.WRAP_CONTENT,
251             x,
252             y));
253
254         // Synchronize our jumping so that it happens exactly on the second.
255         mHandy.sendEmptyMessageDelayed(SCREEN_SAVER_MOVE_MSG,
256             SCREEN_SAVER_MOVE_DELAY +
257             (1000 - (System.currentTimeMillis() % 1000)));
258     }
259
260     private void setWakeLock(boolean hold) {
261         if (DEBUG) Log.d(LOG_TAG, (hold ? "hold" : " releas") + "ing wake lock");
262         Window win = getWindow();
263         WindowManager.LayoutParams winParams = win.getAttributes();
264         winParams.flags |= WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
265         winParams.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
266         winParams.flags |= WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
267         if (hold)
268             winParams.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
269         else
270             winParams.flags &= (~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
271         win.setAttributes(winParams);
272     }
273
274     private void scheduleScreenSaver() {
275         // reschedule screen saver
276         mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG);
277         mHandy.sendMessageDelayed(
278             Message.obtain(mHandy, SCREEN_SAVER_TIMEOUT_MSG),
279             SCREEN_SAVER_TIMEOUT);
280     }
281
282     private void restoreScreen() {
283         if (!mScreenSaverMode) return;
284         if (DEBUG) Log.d(LOG_TAG, "restoreScreen");
285         mScreenSaverMode = false;
286         initViews();
287         doDim(false); // restores previous dim mode
288         // policy: update weather info when returning from screen saver
289         if (mPluggedIn) requestWeatherDataFetch();
290
291         scheduleScreenSaver();
292
293         refreshAll();
294     }
295
296     // Special screen-saver mode for OLED displays that burn in quickly
297     private void saveScreen() {
298         if (mScreenSaverMode) return;
299         if (DEBUG) Log.d(LOG_TAG, "saveScreen");
300
301         // quickly stash away the x/y of the current date
302         final View oldTimeDate = findViewById(R.id.time_date);
303         int oldLoc[] = new int[2];
304         oldTimeDate.getLocationOnScreen(oldLoc);
305
306         mScreenSaverMode = true;
307         Window win = getWindow();
308         WindowManager.LayoutParams winParams = win.getAttributes();
309         winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
310         win.setAttributes(winParams);
311
312         // give up any internal focus before we switch layouts
313         final View focused = getCurrentFocus();
314         if (focused != null) focused.clearFocus();
315
316         setContentView(R.layout.desk_clock_saver);
317
318         mTime = (DigitalClock) findViewById(R.id.time);
319         mDate = (TextView) findViewById(R.id.date);
320         mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
321
322         final int color = mDimmed ? SCREEN_SAVER_COLOR_DIM : SCREEN_SAVER_COLOR;
323
324         ((TextView)findViewById(R.id.timeDisplay)).setTextColor(color);
325         ((TextView)findViewById(R.id.am_pm)).setTextColor(color);
326         mDate.setTextColor(color);
327         mNextAlarm.setTextColor(color);
328         mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
329             getResources().getDrawable(mDimmed
330                 ? R.drawable.ic_lock_idle_alarm_saver_dim
331                 : R.drawable.ic_lock_idle_alarm_saver),
332             null, null, null);
333
334         mBatteryDisplay =
335         mWeatherCurrentTemperature =
336         mWeatherHighTemperature =
337         mWeatherLowTemperature =
338         mWeatherLocation = null;
339         mWeatherIcon = null;
340
341         refreshDate();
342         refreshAlarm();
343
344         moveScreenSaverTo(oldLoc[0], oldLoc[1]);
345     }
346
347     @Override
348     public void onUserInteraction() {
349         if (mScreenSaverMode)
350             restoreScreen();
351     }
352
353     // Tell the Genie widget to load new data from the network.
354     private void requestWeatherDataFetch() {
355         if (DEBUG) Log.d(LOG_TAG, "forcing the Genie widget to update weather now...");
356         sendBroadcast(new Intent(ACTION_GENIE_REFRESH).putExtra("requestWeather", true));
357         // we expect the result to show up in our content observer
358     }
359
360     private boolean supportsWeather() {
361         return (mGenieResources != null);
362     }
363
364     private void scheduleWeatherQueryDelayed(long delay) {
365         // cancel any existing scheduled queries
366         unscheduleWeatherQuery();
367
368         if (DEBUG) Log.d(LOG_TAG, "scheduling weather fetch message for " + delay + "ms from now");
369
370         mHandy.sendEmptyMessageDelayed(QUERY_WEATHER_DATA_MSG, delay);
371     }
372
373     private void unscheduleWeatherQuery() {
374         mHandy.removeMessages(QUERY_WEATHER_DATA_MSG);
375     }
376
377     private void queryWeatherData() {
378         // if we couldn't load the weather widget's resources, we simply
379         // assume it's not present on the device.
380         if (mGenieResources == null) return;
381
382         Uri queryUri = new Uri.Builder()
383             .scheme(android.content.ContentResolver.SCHEME_CONTENT)
384             .authority(WEATHER_CONTENT_AUTHORITY)
385             .path(WEATHER_CONTENT_PATH)
386             .appendPath(new Long(System.currentTimeMillis()).toString())
387             .build();
388
389         if (DEBUG) Log.d(LOG_TAG, "querying genie: " + queryUri);
390
391         Cursor cur;
392         try {
393             cur = managedQuery(
394                 queryUri,
395                 WEATHER_CONTENT_COLUMNS,
396                 null,
397                 null,
398                 null);
399         } catch (RuntimeException e) {
400             Log.e(LOG_TAG, "Weather query failed", e);
401             cur = null;
402         }
403
404         if (cur != null && cur.moveToFirst()) {
405             if (DEBUG) {
406                 java.lang.StringBuilder sb =
407                     new java.lang.StringBuilder("Weather query result: {");
408                 for(int i=0; i<cur.getColumnCount(); i++) {
409                     if (i>0) sb.append(", ");
410                     sb.append(cur.getColumnName(i))
411                         .append("=")
412                         .append(cur.getString(i));
413                 }
414                 sb.append("}");
415                 Log.d(LOG_TAG, sb.toString());
416             }
417
418             mWeatherIconDrawable = mGenieResources.getDrawable(cur.getInt(
419                 cur.getColumnIndexOrThrow("iconResId")));
420             mWeatherCurrentTemperatureString = String.format("%d\u00b0",
421                 (cur.getInt(cur.getColumnIndexOrThrow("temperature"))));
422             mWeatherHighTemperatureString = String.format("%d\u00b0",
423                 (cur.getInt(cur.getColumnIndexOrThrow("highTemperature"))));
424             mWeatherLowTemperatureString = String.format("%d\u00b0",
425                 (cur.getInt(cur.getColumnIndexOrThrow("lowTemperature"))));
426             mWeatherLocationString = cur.getString(
427                 cur.getColumnIndexOrThrow("location"));
428         } else {
429             Log.w(LOG_TAG, "No weather information available (cur="
430                 + cur +")");
431             mWeatherIconDrawable = null;
432             mWeatherHighTemperatureString = "";
433             mWeatherLowTemperatureString = "";
434             mWeatherLocationString = getString(R.string.weather_fetch_failure);
435         }
436
437         mHandy.sendEmptyMessage(UPDATE_WEATHER_DISPLAY_MSG);
438     }
439
440     private void refreshWeather() {
441         if (supportsWeather())
442             scheduleWeatherQueryDelayed(0);
443         updateWeatherDisplay(); // in case we have it cached
444     }
445
446     private void updateWeatherDisplay() {
447         if (mWeatherCurrentTemperature == null) return;
448
449         mWeatherCurrentTemperature.setText(mWeatherCurrentTemperatureString);
450         mWeatherHighTemperature.setText(mWeatherHighTemperatureString);
451         mWeatherLowTemperature.setText(mWeatherLowTemperatureString);
452         mWeatherLocation.setText(mWeatherLocationString);
453         mWeatherIcon.setImageDrawable(mWeatherIconDrawable);
454     }
455
456     // Adapted from KeyguardUpdateMonitor.java
457     private void handleBatteryUpdate(int plugStatus, int batteryLevel) {
458         final boolean pluggedIn = (plugStatus == BATTERY_STATUS_CHARGING || plugStatus == BATTERY_STATUS_FULL);
459         if (pluggedIn != mPluggedIn) {
460             setWakeLock(pluggedIn);
461
462             if (pluggedIn) {
463                 // policy: update weather info when attaching to power
464                 requestWeatherDataFetch();
465             }
466         }
467         if (pluggedIn != mPluggedIn || batteryLevel != mBatteryLevel) {
468             mBatteryLevel = batteryLevel;
469             mPluggedIn = pluggedIn;
470             refreshBattery();
471         }
472     }
473
474     private void refreshBattery() {
475         if (mBatteryDisplay == null) return;
476
477         if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) {
478             mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds(
479                 0, 0, android.R.drawable.ic_lock_idle_charging, 0);
480             mBatteryDisplay.setText(
481                 getString(R.string.battery_charging_level, mBatteryLevel));
482             mBatteryDisplay.setVisibility(View.VISIBLE);
483         } else {
484             mBatteryDisplay.setVisibility(View.INVISIBLE);
485         }
486     }
487
488     private void refreshDate() {
489         final Date now = new Date();
490         if (DEBUG) Log.d(LOG_TAG, "refreshing date..." + now);
491         mDate.setText(DateFormat.format(mDateFormat, now));
492     }
493
494     private void refreshAlarm() {
495         if (mNextAlarm == null) return;
496
497         String nextAlarm = Settings.System.getString(getContentResolver(),
498                 Settings.System.NEXT_ALARM_FORMATTED);
499         if (!TextUtils.isEmpty(nextAlarm)) {
500             mNextAlarm.setText(nextAlarm);
501             //mNextAlarm.setCompoundDrawablesWithIntrinsicBounds(
502             //    android.R.drawable.ic_lock_idle_alarm, 0, 0, 0);
503             mNextAlarm.setVisibility(View.VISIBLE);
504         } else {
505             mNextAlarm.setVisibility(View.INVISIBLE);
506         }
507     }
508
509     private void refreshAll() {
510         refreshDate();
511         refreshAlarm();
512         refreshBattery();
513         refreshWeather();
514     }
515
516     private void doDim(boolean fade) {
517         View tintView = findViewById(R.id.window_tint);
518         if (tintView == null) return;
519
520         Window win = getWindow();
521         WindowManager.LayoutParams winParams = win.getAttributes();
522
523         winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
524         winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
525
526         // dim the wallpaper somewhat (how much is determined below)
527         winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND);
528
529         if (mDimmed) {
530             winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
531             winParams.dimAmount = DIM_BEHIND_AMOUNT_DIMMED;
532             winParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF;
533
534             // show the window tint
535             tintView.startAnimation(AnimationUtils.loadAnimation(this,
536                 fade ? R.anim.dim
537                      : R.anim.dim_instant));
538         } else {
539             winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
540             winParams.dimAmount = DIM_BEHIND_AMOUNT_NORMAL;
541             winParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
542
543             // hide the window tint
544             tintView.startAnimation(AnimationUtils.loadAnimation(this,
545                 fade ? R.anim.undim
546                      : R.anim.undim_instant));
547         }
548
549         win.setAttributes(winParams);
550     }
551
552     @Override
553     public void onNewIntent(Intent newIntent) {
554         super.onNewIntent(newIntent);
555         if (DEBUG) Log.d(LOG_TAG, "onNewIntent with intent: " + newIntent);
556
557         // update our intent so that we can consult it to determine whether or
558         // not the most recent launch was via a dock event 
559         setIntent(newIntent);
560     }
561
562     @Override
563     public void onResume() {
564         super.onResume();
565         if (DEBUG) Log.d(LOG_TAG, "onResume with intent: " + getIntent());
566
567         // reload the date format in case the user has changed settings
568         // recently
569         mDateFormat = getString(R.string.full_wday_month_day_no_year);
570
571         IntentFilter filter = new IntentFilter();
572         filter.addAction(Intent.ACTION_DATE_CHANGED);
573         filter.addAction(Intent.ACTION_BATTERY_CHANGED);
574         filter.addAction(Intent.ACTION_DOCK_EVENT);
575         filter.addAction(ACTION_MIDNIGHT);
576         registerReceiver(mIntentReceiver, filter);
577
578         // Listen for updates to weather data
579         Uri weatherNotificationUri = new Uri.Builder()
580             .scheme(android.content.ContentResolver.SCHEME_CONTENT)
581             .authority(WEATHER_CONTENT_AUTHORITY)
582             .path(WEATHER_CONTENT_PATH)
583             .build();
584         getContentResolver().registerContentObserver(
585             weatherNotificationUri, true, mContentObserver);
586
587         // Elaborate mechanism to find out when the day rolls over
588         Calendar today = Calendar.getInstance();
589         today.set(Calendar.HOUR_OF_DAY, 0);
590         today.set(Calendar.MINUTE, 0);
591         today.set(Calendar.SECOND, 0);
592         today.add(Calendar.DATE, 1);
593         long alarmTimeUTC = today.getTimeInMillis() + today.get(Calendar.ZONE_OFFSET);
594         mMidnightIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_MIDNIGHT), 0);
595         AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
596         am.setRepeating(AlarmManager.RTC, alarmTimeUTC, AlarmManager.INTERVAL_DAY, mMidnightIntent);
597         if (DEBUG) Log.d(LOG_TAG, "set repeating midnight event at "
598             + alarmTimeUTC + " repeating every "
599             + AlarmManager.INTERVAL_DAY + " with intent: " + mMidnightIntent);
600
601         // If we weren't previously visible but now we are, it's because we're
602         // being started from another activity. So it's OK to un-dim.
603         if (mTime != null && mTime.getWindowVisibility() != View.VISIBLE) {
604             mDimmed = false;
605         }
606
607         // Adjust the display to reflect the currently chosen dim mode.
608         doDim(false);
609
610         restoreScreen(); // disable screen saver
611         refreshAll(); // will schedule periodic weather fetch
612
613         setWakeLock(mPluggedIn);
614
615         scheduleScreenSaver();
616
617         final boolean launchedFromDock
618             = getIntent().hasCategory(Intent.CATEGORY_DESK_DOCK);
619
620         if (supportsWeather() && launchedFromDock && !mLaunchedFromDock) {
621             // policy: fetch weather if launched via dock connection
622             if (DEBUG) Log.d(LOG_TAG, "Device now docked; forcing weather to refresh right now");
623             requestWeatherDataFetch();
624         }
625
626         mLaunchedFromDock = launchedFromDock;
627     }
628
629     @Override
630     public void onPause() {
631         if (DEBUG) Log.d(LOG_TAG, "onPause");
632
633         // Turn off the screen saver and cancel any pending timeouts.
634         // (But don't un-dim.)
635         mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG);
636         restoreScreen();
637
638         // Other things we don't want to be doing in the background.
639         unregisterReceiver(mIntentReceiver);
640         getContentResolver().unregisterContentObserver(mContentObserver);
641
642         AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
643         am.cancel(mMidnightIntent);
644         unscheduleWeatherQuery();
645
646         super.onPause();
647     }
648
649     private void initViews() {
650         // give up any internal focus before we switch layouts
651         final View focused = getCurrentFocus();
652         if (focused != null) focused.clearFocus();
653
654         setContentView(R.layout.desk_clock);
655
656         mTime = (DigitalClock) findViewById(R.id.time);
657         mDate = (TextView) findViewById(R.id.date);
658         mBatteryDisplay = (TextView) findViewById(R.id.battery);
659
660         mTime.getRootView().requestFocus();
661
662         mWeatherCurrentTemperature = (TextView) findViewById(R.id.weather_temperature);
663         mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature);
664         mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature);
665         mWeatherLocation = (TextView) findViewById(R.id.weather_location);
666         mWeatherIcon = (ImageView) findViewById(R.id.weather_icon);
667
668         final View.OnClickListener alarmClickListener = new View.OnClickListener() {
669             public void onClick(View v) {
670                 startActivity(new Intent(DeskClock.this, AlarmClock.class));
671             }
672         };
673
674         mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
675         mNextAlarm.setOnClickListener(alarmClickListener);
676
677         final ImageButton alarmButton = (ImageButton) findViewById(R.id.alarm_button);
678         alarmButton.setOnClickListener(alarmClickListener);
679
680         final ImageButton galleryButton = (ImageButton) findViewById(R.id.gallery_button);
681         galleryButton.setOnClickListener(new View.OnClickListener() {
682             public void onClick(View v) {
683                 try {
684                     startActivity(new Intent(
685                         Intent.ACTION_VIEW,
686                         android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
687                             .putExtra("slideshow", true)
688                             .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP));
689                 } catch (android.content.ActivityNotFoundException e) {
690                     Log.e(LOG_TAG, "Couldn't launch image browser", e);
691                 }
692             }
693         });
694
695         final ImageButton musicButton = (ImageButton) findViewById(R.id.music_button);
696         musicButton.setOnClickListener(new View.OnClickListener() {
697             public void onClick(View v) {
698                 try {
699                     Intent musicAppQuery = getPackageManager()
700                         .getLaunchIntentForPackage(MUSIC_PACKAGE_ID)
701                         .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
702                     if (musicAppQuery != null) {
703                         startActivity(musicAppQuery);
704                     }
705                 } catch (android.content.ActivityNotFoundException e) {
706                     Log.e(LOG_TAG, "Couldn't launch music browser", e);
707                 }
708             }
709         });
710
711         final ImageButton homeButton = (ImageButton) findViewById(R.id.home_button);
712         homeButton.setOnClickListener(new View.OnClickListener() {
713             public void onClick(View v) {
714                 startActivity(
715                     new Intent(Intent.ACTION_MAIN)
716                         .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP)
717                         .addCategory(Intent.CATEGORY_HOME));
718             }
719         });
720
721         final ImageButton nightmodeButton = (ImageButton) findViewById(R.id.nightmode_button);
722         nightmodeButton.setOnClickListener(new View.OnClickListener() {
723             public void onClick(View v) {
724                 mDimmed = ! mDimmed;
725                 doDim(true);
726             }
727         });
728
729         nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() {
730             public boolean onLongClick(View v) {
731                 saveScreen();
732                 return true;
733             }
734         });
735
736         final View weatherView = findViewById(R.id.weather);
737         weatherView.setOnClickListener(new View.OnClickListener() {
738             public void onClick(View v) {
739                 if (!supportsWeather()) return;
740
741                 Intent genieAppQuery = getPackageManager()
742                     .getLaunchIntentForPackage(GENIE_PACKAGE_ID)
743                     .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
744                 if (genieAppQuery != null) {
745                     startActivity(genieAppQuery);
746                 }
747             }
748         });
749
750         final View tintView = findViewById(R.id.window_tint);
751         tintView.setOnTouchListener(new View.OnTouchListener() {
752             public boolean onTouch(View v, MotionEvent event) {
753                 if (mDimmed && event.getAction() == MotionEvent.ACTION_DOWN) {
754                     // We want to un-dim the whole screen on tap.
755                     // ...Unless the user is specifically tapping on the dim
756                     // widget, in which case let it do the work.
757                     Rect r = new Rect();
758                     nightmodeButton.getHitRect(r);
759                     int[] gloc = new int[2];
760                     nightmodeButton.getLocationInWindow(gloc);
761                     r.offsetTo(gloc[0], gloc[1]); // convert to window coords
762
763                     if (!r.contains((int) event.getX(), (int) event.getY())) {
764                         mDimmed = false;
765                         doDim(true);
766                     }
767                 }
768                 return false; // always pass the click through
769             }
770         });
771
772         // Tidy up awkward focus behavior: the first view to be focused in
773         // trackball mode should be the alarms button
774         final ViewTreeObserver vto = alarmButton.getViewTreeObserver();
775         vto.addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
776             public void onGlobalFocusChanged(View oldFocus, View newFocus) {
777                 if (oldFocus == null && newFocus == nightmodeButton) {
778                     alarmButton.requestFocus();
779                 }
780             }
781         });
782     }
783
784     @Override
785     public void onConfigurationChanged(Configuration newConfig) {
786         super.onConfigurationChanged(newConfig);
787         if (mScreenSaverMode) {
788             moveScreenSaver();
789         } else {
790             initViews();
791             doDim(false);
792             refreshAll();
793         }
794     }
795
796     @Override
797     public boolean onOptionsItemSelected(MenuItem item) {
798         if (item.getItemId() == R.id.menu_item_alarms) {
799             startActivity(new Intent(DeskClock.this, AlarmClock.class));
800             return true;
801         } else if (item.getItemId() == R.id.menu_item_add_alarm) {
802             AlarmClock.addNewAlarm(this);
803             return true;
804         }
805         return false;
806     }
807
808     @Override
809     public boolean onCreateOptionsMenu(Menu menu) {
810         MenuInflater inflater = getMenuInflater();
811         inflater.inflate(R.menu.desk_clock_menu, menu);
812         return true;
813     }
814
815     @Override
816     protected void onCreate(Bundle icicle) {
817         super.onCreate(icicle);
818
819         mRNG = new Random();
820
821         try {
822             mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID);
823         } catch (PackageManager.NameNotFoundException e) {
824             // no weather info available
825             Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available.");
826         }
827
828         initViews();
829     }
830
831 }