Quick patch to fix operations not ready for HTTPS
[pub/Android/ownCloud.git] / src / eu / alefzero / owncloud / ui / activity / FileDisplayActivity.java
index bdc146c..163fea4 100644 (file)
@@ -19,8 +19,7 @@
 package eu.alefzero.owncloud.ui.activity;\r
 \r
 import java.io.File;\r
-import java.net.URLDecoder;\r
-import java.net.URLEncoder;\r
+import java.util.ArrayList;\r
 \r
 import android.accounts.Account;\r
 import android.accounts.AccountManager;\r
@@ -34,16 +33,22 @@ import android.content.DialogInterface;
 import android.content.DialogInterface.OnClickListener;\r
 import android.content.Intent;\r
 import android.content.IntentFilter;\r
+import android.content.SharedPreferences;\r
+import android.content.pm.PackageInfo;\r
+import android.content.pm.PackageManager.NameNotFoundException;\r
 import android.database.Cursor;\r
 import android.net.Uri;\r
 import android.os.Bundle;\r
+import android.preference.PreferenceManager;\r
 import android.provider.MediaStore;\r
+import android.support.v4.app.FragmentTransaction;\r
 import android.util.Log;\r
 import android.view.View;\r
 import android.view.ViewGroup;\r
 import android.widget.ArrayAdapter;\r
 import android.widget.EditText;\r
 import android.widget.TextView;\r
+import android.widget.Toast;\r
 \r
 import com.actionbarsherlock.app.ActionBar;\r
 import com.actionbarsherlock.app.ActionBar.OnNavigationListener;\r
@@ -54,15 +59,17 @@ import com.actionbarsherlock.view.MenuItem;
 import com.actionbarsherlock.view.Window;\r
 \r
 import eu.alefzero.owncloud.AccountUtils;\r
+import eu.alefzero.owncloud.CrashHandler;\r
 import eu.alefzero.owncloud.R;\r
 import eu.alefzero.owncloud.authenticator.AccountAuthenticator;\r
 import eu.alefzero.owncloud.datamodel.DataStorageManager;\r
 import eu.alefzero.owncloud.datamodel.FileDataStorageManager;\r
 import eu.alefzero.owncloud.datamodel.OCFile;\r
+import eu.alefzero.owncloud.files.services.FileDownloader;\r
 import eu.alefzero.owncloud.files.services.FileUploader;\r
 import eu.alefzero.owncloud.syncadapter.FileSyncService;\r
+import eu.alefzero.owncloud.ui.fragment.FileDetailFragment;\r
 import eu.alefzero.owncloud.ui.fragment.FileListFragment;\r
-import eu.alefzero.owncloud.utils.OwnCloudVersion;\r
 import eu.alefzero.webdav.WebdavClient;\r
 \r
 /**\r
@@ -73,112 +80,87 @@ import eu.alefzero.webdav.WebdavClient;
  */\r
 \r
 public class FileDisplayActivity extends SherlockFragmentActivity implements\r
