1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.activity
;
23 import android
.accounts
.Account
;
24 import android
.app
.AlertDialog
;
25 import android
.app
.ProgressDialog
;
26 import android
.app
.AlertDialog
.Builder
;
27 import android
.app
.Dialog
;
28 import android
.content
.BroadcastReceiver
;
29 import android
.content
.ComponentName
;
30 import android
.content
.ContentResolver
;
31 import android
.content
.Context
;
32 import android
.content
.DialogInterface
;
33 import android
.content
.DialogInterface
.OnClickListener
;
34 import android
.content
.Intent
;
35 import android
.content
.IntentFilter
;
36 import android
.content
.ServiceConnection
;
37 import android
.content
.SharedPreferences
;
38 import android
.content
.pm
.PackageInfo
;
39 import android
.content
.pm
.PackageManager
.NameNotFoundException
;
40 import android
.content
.res
.Resources
.NotFoundException
;
41 import android
.database
.Cursor
;
42 import android
.net
.Uri
;
43 import android
.os
.Bundle
;
44 import android
.os
.Handler
;
45 import android
.os
.IBinder
;
46 import android
.preference
.PreferenceManager
;
47 import android
.provider
.MediaStore
;
48 import android
.support
.v4
.app
.FragmentTransaction
;
49 import android
.util
.Log
;
50 import android
.view
.View
;
51 import android
.view
.ViewGroup
;
52 import android
.widget
.ArrayAdapter
;
53 import android
.widget
.EditText
;
54 import android
.widget
.TextView
;
55 import android
.widget
.Toast
;
57 import com
.actionbarsherlock
.app
.ActionBar
;
58 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
59 import com
.actionbarsherlock
.app
.SherlockFragmentActivity
;
60 import com
.actionbarsherlock
.view
.Menu
;
61 import com
.actionbarsherlock
.view
.MenuInflater
;
62 import com
.actionbarsherlock
.view
.MenuItem
;
63 import com
.actionbarsherlock
.view
.Window
;
64 import com
.owncloud
.android
.AccountUtils
;
65 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
66 import com
.owncloud
.android
.datamodel
.DataStorageManager
;
67 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
68 import com
.owncloud
.android
.datamodel
.OCFile
;
69 import com
.owncloud
.android
.files
.services
.FileDownloader
;
70 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
71 import com
.owncloud
.android
.files
.services
.FileUploader
;
72 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
73 import com
.owncloud
.android
.syncadapter
.FileSyncService
;
74 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
75 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
77 import com
.owncloud
.android
.R
;
78 import eu
.alefzero
.webdav
.WebdavClient
;
81 * Displays, what files the user has available in his ownCloud.
83 * @author Bartek Przybylski
87 public class FileDisplayActivity
extends SherlockFragmentActivity
implements
88 OCFileListFragment
.ContainerActivity
, FileDetailFragment
.ContainerActivity
, OnNavigationListener
{
90 private ArrayAdapter
<String
> mDirectories
;
91 private OCFile mCurrentDir
= null
;
92 private OCFile mCurrentFile
= null
;
94 private DataStorageManager mStorageManager
;
95 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
96 private UploadFinishReceiver mUploadFinishReceiver
;
97 private DownloadFinishReceiver mDownloadFinishReceiver
;
98 private FileDownloaderBinder mDownloaderBinder
= null
;
100 private OCFileListFragment mFileList
;
102 private boolean mDualPane
;
104 private static final int DIALOG_SETUP_ACCOUNT
= 0;
105 private static final int DIALOG_CREATE_DIR
= 1;
106 private static final int DIALOG_ABOUT_APP
= 2;
107 public static final int DIALOG_SHORT_WAIT
= 3;
108 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 4;
110 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
111 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
113 private static final String TAG
= "FileDisplayActivity";
116 public void onCreate(Bundle savedInstanceState
) {
117 Log
.d(getClass().toString(), "onCreate() start");
118 super.onCreate(savedInstanceState
);
120 /// Load of parameters from received intent
121 mCurrentDir
= getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_FILE
); // no check necessary, mCurrenDir == null if the parameter is not in the intent
122 Account account
= getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_ACCOUNT
);
124 AccountUtils
.setCurrentOwnCloudAccount(this, account
.name
);
126 /// Load of saved instance state: keep this always before initDataFromCurrentAccount()
127 if(savedInstanceState
!= null
) {
128 // TODO - test if savedInstanceState should take precedence over file in the intent ALWAYS (now), NEVER, or SOME TIMES
129 mCurrentDir
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
132 if (!AccountUtils
.accountsAreSetup(this)) {
133 /// no account available: FORCE ACCOUNT CREATION
134 mStorageManager
= null
;
135 createFirstAccount();
137 } else { /// at least an account is available
139 initDataFromCurrentAccount(); // it checks mCurrentDir and mCurrentFile with the current account
143 bindService(new Intent(this, FileDownloader
.class), mConnection
, Context
.BIND_AUTO_CREATE
);
145 // PIN CODE request ; best location is to decide, let's try this first
146 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
151 /*Intent observer_intent = new Intent(this, FileObserverService.class);
152 observer_intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_INIT_OBSERVED_LIST);
153 startService(observer_intent);
157 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
159 // Drop-down navigation
160 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
161 OCFile currFile
= mCurrentDir
;
162 while(currFile
!= null
&& currFile
.getFileName() != OCFile
.PATH_SEPARATOR
) {
163 mDirectories
.add(currFile
.getFileName());
164 currFile
= mStorageManager
.getFileById(currFile
.getParentId());
166 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
168 // Inflate and set the layout view
169 setContentView(R
.layout
.files
);
170 mFileList
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
171 mDualPane
= (findViewById(R
.id
.file_details_container
) != null
);
173 initFileDetailsInDualPane();
177 ActionBar actionBar
= getSupportActionBar();
178 actionBar
.setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
179 actionBar
.setDisplayHomeAsUpEnabled(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0);
180 actionBar
.setDisplayShowTitleEnabled(false
);
181 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
182 actionBar
.setListNavigationCallbacks(mDirectories
, this);
183 setSupportProgressBarIndeterminateVisibility(false
); // always AFTER setContentView(...) ; to workaround bug in its implementation
185 Log
.d(getClass().toString(), "onCreate() end");
190 * Launches the account creation activity. To use when no ownCloud account is available
192 private void createFirstAccount() {
193 Intent intent
= new Intent(android
.provider
.Settings
.ACTION_ADD_ACCOUNT
);
194 intent
.putExtra(android
.provider
.Settings
.EXTRA_AUTHORITIES
, new String
[] { AccountAuthenticator
.AUTH_TOKEN_TYPE
});
195 startActivity(intent
); // the new activity won't be created until this.onStart() and this.onResume() are finished;
200 * Load of state dependent of the existence of an ownCloud account
202 private void initDataFromCurrentAccount() {
203 /// Storage manager initialization - access to local database
204 mStorageManager
= new FileDataStorageManager(
205 AccountUtils
.getCurrentOwnCloudAccount(this),
206 getContentResolver());
208 /// Check if mCurrentDir is a directory
209 if(mCurrentDir
!= null
&& !mCurrentDir
.isDirectory()) {
210 mCurrentFile
= mCurrentDir
;
211 mCurrentDir
= mStorageManager
.getFileById(mCurrentDir
.getParentId());
214 /// Check if mCurrentDir and mCurrentFile are in the current account, and update them
215 if (mCurrentDir
!= null
) {
216 mCurrentDir
= mStorageManager
.getFileByPath(mCurrentDir
.getRemotePath()); // mCurrentDir == null if it is not in the current account
218 if (mCurrentFile
!= null
) {
219 mCurrentFile
= mStorageManager
.getFileByPath(mCurrentFile
.getRemotePath()); // mCurrentFile == null if it is not in the current account
222 /// Default to root if mCurrentDir was not found
223 if (mCurrentDir
== null
) {
224 mCurrentDir
= mStorageManager
.getFileByPath("/"); // will be NULL if the database was never synchronized
229 private void initFileDetailsInDualPane() {
230 if (mDualPane
&& getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
) == null
) {
231 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
232 if (mCurrentFile
!= null
) {
233 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(mCurrentFile
, AccountUtils
.getCurrentOwnCloudAccount(this)), FileDetailFragment
.FTAG
); // empty FileDetailFragment
236 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
); // empty FileDetailFragment
238 transaction
.commit();
244 public void onDestroy() {
246 unbindService(mConnection
);
251 public boolean onCreateOptionsMenu(Menu menu
) {
252 MenuInflater inflater
= getSherlock().getMenuInflater();
253 inflater
.inflate(R
.menu
.menu
, menu
);
258 public boolean onOptionsItemSelected(MenuItem item
) {
259 boolean retval
= true
;
260 switch (item
.getItemId()) {
261 case R
.id
.createDirectoryItem
: {
262 showDialog(DIALOG_CREATE_DIR
);
265 case R
.id
.startSync
: {
266 ContentResolver
.cancelSync(null
, AccountAuthenticator
.AUTH_TOKEN_TYPE
); // cancel the current synchronizations of any ownCloud account
267 Bundle bundle
= new Bundle();
268 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
269 ContentResolver
.requestSync(
270 AccountUtils
.getCurrentOwnCloudAccount(this),
271 AccountAuthenticator
.AUTH_TOKEN_TYPE
, bundle
);
274 case R
.id
.action_upload
: {
275 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
278 case R
.id
.action_settings
: {
279 Intent settingsIntent
= new Intent(this, Preferences
.class);
280 startActivity(settingsIntent
);
283 case R
.id
.about_app
: {
284 showDialog(DIALOG_ABOUT_APP
);
287 case android
.R
.id
.home
: {
288 if(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0){
300 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
301 int i
= itemPosition
;
305 // the next operation triggers a new call to this method, but it's necessary to
306 // ensure that the name exposed in the action bar is the current directory when the
307 // user selected it in the navigation list
308 if (itemPosition
!= 0)
309 getSupportActionBar().setSelectedNavigationItem(0);
314 * Called, when the user selected something for uploading
316 public void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
318 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& resultCode
== RESULT_OK
) {
319 requestSimpleUpload(data
);
321 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& resultCode
== RESULT_OK
) {
322 requestMultipleUpload(data
);
327 private void requestMultipleUpload(Intent data
) {
328 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
329 if (filePaths
!= null
) {
330 String
[] remotePaths
= new String
[filePaths
.length
];
331 String remotePathBase
= "";
332 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
333 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
335 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
336 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
337 for (int j
= 0; j
< remotePaths
.length
; j
++) {
338 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
341 Intent i
= new Intent(this, FileUploader
.class);
342 i
.putExtra(FileUploader
.KEY_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
343 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
344 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
345 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
349 Log
.d("FileDisplay", "User clicked on 'Update' with no selection");
350 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
357 private void requestSimpleUpload(Intent data
) {
358 String filepath
= null
;
360 Uri selectedImageUri
= data
.getData();
362 String filemanagerstring
= selectedImageUri
.getPath();
363 String selectedImagePath
= getPath(selectedImageUri
);
365 if (selectedImagePath
!= null
)
366 filepath
= selectedImagePath
;
368 filepath
= filemanagerstring
;
370 } catch (Exception e
) {
371 Log
.e("FileDisplay", "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
375 if (filepath
== null
) {
376 Log
.e("FileDisplay", "Couldnt resolve path to file");
377 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
383 Intent i
= new Intent(this, FileUploader
.class);
384 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
385 AccountUtils
.getCurrentOwnCloudAccount(this));
386 String remotepath
= new String();
387 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
388 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
390 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
391 remotepath
+= OCFile
.PATH_SEPARATOR
;
392 remotepath
+= new File(filepath
).getName();
394 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
395 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
396 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
402 public void onBackPressed() {
403 if (mDirectories
.getCount() <= 1) {
408 mFileList
.onNavigateUp();
409 mCurrentDir
= mFileList
.getCurrentFile();
412 // Resets the FileDetailsFragment on Tablets so that it always displays
413 FileDetailFragment fileDetails
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
414 if (fileDetails
!= null
&& !fileDetails
.isEmpty()) {
415 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
416 transaction
.remove(fileDetails
);
417 transaction
.add(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
);
418 transaction
.commit();
422 if(mCurrentDir
.getParentId() == 0){
423 ActionBar actionBar
= getSupportActionBar();
424 actionBar
.setDisplayHomeAsUpEnabled(false
);
429 protected void onSaveInstanceState(Bundle outState
) {
430 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
431 Log
.d(getClass().toString(), "onSaveInstanceState() start");
432 super.onSaveInstanceState(outState
);
433 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mCurrentDir
);
435 FileDetailFragment fragment
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
436 OCFile file
= fragment
.getDisplayedFile();
438 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, file
);
441 Log
.d(getClass().toString(), "onSaveInstanceState() end");
445 protected void onResume() {
446 Log
.d(getClass().toString(), "onResume() start");
449 if (AccountUtils
.accountsAreSetup(this)) {
451 if (mStorageManager
== null
) {
452 // this is necessary for handling the come back to FileDisplayActivity when the first ownCloud account is created
453 initDataFromCurrentAccount();
455 initFileDetailsInDualPane();
459 // Listen for sync messages
460 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncService
.SYNC_MESSAGE
);
461 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
462 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
464 // Listen for upload messages
465 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
466 mUploadFinishReceiver
= new UploadFinishReceiver();
467 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
469 // Listen for download messages
470 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
471 mDownloadFinishReceiver
= new DownloadFinishReceiver();
472 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
474 // List current directory
475 mFileList
.listDirectory(mCurrentDir
); // we should find the way to avoid the need of this
479 mStorageManager
= null
; // an invalid object will be there if all the ownCloud accounts are removed
480 showDialog(DIALOG_SETUP_ACCOUNT
);
483 Log
.d(getClass().toString(), "onResume() end");
488 protected void onPause() {
489 Log
.d(getClass().toString(), "onPause() start");
491 if (mSyncBroadcastReceiver
!= null
) {
492 unregisterReceiver(mSyncBroadcastReceiver
);
493 mSyncBroadcastReceiver
= null
;
495 if (mUploadFinishReceiver
!= null
) {
496 unregisterReceiver(mUploadFinishReceiver
);
497 mUploadFinishReceiver
= null
;
499 if (mDownloadFinishReceiver
!= null
) {
500 unregisterReceiver(mDownloadFinishReceiver
);
501 mDownloadFinishReceiver
= null
;
503 if (!AccountUtils
.accountsAreSetup(this)) {
504 dismissDialog(DIALOG_SETUP_ACCOUNT
);
507 Log
.d(getClass().toString(), "onPause() end");
511 protected Dialog
onCreateDialog(int id
) {
512 Dialog dialog
= null
;
513 AlertDialog
.Builder builder
;
515 case DIALOG_SETUP_ACCOUNT
: {
516 builder
= new AlertDialog
.Builder(this);
517 builder
.setTitle(R
.string
.main_tit_accsetup
);
518 builder
.setMessage(R
.string
.main_wrn_accsetup
);
519 builder
.setCancelable(false
);
520 builder
.setPositiveButton(android
.R
.string
.ok
, new OnClickListener() {
521 public void onClick(DialogInterface dialog
, int which
) {
522 createFirstAccount();
526 builder
.setNegativeButton(R
.string
.common_exit
, new OnClickListener() {
527 public void onClick(DialogInterface dialog
, int which
) {
532 //builder.setNegativeButton(android.R.string.cancel, this);
533 dialog
= builder
.create();
536 case DIALOG_ABOUT_APP
: {
537 builder
= new AlertDialog
.Builder(this);
538 builder
.setTitle(getString(R
.string
.about_title
));
541 pkg
= getPackageManager().getPackageInfo(getPackageName(), 0);
542 builder
.setMessage("ownCloud android client\n\nversion: " + pkg
.versionName
);
543 builder
.setIcon(android
.R
.drawable
.ic_menu_info_details
);
544 dialog
= builder
.create();
545 } catch (NameNotFoundException e
) {
548 Log
.e(TAG
, "Error while showing about dialog", e
);
552 case DIALOG_CREATE_DIR
: {
553 builder
= new Builder(this);
554 final EditText dirNameInput
= new EditText(getBaseContext());
555 builder
.setView(dirNameInput
);
556 builder
.setTitle(R
.string
.uploader_info_dirname
);
557 int typed_color
= getResources().getColor(R
.color
.setup_text_typed
);
558 dirNameInput
.setTextColor(typed_color
);
559 builder
.setPositiveButton(android
.R
.string
.ok
,
560 new OnClickListener() {
561 public void onClick(DialogInterface dialog
, int which
) {
562 String directoryName
= dirNameInput
.getText().toString();
563 if (directoryName
.trim().length() == 0) {
568 // Figure out the path where the dir needs to be created
570 if (mCurrentDir
== null
) {
571 // this is just a patch; we should ensure that mCurrentDir never is null
572 if (!mStorageManager
.fileExists(OCFile
.PATH_SEPARATOR
)) {
573 OCFile file
= new OCFile(OCFile
.PATH_SEPARATOR
);
574 mStorageManager
.saveFile(file
);
576 mCurrentDir
= mStorageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
);
578 path
= FileDisplayActivity
.this.mCurrentDir
.getRemotePath();
581 path
+= directoryName
+ OCFile
.PATH_SEPARATOR
;
582 Thread thread
= new Thread(new DirectoryCreator(path
, AccountUtils
.getCurrentOwnCloudAccount(FileDisplayActivity
.this), new Handler()));
587 showDialog(DIALOG_SHORT_WAIT
);
590 builder
.setNegativeButton(R
.string
.common_cancel
,
591 new OnClickListener() {
592 public void onClick(DialogInterface dialog
, int which
) {
596 dialog
= builder
.create();
599 case DIALOG_SHORT_WAIT
: {
600 ProgressDialog working_dialog
= new ProgressDialog(this);
601 working_dialog
.setMessage(getResources().getString(
602 R
.string
.wait_a_moment
));
603 working_dialog
.setIndeterminate(true
);
604 working_dialog
.setCancelable(false
);
605 dialog
= working_dialog
;
608 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
609 final String
[] items
= { getString(R
.string
.actionbar_upload_files
),
610 getString(R
.string
.actionbar_upload_from_apps
) };
611 builder
= new AlertDialog
.Builder(this);
612 builder
.setTitle(R
.string
.actionbar_upload
);
613 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
614 public void onClick(DialogInterface dialog
, int item
) {
617 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
618 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
620 // TODO create and handle new fragment LocalFileListFragment
622 } else if (item
== 1) {
623 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
624 action
= action
.setType("*/*")
625 .addCategory(Intent
.CATEGORY_OPENABLE
);
626 startActivityForResult(
627 Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
628 ACTION_SELECT_CONTENT_FROM_APPS
);
632 dialog
= builder
.create();
644 * Translates a content URI of an image to a physical path
646 * @param uri The URI to resolve
647 * @return The path to the image or null if it could not be found
649 public String
getPath(Uri uri
) {
650 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
651 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
652 if (cursor
!= null
) {
653 int column_index
= cursor
654 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
655 cursor
.moveToFirst();
656 return cursor
.getString(column_index
);
662 * Pushes a directory to the drop down list
663 * @param directory to push
664 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
666 public void pushDirname(OCFile directory
) {
667 if(!directory
.isDirectory()){
668 throw new IllegalArgumentException("Only directories may be pushed!");
670 mDirectories
.insert(directory
.getFileName(), 0);
671 mCurrentDir
= directory
;
675 * Pops a directory name from the drop down list
676 * @return True, unless the stack is empty
678 public boolean popDirname() {
679 mDirectories
.remove(mDirectories
.getItem(0));
680 return !mDirectories
.isEmpty();
683 private class DirectoryCreator
implements Runnable
{
684 private String mTargetPath
;
685 private Account mAccount
;
686 private Handler mHandler
;
688 public DirectoryCreator(String targetPath
, Account account
, Handler handler
) {
689 mTargetPath
= targetPath
;
696 WebdavClient wdc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getApplicationContext());
697 boolean created
= wdc
.createDirectory(mTargetPath
);
699 mHandler
.post(new Runnable() {
702 dismissDialog(DIALOG_SHORT_WAIT
);
704 // Save new directory in local database
705 OCFile newDir
= new OCFile(mTargetPath
);
706 newDir
.setMimetype("DIR");
707 newDir
.setParentId(mCurrentDir
.getFileId());
708 mStorageManager
.saveFile(newDir
);
710 // Display the new folder right away
711 mFileList
.listDirectory(mCurrentDir
);
716 mHandler
.post(new Runnable() {
719 dismissDialog(DIALOG_SHORT_WAIT
);
721 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
724 } catch (NotFoundException e
) {
725 Log
.e(TAG
, "Error while trying to show fail message " , e
);
734 // Custom array adapter to override text colors
735 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
737 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
741 public View
getView(int position
, View convertView
, ViewGroup parent
) {
742 View v
= super.getView(position
, convertView
, parent
);
744 ((TextView
) v
).setTextColor(getResources().getColorStateList(
745 android
.R
.color
.white
));
749 public View
getDropDownView(int position
, View convertView
,
751 View v
= super.getDropDownView(position
, convertView
, parent
);
753 ((TextView
) v
).setTextColor(getResources().getColorStateList(
754 android
.R
.color
.white
));
761 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
763 * {@link BroadcastReceiver} to enable syncing feedback in UI
766 public void onReceive(Context context
, Intent intent
) {
767 boolean inProgress
= intent
.getBooleanExtra(
768 FileSyncService
.IN_PROGRESS
, false
);
769 String accountName
= intent
770 .getStringExtra(FileSyncService
.ACCOUNT_NAME
);
772 Log
.d("FileDisplay", "sync of account " + accountName
773 + " is in_progress: " + inProgress
);
775 if (accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
)) {
777 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
);
779 boolean fillBlankRoot
= false
;
780 if (mCurrentDir
== null
) {
781 mCurrentDir
= mStorageManager
.getFileByPath("/");
782 fillBlankRoot
= (mCurrentDir
!= null
);
785 if ((synchFolderRemotePath
!= null
&& mCurrentDir
!= null
&& (mCurrentDir
.getRemotePath().equals(synchFolderRemotePath
)))
788 mCurrentDir
= getStorageManager().getFileByPath(synchFolderRemotePath
);
789 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager()
790 .findFragmentById(R
.id
.fileList
);
791 if (fileListFragment
!= null
) {
792 fileListFragment
.listDirectory(mCurrentDir
);
796 setSupportProgressBarIndeterminateVisibility(inProgress
);
803 private class UploadFinishReceiver
extends BroadcastReceiver
{
805 * Once the file upload has finished -> update view
806 * @author David A. Velasco
807 * {@link BroadcastReceiver} to enable upload feedback in UI
810 public void onReceive(Context context
, Intent intent
) {
811 long parentDirId
= intent
.getLongExtra(FileUploader
.EXTRA_PARENT_DIR_ID
, -1);
812 OCFile parentDir
= mStorageManager
.getFileById(parentDirId
);
813 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
815 if (accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
) &&
817 ( (mCurrentDir
== null
&& parentDir
.getFileName().equals("/")) ||
818 parentDir
.equals(mCurrentDir
)
821 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
822 if (fileListFragment
!= null
) {
823 fileListFragment
.listDirectory();
832 * Once the file download has finished -> update view
834 private class DownloadFinishReceiver
extends BroadcastReceiver
{
836 public void onReceive(Context context
, Intent intent
) {
837 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
838 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
840 if (accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
) &&
841 mCurrentDir
!= null
&& mCurrentDir
.getFileId() == mStorageManager
.getFileByPath(downloadedRemotePath
).getParentId()) {
842 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
843 if (fileListFragment
!= null
) {
844 fileListFragment
.listDirectory();
857 public DataStorageManager
getStorageManager() {
858 return mStorageManager
;
866 public void onDirectoryClick(OCFile directory
) {
867 pushDirname(directory
);
868 ActionBar actionBar
= getSupportActionBar();
869 actionBar
.setDisplayHomeAsUpEnabled(true
);
872 // Resets the FileDetailsFragment on Tablets so that it always displays
873 FileDetailFragment fileDetails
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
874 if (fileDetails
!= null
&& !fileDetails
.isEmpty()) {
875 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
876 transaction
.remove(fileDetails
);
877 transaction
.add(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
);
878 transaction
.commit();
888 public void onFileClick(OCFile file
) {
890 // If we are on a large device -> update fragment
892 // buttons in the details view are problematic when trying to reuse an existing fragment; create always a new one solves some of them, BUT no all; downloads are 'dangerous'
893 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
894 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(file
, AccountUtils
.getCurrentOwnCloudAccount(this)), FileDetailFragment
.FTAG
);
895 transaction
.setTransition(FragmentTransaction
.TRANSIT_FRAGMENT_FADE
);
896 transaction
.commit();
898 } else { // small or medium screen device -> new Activity
899 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
900 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, file
);
901 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
902 startActivity(showDetailsIntent
);
911 public OCFile
getInitialDirectory() {
920 public void onFileStateChanged() {
921 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
922 if (fileListFragment
!= null
) {
923 fileListFragment
.listDirectory();
932 public FileDownloaderBinder
getFileDownloaderBinder() {
933 return mDownloaderBinder
;
937 /** Defines callbacks for service binding, passed to bindService() */
938 private ServiceConnection mConnection
= new ServiceConnection() {
941 public void onServiceConnected(ComponentName className
, IBinder service
) {
942 mDownloaderBinder
= (FileDownloaderBinder
) service
;
943 // a new chance to get the mDownloadBinder through getDownloadBinder() - THIS IS A MESS
944 mFileList
.listDirectory();
946 FileDetailFragment fragment
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
947 if (fragment
!= null
)
948 fragment
.updateFileDetails();
954 public void onServiceDisconnected(ComponentName arg0
) {
955 mDownloaderBinder
= null
;
962 * Launch an intent to request the PIN code to the user before letting him use the app
964 private void requestPinCode() {
965 boolean pinStart
= false
;
966 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
967 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
969 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
970 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");