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
.FileObserverService
;
72 import com
.owncloud
.android
.files
.services
.FileUploader
;
73 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
74 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
75 import com
.owncloud
.android
.syncadapter
.FileSyncService
;
76 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
77 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
79 import com
.owncloud
.android
.R
;
80 import eu
.alefzero
.webdav
.WebdavClient
;
83 * Displays, what files the user has available in his ownCloud.
85 * @author Bartek Przybylski
89 public class FileDisplayActivity
extends SherlockFragmentActivity
implements
90 OCFileListFragment
.ContainerActivity
, FileDetailFragment
.ContainerActivity
, OnNavigationListener
{
92 private ArrayAdapter
<String
> mDirectories
;
93 private OCFile mCurrentDir
= null
;
94 private OCFile mCurrentFile
= null
;
96 private DataStorageManager mStorageManager
;
97 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
98 private UploadFinishReceiver mUploadFinishReceiver
;
99 private DownloadFinishReceiver mDownloadFinishReceiver
;
100 private FileDownloaderBinder mDownloaderBinder
= null
;
101 private FileUploaderBinder mUploaderBinder
= null
;
102 private ServiceConnection mDownloadConnection
= null
, mUploadConnection
= null
;
104 private OCFileListFragment mFileList
;
106 private boolean mDualPane
;
108 private static final int DIALOG_SETUP_ACCOUNT
= 0;
109 private static final int DIALOG_CREATE_DIR
= 1;
110 private static final int DIALOG_ABOUT_APP
= 2;
111 public static final int DIALOG_SHORT_WAIT
= 3;
112 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 4;
114 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
115 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
117 private static final String TAG
= "FileDisplayActivity";
120 public void onCreate(Bundle savedInstanceState
) {
121 Log
.d(getClass().toString(), "onCreate() start");
122 super.onCreate(savedInstanceState
);
124 /// Load of parameters from received intent
125 mCurrentDir
= getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_FILE
); // no check necessary, mCurrenDir == null if the parameter is not in the intent
126 Account account
= getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_ACCOUNT
);
128 AccountUtils
.setCurrentOwnCloudAccount(this, account
.name
);
130 /// Load of saved instance state: keep this always before initDataFromCurrentAccount()
131 if(savedInstanceState
!= null
) {
132 // TODO - test if savedInstanceState should take precedence over file in the intent ALWAYS (now), NEVER, or SOME TIMES
133 mCurrentDir
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
136 if (!AccountUtils
.accountsAreSetup(this)) {
137 /// no account available: FORCE ACCOUNT CREATION
138 mStorageManager
= null
;
139 createFirstAccount();
141 } else { /// at least an account is available
143 initDataFromCurrentAccount(); // it checks mCurrentDir and mCurrentFile with the current account
147 mUploadConnection
= new ListServiceConnection();
148 mDownloadConnection
= new ListServiceConnection();
149 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
150 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
152 // PIN CODE request ; best location is to decide, let's try this first
153 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
158 Intent observer_intent
= new Intent(this, FileObserverService
.class);
159 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
160 startService(observer_intent
);
164 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
166 // Drop-down navigation
167 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
168 OCFile currFile
= mCurrentDir
;
169 while(currFile
!= null
&& currFile
.getFileName() != OCFile
.PATH_SEPARATOR
) {
170 mDirectories
.add(currFile
.getFileName());
171 currFile
= mStorageManager
.getFileById(currFile
.getParentId());
173 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
175 // Inflate and set the layout view
176 setContentView(R
.layout
.files
);
177 mFileList
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
178 mDualPane
= (findViewById(R
.id
.file_details_container
) != null
);
180 initFileDetailsInDualPane();
184 ActionBar actionBar
= getSupportActionBar();
185 actionBar
.setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
186 actionBar
.setDisplayHomeAsUpEnabled(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0);
187 actionBar
.setDisplayShowTitleEnabled(false
);
188 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
189 actionBar
.setListNavigationCallbacks(mDirectories
, this);
190 setSupportProgressBarIndeterminateVisibility(false
); // always AFTER setContentView(...) ; to workaround bug in its implementation
192 Log
.d(getClass().toString(), "onCreate() end");
197 * Launches the account creation activity. To use when no ownCloud account is available
199 private void createFirstAccount() {
200 Intent intent
= new Intent(android
.provider
.Settings
.ACTION_ADD_ACCOUNT
);
201 intent
.putExtra(android
.provider
.Settings
.EXTRA_AUTHORITIES
, new String
[] { AccountAuthenticator
.AUTH_TOKEN_TYPE
});
202 startActivity(intent
); // the new activity won't be created until this.onStart() and this.onResume() are finished;
207 * Load of state dependent of the existence of an ownCloud account
209 private void initDataFromCurrentAccount() {
210 /// Storage manager initialization - access to local database
211 mStorageManager
= new FileDataStorageManager(
212 AccountUtils
.getCurrentOwnCloudAccount(this),
213 getContentResolver());
215 /// Check if mCurrentDir is a directory
216 if(mCurrentDir
!= null
&& !mCurrentDir
.isDirectory()) {
217 mCurrentFile
= mCurrentDir
;
218 mCurrentDir
= mStorageManager
.getFileById(mCurrentDir
.getParentId());
221 /// Check if mCurrentDir and mCurrentFile are in the current account, and update them
222 if (mCurrentDir
!= null
) {
223 mCurrentDir
= mStorageManager
.getFileByPath(mCurrentDir
.getRemotePath()); // mCurrentDir == null if it is not in the current account
225 if (mCurrentFile
!= null
) {
226 if (mCurrentFile
.fileExists()) {
227 mCurrentFile
= mStorageManager
.getFileByPath(mCurrentFile
.getRemotePath()); // mCurrentFile == null if it is not in the current account
228 } // else : keep mCurrentFile with the received value; this is currently the case of an upload in progress, when the user presses the status notification in a landscape tablet
231 /// Default to root if mCurrentDir was not found
232 if (mCurrentDir
== null
) {
233 mCurrentDir
= mStorageManager
.getFileByPath("/"); // will be NULL if the database was never synchronized
238 private void initFileDetailsInDualPane() {
239 if (mDualPane
&& getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
) == null
) {
240 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
241 if (mCurrentFile
!= null
) {
242 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(mCurrentFile
, AccountUtils
.getCurrentOwnCloudAccount(this)), FileDetailFragment
.FTAG
); // empty FileDetailFragment
245 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
); // empty FileDetailFragment
247 transaction
.commit();
253 public void onDestroy() {
255 if (mDownloadConnection
!= null
)
256 unbindService(mDownloadConnection
);
257 if (mUploadConnection
!= null
)
258 unbindService(mUploadConnection
);
263 public boolean onCreateOptionsMenu(Menu menu
) {
264 MenuInflater inflater
= getSherlock().getMenuInflater();
265 inflater
.inflate(R
.menu
.menu
, menu
);
270 public boolean onOptionsItemSelected(MenuItem item
) {
271 boolean retval
= true
;
272 switch (item
.getItemId()) {
273 case R
.id
.createDirectoryItem
: {
274 showDialog(DIALOG_CREATE_DIR
);
277 case R
.id
.startSync
: {
278 ContentResolver
.cancelSync(null
, AccountAuthenticator
.AUTH_TOKEN_TYPE
); // cancel the current synchronizations of any ownCloud account
279 Bundle bundle
= new Bundle();
280 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
281 ContentResolver
.requestSync(
282 AccountUtils
.getCurrentOwnCloudAccount(this),
283 AccountAuthenticator
.AUTH_TOKEN_TYPE
, bundle
);
286 case R
.id
.action_upload
: {
287 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
290 case R
.id
.action_settings
: {
291 Intent settingsIntent
= new Intent(this, Preferences
.class);
292 startActivity(settingsIntent
);
295 case R
.id
.about_app
: {
296 showDialog(DIALOG_ABOUT_APP
);
299 case android
.R
.id
.home
: {
300 if(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0){
312 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
313 int i
= itemPosition
;
317 // the next operation triggers a new call to this method, but it's necessary to
318 // ensure that the name exposed in the action bar is the current directory when the
319 // user selected it in the navigation list
320 if (itemPosition
!= 0)
321 getSupportActionBar().setSelectedNavigationItem(0);
326 * Called, when the user selected something for uploading
328 public void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
330 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& resultCode
== RESULT_OK
) {
331 requestSimpleUpload(data
);
333 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& resultCode
== RESULT_OK
) {
334 requestMultipleUpload(data
);
339 private void requestMultipleUpload(Intent data
) {
340 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
341 if (filePaths
!= null
) {
342 String
[] remotePaths
= new String
[filePaths
.length
];
343 String remotePathBase
= "";
344 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
345 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
347 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
348 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
349 for (int j
= 0; j
< remotePaths
.length
; j
++) {
350 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
353 Intent i
= new Intent(this, FileUploader
.class);
354 i
.putExtra(FileUploader
.KEY_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
355 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
356 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
357 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
361 Log
.d("FileDisplay", "User clicked on 'Update' with no selection");
362 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
369 private void requestSimpleUpload(Intent data
) {
370 String filepath
= null
;
372 Uri selectedImageUri
= data
.getData();
374 String filemanagerstring
= selectedImageUri
.getPath();
375 String selectedImagePath
= getPath(selectedImageUri
);
377 if (selectedImagePath
!= null
)
378 filepath
= selectedImagePath
;
380 filepath
= filemanagerstring
;
382 } catch (Exception e
) {
383 Log
.e("FileDisplay", "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
387 if (filepath
== null
) {
388 Log
.e("FileDisplay", "Couldnt resolve path to file");
389 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
395 Intent i
= new Intent(this, FileUploader
.class);
396 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
397 AccountUtils
.getCurrentOwnCloudAccount(this));
398 String remotepath
= new String();
399 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
400 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
402 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
403 remotepath
+= OCFile
.PATH_SEPARATOR
;
404 remotepath
+= new File(filepath
).getName();
406 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
407 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
408 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
414 public void onBackPressed() {
415 if (mDirectories
.getCount() <= 1) {
420 mFileList
.onNavigateUp();
421 mCurrentDir
= mFileList
.getCurrentFile();
424 // Resets the FileDetailsFragment on Tablets so that it always displays
425 FileDetailFragment fileDetails
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
426 if (fileDetails
!= null
&& !fileDetails
.isEmpty()) {
427 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
428 transaction
.remove(fileDetails
);
429 transaction
.add(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
);
430 transaction
.commit();
434 if(mCurrentDir
.getParentId() == 0){
435 ActionBar actionBar
= getSupportActionBar();
436 actionBar
.setDisplayHomeAsUpEnabled(false
);
441 protected void onSaveInstanceState(Bundle outState
) {
442 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
443 Log
.d(getClass().toString(), "onSaveInstanceState() start");
444 super.onSaveInstanceState(outState
);
445 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mCurrentDir
);
447 FileDetailFragment fragment
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
448 if (fragment
!= null
) {
449 OCFile file
= fragment
.getDisplayedFile();
451 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, file
);
455 Log
.d(getClass().toString(), "onSaveInstanceState() end");
459 protected void onResume() {
460 Log
.d(getClass().toString(), "onResume() start");
463 if (AccountUtils
.accountsAreSetup(this)) {
465 if (mStorageManager
== null
) {
466 // this is necessary for handling the come back to FileDisplayActivity when the first ownCloud account is created
467 initDataFromCurrentAccount();
469 initFileDetailsInDualPane();
473 // Listen for sync messages
474 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncService
.SYNC_MESSAGE
);
475 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
476 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
478 // Listen for upload messages
479 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
480 mUploadFinishReceiver
= new UploadFinishReceiver();
481 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
483 // Listen for download messages
484 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
485 mDownloadFinishReceiver
= new DownloadFinishReceiver();
486 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
488 // List current directory
489 mFileList
.listDirectory(mCurrentDir
); // TODO we should find the way to avoid the need of this (maybe it's not necessary yet; to check)
493 mStorageManager
= null
; // an invalid object will be there if all the ownCloud accounts are removed
494 showDialog(DIALOG_SETUP_ACCOUNT
);
497 Log
.d(getClass().toString(), "onResume() end");
502 protected void onPause() {
503 Log
.d(getClass().toString(), "onPause() start");
505 if (mSyncBroadcastReceiver
!= null
) {
506 unregisterReceiver(mSyncBroadcastReceiver
);
507 mSyncBroadcastReceiver
= null
;
509 if (mUploadFinishReceiver
!= null
) {
510 unregisterReceiver(mUploadFinishReceiver
);
511 mUploadFinishReceiver
= null
;
513 if (mDownloadFinishReceiver
!= null
) {
514 unregisterReceiver(mDownloadFinishReceiver
);
515 mDownloadFinishReceiver
= null
;
517 if (!AccountUtils
.accountsAreSetup(this)) {
518 dismissDialog(DIALOG_SETUP_ACCOUNT
);
521 Log
.d(getClass().toString(), "onPause() end");
525 protected Dialog
onCreateDialog(int id
) {
526 Dialog dialog
= null
;
527 AlertDialog
.Builder builder
;
529 case DIALOG_SETUP_ACCOUNT
: {
530 builder
= new AlertDialog
.Builder(this);
531 builder
.setTitle(R
.string
.main_tit_accsetup
);
532 builder
.setMessage(R
.string
.main_wrn_accsetup
);
533 builder
.setCancelable(false
);
534 builder
.setPositiveButton(android
.R
.string
.ok
, new OnClickListener() {
535 public void onClick(DialogInterface dialog
, int which
) {
536 createFirstAccount();
540 builder
.setNegativeButton(R
.string
.common_exit
, new OnClickListener() {
541 public void onClick(DialogInterface dialog
, int which
) {
546 //builder.setNegativeButton(android.R.string.cancel, this);
547 dialog
= builder
.create();
550 case DIALOG_ABOUT_APP
: {
551 builder
= new AlertDialog
.Builder(this);
552 builder
.setTitle(getString(R
.string
.about_title
));
555 pkg
= getPackageManager().getPackageInfo(getPackageName(), 0);
556 builder
.setMessage(String
.format(getString(R
.string
.about_message
), pkg
.versionName
));
557 builder
.setIcon(android
.R
.drawable
.ic_menu_info_details
);
558 dialog
= builder
.create();
559 } catch (NameNotFoundException e
) {
562 Log
.e(TAG
, "Error while showing about dialog", e
);
566 case DIALOG_CREATE_DIR
: {
567 builder
= new Builder(this);
568 final EditText dirNameInput
= new EditText(getBaseContext());
569 builder
.setView(dirNameInput
);
570 builder
.setTitle(R
.string
.uploader_info_dirname
);
571 int typed_color
= getResources().getColor(R
.color
.setup_text_typed
);
572 dirNameInput
.setTextColor(typed_color
);
573 builder
.setPositiveButton(android
.R
.string
.ok
,
574 new OnClickListener() {
575 public void onClick(DialogInterface dialog
, int which
) {
576 String directoryName
= dirNameInput
.getText().toString();
577 if (directoryName
.trim().length() == 0) {
582 // Figure out the path where the dir needs to be created
584 if (mCurrentDir
== null
) {
585 // this is just a patch; we should ensure that mCurrentDir never is null
586 if (!mStorageManager
.fileExists(OCFile
.PATH_SEPARATOR
)) {
587 OCFile file
= new OCFile(OCFile
.PATH_SEPARATOR
);
588 mStorageManager
.saveFile(file
);
590 mCurrentDir
= mStorageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
);
592 path
= FileDisplayActivity
.this.mCurrentDir
.getRemotePath();
595 path
+= directoryName
+ OCFile
.PATH_SEPARATOR
;
596 Thread thread
= new Thread(new DirectoryCreator(path
, AccountUtils
.getCurrentOwnCloudAccount(FileDisplayActivity
.this), new Handler()));
601 showDialog(DIALOG_SHORT_WAIT
);
604 builder
.setNegativeButton(R
.string
.common_cancel
,
605 new OnClickListener() {
606 public void onClick(DialogInterface dialog
, int which
) {
610 dialog
= builder
.create();
613 case DIALOG_SHORT_WAIT
: {
614 ProgressDialog working_dialog
= new ProgressDialog(this);
615 working_dialog
.setMessage(getResources().getString(
616 R
.string
.wait_a_moment
));
617 working_dialog
.setIndeterminate(true
);
618 working_dialog
.setCancelable(false
);
619 dialog
= working_dialog
;
622 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
623 final String
[] items
= { getString(R
.string
.actionbar_upload_files
),
624 getString(R
.string
.actionbar_upload_from_apps
) };
625 builder
= new AlertDialog
.Builder(this);
626 builder
.setTitle(R
.string
.actionbar_upload
);
627 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
628 public void onClick(DialogInterface dialog
, int item
) {
631 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
632 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
634 // TODO create and handle new fragment LocalFileListFragment
636 } else if (item
== 1) {
637 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
638 action
= action
.setType("*/*")
639 .addCategory(Intent
.CATEGORY_OPENABLE
);
640 startActivityForResult(
641 Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
642 ACTION_SELECT_CONTENT_FROM_APPS
);
646 dialog
= builder
.create();
658 * Translates a content URI of an image to a physical path
660 * @param uri The URI to resolve
661 * @return The path to the image or null if it could not be found
663 public String
getPath(Uri uri
) {
664 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
665 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
666 if (cursor
!= null
) {
667 int column_index
= cursor
668 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
669 cursor
.moveToFirst();
670 return cursor
.getString(column_index
);
676 * Pushes a directory to the drop down list
677 * @param directory to push
678 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
680 public void pushDirname(OCFile directory
) {
681 if(!directory
.isDirectory()){
682 throw new IllegalArgumentException("Only directories may be pushed!");
684 mDirectories
.insert(directory
.getFileName(), 0);
685 mCurrentDir
= directory
;
689 * Pops a directory name from the drop down list
690 * @return True, unless the stack is empty
692 public boolean popDirname() {
693 mDirectories
.remove(mDirectories
.getItem(0));
694 return !mDirectories
.isEmpty();
697 private class DirectoryCreator
implements Runnable
{
698 private String mTargetPath
;
699 private Account mAccount
;
700 private Handler mHandler
;
702 public DirectoryCreator(String targetPath
, Account account
, Handler handler
) {
703 mTargetPath
= targetPath
;
710 WebdavClient wdc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getApplicationContext());
711 boolean created
= wdc
.createDirectory(mTargetPath
);
713 mHandler
.post(new Runnable() {
716 dismissDialog(DIALOG_SHORT_WAIT
);
718 // Save new directory in local database
719 OCFile newDir
= new OCFile(mTargetPath
);
720 newDir
.setMimetype("DIR");
721 newDir
.setParentId(mCurrentDir
.getFileId());
722 mStorageManager
.saveFile(newDir
);
724 // Display the new folder right away
725 mFileList
.listDirectory();
730 mHandler
.post(new Runnable() {
733 dismissDialog(DIALOG_SHORT_WAIT
);
735 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
738 } catch (NotFoundException e
) {
739 Log
.e(TAG
, "Error while trying to show fail message " , e
);
748 // Custom array adapter to override text colors
749 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
751 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
755 public View
getView(int position
, View convertView
, ViewGroup parent
) {
756 View v
= super.getView(position
, convertView
, parent
);
758 ((TextView
) v
).setTextColor(getResources().getColorStateList(
759 android
.R
.color
.white
));
763 public View
getDropDownView(int position
, View convertView
,
765 View v
= super.getDropDownView(position
, convertView
, parent
);
767 ((TextView
) v
).setTextColor(getResources().getColorStateList(
768 android
.R
.color
.white
));
775 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
777 * {@link BroadcastReceiver} to enable syncing feedback in UI
780 public void onReceive(Context context
, Intent intent
) {
781 boolean inProgress
= intent
.getBooleanExtra(
782 FileSyncService
.IN_PROGRESS
, false
);
783 String accountName
= intent
784 .getStringExtra(FileSyncService
.ACCOUNT_NAME
);
786 Log
.d("FileDisplay", "sync of account " + accountName
787 + " is in_progress: " + inProgress
);
789 if (accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
)) {
791 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
);
793 boolean fillBlankRoot
= false
;
794 if (mCurrentDir
== null
) {
795 mCurrentDir
= mStorageManager
.getFileByPath("/");
796 fillBlankRoot
= (mCurrentDir
!= null
);
799 if ((synchFolderRemotePath
!= null
&& mCurrentDir
!= null
&& (mCurrentDir
.getRemotePath().equals(synchFolderRemotePath
)))
802 mCurrentDir
= getStorageManager().getFileByPath(synchFolderRemotePath
);
803 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager()
804 .findFragmentById(R
.id
.fileList
);
805 if (fileListFragment
!= null
) {
806 fileListFragment
.listDirectory(mCurrentDir
);
810 setSupportProgressBarIndeterminateVisibility(inProgress
);
817 private class UploadFinishReceiver
extends BroadcastReceiver
{
819 * Once the file upload has finished -> update view
820 * @author David A. Velasco
821 * {@link BroadcastReceiver} to enable upload feedback in UI
824 public void onReceive(Context context
, Intent intent
) {
825 long parentDirId
= intent
.getLongExtra(FileUploader
.EXTRA_PARENT_DIR_ID
, -1);
826 OCFile parentDir
= mStorageManager
.getFileById(parentDirId
);
827 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
829 if (accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
) &&
831 ( (mCurrentDir
== null
&& parentDir
.getFileName().equals("/")) ||
832 parentDir
.equals(mCurrentDir
)
835 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
836 if (fileListFragment
!= null
) {
837 fileListFragment
.listDirectory();
846 * Once the file download has finished -> update view
848 private class DownloadFinishReceiver
extends BroadcastReceiver
{
850 public void onReceive(Context context
, Intent intent
) {
851 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
852 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
854 if (accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
) &&
855 mCurrentDir
!= null
&& mCurrentDir
.getFileId() == mStorageManager
.getFileByPath(downloadedRemotePath
).getParentId()) {
856 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
857 if (fileListFragment
!= null
) {
858 fileListFragment
.listDirectory();
871 public DataStorageManager
getStorageManager() {
872 return mStorageManager
;
880 public void onDirectoryClick(OCFile directory
) {
881 pushDirname(directory
);
882 ActionBar actionBar
= getSupportActionBar();
883 actionBar
.setDisplayHomeAsUpEnabled(true
);
886 // Resets the FileDetailsFragment on Tablets so that it always displays
887 FileDetailFragment fileDetails
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
888 if (fileDetails
!= null
&& !fileDetails
.isEmpty()) {
889 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
890 transaction
.remove(fileDetails
);
891 transaction
.add(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
);
892 transaction
.commit();
902 public void onFileClick(OCFile file
) {
904 // If we are on a large device -> update fragment
906 // 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'
907 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
908 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(file
, AccountUtils
.getCurrentOwnCloudAccount(this)), FileDetailFragment
.FTAG
);
909 transaction
.setTransition(FragmentTransaction
.TRANSIT_FRAGMENT_FADE
);
910 transaction
.commit();
912 } else { // small or medium screen device -> new Activity
913 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
914 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, file
);
915 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
916 startActivity(showDetailsIntent
);
925 public OCFile
getInitialDirectory() {
934 public void onFileStateChanged() {
935 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
936 if (fileListFragment
!= null
) {
937 fileListFragment
.listDirectory();
946 public FileDownloaderBinder
getFileDownloaderBinder() {
947 return mDownloaderBinder
;
955 public FileUploaderBinder
getFileUploaderBinder() {
956 return mUploaderBinder
;
960 /** Defines callbacks for service binding, passed to bindService() */
961 private class ListServiceConnection
implements ServiceConnection
{
964 public void onServiceConnected(ComponentName component
, IBinder service
) {
965 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
966 Log
.d(TAG
, "Download service connected");
967 mDownloaderBinder
= (FileDownloaderBinder
) service
;
968 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
969 Log
.d(TAG
, "Upload service connected");
970 mUploaderBinder
= (FileUploaderBinder
) service
;
974 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
975 if (mFileList
!= null
)
976 mFileList
.listDirectory();
978 FileDetailFragment fragment
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
979 if (fragment
!= null
)
980 fragment
.updateFileDetails();
985 public void onServiceDisconnected(ComponentName component
) {
986 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
987 Log
.d(TAG
, "Download service disconnected");
988 mDownloaderBinder
= null
;
989 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
990 Log
.d(TAG
, "Upload service disconnected");
991 mUploaderBinder
= null
;
999 * Launch an intent to request the PIN code to the user before letting him use the app
1001 private void requestPinCode() {
1002 boolean pinStart
= false
;
1003 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1004 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1006 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1007 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");