-        OnNavigationListener, OnClickListener {\r
+    FileListFragment.ContainerActivity, OnNavigationListener, OnClickListener, android.view.View.OnClickListener  {\r
+    \r
     private ArrayAdapter<String> mDirectories;\r
-    private DataStorageManager mStorageManager;\r
+    private OCFile mCurrentDir;\r
     private String[] mDirs = null;\r
 \r
-    private SyncBroadcastReceiver syncBroadcastRevceiver;\r
-\r
-    private static final String KEY_DIR = "DIR";\r
+    private DataStorageManager mStorageManager;\r
+    private SyncBroadcastReceiver mSyncBroadcastReceiver;\r
+    private UploadFinishReceiver mUploadFinishReceiver;\r
+    private DownloadFinishReceiver mDownloadFinishReceiver;\r
+    \r
+    private View mLayoutView = null;\r
+    private FileListFragment mFileList;\r
+    \r
+    private boolean mDualPane;\r
+    \r
+    private boolean mForcedLoginToCreateFirstAccount = false;\r
+    \r
+    private static final String KEY_DIR_ARRAY = "DIR_ARRAY";\r
+    private static final String KEY_CURRENT_DIR = "DIR";\r
     \r
     private static final int DIALOG_SETUP_ACCOUNT = 0;\r
     private static final int DIALOG_CREATE_DIR = 1;\r
-\r
-    private static final int REQUEST_ACCOUNT_SETUP = 0;\r
+    private static final int DIALOG_ABOUT_APP = 2;\r
+    \r
     private static final int ACTION_SELECT_FILE = 1;\r
-\r
-    public void pushPath(String path) {\r
-        mDirectories.insert(path, 0);\r
-    }\r
-\r
-    public boolean popPath() {\r
-        mDirectories.remove(mDirectories.getItem(0));\r
-        return !mDirectories.isEmpty();\r
-    }\r
-\r
+    \r
     @Override\r
-    protected Dialog onCreateDialog(int id) {\r
-        Dialog dialog;\r
-        AlertDialog.Builder builder;\r
-        switch (id) {\r
-        case DIALOG_SETUP_ACCOUNT:\r
-            builder = new AlertDialog.Builder(this);\r
-            builder.setTitle(R.string.main_tit_accsetup);\r
-            builder.setMessage(R.string.main_wrn_accsetup);\r
-            builder.setCancelable(false);\r
-            builder.setPositiveButton(android.R.string.ok, this);\r
-            builder.setNegativeButton(android.R.string.cancel, this);\r
-            dialog = builder.create();\r
-            break;\r
-        case DIALOG_CREATE_DIR: {\r
-            builder = new Builder(this);\r
-            final EditText dirName = new EditText(getBaseContext());\r
-            final Account a = AccountUtils.getCurrentOwnCloudAccount(this);\r
-            builder.setView(dirName);\r
-            builder.setTitle(R.string.uploader_info_dirname);\r
-            int typed_color = getResources().getColor(R.color.setup_text_typed);\r
-            dirName.setTextColor(typed_color);\r
-\r
-            builder.setPositiveButton(android.R.string.ok,\r
-                    new OnClickListener() {\r
-                        public void onClick(DialogInterface dialog, int which) {\r
-                            String s = dirName.getText().toString();\r
-                            if (s.trim().length() == 0) {\r
-                                dialog.cancel();\r
-                                return;\r
-                            }\r
+    public void onCreate(Bundle savedInstanceState) {\r
+        Log.i(getClass().toString(), "onCreate() start");\r
+        super.onCreate(savedInstanceState);\r
 \r
-                            String path = "";\r
-                            for (int i = mDirectories.getCount() - 2; i >= 0; --i) {\r
-                                path += "/" + mDirectories.getItem(i);\r
-                            }\r
-                            OCFile parent = mStorageManager.getFileByPath(path\r
-                                    + "/");\r
-                            path += s + "/";\r
-                            Thread thread = new Thread(new DirectoryCreator(\r
-                                    path, a));\r
-                            thread.start();\r
+        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);\r
 \r
-                            OCFile new_file = new OCFile(path);\r
-                            new_file.setMimetype("DIR");\r
-                            new_file.setParentId(parent.getParentId());\r
-                            mStorageManager.saveFile(new_file);\r
+        Thread.setDefaultUncaughtExceptionHandler(new CrashHandler(getApplicationContext()));\r
 \r
-                            dialog.dismiss();\r
-                        }\r
-                    });\r
-            builder.setNegativeButton(R.string.common_cancel,\r
-                    new OnClickListener() {\r
-                        public void onClick(DialogInterface dialog, int which) {\r
-                            dialog.cancel();\r
-                        }\r
-                    });\r
-            dialog = builder.create();\r
-            break;\r
+        if(savedInstanceState != null) {\r
+            mDirs = savedInstanceState.getStringArray(KEY_DIR_ARRAY);\r
+            mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);\r
+            mDirectories.add(OCFile.PATH_SEPARATOR);\r
+            if (mDirs != null)\r
+                for (String s : mDirs)\r
+                    mDirectories.insert(s, 0);\r
+            mCurrentDir = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_FILE);\r
         }\r
-        default:\r
-            dialog = null;\r
+        \r
+        mLayoutView = getLayoutInflater().inflate(R.layout.files, null);  // always inflate this at onCreate() ; just once!\r
+        \r
+        if (AccountUtils.accountsAreSetup(this)) {\r
+            \r
+            initDelayedTilAccountAvailabe();\r
+            \r
+            // PIN CODE request ;  best location is to decide, let's try this first\r
+            //if (savedInstanceState == null) {\r
+            if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {\r
+                requestPinCode();\r
+            }\r
+            \r
+            \r
+        } else {\r
+            \r
+            setContentView(R.layout.no_account_available);\r
+            getSupportActionBar().setNavigationMode(ActionBar.DISPLAY_SHOW_TITLE);\r
+            findViewById(R.id.setup_account).setOnClickListener(this);\r
+\r
+            setSupportProgressBarIndeterminateVisibility(false);\r
+\r
+            Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);\r
+            intent.putExtra(android.provider.Settings.EXTRA_AUTHORITIES, new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });\r
+            startActivity(intent);  // although the code is here, the activity won't be created until this.onStart() and this.onResume() are finished;\r
+            mForcedLoginToCreateFirstAccount = true;\r
         }\r
-\r
-        return dialog;\r
+        \r
+        Log.i(getClass().toString(), "onCreate() end");\r
     }\r
 \r
     @Override\r
-    public void onCreate(Bundle savedInstanceState) {\r
-        super.onCreate(savedInstanceState);\r
-\r
-        if (!accountsAreSetup()) {\r
-            showDialog(DIALOG_SETUP_ACCOUNT);\r
-            return;\r
-        }\r
-\r
-        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);\r
-        setProgressBarIndeterminateVisibility(false);\r
-        // if (getSupportFragmentManager().findFragmentById(R.id.fileList) ==\r
-        // null)\r
-        setContentView(R.layout.files);\r
-\r
+    public boolean onCreateOptionsMenu(Menu menu) {\r
+        MenuInflater inflater = getSherlock().getMenuInflater();\r
+            inflater.inflate(R.menu.menu, menu);\r
+            return true;\r
     }\r
 \r
     @Override\r
