Merge branch 'master' into copy
authorDavid A. Velasco <dvelasco@solidgear.es>
Tue, 1 Sep 2015 16:35:51 +0000 (18:35 +0200)
committerDavid A. Velasco <dvelasco@solidgear.es>
Tue, 1 Sep 2015 16:35:51 +0000 (18:35 +0200)
Conflicts FIXED:
src/com/owncloud/android/ui/activity/FileDisplayActivity.java
src/com/owncloud/android/ui/fragment/OCFileListFragment.java
src/com/owncloud/android/ui/preview/FileDownloadFragment.java
src/com/owncloud/android/ui/preview/PreviewImageFragment.java
src/com/owncloud/android/ui/preview/PreviewMediaFragment.java

1  2 
AndroidManifest.xml
build.gradle
res/values/strings.xml
src/com/owncloud/android/ui/activity/FileActivity.java
src/com/owncloud/android/ui/activity/FileDisplayActivity.java
src/com/owncloud/android/ui/fragment/ExtendedListFragment.java
src/com/owncloud/android/ui/fragment/FileDetailFragment.java
src/com/owncloud/android/ui/fragment/OCFileListFragment.java
src/com/owncloud/android/ui/preview/FileDownloadFragment.java
src/com/owncloud/android/ui/preview/PreviewImageFragment.java
src/com/owncloud/android/ui/preview/PreviewMediaFragment.java

diff --combined AndroidManifest.xml
@@@ -1,4 -1,5 +1,4 @@@
 -<?xml version="1.0" encoding="utf-8"?>
 -<!-- 
 +<?xml version="1.0" encoding="utf-8"?><!--
    ownCloud Android client application
  
    Copyright (C) 2012  Bartek Przybylski
      
      <uses-sdk
          android:minSdkVersion="14"
-         android:targetSdkVersion="19" />
+         android:targetSdkVersion="22" />
  
 -    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
 -    </uses-permission>
 +    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
  
      <application
          android:name=".MainApp"
          android:icon="@drawable/icon"
          android:label="@string/app_name"
 -        android:theme="@style/Theme.ownCloud"> 
 +        android:theme="@style/Theme.ownCloud">
          <activity
              android:name=".ui.activity.FileDisplayActivity"
 -            android:label="@string/app_name"
 -            >
 +            android:label="@string/app_name">
              <intent-filter>
                  <action android:name="android.intent.action.MAIN" />
                  <category android:name="android.intent.category.LAUNCHER" />
              </intent-filter>
          </activity>
 -        <activity android:name=".ui.activity.UploadFilesActivity">
 -        </activity>
 -        <activity android:name=".ui.activity.Uploader" >
 +        <activity android:name=".ui.activity.UploadFilesActivity"></activity>
 +        <activity android:name=".ui.activity.Uploader">
              <intent-filter>
 -                <action android:name="android.intent.action.SEND" >
 -                </action>
 +                <action android:name="android.intent.action.SEND"></action>
  
 -                <category android:name="android.intent.category.DEFAULT" >
 -                </category>
 +                <category android:name="android.intent.category.DEFAULT"></category>
  
 -                <data android:mimeType="*/*" >
 -                </data>
 +                <data android:mimeType="*/*"></data>
              </intent-filter>
              <intent-filter>
 -                <action android:name="android.intent.action.SEND_MULTIPLE" >
 -                </action>
 +                <action android:name="android.intent.action.SEND_MULTIPLE"></action>
  
 -                <category android:name="android.intent.category.DEFAULT" >
 -                </category>
 +                <category android:name="android.intent.category.DEFAULT"></category>
  
 -                <data android:mimeType="*/*" >
 -                </data>
 +                <data android:mimeType="*/*"></data>
  
 -                      </intent-filter>
 +            </intent-filter>
          </activity>
          <activity
              android:name=".ui.activity.Preferences"
              android:theme="@style/Theme.ownCloud" >
          </activity>
          <activity     
-             android:name=".ui.preview.PreviewImageActivity" 
+             android:name=".ui.preview.PreviewImageActivity"
+             android:theme="@style/Theme.ownCloud.Overlay"
              />
                        
          <activity     
              android:name=".ui.preview.PreviewVideoActivity"
 -                      android:label="@string/app_name"
 -                      android:theme="@style/Theme.ownCloud.Fullscreen" 
 -                      >
 -              </activity>        
 +            android:label="@string/app_name"
 +            android:theme="@style/Theme.ownCloud.Fullscreen"></activity>
  
          <service
              android:name=".authentication.AccountAuthenticatorService"
              android:exported="true">
 -            <intent-filter  android:priority="100">
 +            <intent-filter android:priority="100">
                  <action android:name="android.accounts.AccountAuthenticator" />
              </intent-filter>
  
          </service>
          <service
              android:name=".syncadapter.FileSyncService"
 -            android:exported="true" 
 -            >
 +            android:exported="true">
              <intent-filter>
                  <action android:name="android.content.SyncAdapter" />
              </intent-filter>
              android:enabled="true"
              android:exported="false"
              android:label="@string/sync_string_files"
 -            android:syncable="true" >
 -        </provider>
 +            android:syncable="true"></provider>
  
          <activity
              android:name=".authentication.AuthenticatorActivity"
              android:launchMode="singleTask">
              <intent-filter>
                  <action android:name="android.intent.action.VIEW" />
 +
                  <category android:name="android.intent.category.DEFAULT" />
                  <category android:name="android.intent.category.BROWSABLE" />
 +
                  <data android:scheme="@string/oauth2_redirect_scheme" />
              </intent-filter>
              <intent-filter>
          <service android:name=".files.services.FileDownloader" />
          <service android:name=".files.services.FileUploader" />
          <service android:name=".media.MediaService" />
 -        
 +
          <activity android:name=".ui.activity.PassCodeActivity" />
          <activity android:name=".ui.activity.ConflictsResolveActivity"/>
          <activity android:name=".ui.activity.GenericExplanationActivity"/>
              <intent-filter>
                  <!-- unofficially supported by many Android phones but not by HTC devices: -->
                  <action android:name="com.android.camera.NEW_PICTURE" />
 -                <!-- officially supported since Android 4.0 (SDK 14, works even for HTC devices): --> 
 +                <!-- officially supported since Android 4.0 (SDK 14, works even for HTC devices): -->
                  <action android:name="android.hardware.action.NEW_PICTURE" />
                  <data android:mimeType="image/*" />
              </intent-filter>
                  <data android:mimeType="video/*" />
              </intent-filter>
              <intent-filter>
 -                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
 +                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
              </intent-filter>
          </receiver>
          <receiver android:name=".files.BootupBroadcastReceiver">
              <intent-filter>
 -                <action android:name="android.intent.action.BOOT_COMPLETED"/>
 +                <action android:name="android.intent.action.BOOT_COMPLETED" />
              </intent-filter>
          </receiver>
          <service android:name=".services.observer.FileObserverService"/>
                        android:label="@string/copy_link"
                        android:icon="@drawable/copy_link"/>
  
 -        <activity 
 +        <activity
                        android:name=".ui.activity.FolderPickerActivity"
                        android:label="@string/app_name"/>
  
 -        <activity 
 +        <activity
                        android:name=".ui.activity.UploadPathActivity"
                        android:label="@string/app_name"/>
          
