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
.files
.services
.FileUploader
.FileUploaderBinder
;
73 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
74 import com
.owncloud
.android
.syncadapter
.FileSyncService
;
75 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
76 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
78 import com
.owncloud
.android
.R
;
79 import eu
.alefzero
.webdav
.WebdavClient
;
82 * Displays, what files the user has available in his ownCloud.
84 * @author Bartek Przybylski
88 public class FileDisplayActivity
extends SherlockFragmentActivity
implements
89 OCFileListFragment
.ContainerActivity
, FileDetailFragment
.ContainerActivity
, OnNavigationListener
{
91 private ArrayAdapter
<String
> mDirectories
;
92 private OCFile mCurrentDir
= null
;
93 private OCFile mCurrentFile
= null
;
95 private DataStorageManager mStorageManager
;
96 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
97 private UploadFinishReceiver mUploadFinishReceiver
;
98 private DownloadFinishReceiver mDownloadFinishReceiver
;
99 private FileDownloaderBinder mDownloaderBinder
= null
;
100 private FileUploaderBinder mUploaderBinder
= null
;
101 private ServiceConnection mDownloadConnection
= null
, mUploadConnection
= null
;
103 private OCFileListFragment mFileList
;
105 private boolean mDualPane
;
107 private static final int DIALOG_SETUP_ACCOUNT
= 0;
108 private static final int DIALOG_CREATE_DIR
= 1;
109 private static final int DIALOG_ABOUT_APP
= 2;
110 public static final int DIALOG_SHORT_WAIT
= 3;
111 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 4;
113 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
114 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
116 private static final String TAG
= "FileDisplayActivity";
119 public void onCreate(Bundle savedInstanceState
) {
120 Log
.d(getClass().toString(), "onCreate() start");
121 super.onCreate(savedInstanceState
);
123 /// Load of parameters from received intent
124 mCurrentDir
= getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_FILE
); // no check necessary, mCurrenDir == null if the parameter is not in the intent
125 Account account
= getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_ACCOUNT
);
127 AccountUtils
.setCurrentOwnCloudAccount(this, account
.name
);
129 /// Load of saved instance state: keep this always before initDataFromCurrentAccount()
130 if(savedInstanceState
!= null
) {
131 // TODO - test if savedInstanceState should take precedence over file in the intent ALWAYS (now), NEVER, or SOME TIMES
132 mCurrentDir
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
135 if (!AccountUtils
.accountsAreSetup(this)) {
136 /// no account available: FORCE ACCOUNT CREATION
137 mStorageManager
= null
;
138 createFirstAccount();
140 } else { /// at least an account is available
142 initDataFromCurrentAccount(); // it checks mCurrentDir and mCurrentFile with the current account
146 mUploadConnection
= new ListServiceConnection();
147 mDownloadConnection
= new ListServiceConnection();
148 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
149 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
151 // PIN CODE request ; best location is to decide, let's try this first
152 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
157 /*Intent observer_intent = new Intent(this, FileObserverService.class);
158 observer_intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_INIT_OBSERVED_LIST);
159 startService(observer_intent);
163 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
165 // Drop-down navigation
166 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
167 OCFile currFile
= mCurrentDir
;
168 while(currFile
!= null
&& currFile
.getFileName() != OCFile
.PATH_SEPARATOR
) {
169 mDirectories
.add(currFile
.getFileName());
170 currFile
= mStorageManager
.getFileById(currFile
.getParentId());
172 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
174 // Inflate and set the layout view
175 setContentView(R
.layout
.files
);
176 mFileList
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
177 mDualPane
= (findViewById(R
.id
.file_details_container
) != null
);
179 initFileDetailsInDualPane();
183 ActionBar actionBar
= getSupportActionBar();
184 actionBar
.setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
185 actionBar
.setDisplayHomeAsUpEnabled(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0);
186 actionBar
.setDisplayShowTitleEnabled(false
);
187 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
188 actionBar
.setListNavigationCallbacks(mDirectories
, this);
189 setSupportProgressBarIndeterminateVisibility(false
); // always AFTER setContentView(...) ; to workaround bug in its implementation
191 Log
.d(getClass().toString(), "onCreate() end");
196 * Launches the account creation activity. To use when no ownCloud account is available
198 private void createFirstAccount() {
199 Intent intent
= new Intent(android
.provider
.Settings
.ACTION_ADD_ACCOUNT
);
200 intent
.putExtra(android
.provider
.Settings
.EXTRA_AUTHORITIES
, new String
[] { AccountAuthenticator
.AUTH_TOKEN_TYPE
});
201 startActivity(intent
); // the new activity won't be created until this.onStart() and this.onResume() are finished;
206 * Load of state dependent of the existence of an ownCloud account
208 private void initDataFromCurrentAccount() {
209 /// Storage manager initialization - access to local database
210 mStorageManager
= new FileDataStorageManager(
211 AccountUtils
.getCurrentOwnCloudAccount(this),
212 getContentResolver());
214 /// Check if mCurrentDir is a directory
215 if(mCurrentDir
!= null
&& !mCurrentDir
.isDirectory()) {
216 mCurrentFile
= mCurrentDir
;
217 mCurrentDir
= mStorageManager
.getFileById(mCurrentDir
.getParentId());
220 /// Check if mCurrentDir and mCurrentFile are in the current account, and update them
221 if (mCurrentDir
!= null
) {
222 mCurrentDir
= mStorageManager
.getFileByPath(mCurrentDir
.getRemotePath()); // mCurrentDir == null if it is not in the current account
224 if (mCurrentFile
!= null
) {
225 if (mCurrentFile
.fileExists()) {
226 mCurrentFile
= mStorageManager
.getFileByPath(mCurrentFile
.getRemotePath()); // mCurrentFile == null if it is not in the current account
227 } // 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
230 /// Default to root if mCurrentDir was not found
231 if (mCurrentDir
== null
) {
232 mCurrentDir
= mStorageManager
.getFileByPath("/"); // will be NULL if the database was never synchronized
237 private void initFileDetailsInDualPane() {
238 if (mDualPane
&& getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
) == null
) {
239 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
240 if (mCurrentFile
!= null
) {
241 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(mCurrentFile
, AccountUtils
.getCurrentOwnCloudAccount(this)), FileDetailFragment
.FTAG
); // empty FileDetailFragment
244 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
); // empty FileDetailFragment
246 transaction
.commit();
252 public void onDestroy() {
254 if (mDownloadConnection
!= null
)
255 unbindService(mDownloadConnection
);
256 if (mUploadConnection
!= null
)
257 unbindService(mUploadConnection
);
262 public boolean onCreateOptionsMenu(Menu menu
) {
263 MenuInflater inflater
= getSherlock().getMenuInflater();
264 inflater
.inflate(R
.menu
.menu
, menu
);
269 public boolean onOptionsItemSelected(MenuItem item
) {
270 boolean retval
= true
;
271 switch (item
.getItemId()) {
272 case R
.id
.createDirectoryItem
: {
273 showDialog(DIALOG_CREATE_DIR
);
276 case R
.id
.startSync
: {
277 ContentResolver
.cancelSync(null
, AccountAuthenticator
.AUTH_TOKEN_TYPE
); // cancel the current synchronizations of any ownCloud account
278 Bundle bundle
= new Bundle();
279 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
280 ContentResolver
.requestSync(
281 AccountUtils
.getCurrentOwnCloudAccount(this),
282 AccountAuthenticator
.AUTH_TOKEN_TYPE
, bundle
);
285 case R
.id
.action_upload
: {
286 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
289 case R
.id
.action_settings
: {
290 Intent settingsIntent
= new Intent(this, Preferences
.class);
291 startActivity(settingsIntent
);
294 case R
.id
.about_app
: {
295 showDialog(DIALOG_ABOUT_APP
);
298 case android
.R
.id
.home
: {
299 if(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0){
311 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
312 int i
= itemPosition
;
316 // the next operation triggers a new call to this method, but it's necessary to
317 // ensure that the name exposed in the action bar is the current directory when the
318 // user selected it in the navigation list
319 if (itemPosition
!= 0)
320 getSupportActionBar().setSelectedNavigationItem(0);
325 * Called, when the user selected something for uploading
327 public void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
329 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& resultCode
== RESULT_OK
) {
330 requestSimpleUpload(data
);
332 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& resultCode
== RESULT_OK
) {
333 requestMultipleUpload(data
);
338 private void requestMultipleUpload(Intent data
) {
339 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
340 if (filePaths
!= null
) {
341 String
[] remotePaths
= new String
[filePaths
.length
];
342 String remotePathBase
= "";
343 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
344 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
346 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
347 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
348 for (int j
= 0; j
< remotePaths
.length
; j
++) {
349 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
352 Intent i
= new Intent(this, FileUploader
.class);
353 i
.putExtra(FileUploader
.KEY_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
354 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
355 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
356 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
360 Log
.d("FileDisplay", "User clicked on 'Update' with no selection");
361 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
368 private void requestSimpleUpload(Intent data
) {
369 String filepath
= null
;
371 Uri selectedImageUri
= data
.getData();
373 String filemanagerstring
= selectedImageUri
.getPath();
374 String selectedImagePath
= getPath(selectedImageUri
);
376 if (selectedImagePath
!= null
)
377 filepath
= selectedImagePath
;
379 filepath
= filemanagerstring
;
381 } catch (Exception e
) {
382 Log
.e("FileDisplay", "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
386 if (filepath
== null
) {
387 Log
.e("FileDisplay", "Couldnt resolve path to file");
388 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
394 Intent i
= new Intent(this, FileUploader
.class);
395 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
396 AccountUtils
.getCurrentOwnCloudAccount(this));
397 String remotepath
= new String();
398 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
399 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
401 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
402 remotepath
+= OCFile
.PATH_SEPARATOR
;
403 remotepath
+= new File(filepath
).getName();
405 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
406 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
407 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
413 public void onBackPressed() {
414 if (mDirectories
.getCount() <= 1) {
419 mFileList
.onNavigateUp();
420 mCurrentDir
= mFileList
.getCurrentFile();
423 // Resets the FileDetailsFragment on Tablets so that it always displays
424 FileDetailFragment fileDetails
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
425 if (fileDetails
!= null
&& !fileDetails
.isEmpty()) {
426 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
427 transaction
.remove(fileDetails
);
428 transaction
.add(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
);
429 transaction
.commit();
433 if(mCurrentDir
.getParentId() == 0){
434 ActionBar actionBar
= getSupportActionBar();
435 actionBar
.setDisplayHomeAsUpEnabled(false
);
440 protected void onSaveInstanceState(Bundle outState
) {
441 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
442 Log
.d(getClass().toString(), "onSaveInstanceState() start");
443 super.onSaveInstanceState(outState
);
444 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mCurrentDir
);
446 FileDetailFragment fragment
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
447 if (fragment
!= null
) {
448 OCFile file
= fragment
.getDisplayedFile();
450 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, file
);
454 Log
.d(getClass().toString(), "onSaveInstanceState() end");
458 protected void onResume() {
459 Log
.d(getClass().toString(), "onResume() start");
462 if (AccountUtils
.accountsAreSetup(this)) {
464 if (mStorageManager
== null
) {
465 // this is necessary for handling the come back to FileDisplayActivity when the first ownCloud account is created
466 initDataFromCurrentAccount();
468 initFileDetailsInDualPane();
472 // Listen for sync messages
473 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncService
.SYNC_MESSAGE
);
474 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
475 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
477 // Listen for upload messages
478 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
479 mUploadFinishReceiver
= new UploadFinishReceiver();
480 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
482 // Listen for download messages
483 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
484 mDownloadFinishReceiver
= new DownloadFinishReceiver();
485 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
487 // List current directory
488 mFileList
.listDirectory(mCurrentDir
); // TODO we should find the way to avoid the need of this (maybe it's not necessary yet; to check)
492 mStorageManager
= null
; // an invalid object will be there if all the ownCloud accounts are removed
493 showDialog(DIALOG_SETUP_ACCOUNT
);
496 Log
.d(getClass().toString(), "onResume() end");
501 protected void onPause() {
502 Log
.d(getClass().toString(), "onPause() start");
504 if (mSyncBroadcastReceiver
!= null
) {
505 unregisterReceiver(mSyncBroadcastReceiver
);
506 mSyncBroadcastReceiver
= null
;
508 if (mUploadFinishReceiver
!= null
) {
509 unregisterReceiver(mUploadFinishReceiver
);
510 mUploadFinishReceiver
= null
;
512 if (mDownloadFinishReceiver
!= null
) {
513 unregisterReceiver(mDownloadFinishReceiver
);
514 mDownloadFinishReceiver
= null
;
516 if (!AccountUtils
.accountsAreSetup(this)) {
517 dismissDialog(DIALOG_SETUP_ACCOUNT
);
520 Log
.d(getClass().toString(), "onPause() end");
524 protected Dialog
onCreateDialog(int id
) {
525 Dialog dialog
= null
;
526 AlertDialog
.Builder builder
;
528 case DIALOG_SETUP_ACCOUNT
: {
529 builder
= new AlertDialog
.Builder(this);
530 builder
.setTitle(R
.string
.main_tit_accsetup
);
531 builder
.setMessage(R
.string
.main_wrn_accsetup
);
532 builder
.setCancelable(false
);
533 builder
.setPositiveButton(android
.R
.string
.ok
, new OnClickListener() {
534 public void onClick(DialogInterface dialog
, int which
) {
535 createFirstAccount();
539 builder
.setNegativeButton(R
.string
.common_exit
, new OnClickListener() {
540 public void onClick(DialogInterface dialog
, int which
) {
545 //builder.setNegativeButton(android.R.string.cancel, this);
546 dialog
= builder
.create();
549 case DIALOG_ABOUT_APP
: {
550 builder
= new AlertDialog
.Builder(this);
551 builder
.setTitle(getString(R
.string
.about_title
));
554 pkg
= getPackageManager().getPackageInfo(getPackageName(), 0);
555 builder
.setMessage(String
.format(getString(R
.string
.about_message
), pkg
.versionName
));
556 builder
.setIcon(android
.R
.drawable
.ic_menu_info_details
);
557 dialog
= builder
.create();
558 } catch (NameNotFoundException e
) {
561 Log
.e(TAG
, "Error while showing about dialog", e
);
565 case DIALOG_CREATE_DIR
: {
566 builder
= new Builder(this);
567 final EditText dirNameInput
= new EditText(getBaseContext());
568 builder
.setView(dirNameInput
);
569 builder
.setTitle(R
.string
.uploader_info_dirname
);
570 int typed_color
= getResources().getColor(R
.color
.setup_text_typed
);
571 dirNameInput
.setTextColor(typed_color
);
572 builder
.setPositiveButton(android
.R
.string
.ok
,
573 new OnClickListener() {
574 public void onClick(DialogInterface dialog
, int which
) {
575 String directoryName
= dirNameInput
.getText().toString();
576 if (directoryName
.trim().length() == 0) {
581 // Figure out the path where the dir needs to be created
583 if (mCurrentDir
== null
) {
584 // this is just a patch; we should ensure that mCurrentDir never is null
585 if (!mStorageManager
.fileExists(OCFile
.PATH_SEPARATOR
)) {
586 OCFile file
= new OCFile(OCFile
.PATH_SEPARATOR
);
587 mStorageManager
.saveFile(file
);
589 mCurrentDir
= mStorageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
);
591 path
= FileDisplayActivity
.this.mCurrentDir
.getRemotePath();
594 path
+= directoryName
+ OCFile
.PATH_SEPARATOR
;
595 Thread thread
= new Thread(new DirectoryCreator(path
, AccountUtils
.getCurrentOwnCloudAccount(FileDisplayActivity
.this), new Handler()));
600 showDialog(DIALOG_SHORT_WAIT
);
603 builder
.setNegativeButton(R
.string
.common_cancel
,
604 new OnClickListener() {
605 public void onClick(DialogInterface dialog
, int which
) {
609 dialog
= builder
.create();
612 case DIALOG_SHORT_WAIT
: {
613 ProgressDialog working_dialog
= new ProgressDialog(this);
614 working_dialog
.setMessage(getResources().getString(
615 R
.string
.wait_a_moment
));
616 working_dialog
.setIndeterminate(true
);
617 working_dialog
.setCancelable(false
);
618 dialog
= working_dialog
;
621 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
622 final String
[] items
= { getString(R
.string
.actionbar_upload_files
),
623 getString(R
.string
.actionbar_upload_from_apps
) };
624 builder
= new AlertDialog
.Builder(this);
625 builder
.setTitle(R
.string
.actionbar_upload
);
626 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
627 public void onClick(DialogInterface dialog
, int item
) {
630 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
631 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
633 // TODO create and handle new fragment LocalFileListFragment
635 } else if (item
== 1) {
636 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
637 action
= action
.setType("*/*")
638 .addCategory(Intent
.CATEGORY_OPENABLE
);
639 startActivityForResult(
640 Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
641 ACTION_SELECT_CONTENT_FROM_APPS
);
645 dialog
= builder
.create();
657 * Translates a content URI of an image to a physical path
659 * @param uri The URI to resolve
660 * @return The path to the image or null if it could not be found
662 public String
getPath(Uri uri
) {
663 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
664 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
665 if (cursor
!= null
) {
666 int column_index
= cursor
667 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
668 cursor
.moveToFirst();
669 return cursor
.getString(column_index
);
675 * Pushes a directory to the drop down list
676 * @param directory to push
677 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
679 public void pushDirname(OCFile directory
) {
680 if(!directory
.isDirectory()){
681 throw new IllegalArgumentException("Only directories may be pushed!");
683 mDirectories
.insert(directory
.getFileName(), 0);
684 mCurrentDir
= directory
;
688 * Pops a directory name from the drop down list
689 * @return True, unless the stack is empty
691 public boolean popDirname() {
692 mDirectories
.remove(mDirectories
.getItem(0));
693 return !mDirectories
.isEmpty();
696 private class DirectoryCreator
implements Runnable
{
697 private String mTargetPath
;
698 private Account mAccount
;
699 private Handler mHandler
;
701 public DirectoryCreator(String targetPath
, Account account
, Handler handler
) {
702 mTargetPath
= targetPath
;
709 WebdavClient wdc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getApplicationContext());
710 boolean created
= wdc
.createDirectory(mTargetPath
);
712 mHandler
.post(new Runnable() {
715 dismissDialog(DIALOG_SHORT_WAIT
);
717 // Save new directory in local database
718 OCFile newDir
= new OCFile(mTargetPath
);
719 newDir
.setMimetype("DIR");
720 newDir
.setParentId(mCurrentDir
.getFileId());
721 mStorageManager
.saveFile(newDir
);
723 // Display the new folder right away
724 mFileList
.listDirectory();
729 mHandler
.post(new Runnable() {
732 dismissDialog(DIALOG_SHORT_WAIT
);
734 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
737 } catch (NotFoundException e
) {
738 Log
.e(TAG
, "Error while trying to show fail message " , e
);
747 // Custom array adapter to override text colors
748 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
750 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
754 public View
getView(int position
, View convertView
, ViewGroup parent
) {
755 View v
= super.getView(position
, convertView
, parent
);
757 ((TextView
) v
).setTextColor(getResources().getColorStateList(
758 android
.R
.color
.white
));
762 public View
getDropDownView(int position
, View convertView
,
764 View v
= super.getDropDownView(position
, convertView
, parent
);
766 ((TextView
) v
).setTextColor(getResources().getColorStateList(
767 android
.R
.color
.white
));
774 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
776 * {@link BroadcastReceiver} to enable syncing feedback in UI
779 public void onReceive(Context context
, Intent intent
) {
780 boolean inProgress
= intent
.getBooleanExtra(
781 FileSyncService
.IN_PROGRESS
, false
);
782 String accountName
= intent
783 .getStringExtra(FileSyncService
.ACCOUNT_NAME
);
785 Log
.d("FileDisplay", "sync of account " + accountName
786 + " is in_progress: " + inProgress
);
788 if (accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
)) {
790 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
);
792 boolean fillBlankRoot
= false
;
793 if (mCurrentDir
== null
) {
794 mCurrentDir
= mStorageManager
.getFileByPath("/");
795 fillBlankRoot
= (mCurrentDir
!= null
);
798 if ((synchFolderRemotePath
!= null
&& mCurrentDir
!= null
&& (mCurrentDir
.getRemotePath().equals(synchFolderRemotePath
)))
801 mCurrentDir
= getStorageManager().getFileByPath(synchFolderRemotePath
);
802 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager()
803 .findFragmentById(R
.id
.fileList
);
804 if (fileListFragment
!= null
) {
805 fileListFragment
.listDirectory(mCurrentDir
);
809 setSupportProgressBarIndeterminateVisibility(inProgress
);
816 private class UploadFinishReceiver
extends BroadcastReceiver
{
818 * Once the file upload has finished -> update view
819 * @author David A. Velasco
820 * {@link BroadcastReceiver} to enable upload feedback in UI
823 public void onReceive(Context context
, Intent intent
) {
824 long parentDirId
= intent
.getLongExtra(FileUploader
.EXTRA_PARENT_DIR_ID
, -1);
825 OCFile parentDir
= mStorageManager
.getFileById(parentDirId
);
826 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
828 if (accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
) &&
830 ( (mCurrentDir
== null
&& parentDir
.getFileName().equals("/")) ||
831 parentDir
.equals(mCurrentDir
)
834 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
835 if (fileListFragment
!= null
) {
836 fileListFragment
.listDirectory();
845 * Once the file download has finished -> update view
847 private class DownloadFinishReceiver
extends BroadcastReceiver
{
849 public void onReceive(Context context
, Intent intent
) {
850 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
851 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
853 if (accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
) &&
854 mCurrentDir
!= null
&& mCurrentDir
.getFileId() == mStorageManager
.getFileByPath(downloadedRemotePath
).getParentId()) {
855 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
856 if (fileListFragment
!= null
) {
857 fileListFragment
.listDirectory();
870 public DataStorageManager
getStorageManager() {
871 return mStorageManager
;
879 public void onDirectoryClick(OCFile directory
) {
880 pushDirname(directory
);
881 ActionBar actionBar
= getSupportActionBar();
882 actionBar
.setDisplayHomeAsUpEnabled(true
);
885 // Resets the FileDetailsFragment on Tablets so that it always displays
886 FileDetailFragment fileDetails
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
887 if (fileDetails
!= null
&& !fileDetails
.isEmpty()) {
888 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
889 transaction
.remove(fileDetails
);
890 transaction
.add(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
);
891 transaction
.commit();
901 public void onFileClick(OCFile file
) {
903 // If we are on a large device -> update fragment
905 // 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'
906 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
907 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(file
, AccountUtils
.getCurrentOwnCloudAccount(this)), FileDetailFragment
.FTAG
);
908 transaction
.setTransition(FragmentTransaction
.TRANSIT_FRAGMENT_FADE
);
909 transaction
.commit();
911 } else { // small or medium screen device -> new Activity
912 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
913 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, file
);
914 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
915 startActivity(showDetailsIntent
);
924 public OCFile
getInitialDirectory() {
933 public void onFileStateChanged() {
934 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
935 if (fileListFragment
!= null
) {
936 fileListFragment
.listDirectory();
945 public FileDownloaderBinder
getFileDownloaderBinder() {
946 return mDownloaderBinder
;
954 public FileUploaderBinder
getFileUploaderBinder() {
955 return mUploaderBinder
;
959 /** Defines callbacks for service binding, passed to bindService() */
960 private class ListServiceConnection
implements ServiceConnection
{
963 public void onServiceConnected(ComponentName component
, IBinder service
) {
964 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
965 Log
.d(TAG
, "Download service connected");
966 mDownloaderBinder
= (FileDownloaderBinder
) service
;
967 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
968 Log
.d(TAG
, "Upload service connected");
969 mUploaderBinder
= (FileUploaderBinder
) service
;
973 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
974 if (mFileList
!= null
)
975 mFileList
.listDirectory();
977 FileDetailFragment fragment
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
978 if (fragment
!= null
)
979 fragment
.updateFileDetails();
984 public void onServiceDisconnected(ComponentName component
) {
985 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
986 Log
.d(TAG
, "Download service disconnected");
987 mDownloaderBinder
= null
;
988 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
989 Log
.d(TAG
, "Upload service disconnected");
990 mUploaderBinder
= null
;
998 * Launch an intent to request the PIN code to the user before letting him use the app
1000 private void requestPinCode() {
1001 boolean pinStart
= false
;
1002 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1003 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1005 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1006 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");