@@ -190,6 +172,7 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
                 break;\r
             }\r
             case R.id.startSync: {\r
+                ContentResolver.cancelSync(null, "org.owncloud");   // cancel the current synchronizations of any ownCloud account\r
                 Bundle bundle = new Bundle();\r
                 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);\r
                 ContentResolver.requestSync(\r
@@ -206,11 +189,19 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
                         ACTION_SELECT_FILE);\r
                 break;\r
             }\r
-    \r
+            case R.id.action_settings: {\r
+                Intent settingsIntent = new Intent(this, Preferences.class);\r
+                startActivity(settingsIntent);\r
+                break;\r
+            }\r
+            case R.id.about_app : {\r
+                showDialog(DIALOG_ABOUT_APP);\r
+                break;\r
+            }\r
             case android.R.id.home: {\r
-                Intent i = new Intent(this, AccountSelectActivity.class);\r
-                startActivity(i);\r
-                finish();\r
+                if(mCurrentDir != null && mCurrentDir.getParentId() != 0){\r
+                    onBackPressed(); \r
+                }\r
                 break;\r
             }\r
             default:\r
@@ -220,122 +211,339 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
     }\r
 \r
     @Override\r
-    public void onBackPressed() {\r
-        if (mDirectories.getCount() == 1) {\r
-            finish();\r
-            return;\r
+    public boolean onNavigationItemSelected(int itemPosition, long itemId) {\r
+        int i = itemPosition;\r
+        while (i-- != 0) {\r
+            onBackPressed();\r
         }\r
-        popPath();\r
-        ((FileListFragment) getSupportFragmentManager().findFragmentById(\r
-                R.id.fileList)).onNavigateUp();\r
+        return true;\r
     }\r
 \r
-    @Override\r
-    public boolean onCreateOptionsMenu(Menu menu) {\r
-        MenuInflater inflater = getSherlock().getMenuInflater();\r
-        inflater.inflate(R.menu.menu, menu);\r
-        return true;\r
+    /**\r
+     * Called, when the user selected something for uploading\r
+     */\r
+    public void onActivityResult(int requestCode, int resultCode, Intent data) {\r
+        if (requestCode == ACTION_SELECT_FILE) {\r
+            if (resultCode == RESULT_OK) {\r
+                String filepath = null;\r
+                try {\r
+                    Uri selectedImageUri = data.getData();\r
+    \r
+                    String filemanagerstring = selectedImageUri.getPath();\r
+                    String selectedImagePath = getPath(selectedImageUri);\r
+    \r
+                    if (selectedImagePath != null)\r
+                        filepath = selectedImagePath;\r
+                    else\r
+                        filepath = filemanagerstring;\r
+                    \r
+                } catch (Exception e) {\r
+                    Log.e("FileDisplay", "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);\r
+                    e.printStackTrace();\r
+                    \r
+                } finally {\r
+                    if (filepath == null) {\r
+                        Log.e("FileDisplay", "Couldnt resolve path to file");\r
+                        Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);\r
+                        t.show();\r
+                        return;\r
+                    }\r
+                }\r
+    \r
+                Intent i = new Intent(this, FileUploader.class);\r
+                i.putExtra(FileUploader.KEY_ACCOUNT,\r
+                        AccountUtils.getCurrentOwnCloudAccount(this));\r
+                String remotepath = new String();\r
+                for (int j = mDirectories.getCount() - 2; j >= 0; --j) {\r
+                    remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);\r
+                }\r
+                if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))\r
+                    remotepath += OCFile.PATH_SEPARATOR;\r
+                remotepath += new File(filepath).getName();\r
+    \r
+                i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);\r
+                i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);\r
+                i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);\r
+                startService(i);\r
+            }\r
+            \r
+        }/* dvelasco: WIP - not working as expected ... yet :)\r
+             else if (requestCode == ACTION_CREATE_FIRST_ACCOUNT) {\r
+            if (resultCode != RESULT_OK) {\r
+                finish();   // the user cancelled the AuthenticatorActivity\r
+            }\r
+        }*/\r
     }\r
 \r
     @Override\r
