create changelog entry
[debian/openrocket] / android-libraries / ActionBarSherlock / src / com / actionbarsherlock / widget / ActivityChooserModel.java
1 /*
2  * Copyright (C) 2011 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.actionbarsherlock.widget;
18
19 import android.content.ComponentName;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.pm.ResolveInfo;
23 import android.database.DataSetObservable;
24 import android.os.Handler;
25 import android.text.TextUtils;
26 import android.util.Log;
27 import android.util.Xml;
28
29 import org.xmlpull.v1.XmlPullParser;
30 import org.xmlpull.v1.XmlPullParserException;
31 import org.xmlpull.v1.XmlSerializer;
32
33 import java.io.FileInputStream;
34 import java.io.FileNotFoundException;
35 import java.io.FileOutputStream;
36 import java.io.IOException;
37 import java.math.BigDecimal;
38 import java.util.ArrayList;
39 import java.util.Collections;
40 import java.util.HashMap;
41 import java.util.LinkedHashSet;
42 import java.util.LinkedList;
43 import java.util.List;
44 import java.util.Map;
45 import java.util.Set;
46 import java.util.concurrent.Executor;
47
48 /**
49  * <p>
50  * This class represents a data model for choosing a component for handing a
51  * given {@link Intent}. The model is responsible for querying the system for
52  * activities that can handle the given intent and order found activities
53  * based on historical data of previous choices. The historical data is stored
54  * in an application private file. If a client does not want to have persistent
55  * choice history the file can be omitted, thus the activities will be ordered
56  * based on historical usage for the current session.
57  * <p>
58  * </p>
59  * For each backing history file there is a singleton instance of this class. Thus,
60  * several clients that specify the same history file will share the same model. Note
61  * that if multiple clients are sharing the same model they should implement semantically
62  * equivalent functionality since setting the model intent will change the found
63  * activities and they may be inconsistent with the functionality of some of the clients.
64  * For example, choosing a share activity can be implemented by a single backing
65  * model and two different views for performing the selection. If however, one of the
66  * views is used for sharing but the other for importing, for example, then each
67  * view should be backed by a separate model.
68  * </p>
69  * <p>
70  * The way clients interact with this class is as follows:
71  * </p>
72  * <p>
73  * <pre>
74  * <code>
75  *  // Get a model and set it to a couple of clients with semantically similar function.
76  *  ActivityChooserModel dataModel =
77  *      ActivityChooserModel.get(context, "task_specific_history_file_name.xml");
78  *
79  *  ActivityChooserModelClient modelClient1 = getActivityChooserModelClient1();
80  *  modelClient1.setActivityChooserModel(dataModel);
81  *
82  *  ActivityChooserModelClient modelClient2 = getActivityChooserModelClient2();
83  *  modelClient2.setActivityChooserModel(dataModel);
84  *
85  *  // Set an intent to choose a an activity for.
86  *  dataModel.setIntent(intent);
87  * <pre>
88  * <code>
89  * </p>
90  * <p>
91  * <strong>Note:</strong> This class is thread safe.
92  * </p>
93  *
94  * @hide
95  */
96 class ActivityChooserModel extends DataSetObservable {
97
98     /**
99      * Client that utilizes an {@link ActivityChooserModel}.
100      */
101     public interface ActivityChooserModelClient {
102
103         /**
104          * Sets the {@link ActivityChooserModel}.
105          *
106          * @param dataModel The model.
107          */
108         public void setActivityChooserModel(ActivityChooserModel dataModel);
109     }
110
111     /**
112      * Defines a sorter that is responsible for sorting the activities
113      * based on the provided historical choices and an intent.
114      */
115     public interface ActivitySorter {
116
117         /**
118          * Sorts the <code>activities</code> in descending order of relevance
119          * based on previous history and an intent.
120          *
121          * @param intent The {@link Intent}.
122          * @param activities Activities to be sorted.
123          * @param historicalRecords Historical records.
124          */
125         // This cannot be done by a simple comparator since an Activity weight
126         // is computed from history. Note that Activity implements Comparable.
127         public void sort(Intent intent, List<ActivityResolveInfo> activities,
128                 List<HistoricalRecord> historicalRecords);
129     }
130
131     /**
132      * Listener for choosing an activity.
133      */
134     public interface OnChooseActivityListener {
135
136         /**
137          * Called when an activity has been chosen. The client can decide whether
138          * an activity can be chosen and if so the caller of
139          * {@link ActivityChooserModel#chooseActivity(int)} will receive and {@link Intent}
140          * for launching it.
141          * <p>
142          * <strong>Note:</strong> Modifying the intent is not permitted and
143          *     any changes to the latter will be ignored.
144          * </p>
145          *
146          * @param host The listener's host model.
147          * @param intent The intent for launching the chosen activity.
148          * @return Whether the intent is handled and should not be delivered to clients.
149          *
150          * @see ActivityChooserModel#chooseActivity(int)
151          */
152         public boolean onChooseActivity(ActivityChooserModel host, Intent intent);
153     }
154
155     /**
156      * Flag for selecting debug mode.
157      */
158     private static final boolean DEBUG = false;
159
160     /**
161      * Tag used for logging.
162      */
163     private static final String LOG_TAG = ActivityChooserModel.class.getSimpleName();
164
165     /**
166      * The root tag in the history file.
167      */
168     private static final String TAG_HISTORICAL_RECORDS = "historical-records";
169
170     /**
171      * The tag for a record in the history file.
172      */
173     private static final String TAG_HISTORICAL_RECORD = "historical-record";
174
175     /**
176      * Attribute for the activity.
177      */
178     private static final String ATTRIBUTE_ACTIVITY = "activity";
179
180     /**
181      * Attribute for the choice time.
182      */
183     private static final String ATTRIBUTE_TIME = "time";
184
185     /**
186      * Attribute for the choice weight.
187      */
188     private static final String ATTRIBUTE_WEIGHT = "weight";
189
190     /**
191      * The default name of the choice history file.
192      */
193     public static final String DEFAULT_HISTORY_FILE_NAME =
194         "activity_choser_model_history.xml";
195
196     /**
197      * The default maximal length of the choice history.
198      */
199     public static final int DEFAULT_HISTORY_MAX_LENGTH = 50;
200
201     /**
202      * The amount with which to inflate a chosen activity when set as default.
203      */
204     private static final int DEFAULT_ACTIVITY_INFLATION = 5;
205
206     /**
207      * Default weight for a choice record.
208      */
209     private static final float DEFAULT_HISTORICAL_RECORD_WEIGHT = 1.0f;
210
211     /**
212      * The extension of the history file.
213      */
214     private static final String HISTORY_FILE_EXTENSION = ".xml";
215
216     /**
217      * An invalid item index.
218      */
219     private static final int INVALID_INDEX = -1;
220
221     /**
222      * Lock to guard the model registry.
223      */
224     private static final Object sRegistryLock = new Object();
225
226     /**
227      * This the registry for data models.
228      */
229     private static final Map<String, ActivityChooserModel> sDataModelRegistry =
230         new HashMap<String, ActivityChooserModel>();
231
232     /**
233      * Lock for synchronizing on this instance.
234      */
235     private final Object mInstanceLock = new Object();
236
237     /**
238      * List of activities that can handle the current intent.
239      */
240     private final List<ActivityResolveInfo> mActivites = new ArrayList<ActivityResolveInfo>();
241
242     /**
243      * List with historical choice records.
244      */
245     private final List<HistoricalRecord> mHistoricalRecords = new ArrayList<HistoricalRecord>();
246
247     /**
248      * Context for accessing resources.
249      */
250     private final Context mContext;
251
252     /**
253      * The name of the history file that backs this model.
254      */
255     private final String mHistoryFileName;
256
257     /**
258      * The intent for which a activity is being chosen.
259      */
260     private Intent mIntent;
261
262     /**
263      * The sorter for ordering activities based on intent and past choices.
264      */
265     private ActivitySorter mActivitySorter = new DefaultSorter();
266
267     /**
268      * The maximal length of the choice history.
269      */
270     private int mHistoryMaxSize = DEFAULT_HISTORY_MAX_LENGTH;
271
272     /**
273      * Flag whether choice history can be read. In general many clients can
274      * share the same data model and {@link #readHistoricalData()} may be called
275      * by arbitrary of them any number of times. Therefore, this class guarantees
276      * that the very first read succeeds and subsequent reads can be performed
277      * only after a call to {@link #persistHistoricalData()} followed by change
278      * of the share records.
279      */
280     private boolean mCanReadHistoricalData = true;
281
282     /**
283      * Flag whether the choice history was read. This is used to enforce that
284      * before calling {@link #persistHistoricalData()} a call to
285      * {@link #persistHistoricalData()} has been made. This aims to avoid a
286      * scenario in which a choice history file exits, it is not read yet and
287      * it is overwritten. Note that always all historical records are read in
288      * full and the file is rewritten. This is necessary since we need to
289      * purge old records that are outside of the sliding window of past choices.
290      */
291     private boolean mReadShareHistoryCalled = false;
292
293     /**
294      * Flag whether the choice records have changed. In general many clients can
295      * share the same data model and {@link #persistHistoricalData()} may be called
296      * by arbitrary of them any number of times. Therefore, this class guarantees
297      * that choice history will be persisted only if it has changed.
298      */
299     private boolean mHistoricalRecordsChanged = true;
300
301     /**
302      * Hander for scheduling work on client tread.
303      */
304     private final Handler mHandler = new Handler();
305
306     /**
307      * Policy for controlling how the model handles chosen activities.
308      */
309     private OnChooseActivityListener mActivityChoserModelPolicy;
310
311     /**
312      * Gets the data model backed by the contents of the provided file with historical data.
313      * Note that only one data model is backed by a given file, thus multiple calls with
314      * the same file name will return the same model instance. If no such instance is present
315      * it is created.
316      * <p>
317      * <strong>Note:</strong> To use the default historical data file clients should explicitly
318      * pass as file name {@link #DEFAULT_HISTORY_FILE_NAME}. If no persistence of the choice
319      * history is desired clients should pass <code>null</code> for the file name. In such
320      * case a new model is returned for each invocation.
321      * </p>
322      *
323      * <p>
324      * <strong>Always use difference historical data files for semantically different actions.
325      * For example, sharing is different from importing.</strong>
326      * </p>
327      *
328      * @param context Context for loading resources.
329      * @param historyFileName File name with choice history, <code>null</code>
330      *        if the model should not be backed by a file. In this case the activities
331      *        will be ordered only by data from the current session.
332      *
333      * @return The model.
334      */
335     public static ActivityChooserModel get(Context context, String historyFileName) {
336         synchronized (sRegistryLock) {
337             ActivityChooserModel dataModel = sDataModelRegistry.get(historyFileName);
338             if (dataModel == null) {
339                 dataModel = new ActivityChooserModel(context, historyFileName);
340                 sDataModelRegistry.put(historyFileName, dataModel);
341             }
342             dataModel.readHistoricalData();
343             return dataModel;
344         }
345     }
346
347     /**
348      * Creates a new instance.
349      *
350      * @param context Context for loading resources.
351      * @param historyFileName The history XML file.
352      */
353     private ActivityChooserModel(Context context, String historyFileName) {
354         mContext = context.getApplicationContext();
355         if (!TextUtils.isEmpty(historyFileName)
356                 && !historyFileName.endsWith(HISTORY_FILE_EXTENSION)) {
357             mHistoryFileName = historyFileName + HISTORY_FILE_EXTENSION;
358         } else {
359             mHistoryFileName = historyFileName;
360         }
361     }
362
363     /**
364      * Sets an intent for which to choose a activity.
365      * <p>
366      * <strong>Note:</strong> Clients must set only semantically similar
367      * intents for each data model.
368      * <p>
369      *
370      * @param intent The intent.
371      */
372     public void setIntent(Intent intent) {
373         synchronized (mInstanceLock) {
374             if (mIntent == intent) {
375                 return;
376             }
377             mIntent = intent;
378             loadActivitiesLocked();
379         }
380     }
381
382     /**
383      * Gets the intent for which a activity is being chosen.
384      *
385      * @return The intent.
386      */
387     public Intent getIntent() {
388         synchronized (mInstanceLock) {
389             return mIntent;
390         }
391     }
392
393     /**
394      * Gets the number of activities that can handle the intent.
395      *
396      * @return The activity count.
397      *
398      * @see #setIntent(Intent)
399      */
400     public int getActivityCount() {
401         synchronized (mInstanceLock) {
402             return mActivites.size();
403         }
404     }
405
406     /**
407      * Gets an activity at a given index.
408      *
409      * @return The activity.
410      *
411      * @see ActivityResolveInfo
412      * @see #setIntent(Intent)
413      */
414     public ResolveInfo getActivity(int index) {
415         synchronized (mInstanceLock) {
416             return mActivites.get(index).resolveInfo;
417         }
418     }
419
420     /**
421      * Gets the index of a the given activity.
422      *
423      * @param activity The activity index.
424      *
425      * @return The index if found, -1 otherwise.
426      */
427     public int getActivityIndex(ResolveInfo activity) {
428         List<ActivityResolveInfo> activities = mActivites;
429         final int activityCount = activities.size();
430         for (int i = 0; i < activityCount; i++) {
431             ActivityResolveInfo currentActivity = activities.get(i);
432             if (currentActivity.resolveInfo == activity) {
433                 return i;
434             }
435         }
436         return INVALID_INDEX;
437     }
438
439     /**
440      * Chooses a activity to handle the current intent. This will result in
441      * adding a historical record for that action and construct intent with
442      * its component name set such that it can be immediately started by the
443      * client.
444      * <p>
445      * <strong>Note:</strong> By calling this method the client guarantees
446      * that the returned intent will be started. This intent is returned to
447      * the client solely to let additional customization before the start.
448      * </p>
449      *
450      * @return An {@link Intent} for launching the activity or null if the
451      *         policy has consumed the intent.
452      *
453      * @see HistoricalRecord
454      * @see OnChooseActivityListener
455      */
456     public Intent chooseActivity(int index) {
457         ActivityResolveInfo chosenActivity = mActivites.get(index);
458
459         ComponentName chosenName = new ComponentName(
460                 chosenActivity.resolveInfo.activityInfo.packageName,
461                 chosenActivity.resolveInfo.activityInfo.name);
462
463         Intent choiceIntent = new Intent(mIntent);
464         choiceIntent.setComponent(chosenName);
465
466         if (mActivityChoserModelPolicy != null) {
467             // Do not allow the policy to change the intent.
468             Intent choiceIntentCopy = new Intent(choiceIntent);
469             final boolean handled = mActivityChoserModelPolicy.onChooseActivity(this,
470                     choiceIntentCopy);
471             if (handled) {
472                 return null;
473             }
474         }
475
476         HistoricalRecord historicalRecord = new HistoricalRecord(chosenName,
477                 System.currentTimeMillis(), DEFAULT_HISTORICAL_RECORD_WEIGHT);
478         addHisoricalRecord(historicalRecord);
479
480         return choiceIntent;
481     }
482
483     /**
484      * Sets the listener for choosing an activity.
485      *
486      * @param listener The listener.
487      */
488     public void setOnChooseActivityListener(OnChooseActivityListener listener) {
489         mActivityChoserModelPolicy = listener;
490     }
491
492     /**
493      * Gets the default activity, The default activity is defined as the one
494      * with highest rank i.e. the first one in the list of activities that can
495      * handle the intent.
496      *
497      * @return The default activity, <code>null</code> id not activities.
498      *
499      * @see #getActivity(int)
500      */
501     public ResolveInfo getDefaultActivity() {
502         synchronized (mInstanceLock) {
503             if (!mActivites.isEmpty()) {
504                 return mActivites.get(0).resolveInfo;
505             }
506         }
507         return null;
508     }
509
510     /**
511      * Sets the default activity. The default activity is set by adding a
512      * historical record with weight high enough that this activity will
513      * become the highest ranked. Such a strategy guarantees that the default
514      * will eventually change if not used. Also the weight of the record for
515      * setting a default is inflated with a constant amount to guarantee that
516      * it will stay as default for awhile.
517      *
518      * @param index The index of the activity to set as default.
519      */
520     public void setDefaultActivity(int index) {
521         ActivityResolveInfo newDefaultActivity = mActivites.get(index);
522         ActivityResolveInfo oldDefaultActivity = mActivites.get(0);
523
524         final float weight;
525         if (oldDefaultActivity != null) {
526             // Add a record with weight enough to boost the chosen at the top.
527             weight = oldDefaultActivity.weight - newDefaultActivity.weight
528                 + DEFAULT_ACTIVITY_INFLATION;
529         } else {
530             weight = DEFAULT_HISTORICAL_RECORD_WEIGHT;
531         }
532
533         ComponentName defaultName = new ComponentName(
534                 newDefaultActivity.resolveInfo.activityInfo.packageName,
535                 newDefaultActivity.resolveInfo.activityInfo.name);
536         HistoricalRecord historicalRecord = new HistoricalRecord(defaultName,
537                 System.currentTimeMillis(), weight);
538         addHisoricalRecord(historicalRecord);
539     }
540
541     /**
542      * Reads the history data from the backing file if the latter
543      * was provided. Calling this method more than once before a call
544      * to {@link #persistHistoricalData()} has been made has no effect.
545      * <p>
546      * <strong>Note:</strong> Historical data is read asynchronously and
547      *       as soon as the reading is completed any registered
548      *       {@link DataSetObserver}s will be notified. Also no historical
549      *       data is read until this method is invoked.
550      * <p>
551      */
552     private void readHistoricalData() {
553         synchronized (mInstanceLock) {
554             if (!mCanReadHistoricalData || !mHistoricalRecordsChanged) {
555                 return;
556             }
557             mCanReadHistoricalData = false;
558             mReadShareHistoryCalled = true;
559             if (!TextUtils.isEmpty(mHistoryFileName)) {
560                 /*AsyncTask.*/SERIAL_EXECUTOR.execute(new HistoryLoader());
561             }
562         }
563     }
564
565     private static final SerialExecutor SERIAL_EXECUTOR = new SerialExecutor();
566
567     private static class SerialExecutor implements Executor {
568         final LinkedList<Runnable> mTasks = new LinkedList<Runnable>();
569         Runnable mActive;
570
571         public synchronized void execute(final Runnable r) {
572             mTasks.offer(new Runnable() {
573                 public void run() {
574                     try {
575                         r.run();
576                     } finally {
577                         scheduleNext();
578                     }
579                 }
580             });
581             if (mActive == null) {
582                 scheduleNext();
583             }
584         }
585
586         protected synchronized void scheduleNext() {
587             if ((mActive = mTasks.poll()) != null) {
588                 mActive.run();
589             }
590         }
591     }
592
593     /**
594      * Persists the history data to the backing file if the latter
595      * was provided. Calling this method before a call to {@link #readHistoricalData()}
596      * throws an exception. Calling this method more than one without choosing an
597      * activity has not effect.
598      *
599      * @throws IllegalStateException If this method is called before a call to
600      *         {@link #readHistoricalData()}.
601      */
602     private void persistHistoricalData() {
603         synchronized (mInstanceLock) {
604             if (!mReadShareHistoryCalled) {
605                 throw new IllegalStateException("No preceding call to #readHistoricalData");
606             }
607             if (!mHistoricalRecordsChanged) {
608                 return;
609             }
610             mHistoricalRecordsChanged = false;
611             mCanReadHistoricalData = true;
612             if (!TextUtils.isEmpty(mHistoryFileName)) {
613                 /*AsyncTask.*/SERIAL_EXECUTOR.execute(new HistoryPersister());
614             }
615         }
616     }
617
618     /**
619      * Sets the sorter for ordering activities based on historical data and an intent.
620      *
621      * @param activitySorter The sorter.
622      *
623      * @see ActivitySorter
624      */
625     public void setActivitySorter(ActivitySorter activitySorter) {
626         synchronized (mInstanceLock) {
627             if (mActivitySorter == activitySorter) {
628                 return;
629             }
630             mActivitySorter = activitySorter;
631             sortActivities();
632         }
633     }
634
635     /**
636      * Sorts the activities based on history and an intent. If
637      * a sorter is not specified this a default implementation is used.
638      *
639      * @see #setActivitySorter(ActivitySorter)
640      */
641     private void sortActivities() {
642         synchronized (mInstanceLock) {
643             if (mActivitySorter != null && !mActivites.isEmpty()) {
644                 mActivitySorter.sort(mIntent, mActivites,
645                         Collections.unmodifiableList(mHistoricalRecords));
646                 notifyChanged();
647             }
648         }
649     }
650
651     /**
652      * Sets the maximal size of the historical data. Defaults to
653      * {@link #DEFAULT_HISTORY_MAX_LENGTH}
654      * <p>
655      *   <strong>Note:</strong> Setting this property will immediately
656      *   enforce the specified max history size by dropping enough old
657      *   historical records to enforce the desired size. Thus, any
658      *   records that exceed the history size will be discarded and
659      *   irreversibly lost.
660      * </p>
661      *
662      * @param historyMaxSize The max history size.
663      */
664     public void setHistoryMaxSize(int historyMaxSize) {
665         synchronized (mInstanceLock) {
666             if (mHistoryMaxSize == historyMaxSize) {
667                 return;
668             }
669             mHistoryMaxSize = historyMaxSize;
670             pruneExcessiveHistoricalRecordsLocked();
671             sortActivities();
672         }
673     }
674
675     /**
676      * Gets the history max size.
677      *
678      * @return The history max size.
679      */
680     public int getHistoryMaxSize() {
681         synchronized (mInstanceLock) {
682             return mHistoryMaxSize;
683         }
684     }
685
686     /**
687      * Gets the history size.
688      *
689      * @return The history size.
690      */
691     public int getHistorySize() {
692         synchronized (mInstanceLock) {
693             return mHistoricalRecords.size();
694         }
695     }
696
697     /**
698      * Adds a historical record.
699      *
700      * @param historicalRecord The record to add.
701      * @return True if the record was added.
702      */
703     private boolean addHisoricalRecord(HistoricalRecord historicalRecord) {
704         synchronized (mInstanceLock) {
705             final boolean added = mHistoricalRecords.add(historicalRecord);
706             if (added) {
707                 mHistoricalRecordsChanged = true;
708                 pruneExcessiveHistoricalRecordsLocked();
709                 persistHistoricalData();
710                 sortActivities();
711             }
712             return added;
713         }
714     }
715
716     /**
717      * Prunes older excessive records to guarantee {@link #mHistoryMaxSize}.
718      */
719     private void pruneExcessiveHistoricalRecordsLocked() {
720         List<HistoricalRecord> choiceRecords = mHistoricalRecords;
721         final int pruneCount = choiceRecords.size() - mHistoryMaxSize;
722         if (pruneCount <= 0) {
723             return;
724         }
725         mHistoricalRecordsChanged = true;
726         for (int i = 0; i < pruneCount; i++) {
727             HistoricalRecord prunedRecord = choiceRecords.remove(0);
728             if (DEBUG) {
729                 Log.i(LOG_TAG, "Pruned: " + prunedRecord);
730             }
731         }
732     }
733
734     /**
735      * Loads the activities.
736      */
737     private void loadActivitiesLocked() {
738         mActivites.clear();
739         if (mIntent != null) {
740             List<ResolveInfo> resolveInfos =
741                 mContext.getPackageManager().queryIntentActivities(mIntent, 0);
742             final int resolveInfoCount = resolveInfos.size();
743             for (int i = 0; i < resolveInfoCount; i++) {
744                 ResolveInfo resolveInfo = resolveInfos.get(i);
745                 mActivites.add(new ActivityResolveInfo(resolveInfo));
746             }
747             sortActivities();
748         } else {
749             notifyChanged();
750         }
751     }
752
753     /**
754      * Represents a record in the history.
755      */
756     public final static class HistoricalRecord {
757
758         /**
759          * The activity name.
760          */
761         public final ComponentName activity;
762
763         /**
764          * The choice time.
765          */
766         public final long time;
767
768         /**
769          * The record weight.
770          */
771         public final float weight;
772
773         /**
774          * Creates a new instance.
775          *
776          * @param activityName The activity component name flattened to string.
777          * @param time The time the activity was chosen.
778          * @param weight The weight of the record.
779          */
780         public HistoricalRecord(String activityName, long time, float weight) {
781             this(ComponentName.unflattenFromString(activityName), time, weight);
782         }
783
784         /**
785          * Creates a new instance.
786          *
787          * @param activityName The activity name.
788          * @param time The time the activity was chosen.
789          * @param weight The weight of the record.
790          */
791         public HistoricalRecord(ComponentName activityName, long time, float weight) {
792             this.activity = activityName;
793             this.time = time;
794             this.weight = weight;
795         }
796
797         @Override
798         public int hashCode() {
799             final int prime = 31;
800             int result = 1;
801             result = prime * result + ((activity == null) ? 0 : activity.hashCode());
802             result = prime * result + (int) (time ^ (time >>> 32));
803             result = prime * result + Float.floatToIntBits(weight);
804             return result;
805         }
806
807         @Override
808         public boolean equals(Object obj) {
809             if (this == obj) {
810                 return true;
811             }
812             if (obj == null) {
813                 return false;
814             }
815             if (getClass() != obj.getClass()) {
816                 return false;
817             }
818             HistoricalRecord other = (HistoricalRecord) obj;
819             if (activity == null) {
820                 if (other.activity != null) {
821                     return false;
822                 }
823             } else if (!activity.equals(other.activity)) {
824                 return false;
825             }
826             if (time != other.time) {
827                 return false;
828             }
829             if (Float.floatToIntBits(weight) != Float.floatToIntBits(other.weight)) {
830                 return false;
831             }
832             return true;
833         }
834
835         @Override
836         public String toString() {
837             StringBuilder builder = new StringBuilder();
838             builder.append("[");
839             builder.append("; activity:").append(activity);
840             builder.append("; time:").append(time);
841             builder.append("; weight:").append(new BigDecimal(weight));
842             builder.append("]");
843             return builder.toString();
844         }
845     }
846
847     /**
848      * Represents an activity.
849      */
850     public final class ActivityResolveInfo implements Comparable<ActivityResolveInfo> {
851
852         /**
853          * The {@link ResolveInfo} of the activity.
854          */
855         public final ResolveInfo resolveInfo;
856
857         /**
858          * Weight of the activity. Useful for sorting.
859          */
860         public float weight;
861
862         /**
863          * Creates a new instance.
864          *
865          * @param resolveInfo activity {@link ResolveInfo}.
866          */
867         public ActivityResolveInfo(ResolveInfo resolveInfo) {
868             this.resolveInfo = resolveInfo;
869         }
870
871         @Override
872         public int hashCode() {
873             return 31 + Float.floatToIntBits(weight);
874         }
875
876         @Override
877         public boolean equals(Object obj) {
878             if (this == obj) {
879                 return true;
880             }
881             if (obj == null) {
882                 return false;
883             }
884             if (getClass() != obj.getClass()) {
885                 return false;
886             }
887             ActivityResolveInfo other = (ActivityResolveInfo) obj;
888             if (Float.floatToIntBits(weight) != Float.floatToIntBits(other.weight)) {
889                 return false;
890             }
891             return true;
892         }
893
894         public int compareTo(ActivityResolveInfo another) {
895              return  Float.floatToIntBits(another.weight) - Float.floatToIntBits(weight);
896         }
897
898         @Override
899         public String toString() {
900             StringBuilder builder = new StringBuilder();
901             builder.append("[");
902             builder.append("resolveInfo:").append(resolveInfo.toString());
903             builder.append("; weight:").append(new BigDecimal(weight));
904             builder.append("]");
905             return builder.toString();
906         }
907     }
908
909     /**
910      * Default activity sorter implementation.
911      */
912     private final class DefaultSorter implements ActivitySorter {
913         private static final float WEIGHT_DECAY_COEFFICIENT = 0.95f;
914
915         private final Map<String, ActivityResolveInfo> mPackageNameToActivityMap =
916             new HashMap<String, ActivityResolveInfo>();
917
918         public void sort(Intent intent, List<ActivityResolveInfo> activities,
919                 List<HistoricalRecord> historicalRecords) {
920             Map<String, ActivityResolveInfo> packageNameToActivityMap =
921                 mPackageNameToActivityMap;
922             packageNameToActivityMap.clear();
923
924             final int activityCount = activities.size();
925             for (int i = 0; i < activityCount; i++) {
926                 ActivityResolveInfo activity = activities.get(i);
927                 activity.weight = 0.0f;
928                 String packageName = activity.resolveInfo.activityInfo.packageName;
929                 packageNameToActivityMap.put(packageName, activity);
930             }
931
932             final int lastShareIndex = historicalRecords.size() - 1;
933             float nextRecordWeight = 1;
934             for (int i = lastShareIndex; i >= 0; i--) {
935                 HistoricalRecord historicalRecord = historicalRecords.get(i);
936                 String packageName = historicalRecord.activity.getPackageName();
937                 ActivityResolveInfo activity = packageNameToActivityMap.get(packageName);
938                 if (activity != null) {
939                     activity.weight += historicalRecord.weight * nextRecordWeight;
940                     nextRecordWeight = nextRecordWeight * WEIGHT_DECAY_COEFFICIENT;
941                 }
942             }
943
944             Collections.sort(activities);
945
946             if (DEBUG) {
947                 for (int i = 0; i < activityCount; i++) {
948                     Log.i(LOG_TAG, "Sorted: " + activities.get(i));
949                 }
950             }
951         }
952     }
953
954     /**
955      * Command for reading the historical records from a file off the UI thread.
956      */
957     private final class HistoryLoader implements Runnable {
958
959        public void run() {
960             FileInputStream fis = null;
961             try {
962                 fis = mContext.openFileInput(mHistoryFileName);
963             } catch (FileNotFoundException fnfe) {
964                 if (DEBUG) {
965                     Log.i(LOG_TAG, "Could not open historical records file: " + mHistoryFileName);
966                 }
967                 return;
968             }
969             try {
970                 XmlPullParser parser = Xml.newPullParser();
971                 parser.setInput(fis, null);
972
973                 int type = XmlPullParser.START_DOCUMENT;
974                 while (type != XmlPullParser.END_DOCUMENT && type != XmlPullParser.START_TAG) {
975                     type = parser.next();
976                 }
977
978                 if (!TAG_HISTORICAL_RECORDS.equals(parser.getName())) {
979                     throw new XmlPullParserException("Share records file does not start with "
980                             + TAG_HISTORICAL_RECORDS + " tag.");
981                 }
982
983                 List<HistoricalRecord> readRecords = new ArrayList<HistoricalRecord>();
984
985                 while (true) {
986                     type = parser.next();
987                     if (type == XmlPullParser.END_DOCUMENT) {
988                         break;
989                     }
990                     if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
991                         continue;
992                     }
993                     String nodeName = parser.getName();
994                     if (!TAG_HISTORICAL_RECORD.equals(nodeName)) {
995                         throw new XmlPullParserException("Share records file not well-formed.");
996                     }
997
998                     String activity = parser.getAttributeValue(null, ATTRIBUTE_ACTIVITY);
999                     final long time =
1000                         Long.parseLong(parser.getAttributeValue(null, ATTRIBUTE_TIME));
1001                     final float weight =
1002                         Float.parseFloat(parser.getAttributeValue(null, ATTRIBUTE_WEIGHT));
1003
1004                     HistoricalRecord readRecord = new HistoricalRecord(activity, time,
1005                             weight);
1006                     readRecords.add(readRecord);
1007
1008                     if (DEBUG) {
1009                         Log.i(LOG_TAG, "Read " + readRecord.toString());
1010                     }
1011                 }
1012
1013                 if (DEBUG) {
1014                     Log.i(LOG_TAG, "Read " + readRecords.size() + " historical records.");
1015                 }
1016
1017                 synchronized (mInstanceLock) {
1018                     Set<HistoricalRecord> uniqueShareRecords =
1019                         new LinkedHashSet<HistoricalRecord>(readRecords);
1020
1021                     // Make sure no duplicates. Example: Read a file with
1022                     // one record, add one record, persist the two records,
1023                     // add a record, read the persisted records - the
1024                     // read two records should not be added again.
1025                     List<HistoricalRecord> historicalRecords = mHistoricalRecords;
1026                     final int historicalRecordsCount = historicalRecords.size();
1027                     for (int i = historicalRecordsCount - 1; i >= 0; i--) {
1028                         HistoricalRecord historicalRecord = historicalRecords.get(i);
1029                         uniqueShareRecords.add(historicalRecord);
1030                     }
1031
1032                     if (historicalRecords.size() == uniqueShareRecords.size()) {
1033                         return;
1034                     }
1035
1036                     // Make sure the oldest records go to the end.
1037                     historicalRecords.clear();
1038                     historicalRecords.addAll(uniqueShareRecords);
1039
1040                     mHistoricalRecordsChanged = true;
1041
1042                     // Do this on the client thread since the client may be on the UI
1043                     // thread, wait for data changes which happen during sorting, and
1044                     // perform UI modification based on the data change.
1045                     mHandler.post(new Runnable() {
1046                         public void run() {
1047                             pruneExcessiveHistoricalRecordsLocked();
1048                             sortActivities();
1049                         }
1050                     });
1051                 }
1052             } catch (XmlPullParserException xppe) {
1053                 Log.e(LOG_TAG, "Error reading historical recrod file: " + mHistoryFileName, xppe);
1054             } catch (IOException ioe) {
1055                 Log.e(LOG_TAG, "Error reading historical recrod file: " + mHistoryFileName, ioe);
1056             } finally {
1057                 if (fis != null) {
1058                     try {
1059                         fis.close();
1060                     } catch (IOException ioe) {
1061                         /* ignore */
1062                     }
1063                 }
1064             }
1065         }
1066     }
1067
1068     /**
1069      * Command for persisting the historical records to a file off the UI thread.
1070      */
1071     private final class HistoryPersister implements Runnable {
1072
1073         public void run() {
1074             FileOutputStream fos = null;
1075             List<HistoricalRecord> records = null;
1076
1077             synchronized (mInstanceLock) {
1078                 records = new ArrayList<HistoricalRecord>(mHistoricalRecords);
1079             }
1080
1081             try {
1082                 fos = mContext.openFileOutput(mHistoryFileName, Context.MODE_PRIVATE);
1083             } catch (FileNotFoundException fnfe) {
1084                 Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, fnfe);
1085                 return;
1086             }
1087
1088             XmlSerializer serializer = Xml.newSerializer();
1089
1090             try {
1091                 serializer.setOutput(fos, null);
1092                 serializer.startDocument("UTF-8", true);
1093                 serializer.startTag(null, TAG_HISTORICAL_RECORDS);
1094
1095                 final int recordCount = records.size();
1096                 for (int i = 0; i < recordCount; i++) {
1097                     HistoricalRecord record = records.remove(0);
1098                     serializer.startTag(null, TAG_HISTORICAL_RECORD);
1099                     serializer.attribute(null, ATTRIBUTE_ACTIVITY, record.activity.flattenToString());
1100                     serializer.attribute(null, ATTRIBUTE_TIME, String.valueOf(record.time));
1101                     serializer.attribute(null, ATTRIBUTE_WEIGHT, String.valueOf(record.weight));
1102                     serializer.endTag(null, TAG_HISTORICAL_RECORD);
1103                     if (DEBUG) {
1104                         Log.i(LOG_TAG, "Wrote " + record.toString());
1105                     }
1106                 }
1107
1108                 serializer.endTag(null, TAG_HISTORICAL_RECORDS);
1109                 serializer.endDocument();
1110
1111                 if (DEBUG) {
1112                     Log.i(LOG_TAG, "Wrote " + recordCount + " historical records.");
1113                 }
1114             } catch (IllegalArgumentException iae) {
1115                 Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, iae);
1116             } catch (IllegalStateException ise) {
1117                 Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, ise);
1118             } catch (IOException ioe) {
1119                 Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, ioe);
1120             } finally {
1121                 if (fos != null) {
1122                     try {
1123                         fos.close();
1124                     } catch (IOException e) {
1125                         /* ignore */
1126                     }
1127                 }
1128             }
1129         }
1130     }
1131 }