1/*
2 * Copyright (c) 2008-2009, Motorola, Inc.
3 *
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
8 *
9 * - Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
11 *
12 * - Redistributions in binary form must reproduce the above copyright notice,
13 * this list of conditions and the following disclaimer in the documentation
14 * and/or other materials provided with the distribution.
15 *
16 * - Neither the name of the Motorola, Inc. nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 */
32
33package com.android.bluetooth.opp;
34
35import com.android.bluetooth.R;
36
37import android.app.Activity;
38import android.app.AlertDialog;
39import android.bluetooth.BluetoothAdapter;
40import android.content.DialogInterface;
41import android.content.Intent;
42import android.database.Cursor;
43import android.net.Uri;
44import android.os.Bundle;
45import android.util.Log;
46import android.view.ContextMenu;
47import android.view.Menu;
48import android.view.MenuInflater;
49import android.view.MenuItem;
50import android.view.View;
51import android.view.ContextMenu.ContextMenuInfo;
52import android.widget.AdapterView;
53import android.widget.ListView;
54import android.widget.AdapterView.OnItemClickListener;
55
56/**
57 * View showing the user's finished bluetooth opp transfers that the user does
58 * not confirm. Including outbound and inbound transfers, both successful and
59 * failed. *
60 */
61public class BluetoothOppTransferHistory extends Activity implements
62        View.OnCreateContextMenuListener, OnItemClickListener {
63    private static final String TAG = "BluetoothOppTransferHistory";
64
65    private static final boolean V = Constants.VERBOSE;
66
67    private ListView mListView;
68
69    private Cursor mTransferCursor;
70
71    private BluetoothOppTransferAdapter mTransferAdapter;
72
73    private int mIdColumnId;
74
75    private int mContextMenuPosition;
76
77    private boolean mShowAllIncoming;
78
79    /** Class to handle Notification Manager updates */
80    private BluetoothOppNotification mNotifier;
81
82    @Override
83    public void onCreate(Bundle icicle) {
84        super.onCreate(icicle);
85        setContentView(R.layout.bluetooth_transfers_page);
86        mListView = (ListView)findViewById(R.id.list);
87        mListView.setEmptyView(findViewById(R.id.empty));
88
89        mShowAllIncoming = getIntent().getBooleanExtra(
90                Constants.EXTRA_SHOW_ALL_FILES, false);
91
92        String direction;
93        int dir = getIntent().getIntExtra("direction", 0);
94        if (dir == BluetoothShare.DIRECTION_OUTBOUND) {
95            setTitle(getText(R.string.outbound_history_title));
96            direction = "(" + BluetoothShare.DIRECTION + " == " + BluetoothShare.DIRECTION_OUTBOUND
97                    + ")";
98        } else {
99            if (mShowAllIncoming) {
100                setTitle(getText(R.string.btopp_live_folder));
101            } else {
102                setTitle(getText(R.string.inbound_history_title));
103            }
104            direction = "(" + BluetoothShare.DIRECTION + " == " + BluetoothShare.DIRECTION_INBOUND
105                    + ")";
106        }
107
108        String selection = BluetoothShare.STATUS + " >= '200' AND " + direction;
109
110        if (!mShowAllIncoming) {
111            selection = selection + " AND ("
112                    + BluetoothShare.VISIBILITY + " IS NULL OR "
113                    + BluetoothShare.VISIBILITY + " == '"
114                    + BluetoothShare.VISIBILITY_VISIBLE + "')";
115        }
116
117        final String sortOrder = BluetoothShare.TIMESTAMP + " DESC";
118
119        mTransferCursor = managedQuery(BluetoothShare.CONTENT_URI, new String[] {
120                "_id", BluetoothShare.FILENAME_HINT, BluetoothShare.STATUS,
121                BluetoothShare.TOTAL_BYTES, BluetoothShare._DATA, BluetoothShare.TIMESTAMP,
122                BluetoothShare.VISIBILITY, BluetoothShare.DESTINATION, BluetoothShare.DIRECTION
123        }, selection, sortOrder);
124
125        // only attach everything to the listbox if we can access
126        // the transfer database. Otherwise, just show it empty
127        if (mTransferCursor != null) {
128            mIdColumnId = mTransferCursor.getColumnIndexOrThrow(BluetoothShare._ID);
129            // Create a list "controller" for the data
130            mTransferAdapter = new BluetoothOppTransferAdapter(this,
131                    R.layout.bluetooth_transfer_item, mTransferCursor);
132            mListView.setAdapter(mTransferAdapter);
133            mListView.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
134            mListView.setOnCreateContextMenuListener(this);
135            mListView.setOnItemClickListener(this);
136        }
137
138        mNotifier = new BluetoothOppNotification(this);
139    }
140
141    @Override
142    public boolean onCreateOptionsMenu(Menu menu) {
143        if (mTransferCursor != null && !mShowAllIncoming) {
144            MenuInflater inflater = getMenuInflater();
145            inflater.inflate(R.menu.transferhistory, menu);
146        }
147        return true;
148    }
149
150    @Override
151    public boolean onPrepareOptionsMenu(Menu menu) {
152        if (!mShowAllIncoming) {
153            boolean showClear = getClearableCount() > 0;
154            menu.findItem(R.id.transfer_menu_clear_all).setEnabled(showClear);
155        }
156        return super.onPrepareOptionsMenu(menu);
157    }
158
159    @Override
160    public boolean onOptionsItemSelected(MenuItem item) {
161        switch (item.getItemId()) {
162            case R.id.transfer_menu_clear_all:
163                promptClearList();
164                return true;
165        }
166        return false;
167    }
168
169    @Override
170    public boolean onContextItemSelected(MenuItem item) {
171        mTransferCursor.moveToPosition(mContextMenuPosition);
172        switch (item.getItemId()) {
173            case R.id.transfer_menu_open:
174                openCompleteTransfer();
175                updateNotificationWhenBtDisabled();
176                return true;
177
178            case R.id.transfer_menu_clear:
179                int sessionId = mTransferCursor.getInt(mIdColumnId);
180                Uri contentUri = Uri.parse(BluetoothShare.CONTENT_URI + "/" + sessionId);
181                BluetoothOppUtility.updateVisibilityToHidden(this, contentUri);
182                updateNotificationWhenBtDisabled();
183                return true;
184        }
185        return false;
186    }
187
188    @Override
189    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
190        if (mTransferCursor != null) {
191            AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
192            mTransferCursor.moveToPosition(info.position);
193            mContextMenuPosition = info.position;
194
195            String fileName = mTransferCursor.getString(mTransferCursor
196                    .getColumnIndexOrThrow(BluetoothShare.FILENAME_HINT));
197            if (fileName == null) {
198                fileName = this.getString(R.string.unknown_file);
199            }
200            menu.setHeaderTitle(fileName);
201
202            MenuInflater inflater = getMenuInflater();
203            if (mShowAllIncoming) {
204                inflater.inflate(R.menu.receivedfilescontextfinished, menu);
205            } else {
206                inflater.inflate(R.menu.transferhistorycontextfinished, menu);
207            }
208        }
209    }
210
211    /**
212     * Prompt the user if they would like to clear the transfer history
213     */
214    private void promptClearList() {
215        new AlertDialog.Builder(this).setTitle(R.string.transfer_clear_dlg_title).setMessage(
216                R.string.transfer_clear_dlg_msg).setPositiveButton(android.R.string.ok,
217                new DialogInterface.OnClickListener() {
218                    public void onClick(DialogInterface dialog, int whichButton) {
219                        clearAllDownloads();
220                    }
221                }).setNegativeButton(android.R.string.cancel, null).show();
222    }
223
224    /**
225     * Get the number of finished transfers, including error and success.
226     */
227    private int getClearableCount() {
228        int count = 0;
229        if (mTransferCursor.moveToFirst()) {
230            while (!mTransferCursor.isAfterLast()) {
231                int statusColumnId = mTransferCursor.getColumnIndexOrThrow(BluetoothShare.STATUS);
232                int status = mTransferCursor.getInt(statusColumnId);
233                if (BluetoothShare.isStatusCompleted(status)) {
234                    count++;
235                }
236                mTransferCursor.moveToNext();
237            }
238        }
239        return count;
240    }
241
242    /**
243     * Clear all finished transfers, error and success transfer items.
244     */
245    private void clearAllDownloads() {
246        if (mTransferCursor.moveToFirst()) {
247            while (!mTransferCursor.isAfterLast()) {
248                int sessionId = mTransferCursor.getInt(mIdColumnId);
249                Uri contentUri = Uri.parse(BluetoothShare.CONTENT_URI + "/" + sessionId);
250                BluetoothOppUtility.updateVisibilityToHidden(this, contentUri);
251
252                mTransferCursor.moveToNext();
253            }
254            updateNotificationWhenBtDisabled();
255        }
256    }
257
258    /*
259     * (non-Javadoc)
260     * @see
261     * android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget
262     * .AdapterView, android.view.View, int, long)
263     */
264    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
265        // Open the selected item
266        mTransferCursor.moveToPosition(position);
267        openCompleteTransfer();
268        updateNotificationWhenBtDisabled();
269    }
270
271    /**
272     * Open the selected finished transfer. mDownloadCursor must be moved to
273     * appropriate position before calling this function
274     */
275    private void openCompleteTransfer() {
276        int sessionId = mTransferCursor.getInt(mIdColumnId);
277        Uri contentUri = Uri.parse(BluetoothShare.CONTENT_URI + "/" + sessionId);
278        BluetoothOppTransferInfo transInfo = BluetoothOppUtility.queryRecord(this, contentUri);
279        if (transInfo == null) {
280            Log.e(TAG, "Error: Can not get data from db");
281            return;
282        }
283        if (transInfo.mDirection == BluetoothShare.DIRECTION_INBOUND
284                && BluetoothShare.isStatusSuccess(transInfo.mStatus)) {
285            // if received file successfully, open this file
286            BluetoothOppUtility.updateVisibilityToHidden(this, contentUri);
287            BluetoothOppUtility.openReceivedFile(this, transInfo.mFileName, transInfo.mFileType,
288                    transInfo.mTimeStamp, contentUri);
289        } else {
290            Intent in = new Intent(this, BluetoothOppTransferActivity.class);
291            in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
292            in.setDataAndNormalize(contentUri);
293            this.startActivity(in);
294        }
295    }
296
297    /**
298     * When Bluetooth is disabled, notification can not be updated by
299     * ContentObserver in OppService, so need update manually.
300     */
301    private void updateNotificationWhenBtDisabled() {
302        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
303        if (!adapter.isEnabled()) {
304            if (V) Log.v(TAG, "Bluetooth is not enabled, update notification manually.");
305            mNotifier.updateNotification();
306        }
307    }
308}
309