-    protected void onRestoreInstanceState(Bundle savedInstanceState) {\r
-        super.onRestoreInstanceState(savedInstanceState);\r
-        // Check, if there are ownCloud accounts\r
-        if (!accountsAreSetup()) {\r
-            showDialog(DIALOG_SETUP_ACCOUNT);\r
+    public void onBackPressed() {\r
+        if (mDirectories == null || mDirectories.getCount() <= 1) {\r
+            finish();\r
+            return;\r
         }\r
-        mDirs = savedInstanceState.getStringArray(KEY_DIR);\r
-        mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);\r
-        mDirectories.add("/");\r
-        if (mDirs != null)\r
-            for (String s : mDirs)\r
-                mDirectories.insert(s, 0);\r
+        popDirname();\r
+        mFileList.onNavigateUp();\r
+        mCurrentDir = mFileList.getCurrentFile();\r
+        \r
+        if(mCurrentDir.getParentId() == 0){\r
+            ActionBar actionBar = getSupportActionBar(); \r
+            actionBar.setDisplayHomeAsUpEnabled(false);\r
+        } \r
     }\r
-    \r
+\r
     @Override\r
     protected void onSaveInstanceState(Bundle outState) {\r
+        // responsability of restore is prefered in onCreate() before than in onRestoreInstanceState when there are Fragments involved\r
+        Log.i(getClass().toString(), "onSaveInstanceState() start");\r
         super.onSaveInstanceState(outState);\r
-        if(mDirectories != null){\r
+        if(mDirectories != null && mDirectories.getCount() != 0){\r
             mDirs = new String[mDirectories.getCount()-1];\r
             for (int j = mDirectories.getCount() - 2, i = 0; j >= 0; --j, ++i) {\r
                 mDirs[i] = mDirectories.getItem(j);\r
             }\r
         }\r
+        outState.putStringArray(KEY_DIR_ARRAY, mDirs);\r
+        outState.putParcelable(FileDetailFragment.EXTRA_FILE, mCurrentDir);\r
+        Log.i(getClass().toString(), "onSaveInstanceState() end");\r
     }\r
 \r
     @Override\r
     protected void onResume() {\r
+        Log.i(getClass().toString(), "onResume() start");\r
         super.onResume();\r
-        if (!accountsAreSetup()) {\r
-            showDialog(DIALOG_SETUP_ACCOUNT);\r
-            return;\r
-        }\r
-\r
-        IntentFilter f = new IntentFilter(FileSyncService.SYNC_MESSAGE);\r
-        syncBroadcastRevceiver = new SyncBroadcastReceiver();\r
-        registerReceiver(syncBroadcastRevceiver, f);\r
-\r
-        mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);\r
-        mDirectories.add("/");\r
-        if (mDirs != null) {\r
-            for (String s : mDirs)\r
-                mDirectories.insert(s, 0);\r
-            FileListFragment fileListFramgent = (FileListFragment) getSupportFragmentManager()\r
-                    .findFragmentById(R.id.fileList);\r
-            if (fileListFramgent != null) fileListFramgent.populateFileList();\r
-        }\r
 \r
-        mStorageManager = new FileDataStorageManager(\r
-                AccountUtils.getCurrentOwnCloudAccount(this),\r
-                getContentResolver());\r
-        ActionBar action_bar = getSupportActionBar();\r
-        action_bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);\r
-        action_bar.setDisplayShowTitleEnabled(false);\r
-        action_bar.setListNavigationCallbacks(mDirectories, this);\r
-        action_bar.setDisplayHomeAsUpEnabled(true);\r
-    }\r
+        if (AccountUtils.accountsAreSetup(this)) {\r
+         // at least an account exist: normal operation\r
+            \r
+            // set the layout only if it couldn't be set in onCreate\r
+            if (mForcedLoginToCreateFirstAccount) {\r
+                initDelayedTilAccountAvailabe();\r
+                mForcedLoginToCreateFirstAccount = false;\r
+            }\r
 \r
-    public void onActivityResult(int requestCode, int resultCode, Intent data) {\r
-        Log.e("ASD", requestCode + " " + resultCode);\r
-        if (resultCode == RESULT_OK) {\r
-            if (requestCode == ACTION_SELECT_FILE) {\r
-                Uri selectedImageUri = data.getData();\r
-\r
-                String filemanagerstring = selectedImageUri.getPath();\r
-                String selectedImagePath = getPath(selectedImageUri);\r
-                String filepath;\r
-\r
-                if (selectedImagePath != null)\r
-                    filepath = selectedImagePath;\r
-                else\r
-                    filepath = filemanagerstring;\r
-\r
-                if (filepath == null) {\r
-                    Log.e("FileDisplay", "Couldnt resolve path to file");\r
-                    return;\r
+            // Listen for sync messages\r
+            IntentFilter syncIntentFilter = new IntentFilter(FileSyncService.SYNC_MESSAGE);\r
+            mSyncBroadcastReceiver = new SyncBroadcastReceiver();\r
+            registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);\r
+            \r
+            // Listen for upload messages\r
+            IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);\r
+            mUploadFinishReceiver = new UploadFinishReceiver();\r
+            registerReceiver(mUploadFinishReceiver, uploadIntentFilter);\r
+            \r
+            // Listen for download messages\r
+            IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.DOWNLOAD_FINISH_MESSAGE);\r
+            mDownloadFinishReceiver = new DownloadFinishReceiver();\r
+            registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);\r
+        \r
+            // Storage manager initialization\r
+            mStorageManager = new FileDataStorageManager(\r
+                    AccountUtils.getCurrentOwnCloudAccount(this),\r
+                    getContentResolver());\r
+        \r
+            // File list fragments   \r
+            mFileList = (FileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);\r
+            \r
+            \r
+            // Figure out what directory to list. \r
+            // Priority: Intent (here), savedInstanceState (onCreate), root dir (dir is null)\r
+            if(getIntent().hasExtra(FileDetailFragment.EXTRA_FILE)){\r
+                mCurrentDir = (OCFile) getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE);\r
+                if(mCurrentDir != null && !mCurrentDir.isDirectory()){\r
+                    mCurrentDir = mStorageManager.getFileById(mCurrentDir.getParentId());\r
                 }\r
-\r
-                Intent i = new Intent(this, FileUploader.class);\r
-                i.putExtra(FileUploader.KEY_ACCOUNT,\r
-                        AccountUtils.getCurrentOwnCloudAccount(this));\r
-                String remotepath = new String();\r
-                for (int j = mDirectories.getCount() - 2; j >= 0; --j) {\r
-                    remotepath += "/" + URLDecoder.decode(mDirectories.getItem(j));\r
+            \r
+                // Clear intent extra, so rotating the screen will not return us to this directory\r
+                getIntent().removeExtra(FileDetailFragment.EXTRA_FILE);\r
+            }\r
+            \r
+            if (mCurrentDir == null)\r
+                mCurrentDir = mStorageManager.getFileByPath("/");\r
+                \r
+            // Drop-Down navigation and file list restore\r
+            mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);\r
+        \r
+        \r
+            // Given the case we have a file to display:\r
+            if(mCurrentDir != null){\r
+                ArrayList<OCFile> files = new ArrayList<OCFile>();\r
+                OCFile currFile = mCurrentDir;\r
+                while(currFile != null){\r
+                    files.add(currFile);\r
+                    currFile = mStorageManager.getFileById(currFile.getParentId());\r
                 }\r
-                if (!remotepath.endsWith("/"))\r
-                    remotepath += "/";\r
-                remotepath += new File(filepath).getName();\r
-                Log.e("ASD", remotepath + "");\r
+            \r
+                // Insert in mDirs\r
+                mDirs = new String[files.size()];\r
+                for(int i = files.size() - 1; i >= 0; i--){\r
+                    mDirs[i] = files.get(i).getFileName();\r
+                }\r
+            }\r
+        \r
+            if (mDirs != null) {\r
+                for (String s : mDirs)\r
+                    mDirectories.add(s);\r
+            } else {\r
+                mDirectories.add(OCFile.PATH_SEPARATOR);\r
+            }\r
+               \r
+            // Actionbar setup\r
+            ActionBar action_bar = getSupportActionBar();\r
+            action_bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);\r
+            action_bar.setDisplayShowTitleEnabled(false);\r
+            action_bar.setListNavigationCallbacks(mDirectories, this);\r
+            if(mCurrentDir != null && mCurrentDir.getParentId() != 0){\r
+                action_bar.setDisplayHomeAsUpEnabled(true);\r
+            } else {\r
+                action_bar.setDisplayHomeAsUpEnabled(false);\r
+            }\r
+        \r
+            // List dir here\r
+            mFileList.listDirectory(mCurrentDir);\r
+        }\r
+        Log.i(getClass().toString(), "onResume() end");\r
+    }\r
 \r
