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