OSDN Git Service

Several tweaks to DeskClock's dimming feature:
[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
533             // show the window tint
534             tintView.startAnimation(AnimationUtils.loadAnimation(this,
535                 fade ? R.anim.dim
536                      : R.anim.dim_instant));
537         } else {
538             winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
539             winParams.dimAmount = DIM_BEHIND_AMOUNT_NORMAL;
540
541             // hide the window tint
542             tintView.startAnimation(AnimationUtils.loadAnimation(this,
543                 fade ? R.anim.undim
544                      : R.anim.undim_instant));
545         }
546
547         win.setAttributes(winParams);
548     }
549
550     @Override
551     public void onNewIntent(Intent newIntent) {
552         super.onNewIntent(newIntent);
553         if (DEBUG) Log.d(LOG_TAG, "onNewIntent with intent: " + newIntent);
554
555         // update our intent so that we can consult it to determine whether or
556         // not the most recent launch was via a dock event 
557         setIntent(newIntent);
558     }
559
560     @Override
561     public void onResume() {
562         super.onResume();
563         if (DEBUG) Log.d(LOG_TAG, "onResume with intent: " + getIntent());
564
565         // reload the date format in case the user has changed settings
566         // recently
567         mDateFormat = getString(com.android.internal.R.string.full_wday_month_day_no_year);
568
569         IntentFilter filter = new IntentFilter();
570         filter.addAction(Intent.ACTION_DATE_CHANGED);
571         filter.addAction(Intent.ACTION_BATTERY_CHANGED);
572         filter.addAction(Intent.ACTION_DOCK_EVENT);
573         filter.addAction(ACTION_MIDNIGHT);
574         registerReceiver(mIntentReceiver, filter);
575
576         // Listen for updates to weather data
577         Uri weatherNotificationUri = new Uri.Builder()
578             .scheme(android.content.ContentResolver.SCHEME_CONTENT)
579             .authority(WEATHER_CONTENT_AUTHORITY)
580             .path(WEATHER_CONTENT_PATH)
581             .build();
582         getContentResolver().registerContentObserver(
583             weatherNotificationUri, true, mContentObserver);
584
585         // Elaborate mechanism to find out when the day rolls over
586         Calendar today = Calendar.getInstance();
587         today.set(Calendar.HOUR_OF_DAY, 0);
588         today.set(Calendar.MINUTE, 0);
589         today.set(Calendar.SECOND, 0);
590         today.add(Calendar.DATE, 1);
591         long alarmTimeUTC = today.getTimeInMillis() + today.get(Calendar.ZONE_OFFSET);
592         mMidnightIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_MIDNIGHT), 0);
593         AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
594         am.setRepeating(AlarmManager.RTC, alarmTimeUTC, AlarmManager.INTERVAL_DAY, mMidnightIntent);
595         if (DEBUG) Log.d(LOG_TAG, "set repeating midnight event at "
596             + alarmTimeUTC + " repeating every "
597             + AlarmManager.INTERVAL_DAY + " with intent: " + mMidnightIntent);
598
599         // If we weren't previously visible but now we are, it's because we're
600         // being started from another activity. So it's OK to un-dim.
601         if (mTime != null && mTime.getWindowVisibility() != View.VISIBLE) {
602             mDimmed = false;
603         }
604
605         // Adjust the display to reflect the currently chosen dim mode.
606         doDim(false);
607
608         restoreScreen(); // disable screen saver
609         refreshAll(); // will schedule periodic weather fetch
610
611         setWakeLock(mPluggedIn);
612
613         scheduleScreenSaver();
614
615         final boolean launchedFromDock
616             = getIntent().hasCategory(Intent.CATEGORY_DESK_DOCK);
617
618         if (supportsWeather() && launchedFromDock && !mLaunchedFromDock) {
619             // policy: fetch weather if launched via dock connection
620             if (DEBUG) Log.d(LOG_TAG, "Device now docked; forcing weather to refresh right now");
621             requestWeatherDataFetch();
622         }
623
624         mLaunchedFromDock = launchedFromDock;
625     }
626
627     @Override
628     public void onPause() {
629         if (DEBUG) Log.d(LOG_TAG, "onPause");
630
631         // Turn off the screen saver and cancel any pending timeouts.
632         // (But don't un-dim.)
633         mHandy.removeMessages(SCREEN_SAVER_TIMEOUT_MSG);
634         restoreScreen();
635
636         // Other things we don't want to be doing in the background.
637         unregisterReceiver(mIntentReceiver);
638         getContentResolver().unregisterContentObserver(mContentObserver);
639
640         AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
641         am.cancel(mMidnightIntent);
642         unscheduleWeatherQuery();
643
644         super.onPause();
645     }
646
647     private void initViews() {
648         // give up any internal focus before we switch layouts
649         final View focused = getCurrentFocus();
650         if (focused != null) focused.clearFocus();
651
652         setContentView(R.layout.desk_clock);
653
654         mTime = (DigitalClock) findViewById(R.id.time);
655         mDate = (TextView) findViewById(R.id.date);
656         mBatteryDisplay = (TextView) findViewById(R.id.battery);
657
658         mTime.getRootView().requestFocus();
659
660         mWeatherCurrentTemperature = (TextView) findViewById(R.id.weather_temperature);
661         mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature);
662         mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature);
663         mWeatherLocation = (TextView) findViewById(R.id.weather_location);
664         mWeatherIcon = (ImageView) findViewById(R.id.weather_icon);
665
666         final View.OnClickListener alarmClickListener = new View.OnClickListener() {
667             public void onClick(View v) {
668                 startActivity(new Intent(DeskClock.this, AlarmClock.class));
669             }
670         };
671
672         mNextAlarm = (TextView) findViewById(R.id.nextAlarm);
673         mNextAlarm.setOnClickListener(alarmClickListener);
674
675         final ImageButton alarmButton = (ImageButton) findViewById(R.id.alarm_button);
676         alarmButton.setOnClickListener(alarmClickListener);
677
678         final ImageButton galleryButton = (ImageButton) findViewById(R.id.gallery_button);
679         galleryButton.setOnClickListener(new View.OnClickListener() {
680             public void onClick(View v) {
681                 try {
682                     startActivity(new Intent(
683                         Intent.ACTION_VIEW,
684                         android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
685                             .putExtra("slideshow", true)
686                             .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP));
687                 } catch (android.content.ActivityNotFoundException e) {
688                     Log.e(LOG_TAG, "Couldn't launch image browser", e);
689                 }
690             }
691         });
692
693         final ImageButton musicButton = (ImageButton) findViewById(R.id.music_button);
694         musicButton.setOnClickListener(new View.OnClickListener() {
695             public void onClick(View v) {
696                 try {
697                     Intent musicAppQuery = getPackageManager()
698                         .getLaunchIntentForPackage(MUSIC_PACKAGE_ID)
699                         .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
700                     if (musicAppQuery != null) {
701                         startActivity(musicAppQuery);
702                     }
703                 } catch (android.content.ActivityNotFoundException e) {
704                     Log.e(LOG_TAG, "Couldn't launch music browser", e);
705                 }
706             }
707         });
708
709         final ImageButton homeButton = (ImageButton) findViewById(R.id.home_button);
710         homeButton.setOnClickListener(new View.OnClickListener() {
711             public void onClick(View v) {
712                 startActivity(
713                     new Intent(Intent.ACTION_MAIN)
714                         .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP)
715                         .addCategory(Intent.CATEGORY_HOME));
716             }
717         });
718
719         final ImageButton nightmodeButton = (ImageButton) findViewById(R.id.nightmode_button);
720         nightmodeButton.setOnClickListener(new View.OnClickListener() {
721             public void onClick(View v) {
722                 mDimmed = ! mDimmed;
723                 doDim(true);
724             }
725         });
726
727         nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() {
728             public boolean onLongClick(View v) {
729                 saveScreen();
730                 return true;
731             }
732         });
733
734         final View weatherView = findViewById(R.id.weather);
735         weatherView.setOnClickListener(new View.OnClickListener() {
736             public void onClick(View v) {
737                 if (!supportsWeather()) return;
738
739                 Intent genieAppQuery = getPackageManager()
740                     .getLaunchIntentForPackage(GENIE_PACKAGE_ID)
741                     .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
742                 if (genieAppQuery != null) {
743                     startActivity(genieAppQuery);
744                 }
745             }
746         });
747
748         final View tintView = findViewById(R.id.window_tint);
749         tintView.setOnTouchListener(new View.OnTouchListener() {
750             public boolean onTouch(View v, MotionEvent event) {
751                 if (mDimmed && event.getAction() == MotionEvent.ACTION_DOWN) {
752                     // We want to un-dim the whole screen on tap.
753                     // ...Unless the user is specifically tapping on the dim
754                     // widget, in which case let it do the work.
755                     Rect r = new Rect();
756                     nightmodeButton.getHitRect(r);
757                     int[] gloc = new int[2];
758                     nightmodeButton.getLocationInWindow(gloc);
759                     r.offsetTo(gloc[0], gloc[1]); // convert to window coords
760
761                     if (!r.contains((int) event.getX(), (int) event.getY())) {
762                         mDimmed = false;
763                         doDim(true);
764                     }
765                 }
766                 return false; // always pass the click through
767             }
768         });
769
770         // Tidy up awkward focus behavior: the first view to be focused in
771         // trackball mode should be the alarms button
772         final ViewTreeObserver vto = alarmButton.getViewTreeObserver();
773         vto.addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
774             public void onGlobalFocusChanged(View oldFocus, View newFocus) {
775                 if (oldFocus == null && newFocus == nightmodeButton) {
776                     alarmButton.requestFocus();
777                 }
778             }
779         });
780     }
781
782     @Override
783     public void onConfigurationChanged(Configuration newConfig) {
784         super.onConfigurationChanged(newConfig);
785         if (mScreenSaverMode) {
786             moveScreenSaver();
787         } else {
788             initViews();
789             doDim(false);
790             refreshAll();
791         }
792     }
793
794     @Override
795     public boolean onOptionsItemSelected(MenuItem item) {
796         if (item.getItemId() == R.id.menu_item_alarms) {
797             startActivity(new Intent(DeskClock.this, AlarmClock.class));
798             return true;
799         } else if (item.getItemId() == R.id.menu_item_add_alarm) {
800             AlarmClock.addNewAlarm(this);
801             return true;
802         }
803         return false;
804     }
805
806     @Override
807     public boolean onCreateOptionsMenu(Menu menu) {
808         MenuInflater inflater = getMenuInflater();
809         inflater.inflate(R.menu.desk_clock_menu, menu);
810         return true;
811     }
812
813     @Override
814     protected void onCreate(Bundle icicle) {
815         super.onCreate(icicle);
816
817         mRNG = new Random();
818
819         try {
820             mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID);
821         } catch (PackageManager.NameNotFoundException e) {
822             // no weather info available
823             Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available.");
824         }
825
826         initViews();
827     }
828
829 }