-                i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);\r
-                i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);\r
-                i.putExtra(FileUploader.KEY_UPLOAD_TYPE,\r
-                        FileUploader.UPLOAD_SINGLE_FILE);\r
-                startService(i);\r
+    @Override\r
+    protected void onPause() {\r
+        Log.i(getClass().toString(), "onPause() start");\r
+        super.onPause();\r
+        if (mSyncBroadcastReceiver != null) {\r
+            unregisterReceiver(mSyncBroadcastReceiver);\r
+            mSyncBroadcastReceiver = null;\r
+        }\r
+        if (mUploadFinishReceiver != null) {\r
+            unregisterReceiver(mUploadFinishReceiver);\r
+            mUploadFinishReceiver = null;\r
+        }\r
+        if (mDownloadFinishReceiver != null) {\r
+            unregisterReceiver(mDownloadFinishReceiver);\r
+            mDownloadFinishReceiver = null;\r
+        }\r
+        \r
+        getIntent().putExtra(FileDetailFragment.EXTRA_FILE, mCurrentDir);\r
+        Log.i(getClass().toString(), "onPause() end");\r
+    }\r
+\r
+    @Override\r
+    protected Dialog onCreateDialog(int id) {\r
+        Dialog dialog = null;\r
+        AlertDialog.Builder builder;\r
+        switch (id) {\r
+        case DIALOG_SETUP_ACCOUNT:\r
+            builder = new AlertDialog.Builder(this);\r
+            builder.setTitle(R.string.main_tit_accsetup);\r
+            builder.setMessage(R.string.main_wrn_accsetup);\r
+            builder.setCancelable(false);\r
+            builder.setPositiveButton(android.R.string.ok, this);\r
+            builder.setNegativeButton(android.R.string.cancel, this);\r
+            dialog = builder.create();\r
+            break;\r
+        case DIALOG_ABOUT_APP: {\r
+            builder = new AlertDialog.Builder(this);\r
+            builder.setTitle("About");\r
+            PackageInfo pkg;\r
+            try {\r
+                pkg = getPackageManager().getPackageInfo(getPackageName(), 0);\r
+                builder.setMessage("ownCloud android client\n\nversion: " + pkg.versionName );\r
+                builder.setIcon(android.R.drawable.ic_menu_info_details);\r
+                dialog = builder.create();\r
+            } catch (NameNotFoundException e) {\r
+                builder = null;\r
+                dialog = null;\r
+                e.printStackTrace();\r
             }\r
+            break;\r
         }\r
+        case DIALOG_CREATE_DIR: {\r
+            builder = new Builder(this);\r
+            final EditText dirNameInput = new EditText(getBaseContext());\r
+            final Account a = AccountUtils.getCurrentOwnCloudAccount(this);\r
+            builder.setView(dirNameInput);\r
+            builder.setTitle(R.string.uploader_info_dirname);\r
+            int typed_color = getResources().getColor(R.color.setup_text_typed);\r
+            dirNameInput.setTextColor(typed_color);\r
+            builder.setPositiveButton(android.R.string.ok,\r
+                    new OnClickListener() {\r
+                        public void onClick(DialogInterface dialog, int which) {\r
+                            String directoryName = dirNameInput.getText().toString();\r
+                            if (directoryName.trim().length() == 0) {\r
+                                dialog.cancel();\r
+                                return;\r
+                            }\r
+    \r
+                            // Figure out the path where the dir needs to be created\r
+                            String path;\r
+                            if (mCurrentDir == null) {\r
+                                // this is just a patch; we should ensure that mCurrentDir never is null\r
+                                if (!mStorageManager.fileExists(OCFile.PATH_SEPARATOR)) {\r
+                                    OCFile file = new OCFile(OCFile.PATH_SEPARATOR);\r
+                                    mStorageManager.saveFile(file);\r
+                                }\r
+                                mCurrentDir = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);\r
+                            }\r
+                            path = FileDisplayActivity.this.mCurrentDir.getRemotePath();\r
+                            \r
+                            // Create directory\r
+                            path += directoryName + OCFile.PATH_SEPARATOR;\r
+                            Thread thread = new Thread(new DirectoryCreator(path, a));\r
+                            thread.start();\r
+    \r
+                            // Save new directory in local database\r
+                            OCFile newDir = new OCFile(path);\r
+                            newDir.setMimetype("DIR");\r
+                            newDir.setParentId(mCurrentDir.getFileId());\r
+                            mStorageManager.saveFile(newDir);\r
+    \r
+                            // Display the new folder right away\r
+                            dialog.dismiss();\r
+                            mFileList.listDirectory(mCurrentDir);\r
+                        }\r
+                    });\r
+            builder.setNegativeButton(R.string.common_cancel,\r
+                    new OnClickListener() {\r
+                        public void onClick(DialogInterface dialog, int which) {\r
+                            dialog.cancel();\r
+                        }\r
+                    });\r
+            dialog = builder.create();\r
+            break;\r
+        }\r
+        default:\r
+            dialog = null;\r
+        }\r
+    \r
+        return dialog;\r
     }\r
 \r