diff --combined build.gradle
@@@ -20,14 -20,14 +20,14 @@@ repositories 
  
  dependencies {
      compile name: 'touch-image-view'
-     compile 'com.android.support:support-v4:19.1.0'
+     compile 'com.android.support:support-v4:22.2.1'
      compile project(':owncloud-android-library')
      compile 'com.jakewharton:disklrucache:2.0.2'
-     compile 'com.android.support:appcompat-v7:19.1.0'
+     compile 'com.android.support:appcompat-v7:22.2.1'
  }
  
  android {
-     compileSdkVersion 19
+     compileSdkVersion 22
      buildToolsVersion "22.0.1"
      sourceSets {
          main {
              abortOnError false
          }
      }
 -
 -
 -    compileOptions {
 -        sourceCompatibility JavaVersion.VERSION_1_7
 -        targetCompatibility JavaVersion.VERSION_1_7
 -    }
      
      productFlavors {
      }
diff --combined res/values/strings.xml
@@@ -28,6 -28,7 +28,7 @@@
      <string name="drawer_item_settings">Settings</string>
      <string name="drawer_item_logs">Logs</string>
        <string name="drawer_close">Close</string>
+     <string name="drawer_open">Open</string>
      <string name="prefs_category_general">General</string>
      <string name="prefs_category_more">More</string>
      <string name="prefs_accounts">Accounts</string>
      <string name="sync_fail_ticker_unauthorized">Synchronization failed, you need to relogin</string>
      <string name="sync_fail_content">Synchronization of %1$s could not be completed</string>
      <string name="sync_fail_content_unauthorized">Invalid password for %1$s</string>
 -      <string name="sync_conflicts_in_favourites_ticker">Conflicts found</string>
 -      <string name="sync_conflicts_in_favourites_content">%1$d kept-in-sync files could not be sync\'ed</string>
 +    <string name="sync_conflicts_in_favourites_ticker">Conflicts found</string>
 +    <string name="sync_conflicts_in_favourites_content">%1$d kept-in-sync files could not be sync\'ed</string>
      <string name="sync_fail_in_favourites_ticker">Kept-in-sync files failed</string>
      <string name="sync_fail_in_favourites_content">Contents of %1$d files could not be sync\'ed (%2$d conflicts)</string>
      <string name="sync_foreign_files_forgotten_ticker">Some local files were forgotten</string>
      <string name="sync_foreign_files_forgotten_content">%1$d files out of the %2$s folder could not be copied into</string>
      <string name="sync_foreign_files_forgotten_explanation">As of version 1.3.16, files uploaded from this device are copied into the local %1$s folder to prevent data loss when a single file is synced with multiple accounts.\n\nDue to this change, all files uploaded in previous versions of this app were copied into the %2$s folder. However, an error prevented the completion of this operation during account synchronization. You may either leave the file(s) as is and remove the link to %3$s, or move the file(s) into the %1$s folder and retain the link to %4$s.\n\nListed below are the local file(s), and the remote file(s) in %5$s they were linked to.</string>
 -      <string name="sync_current_folder_was_removed">Folder %1$s does not exist anymore</string>    
 +    <string name="sync_current_folder_was_removed">Folder %1$s does not exist anymore</string>
      <string name="foreign_files_move">"Move all"</string>
      <string name="foreign_files_success">"All files were moved"</string>
      <string name="foreign_files_fail">"Some files could not be moved"</string>
      <string name="media_state_loading">"%1$s (loading)"</string>
      <string name="media_event_done">"%1$s playback finished"</string>
      <string name="media_err_nothing_to_play">No media file found</string>
 -      <string name="media_err_no_account">No account provided</string>
 -      <string name="media_err_not_in_owncloud">File not in a valid account</string>
 -      <string name="media_err_unsupported">Unsupported media codec</string>
 -      <string name="media_err_io">Media file could not be read</string>
 -      <string name="media_err_malformed">Media file not correctly encoded</string>
 -      <string name="media_err_timeout">Timed out while trying to play</string>
 -      <string name="media_err_invalid_progressive_playback">Media file cannot be streamed</string>
 -      <string name="media_err_unknown">Media file cannot be played with the stock media player</string>
 -      <string name="media_err_security_ex">Security error trying to play %1$s</string>
 -      <string name="media_err_io_ex">Input error trying to play %1$s</string>
 -      <string name="media_err_unexpected">Unexpected error trying to play %1$s</string>
 -      <string name="media_rewind_description">Rewind button</string>
 -      <string name="media_play_pause_description">Play or pause button</string>
 -      <string name="media_forward_description">Fast forward button</string>
 +    <string name="media_err_no_account">No account provided</string>
 +    <string name="media_err_not_in_owncloud">File not in a valid account</string>
 +    <string name="media_err_unsupported">Unsupported media codec</string>
 +    <string name="media_err_io">Media file could not be read</string>
 +    <string name="media_err_malformed">Media file not correctly encoded</string>
 +    <string name="media_err_timeout">Timed out while trying to play</string>
 +    <string name="media_err_invalid_progressive_playback">Media file cannot be streamed</string>
 +    <string name="media_err_unknown">Media file cannot be played with the stock media player</string>
 +    <string name="media_err_security_ex">Security error trying to play %1$s</string>
 +    <string name="media_err_io_ex">Input error trying to play %1$s</string>
 +    <string name="media_err_unexpected">Unexpected error trying to play %1$s</string>
 +    <string name="media_rewind_description">Rewind button</string>
 +    <string name="media_play_pause_description">Play or pause button</string>
 +    <string name="media_forward_description">Fast forward button</string>
  
        <string name="auth_getting_authorization">Getting authorization&#8230;</string>
        <string name="auth_trying_to_login">Trying to login&#8230;</string>
      <string name="confirmation_remove_alert">"Do you really want to remove %1$s?"</string>
      <string name="confirmation_remove_folder_alert">"Do you really want to remove %1$s and its contents?"</string>
      <string name="confirmation_remove_local">Local only</string>
-     <string name="confirmation_remove_folder_local">Local contents only</string>
-     <string name="confirmation_remove_remote">Remove from server</string>
-     <string name="confirmation_remove_remote_and_local">Remote and local</string>
+     <string name="confirmation_remove_folder_local">Local only</string>
+     <string name="confirmation_remove_remote">From server</string>
+     <string name="confirmation_remove_remote_and_local">Remote &amp; local</string>
      <string name="remove_success_msg">"Removal succeeded"</string>
      <string name="remove_fail_msg">"Removal failed"</string>
      <string name="rename_dialog_title">Enter a new name</string>
      <string name="ssl_validator_label_L">Location:</string>
      <string name="ssl_validator_label_validity">Validity:</string>
      <string name="ssl_validator_label_validity_from">From:</string>
 -      <string name="ssl_validator_label_validity_to">To:</string>
 -      <string name="ssl_validator_label_signature">Signature:</string>
 -      <string name="ssl_validator_label_signature_algorithm">Algorithm:</string>
 -      <string name="ssl_validator_null_cert">The certificate could not be shown.</string>
 -      <string name="ssl_validator_no_info_about_error">- No information about the error</string>
 -                      
 +    <string name="ssl_validator_label_validity_to">To:</string>
 +    <string name="ssl_validator_label_signature">Signature:</string>
 +    <string name="ssl_validator_label_signature_algorithm">Algorithm:</string>
 +    <string name="ssl_validator_null_cert">The certificate could not be shown.</string>
 +    <string name="ssl_validator_no_info_about_error">- No information about the error</string>
 +
      <string name="placeholder_sentence">This is a placeholder</string>
      <string name="placeholder_filename">placeholder.txt</string>
      <string name="placeholder_filetype">PNG Image</string>
      <string name="placeholder_filesize">389 KB</string>
      <string name="placeholder_timestamp">2012/05/18 12:23 PM</string>
      <string name="placeholder_media_time">12:23:45</string>
 -    
 +
      <string name="instant_upload_on_wifi">Upload pictures via WiFi only</string>
      <string name="instant_video_upload_on_wifi">Upload videos via WiFi only</string>
      <string name="instant_upload_path">/InstantUpload</string>
      <string name="conflict_title">File conflict</string>
      <string name="conflict_message">Which files do you want to keep? If you select both versions, the local file will have a number added to its name.</string>
      <string name="conflict_keep_both">Keep both</string>
-     <string name="conflict_use_local_version">Use local version</string>
-     <string name="conflict_use_server_version">Use server version</string>
+     <string name="conflict_use_local_version">local version</string>
+     <string name="conflict_use_server_version">server version</string>
      
      <string name="preview_image_description">Image preview</string>
      <string name="preview_image_error_unknown_format">This image cannot be shown</string>
 -    
 +
      <string name="error__upload__local_file_not_copied">%1$s could not be copied to %2$s local folder</string>
      <string name="prefs_instant_upload_path_title">Upload Path</string>
  
      <string name="share_link_password_title">Enter a password</string>
      <string name="share_link_empty_password">You must enter a password</string>
  
 -      <string name="activity_chooser_send_file_title">Send</string>
 +    <string name="network_error_socket_exception">An error occurred while connecting with the server.</string>
 +    <string name="network_error_socket_timeout_exception">An error occurred while waiting for the server, the operation couldn\'t have been done</string>
 +    <string name="network_error_connect_timeout_exception">An error occurred while waiting for the server, the operation couldn\'t have been done</string>
 +    <string name="network_host_not_available">The operation couldn\'t be completed, server is unavailable</string>
 +    <string name="empty" />
  
 -      <string name="copy_link">Copy link</string>
 -      <string name="clipboard_text_copied">Copied to clipboard</string>
 +    <string name="forbidden_permissions">You do not have permission %s</string>
 +    <string name="forbidden_permissions_rename">to rename this file</string>
 +    <string name="forbidden_permissions_delete">to delete this file</string>
 +    <string name="share_link_forbidden_permissions">to share this file</string>
 +    <string name="unshare_link_forbidden_permissions">to unshare this file</string>
 +    <string name="forbidden_permissions_create">to create the file</string>
 +    <string name="uploader_upload_forbidden_permissions">to upload in this folder</string>
 +    <string name="downloader_download_file_not_found">The file is no longer available on the server</string>
  
 -      <string name="error_cant_bind_to_operations_service">Critical error: cannot perform operations</string>
 -      
 -      <string name="network_error_socket_exception">An error occurred while connecting with the server.</string>
 -      <string name="network_error_socket_timeout_exception">An error occurred while waiting for the server, the operation couldn\'t have been done</string>
 -      <string name="network_error_connect_timeout_exception">An error occurred while waiting for the server, the operation couldn\'t have been done</string>
 -      <string name="network_host_not_available">The operation couldn\'t be completed, server is unavailable</string>
 -
 -      <string name="empty" />
 -      
 -      <string name="forbidden_permissions">You do not have permission %s</string>
 -      <string name="forbidden_permissions_rename">to rename this file</string>
 -      <string name="forbidden_permissions_delete">to delete this file</string>
 -      <string name="share_link_forbidden_permissions">to share this file</string>
 -      <string name="unshare_link_forbidden_permissions">to unshare this file</string>
 -      <string name="forbidden_permissions_create">to create the file</string>
 -      <string name="uploader_upload_forbidden_permissions">to upload in this folder</string>
 -      <string name="downloader_download_file_not_found">The file is no longer available on the server</string>
 -
 -      <string name="prefs_category_accounts">Accounts</string>
 -      <string name="prefs_add_account">Add account</string>
 -      <string name="auth_redirect_non_secure_connection_title">Secure connection is redirected to an unsecured route.</string>
 +    <string name="prefs_category_accounts">Accounts</string>
 +    <string name="prefs_add_account">Add account</string>
 +    <string name="auth_redirect_non_secure_connection_title">Secure connection is redirected through an unsecured route.</string>
  
        <string name="actionbar_logger">Logs</string>
        <string name="log_send_history_button">Send History</string>
        <string name="file_list_empty_moving">Nothing in here. You can add a folder!</string>
        <string name="folder_picker_choose_button_text">Choose</string>
  
 -      <string name="move_file_not_found">Unable to move. Please check whether the file exists</string>
 -      <string name="move_file_invalid_into_descendent">It is not possible to move a folder into a descendant</string>
 -      <string name="move_file_invalid_overwrite">The file exists already in the destination folder</string>
 -      <string name="move_file_error">An error occurred while trying to move this file or folder</string>
 -      <string name="forbidden_permissions_move">to move this file</string>
 +    <string name="move_file_not_found">Unable to move. Please check whether the file exists</string>
 +    <string name="move_file_invalid_into_descendent">It is not possible to move a folder into a descendant</string>
 +    <string name="move_file_invalid_overwrite">The file exists already in the destination folder</string>
 +    <string name="move_file_error">An error occurred while trying to move this file or folder</string>
 +    <string name="forbidden_permissions_move">to move this file</string>
 +
 +
 +    <string name="copy_file_not_found">Unable to copy. Please check whether the file exists</string>
 +    <string name="copy_file_invalid_into_descendent">It is not possible to copy a folder into a descendant</string>
 +    <string name="copy_file_invalid_overwrite">The file exists already in the destination folder</string>
 +    <string name="copy_file_error">An error occurred while trying to copy this file or folder</string>
 +    <string name="forbidden_permissions_copy">to copy this file</string>
  
 -      <string name="prefs_category_instant_uploading">Instant Uploads</string>
 +    <string name="prefs_category_instant_uploading">Instant Uploads</string>
        <string name="prefs_category_security">Security</string>
  
        <string name="prefs_instant_video_upload_path_title">Upload Video Path</string>
@@@ -35,18 -35,20 +35,20 @@@ import android.content.res.Configuratio
  import android.os.Bundle;
  import android.os.Handler;
  import android.os.IBinder;
- import android.support.v4.app.ActionBarDrawerToggle;
  import android.support.v4.app.Fragment;
  import android.support.v4.app.FragmentManager;
  import android.support.v4.app.FragmentTransaction;
  import android.support.v4.view.GravityCompat;
  import android.support.v4.widget.DrawerLayout;
  import android.support.v7.app.ActionBar;
- import android.support.v7.app.ActionBarActivity;
+ import android.support.v7.app.ActionBarDrawerToggle;
+ import android.support.v7.app.AppCompatActivity;
+ import android.util.Log;
  import android.view.View;
  import android.widget.AdapterView;
- import android.widget.LinearLayout;
  import android.widget.ListView;
+ import android.widget.RelativeLayout;
+ import android.widget.TextView;
  import android.widget.Toast;
  
  import com.owncloud.android.BuildConfig;
@@@ -85,7 -87,7 +87,7 @@@ import java.util.ArrayList
   * Activity with common behaviour for activities handling {@link OCFile}s in ownCloud
   * {@link Account}s .
   */
- public class FileActivity extends ActionBarActivity
+ public class FileActivity extends AppCompatActivity
          implements OnRemoteOperationListener, ComponentsGetter {
  
      public static final String EXTRA_FILE = "com.owncloud.android.ui.activity.FILE";
          // Sync the toggle state after onRestoreInstanceState has occurred.
          if (mDrawerToggle != null) {
              mDrawerToggle.syncState();
-             if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
+             if (isDrawerOpen()) {
                  getSupportActionBar().setTitle(R.string.app_name);
                  mDrawerToggle.setDrawerIndicatorEnabled(true);
              }
          }
      }
  
+     @Override
+     public void onBackPressed() {
+         if (isDrawerOpen()) {
+             closeNavDrawer();
+             return;
+         }
+         super.onBackPressed();
+     }
+     /**
+      * checks if the drawer exists and is opened.
+      *
+      * @return <code>true</code> if the drawer is open, else <code>false</code>
+      */
+     public boolean isDrawerOpen() {
+         if(mDrawerLayout != null) {
+             return mDrawerLayout.isDrawerOpen(GravityCompat.START);
+         } else {
+             return false;
+         }
+     }
+     /**
+      * closes the navigation drawer.
+      */
+     public void closeNavDrawer() {
+         if(mDrawerLayout != null) {
+             mDrawerLayout.closeDrawer(GravityCompat.START);
+         }
+     }
      protected void initDrawer(){
          // constant settings for action bar when navigation drawer is inited
          getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
  
          mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
          // Notification Drawer
-         LinearLayout navigationDrawerLayout = (LinearLayout) findViewById(R.id.left_drawer);
+         RelativeLayout navigationDrawerLayout = (RelativeLayout) findViewById(R.id.left_drawer);
          mDrawerList = (ListView) navigationDrawerLayout.findViewById(R.id.drawer_list);
  
          // TODO re-enable when "Accounts" is available in Navigation Drawer
  //            username.setText(account.name.substring(0, lastAtPos));
  //        }
  
+         // Display username in drawer
+         Account account = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
+         if (account != null) {
+             TextView username = (TextView) navigationDrawerLayout.findViewById(R.id.drawer_username);
+             int lastAtPos = account.name.lastIndexOf("@");
+             username.setText(account.name.substring(0, lastAtPos));
+         }
          // load slide menu items
          mDrawerTitles = getResources().getStringArray(R.array.drawer_items);
  
          // mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[0],
          // mDrawerContentDescriptions[0]));
          // All Files
-         mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[0], mDrawerContentDescriptions[0]));
+         mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[0], mDrawerContentDescriptions[0],
+                 R.drawable.ic_folder_open));
  
          // TODO Enable when "On Device" is recovered
          // On Device
          //        mDrawerContentDescriptions[2]));
  
          // Settings
-         mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[1], mDrawerContentDescriptions[1]));
+         mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[1], mDrawerContentDescriptions[1],
+                 R.drawable.ic_settings));
          // Logs
          if (BuildConfig.DEBUG) {
              mDrawerItems.add(new NavigationDrawerItem(mDrawerTitles[2],
-                     mDrawerContentDescriptions[2]));
+                     mDrawerContentDescriptions[2],R.drawable.ic_log));
          }
  
          // setting the nav drawer list adapter
                  mDrawerItems);
          mDrawerList.setAdapter(mNavigationDrawerAdapter);
  
-         mDrawerToggle = new ActionBarDrawerToggle(
-                 this,
-                 mDrawerLayout,
-                 R.drawable.ic_drawer,
-                 R.string.app_name,
-                 R.string.drawer_close) {
+         mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.string.drawer_open,R.string.drawer_close) {
  
              /** Called when a drawer has settled in a completely closed state. */
              public void onDrawerClosed(View view) {
                  invalidateOptionsMenu();
              }
          };
-         //mDrawerToggle.setDrawerIndicatorEnabled(true);
+         
          // Set the list's click listener
          mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
  
          // Set the drawer toggle as the DrawerListener
          mDrawerLayout.setDrawerListener(mDrawerToggle);
