michael@0: /* michael@0: * Copyright (C) 2011 The Android Open Source Project michael@0: * michael@0: * Licensed under the Apache License, Version 2.0 (the "License"); michael@0: * you may not use this file except in compliance with the License. michael@0: * You may obtain a copy of the License at michael@0: * michael@0: * http://www.apache.org/licenses/LICENSE-2.0 michael@0: * michael@0: * Unless required by applicable law or agreed to in writing, software michael@0: * distributed under the License is distributed on an "AS IS" BASIS, michael@0: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. michael@0: * See the License for the specific language governing permissions and michael@0: * limitations under the License. michael@0: */ michael@0: michael@0: /** michael@0: * Mozilla: Changing the package. michael@0: */ michael@0: //package android.widget; michael@0: package org.mozilla.gecko.widget; michael@0: michael@0: // Mozilla: New import michael@0: import org.mozilla.gecko.Distribution; michael@0: import org.mozilla.gecko.GeckoProfile; michael@0: import java.io.File; michael@0: michael@0: import android.content.BroadcastReceiver; michael@0: import android.content.ComponentName; michael@0: import android.content.Context; michael@0: import android.content.Intent; michael@0: import android.content.IntentFilter; michael@0: import android.content.pm.ResolveInfo; michael@0: import android.database.DataSetObservable; michael@0: import android.os.AsyncTask; michael@0: import android.text.TextUtils; michael@0: import android.util.Log; michael@0: import android.util.Xml; michael@0: michael@0: /** michael@0: * Mozilla: Unused import. michael@0: */ michael@0: //import com.android.internal.content.PackageMonitor; michael@0: michael@0: import org.xmlpull.v1.XmlPullParser; michael@0: import org.xmlpull.v1.XmlPullParserException; michael@0: import org.xmlpull.v1.XmlSerializer; michael@0: michael@0: import java.io.FileInputStream; michael@0: import java.io.FileNotFoundException; michael@0: import java.io.FileOutputStream; michael@0: import java.io.IOException; michael@0: import java.math.BigDecimal; michael@0: import java.util.ArrayList; michael@0: import java.util.Collections; michael@0: import java.util.HashMap; michael@0: import java.util.Iterator; michael@0: import java.util.List; michael@0: import java.util.Map; michael@0: michael@0: /** michael@0: *
michael@0: * This class represents a data model for choosing a component for handing a michael@0: * given {@link Intent}. The model is responsible for querying the system for michael@0: * activities that can handle the given intent and order found activities michael@0: * based on historical data of previous choices. The historical data is stored michael@0: * in an application private file. If a client does not want to have persistent michael@0: * choice history the file can be omitted, thus the activities will be ordered michael@0: * based on historical usage for the current session. michael@0: *
michael@0: *
michael@0: * For each backing history file there is a singleton instance of this class. Thus, michael@0: * several clients that specify the same history file will share the same model. Note michael@0: * that if multiple clients are sharing the same model they should implement semantically michael@0: * equivalent functionality since setting the model intent will change the found michael@0: * activities and they may be inconsistent with the functionality of some of the clients. michael@0: * For example, choosing a share activity can be implemented by a single backing michael@0: * model and two different views for performing the selection. If however, one of the michael@0: * views is used for sharing but the other for importing, for example, then each michael@0: * view should be backed by a separate model. michael@0: * michael@0: *michael@0: * The way clients interact with this class is as follows: michael@0: *
michael@0: *michael@0: *
michael@0: *
michael@0: * // Get a model and set it to a couple of clients with semantically similar function.
michael@0: * ActivityChooserModel dataModel =
michael@0: * ActivityChooserModel.get(context, "task_specific_history_file_name.xml");
michael@0: *
michael@0: * ActivityChooserModelClient modelClient1 = getActivityChooserModelClient1();
michael@0: * modelClient1.setActivityChooserModel(dataModel);
michael@0: *
michael@0: * ActivityChooserModelClient modelClient2 = getActivityChooserModelClient2();
michael@0: * modelClient2.setActivityChooserModel(dataModel);
michael@0: *
michael@0: * // Set an intent to choose a an activity for.
michael@0: * dataModel.setIntent(intent);
michael@0: *
michael@0: *
michael@0: *
michael@0: *
michael@0: * Note: This class is thread safe.
michael@0: *
michael@0: *
michael@0: * @hide
michael@0: */
michael@0: public class ActivityChooserModel extends DataSetObservable {
michael@0:
michael@0: /**
michael@0: * Client that utilizes an {@link ActivityChooserModel}.
michael@0: */
michael@0: public interface ActivityChooserModelClient {
michael@0:
michael@0: /**
michael@0: * Sets the {@link ActivityChooserModel}.
michael@0: *
michael@0: * @param dataModel The model.
michael@0: */
michael@0: public void setActivityChooserModel(ActivityChooserModel dataModel);
michael@0: }
michael@0:
michael@0: /**
michael@0: * Defines a sorter that is responsible for sorting the activities
michael@0: * based on the provided historical choices and an intent.
michael@0: */
michael@0: public interface ActivitySorter {
michael@0:
michael@0: /**
michael@0: * Sorts the activities
in descending order of relevance
michael@0: * based on previous history and an intent.
michael@0: *
michael@0: * @param intent The {@link Intent}.
michael@0: * @param activities Activities to be sorted.
michael@0: * @param historicalRecords Historical records.
michael@0: */
michael@0: // This cannot be done by a simple comparator since an Activity weight
michael@0: // is computed from history. Note that Activity implements Comparable.
michael@0: public void sort(Intent intent, List activities,
michael@0: List historicalRecords);
michael@0: }
michael@0:
michael@0: /**
michael@0: * Listener for choosing an activity.
michael@0: */
michael@0: public interface OnChooseActivityListener {
michael@0:
michael@0: /**
michael@0: * Called when an activity has been chosen. The client can decide whether
michael@0: * an activity can be chosen and if so the caller of
michael@0: * {@link ActivityChooserModel#chooseActivity(int)} will receive and {@link Intent}
michael@0: * for launching it.
michael@0: *
michael@0: * Note: Modifying the intent is not permitted and
michael@0: * any changes to the latter will be ignored.
michael@0: *
michael@0: *
michael@0: * @param host The listener's host model.
michael@0: * @param intent The intent for launching the chosen activity.
michael@0: * @return Whether the intent is handled and should not be delivered to clients.
michael@0: *
michael@0: * @see ActivityChooserModel#chooseActivity(int)
michael@0: */
michael@0: public boolean onChooseActivity(ActivityChooserModel host, Intent intent);
michael@0: }
michael@0:
michael@0: /**
michael@0: * Flag for selecting debug mode.
michael@0: */
michael@0: private static final boolean DEBUG = false;
michael@0:
michael@0: /**
michael@0: * Tag used for logging.
michael@0: */
michael@0: private static final String LOG_TAG = ActivityChooserModel.class.getSimpleName();
michael@0:
michael@0: /**
michael@0: * The root tag in the history file.
michael@0: */
michael@0: private static final String TAG_HISTORICAL_RECORDS = "historical-records";
michael@0:
michael@0: /**
michael@0: * The tag for a record in the history file.
michael@0: */
michael@0: private static final String TAG_HISTORICAL_RECORD = "historical-record";
michael@0:
michael@0: /**
michael@0: * Attribute for the activity.
michael@0: */
michael@0: private static final String ATTRIBUTE_ACTIVITY = "activity";
michael@0:
michael@0: /**
michael@0: * Attribute for the choice time.
michael@0: */
michael@0: private static final String ATTRIBUTE_TIME = "time";
michael@0:
michael@0: /**
michael@0: * Attribute for the choice weight.
michael@0: */
michael@0: private static final String ATTRIBUTE_WEIGHT = "weight";
michael@0:
michael@0: /**
michael@0: * The default name of the choice history file.
michael@0: */
michael@0: public static final String DEFAULT_HISTORY_FILE_NAME =
michael@0: "activity_choser_model_history.xml";
michael@0:
michael@0: /**
michael@0: * The default maximal length of the choice history.
michael@0: */
michael@0: public static final int DEFAULT_HISTORY_MAX_LENGTH = 50;
michael@0:
michael@0: /**
michael@0: * The amount with which to inflate a chosen activity when set as default.
michael@0: */
michael@0: private static final int DEFAULT_ACTIVITY_INFLATION = 5;
michael@0:
michael@0: /**
michael@0: * Default weight for a choice record.
michael@0: */
michael@0: private static final float DEFAULT_HISTORICAL_RECORD_WEIGHT = 1.0f;
michael@0:
michael@0: /**
michael@0: * The extension of the history file.
michael@0: */
michael@0: private static final String HISTORY_FILE_EXTENSION = ".xml";
michael@0:
michael@0: /**
michael@0: * An invalid item index.
michael@0: */
michael@0: private static final int INVALID_INDEX = -1;
michael@0:
michael@0: /**
michael@0: * Lock to guard the model registry.
michael@0: */
michael@0: private static final Object sRegistryLock = new Object();
michael@0:
michael@0: /**
michael@0: * This the registry for data models.
michael@0: */
michael@0: private static final Map sDataModelRegistry =
michael@0: new HashMap();
michael@0:
michael@0: /**
michael@0: * Lock for synchronizing on this instance.
michael@0: */
michael@0: private final Object mInstanceLock = new Object();
michael@0:
michael@0: /**
michael@0: * List of activities that can handle the current intent.
michael@0: */
michael@0: private final List mActivities = new ArrayList();
michael@0:
michael@0: /**
michael@0: * List with historical choice records.
michael@0: */
michael@0: private final List mHistoricalRecords = new ArrayList();
michael@0:
michael@0: /**
michael@0: * Monitor for added and removed packages.
michael@0: */
michael@0: /**
michael@0: * Mozilla: Converted from a PackageMonitor to a DataModelPackageMonitor to avoid importing a new class.
michael@0: */
michael@0: private final DataModelPackageMonitor mPackageMonitor = new DataModelPackageMonitor();
michael@0:
michael@0: /**
michael@0: * Context for accessing resources.
michael@0: */
michael@0: private final Context mContext;
michael@0:
michael@0: /**
michael@0: * The name of the history file that backs this model.
michael@0: */
michael@0: private final String mHistoryFileName;
michael@0:
michael@0: /**
michael@0: * The intent for which a activity is being chosen.
michael@0: */
michael@0: private Intent mIntent;
michael@0:
michael@0: /**
michael@0: * The sorter for ordering activities based on intent and past choices.
michael@0: */
michael@0: private ActivitySorter mActivitySorter = new DefaultSorter();
michael@0:
michael@0: /**
michael@0: * The maximal length of the choice history.
michael@0: */
michael@0: private int mHistoryMaxSize = DEFAULT_HISTORY_MAX_LENGTH;
michael@0:
michael@0: /**
michael@0: * Flag whether choice history can be read. In general many clients can
michael@0: * share the same data model and {@link #readHistoricalDataIfNeeded()} may be called
michael@0: * by arbitrary of them any number of times. Therefore, this class guarantees
michael@0: * that the very first read succeeds and subsequent reads can be performed
michael@0: * only after a call to {@link #persistHistoricalDataIfNeeded()} followed by change
michael@0: * of the share records.
michael@0: */
michael@0: private boolean mCanReadHistoricalData = true;
michael@0:
michael@0: /**
michael@0: * Flag whether the choice history was read. This is used to enforce that
michael@0: * before calling {@link #persistHistoricalDataIfNeeded()} a call to
michael@0: * {@link #persistHistoricalDataIfNeeded()} has been made. This aims to avoid a
michael@0: * scenario in which a choice history file exits, it is not read yet and
michael@0: * it is overwritten. Note that always all historical records are read in
michael@0: * full and the file is rewritten. This is necessary since we need to
michael@0: * purge old records that are outside of the sliding window of past choices.
michael@0: */
michael@0: private boolean mReadShareHistoryCalled = false;
michael@0:
michael@0: /**
michael@0: * Flag whether the choice records have changed. In general many clients can
michael@0: * share the same data model and {@link #persistHistoricalDataIfNeeded()} may be called
michael@0: * by arbitrary of them any number of times. Therefore, this class guarantees
michael@0: * that choice history will be persisted only if it has changed.
michael@0: */
michael@0: private boolean mHistoricalRecordsChanged = true;
michael@0:
michael@0: /**
michael@0: * Flag whether to reload the activities for the current intent.
michael@0: */
michael@0: private boolean mReloadActivities = false;
michael@0:
michael@0: /**
michael@0: * Policy for controlling how the model handles chosen activities.
michael@0: */
michael@0: private OnChooseActivityListener mActivityChoserModelPolicy;
michael@0:
michael@0: /**
michael@0: * Gets the data model backed by the contents of the provided file with historical data.
michael@0: * Note that only one data model is backed by a given file, thus multiple calls with
michael@0: * the same file name will return the same model instance. If no such instance is present
michael@0: * it is created.
michael@0: *
michael@0: * Note: To use the default historical data file clients should explicitly
michael@0: * pass as file name {@link #DEFAULT_HISTORY_FILE_NAME}. If no persistence of the choice
michael@0: * history is desired clients should pass null
for the file name. In such
michael@0: * case a new model is returned for each invocation.
michael@0: *
michael@0: *
michael@0: *
michael@0: * Always use difference historical data files for semantically different actions.
michael@0: * For example, sharing is different from importing.
michael@0: *
michael@0: *
michael@0: * @param context Context for loading resources.
michael@0: * @param historyFileName File name with choice history, null
michael@0: * if the model should not be backed by a file. In this case the activities
michael@0: * will be ordered only by data from the current session.
michael@0: *
michael@0: * @return The model.
michael@0: */
michael@0: public static ActivityChooserModel get(Context context, String historyFileName) {
michael@0: synchronized (sRegistryLock) {
michael@0: ActivityChooserModel dataModel = sDataModelRegistry.get(historyFileName);
michael@0: if (dataModel == null) {
michael@0: dataModel = new ActivityChooserModel(context, historyFileName);
michael@0: sDataModelRegistry.put(historyFileName, dataModel);
michael@0: }
michael@0: return dataModel;
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Creates a new instance.
michael@0: *
michael@0: * @param context Context for loading resources.
michael@0: * @param historyFileName The history XML file.
michael@0: */
michael@0: private ActivityChooserModel(Context context, String historyFileName) {
michael@0: mContext = context.getApplicationContext();
michael@0: if (!TextUtils.isEmpty(historyFileName)
michael@0: && !historyFileName.endsWith(HISTORY_FILE_EXTENSION)) {
michael@0: mHistoryFileName = historyFileName + HISTORY_FILE_EXTENSION;
michael@0: } else {
michael@0: mHistoryFileName = historyFileName;
michael@0: }
michael@0:
michael@0: /**
michael@0: * Mozilla: Uses modified receiver
michael@0: */
michael@0: mPackageMonitor.register(mContext);
michael@0: }
michael@0:
michael@0: /**
michael@0: * Sets an intent for which to choose a activity.
michael@0: *
michael@0: * Note: Clients must set only semantically similar
michael@0: * intents for each data model.
michael@0: *
michael@0: *
michael@0: * @param intent The intent.
michael@0: */
michael@0: public void setIntent(Intent intent) {
michael@0: synchronized (mInstanceLock) {
michael@0: if (mIntent == intent) {
michael@0: return;
michael@0: }
michael@0: mIntent = intent;
michael@0: mReloadActivities = true;
michael@0: ensureConsistentState();
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Gets the intent for which a activity is being chosen.
michael@0: *
michael@0: * @return The intent.
michael@0: */
michael@0: public Intent getIntent() {
michael@0: synchronized (mInstanceLock) {
michael@0: return mIntent;
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Gets the number of activities that can handle the intent.
michael@0: *
michael@0: * @return The activity count.
michael@0: *
michael@0: * @see #setIntent(Intent)
michael@0: */
michael@0: public int getActivityCount() {
michael@0: synchronized (mInstanceLock) {
michael@0: ensureConsistentState();
michael@0: return mActivities.size();
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Gets an activity at a given index.
michael@0: *
michael@0: * @return The activity.
michael@0: *
michael@0: * @see ActivityResolveInfo
michael@0: * @see #setIntent(Intent)
michael@0: */
michael@0: public ResolveInfo getActivity(int index) {
michael@0: synchronized (mInstanceLock) {
michael@0: ensureConsistentState();
michael@0: return mActivities.get(index).resolveInfo;
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Gets the index of a the given activity.
michael@0: *
michael@0: * @param activity The activity index.
michael@0: *
michael@0: * @return The index if found, -1 otherwise.
michael@0: */
michael@0: public int getActivityIndex(ResolveInfo activity) {
michael@0: synchronized (mInstanceLock) {
michael@0: ensureConsistentState();
michael@0: List activities = mActivities;
michael@0: final int activityCount = activities.size();
michael@0: for (int i = 0; i < activityCount; i++) {
michael@0: ActivityResolveInfo currentActivity = activities.get(i);
michael@0: if (currentActivity.resolveInfo == activity) {
michael@0: return i;
michael@0: }
michael@0: }
michael@0: return INVALID_INDEX;
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Chooses a activity to handle the current intent. This will result in
michael@0: * adding a historical record for that action and construct intent with
michael@0: * its component name set such that it can be immediately started by the
michael@0: * client.
michael@0: *
michael@0: * Note: By calling this method the client guarantees
michael@0: * that the returned intent will be started. This intent is returned to
michael@0: * the client solely to let additional customization before the start.
michael@0: *
michael@0: *
michael@0: * @return An {@link Intent} for launching the activity or null if the
michael@0: * policy has consumed the intent or there is not current intent
michael@0: * set via {@link #setIntent(Intent)}.
michael@0: *
michael@0: * @see HistoricalRecord
michael@0: * @see OnChooseActivityListener
michael@0: */
michael@0: public Intent chooseActivity(int index) {
michael@0: synchronized (mInstanceLock) {
michael@0: if (mIntent == null) {
michael@0: return null;
michael@0: }
michael@0:
michael@0: ensureConsistentState();
michael@0:
michael@0: ActivityResolveInfo chosenActivity = mActivities.get(index);
michael@0:
michael@0: ComponentName chosenName = new ComponentName(
michael@0: chosenActivity.resolveInfo.activityInfo.packageName,
michael@0: chosenActivity.resolveInfo.activityInfo.name);
michael@0:
michael@0: Intent choiceIntent = new Intent(mIntent);
michael@0: choiceIntent.setComponent(chosenName);
michael@0:
michael@0: if (mActivityChoserModelPolicy != null) {
michael@0: // Do not allow the policy to change the intent.
michael@0: Intent choiceIntentCopy = new Intent(choiceIntent);
michael@0: final boolean handled = mActivityChoserModelPolicy.onChooseActivity(this,
michael@0: choiceIntentCopy);
michael@0: if (handled) {
michael@0: return null;
michael@0: }
michael@0: }
michael@0:
michael@0: HistoricalRecord historicalRecord = new HistoricalRecord(chosenName,
michael@0: System.currentTimeMillis(), DEFAULT_HISTORICAL_RECORD_WEIGHT);
michael@0: addHistoricalRecord(historicalRecord);
michael@0:
michael@0: return choiceIntent;
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Sets the listener for choosing an activity.
michael@0: *
michael@0: * @param listener The listener.
michael@0: */
michael@0: public void setOnChooseActivityListener(OnChooseActivityListener listener) {
michael@0: synchronized (mInstanceLock) {
michael@0: mActivityChoserModelPolicy = listener;
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Gets the default activity, The default activity is defined as the one
michael@0: * with highest rank i.e. the first one in the list of activities that can
michael@0: * handle the intent.
michael@0: *
michael@0: * @return The default activity, null
id not activities.
michael@0: *
michael@0: * @see #getActivity(int)
michael@0: */
michael@0: public ResolveInfo getDefaultActivity() {
michael@0: synchronized (mInstanceLock) {
michael@0: ensureConsistentState();
michael@0: if (!mActivities.isEmpty()) {
michael@0: return mActivities.get(0).resolveInfo;
michael@0: }
michael@0: }
michael@0: return null;
michael@0: }
michael@0:
michael@0: /**
michael@0: * Sets the default activity. The default activity is set by adding a
michael@0: * historical record with weight high enough that this activity will
michael@0: * become the highest ranked. Such a strategy guarantees that the default
michael@0: * will eventually change if not used. Also the weight of the record for
michael@0: * setting a default is inflated with a constant amount to guarantee that
michael@0: * it will stay as default for awhile.
michael@0: *
michael@0: * @param index The index of the activity to set as default.
michael@0: */
michael@0: public void setDefaultActivity(int index) {
michael@0: synchronized (mInstanceLock) {
michael@0: ensureConsistentState();
michael@0:
michael@0: ActivityResolveInfo newDefaultActivity = mActivities.get(index);
michael@0: ActivityResolveInfo oldDefaultActivity = mActivities.get(0);
michael@0:
michael@0: final float weight;
michael@0: if (oldDefaultActivity != null) {
michael@0: // Add a record with weight enough to boost the chosen at the top.
michael@0: weight = oldDefaultActivity.weight - newDefaultActivity.weight
michael@0: + DEFAULT_ACTIVITY_INFLATION;
michael@0: } else {
michael@0: weight = DEFAULT_HISTORICAL_RECORD_WEIGHT;
michael@0: }
michael@0:
michael@0: ComponentName defaultName = new ComponentName(
michael@0: newDefaultActivity.resolveInfo.activityInfo.packageName,
michael@0: newDefaultActivity.resolveInfo.activityInfo.name);
michael@0: HistoricalRecord historicalRecord = new HistoricalRecord(defaultName,
michael@0: System.currentTimeMillis(), weight);
michael@0: addHistoricalRecord(historicalRecord);
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Persists the history data to the backing file if the latter
michael@0: * was provided. Calling this method before a call to {@link #readHistoricalDataIfNeeded()}
michael@0: * throws an exception. Calling this method more than one without choosing an
michael@0: * activity has not effect.
michael@0: *
michael@0: * @throws IllegalStateException If this method is called before a call to
michael@0: * {@link #readHistoricalDataIfNeeded()}.
michael@0: */
michael@0: private void persistHistoricalDataIfNeeded() {
michael@0: if (!mReadShareHistoryCalled) {
michael@0: throw new IllegalStateException("No preceding call to #readHistoricalData");
michael@0: }
michael@0: if (!mHistoricalRecordsChanged) {
michael@0: return;
michael@0: }
michael@0: mHistoricalRecordsChanged = false;
michael@0: if (!TextUtils.isEmpty(mHistoryFileName)) {
michael@0: /**
michael@0: * Mozilla: Converted to a normal task.execute call so that this works on < ICS phones.
michael@0: */
michael@0: new PersistHistoryAsyncTask().execute(new ArrayList(mHistoricalRecords), mHistoryFileName);
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Sets the sorter for ordering activities based on historical data and an intent.
michael@0: *
michael@0: * @param activitySorter The sorter.
michael@0: *
michael@0: * @see ActivitySorter
michael@0: */
michael@0: public void setActivitySorter(ActivitySorter activitySorter) {
michael@0: synchronized (mInstanceLock) {
michael@0: if (mActivitySorter == activitySorter) {
michael@0: return;
michael@0: }
michael@0: mActivitySorter = activitySorter;
michael@0: if (sortActivitiesIfNeeded()) {
michael@0: notifyChanged();
michael@0: }
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Sets the maximal size of the historical data. Defaults to
michael@0: * {@link #DEFAULT_HISTORY_MAX_LENGTH}
michael@0: *
michael@0: * Note: Setting this property will immediately
michael@0: * enforce the specified max history size by dropping enough old
michael@0: * historical records to enforce the desired size. Thus, any
michael@0: * records that exceed the history size will be discarded and
michael@0: * irreversibly lost.
michael@0: *
michael@0: *
michael@0: * @param historyMaxSize The max history size.
michael@0: */
michael@0: public void setHistoryMaxSize(int historyMaxSize) {
michael@0: synchronized (mInstanceLock) {
michael@0: if (mHistoryMaxSize == historyMaxSize) {
michael@0: return;
michael@0: }
michael@0: mHistoryMaxSize = historyMaxSize;
michael@0: pruneExcessiveHistoricalRecordsIfNeeded();
michael@0: if (sortActivitiesIfNeeded()) {
michael@0: notifyChanged();
michael@0: }
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Gets the history max size.
michael@0: *
michael@0: * @return The history max size.
michael@0: */
michael@0: public int getHistoryMaxSize() {
michael@0: synchronized (mInstanceLock) {
michael@0: return mHistoryMaxSize;
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Gets the history size.
michael@0: *
michael@0: * @return The history size.
michael@0: */
michael@0: public int getHistorySize() {
michael@0: synchronized (mInstanceLock) {
michael@0: ensureConsistentState();
michael@0: return mHistoricalRecords.size();
michael@0: }
michael@0: }
michael@0:
michael@0: public int getDistinctActivityCountInHistory() {
michael@0: synchronized (mInstanceLock) {
michael@0: ensureConsistentState();
michael@0: final List packages = new ArrayList();
michael@0: for (HistoricalRecord record : mHistoricalRecords) {
michael@0: String activity = record.activity.flattenToString();
michael@0: if (!packages.contains(activity)) {
michael@0: packages.add(activity);
michael@0: }
michael@0: }
michael@0: return packages.size();
michael@0: }
michael@0: }
michael@0:
michael@0: @Override
michael@0: protected void finalize() throws Throwable {
michael@0: super.finalize();
michael@0:
michael@0: /**
michael@0: * Mozilla: Not needed for the application.
michael@0: */
michael@0: mPackageMonitor.unregister();
michael@0: }
michael@0:
michael@0: /**
michael@0: * Ensures the model is in a consistent state which is the
michael@0: * activities for the current intent have been loaded, the
michael@0: * most recent history has been read, and the activities
michael@0: * are sorted.
michael@0: */
michael@0: private void ensureConsistentState() {
michael@0: boolean stateChanged = loadActivitiesIfNeeded();
michael@0: stateChanged |= readHistoricalDataIfNeeded();
michael@0: pruneExcessiveHistoricalRecordsIfNeeded();
michael@0: if (stateChanged) {
michael@0: sortActivitiesIfNeeded();
michael@0: notifyChanged();
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Sorts the activities if necessary which is if there is a
michael@0: * sorter, there are some activities to sort, and there is some
michael@0: * historical data.
michael@0: *
michael@0: * @return Whether sorting was performed.
michael@0: */
michael@0: private boolean sortActivitiesIfNeeded() {
michael@0: if (mActivitySorter != null && mIntent != null
michael@0: && !mActivities.isEmpty() && !mHistoricalRecords.isEmpty()) {
michael@0: mActivitySorter.sort(mIntent, mActivities,
michael@0: Collections.unmodifiableList(mHistoricalRecords));
michael@0: return true;
michael@0: }
michael@0: return false;
michael@0: }
michael@0:
michael@0: /**
michael@0: * Loads the activities for the current intent if needed which is
michael@0: * if they are not already loaded for the current intent.
michael@0: *
michael@0: * @return Whether loading was performed.
michael@0: */
michael@0: private boolean loadActivitiesIfNeeded() {
michael@0: if (mReloadActivities && mIntent != null) {
michael@0: mReloadActivities = false;
michael@0: mActivities.clear();
michael@0: List resolveInfos = mContext.getPackageManager()
michael@0: .queryIntentActivities(mIntent, 0);
michael@0: final int resolveInfoCount = resolveInfos.size();
michael@0: for (int i = 0; i < resolveInfoCount; i++) {
michael@0: ResolveInfo resolveInfo = resolveInfos.get(i);
michael@0: mActivities.add(new ActivityResolveInfo(resolveInfo));
michael@0: }
michael@0: return true;
michael@0: }
michael@0: return false;
michael@0: }
michael@0:
michael@0: /**
michael@0: * Reads the historical data if necessary which is it has
michael@0: * changed, there is a history file, and there is not persist
michael@0: * in progress.
michael@0: *
michael@0: * @return Whether reading was performed.
michael@0: */
michael@0: private boolean readHistoricalDataIfNeeded() {
michael@0: if (mCanReadHistoricalData && mHistoricalRecordsChanged &&
michael@0: !TextUtils.isEmpty(mHistoryFileName)) {
michael@0: mCanReadHistoricalData = false;
michael@0: mReadShareHistoryCalled = true;
michael@0: readHistoricalDataImpl();
michael@0: return true;
michael@0: }
michael@0: return false;
michael@0: }
michael@0:
michael@0: /**
michael@0: * Adds a historical record.
michael@0: *
michael@0: * @param historicalRecord The record to add.
michael@0: * @return True if the record was added.
michael@0: */
michael@0: private boolean addHistoricalRecord(HistoricalRecord historicalRecord) {
michael@0: final boolean added = mHistoricalRecords.add(historicalRecord);
michael@0: if (added) {
michael@0: mHistoricalRecordsChanged = true;
michael@0: pruneExcessiveHistoricalRecordsIfNeeded();
michael@0: persistHistoricalDataIfNeeded();
michael@0: sortActivitiesIfNeeded();
michael@0: notifyChanged();
michael@0: }
michael@0: return added;
michael@0: }
michael@0:
michael@0: /**
michael@0: * Removes all historical records for this pkg.
michael@0: *
michael@0: * @param historicalRecord The pkg to delete records for.
michael@0: * @return True if the record was added.
michael@0: */
michael@0: private boolean removeHistoricalRecordsForPackage(final String pkg) {
michael@0: boolean removed = false;
michael@0:
michael@0: for (Iterator i = mHistoricalRecords.iterator(); i.hasNext();) {
michael@0: final HistoricalRecord record = i.next();
michael@0: if (record.activity.getPackageName().equals(pkg)) {
michael@0: i.remove();
michael@0: removed = true;
michael@0: }
michael@0: }
michael@0:
michael@0: if (removed) {
michael@0: mHistoricalRecordsChanged = true;
michael@0: pruneExcessiveHistoricalRecordsIfNeeded();
michael@0: persistHistoricalDataIfNeeded();
michael@0: sortActivitiesIfNeeded();
michael@0: notifyChanged();
michael@0: }
michael@0:
michael@0: return removed;
michael@0: }
michael@0:
michael@0: /**
michael@0: * Prunes older excessive records to guarantee maxHistorySize.
michael@0: */
michael@0: private void pruneExcessiveHistoricalRecordsIfNeeded() {
michael@0: final int pruneCount = mHistoricalRecords.size() - mHistoryMaxSize;
michael@0: if (pruneCount <= 0) {
michael@0: return;
michael@0: }
michael@0: mHistoricalRecordsChanged = true;
michael@0: for (int i = 0; i < pruneCount; i++) {
michael@0: HistoricalRecord prunedRecord = mHistoricalRecords.remove(0);
michael@0: if (DEBUG) {
michael@0: Log.i(LOG_TAG, "Pruned: " + prunedRecord);
michael@0: }
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Represents a record in the history.
michael@0: */
michael@0: public final static class HistoricalRecord {
michael@0:
michael@0: /**
michael@0: * The activity name.
michael@0: */
michael@0: public final ComponentName activity;
michael@0:
michael@0: /**
michael@0: * The choice time.
michael@0: */
michael@0: public final long time;
michael@0:
michael@0: /**
michael@0: * The record weight.
michael@0: */
michael@0: public final float weight;
michael@0:
michael@0: /**
michael@0: * Creates a new instance.
michael@0: *
michael@0: * @param activityName The activity component name flattened to string.
michael@0: * @param time The time the activity was chosen.
michael@0: * @param weight The weight of the record.
michael@0: */
michael@0: public HistoricalRecord(String activityName, long time, float weight) {
michael@0: this(ComponentName.unflattenFromString(activityName), time, weight);
michael@0: }
michael@0:
michael@0: /**
michael@0: * Creates a new instance.
michael@0: *
michael@0: * @param activityName The activity name.
michael@0: * @param time The time the activity was chosen.
michael@0: * @param weight The weight of the record.
michael@0: */
michael@0: public HistoricalRecord(ComponentName activityName, long time, float weight) {
michael@0: this.activity = activityName;
michael@0: this.time = time;
michael@0: this.weight = weight;
michael@0: }
michael@0:
michael@0: @Override
michael@0: public int hashCode() {
michael@0: final int prime = 31;
michael@0: int result = 1;
michael@0: result = prime * result + ((activity == null) ? 0 : activity.hashCode());
michael@0: result = prime * result + (int) (time ^ (time >>> 32));
michael@0: result = prime * result + Float.floatToIntBits(weight);
michael@0: return result;
michael@0: }
michael@0:
michael@0: @Override
michael@0: public boolean equals(Object obj) {
michael@0: if (this == obj) {
michael@0: return true;
michael@0: }
michael@0: if (obj == null) {
michael@0: return false;
michael@0: }
michael@0: if (getClass() != obj.getClass()) {
michael@0: return false;
michael@0: }
michael@0: HistoricalRecord other = (HistoricalRecord) obj;
michael@0: if (activity == null) {
michael@0: if (other.activity != null) {
michael@0: return false;
michael@0: }
michael@0: } else if (!activity.equals(other.activity)) {
michael@0: return false;
michael@0: }
michael@0: if (time != other.time) {
michael@0: return false;
michael@0: }
michael@0: if (Float.floatToIntBits(weight) != Float.floatToIntBits(other.weight)) {
michael@0: return false;
michael@0: }
michael@0: return true;
michael@0: }
michael@0:
michael@0: @Override
michael@0: public String toString() {
michael@0: StringBuilder builder = new StringBuilder();
michael@0: builder.append("[");
michael@0: builder.append("; activity:").append(activity);
michael@0: builder.append("; time:").append(time);
michael@0: builder.append("; weight:").append(new BigDecimal(weight));
michael@0: builder.append("]");
michael@0: return builder.toString();
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Represents an activity.
michael@0: */
michael@0: public final class ActivityResolveInfo implements Comparable {
michael@0:
michael@0: /**
michael@0: * The {@link ResolveInfo} of the activity.
michael@0: */
michael@0: public final ResolveInfo resolveInfo;
michael@0:
michael@0: /**
michael@0: * Weight of the activity. Useful for sorting.
michael@0: */
michael@0: public float weight;
michael@0:
michael@0: /**
michael@0: * Creates a new instance.
michael@0: *
michael@0: * @param resolveInfo activity {@link ResolveInfo}.
michael@0: */
michael@0: public ActivityResolveInfo(ResolveInfo resolveInfo) {
michael@0: this.resolveInfo = resolveInfo;
michael@0: }
michael@0:
michael@0: @Override
michael@0: public int hashCode() {
michael@0: return 31 + Float.floatToIntBits(weight);
michael@0: }
michael@0:
michael@0: @Override
michael@0: public boolean equals(Object obj) {
michael@0: if (this == obj) {
michael@0: return true;
michael@0: }
michael@0: if (obj == null) {
michael@0: return false;
michael@0: }
michael@0: if (getClass() != obj.getClass()) {
michael@0: return false;
michael@0: }
michael@0: ActivityResolveInfo other = (ActivityResolveInfo) obj;
michael@0: if (Float.floatToIntBits(weight) != Float.floatToIntBits(other.weight)) {
michael@0: return false;
michael@0: }
michael@0: return true;
michael@0: }
michael@0:
michael@0: public int compareTo(ActivityResolveInfo another) {
michael@0: return Float.floatToIntBits(another.weight) - Float.floatToIntBits(weight);
michael@0: }
michael@0:
michael@0: @Override
michael@0: public String toString() {
michael@0: StringBuilder builder = new StringBuilder();
michael@0: builder.append("[");
michael@0: builder.append("resolveInfo:").append(resolveInfo.toString());
michael@0: builder.append("; weight:").append(new BigDecimal(weight));
michael@0: builder.append("]");
michael@0: return builder.toString();
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Default activity sorter implementation.
michael@0: */
michael@0: private final class DefaultSorter implements ActivitySorter {
michael@0: private static final float WEIGHT_DECAY_COEFFICIENT = 0.95f;
michael@0:
michael@0: private final Map mPackageNameToActivityMap =
michael@0: new HashMap();
michael@0:
michael@0: public void sort(Intent intent, List activities,
michael@0: List historicalRecords) {
michael@0: Map packageNameToActivityMap =
michael@0: mPackageNameToActivityMap;
michael@0: packageNameToActivityMap.clear();
michael@0:
michael@0: final int activityCount = activities.size();
michael@0: for (int i = 0; i < activityCount; i++) {
michael@0: ActivityResolveInfo activity = activities.get(i);
michael@0: activity.weight = 0.0f;
michael@0:
michael@0: // Make sure we're using a non-ambiguous name here
michael@0: ComponentName chosenName = new ComponentName(
michael@0: activity.resolveInfo.activityInfo.packageName,
michael@0: activity.resolveInfo.activityInfo.name);
michael@0: String packageName = chosenName.flattenToString();
michael@0: packageNameToActivityMap.put(packageName, activity);
michael@0: }
michael@0:
michael@0: final int lastShareIndex = historicalRecords.size() - 1;
michael@0: float nextRecordWeight = 1;
michael@0: for (int i = lastShareIndex; i >= 0; i--) {
michael@0: HistoricalRecord historicalRecord = historicalRecords.get(i);
michael@0: String packageName = historicalRecord.activity.flattenToString();
michael@0: ActivityResolveInfo activity = packageNameToActivityMap.get(packageName);
michael@0: if (activity != null) {
michael@0: activity.weight += historicalRecord.weight * nextRecordWeight;
michael@0: nextRecordWeight = nextRecordWeight * WEIGHT_DECAY_COEFFICIENT;
michael@0: }
michael@0: }
michael@0:
michael@0: Collections.sort(activities);
michael@0:
michael@0: if (DEBUG) {
michael@0: for (int i = 0; i < activityCount; i++) {
michael@0: Log.i(LOG_TAG, "Sorted: " + activities.get(i));
michael@0: }
michael@0: }
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Command for reading the historical records from a file off the UI thread.
michael@0: */
michael@0: private void readHistoricalDataImpl() {
michael@0: FileInputStream fis = null;
michael@0: try {
michael@0: GeckoProfile profile = GeckoProfile.get(mContext);
michael@0: File f = profile.getFile(mHistoryFileName);
michael@0: if (!f.exists()) {
michael@0: // Fall back to the non-profile aware file if it exists...
michael@0: File oldFile = new File(mHistoryFileName);
michael@0: oldFile.renameTo(f);
michael@0: }
michael@0: fis = new FileInputStream(f);
michael@0: } catch (FileNotFoundException fnfe) {
michael@0: try {
michael@0: Distribution dist = new Distribution(mContext);
michael@0: File distFile = dist.getDistributionFile("quickshare/" + mHistoryFileName);
michael@0: if (distFile == null) {
michael@0: if (DEBUG) {
michael@0: Log.i(LOG_TAG, "Could not open historical records file: " + mHistoryFileName);
michael@0: }
michael@0: return;
michael@0: }
michael@0: fis = new FileInputStream(distFile);
michael@0: } catch(Exception ex) {
michael@0: if (DEBUG) {
michael@0: Log.i(LOG_TAG, "Could not open historical records file: " + mHistoryFileName);
michael@0: }
michael@0: return;
michael@0: }
michael@0: }
michael@0:
michael@0: try {
michael@0: XmlPullParser parser = Xml.newPullParser();
michael@0: parser.setInput(fis, null);
michael@0:
michael@0: int type = XmlPullParser.START_DOCUMENT;
michael@0: while (type != XmlPullParser.END_DOCUMENT && type != XmlPullParser.START_TAG) {
michael@0: type = parser.next();
michael@0: }
michael@0:
michael@0: if (!TAG_HISTORICAL_RECORDS.equals(parser.getName())) {
michael@0: throw new XmlPullParserException("Share records file does not start with "
michael@0: + TAG_HISTORICAL_RECORDS + " tag.");
michael@0: }
michael@0:
michael@0: List historicalRecords = mHistoricalRecords;
michael@0: historicalRecords.clear();
michael@0:
michael@0: while (true) {
michael@0: type = parser.next();
michael@0: if (type == XmlPullParser.END_DOCUMENT) {
michael@0: break;
michael@0: }
michael@0: if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
michael@0: continue;
michael@0: }
michael@0: String nodeName = parser.getName();
michael@0: if (!TAG_HISTORICAL_RECORD.equals(nodeName)) {
michael@0: throw new XmlPullParserException("Share records file not well-formed.");
michael@0: }
michael@0:
michael@0: String activity = parser.getAttributeValue(null, ATTRIBUTE_ACTIVITY);
michael@0: final long time =
michael@0: Long.parseLong(parser.getAttributeValue(null, ATTRIBUTE_TIME));
michael@0: final float weight =
michael@0: Float.parseFloat(parser.getAttributeValue(null, ATTRIBUTE_WEIGHT));
michael@0: HistoricalRecord readRecord = new HistoricalRecord(activity, time, weight);
michael@0: historicalRecords.add(readRecord);
michael@0:
michael@0: if (DEBUG) {
michael@0: Log.i(LOG_TAG, "Read " + readRecord.toString());
michael@0: }
michael@0: }
michael@0:
michael@0: if (DEBUG) {
michael@0: Log.i(LOG_TAG, "Read " + historicalRecords.size() + " historical records.");
michael@0: }
michael@0: } catch (XmlPullParserException xppe) {
michael@0: Log.e(LOG_TAG, "Error reading historical recrod file: " + mHistoryFileName, xppe);
michael@0: } catch (IOException ioe) {
michael@0: Log.e(LOG_TAG, "Error reading historical recrod file: " + mHistoryFileName, ioe);
michael@0: } finally {
michael@0: if (fis != null) {
michael@0: try {
michael@0: fis.close();
michael@0: } catch (IOException ioe) {
michael@0: /* ignore */
michael@0: }
michael@0: }
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Command for persisting the historical records to a file off the UI thread.
michael@0: */
michael@0: private final class PersistHistoryAsyncTask extends AsyncTask