+    \r
+    /**\r
+     * Responds to the "There are no ownCloud Accounts setup" dialog\r
+     * TODO: Dialog is 100% useless -> Remove\r
+     */\r
+    @Override\r
+    public void onClick(DialogInterface dialog, int which) {\r
+        // In any case - we won't need it anymore\r
+        dialog.dismiss();\r
+        switch (which) {\r
+        case DialogInterface.BUTTON_POSITIVE:\r
+            Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");\r
+            intent.putExtra("authorities",\r
+                    new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });\r
+            startActivity(intent);\r
+            break;\r
+        case DialogInterface.BUTTON_NEGATIVE:\r
+            finish();\r
+        }\r
+    \r
+    }\r
+\r
+    /**\r
+     * Translates a content URI of an image to a physical path\r
+     * on the disk\r
+     * @param uri The URI to resolve\r
+     * @return The path to the image or null if it could not be found\r
+     */\r
     public String getPath(Uri uri) {\r
         String[] projection = { MediaStore.Images.Media.DATA };\r
         Cursor cursor = managedQuery(uri, projection, null, null, null);\r
@@ -344,109 +552,83 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
                     .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);\r
             cursor.moveToFirst();\r
             return cursor.getString(column_index);\r
-        } else\r
-            return null;\r
+        } \r
+        return null;\r
     }\r