+         mDrawerToggle.setDrawerIndicatorEnabled(false);
      }
  
      /**
       */
      private void swapToDefaultAccount() {
          // default to the most recently used account
 -        Account newAccount  = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
 +        Account newAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
          if (newAccount == null) {
              /// no account available: force account creation
              createFirstAccount();
          outState.putBoolean(FileActivity.EXTRA_FROM_NOTIFICATION, mFromNotification);
          outState.putLong(KEY_WAITING_FOR_OP_ID, mFileOperationsHelper.getOpIdWaitingFor());
          outState.putBoolean(KEY_TRY_SHARE_AGAIN, mTryShareAgain);
-         outState.putString(KEY_ACTION_BAR_TITLE, getSupportActionBar().getTitle().toString());
+         if(getSupportActionBar().getTitle() != null) {
+             // Null check in case the actionbar is used in ActionBar.NAVIGATION_MODE_LIST
+             // since it doesn't have a title then
+             outState.putString(KEY_ACTION_BAR_TITLE, getSupportActionBar().getTitle().toString());
+         }
      }
  
  
      }
  
      /**
 -     * @return  'True' when the Activity is finishing to enforce the setup of a new account.
 +     * @return 'True' when the Activity is finishing to enforce the setup of a new account.
       */
      protected boolean isRedirectingToSetupAccount() {
          return mRedirectingToSetupAccount;
      }
  
  
 +
      private void onCreateShareOperationFinish(CreateShareOperation operation,
                                                RemoteOperationResult result) {
          dismissLoadingDialog();
      /**
       * Dismiss loading dialog
       */
 -    public void dismissLoadingDialog(){
 +    public void dismissLoadingDialog() {
          Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
          if (frag != null) {
              LoadingDialog loading = (LoadingDialog) frag;
@@@ -26,7 -26,7 +26,7 @@@ import android.accounts.Account
  import android.accounts.AccountManager;
  import android.accounts.AuthenticatorException;
  import android.annotation.TargetApi;
- import android.app.AlertDialog;
+ import android.support.v7.app.AlertDialog;
  import android.content.BroadcastReceiver;
  import android.content.ComponentName;
  import android.content.ContentResolver;
@@@ -48,12 -48,15 +48,15 @@@ import android.provider.OpenableColumns
  import android.support.v4.app.Fragment;
  import android.support.v4.app.FragmentManager;
  import android.support.v4.app.FragmentTransaction;
+ import android.support.v4.content.ContextCompat;
  import android.support.v4.view.GravityCompat;
  import android.view.Menu;
  import android.view.MenuInflater;
  import android.view.MenuItem;
  import android.view.View;
- import android.view.Window;
+ import android.widget.ProgressBar;
+ import android.widget.RelativeLayout;
+ import android.widget.TextView;
  import android.widget.Toast;
  
  import com.owncloud.android.MainApp;
@@@ -74,7 -77,6 +77,7 @@@ import com.owncloud.android.lib.common.
  import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  import com.owncloud.android.lib.common.utils.Log_OC;
 +import com.owncloud.android.operations.CopyFileOperation;
  import com.owncloud.android.operations.CreateFolderOperation;
  import com.owncloud.android.operations.CreateShareOperation;
  import com.owncloud.android.operations.MoveFileOperation;
@@@ -121,6 -123,7 +124,7 @@@ public class FileDisplayActivity extend
      private boolean mDualPane;
      private View mLeftFragmentContainer;
      private View mRightFragmentContainer;
+     private ProgressBar mProgressBar;
  
      private static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
      private static final String KEY_SYNC_IN_PROGRESS = "SYNC_IN_PROGRESS";
      public static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
      public static final int ACTION_SELECT_MULTIPLE_FILES = 2;
      public static final int ACTION_MOVE_FILES = 3;
 +    public static final int ACTION_COPY_FILES = 4;
  
      private static final String TAG = FileDisplayActivity.class.getSimpleName();
  
      private static final String TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT";
  
      private OCFile mWaitingToPreview;
 -    
 +
      private boolean mSyncInProgress = false;
  
      private static String DIALOG_UNTRUSTED_CERT = "DIALOG_UNTRUSTED_CERT";
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          Log_OC.v(TAG, "onCreate() start");
-         requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
  
          super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account
                                              // is valid
              Intent initObserversIntent = FileObserverService.makeInitIntent(this);
              startService(initObserversIntent);
          }
 -        
 +
          /// Load of saved instance state
          if(savedInstanceState != null) {
              mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(
              mWaitingToPreview = null;
              mSyncInProgress = false;
              mWaitingToSend = null;
 -        }        
 +        }
  
          /// USER INTERFACE
  
          // Inflate and set the layout view
          setContentView(R.layout.files);
 -        
 +
          // Navigation Drawer
          initDrawer();
  
+         mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
+         mProgressBar.setIndeterminateDrawable(
+                 ContextCompat.getDrawable(this,
+                         R.drawable.actionbar_progress_indeterminate_horizontal));
          mDualPane = getResources().getBoolean(R.bool.large_land_layout);
          mLeftFragmentContainer = findViewById(R.id.left_fragment_container);
          mRightFragmentContainer = findViewById(R.id.right_fragment_container);
                                                                  // according to the official
                                                                  // documentation
  
-         setSupportProgressBarIndeterminateVisibility(mSyncInProgress
-         /*|| mRefreshSharesInProgress*/);
+         // enable ActionBar app icon to behave as action to toggle nav drawer
+         //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
+         getSupportActionBar().setHomeButtonEnabled(true);
+         mProgressBar.setIndeterminate(mSyncInProgress);
          // always AFTER setContentView(...) ; to work around bug in its implementation
          
          setBackgroundText();
      protected void onStart() {
          Log_OC.v(TAG, "onStart() start");
          super.onStart();
-         getSupportActionBar().setIcon(DisplayUtils.getSeasonalIconId());
          Log_OC.v(TAG, "onStart() end");
      }
  
      }
  
      /**
 -     *  Called when the ownCloud {@link Account} associated to the Activity was just updated.
 -     */ 
 +     * Called when the ownCloud {@link Account} associated to the Activity was just updated.
 +     */
      @Override
      protected void onAccountSet(boolean stateWasRecovered) {
          super.onAccountSet(stateWasRecovered);
              }
              setFile(file);
  
+             if (mAccountWasSet) {
+                 RelativeLayout navigationDrawerLayout = (RelativeLayout) findViewById(R.id.left_drawer);
+                 if (navigationDrawerLayout != null && getAccount() != null) {
+                     TextView username = (TextView) navigationDrawerLayout.findViewById(R.id.drawer_username);
+                     int lastAtPos = getAccount().name.lastIndexOf("@");
+                     username.setText(getAccount().name.substring(0, lastAtPos));
+                 }
+             }
              if (!stateWasRecovered) {
                  Log_OC.d(TAG, "Initializing Fragments in onAccountChanged..");
                  initFragmentsWithFile();
                  if (file.isFolder()) {
                      startSyncFolderOperation(file, false);
                  }
 -                
 +
              } else {
                  updateFragmentsVisibility(!file.isFolder());
                  updateActionBarTitleAndHomeButton(file.isFolder() ? null : file);
          transaction.add(R.id.left_fragment_container, listOfFiles, TAG_LIST_OF_FILES);
          transaction.commit();
      }
 -    
 +
      private void initFragmentsWithFile() {
          if (getAccount() != null && getFile() != null) {
              /// First fragment
 -            OCFileListFragment listOfFiles = getListOfFilesFragment(); 
 +            OCFileListFragment listOfFiles = getListOfFilesFragment();
              if (listOfFiles != null) {
                  listOfFiles.listDirectory(getCurrentDir());
                  // TODO Enable when "On Device" is recovered
              } else {
                  Log_OC.e(TAG, "Still have a chance to lose the initializacion of list fragment >(");
              }
 -            
 +
              /// Second fragment
 -            OCFile file = getFile(); 
 +            OCFile file = getFile();
              Fragment secondFragment = chooseInitialSecondFragment(file);
              if (secondFragment != null) {
                  setSecondFragment(secondFragment);
      private Fragment chooseInitialSecondFragment(OCFile file) {
          Fragment secondFragment = null;
          if (file != null && !file.isFolder()) {
 -            if (file.isDown() && PreviewMediaFragment.canBePreviewed(file) 
 +            if (file.isDown() && PreviewMediaFragment.canBePreviewed(file)
                      && file.getLastSyncDateForProperties() > 0  // temporal fix
                      ) {
                  int startPlaybackPosition =
      /**
       * Replaces the second fragment managed by the activity with the received as
       * a parameter.
 -     * 
 -     * Assumes never will be more than two fragments managed at the same time. 
 -     * 
 -     * @param fragment      New second Fragment to set.
 +     * <p/>
 +     * Assumes never will be more than two fragments managed at the same time.
 +     *
 +     * @param fragment New second Fragment to set.
       */
      private void setSecondFragment(Fragment fragment) {
          FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
          Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(
                  FileDisplayActivity.TAG_LIST_OF_FILES);
          if (listOfFiles != null) {
 -            return (OCFileListFragment)listOfFiles;
 +            return (OCFileListFragment) listOfFiles;
          }
          Log_OC.wtf(TAG, "Access to unexisting list of files fragment!!");
          return null;
          Fragment second = getSupportFragmentManager().findFragmentByTag(
                  FileDisplayActivity.TAG_SECOND_FRAGMENT);
          if (second != null) {
 -            return (FileFragment)second;
 +            return (FileFragment) second;
          }
          return null;
      }
              requestMultipleUpload(data, resultCode);
  
          } else if (requestCode == ACTION_MOVE_FILES && resultCode == RESULT_OK){
 +            final Intent fData = data;
 +            final int fResultCode = resultCode;
 +            getHandler().postDelayed(
 +                    new Runnable() {
 +                        @Override
 +                        public void run() {
 +                            requestMoveOperation(fData, fResultCode);
 +                        }
 +                    },
 +                    DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
 +            );
 +
 +        } else if (requestCode == ACTION_COPY_FILES && resultCode == RESULT_OK) {
  
              final Intent fData = data;
 -            final int fResultCode = resultCode; 
 +            final int fResultCode = resultCode;
              getHandler().postDelayed(
 -                new Runnable() {
 -                    @Override
 -                    public void run() {
 -                        requestMoveOperation(fData, fResultCode);
 -                    }
 -                }, 
 -                DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
 +                    new Runnable() {
 +                        @Override
 +                        public void run() {
 +                            requestCopyOperation(fData, fResultCode);
 +                        }
 +                    },
 +                    DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
              );
  
          } else {
  
      /**
       * Request the operation for moving the file/folder from one path to another
 -     * 
 -     * @param data              Intent received
 -     * @param resultCode        Result code received
 +     *
 +     * @param data       Intent received
 +     * @param resultCode Result code received
       */
      private void requestMoveOperation(Intent data, int resultCode) {
          OCFile folderToMoveAt = (OCFile) data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
          getFileOperationsHelper().moveFile(folderToMoveAt, targetFile);
      }
  
 +    /**
 +     * Request the operation for copying the file/folder from one path to another
 +     *
 +     * @param data       Intent received
 +     * @param resultCode Result code received
 +     */
 +    private void requestCopyOperation(Intent data, int resultCode) {
 +        OCFile folderToMoveAt = data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
 +        OCFile targetFile = data.getParcelableExtra(FolderPickerActivity.EXTRA_FILE);
 +        getFileOperationsHelper().copyFile(folderToMoveAt, targetFile);
 +    }
 +
      @Override
      public void onBackPressed() {
-         OCFileListFragment listOfFiles = getListOfFilesFragment();
-         if (mDualPane || getSecondFragment() == null) {
-             OCFile currentDir = getCurrentDir();
-             if (currentDir == null || currentDir.getParentId() == FileDataStorageManager.ROOT_PARENT_ID) {
-                 finish();
-                 return;
+         if (!isDrawerOpen()){
+             OCFileListFragment listOfFiles = getListOfFilesFragment();
+             if (mDualPane || getSecondFragment() == null) {
+                 OCFile currentDir = getCurrentDir();
+                 if (currentDir == null || currentDir.getParentId() == FileDataStorageManager.ROOT_PARENT_ID) {
+                     finish();
+                     return;
+                 }
+                 if (listOfFiles != null) {  // should never be null, indeed
+                     listOfFiles.onBrowseUp();
+                 }
              }
              if (listOfFiles != null) {  // should never be null, indeed
-                 listOfFiles.onBrowseUp();
+                 setFile(listOfFiles.getCurrentFile());
              }
+             cleanSecondFragment();
+         } else {
+             super.onBackPressed();
          }
-         if (listOfFiles != null) {  // should never be null, indeed
-             setFile(listOfFiles.getCurrentFile());
-         }
-         cleanSecondFragment();
      }
  
      @Override
  
          Log_OC.v(TAG, "onSaveInstanceState() end");
      }
 -    
  
  
      @Override
          downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
          mDownloadFinishReceiver = new DownloadFinishReceiver();
          registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
 -        
 +
          Log_OC.v(TAG, "onResume() end");
      }
  
              unregisterReceiver(mDownloadFinishReceiver);
              mDownloadFinishReceiver = null;
          }
 -        
 +
          super.onPause();
          Log_OC.v(TAG, "onPause() end");
      }
                          accountName.equals(getAccount().name) && getStorageManager() != null);
      
                  if (sameAccount) {
 -                    
 +
                      if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
                          mSyncInProgress = true;
 -                        
 +
                      } else {
                          OCFile currentFile = (getFile() == null) ? null :
                                  getStorageManager().getFileByPath(getFile().getRemotePath());
                                              Toast.LENGTH_LONG)
                                  .show();
                              browseToRoot();
 -                            
 +
                          } else {
                              if (currentFile == null && !getFile().isFolder()) {
                                  // currently selected file was removed in the server, and now we
                              }
                              setFile(currentFile);
                          }
 -                        
 +
                          mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
                                  !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED
                                          .equals(event));
                          if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
                                      equals(event) &&
                                  /// TODO refactor and make common
 -                                synchResult != null && !synchResult.isSuccess() &&  
 -                                (synchResult.getCode() == ResultCode.UNAUTHORIZED   || 
 -                                    synchResult.isIdPRedirection()                  ||
 -                                    (synchResult.isException() && synchResult.getException() 
 -                                            instanceof AuthenticatorException))) {
 +                                synchResult != null && !synchResult.isSuccess() &&
 +                                (synchResult.getCode() == ResultCode.UNAUTHORIZED ||
 +                                        synchResult.isIdPRedirection() ||
 +                                        (synchResult.isException() && synchResult.getException()
 +                                                instanceof AuthenticatorException))) {
  
  
                              try {
                      }
                      removeStickyBroadcast(intent);
                      Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
-                     setSupportProgressBarIndeterminateVisibility(mSyncInProgress
-                     /*|| mRefreshSharesInProgress*/);
+                     mProgressBar.setIndeterminate(mSyncInProgress);
+                     //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
+                     //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
+                     /*|| mRefreshSharesInProgress*/ //);
  
                      setBackgroundText();
 -                        
 +
                  }
 -                
 +
                  if (synchResult != null) {
                      if (synchResult.getCode().equals(
                              RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
              }
          }
      }
 -    
 +
      /**
       * Show a text message on screen view for notifying user if content is
       * loading or folder is empty
      private class UploadFinishReceiver extends BroadcastReceiver {
          /**
           * Once the file upload has finished -> update view
 -         *  @author David A. Velasco
 +         *
 +         * @author David A. Velasco
           * {@link BroadcastReceiver} to enable upload feedback in UI
           */
          @Override
                  String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
                  boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
                  OCFile currentDir = getCurrentDir();
 -                boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) && 
 +                boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) &&
                          (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
 -                
 +
                  if (sameAccount && isDescendant) {
                      refreshListOfFilesFragment();
                  }
 -                
 +
                  boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT,
                          false);
                  boolean renamedInUpload = getFile().getRemotePath().
                          equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
 -                boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) || 
 +                boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
                          renamedInUpload;
                  FileFragment details = getSecondFragment();
 -                boolean detailFragmentIsShown = (details != null && 
 +                boolean detailFragmentIsShown = (details != null &&
                          details instanceof FileDetailFragment);
 -                
 +
                  if (sameAccount && sameFile && detailFragmentIsShown) {
                      if (uploadWasFine) {
                          setFile(getStorageManager().getFileByPath(uploadedRemotePath));
                      if (renamedInUpload) {
                          String newName = (new File(uploadedRemotePath)).getName();
                          Toast msg = Toast.makeText(
 -                                context, 
 +                                context,
                                  String.format(
 -                                        getString(R.string.filedetails_renamed_in_upload_msg), 
 -                                        newName), 
 +                                        getString(R.string.filedetails_renamed_in_upload_msg),
 +                                        newName),
                                  Toast.LENGTH_LONG);
                          msg.show();
                      }
                      if (uploadWasFine || getFile().fileExists()) {
 -                        ((FileDetailFragment)details).updateFileDetails(false, true);
 +                        ((FileDetailFragment) details).updateFileDetails(false, true);
                      } else {
                          cleanSecondFragment();
                      }
 -                    
 +
                      // Force the preview if the file is an image
                      if (uploadWasFine && PreviewImageFragment.canBePreviewed(getFile())) {
                          startImagePreview(getFile());
                      } // TODO what about other kind of previews?
                  }
  
+                 mProgressBar.setIndeterminate(false);
              } finally {
                  if (intent != null) {
                      removeStickyBroadcast(intent);
                  }
              }
 -            
 +
          }
 -        
 +
      }
  
  
      /**
       * Class waiting for broadcast events from the {@link FileDownloader} service.
 -     * 
 +     *
       * Updates the UI when a download is started or finished, provided that it is relevant for the
       * current folder.
       */
                              intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false)
                      );
                  }
 -    
 +
                  if (mWaitingToSend != null) {
                      mWaitingToSend =
                              getStorageManager().getFileByPath(mWaitingToSend.getRemotePath());
                          sendDownloadedFile();
                      }
                  }
 -            
 +
              } finally {
                  if (intent != null) {
                      removeStickyBroadcast(intent);
                      accountName.equals(getAccount().name));
          }
      }
 -    
 -    
 +
 +
      public void browseToRoot() {
 -        OCFileListFragment listOfFiles = getListOfFilesFragment(); 
 +        OCFileListFragment listOfFiles = getListOfFilesFragment();
          if (listOfFiles != null) {  // should never be null, indeed
              OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
              listOfFiles.listDirectory(root);
  
      /**
       * {@inheritDoc}
 -     * 
 +     * <p/>
       * Updates action bar and second fragment, if in dual pane mode.
       */
      @Override
      }
  
      /**
 -     * Shows the information of the {@link OCFile} received as a 
 +     * Shows the information of the {@link OCFile} received as a
       * parameter in the second fragment.
 -     * 
 -     * @param file          {@link OCFile} whose details will be shown
 +     *
 +     * @param file {@link OCFile} whose details will be shown
       */
      @Override
      public void showDetails(OCFile file) {
  
      }
  
      @Override
      protected ServiceConnection newTransferenceServiceConnection() {
          return new ListServiceConnection();
      }
  
 -    /** Defines callbacks for service binding, passed to bindService() */
 +    /**
 +     * Defines callbacks for service binding, passed to bindService()
 +     */
      private class ListServiceConnection implements ServiceConnection {
  
          @Override
                          if (!mWaitingToPreview.isDown()) {
                              requestForDownload();
                          }
 -                }
 +                    }
  
              } else if (component.equals(new ComponentName(FileDisplayActivity.this,
                      FileUploader.class))) {
              }
              FileFragment secondFragment = getSecondFragment();
              if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
 -                FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
 +                FileDetailFragment detailFragment = (FileDetailFragment) secondFragment;
                  detailFragment.listenForTransferProgress();
                  detailFragment.updateFileDetails(false, false);
              }
                  mUploaderBinder = null;
              }
          }
 -    };    
 +    }
  
      @Override
      public void onSavedCertificate() {
      /**
       * Updates the view associated to the activity after the finish of some operation over files
       * in the current account.
 -     * 
 -     * @param operation     Removal operation performed.
 -     * @param result        Result of the removal.
 +     *
 +     * @param operation Removal operation performed.
 +     * @param result    Result of the removal.
       */
      @Override
      public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
          super.onRemoteOperationFinish(operation, result);
 -        
 +
          if (operation instanceof RemoveFileOperation) {
              onRemoveFileOperationFinish((RemoveFileOperation) operation, result);
  
          } else if (operation instanceof RenameFileOperation) {
 -            onRenameFileOperationFinish((RenameFileOperation)operation, result);
 +            onRenameFileOperationFinish((RenameFileOperation) operation, result);
  
          } else if (operation instanceof SynchronizeFileOperation) {
 -            onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
 +            onSynchronizeFileOperationFinish((SynchronizeFileOperation) operation, result);
  
          } else if (operation instanceof CreateFolderOperation) {
 -            onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
 -            
 +            onCreateFolderOperationFinish((CreateFolderOperation) operation, result);
 +
          } else if (operation instanceof CreateShareOperation) {
              onCreateShareOperationFinish((CreateShareOperation) operation, result);
 -            
 +
          } else if (operation instanceof UnshareLinkOperation) {
 -            onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
 -        
 +            onUnshareLinkOperationFinish((UnshareLinkOperation) operation, result);
 +
          } else if (operation instanceof MoveFileOperation) {
 -            onMoveFileOperationFinish((MoveFileOperation)operation, result);
 +            onMoveFileOperationFinish((MoveFileOperation) operation, result);
 +
 +        } else if (operation instanceof CopyFileOperation) {
 +            onCopyFileOperationFinish((CopyFileOperation) operation, result);
          }
 -        
 +
      }
  
 -    
 +
      private void onCreateShareOperationFinish(CreateShareOperation operation,
                                                RemoteOperationResult result) {
          if (result.isSuccess()) {
          }
      }
  
 -    
 +
      private void onUnshareLinkOperationFinish(UnshareLinkOperation operation,
                                                RemoteOperationResult result) {
          if (result.isSuccess()) {
              refreshShowDetails();
              refreshListOfFilesFragment();
 -            
 +
          } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
              cleanSecondFragment();
              refreshListOfFilesFragment();
          }
      }
 -    
 +
      private void refreshShowDetails() {
          FileFragment details = getSecondFragment();
          if (details != null) {
              OCFile file = details.getFile();
              if (file != null) {
 -                file = getStorageManager().getFileByPath(file.getRemotePath()); 
 +                file = getStorageManager().getFileByPath(file.getRemotePath());
                  if (details instanceof PreviewMediaFragment) {
                      // Refresh  OCFile of the fragment
                      ((PreviewMediaFragment) details).updateFile(file);
                  } else {
                      showDetails(file);
 -                } 
 +                }
              }
              invalidateOptionsMenu();
 -        } 
 +        }
      }
 -    
 +
      /**
       * Updates the view associated to the activity after the finish of an operation trying to
       * remove a file.
      private void onRemoveFileOperationFinish(RemoveFileOperation operation,
                                               RemoteOperationResult result) {
          dismissLoadingDialog();
 -        
 +
          Toast msg = Toast.makeText(this,
                  ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
                  Toast.LENGTH_LONG); 
          msg.show();
 -        
 +
          if (result.isSuccess()) {
              OCFile removedFile = operation.getFile();
              FileFragment second = getSecondFragment();
              if (second != null && removedFile.equals(second.getFile())) {
                  if (second instanceof PreviewMediaFragment) {
 -                    ((PreviewMediaFragment)second).stopPreview(true);
 +                    ((PreviewMediaFragment) second).stopPreview(true);
                  }
                  setFile(getStorageManager().getFileById(removedFile.getParentId()));
                  cleanSecondFragment();
              }
          }
      }
 -    
 -    
 +
 +
      /**
 -     * Updates the view associated to the activity after the finish of an operation trying to move a 
 +     * Updates the view associated to the activity after the finish of an operation trying to move a
       * file.
 -     * 
 -     * @param operation     Move operation performed.
 -     * @param result        Result of the move operation.
 +     *
 +     * @param operation Move operation performed.
 +     * @param result    Result of the move operation.
       */
      private void onMoveFileOperationFinish(MoveFileOperation operation,
                                             RemoteOperationResult result) {
          } else {
              dismissLoadingDialog();
              try {
 -                Toast msg = Toast.makeText(FileDisplayActivity.this, 
 -                        ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()), 
 -                        Toast.LENGTH_LONG); 
 +                Toast msg = Toast.makeText(FileDisplayActivity.this,
 +                        ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
 +                        Toast.LENGTH_LONG);
                  msg.show();
  
              } catch (NotFoundException e) {
 -                Log_OC.e(TAG, "Error while trying to show fail message " , e);
 +                Log_OC.e(TAG, "Error while trying to show fail message ", e);
              }
          }
      }
  
 +    /**
 +     * Updates the view associated to the activity after the finish of an operation trying to copy a
 +     * file.
 +     *
 +     * @param operation Copy operation performed.
 +     * @param result    Result of the copy operation.
 +     */
 +    private void onCopyFileOperationFinish(CopyFileOperation operation, RemoteOperationResult result) {
 +        if (result.isSuccess()) {
 +            dismissLoadingDialog();
 +            refreshListOfFilesFragment();
 +        } else {
 +            dismissLoadingDialog();
 +            try {
 +                Toast msg = Toast.makeText(FileDisplayActivity.this,
 +                        ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
 +                        Toast.LENGTH_LONG);
 +                msg.show();
 +
 +            } catch (NotFoundException e) {
 +                Log_OC.e(TAG, "Error while trying to show fail message ", e);
 +            }
 +        }
 +    }
  
      /**
       * Updates the view associated to the activity after the finish of an operation trying to rename
                          renamedFile.equals(details.getFile())) {
                      ((PreviewMediaFragment) details).updateFile(renamedFile);
                      if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
 -                        int position = ((PreviewMediaFragment)details).getPosition();
 +                        int position = ((PreviewMediaFragment) details).getPosition();
                          startMediaPreview(renamedFile, position, true);
                      } else {
                          getFileOperationsHelper().openFile(renamedFile);
                      }
                  }
              }
 -            
 +
              if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())){
                  refreshListOfFilesFragment();
              }
                      ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
                      Toast.LENGTH_LONG); 
              msg.show();
 -            
 +
              if (result.isSslRecoverableException()) {
                  mLastSslUntrustedServerResult = result;
                  showUntrustedCertDialog(mLastSslUntrustedServerResult);
          } else {
              dismissLoadingDialog();
              try {
 -                Toast msg = Toast.makeText(FileDisplayActivity.this, 
 -                        ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()), 
 -                        Toast.LENGTH_LONG); 
 +                Toast msg = Toast.makeText(FileDisplayActivity.this,
 +                        ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
 +                        Toast.LENGTH_LONG);
                  msg.show();
  
              } catch (NotFoundException e) {
 -                Log_OC.e(TAG, "Error while trying to show fail message " , e);
 +                Log_OC.e(TAG, "Error while trying to show fail message ", e);
              }
          }
      }
  
 -    
 +
      /**
       * {@inheritDoc}
       */
          if (details != null && details instanceof FileDetailFragment &&
                  file.equals(details.getFile()) ) {
              if (downloading || uploading) {
 -                ((FileDetailFragment)details).updateFileDetails(file, getAccount());
 +                ((FileDetailFragment) details).updateFileDetails(file, getAccount());
              } else {
                  if (!file.fileExists()) {
                      cleanSecondFragment();
                  } else {
 -                    ((FileDetailFragment)details).updateFileDetails(false, true);
 +                    ((FileDetailFragment) details).updateFileDetails(false, true);
                  }
              }
          }
 -            
 +
      }
  
  
          }
          return null;
      }
 -    
 +
      public void startSyncFolderOperation(OCFile folder, boolean ignoreETag) {
 -        long currentSyncTime = System.currentTimeMillis(); 
 -        
 +        long currentSyncTime = System.currentTimeMillis();
 +
          mSyncInProgress = true;
 -                
 +
          // perform folder synchronization
          RemoteOperation synchFolderOp = new RefreshFolderOperation( folder,
                  currentSyncTime,
                  getApplicationContext()
          );
          synchFolderOp.execute(getAccount(), MainApp.getAppContext(), this, null, null);
-         
-         setSupportProgressBarIndeterminateVisibility(true);
+         mProgressBar.setIndeterminate(true);
  
          setBackgroundText();
      }
  
      /**
 -     * Show untrusted cert dialog 
 +     * Show untrusted cert dialog
       */
      public void showUntrustedCertDialog(RemoteOperationResult result) {
          // Show a dialog with the certificate info
          FragmentTransaction ft = fm.beginTransaction();
          dialog.show(ft, DIALOG_UNTRUSTED_CERT);
      }
 -    
 +
      private void requestForDownload(OCFile file) {
          Account account = getAccount();
          if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
              startService(i);
          }
      }
 -    
 -    private void sendDownloadedFile(){
 +
 +    private void sendDownloadedFile() {
          getFileOperationsHelper().sendDownloadedFile(mWaitingToSend);
          mWaitingToSend = null;
      }
  
 -    
 +
      /**
       * Requests the download of the received {@link OCFile} , updates the UI
       * to monitor the download progress and prepares the activity to send the file
       * when the download finishes.
 -     * 
 -     * @param file          {@link OCFile} to download and preview.
 +     *
 +     * @param file {@link OCFile} to download and preview.
       */
      public void startDownloadForSending(OCFile file) {
          mWaitingToSend = file;
          requestForDownload(mWaitingToSend);
 -        boolean hasSecondFragment = (getSecondFragment()!= null);
 +        boolean hasSecondFragment = (getSecondFragment() != null);
          updateFragmentsVisibility(hasSecondFragment);
      }
 -    
 +
      /**
       * Opens the image gallery showing the image {@link OCFile} received as parameter.
 -     * 
 -     * @param file                      Image {@link OCFile} to show.
 +     *
 +     * @param file Image {@link OCFile} to show.
       */
      public void startImagePreview(OCFile file) {
          Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
          showDetailsIntent.putExtra(EXTRA_FILE, file);
          showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
          startActivity(showDetailsIntent);
 -        
 +
      }
  
      /**
       * Stars the preview of an already down media {@link OCFile}.
 -     * 
 +     *
       * @param file                      Media {@link OCFile} to preview.
       * @param startPlaybackPosition     Media position where the playback will be started,
       *                                  in milliseconds.
       * Requests the download of the received {@link OCFile} , updates the UI
       * to monitor the download progress and prepares the activity to preview
       * or open the file when the download finishes.
 -     * 
 -     * @param file          {@link OCFile} to download and preview.
 +     *
 +     * @param file {@link OCFile} to download and preview.
       */
      public void startDownloadForPreview(OCFile file) {
          Fragment detailFragment = FileDetailFragment.newInstance(file, getAccount());
  
      public void cancelTransference(OCFile file) {
          getFileOperationsHelper().cancelTransference(file);
 -        if (mWaitingToPreview != null && 
 +        if (mWaitingToPreview != null &&
                  mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
              mWaitingToPreview = null;
          }
          }
      }
  
 -    private void sortByDate(boolean ascending){
 +    private void sortByDate(boolean ascending) {
          getListOfFilesFragment().sortByDate(ascending);
      }
  
 -    private void sortBySize(boolean ascending){
 +    private void sortBySize(boolean ascending) {
          getListOfFilesFragment().sortBySize(ascending);
      }
  
 -    private void sortByName(boolean ascending){
 +    private void sortByName(boolean ascending) {
          getListOfFilesFragment().sortByName(ascending);
      }
  
@@@ -71,8 -71,8 +71,8 @@@ public class ExtendedListFragment exten
      private ArrayList<Integer> mTops;
      private int mHeightCell = 0;
  
 -    private OnEnforceableRefreshListener mOnRefreshListener = null;
 -    
 +    private SwipeRefreshLayout.OnRefreshListener mOnRefreshListener = null;
 +
      protected AbsListView mCurrentListView;
      private ExtendedListView mListView;
      private View mListFooterView;
      }
  
      private void onCreateSwipeToRefresh(SwipeRefreshLayout refreshLayout) {
-         // Colors in animations: background
-         refreshLayout.setColorScheme(R.color.background_color, R.color.background_color,
-                 R.color.background_color, R.color.background_color);
+         // Colors in animations
+         refreshLayout.setColorSchemeResources(R.color.color_accent, R.color.primary,
+                 R.color.primary_dark);
  
          refreshLayout.setOnRefreshListener(this);
      }
          mRefreshEmptyLayout.setRefreshing(false);
  
          if (mOnRefreshListener != null) {
 -            mOnRefreshListener.onRefresh(ignoreETag);
 +            mOnRefreshListener.onRefresh();
          }
      }
  
   */
  package com.owncloud.android.ui.fragment;
  
 -import java.lang.ref.WeakReference;
 -
  import android.accounts.Account;
 -import android.content.Intent;
  import android.os.Bundle;
  import android.view.LayoutInflater;
  import android.view.Menu;
@@@ -43,14 -46,13 +43,14 @@@ import com.owncloud.android.files.servi
  import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
  import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
  import com.owncloud.android.lib.common.utils.Log_OC;
 -import com.owncloud.android.services.observer.FileObserverService;
  import com.owncloud.android.ui.activity.FileActivity;
  import com.owncloud.android.ui.activity.FileDisplayActivity;
  import com.owncloud.android.ui.dialog.RemoveFileDialogFragment;
  import com.owncloud.android.ui.dialog.RenameFileDialogFragment;
  import com.owncloud.android.utils.DisplayUtils;
  
 +import java.lang.ref.WeakReference;
 +
  
  /**
   * This Fragment is used to display the details about a file.
@@@ -60,9 -62,9 +60,9 @@@ public class FileDetailFragment extend
      private int mLayout;
      private View mView;
      private Account mAccount;
 -    
 +
      public ProgressListener mProgressListener;
 -    
 +
      private static final String TAG = FileDetailFragment.class.getSimpleName();
      public static final String FTAG_CONFIRMATION = "REMOVE_CONFIRMATION_FRAGMENT";
      public static final String FTAG_RENAME_FILE = "RENAME_FILE_FRAGMENT";
          mLayout = R.layout.file_details_empty;
          mProgressListener = null;
      }
 -    
 +
  
      @Override
      public void onActivityCreated(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setHasOptionsMenu(true);
      }
 -    
 +
  
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
          mAccount = getArguments().getParcelable(ARG_ACCOUNT);
  
          if (savedInstanceState != null) {
 -            setFile((OCFile)savedInstanceState.getParcelable(FileActivity.EXTRA_FILE));
 +            setFile((OCFile) savedInstanceState.getParcelable(FileActivity.EXTRA_FILE));
              mAccount = savedInstanceState.getParcelable(FileActivity.EXTRA_ACCOUNT);
          }
 -        
 -        if(getFile() != null && mAccount != null) {
 +
 +        if (getFile() != null && mAccount != null) {
              mLayout = R.layout.file_details_fragment;
          }
 -        
 +
          mView = inflater.inflate(mLayout, null);
          
          if (mLayout == R.layout.file_details_fragment) {
              mView.findViewById(R.id.fdFavorite).setOnClickListener(this);
              ProgressBar progressBar = (ProgressBar)mView.findViewById(R.id.fdProgressBar);
+             DisplayUtils.colorPreLollipopHorizontalProgressBar(progressBar);
              mProgressListener = new ProgressListener(progressBar);
              mView.findViewById(R.id.fdCancelBtn).setOnClickListener(this);
          }
          super.onStart();
          listenForTransferProgress();
      }
 -    
 +
      @Override
      public void onStop() {
          leaveTransferProgress();
          super.onStop();
      }
  
 -    
 +
      @Override
      public View getView() {
          return super.getView() == null ? mView : super.getView();
      }
  
 -    
 +
      /**
       * {@inheritDoc}
       */
      public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
          super.onCreateOptionsMenu(menu, inflater);
          inflater.inflate(R.menu.file_actions_menu, menu);
 -   }
 +    }
 +
  
 -    
      /**
       * {@inheritDoc}
       */
      @Override
 -    public void onPrepareOptionsMenu (Menu menu) {
 +    public void onPrepareOptionsMenu(Menu menu) {
          super.onPrepareOptionsMenu(menu);
 -        
 +
          if (mContainerActivity.getStorageManager() != null) {
              FileMenuFilter mf = new FileMenuFilter(
                  getFile(),
              );
              mf.filter(menu);
          }
 -        
 +
          // additional restriction for this fragment 
          MenuItem item = menu.findItem(R.id.action_see_details);
          if (item != null) {
              item.setVisible(false);
              item.setEnabled(false);
          }
 +
 +        // additional restriction for this fragment
 +        item = menu.findItem(R.id.action_copy);
 +        if (item != null) {
 +            item.setVisible(false);
 +            item.setEnabled(false);
 +        }
      }
  
 -    
 +
      /**
       * {@inheritDoc}
       */
              }
              case R.id.action_cancel_download:
              case R.id.action_cancel_upload: {
 -                ((FileDisplayActivity)mContainerActivity).cancelTransference(getFile());
 +                ((FileDisplayActivity) mContainerActivity).cancelTransference(getFile());
                  return true;
              }
 -            case R.id.action_download_file: 
 +            case R.id.action_download_file:
              case R.id.action_sync_file: {
                  mContainerActivity.getFileOperationsHelper().syncFile(getFile());
                  return true;
                  // Obtain the file
                  if (!getFile().isDown()) {  // Download the file                    
                      Log_OC.d(TAG, getFile().getRemotePath() + " : File must be downloaded");
 -                    ((FileDisplayActivity)mContainerActivity).startDownloadForSending(getFile());
 -                    
 -                } else {
 +                    ((FileDisplayActivity) mContainerActivity).startDownloadForSending(getFile());
 +
 +                }
 +                else {
                      mContainerActivity.getFileOperationsHelper().sendDownloadedFile(getFile());
                  }
                  return true;
                  break;
              }
              case R.id.fdCancelBtn: {
 -                ((FileDisplayActivity)mContainerActivity).cancelTransference(getFile());
 +                ((FileDisplayActivity) mContainerActivity).cancelTransference(getFile());
                  break;
              }
              default:
  
      /**
       * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
 -     * 
 -     * @return  True when the fragment was created with the empty layout.
 +     *
 +     * @return True when the fragment was created with the empty layout.
       */
      public boolean isEmpty() {
          return (mLayout == R.layout.file_details_empty || getFile() == null || mAccount == null);
      }
  
 -    
 +
      /**
       * Use this method to signal this Activity that it shall update its view.
 -     * 
 +     *
       * @param file : An {@link OCFile}
       */
      public void updateFileDetails(OCFile file, Account ocAccount) {
  
      /**
       * Updates the view with all relevant details about that file.
 +     * <p/>
 +     * TODO Remove parameter when the transferring state of files is kept in database.
       *
 -     * TODO Remove parameter when the transferring state of files is kept in database. 
 -     * 
 -     * @param transferring      Flag signaling if the file should be considered as downloading or uploading, 
 -     *                          although {@link FileDownloaderBinder#isDownloading(Account, OCFile)}  and 
 -     *                          {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
 -     *                          
 -     * @param refresh           If 'true', try to refresh the whole file from the database
 +     * @param transferring Flag signaling if the file should be considered as downloading or uploading,
 +     *                     although {@link FileDownloaderBinder#isDownloading(Account, OCFile)}  and
 +     *                     {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
 +     * @param refresh      If 'true', try to refresh the whole file from the database
       */
      public void updateFileDetails(boolean transferring, boolean refresh) {
          if (readyToShow()) {
                  setFile(storageManager.getFileByPath(getFile().getRemotePath()));
              }
              OCFile file = getFile();
 -            
 +
              // set file details
              setFilename(file.getFileName());
              setFiletype(file.getMimetype(), file.getFileName());
                      (uploaderBinder != null && uploaderBinder.isUploading(mAccount, file))
                      ) {
                  setButtonsForTransferring();
 -                
 +
              } else if (file.isDown()) {
                  
                  setButtonsForDown();
          }
          getView().invalidate();
      }
 -    
 +
      /**
       * Checks if the fragment is ready to show details of a OCFile
 -     *  
 -     * @return  'True' when the fragment is ready to show details of a file
 +     *
 +     * @return 'True' when the fragment is ready to show details of a file
       */
      private boolean readyToShow() {
 -        return (getFile() != null && mAccount != null && mLayout == R.layout.file_details_fragment);        
 +        return (getFile() != null && mAccount != null && mLayout == R.layout.file_details_fragment);
      }
  
  
      /**
       * Updates the filename in view
 +     *
       * @param filename to set
       */
      private void setFilename(String filename) {
          TextView tv = (TextView) getView().findViewById(R.id.fdFilename);
 -        if (tv != null)
 +        if (tv != null) {
              tv.setText(filename);
 +        }
      }
  
      /**
  
      /**
       * Updates the file size in view
 +     *
       * @param filesize in bytes to set
       */
      private void setFilesize(long filesize) {
          TextView tv = (TextView) getView().findViewById(R.id.fdSize);
 -        if (tv != null)
 +        if (tv != null) {
              tv.setText(DisplayUtils.bytesToHumanReadable(filesize));
 +        }
      }
 -    
 +
      /**
       * Updates the time that the file was last modified
 +     *
       * @param milliseconds Unix time to set
       */
 -    private void setTimeModified(long milliseconds){
 +    private void setTimeModified(long milliseconds) {
          TextView tv = (TextView) getView().findViewById(R.id.fdModified);
 -        if(tv != null){
 +        if (tv != null) {
              tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
          }
      }
 -    
 +
      /**
       * Enables or disables buttons for a file being downloaded
       */
              
              // show the progress bar for the transfer
              getView().findViewById(R.id.fdProgressBlock).setVisibility(View.VISIBLE);
 -            TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
 +            TextView progressText = (TextView) getView().findViewById(R.id.fdProgressText);
              progressText.setVisibility(View.VISIBLE);
              FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
              FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
              //if (getFile().isDownloading()) {
              if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, getFile())) {
                  progressText.setText(R.string.downloader_download_in_progress_ticker);
 -            } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, getFile())) {
 -                progressText.setText(R.string.uploader_upload_in_progress_ticker);
 +            }
 +            else {
 +                if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, getFile())) {
 +                    progressText.setText(R.string.uploader_upload_in_progress_ticker);
 +                }
              }
          }
      }
  
      /**
 -     * Enables or disables buttons for a file locally available 
 +     * Enables or disables buttons for a file locally available
       */
      private void setButtonsForDown() {
          if (!isEmpty()) {
              
              // hides the progress bar
              getView().findViewById(R.id.fdProgressBlock).setVisibility(View.GONE);
 -            TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
 +            TextView progressText = (TextView) getView().findViewById(R.id.fdProgressText);
              progressText.setVisibility(View.GONE);
          }
      }
  
      /**
 -     * Enables or disables buttons for a file not locally available 
 +     * Enables or disables buttons for a file not locally available
       */
      private void setButtonsForRemote() {
          if (!isEmpty()) {
              
              // hides the progress bar
              getView().findViewById(R.id.fdProgressBlock).setVisibility(View.GONE);
 -            TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
 +            TextView progressText = (TextView) getView().findViewById(R.id.fdProgressText);
              progressText.setVisibility(View.GONE);
          }
      }
 -    
 +
  
      public void listenForTransferProgress() {
          if (mProgressListener != null) {
              }
          }
      }
 -    
 -    
 +
 +
      public void leaveTransferProgress() {
          if (mProgressListener != null) {
              if (mContainerActivity.getFileDownloaderBinder() != null) {
      }
  
  
 -    
      /**
       * Helper class responsible for updating the progress bar shown for file uploading or
       * downloading
      private class ProgressListener implements OnDatatransferProgressListener {
          int mLastPercent = 0;
          WeakReference<ProgressBar> mProgressBar = null;
 -        
 +
          ProgressListener(ProgressBar progressBar) {
              mProgressBar = new WeakReference<ProgressBar>(progressBar);
          }
 -        
 +
          @Override
          public void onTransferProgress(long progressRate, long totalTransferredSoFar,
                                         long totalToTransfer, String filename) {
   */
  package com.owncloud.android.ui.fragment;
  
 -import java.io.File;
 -
  import android.app.Activity;
  import android.content.Intent;
  import android.os.Bundle;
  import android.support.v4.widget.SwipeRefreshLayout;
  import android.view.ContextMenu;
+ import android.view.Menu;
  import android.view.MenuInflater;
  import android.view.MenuItem;
  import android.view.View;
  import android.widget.AdapterView;
  import android.widget.AdapterView.AdapterContextMenuInfo;
+ import android.widget.PopupMenu;
  
  import com.owncloud.android.R;
  import com.owncloud.android.authentication.AccountUtils;
@@@ -46,34 -50,33 +48,35 @@@ import com.owncloud.android.ui.activity
  import com.owncloud.android.ui.activity.OnEnforceableRefreshListener;
  import com.owncloud.android.ui.adapter.FileListListAdapter;
  import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
+ import com.owncloud.android.ui.dialog.FileActionsDialogFragment;
  import com.owncloud.android.ui.dialog.RemoveFileDialogFragment;
  import com.owncloud.android.ui.dialog.RenameFileDialogFragment;
  import com.owncloud.android.ui.preview.PreviewImageFragment;
  import com.owncloud.android.ui.preview.PreviewMediaFragment;
 -import com.owncloud.android.utils.DialogMenuItem;
  import com.owncloud.android.utils.FileStorageUtils;
  
 +import java.io.File;
 +import java.util.Vector;
 +
  /**
   * A Fragment that lists all files and folders in a given path.
 - * 
 + *
   * TODO refactor to get rid of direct dependency on FileDisplayActivity
   */
- public class OCFileListFragment extends ExtendedListFragment {
+ public class OCFileListFragment extends ExtendedListFragment implements FileActionsDialogFragment.FileActionsDialogFragmentListener {
+     
      private static final String TAG = OCFileListFragment.class.getSimpleName();
  
      private static final String MY_PACKAGE = OCFileListFragment.class.getPackage() != null ?
              OCFileListFragment.class.getPackage().getName() : "com.owncloud.android.ui.fragment";
 -            
 +
      public final static String ARG_JUST_FOLDERS = MY_PACKAGE + ".JUST_FOLDERS";
      public final static String ARG_ALLOW_CONTEXTUAL_ACTIONS = MY_PACKAGE + ".ALLOW_CONTEXTUAL";
 -            
 +
      private static final String KEY_FILE = MY_PACKAGE + ".extra.FILE";
  
      private FileFragment.ContainerActivity mContainerActivity;
 -   
 +
      private OCFile mFile = null;
      private FileListListAdapter mAdapter;
      private boolean mJustFolders;
          Log_OC.e(TAG, "onAttach");
          try {
              mContainerActivity = (FileFragment.ContainerActivity) activity;
 -            
 +
          } catch (ClassCastException e) {
 -            throw new ClassCastException(activity.toString() + " must implement " + 
 +            throw new ClassCastException(activity.toString() + " must implement " +
                      FileFragment.ContainerActivity.class.getSimpleName());
          }
          try {
              setOnRefreshListener((OnEnforceableRefreshListener) activity);
              
          } catch (ClassCastException e) {
 -            throw new ClassCastException(activity.toString() + " must implement " + 
 +            throw new ClassCastException(activity.toString() + " must implement " +
                      SwipeRefreshLayout.OnRefreshListener.class.getSimpleName());
          }
      }
  
 -    
 +
      @Override
      public void onDetach() {
          setOnRefreshListener(null);
                  mJustFolders,
                  getActivity(),
                  mContainerActivity
 -                );
 +        );
          setListAdapter(mAdapter);
  
-         registerForContextMenu();
+         registerLongClickListener();
    }
  
+     private void registerLongClickListener() {
+         getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
+             public boolean onItemLongClick(AdapterView<?> arg0, View v,
+                                            int index, long arg3) {
+                 showFileAction(index);
+                 return true;
+             }
+         });
+     }
+     private void showFileAction(int fileIndex) {
+         Bundle args = getArguments();
+         PopupMenu pm = new PopupMenu(getActivity(),null);
+         Menu menu = pm.getMenu();
+         boolean allowContextualActions =
+                 (args == null) ? true : args.getBoolean(ARG_ALLOW_CONTEXTUAL_ACTIONS, true);
+         if (allowContextualActions) {
+             MenuInflater inflater = getActivity().getMenuInflater();
+             inflater.inflate(R.menu.file_actions_menu, menu);
+             OCFile targetFile = (OCFile) mAdapter.getItem(fileIndex);
+             if (mContainerActivity.getStorageManager() != null) {
+                 FileMenuFilter mf = new FileMenuFilter(
+                         targetFile,
+                         mContainerActivity.getStorageManager().getAccount(),
+                         mContainerActivity,
+                         getActivity()
+                 );
+                 mf.filter(menu);
+             }
+             /// TODO break this direct dependency on FileDisplayActivity... if possible
+             MenuItem item = menu.findItem(R.id.action_open_file_with);
+             FileFragment frag = ((FileDisplayActivity)getActivity()).getSecondFragment();
+             if (frag != null && frag instanceof FileDetailFragment &&
+                     frag.getFile().getFileId() == targetFile.getFileId()) {
+                 item = menu.findItem(R.id.action_see_details);
+                 if (item != null) {
+                     item.setVisible(false);
+                     item.setEnabled(false);
+                 }
+             }
+             FileActionsDialogFragment dialog = FileActionsDialogFragment.newInstance(menu, fileIndex);
+             dialog.setTargetFragment(this, 0);
+             dialog.show(getFragmentManager(), FileActionsDialogFragment.FTAG_FILE_ACTIONS);
+         }
+     }
      /**
       * Saves the current listed folder.
       */
      @Override
 -    public void onSaveInstanceState (Bundle outState) {
 +    public void onSaveInstanceState(Bundle outState) {
          super.onSaveInstanceState(outState);
          outState.putParcelable(KEY_FILE, mFile);
      }
 -    
 +
      /**
       * Call this, when the user presses the up button.
-      * <p/>
 -     * 
++     *
       * Tries to move up the current folder one level. If the parent folder was removed from the
       * database, it continues browsing up until finding an existing folders.
 -     * 
 +     * <p/>
       * return       Count of folder levels browsed up.
       */
      public int onBrowseUp() {
          OCFile parentDir = null;
          int moveCount = 0;
 -        
 -        if(mFile != null){
 +
 +        if (mFile != null) {
              FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
 -            
 +
              String parentPath = null;
              if (mFile.getParentId() != FileDataStorageManager.ROOT_PARENT_ID) {
                  parentPath = new File(mFile.getRemotePath()).getParent();
 -                parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : 
 -                      parentPath + OCFile.PATH_SEPARATOR;
 +                parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath :
 +                        parentPath + OCFile.PATH_SEPARATOR;
                  parentDir = storageManager.getFileByPath(parentPath);
                  moveCount++;
              } else {
              }
              while (parentDir == null) {
                  parentPath = new File(parentPath).getParent();
 -                parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : 
 -                      parentPath + OCFile.PATH_SEPARATOR;
 +                parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath :
 +                        parentPath + OCFile.PATH_SEPARATOR;
                  parentDir = storageManager.getFileByPath(parentPath);
                  moveCount++;
              }   // exit is granted because storageManager.getFileByPath("/") never returns null
              listDirectory(mFile /*, MainApp.getOnlyOnDevice()*/);
  
              onRefresh(false);
 -            
 +
              // restore index and top position
              restoreIndexAndTopPosition();
 -            
 +
          }   // else - should never happen now
 -   
 +
          return moveCount;
      }
 -    
 +
      @Override
      public void onItemClick(AdapterView<?> l, View v, int position, long id) {
          OCFile file = (OCFile) mAdapter.getItem(position);
          if (file != null) {
 -            if (file.isFolder()) { 
 +            if (file.isFolder()) {
                  // update state and view of this fragment
                  // TODO Enable when "On Device" is recovered ?
                  listDirectory(file/*, MainApp.getOnlyOnDevice()*/);
                  mContainerActivity.onBrowsedDownTo(file);
                  // save index and top position
                  saveIndexAndTopPosition(position);
 -                
 +
              } else { /// Click on a file
                  if (PreviewImageFragment.canBePreviewed(file)) {
                      // preview image - it handles the download, if needed
 -                    ((FileDisplayActivity)mContainerActivity).startImagePreview(file);
 -                    
 +                    ((FileDisplayActivity) mContainerActivity).startImagePreview(file);
 +
                  } else if (file.isDown()) {
                      if (PreviewMediaFragment.canBePreviewed(file)) {
                          // media preview
 -                        ((FileDisplayActivity)mContainerActivity).startMediaPreview(file, 0, true);
 +                        ((FileDisplayActivity) mContainerActivity).startMediaPreview(file, 0, true);
                      } else {
                          mContainerActivity.getFileOperationsHelper().openFile(file);
                      }
 -                    
 +
                  } else {
                      // automatic download, preview on finish
 -                    ((FileDisplayActivity)mContainerActivity).startDownloadForPreview(file);
 +                    ((FileDisplayActivity) mContainerActivity).startDownloadForPreview(file);
                  }
 -                    
 +
              }
 -            
 +
          } else {
              Log_OC.d(TAG, "Null object in ListAdapter!!");
          }
 -        
 +
      }
 -    
 +
      /**
       * {@inheritDoc}
       */
      @Override
 -    public void onCreateContextMenu (
 +    public void onCreateContextMenu(
              ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
-         super.onCreateContextMenu(menu, v, menuInfo);
          Bundle args = getArguments();
 -        boolean allowContextualActions = 
 -                (args == null) ? true : args.getBoolean(ARG_ALLOW_CONTEXTUAL_ACTIONS, true); 
 +        boolean allowContextualActions =
 +                (args == null) ? true : args.getBoolean(ARG_ALLOW_CONTEXTUAL_ACTIONS, true);
          if (allowContextualActions) {
              MenuInflater inflater = getActivity().getMenuInflater();
              inflater.inflate(R.menu.file_actions_menu, menu);
              AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
              OCFile targetFile = (OCFile) mAdapter.getItem(info.position);
 -            
 +
              if (mContainerActivity.getStorageManager() != null) {
                  FileMenuFilter mf = new FileMenuFilter(
                      targetFile,
          }
      }
  
      /**
-      * {@inhericDoc}
+      * {@inheritDoc}
       */
      @Override
-     public boolean onContextItemSelected(MenuItem item) {
-         AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
-         mTargetFile = (OCFile) mAdapter.getItem(info.position);
-         switch (item.getItemId()) {
+     public boolean onFileActionChosen(int menuId, int filePosition) {
+         mTargetFile = (OCFile) mAdapter.getItem(filePosition);
+         switch (menuId) {
              case R.id.action_share_file: {
                  mContainerActivity.getFileOperationsHelper().shareFileWithLink(mTargetFile);
                  return true;
                  getActivity().startActivityForResult(action, FileDisplayActivity.ACTION_MOVE_FILES);
                  return true;
              }
-             case R.id.action_favorite_file:{
+             case R.id.action_favorite_file: {
                  mContainerActivity.getFileOperationsHelper().toggleFavorite(mTargetFile, true);
                  return true;
              }
-             case R.id.action_unfavorite_file:{
+             case R.id.action_unfavorite_file: {
                  mContainerActivity.getFileOperationsHelper().toggleFavorite(mTargetFile, false);
                  return true;
              }
 +            case R.id.action_copy:
 +                Intent action = new Intent(getActivity(), FolderPickerActivity.class);
 +
 +                // Pass mTargetFile that contains info of selected file/folder
 +                action.putExtra(FolderPickerActivity.EXTRA_FILE, mTargetFile);
 +                getActivity().startActivityForResult(action, FileDisplayActivity.ACTION_COPY_FILES);
 +                return true;
              default:
-                 return super.onContextItemSelected(item);
+                 return false;
+         }
+     }
+     
+     /**
+      * {@inhericDoc}
+      */
+     @Override
+     public boolean onContextItemSelected (MenuItem item) {
+         AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
+         boolean matched = onFileActionChosen(item.getItemId(), ((AdapterContextMenuInfo) item.getMenuInfo()).position);
+         if(!matched) {
+             return super.onContextItemSelected(item);
+         } else {
+             return matched;
          }
      }
  
      /**
       * Use this to query the {@link OCFile} that is currently
       * being displayed by this fragment
 +     *
       * @return The currently viewed OCFile
       */
 -    public OCFile getCurrentFile(){
 +    public OCFile getCurrentFile() {
          return mFile;
      }
 -    
 +
      /**
       * Calls {@link OCFileListFragment#listDirectory(OCFile)} with a null parameter
       */
          // TODO Enable when "On Device" is recovered ?
          listDirectory(getCurrentFile()/*, MainApp.getOnlyOnDevice()*/);
      }
 -    
 +
      /**
       * Lists the given directory on the view. When the input parameter is null,
       * it will either refresh the last known directory. list the root
       * if there never was a directory.
 -     * 
 +     *
       * @param directory File to be listed
       */
      public void listDirectory(OCFile directory/*, boolean onlyOnDevice*/) {
          if (storageManager != null) {
  
              // Check input parameters for null
 -            if(directory == null){
 -                if(mFile != null){
 +            if (directory == null) {
 +                if (mFile != null) {
                      directory = mFile;
                  } else {
                      directory = storageManager.getFileByPath("/");
                      if (directory == null) return; // no files, wait for sync
                  }
              }
 -        
 -        
 +
 +
              // If that's not a directory -> List its parent
 -            if(!directory.isFolder()){
 +            if (!directory.isFolder()) {
                  Log_OC.w(TAG, "You see, that is not a directory -> " + directory.toString());
                  directory = storageManager.getFileById(directory.getParentId());
              }
                  if (file.isFolder()) {
                      foldersCount++;
                  } else {
-                     filesCount++;
-                     if (file.isImage()){
-                         imagesCount++;
+                     if (!file.isHidden()) {
+                         filesCount++;
+                         if (file.isImage()) {
+                             imagesCount++;
+                         }
                      }
                  }
              }
              if (version != null && version.supportsRemoteThumbnails() &&
                  imagesCount > 0 && imagesCount == filesCount) {
                  switchToGridView();
+                 registerLongClickListener();
              } else {
                  switchToListView();
              }
          return output;
      }
  
      public void sortByName(boolean descending) {
          mAdapter.setSortOrder(FileStorageUtils.SORT_NAME, descending);
      }
      public void sortBySize(boolean descending) {
          mAdapter.setSortOrder(FileStorageUtils.SORT_SIZE, descending);
      }
-     
  }
@@@ -36,13 -36,9 +36,9 @@@ import android.view.ViewGroup
  import android.widget.ProgressBar;
  import android.widget.TextView;
  
- import com.owncloud.android.R;
- import com.owncloud.android.datamodel.OCFile;
  import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
  import com.owncloud.android.lib.common.utils.Log_OC;
- import com.owncloud.android.ui.fragment.FileFragment;
- import java.lang.ref.WeakReference;
+ import com.owncloud.android.utils.DisplayUtils;
  
  
  /**
@@@ -63,9 -59,9 +59,9 @@@ public class FileDownloadFragment exten
  
      public ProgressListener mProgressListener;
      private boolean mListening;
 -    
 +
      private static final String TAG = FileDownloadFragment.class.getSimpleName();
 -    
 +
      private boolean mIgnoreFirstSavedState;
      private boolean mError;
  
          mIgnoreFirstSavedState = args.getBoolean(ARG_IGNORE_FIRST);
          mAccount = args.getParcelable(ARG_ACCOUNT);
      }
 -    
 +
  
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
 -            Bundle savedInstanceState) {
 +                             Bundle savedInstanceState) {
          super.onCreateView(inflater, container, savedInstanceState);
 -        
 +
          if (savedInstanceState != null) {
              if (!mIgnoreFirstSavedState) {
 -                setFile((OCFile)savedInstanceState.getParcelable(FileDownloadFragment.EXTRA_FILE));
 +                setFile((OCFile) savedInstanceState.getParcelable(FileDownloadFragment.EXTRA_FILE));
                  mAccount = savedInstanceState.getParcelable(FileDownloadFragment.EXTRA_ACCOUNT);
                  mError = savedInstanceState.getBoolean(FileDownloadFragment.EXTRA_ERROR);
 -            } else {
 +            }
 +            else {
                  mIgnoreFirstSavedState = false;
              }
          }
  
-         View view = null;
-         view = inflater.inflate(R.layout.file_download_fragment, container, false);
-         mView = view;
-         ProgressBar progressBar = (ProgressBar) mView.findViewById(R.id.progressBar);
+         mView = inflater.inflate(R.layout.file_download_fragment, container, false);
+         
+         ProgressBar progressBar = (ProgressBar)mView.findViewById(R.id.progressBar);
+         DisplayUtils.colorPreLollipopHorizontalProgressBar(progressBar);
          mProgressListener = new ProgressListener(progressBar);
 -        
 +
          (mView.findViewById(R.id.cancelBtn)).setOnClickListener(this);
          
          (mView.findViewById(R.id.fileDownloadLL)).setOnClickListener(new OnClickListener() {
  
          if (mError) {
              setButtonsForRemote();
 -        } else {
 +        }
 +        else {
              setButtonsForTransferring();
          }
 -        
 +
-         return view;
+         return mView;
      }
 -    
 +
  
      @Override
      public void onSaveInstanceState(Bundle outState) {
          super.onStart();
          listenForTransferProgress();
      }
 -    
 +
      @Override
      public void onResume() {
          super.onResume();
          super.onPause();
      }
  
 -    
 +
      @Override
      public void onStop() {
          leaveTransferProgress();
          super.onStop();
      }
 -    
 +
      @Override
      public void onDestroy() {
          super.onDestroy();
      }
 -    
 -    
 +
 +
      @Override
      public View getView() {
          if (!mListening) {
          return super.getView() == null ? mView : super.getView();
      }
  
 -    
 +
      @Override
      public void onClick(View v) {
          switch (v.getId()) {
          }
      }
  
 -    
 +
      /**
       * Enables or disables buttons for a file being downloaded
       */
      private void setButtonsForTransferring() {
          getView().findViewById(R.id.cancelBtn).setVisibility(View.VISIBLE);
 -    
 +
          // show the progress bar for the transfer
          getView().findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
 -        TextView progressText = (TextView)getView().findViewById(R.id.progressText);
 +        TextView progressText = (TextView) getView().findViewById(R.id.progressText);
          progressText.setText(R.string.downloader_download_in_progress_ticker);
          progressText.setVisibility(View.VISIBLE);
 -                
 +
          // hides the error icon
          getView().findViewById(R.id.errorText).setVisibility(View.GONE);
          getView().findViewById(R.id.error_image).setVisibility(View.GONE);
      }
 -    
  
      /**
 -     * Enables or disables buttons for a file locally available 
 +     * Enables or disables buttons for a file locally available
       */
      private void setButtonsForDown() {
          getView().findViewById(R.id.cancelBtn).setVisibility(View.GONE);
 -    
 +
          // hides the progress bar
          getView().findViewById(R.id.progressBar).setVisibility(View.GONE);
 -        
 +
          // updates the text message
 -        TextView progressText = (TextView)getView().findViewById(R.id.progressText);
 +        TextView progressText = (TextView) getView().findViewById(R.id.progressText);
          progressText.setText(R.string.common_loading);
          progressText.setVisibility(View.VISIBLE);
 -        
 +
          // hides the error icon
          getView().findViewById(R.id.errorText).setVisibility(View.GONE);
          getView().findViewById(R.id.error_image).setVisibility(View.GONE);
      }
  
 -    
 +
      /**
 -     * Enables or disables buttons for a file not locally available 
 -     * 
 +     * Enables or disables buttons for a file not locally available
 +     * <p/>
       * Currently, this is only used when a download was failed
       */
      private void setButtonsForRemote() {
          getView().findViewById(R.id.cancelBtn).setVisibility(View.GONE);
 -        
 +
          // hides the progress bar and message
          getView().findViewById(R.id.progressBar).setVisibility(View.GONE);
          getView().findViewById(R.id.progressText).setVisibility(View.GONE);
          getView().findViewById(R.id.errorText).setVisibility(View.VISIBLE);
          getView().findViewById(R.id.error_image).setVisibility(View.VISIBLE);
      }
 -    
 +
  
      public void listenForTransferProgress() {
          if (mProgressListener != null && !mListening) {
              }
          }
      }
 -    
 -    
 +
 +
      public void leaveTransferProgress() {
          if (mProgressListener != null) {
              if (mContainerActivity.getFileDownloaderBinder() != null) {
      private class ProgressListener implements OnDatatransferProgressListener {
          int mLastPercent = 0;
          WeakReference<ProgressBar> mProgressBar = null;
 -        
 +
          ProgressListener(ProgressBar progressBar) {
              mProgressBar = new WeakReference<ProgressBar>(progressBar);
          }
 -        
 +
          @Override
          public void onTransferProgress(
                  long progressRate, long totalTransferredSoFar, long totalToTransfer, String filename
  
      public void setError(boolean error) {
          mError = error;
 -    };
 -    
 +    }
 +
 +    ;
  
  
  }
@@@ -26,6 -26,7 +26,7 @@@ import android.annotation.SuppressLint
  import android.app.Activity;
  import android.graphics.Bitmap;
  import android.graphics.Point;
+ import android.graphics.drawable.Drawable;
  import android.os.AsyncTask;
  import android.os.Bundle;
  import android.support.v4.app.FragmentStatePagerAdapter;
@@@ -74,11 -75,11 +75,11 @@@ public class PreviewImageFragment exten
      private ProgressBar mProgressWheel;
  
      public Bitmap mBitmap = null;
 -    
 +
      private static final String TAG = PreviewImageFragment.class.getSimpleName();
  
      private boolean mIgnoreFirstSavedState;
 -    
 +
      private LoadBitmapTask mLoadBitmapTask = null;
  
  
          return frag;
      }
  
 -    
 +
      
      /**
       *  Creates an empty fragment for image previews.
      public PreviewImageFragment() {
          mIgnoreFirstSavedState = false;
      }
 -    
 -    
 +
 +
      /**
       * {@inheritDoc}
       */
          mIgnoreFirstSavedState = args.getBoolean(ARG_IGNORE_FIRST);
          setHasOptionsMenu(true);
      }
 -    
 +
  
      /**
       * {@inheritDoc}
       */
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
 -            Bundle savedInstanceState) {
 +                             Bundle savedInstanceState) {
          super.onCreateView(inflater, container, savedInstanceState);
          View view = inflater.inflate(R.layout.preview_image_fragment, container, false);
          mImageView = (TouchImageViewCustom) view.findViewById(R.id.image);
              throw new IllegalStateException("There is no local file to preview");
          }
      }
 -        
 +
  
      /**
       * {@inheritDoc}
          super.onSaveInstanceState(outState);
          outState.putParcelable(PreviewImageFragment.EXTRA_FILE, getFile());
      }
 -    
 +
  
      @Override
      public void onStart() {
          if (getFile() != null) {
              mLoadBitmapTask = new LoadBitmapTask(mImageView, mMessageView, mProgressWheel);
              //mLoadBitmapTask.execute(new String[]{getFile().getStoragePath()});
-             mLoadBitmapTask.execute(getFile().getStoragePath());
+ //            mLoadBitmapTask.execute(getFile().getStoragePath());
+             mLoadBitmapTask.execute(getFile());
          }
      }
 -    
 -    
 +
 +
      @Override
      public void onStop() {
          Log_OC.d(TAG, "onStop starts");
          }
          super.onStop();
      }
 -    
 +
      /**
       * {@inheritDoc}
       */
      @Override
      public void onPrepareOptionsMenu(Menu menu) {
          super.onPrepareOptionsMenu(menu);
 -        
 +
          if (mContainerActivity.getStorageManager() != null) {
              // Update the file
              setFile(mContainerActivity.getStorageManager().getFileById(getFile().getFileId()));
 -            
 +
              FileMenuFilter mf = new FileMenuFilter(
                  getFile(),
                  mContainerActivity.getStorageManager().getAccount(),
              );
              mf.filter(menu);
          }
 -        
 +
          // additional restriction for this fragment 
          // TODO allow renaming in PreviewImageFragment
          MenuItem item = menu.findItem(R.id.action_rename_file);
              item.setVisible(false);
              item.setEnabled(false);
          }
 -        
 +
          // additional restriction for this fragment 
          // TODO allow refresh file in PreviewImageFragment
          item = menu.findItem(R.id.action_sync_file);
              item.setVisible(false);
              item.setEnabled(false);
          }
 -        
 +
 +        // additional restriction for this fragment
 +        item = menu.findItem(R.id.action_copy);
 +        if (item != null) {
 +            item.setVisible(false);
 +            item.setEnabled(false);
 +        }
 +
      }
  
 -    
 -    
 +
      /**
       * {@inheritDoc}
       */
                  return false;
          }
      }
 -    
 +
  
      private void seeDetails() {
 -        mContainerActivity.showDetails(getFile());        
 +        mContainerActivity.showDetails(getFile());
      }
  
  
          super.onDestroy();
      }
  
 -    
 +
      /**
       * Opens the previewed image with an external application.
       */
          mContainerActivity.getFileOperationsHelper().openFile(getFile());
          finish();
      }
 -    
 +
-     private class LoadBitmapTask extends AsyncTask<String, Void, Bitmap> {
+     
+     private class LoadBitmapTask extends AsyncTask<OCFile, Void, LoadImage> {
  
          /**
           * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
           */
          private final WeakReference<TextView> mMessageViewRef;
  
 -        
 +
          /**
           * Weak reference to the target {@link ProgressBar} shown while the load is in progress.
           * 
           */
          private final WeakReference<ProgressBar> mProgressWheelRef;
  
 -        
 +
          /**
 -         * Error message to show when a load fails 
 +         * Error message to show when a load fails
           */
          private int mErrorMessageId;
 -        
 -        
 +
 +
          /**
           * Constructor.
 -         * 
 -         * @param imageView     Target {@link ImageView} where the bitmap will be loaded into.
 +         *
 +         * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
           */
          public LoadBitmapTask(ImageViewCustom imageView, TextView messageView,
                                ProgressBar progressWheel) {
              mMessageViewRef = new WeakReference<TextView>(messageView);
              mProgressWheelRef = new WeakReference<ProgressBar>(progressWheel);
          }
 -        
 +
          @Override
-         protected Bitmap doInBackground(String... params) {
+         protected LoadImage doInBackground(OCFile... params) {
              Bitmap result = null;
              if (params.length != 1) return null;
-             String storagePath = params[0];
+             OCFile ocFile = params[0];
+             String storagePath = ocFile.getStoragePath();
              try {
  
                  int maxDownScale = 3;   // could be a parameter passed to doInBackground(...)
                          result = BitmapUtils.decodeSampledBitmapFromFile(storagePath, minWidth,
                                  minHeight);
  
-                         if (isCancelled()) return result;
+                         if (isCancelled()) return new LoadImage(result, ocFile);
  
                          if (result == null) {
                              mErrorMessageId = R.string.preview_image_error_unknown_format;
  
              } catch (NoSuchFieldError e) {
                  mErrorMessageId = R.string.common_error_unknown;
 -                Log_OC.e(TAG, "Error from access to unexisting field despite protection; file " 
 -                                + storagePath, e);
 -                    
 +                Log_OC.e(TAG, "Error from access to unexisting field despite protection; file "
 +                        + storagePath, e);
 +
              } catch (Throwable t) {
                  mErrorMessageId = R.string.common_error_unknown;
                  Log_OC.e(TAG, "Unexpected error loading " + getFile().getStoragePath(), t);
 -                
 +
              }
-             return result;
 +
+             return new LoadImage(result, ocFile);
          }
 -        
 +
          @Override
-         protected void onCancelled(Bitmap result) {
-             if (result != null) {
-                 result.recycle();
+         protected void onCancelled(LoadImage result) {
+             if (result.bitmap != null) {
+                 result.bitmap.recycle();
              }
          }
  
          @Override
-         protected void onPostExecute(Bitmap result) {
+         protected void onPostExecute(LoadImage result) {
              hideProgressWheel();
-             if (result != null) {
+             if (result.bitmap != null) {
                  showLoadedImage(result);
 -            } else {
 +            }
 +            else {
                  showErrorMessage();
              }
-             if (result != null && mBitmap != result)  {
+             if (result.bitmap != null && mBitmap != result.bitmap)  {
                  // unused bitmap, release it! (just in case)
-                 result.recycle();
+                 result.bitmap.recycle();
              }
          }
 -        
 +
          @SuppressLint("InlinedApi")
-         private void showLoadedImage(Bitmap result) {
+         private void showLoadedImage(LoadImage result) {
              final ImageViewCustom imageView = mImageViewRef.get();
+             Bitmap bitmap = result.bitmap;
              if (imageView != null) {
-                 Log_OC.d(TAG, "Showing image with resolution " + result.getWidth() + "x" +
-                         result.getHeight());
-                 imageView.setImageBitmap(result);
+                 Log_OC.d(TAG, "Showing image with resolution " + bitmap.getWidth() + "x" +
+                         bitmap.getHeight());
+                 if (result.ocFile.getMimetype().equalsIgnoreCase("image/png")){
+                     Drawable backrepeat = getResources().getDrawable(R.drawable.backrepeat);
+                     imageView.setBackground(backrepeat);
+                 }
+                 imageView.setImageBitmap(bitmap);
                  imageView.setVisibility(View.VISIBLE);
-                 mBitmap  = result;  // needs to be kept for recycling when not useful
+                 mBitmap  = bitmap;  // needs to be kept for recycling when not useful
              }
  
              final TextView messageView = mMessageViewRef.get();
                  messageView.setVisibility(View.GONE);
              } // else , silently finish, the fragment was destroyed
          }
 -        
 +
          private void showErrorMessage() {
              final ImageView imageView = mImageViewRef.get();
              if (imageView != null) {
                  messageView.setVisibility(View.VISIBLE);
              } // else , silently finish, the fragment was destroyed
          }
 -        
 +
          private void hideProgressWheel() {
              final ProgressBar progressWheel = mProgressWheelRef.get();
              if (progressWheel != null) {
                  progressWheel.setVisibility(View.GONE);
              }
          }
 -        
 +
      }
  
      /**
          return (file != null && file.isImage());
      }
  
 -    
 +
      /**
       * Finishes the preview
       */
          Activity container = getActivity();
          container.finish();
      }
 -    
 +
      public TouchImageViewCustom getImageView() {
          return mImageView;
      }
  
+     private class LoadImage {
+         private Bitmap bitmap;
+         private OCFile ocFile;
+         public LoadImage(Bitmap bitmap, OCFile ocFile){
+             this.bitmap = bitmap;
+             this.ocFile = ocFile;
+         }
+     }
  }
@@@ -21,7 -21,10 +21,10 @@@ package com.owncloud.android.ui.preview
  
  import android.accounts.Account;
  import android.app.Activity;
- import android.app.AlertDialog;
+ import android.graphics.Bitmap;
+ import android.graphics.BitmapFactory;
+ import android.media.MediaMetadataRetriever;
+ import android.support.v7.app.AlertDialog;
  import android.content.ComponentName;
  import android.content.Context;
  import android.content.DialogInterface;
@@@ -46,6 -49,7 +49,6 @@@ import android.view.View
  import android.view.View.OnTouchListener;
  import android.view.ViewGroup;
  import android.widget.ImageView;
 -import android.widget.LinearLayout;
  import android.widget.Toast;
  import android.widget.VideoView;
  
@@@ -64,7 -68,7 +67,7 @@@ import com.owncloud.android.ui.fragment
  
  /**
   * This fragment shows a preview of a downloaded media file (audio or video).
 - * 
 + *
   * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will
   * produce an {@link IllegalStateException}.
   * 
@@@ -84,46 -88,46 +87,46 @@@ public class PreviewMediaFragment exten
      private ImageView mImagePreview;
      private VideoView mVideoPreview;
      private int mSavedPlaybackPosition;
 -    
 +
      private MediaServiceBinder mMediaServiceBinder = null;
      private MediaControlView mMediaController = null;
      private MediaServiceConnection mMediaServiceConnection = null;
      private VideoHelper mVideoHelper;
      private boolean mAutoplay;
      public boolean mPrepared;
 -    
 +
      private static final String TAG = PreviewMediaFragment.class.getSimpleName();
  
 -    
 +
      /**
       * Creates a fragment to preview a file.
 -     * 
 +     * <p/>
       * When 'fileToDetail' or 'ocAccount' are null
 -     * 
 -     * @param fileToDetail      An {@link OCFile} to preview in the fragment
 -     * @param ocAccount         An ownCloud account; needed to start downloads
 +     *
 +     * @param fileToDetail An {@link OCFile} to preview in the fragment
 +     * @param ocAccount    An ownCloud account; needed to start downloads
       */
      public PreviewMediaFragment(
 -            OCFile fileToDetail, 
 -            Account ocAccount, 
 -            int startPlaybackPosition, 
 +            OCFile fileToDetail,
 +            Account ocAccount,
 +            int startPlaybackPosition,
              boolean autoplay) {
 -        
 +
          super(fileToDetail);
          mAccount = ocAccount;
          mSavedPlaybackPosition = startPlaybackPosition;
          mAutoplay = autoplay;
      }
 -    
 -    
 +
 +
      /**
 -     *  Creates an empty fragment for previews.
 -     * 
 -     *  MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically 
 -     *  (for instance, when the device is turned a aside).
 -     * 
 -     *  DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful 
 -     *  construction 
 +     * Creates an empty fragment for previews.
 +     * <p/>
 +     * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically
 +     * (for instance, when the device is turned a aside).
 +     * <p/>
 +     * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful
 +     * construction
       */
      public PreviewMediaFragment() {
          super();
          mSavedPlaybackPosition = 0;
          mAutoplay = true;
      }
 -    
 -    
 +
 +
      /**
       * {@inheritDoc}
       */
          super.onCreate(savedInstanceState);
          setHasOptionsMenu(true);
      }
 -    
 +
  
      /**
       * {@inheritDoc}
       */
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
 -            Bundle savedInstanceState) {
 +                             Bundle savedInstanceState) {
          super.onCreateView(inflater, container, savedInstanceState);
          Log_OC.e(TAG, "onCreateView");
  
 -        
 +
          mView = inflater.inflate(R.layout.file_preview, container, false);
 -        
 -        mImagePreview = (ImageView)mView.findViewById(R.id.image_preview);
 -        mVideoPreview = (VideoView)mView.findViewById(R.id.video_preview);
 +
 +        mImagePreview = (ImageView) mView.findViewById(R.id.image_preview);
 +        mVideoPreview = (VideoView) mView.findViewById(R.id.video_preview);
          mVideoPreview.setOnTouchListener(this);
 -        
 -        mMediaController = (MediaControlView)mView.findViewById(R.id.media_controller);
 -        
 +
 +        mMediaController = (MediaControlView) mView.findViewById(R.id.media_controller);
 +
          return mView;
      }
 -    
 +
  
      /**
       * {@inheritDoc}
              if (!file.isDown()) {
                  throw new IllegalStateException("There is no local file to preview");
              }
 -            
 -        } else {
 -            file = (OCFile)savedInstanceState.getParcelable(PreviewMediaFragment.EXTRA_FILE);
 +
 +        }
 +        else {
 +            file = (OCFile) savedInstanceState.getParcelable(PreviewMediaFragment.EXTRA_FILE);
              setFile(file);
              mAccount = savedInstanceState.getParcelable(PreviewMediaFragment.EXTRA_ACCOUNT);
 -            mSavedPlaybackPosition = 
 +            mSavedPlaybackPosition =
                      savedInstanceState.getInt(PreviewMediaFragment.EXTRA_PLAY_POSITION);
              mAutoplay = savedInstanceState.getBoolean(PreviewMediaFragment.EXTRA_PLAYING);
 -            
 +
          }
          if (file != null && file.isDown()) {
              if (file.isVideo()) {
                  mVideoPreview.setVisibility(View.VISIBLE);
                  mImagePreview.setVisibility(View.GONE);
                  prepareVideo();
 -            
 -            } else {
 +
 +            }
 +            else {
                  mVideoPreview.setVisibility(View.GONE);
                  mImagePreview.setVisibility(View.VISIBLE);
+                 extractAndSetCoverArt(file);
              }
          }
 -        
 +
      }
  
+     /**
+      * tries to read the cover art from the audio file and sets it as cover art.
+      *
+      * @param file audio file with potential cover art
+      */
+     private void extractAndSetCoverArt(OCFile file) {
+         if (file.isAudio()) {
+             try {
+                 MediaMetadataRetriever mmr = new MediaMetadataRetriever();
+                 mmr.setDataSource(file.getStoragePath());
+                 byte[] data = mmr.getEmbeddedPicture();
+                 if (data != null) {
+                     Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
+                     mImagePreview.setImageBitmap(bitmap); //associated cover art in bitmap
+                 } else {
+                     mImagePreview.setImageResource(R.drawable.logo);
+                 }
+             } catch (Throwable t) {
+                 mImagePreview.setImageResource(R.drawable.logo);
+             }
+         }
+     }
  
      /**
       * {@inheritDoc}
      public void onSaveInstanceState(Bundle outState) {
          super.onSaveInstanceState(outState);
          Log_OC.e(TAG, "onSaveInstanceState");
 -        
 +
          outState.putParcelable(PreviewMediaFragment.EXTRA_FILE, getFile());
          outState.putParcelable(PreviewMediaFragment.EXTRA_ACCOUNT, mAccount);
 -        
 +
          if (getFile().isVideo()) {
              mSavedPlaybackPosition = mVideoPreview.getCurrentPosition();
              mAutoplay = mVideoPreview.isPlaying();
 -            outState.putInt(PreviewMediaFragment.EXTRA_PLAY_POSITION , mSavedPlaybackPosition);
 -            outState.putBoolean(PreviewMediaFragment.EXTRA_PLAYING , mAutoplay);
 -        } else {
 +            outState.putInt(PreviewMediaFragment.EXTRA_PLAY_POSITION, mSavedPlaybackPosition);
 +            outState.putBoolean(PreviewMediaFragment.EXTRA_PLAYING, mAutoplay);
 +        }
 +        else {
              outState.putInt(
 -                    PreviewMediaFragment.EXTRA_PLAY_POSITION , 
 +                    PreviewMediaFragment.EXTRA_PLAY_POSITION,
                      mMediaServiceBinder.getCurrentPosition());
              outState.putBoolean(
 -                    PreviewMediaFragment.EXTRA_PLAYING , mMediaServiceBinder.isPlaying());
 +                    PreviewMediaFragment.EXTRA_PLAYING, mMediaServiceBinder.isPlaying());
          }
      }
 -    
 +
  
      @Override
      public void onStart() {
  
          OCFile file = getFile();
          if (file != null && file.isDown()) {
 -           if (file.isAudio()) {
 -               bindMediaService();
 -               
 -           } else if (file.isVideo()) {
 -               stopAudio();
 -               playVideo(); 
 -           }
 +            if (file.isAudio()) {
 +                bindMediaService();
 +
 +            }
 +            else {
 +                if (file.isVideo()) {
 +                    stopAudio();
 +                    playVideo();
 +                }
 +            }
          }
      }
 -    
 -    
 +
 +
      private void stopAudio() {
          Intent i = new Intent(getActivity(), MediaService.class);
          i.setAction(MediaService.ACTION_STOP_ALL);
      @Override
      public void onPrepareOptionsMenu(Menu menu) {
          super.onPrepareOptionsMenu(menu);
 -        
 +
          if (mContainerActivity.getStorageManager() != null) {
              FileMenuFilter mf = new FileMenuFilter(
                  getFile(),
              item.setVisible(false);
              item.setEnabled(false);
          }
 +
 +        // additional restriction for this fragment
 +        item = menu.findItem(R.id.action_copy);
 +        if (item != null) {
 +            item.setVisible(false);
 +            item.setEnabled(false);
 +        }
      }
 -    
 -    
 +
 +
      /**
       * {@inheritDoc}
       */
                  return false;
          }
      }
 -    
  
  
      /**
       * Update the file of the fragment with file value
 +     *
       * @param file
       */
 -    public void updateFile(OCFile file){
 +    public void updateFile(OCFile file) {
          setFile(file);
      }
 -    
 +
      private void sendFile() {
          stopPreview(false);
          mContainerActivity.getFileOperationsHelper().sendDownloadedFile(getFile());
 -        
 +
      }
  
      private void seeDetails() {
          stopPreview(false);
 -        mContainerActivity.showDetails(getFile());        
 +        mContainerActivity.showDetails(getFile());
      }
  
  
          mVideoPreview.setOnCompletionListener(mVideoHelper);
          mVideoPreview.setOnErrorListener(mVideoHelper);
      }
 -    
 +
      @SuppressWarnings("static-access")
      private void playVideo() {
          // create and prepare control panel for the user
          mMediaController.setMediaPlayer(mVideoPreview);
 -        
 +
          // load the video file in the video player ; 
          // when done, VideoHelper#onPrepared() will be called
          Uri uri = Uri.parse(getFile().getStoragePath());
          mVideoPreview.setVideoPath(uri.encode(getFile().getStoragePath()));
      }
 -    
 +
  
      private class VideoHelper implements OnCompletionListener, OnPreparedListener, OnErrorListener {
 -        
 -        /** 
 +
 +        /**
           * Called when the file is ready to be played.
 -         * 
 +         * <p/>
           * Just starts the playback.
 -         * 
 +         *
           * @param   vp    {@link MediaPlayer} instance performing the playback.
           */
          @Override
          public void onPrepared(MediaPlayer vp) {
              Log_OC.e(TAG, "onPrepared");
              mVideoPreview.seekTo(mSavedPlaybackPosition);
 -            if (mAutoplay) { 
 +            if (mAutoplay) {
                  mVideoPreview.start();
              }
              mMediaController.setEnabled(true);
              mMediaController.updatePausePlay();
              mPrepared = true;
          }
 -        
 -        
 +
 +
          /**
           * Called when the file is finished playing.
 -         *  
 +         * <p/>
           * Finishes the activity.
 -         * 
 -         * @param   mp    {@link MediaPlayer} instance performing the playback.
 +         *
 +         * @param mp {@link MediaPlayer} instance performing the playback.
           */
          @Override
 -        public void onCompletion(MediaPlayer  mp) {
 +        public void onCompletion(MediaPlayer mp) {
              Log_OC.e(TAG, "completed");
              if (mp != null) {
                  mVideoPreview.seekTo(0);
                  // next lines are necessary to work around undesired video loops
                  if (Build.VERSION.SDK_INT == Build.VERSION_CODES.GINGERBREAD) {
 -                    mVideoPreview.pause();   
 -                    
 -                } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.GINGERBREAD_MR1) {
 -                    // mVideePreview.pause() is not enough
 -                    
 -                    mMediaController.setEnabled(false);
 -                    mVideoPreview.stopPlayback();
 -                    mAutoplay = false;
 -                    mSavedPlaybackPosition = 0;
 -                    mVideoPreview.setVideoPath(getFile().getStoragePath());
 +                    mVideoPreview.pause();
 +
 +                }
 +                else {
 +                    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.GINGERBREAD_MR1) {
 +                        // mVideePreview.pause() is not enough
 +
 +                        mMediaController.setEnabled(false);
 +                        mVideoPreview.stopPlayback();
 +                        mAutoplay = false;
 +                        mSavedPlaybackPosition = 0;
 +                        mVideoPreview.setVideoPath(getFile().getStoragePath());
 +                    }
                  }
              } // else : called from onError()
              mMediaController.updatePausePlay();
          }
 -        
 -        
 +
 +
          /**
           * Called when an error in playback occurs.
 -         * 
 -         * @param   mp      {@link MediaPlayer} instance performing the playback.
 -         * @param   what    Type of error
 -         * @param   extra   Extra code specific to the error
 +         *
 +         * @param mp    {@link MediaPlayer} instance performing the playback.
 +         * @param what  Type of error
 +         * @param extra Extra code specific to the error
           */
          @Override
          public boolean onError(MediaPlayer mp, int what, int extra) {
              }
              return true;
          }
 -        
 +
      }
  
 -    
 +
      @Override
      public void onPause() {
          Log_OC.e(TAG, "onPause");
          super.onPause();
      }
 -    
 +
      @Override
      public void onResume() {
          super.onResume();
          Log_OC.e(TAG, "onResume");
      }
 -    
 +
      @Override
      public void onDestroy() {
          Log_OC.e(TAG, "onDestroy");
          super.onDestroy();
      }
 -    
 +
      @Override
      public void onStop() {
          Log_OC.e(TAG, "onStop");
              mMediaServiceConnection = null;
              mMediaServiceBinder = null;
          }
 -        
 +
          super.onStop();
      }
 -    
 +
      @Override
      public boolean onTouch(View v, MotionEvent event) {
          if (event.getAction() == MotionEvent.ACTION_DOWN && v == mVideoPreview) {
          return false;
      }
  
 -    
 +
      private void startFullScreenVideo() {
          Intent i = new Intent(getActivity(), PreviewVideoActivity.class);
          i.putExtra(FileActivity.EXTRA_ACCOUNT, mAccount);
      }
  
      @Override
 -    public void onConfigurationChanged (Configuration newConfig) {
 +    public void onConfigurationChanged(Configuration newConfig) {
          Log_OC.e(TAG, "onConfigurationChanged " + this);
      }
 -    
 +
      @Override
 -    public void onActivityResult (int requestCode, int resultCode, Intent data) {
 +    public void onActivityResult(int requestCode, int resultCode, Intent data) {
          Log_OC.e(TAG, "onActivityResult " + this);
          super.onActivityResult(requestCode, resultCode, data);
          if (resultCode == Activity.RESULT_OK) {
              mSavedPlaybackPosition = data.getExtras().getInt(
                      PreviewVideoActivity.EXTRA_START_POSITION);
 -            mAutoplay = data.getExtras().getBoolean(PreviewVideoActivity.EXTRA_AUTOPLAY); 
 +            mAutoplay = data.getExtras().getBoolean(PreviewVideoActivity.EXTRA_AUTOPLAY);
          }
      }
 -    
 +
  
      private void playAudio() {
          OCFile file = getFile();
          if (!mMediaServiceBinder.isPlaying(file)) {
              Log_OC.d(TAG, "starting playback of " + file.getStoragePath());
              mMediaServiceBinder.start(mAccount, file, mAutoplay, mSavedPlaybackPosition);
 -            
 -        } else {
 +
 +        }
 +        else {
              if (!mMediaServiceBinder.isPlaying() && mAutoplay) {
                  mMediaServiceBinder.start();
                  mMediaController.updatePausePlay();
  
                          Log_OC.d(TAG, "Successfully bound to MediaService, MediaController ready");
  
 -                    } else {
 +                    }
 +                    else {
                          Log_OC.e(TAG, "Unexpected response from MediaService while binding");
                      }
                  }
                  Log_OC.e(TAG, "Media service suddenly disconnected");
                  if (mMediaController != null) {
                      mMediaController.setMediaPlayer(null);
 -                } else {
 +                }
 +                else {
                      Toast.makeText(
                              getActivity(),
                              "No media controller to release when disconnected from media service", 
                  mMediaServiceConnection = null;
              }
          }
 -    }    
 +    }
  
 -    
  
      /**
       * Opens the previewed file with an external application.
          mContainerActivity.getFileOperationsHelper().openFile(getFile());
          finish();
      }
 -    
 +
      /**
       * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewMediaFragment}
 -     *  to be previewed.
 -     * 
 -     * @param file      File to test if can be previewed.
 -     * @return          'True' if the file can be handled by the fragment.
 +     * to be previewed.
 +     *
 +     * @param file File to test if can be previewed.
 +     * @return 'True' if the file can be handled by the fragment.
       */
      public static boolean canBePreviewed(OCFile file) {
          return (file != null && (file.isAudio() || file.isVideo()));
      }
 -    
 +
  
      public void stopPreview(boolean stopAudio) {
          OCFile file = getFile();
          if (file.isAudio() && stopAudio) {
              mMediaServiceBinder.pause();
 -            
 -        } else if (file.isVideo()) {
 -            mVideoPreview.stopPlayback();
 +
 +        }
 +        else {
 +            if (file.isVideo()) {
 +                mVideoPreview.stopPlayback();
 +            }
          }
      }
  
  
 -
      /**
       * Finishes the preview
       */
          Log_OC.e(TAG, "getting position: " + mSavedPlaybackPosition);
          return mSavedPlaybackPosition;
      }
 -    
 +
      public boolean isPlaying() {
          if (mPrepared) {
              mAutoplay = mVideoPreview.isPlaying();
          }
          return mAutoplay;
      }
 -    
 +
  }