1/*
2 * Copyright (C) 2010 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
17package com.android.providers.downloads.ui;
18
19import android.app.DownloadManager;
20import android.content.Context;
21import android.content.Intent;
22import android.content.pm.PackageManager;
23import android.content.pm.ResolveInfo;
24import android.content.res.Resources;
25import android.database.Cursor;
26import android.graphics.drawable.Drawable;
27import android.net.Uri;
28import android.text.format.Formatter;
29import android.view.LayoutInflater;
30import android.view.View;
31import android.view.ViewGroup;
32import android.widget.CursorAdapter;
33import android.widget.ImageView;
34import android.widget.TextView;
35
36import java.text.DateFormat;
37import java.util.Calendar;
38import java.util.Date;
39import java.util.GregorianCalendar;
40import java.util.List;
41
42/**
43 * List adapter for Cursors returned by {@link DownloadManager}.
44 */
45public class DownloadAdapter extends CursorAdapter {
46    private final DownloadList mDownloadList;
47    private Cursor mCursor;
48    private Resources mResources;
49    private DateFormat mDateFormat;
50    private DateFormat mTimeFormat;
51
52    private final int mTitleColumnId;
53    private final int mDescriptionColumnId;
54    private final int mStatusColumnId;
55    private final int mReasonColumnId;
56    private final int mTotalBytesColumnId;
57    private final int mMediaTypeColumnId;
58    private final int mDateColumnId;
59    private final int mIdColumnId;
60    private final int mFileNameColumnId;
61
62    public DownloadAdapter(DownloadList downloadList, Cursor cursor) {
63        super(downloadList, cursor);
64        mDownloadList = downloadList;
65        mCursor = cursor;
66        mResources = mDownloadList.getResources();
67        mDateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
68        mTimeFormat = DateFormat.getTimeInstance(DateFormat.SHORT);
69
70        mIdColumnId = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_ID);
71        mTitleColumnId = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE);
72        mDescriptionColumnId = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_DESCRIPTION);
73        mStatusColumnId = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS);
74        mReasonColumnId = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_REASON);
75        mTotalBytesColumnId = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
76        mMediaTypeColumnId = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_MEDIA_TYPE);
77        mDateColumnId =
78                cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP);
79        mFileNameColumnId =
80                cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_FILENAME);
81    }
82
83    public View newView() {
84        final DownloadItem view = (DownloadItem) LayoutInflater.from(mDownloadList)
85                .inflate(R.layout.download_list_item, null);
86        view.setDownloadListObj(mDownloadList);
87        return view;
88    }
89
90    public void bindView(View convertView, int position) {
91        if (!(convertView instanceof DownloadItem)) {
92            return;
93        }
94
95        long downloadId = mCursor.getLong(mIdColumnId);
96        ((DownloadItem) convertView).setData(downloadId, position,
97                mCursor.getString(mFileNameColumnId),
98                mCursor.getString(mMediaTypeColumnId));
99
100        // Retrieve the icon for this download
101        retrieveAndSetIcon(convertView);
102
103        String title = mCursor.getString(mTitleColumnId);
104        if (title.isEmpty()) {
105            title = mResources.getString(R.string.missing_title);
106        }
107        setTextForView(convertView, R.id.download_title, title);
108        setTextForView(convertView, R.id.domain, mCursor.getString(mDescriptionColumnId));
109        setTextForView(convertView, R.id.size_text, getSizeText());
110
111        final int status = mCursor.getInt(mStatusColumnId);
112        final CharSequence statusText;
113        if (status == DownloadManager.STATUS_SUCCESSFUL) {
114            statusText = getDateString();
115        } else {
116            statusText = mResources.getString(getStatusStringId(status));
117        }
118        setTextForView(convertView, R.id.status_text, statusText);
119
120        ((DownloadItem) convertView).getCheckBox()
121                .setChecked(mDownloadList.isDownloadSelected(downloadId));
122    }
123
124    private String getDateString() {
125        Date date = new Date(mCursor.getLong(mDateColumnId));
126        if (date.before(getStartOfToday())) {
127            return mDateFormat.format(date);
128        } else {
129            return mTimeFormat.format(date);
130        }
131    }
132
133    private Date getStartOfToday() {
134        Calendar today = new GregorianCalendar();
135        today.set(Calendar.HOUR_OF_DAY, 0);
136        today.set(Calendar.MINUTE, 0);
137        today.set(Calendar.SECOND, 0);
138        today.set(Calendar.MILLISECOND, 0);
139        return today.getTime();
140    }
141
142    private String getSizeText() {
143        long totalBytes = mCursor.getLong(mTotalBytesColumnId);
144        String sizeText = "";
145        if (totalBytes >= 0) {
146            sizeText = Formatter.formatFileSize(mContext, totalBytes);
147        }
148        return sizeText;
149    }
150
151    private int getStatusStringId(int status) {
152        switch (status) {
153            case DownloadManager.STATUS_FAILED:
154                return R.string.download_error;
155
156            case DownloadManager.STATUS_SUCCESSFUL:
157                return R.string.download_success;
158
159            case DownloadManager.STATUS_PENDING:
160            case DownloadManager.STATUS_RUNNING:
161                return R.string.download_running;
162
163            case DownloadManager.STATUS_PAUSED:
164                final int reason = mCursor.getInt(mReasonColumnId);
165                switch (reason) {
166                    case DownloadManager.PAUSED_QUEUED_FOR_WIFI:
167                        return R.string.download_queued;
168                    default:
169                        return R.string.download_running;
170                }
171        }
172        throw new IllegalStateException("Unknown status: " + mCursor.getInt(mStatusColumnId));
173    }
174
175    private void retrieveAndSetIcon(View convertView) {
176        String mediaType = mCursor.getString(mMediaTypeColumnId);
177        ImageView iconView = (ImageView) convertView.findViewById(R.id.download_icon);
178        iconView.setVisibility(View.INVISIBLE);
179
180        if (mediaType == null) {
181            return;
182        }
183
184        Intent intent = new Intent(Intent.ACTION_VIEW);
185        intent.setDataAndType(Uri.fromParts("file", "", null), mediaType);
186        PackageManager pm = mContext.getPackageManager();
187        List<ResolveInfo> list = pm.queryIntentActivities(intent,
188                PackageManager.MATCH_DEFAULT_ONLY);
189        if (list.size() == 0) {
190            // no icon found for this mediatype. use "unknown" icon
191            iconView.setImageResource(R.drawable.ic_download_misc_file_type);
192        } else {
193            Drawable icon = list.get(0).activityInfo.loadIcon(pm);
194            iconView.setImageDrawable(icon);
195        }
196        iconView.setVisibility(View.VISIBLE);
197    }
198
199    private void setTextForView(View parent, int textViewId, CharSequence text) {
200        TextView view = (TextView) parent.findViewById(textViewId);
201        view.setText(text);
202    }
203
204    // CursorAdapter overrides
205
206    @Override
207    public View newView(Context context, Cursor cursor, ViewGroup parent) {
208        return newView();
209    }
210
211    @Override
212    public void bindView(View view, Context context, Cursor cursor) {
213        bindView(view, cursor.getPosition());
214    }
215}
216