-\r
-    @Override\r
-    protected void onPause() {\r
-        super.onPause();\r
-        if (syncBroadcastRevceiver != null) {\r
-            unregisterReceiver(syncBroadcastRevceiver);\r
-            syncBroadcastRevceiver = null;\r
+    \r
+    /**\r
+     * Pushes a directory to the drop down list\r
+     * @param directory to push\r
+     * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.\r
+     */\r
+    public void pushDirname(OCFile directory) {\r
+        if(!directory.isDirectory()){\r
+            throw new IllegalArgumentException("Only directories may be pushed!");\r
         }\r
-\r
+        mDirectories.insert(directory.getFileName(), 0);\r
+        mCurrentDir = directory;\r
     }\r
 \r
-    @Override\r
-    public boolean onNavigationItemSelected(int itemPosition, long itemId) {\r
-        int i = itemPosition;\r
-        while (i-- != 0) {\r
-            onBackPressed();\r
-        }\r
-        return true;\r
+    /**\r
+     * Pops a directory name from the drop down list\r
+     * @return True, unless the stack is empty\r
+     */\r
+    public boolean popDirname() {\r
+        mDirectories.remove(mDirectories.getItem(0));\r
+        return !mDirectories.isEmpty();\r
     }\r
 \r
     private class DirectoryCreator implements Runnable {\r
         private String mTargetPath;\r
         private Account mAccount;\r
         private AccountManager mAm;\r
-\r
+    \r
         public DirectoryCreator(String targetPath, Account account) {\r
             mTargetPath = targetPath;\r
             mAccount = account;\r
             mAm = (AccountManager) getSystemService(ACCOUNT_SERVICE);\r
         }\r
-\r
+    \r
         @Override\r
         public void run() {\r
-            WebdavClient wdc = new WebdavClient(Uri.parse(mAm.getUserData(\r
-                    mAccount, AccountAuthenticator.KEY_OC_URL)));\r
-\r
+            WebdavClient wdc = new WebdavClient(mAccount, getApplicationContext());\r
+            \r
             String username = mAccount.name.substring(0,\r
                     mAccount.name.lastIndexOf('@'));\r
             String password = mAm.getPassword(mAccount);\r
-\r
+    \r
             wdc.setCredentials(username, password);\r
-            wdc.allowUnsignedCertificates();\r
+            wdc.allowSelfsignedCertificates();\r
             wdc.createDirectory(mTargetPath);\r
         }\r
-\r
+    \r
     }\r
 \r
     // Custom array adapter to override text colors\r
     private class CustomArrayAdapter<T> extends ArrayAdapter<T> {\r
-\r
+    \r
         public CustomArrayAdapter(FileDisplayActivity ctx, int view) {\r
             super(ctx, view);\r
         }\r
-\r
+    \r
         public View getView(int position, View convertView, ViewGroup parent) {\r
             View v = super.getView(position, convertView, parent);\r
-\r
+    \r
             ((TextView) v).setTextColor(getResources().getColorStateList(\r
                     android.R.color.white));\r
             return v;\r
         }\r
-\r
+    \r
         public View getDropDownView(int position, View convertView,\r
                 ViewGroup parent) {\r
             View v = super.getDropDownView(position, convertView, parent);\r
-\r
+    \r
             ((TextView) v).setTextColor(getResources().getColorStateList(\r
                     android.R.color.white));\r
-\r
+    \r
             return v;\r
         }\r
-\r
-    }\r
-\r
-    public void onClick(DialogInterface dialog, int which) {\r
-        // In any case - we won't need it anymore\r
-        dialog.dismiss();\r
-        switch (which) {\r
-        case DialogInterface.BUTTON_POSITIVE:\r
-            Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");\r
-            intent.putExtra("authorities",\r
-                    new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });\r
-            startActivity(intent);\r
-            break;\r
-        case DialogInterface.BUTTON_NEGATIVE:\r
-            finish();\r
-        }\r
-\r
-    }\r
-\r
-    /**\r
-     * Checks, whether or not there are any ownCloud accounts setup.\r
-     * \r
-     * @return true, if there is at least one account.\r
-     */\r
-    private boolean accountsAreSetup() {\r
-        AccountManager accMan = AccountManager.get(this);\r
-        Account[] accounts = accMan\r
-                .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);\r
-        return accounts.length > 0;\r
+    \r
     }\r
 \r
     private class SyncBroadcastReceiver extends BroadcastReceiver {\r
@@ -457,19 +639,191 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
         public void onReceive(Context context, Intent intent) {\r
             boolean inProgress = intent.getBooleanExtra(\r
                     FileSyncService.IN_PROGRESS, false);\r
-            String account_name = intent\r
+            String accountName = intent\r
                     .getStringExtra(FileSyncService.ACCOUNT_NAME);\r
-            Log.d("FileDisplay", "sync of account " + account_name\r
+\r
+            Log.d("FileDisplay", "sync of account " + accountName\r
                     + " is in_progress: " + inProgress);\r
-            setProgressBarIndeterminateVisibility(inProgress);\r
-            if (!inProgress) {\r
-                FileListFragment fileListFramgent = (FileListFragment) getSupportFragmentManager()\r
-                        .findFragmentById(R.id.fileList);\r
-                if (fileListFramgent != null)\r
-                    fileListFramgent.populateFileList();\r
+\r
+            if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name)) {  \r
+            \r
+                String synchFolderRemotePath = intent.getStringExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH); \r
+                 \r
+                boolean fillBlankRoot = false;\r
+                if (mCurrentDir == null) {\r
+                    mCurrentDir = mStorageManager.getFileByPath("/");\r
+                    fillBlankRoot = (mCurrentDir != null);\r
+                }\r
+\r
+                if ((synchFolderRemotePath != null && mCurrentDir != null && (mCurrentDir.getRemotePath().equals(synchFolderRemotePath)))\r
+                        || fillBlankRoot ) {\r
+                    if (!fillBlankRoot) \r
+                        mCurrentDir = getStorageManager().getFileByPath(synchFolderRemotePath);\r
+                    FileListFragment fileListFragment = (FileListFragment) getSupportFragmentManager()\r
+                            .findFragmentById(R.id.fileList);\r
+                    if (fileListFragment != null) {\r
+                        fileListFragment.listDirectory(mCurrentDir);  \r
+                    }\r
+                }\r
+                \r
+                setSupportProgressBarIndeterminateVisibility(inProgress);\r
+                \r
+            }\r
+        }\r
+    }\r
+    \r
+\r
+    private class UploadFinishReceiver extends BroadcastReceiver {\r
+        /**\r
+         * Once the file upload has finished -> update view\r
+         *  @author David A. Velasco\r
+         * {@link BroadcastReceiver} to enable upload feedback in UI\r
+         */\r
+        @Override\r
+        public void onReceive(Context context, Intent intent) {\r
+            long parentDirId = intent.getLongExtra(FileUploader.EXTRA_PARENT_DIR_ID, -1);\r
+            OCFile parentDir = mStorageManager.getFileById(parentDirId);\r
+            String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);\r
+\r
+            if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name) &&\r
+                    parentDir != null && \r
+                    (   (mCurrentDir == null && parentDir.getFileName().equals("/")) ||\r
+                            parentDir.equals(mCurrentDir)\r
+                    )\r
+                ) {\r
+                FileListFragment fileListFragment = (FileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);\r
+                if (fileListFragment != null) { \r
+                    fileListFragment.listDirectory();\r
+                }\r
+            }\r
+        }\r
+        \r
+    }\r
+    \r
+    \r
+    /**\r
+     * Once the file download has finished -> update view\r
+     */\r
+    private class DownloadFinishReceiver extends BroadcastReceiver {\r
+        @Override\r
+        public void onReceive(Context context, Intent intent) {\r
+            String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);\r
+            String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);\r
+\r
+            if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name) &&\r
+                     mCurrentDir != null && mCurrentDir.getFileId() == mStorageManager.getFileByPath(downloadedRemotePath).getParentId()) {\r
+                FileListFragment fileListFragment = (FileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);\r
+                if (fileListFragment != null) { \r
+                    fileListFragment.listDirectory();\r
+                }\r
             }\r
         }\r
