add sort to UploadFileActiviy
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / UploadFilesActivity.java
1 /**
2 * ownCloud Android client application
3 *
4 * @author David A. Velasco
5 * Copyright (C) 2015 ownCloud Inc.
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2,
9 * as published by the Free Software Foundation.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 *
19 */
20
21 package com.owncloud.android.ui.activity;
22
23 import java.io.File;
24
25 import android.accounts.Account;
26 import android.app.AlertDialog;
27 import android.content.DialogInterface;
28 import android.content.Intent;
29 import android.content.SharedPreferences;
30 import android.os.AsyncTask;
31 import android.os.Bundle;
32 import android.os.Environment;
33 import android.preference.PreferenceManager;
34 import android.support.v4.app.DialogFragment;
35 import android.support.v7.app.ActionBar;
36 import android.view.Menu;
37 import android.view.MenuInflater;
38 import android.view.MenuItem;
39 import android.view.View;
40 import android.view.View.OnClickListener;
41 import android.view.ViewGroup;
42 import android.widget.ArrayAdapter;
43 import android.widget.Button;
44 import android.widget.TextView;
45
46 import com.owncloud.android.R;
47 import com.owncloud.android.lib.common.utils.Log_OC;
48 import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
49 import com.owncloud.android.ui.dialog.IndeterminateProgressDialog;
50 import com.owncloud.android.ui.dialog.ConfirmationDialogFragment.ConfirmationDialogFragmentListener;
51 import com.owncloud.android.ui.fragment.LocalFileListFragment;
52 import com.owncloud.android.utils.DisplayUtils;
53 import com.owncloud.android.utils.FileStorageUtils;
54
55
56 /**
57 * Displays local files and let the user choose what of them wants to upload
58 * to the current ownCloud account
59 */
60
61 public class UploadFilesActivity extends FileActivity implements
62 LocalFileListFragment.ContainerActivity, ActionBar.OnNavigationListener,
63 OnClickListener, ConfirmationDialogFragmentListener {
64
65 private ArrayAdapter<String> mDirectories;
66 private File mCurrentDir = null;
67 private LocalFileListFragment mFileListFragment;
68 private Button mCancelBtn;
69 private Button mUploadBtn;
70 private Account mAccountOnCreation;
71 private DialogFragment mCurrentDialog;
72
73 public static final String EXTRA_CHOSEN_FILES =
74 UploadFilesActivity.class.getCanonicalName() + ".EXTRA_CHOSEN_FILES";
75
76 public static final int RESULT_OK_AND_MOVE = RESULT_FIRST_USER;
77
78 private static final String KEY_DIRECTORY_PATH =
79 UploadFilesActivity.class.getCanonicalName() + ".KEY_DIRECTORY_PATH";
80 private static final String TAG = "UploadFilesActivity";
81 private static final String WAIT_DIALOG_TAG = "WAIT";
82 private static final String QUERY_TO_MOVE_DIALOG_TAG = "QUERY_TO_MOVE";
83
84
85 @Override
86 public void onCreate(Bundle savedInstanceState) {
87 Log_OC.d(TAG, "onCreate() start");
88 super.onCreate(savedInstanceState);
89
90 if(savedInstanceState != null) {
91 mCurrentDir = new File(savedInstanceState.getString(
92 UploadFilesActivity.KEY_DIRECTORY_PATH));
93 } else {
94 mCurrentDir = Environment.getExternalStorageDirectory();
95 }
96
97 mAccountOnCreation = getAccount();
98
99 /// USER INTERFACE
100
101 // Drop-down navigation
102 mDirectories = new CustomArrayAdapter<String>(this,
103 R.layout.support_simple_spinner_dropdown_item);
104 File currDir = mCurrentDir;
105 while(currDir != null && currDir.getParentFile() != null) {
106 mDirectories.add(currDir.getName());
107 currDir = currDir.getParentFile();
108 }
109 mDirectories.add(File.separator);
110
111 // Inflate and set the layout view
112 setContentView(R.layout.upload_files_layout);
113 mFileListFragment = (LocalFileListFragment)
114 getSupportFragmentManager().findFragmentById(R.id.local_files_list);
115
116
117 // Set input controllers
118 mCancelBtn = (Button) findViewById(R.id.upload_files_btn_cancel);
119 mCancelBtn.setOnClickListener(this);
120 mUploadBtn = (Button) findViewById(R.id.upload_files_btn_upload);
121 mUploadBtn.setOnClickListener(this);
122
123
124 // Action bar setup
125 ActionBar actionBar = getSupportActionBar();
126 actionBar.setIcon(DisplayUtils.getSeasonalIconId());
127 actionBar.setHomeButtonEnabled(true); // mandatory since Android ICS, according to the
128 // official documentation
129 actionBar.setDisplayHomeAsUpEnabled(mCurrentDir != null && mCurrentDir.getName() != null);
130 actionBar.setDisplayShowTitleEnabled(false);
131 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
132 actionBar.setListNavigationCallbacks(mDirectories, this);
133
134 // wait dialog
135 if (mCurrentDialog != null) {
136 mCurrentDialog.dismiss();
137 mCurrentDialog = null;
138 }
139
140 Log_OC.d(TAG, "onCreate() end");
141 }
142
143 @Override
144 public boolean onCreateOptionsMenu(Menu menu) {
145 MenuInflater inflater = getMenuInflater();
146 inflater.inflate(R.menu.uploader_menu, menu);
147 return true;
148 }
149
150
151 @Override
152 public boolean onOptionsItemSelected(MenuItem item) {
153 boolean retval = true;
154 switch (item.getItemId()) {
155 case android.R.id.home: {
156 if(mCurrentDir != null && mCurrentDir.getParentFile() != null){
157 onBackPressed();
158 }
159 break;
160 }
161 case R.id.action_sort: {
162 SharedPreferences appPreferences = PreferenceManager
163 .getDefaultSharedPreferences(this);
164
165 // Read sorting order, default to sort by name ascending
166 Integer sortOrder = appPreferences
167 .getInt("sortOrder", FileStorageUtils.SORT_NAME);
168
169 AlertDialog.Builder builder = new AlertDialog.Builder(this);
170 builder.setTitle(R.string.actionbar_sort_title)
171 .setSingleChoiceItems(R.array.actionbar_sortby, sortOrder ,
172 new DialogInterface.OnClickListener() {
173 public void onClick(DialogInterface dialog, int which) {
174 switch (which){
175 case 0:
176 mFileListFragment.sortByName(true);
177 break;
178 case 1:
179 mFileListFragment.sortByDate(false);
180 break;
181 }
182
183 dialog.dismiss();
184 }
185 });
186 builder.create().show();
187 break;
188 }
189 default:
190 retval = super.onOptionsItemSelected(item);
191 }
192 return retval;
193 }
194
195
196 @Override
197 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
198 int i = itemPosition;
199 while (i-- != 0) {
200 onBackPressed();
201 }
202 // the next operation triggers a new call to this method, but it's necessary to
203 // ensure that the name exposed in the action bar is the current directory when the
204 // user selected it in the navigation list
205 if (itemPosition != 0)
206 getSupportActionBar().setSelectedNavigationItem(0);
207 return true;
208 }
209
210
211 @Override
212 public void onBackPressed() {
213 if (mDirectories.getCount() <= 1) {
214 finish();
215 return;
216 }
217 popDirname();
218 mFileListFragment.onNavigateUp();
219 mCurrentDir = mFileListFragment.getCurrentDirectory();
220
221 if(mCurrentDir.getParentFile() == null){
222 ActionBar actionBar = getSupportActionBar();
223 actionBar.setDisplayHomeAsUpEnabled(false);
224 }
225 }
226
227
228 @Override
229 protected void onSaveInstanceState(Bundle outState) {
230 // responsibility of restore is preferred in onCreate() before than in
231 // onRestoreInstanceState when there are Fragments involved
232 Log_OC.d(TAG, "onSaveInstanceState() start");
233 super.onSaveInstanceState(outState);
234 outState.putString(UploadFilesActivity.KEY_DIRECTORY_PATH, mCurrentDir.getAbsolutePath());
235 Log_OC.d(TAG, "onSaveInstanceState() end");
236 }
237
238
239 /**
240 * Pushes a directory to the drop down list
241 * @param directory to push
242 * @throws IllegalArgumentException If the {@link File#isDirectory()} returns false.
243 */
244 public void pushDirname(File directory) {
245 if(!directory.isDirectory()){
246 throw new IllegalArgumentException("Only directories may be pushed!");
247 }
248 mDirectories.insert(directory.getName(), 0);
249 mCurrentDir = directory;
250 }
251
252 /**
253 * Pops a directory name from the drop down list
254 * @return True, unless the stack is empty
255 */
256 public boolean popDirname() {
257 mDirectories.remove(mDirectories.getItem(0));
258 return !mDirectories.isEmpty();
259 }
260
261
262 // Custom array adapter to override text colors
263 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
264
265 public CustomArrayAdapter(UploadFilesActivity ctx, int view) {
266 super(ctx, view);
267 }
268
269 public View getView(int position, View convertView, ViewGroup parent) {
270 View v = super.getView(position, convertView, parent);
271
272 ((TextView) v).setTextColor(getResources().getColorStateList(
273 android.R.color.white));
274 return v;
275 }
276
277 public View getDropDownView(int position, View convertView,
278 ViewGroup parent) {
279 View v = super.getDropDownView(position, convertView, parent);
280
281 ((TextView) v).setTextColor(getResources().getColorStateList(
282 android.R.color.white));
283
284 return v;
285 }
286
287 }
288
289 /**
290 * {@inheritDoc}
291 */
292 @Override
293 public void onDirectoryClick(File directory) {
294 pushDirname(directory);
295 ActionBar actionBar = getSupportActionBar();
296 actionBar.setDisplayHomeAsUpEnabled(true);
297 }
298
299
300 /**
301 * {@inheritDoc}
302 */
303 @Override
304 public void onFileClick(File file) {
305 // nothing to do
306 }
307
308 /**
309 * {@inheritDoc}
310 */
311 @Override
312 public File getInitialDirectory() {
313 return mCurrentDir;
314 }
315
316
317 /**
318 * Performs corresponding action when user presses 'Cancel' or 'Upload' button
319 *
320 * TODO Make here the real request to the Upload service ; will require to receive the account and
321 * target folder where the upload must be done in the received intent.
322 */
323 @Override
324 public void onClick(View v) {
325 if (v.getId() == R.id.upload_files_btn_cancel) {
326 setResult(RESULT_CANCELED);
327 finish();
328
329 } else if (v.getId() == R.id.upload_files_btn_upload) {
330 new CheckAvailableSpaceTask().execute();
331 }
332 }
333
334
335 /**
336 * Asynchronous task checking if there is space enough to copy all the files chosen
337 * to upload into the ownCloud local folder.
338 *
339 * Maybe an AsyncTask is not strictly necessary, but who really knows.
340 */
341 private class CheckAvailableSpaceTask extends AsyncTask<Void, Void, Boolean> {
342
343 /**
344 * Updates the UI before trying the movement
345 */
346 @Override
347 protected void onPreExecute () {
348 /// progress dialog and disable 'Move' button
349 mCurrentDialog = IndeterminateProgressDialog.newInstance(R.string.wait_a_moment, false);
350 mCurrentDialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
351 }
352
353
354 /**
355 * Checks the available space
356 *
357 * @return 'True' if there is space enough.
358 */
359 @Override
360 protected Boolean doInBackground(Void... params) {
361 String[] checkedFilePaths = mFileListFragment.getCheckedFilePaths();
362 long total = 0;
363 for (int i=0; checkedFilePaths != null && i < checkedFilePaths.length ; i++) {
364 String localPath = checkedFilePaths[i];
365 File localFile = new File(localPath);
366 total += localFile.length();
367 }
368 return (new Boolean(FileStorageUtils.getUsableSpace(mAccountOnCreation.name) >= total));
369 }
370
371 /**
372 * Updates the activity UI after the check of space is done.
373 *
374 * If there is not space enough. shows a new dialog to query the user if wants to move the files instead
375 * of copy them.
376 *
377 * @param result 'True' when there is space enough to copy all the selected files.
378 */
379 @Override
380 protected void onPostExecute(Boolean result) {
381 mCurrentDialog.dismiss();
382 mCurrentDialog = null;
383
384 if (result) {
385 // return the list of selected files (success)
386 Intent data = new Intent();
387 data.putExtra(EXTRA_CHOSEN_FILES, mFileListFragment.getCheckedFilePaths());
388 setResult(RESULT_OK, data);
389 finish();
390
391 } else {
392 // show a dialog to query the user if wants to move the selected files
393 // to the ownCloud folder instead of copying
394 String[] args = {getString(R.string.app_name)};
395 ConfirmationDialogFragment dialog = ConfirmationDialogFragment.newInstance(
396 R.string.upload_query_move_foreign_files, args, R.string.common_yes, -1, R.string.common_no
397 );
398 dialog.setOnConfirmationListener(UploadFilesActivity.this);
399 dialog.show(getSupportFragmentManager(), QUERY_TO_MOVE_DIALOG_TAG);
400 }
401 }
402 }
403
404 @Override
405 public void onConfirmation(String callerTag) {
406 Log_OC.d(TAG, "Positive button in dialog was clicked; dialog tag is " + callerTag);
407 if (callerTag.equals(QUERY_TO_MOVE_DIALOG_TAG)) {
408 // return the list of selected files to the caller activity (success),
409 // signaling that they should be moved to the ownCloud folder, instead of copied
410 Intent data = new Intent();
411 data.putExtra(EXTRA_CHOSEN_FILES, mFileListFragment.getCheckedFilePaths());
412 setResult(RESULT_OK_AND_MOVE, data);
413 finish();
414 }
415 }
416
417
418 @Override
419 public void onNeutral(String callerTag) {
420 Log_OC.d(TAG, "Phantom neutral button in dialog was clicked; dialog tag is " + callerTag);
421 }
422
423
424 @Override
425 public void onCancel(String callerTag) {
426 /// nothing to do; don't finish, let the user change the selection
427 Log_OC.d(TAG, "Negative button in dialog was clicked; dialog tag is " + callerTag);
428 }
429
430
431 @Override
432 protected void onAccountSet(boolean stateWasRecovered) {
433 super.onAccountSet(stateWasRecovered);
434 if (getAccount() != null) {
435 if (!mAccountOnCreation.equals(getAccount())) {
436 setResult(RESULT_CANCELED);
437 finish();
438 }
439
440 } else {
441 setResult(RESULT_CANCELED);
442 finish();
443 }
444 }
445
446
447 }