+    }\r
 \r
+    \r
+    @Override\r
+    public void onClick(View v) {\r
+        if (v.getId() == R.id.setup_account) {\r
+            Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);\r
+            intent.putExtra(android.provider.Settings.EXTRA_AUTHORITIES, new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });\r
+            startActivity(intent); \r
+            mForcedLoginToCreateFirstAccount = true;\r
+        }\r
     }\r
 \r
+    \r
+    \r
+    \r
+    \r
+    /**\r
+     * {@inheritDoc}\r
+     */\r
+    @Override\r
+    public DataStorageManager getStorageManager() {\r
+        return mStorageManager;\r
+    }\r
+    \r
+    \r
+    /**\r
+     * {@inheritDoc}\r
+     */\r
+    @Override\r
+    public void onDirectoryClick(OCFile directory) {\r
+        pushDirname(directory);\r
+        ActionBar actionBar = getSupportActionBar();\r
+        actionBar.setDisplayHomeAsUpEnabled(true);\r
+        \r
+        if (mDualPane) {\r
+            // Resets the FileDetailsFragment on Tablets so that it always displays\r
+            FileDetailFragment fileDetails = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);\r
+            if (fileDetails != null) {\r
+                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();\r
+                transaction.remove(fileDetails);\r
+                transaction.add(R.id.file_details_container, new FileDetailFragment(null, null));\r
+                transaction.commit();\r
+            }\r
+        }\r
+    }\r
+    \r
+    \r
+    /**\r
+     * {@inheritDoc}\r
+     */\r
+    @Override\r
+    public void onFileClick(OCFile file) {\r
+        \r
+        // If we are on a large device -> update fragment\r
+        if (mDualPane) {\r
+            // 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'\r
+            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();\r
+            transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);\r
+            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);\r
+            transaction.commit();\r
+            \r
+        } else {    // small or medium screen device -> new Activity\r
+            Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);\r
+            showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);\r
+            showDetailsIntent.putExtra(FileDownloader.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));\r
+            startActivity(showDetailsIntent);\r
+        }\r
+    }\r
+    \r
+    /**\r
+     *  Operations in this method should be preferably performed in onCreate to have a lighter onResume method. \r
+     * \r
+     *  But we need to delay them to onResume for the first start of the application, when no account exists and the login activity must be shown; and \r
+     *  put instead the ugly view that shows the 'Setup' button to restart the login activity.   \r
+     *  \r
+     *  In other way, if the users cancels or presses BACK in the login page that first time (users can be cruel sometimes) would show a blank view (the \r
+     *  FragmentList view empty).\r
+     *  \r
+     *  This is temporal, until we found out how to get a result in this activity after launching the ADD_ACCOUNT Intent with startActivityForResult (not trivial)\r
+     */\r
+    private void initDelayedTilAccountAvailabe() {\r
+        setContentView(mLayoutView);    \r
+        mDualPane = (findViewById(R.id.file_details_container) != null);\r
+        if (mDualPane && getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG) == null) {\r
+            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();\r
+            transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment\r
+            transaction.commit();\r
+        }\r
+        setSupportProgressBarIndeterminateVisibility(false);\r
+    }\r
+    \r
+\r
+    /**\r
+     * Launch an intent to request the PIN code to the user before letting him use the app\r
+     */\r
+    private void requestPinCode() {\r
+        boolean pinStart = false;\r
+        SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\r
+        pinStart = appPrefs.getBoolean("set_pincode", false);\r
+        if (pinStart) {\r
+            Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);\r
+            i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");\r
+            startActivity(i);\r
+        }\r
+    }\r
+\r
+    \r
 }\r