From: tobiasKaminsky Date: Thu, 29 Oct 2015 16:55:13 +0000 (+0100) Subject: Merge remote-tracking branch 'remotes/upstream/master' into switchListVsGridMaster X-Git-Tag: beta-20151122~25^2~4 X-Git-Url: http://git.linex4red.de/pub/Android/ownCloud.git/commitdiff_plain/65f8034c3030948b0a348f7f654821b6226f6a1d?ds=inline;hp=-c Merge remote-tracking branch 'remotes/upstream/master' into switchListVsGridMaster --- 65f8034c3030948b0a348f7f654821b6226f6a1d diff --combined res/menu/file_actions_menu.xml index 2551f314,3e6f4cd4..4a295d53 --- a/res/menu/file_actions_menu.xml +++ b/res/menu/file_actions_menu.xml @@@ -1,5 -1,4 +1,5 @@@ - - + - - - - - - - - - - - - - - + + + + + + + + + + + + + + + diff --combined res/values/strings.xml index b8475287,267d713e..ad90cdf1 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@@ -74,6 -74,7 +74,7 @@@ seconds ago Nothing in here. Upload something! Loading… + No App found for file type! There are no files in this folder. Tap on a file to display additional information. Size: @@@ -122,14 -123,14 +123,14 @@@ Synchronization failed, you need to relogin Synchronization of %1$s could not be completed Invalid password for %1$s - Conflicts found - %1$d kept-in-sync files could not be sync\'ed + Conflicts found + %1$d kept-in-sync files could not be sync\'ed Kept-in-sync files failed Contents of %1$d files could not be sync\'ed (%2$d conflicts) Some local files were forgotten %1$d files out of the %2$s folder could not be copied into 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. - Folder %1$s does not exist anymore + Folder %1$s does not exist anymore "Move all" "All files were moved" "Some files could not be moved" @@@ -152,20 -153,20 +153,20 @@@ "%1$s (loading)" "%1$s playback finished" No media file found - No account provided - File not in a valid account - Unsupported media codec - Media file could not be read - Media file not correctly encoded - Timed out while trying to play - Media file cannot be streamed - Media file cannot be played with the stock media player - Security error trying to play %1$s - Input error trying to play %1$s - Unexpected error trying to play %1$s - Rewind button - Play or pause button - Fast forward button + No account provided + File not in a valid account + Unsupported media codec + Media file could not be read + Media file not correctly encoded + Timed out while trying to play + Media file cannot be streamed + Media file cannot be played with the stock media player + Security error trying to play %1$s + Input error trying to play %1$s + Unexpected error trying to play %1$s + Rewind button + Play or pause button + Fast forward button Getting authorization… Trying to login… @@@ -250,19 -251,19 +251,19 @@@ Location: Validity: From: - To: - Signature: - Algorithm: - The certificate could not be shown. - - No information about the error - + To: + Signature: + Algorithm: + The certificate could not be shown. + - No information about the error + This is a placeholder placeholder.txt PNG Image 389 KB 2012/05/18 12:23 PM 12:23:45 - + Upload pictures via WiFi only Upload videos via WiFi only /InstantUpload @@@ -274,7 -275,7 +275,7 @@@ Image preview This image cannot be shown - + %1$s could not be copied to %2$s local folder Upload Path @@@ -287,32 -288,31 +288,31 @@@ Enter a password You must enter a password - Send + Send + + Copy link + Copied to clipboard - Copy link - Copied to clipboard + Critical error: cannot perform operations - Critical error: cannot perform operations - - An error occurred while connecting with the server. - An error occurred while waiting for the server, the operation couldn\'t have been done - An error occurred while waiting for the server, the operation couldn\'t have been done - The operation couldn\'t be completed, server is unavailable + An error occurred while connecting with the server. + An error occurred while waiting for the server, the operation couldn\'t have been done + An error occurred while waiting for the server, the operation couldn\'t have been done + The operation couldn\'t be completed, server is unavailable + - - - You do not have permission %s - to rename this file - to delete this file - to share this file - to unshare this file - to create the file - to upload in this folder - The file is no longer available on the server + You do not have permission %s + to rename this file + to delete this file + to share this file + to unshare this file + to create the file + to upload in this folder + The file is no longer available on the server - Accounts - Add account - Secure connection is redirected to an unsecured route. + Accounts + Add account + Secure connection is redirected through an unsecured route. Logs Send History @@@ -326,13 -326,20 +326,20 @@@ Nothing in here. You can add a folder! Choose - Unable to move. Please check whether the file exists - It is not possible to move a folder into a descendant - The file exists already in the destination folder - An error occurred while trying to move this file or folder - to move this file + Unable to move. Please check whether the file exists + It is not possible to move a folder into a descendant + The file exists already in the destination folder + An error occurred while trying to move this file or folder + to move this file + + + Unable to copy. Please check whether the file exists + It is not possible to copy a folder into a descendant + The file exists already in the destination folder + An error occurred while trying to copy this file or folder + to copy this file - Instant Uploads + Instant Uploads Security Upload Video Path @@@ -358,6 -365,5 +365,6 @@@ %1$d files %1$d files, 1 folder %1$d files, %2$d folders - + Switch to grid view + Switch to list view diff --combined src/com/owncloud/android/datamodel/OCFile.java index 4b9b69aa,4baf1ea5..0c7cc714 --- a/src/com/owncloud/android/datamodel/OCFile.java +++ b/src/com/owncloud/android/datamodel/OCFile.java @@@ -22,12 -22,11 +22,12 @@@ package com.owncloud.android.datamodel import android.os.Parcel; import android.os.Parcelable; + import android.webkit.MimeTypeMap; import com.owncloud.android.lib.common.utils.Log_OC; - import com.owncloud.android.utils.FileStorageUtils; import java.io.File; +import java.util.Enumeration; import third_parties.daveKoeller.AlphanumComparator; public class OCFile implements Parcelable, Comparable { @@@ -75,8 -74,6 +75,8 @@@ private boolean mIsDownloading; + private boolean mShowGridView; + /** * Create new {@link OCFile} with given path. @@@ -292,11 -289,13 +292,13 @@@ /** * Sets the name of the file *

- * Does nothing if the new name is null, empty or includes "/" ; or if the file is the root directory + * Does nothing if the new name is null, empty or includes "/" ; or if the file is the root + * directory */ public void setFileName(String name) { Log_OC.d(TAG, "OCFile name changin from " + mRemotePath); - if (name != null && name.length() > 0 && !name.contains(PATH_SEPARATOR) && !mRemotePath.equals(ROOT_PATH)) { + if (name != null && name.length() > 0 && !name.contains(PATH_SEPARATOR) && + !mRemotePath.equals(ROOT_PATH)) { String parent = (new File(getRemotePath())).getParent(); parent = (parent.endsWith(PATH_SEPARATOR)) ? parent : parent + PATH_SEPARATOR; mRemotePath = parent + name; @@@ -457,7 -456,7 +459,7 @@@ @Override public int describeContents() { - return ((Object) this).hashCode(); + return super.hashCode(); } @Override @@@ -486,8 -485,11 +488,11 @@@ @Override public String toString() { - String asString = "[id=%s, name=%s, mime=%s, downloaded=%s, local=%s, remote=%s, parentId=%s, favorite=%s etag=%s]"; - asString = String.format(asString, Long.valueOf(mId), getFileName(), mMimeType, isDown(), mLocalPath, mRemotePath, Long.valueOf(mParentId), Boolean.valueOf(mFavorite), mEtag); + String asString = "[id=%s, name=%s, mime=%s, downloaded=%s, local=%s, remote=%s, " + + "parentId=%s, favorite=%s etag=%s]"; + asString = String.format(asString, Long.valueOf(mId), getFileName(), mMimeType, isDown(), + mLocalPath, mRemotePath, Long.valueOf(mParentId), Boolean.valueOf(mFavorite), + mEtag); return asString; } @@@ -543,7 -545,33 +548,33 @@@ */ public boolean isImage() { return ((mMimeType != null && mMimeType.startsWith("image/")) || - FileStorageUtils.getMimeTypeFromName(mRemotePath).startsWith("image/")); + getMimeTypeFromName().startsWith("image/")); + } + + /** + * @return 'True' if the file is simple text (e.g. not application-dependent, like .doc or .docx) + */ + public boolean isText() { + return ((mMimeType != null && mMimeType.startsWith("text/")) || + getMimeTypeFromName().startsWith("text/")); + } + + public String getMimeTypeFromName() { + String extension = ""; + int pos = mRemotePath.lastIndexOf('.'); + if (pos >= 0) { + extension = mRemotePath.substring(pos + 1); + } + String result = MimeTypeMap.getSingleton(). + getMimeTypeFromExtension(extension.toLowerCase()); + return (result != null) ? result : ""; + } + + /** + * @return 'True' if the file is hidden + */ + public boolean isHidden() { + return getFileName().startsWith("."); } public String getPermissions() { diff --combined src/com/owncloud/android/files/FileMenuFilter.java index 58f35db3,f7fee626..1d5ca454 --- a/src/com/owncloud/android/files/FileMenuFilter.java +++ b/src/com/owncloud/android/files/FileMenuFilter.java @@@ -39,7 -39,7 +39,7 @@@ import com.owncloud.android.services.Op import com.owncloud.android.ui.activity.ComponentsGetter; /** - * Filters out the file actions available in a given {@link Menu} for a given {@link OCFile} + * Filters out the file actions available in a given {@link Menu} for a given {@link OCFile} * according to the current state of the latest. */ public class FileMenuFilter { @@@ -48,10 -48,10 +48,10 @@@ private ComponentsGetter mComponentsGetter; private Account mAccount; private Context mContext; - + /** * Constructor - * + * * @param targetFile {@link OCFile} target of the action to filter in the {@link Menu}. * @param account ownCloud {@link Account} holding targetFile. * @param cg Accessor to app components, needed to access the @@@ -64,20 -64,20 +64,20 @@@ mComponentsGetter = cg; mContext = context; } - - + + /** * Filters out the file actions available in the passed {@link Menu} taken into account * the state of the {@link OCFile} held by the filter. - * + * * @param menu Options or context menu to filter. */ public void filter(Menu menu) { - List toShow = new ArrayList(); - List toHide = new ArrayList(); - + List toShow = new ArrayList(); + List toHide = new ArrayList(); + filter(toShow, toHide); - + MenuItem item = null; for (int i : toShow) { item = menu.findItem(i); @@@ -86,7 -86,7 +86,7 @@@ item.setEnabled(true); } } - + for (int i : toHide) { item = menu.findItem(i); if (item != null) { @@@ -99,10 -99,10 +99,10 @@@ /** * Performs the real filtering, to be applied in the {@link Menu} by the caller methods. - * + * * Decides what actions must be shown and hidden. - * - * @param toShow List to save the options that must be shown in the menu. + * + * @param toShow List to save the options that must be shown in the menu. * @param toHide List to save the options that must be shown in the menu. */ private void filter(List toShow, List toHide) { @@@ -116,71 -116,72 +116,72 @@@ FileUploaderBinder uploaderBinder = mComponentsGetter.getFileUploaderBinder(); uploading = (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile)); } - + /// decision is taken for each possible action on a file in the menu - + // DOWNLOAD if (mFile == null || mFile.isDown() || downloading || uploading) { toHide.add(R.id.action_download_file); - + } else { toShow.add(R.id.action_download_file); } - + // RENAME if (mFile == null || downloading || uploading) { toHide.add(R.id.action_rename_file); - + } else { toShow.add(R.id.action_rename_file); } - // MOVE + // MOVE & COPY if (mFile == null || downloading || uploading) { toHide.add(R.id.action_move); - + toHide.add(R.id.action_copy); } else { toShow.add(R.id.action_move); + toShow.add(R.id.action_copy); } - + // REMOVE if (mFile == null || downloading || uploading) { toHide.add(R.id.action_remove_file); - + } else { toShow.add(R.id.action_remove_file); } - + // OPEN WITH (different to preview!) if (mFile == null || mFile.isFolder() || !mFile.isDown() || downloading || uploading) { toHide.add(R.id.action_open_file_with); - + } else { toShow.add(R.id.action_open_file_with); } - - + + // CANCEL DOWNLOAD if (mFile == null || !downloading) { toHide.add(R.id.action_cancel_download); } else { toShow.add(R.id.action_cancel_download); } - + // CANCEL UPLOAD if (mFile == null || !uploading || mFile.isFolder()) { toHide.add(R.id.action_cancel_upload); } else { toShow.add(R.id.action_cancel_upload); } - + // SYNC FILE CONTENTS if (mFile == null || mFile.isFolder() || !mFile.isDown() || downloading || uploading) { toHide.add(R.id.action_sync_file); } else { toShow.add(R.id.action_sync_file); } - + // SHARE FILE // TODO add check on SHARE available on server side? boolean shareAllowed = (mContext != null && @@@ -190,7 -191,7 +191,7 @@@ } else { toShow.add(R.id.action_share_file); } - + // UNSHARE FILE // TODO add check on SHARE available on server side? if ( !shareAllowed || (mFile == null || !mFile.isShareByLink())) { @@@ -205,7 -206,7 +206,7 @@@ } else { toShow.add(R.id.action_see_details); } - + // SEND boolean sendAllowed = (mContext != null && mContext.getString(R.string.send_files_to_other_apps).equalsIgnoreCase("on")); @@@ -228,6 -229,7 +229,6 @@@ } else { toShow.add(R.id.action_unfavorite_file); } - } } diff --combined src/com/owncloud/android/ui/activity/FileDisplayActivity.java index 5df6c61c,240d146f..37bd66f3 --- a/src/com/owncloud/android/ui/activity/FileDisplayActivity.java +++ b/src/com/owncloud/android/ui/activity/FileDisplayActivity.java @@@ -77,6 -77,7 +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; @@@ -98,6 -99,7 +99,7 @@@ import com.owncloud.android.ui.fragment import com.owncloud.android.ui.preview.PreviewImageActivity; import com.owncloud.android.ui.preview.PreviewImageFragment; import com.owncloud.android.ui.preview.PreviewMediaFragment; + import com.owncloud.android.ui.preview.PreviewTextFragment; import com.owncloud.android.ui.preview.PreviewVideoActivity; import com.owncloud.android.utils.DisplayUtils; import com.owncloud.android.utils.ErrorMessageAdapter; @@@ -106,7 -108,6 +108,6 @@@ import com.owncloud.android.utils.UriUt import java.io.File; - /** * Displays, what files the user has available in his ownCloud. */ @@@ -115,6 -116,8 +116,8 @@@ public class FileDisplayActivity extend implements FileFragment.ContainerActivity, OnSslUntrustedCertListener, OnEnforceableRefreshListener { + + private SyncBroadcastReceiver mSyncBroadcastReceiver; private UploadFinishReceiver mUploadFinishReceiver; private DownloadFinishReceiver mDownloadFinishReceiver; @@@ -134,6 -137,7 +137,7 @@@ 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(); @@@ -141,7 -145,7 +145,7 @@@ 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"; @@@ -150,9 -154,8 +154,9 @@@ private static String DIALOG_CERT_NOT_SAVED = "DIALOG_CERT_NOT_SAVED"; private OCFile mWaitingToSend; + private Menu mOptionsMenu; + - @Override protected void onCreate(Bundle savedInstanceState) { Log_OC.v(TAG, "onCreate() start"); @@@ -165,7 -168,7 +169,7 @@@ Intent initObserversIntent = FileObserverService.makeInitIntent(this); startService(initObserversIntent); } - + /// Load of saved instance state if(savedInstanceState != null) { mWaitingToPreview = (OCFile) savedInstanceState.getParcelable( @@@ -173,18 -176,17 +177,17 @@@ mSyncInProgress = savedInstanceState.getBoolean(KEY_SYNC_IN_PROGRESS); mWaitingToSend = (OCFile) savedInstanceState.getParcelable( FileDisplayActivity.KEY_WAITING_TO_SEND); - } else { mWaitingToPreview = null; mSyncInProgress = false; mWaitingToSend = null; - } + } /// USER INTERFACE // Inflate and set the layout view setContentView(R.layout.files); - + // Navigation Drawer initDrawer(); @@@ -211,7 -213,7 +214,7 @@@ mProgressBar.setIndeterminate(mSyncInProgress); // always AFTER setContentView(...) ; to work around bug in its implementation - + setBackgroundText(); Log_OC.v(TAG, "onCreate() end"); @@@ -232,8 -234,8 +235,8 @@@ } /** - * 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); @@@ -277,7 -279,7 +280,7 @@@ if (file.isFolder()) { startSyncFolderOperation(file, false); } - + } else { updateFragmentsVisibility(!file.isFolder()); updateActionBarTitleAndHomeButton(file.isFolder() ? null : file); @@@ -285,44 -287,40 +288,46 @@@ } } - private void createMinFragments() { OCFileListFragment listOfFiles = new OCFileListFragment(); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 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 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice()); + } 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); updateFragmentsVisibility(true); updateActionBarTitleAndHomeButton(file); - + } else { cleanSecondFragment(); + if (file.isDown() && PreviewTextFragment.canBePreviewed(file)) + startTextPreview(file); } + if (DisplayUtils.isGridView(getFile(), getStorageManager())){ + switchToGridView(); + } else { + switchToListView(); + } + } else { Log_OC.wtf(TAG, "initFragments() called with invalid NULLs!"); if (getAccount() == null) { @@@ -337,7 -335,7 +342,7 @@@ 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 = @@@ -347,9 -345,11 +352,11 @@@ secondFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay); + } else if (file.isDown() && PreviewTextFragment.canBePreviewed(file)) { + secondFragment = null; } else { - secondFragment = FileDetailFragment.newInstance(file, getAccount()); - } + secondFragment = FileDetailFragment.newInstance(file, getAccount()); + } } return secondFragment; } @@@ -358,10 -358,10 +365,10 @@@ /** * 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. + *

+ * 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(); @@@ -402,7 -402,7 +409,7 @@@ 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; @@@ -412,7 -412,7 +419,7 @@@ Fragment second = getSupportFragmentManager().findFragmentByTag( FileDisplayActivity.TAG_SECOND_FRAGMENT); if (second != null) { - return (FileFragment)second; + return (FileFragment) second; } return null; } @@@ -466,6 -466,9 +473,9 @@@ if (PreviewMediaFragment.canBePreviewed(mWaitingToPreview)) { startMediaPreview(mWaitingToPreview, 0, true); detailsFragmentChanged = true; + } else if (PreviewTextFragment.canBePreviewed(mWaitingToPreview)) { + startTextPreview(mWaitingToPreview); + detailsFragmentChanged = true; } else { getFileOperationsHelper().openFile(mWaitingToPreview); } @@@ -486,7 -489,6 +496,7 @@@ menu.findItem(R.id.action_create_dir).setVisible(!drawerOpen); menu.findItem(R.id.action_sort).setVisible(!drawerOpen); menu.findItem(R.id.action_sync_account).setVisible(!drawerOpen); + menu.findItem(R.id.action_switch_view).setVisible(!drawerOpen); return super.onPrepareOptionsMenu(menu); } @@@ -495,12 -497,6 +505,12 @@@ public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); + mOptionsMenu = menu; + + MenuItem menuItem = mOptionsMenu.findItem(R.id.action_switch_view); + + changeGridIcon(); + return true; } @@@ -515,6 -511,7 +525,7 @@@ dialog.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER); break; } + case R.id.action_sync_account: { startSynchronization(); break; @@@ -523,7 -520,6 +534,6 @@@ UploadSourceDialogFragment dialog = UploadSourceDialogFragment.newInstance(getAccount()); dialog.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE); - break; } case android.R.id.home: { @@@ -568,23 -564,6 +578,23 @@@ builder.create().show(); break; } + case R.id.action_switch_view:{ + if (isGridView()){ + item.setTitle(getApplicationContext().getString(R.string.action_switch_grid_view)); + item.setIcon(ContextCompat.getDrawable(getApplicationContext(), + R.drawable.ic_view_module)); + DisplayUtils.setViewMode(getFile(), false); + switchToListView(); + } else { + item.setTitle(getApplicationContext().getString(R.string.action_switch_list_view)); + item.setIcon(ContextCompat.getDrawable(getApplicationContext(), + R.drawable.ic_view_list)); + DisplayUtils.setViewMode(getFile(), true); + switchToGridView(); + } + + return true; + } default: retval = super.onOptionsItemSelected(item); } @@@ -648,17 -627,30 +658,30 @@@ 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 { @@@ -766,9 -758,9 +789,9 @@@ /** * 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); @@@ -776,6 -768,18 +799,18 @@@ 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() { if (!isDrawerOpen()){ @@@ -794,26 -798,11 +829,26 @@@ setFile(listOfFiles.getCurrentFile()); } cleanSecondFragment(); + + changeGridIcon(); } else { super.onBackPressed(); } } + private void changeGridIcon(){ + MenuItem menuItem = mOptionsMenu.findItem(R.id.action_switch_view); + if (DisplayUtils.isGridView(getFile(), getStorageManager())){ + menuItem.setTitle(getApplicationContext().getString(R.string.action_switch_list_view)); + menuItem.setIcon(ContextCompat.getDrawable(getApplicationContext(), + R.drawable.ic_view_list)); + } else { + menuItem.setTitle(getApplicationContext().getString(R.string.action_switch_grid_view)); + menuItem.setIcon(ContextCompat.getDrawable(getApplicationContext(), + R.drawable.ic_view_module)); + } + } + @Override protected void onSaveInstanceState(Bundle outState) { // responsibility of restore is preferred in onCreate() before than in @@@ -828,18 -817,15 +863,15 @@@ Log_OC.v(TAG, "onSaveInstanceState() end"); } - @Override protected void onResume() { Log_OC.v(TAG, "onResume() start"); super.onResume(); - // refresh Navigation Drawer account list mNavigationDrawerAdapter.updateAccountList(); - // refresh list of files refreshListOfFilesFragment(); @@@ -865,8 -851,9 +897,9 @@@ downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage()); mDownloadFinishReceiver = new DownloadFinishReceiver(); registerReceiver(mDownloadFinishReceiver, downloadIntentFilter); - + Log_OC.v(TAG, "onResume() end"); + } @@@ -886,7 -873,7 +919,7 @@@ unregisterReceiver(mDownloadFinishReceiver); mDownloadFinishReceiver = null; } - + super.onPause(); Log_OC.v(TAG, "onPause() end"); } @@@ -910,12 -897,12 +943,12 @@@ FileSyncAdapter.EXTRA_RESULT); boolean sameAccount = (getAccount() != null && 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()); @@@ -931,8 -918,9 +964,9 @@@ synchFolderRemotePath), Toast.LENGTH_LONG) .show(); + browseToRoot(); - + } else { if (currentFile == null && !getFile().isFolder()) { // currently selected file was removed in the server, and now we @@@ -953,19 -941,19 +987,19 @@@ } 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))) { + equals(event) &&/// TODO refactor and make common + + synchResult != null && !synchResult.isSuccess() && + (synchResult.getCode() == ResultCode.UNAUTHORIZED || + synchResult.isIdPRedirection() || + (synchResult.isException() && synchResult.getException() + instanceof AuthenticatorException))) { try { @@@ -974,7 -962,6 +1008,6 @@@ new OwnCloudAccount(getAccount(), context); client = (OwnCloudClientManagerFactory.getDefaultSingleton(). removeClientFor(ocAccount)); - if (client != null) { OwnCloudCredentials cred = client.getCredentials(); if (cred != null) { @@@ -1005,9 -992,9 +1038,9 @@@ /*|| mRefreshSharesInProgress*/ //); setBackgroundText(); - + } - + if (synchResult != null) { if (synchResult.getCode().equals( RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) { @@@ -1021,7 -1008,7 +1054,7 @@@ } } } - + /** * Show a text message on screen view for notifying user if content is * loading or folder is empty @@@ -1046,7 -1033,8 +1079,8 @@@ 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 @@@ -1056,23 -1044,23 +1090,23 @@@ 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)); @@@ -1080,23 -1068,28 +1114,28 @@@ 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? + + // Force the preview if the file is an image or text file + if (uploadWasFine) { + OCFile ocFile = getFile(); + if (PreviewImageFragment.canBePreviewed(ocFile)) + startImagePreview(getFile()); + else if (PreviewTextFragment.canBePreviewed(ocFile)) + startTextPreview(ocFile); + // TODO what about other kind of previews? + } } mProgressBar.setIndeterminate(false); @@@ -1105,15 -1098,15 +1144,15 @@@ 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. */ @@@ -1141,15 -1134,15 +1180,15 @@@ intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false) ); } - + if (mWaitingToSend != null) { mWaitingToSend = getStorageManager().getFileByPath(mWaitingToSend.getRemotePath()); - if (mWaitingToSend.isDown()) { + if (mWaitingToSend.isDown()) { sendDownloadedFile(); } } - + } finally { if (intent != null) { removeStickyBroadcast(intent); @@@ -1180,10 -1173,10 +1219,10 @@@ 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); @@@ -1193,13 -1186,12 +1232,12 @@@ startSyncFolderOperation(root, false); } cleanSecondFragment(); - } /** * {@inheritDoc} - * + *

* Updates action bar and second fragment, if in dual pane mode. */ @Override @@@ -1208,22 -1200,13 +1246,22 @@@ cleanSecondFragment(); // Sync Folder startSyncFolderOperation(directory, false); + + MenuItem menuItem = mOptionsMenu.findItem(R.id.action_switch_view); + + changeGridIcon(); + if (DisplayUtils.isGridView(directory, getStorageManager())){ + switchToGridView(); + } else { + switchToListView(); + } } /** - * 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) { @@@ -1251,7 -1234,9 +1289,9 @@@ 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 @@@ -1268,7 -1253,7 +1308,7 @@@ if (!mWaitingToPreview.isDown()) { requestForDownload(); } - } + } } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) { @@@ -1279,7 -1264,7 +1319,7 @@@ } // a new chance to get the mDownloadBinder through // getFileDownloadBinder() - THIS IS A MESS - OCFileListFragment listOfFiles = getListOfFilesFragment(); + OCFileListFragment listOfFiles = getListOfFilesFragment(); if (listOfFiles != null) { listOfFiles.listDirectory(); // TODO Enable when "On Device" is recovered ? @@@ -1287,7 -1272,7 +1327,7 @@@ } FileFragment secondFragment = getSecondFragment(); if (secondFragment != null && secondFragment instanceof FileDetailFragment) { - FileDetailFragment detailFragment = (FileDetailFragment)secondFragment; + FileDetailFragment detailFragment = (FileDetailFragment) secondFragment; detailFragment.listenForTransferProgress(); detailFragment.updateFileDetails(false, false); } @@@ -1305,7 -1290,7 +1345,7 @@@ mUploaderBinder = null; } } - }; + } @Override public void onSavedCertificate() { @@@ -1329,39 -1314,40 +1369,40 @@@ /** * 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()) { @@@ -1370,36 -1356,38 +1411,38 @@@ } } - 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 if (details instanceof PreviewTextFragment) { + // Refresh OCFile of the fragment + ((PreviewTextFragment) 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. @@@ -1410,23 -1398,23 +1453,23 @@@ private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) { dismissLoadingDialog(); - + Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()), - Toast.LENGTH_LONG); + 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(); } - if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) { + if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())){ refreshListOfFilesFragment(); } invalidateOptionsMenu(); @@@ -1437,14 -1425,14 +1480,14 @@@ } } } - - + + /** - * 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) { @@@ -1454,17 -1442,41 +1497,41 @@@ } 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 @@@ -1489,14 -1501,22 +1556,22 @@@ 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); } + } else if (details instanceof PreviewTextFragment && + renamedFile.equals(details.getFile())) { + ((PreviewTextFragment) details).updateFile(renamedFile); + if (PreviewTextFragment.canBePreviewed(renamedFile)) { + startTextPreview(renamedFile); + } else { + getFileOperationsHelper().openFile(renamedFile); + } } } - + if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())){ refreshListOfFilesFragment(); } @@@ -1504,9 -1524,9 +1579,9 @@@ } else { Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()), - Toast.LENGTH_LONG); + Toast.LENGTH_LONG); msg.show(); - + if (result.isSslRecoverableException()) { mLastSslUntrustedServerResult = result; showUntrustedCertDialog(mLastSslUntrustedServerResult); @@@ -1521,6 -1541,7 +1596,7 @@@ OCFile syncedFile = operation.getLocalFile(); onTransferStateChanged(syncedFile, true, true); invalidateOptionsMenu(); + refreshShowDetails(); } } } @@@ -1540,18 -1561,18 +1616,18 @@@ } 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} */ @@@ -1562,16 -1583,16 +1638,16 @@@ 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); } } } - + } @@@ -1600,12 -1621,12 +1676,12 @@@ } 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, @@@ -1617,13 -1638,14 +1693,14 @@@ getApplicationContext() ); synchFolderOp.execute(getAccount(), MainApp.getAppContext(), this, null, null); + mProgressBar.setIndeterminate(true); setBackgroundText(); } /** - * Show untrusted cert dialog + * Show untrusted cert dialog */ public void showUntrustedCertDialog(RemoteOperationResult result) { // Show a dialog with the certificate info @@@ -1633,7 -1655,7 +1710,7 @@@ FragmentTransaction ft = fm.beginTransaction(); dialog.show(ft, DIALOG_UNTRUSTED_CERT); } - + private void requestForDownload(OCFile file) { Account account = getAccount(); if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) { @@@ -1643,43 -1665,42 +1720,42 @@@ 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. @@@ -1696,11 -1717,28 +1772,28 @@@ } /** + * Stars the preview of a text file {@link OCFile}. + * + * @param file Text {@link OCFile} to preview. + */ + public void startTextPreview(OCFile file) { + Bundle args = new Bundle(); + args.putParcelable(EXTRA_FILE, file); + args.putParcelable(EXTRA_ACCOUNT, getAccount()); + Fragment textPreviewFragment = Fragment.instantiate(getApplicationContext(), + PreviewTextFragment.class.getName(), args); + setSecondFragment(textPreviewFragment); + updateFragmentsVisibility(true); + //updateNavigationElementsInActionBar(file); + setFile(file); + } + + /** * 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()); @@@ -1715,7 -1753,7 +1808,7 @@@ public void cancelTransference(OCFile file) { getFileOperationsHelper().cancelTransference(file); - if (mWaitingToPreview != null && + if (mWaitingToPreview != null && mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) { mWaitingToPreview = null; } @@@ -1748,24 -1786,17 +1841,24 @@@ } } - 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); } + private boolean isGridView(){ return getListOfFilesFragment().isGridView(); } + private void switchToGridView() { + getListOfFilesFragment().switchToGridView(); + } + private void switchToListView() { + getListOfFilesFragment().switchToListView(); + } public void allFilesOption() { browseToRoot(); diff --combined src/com/owncloud/android/ui/adapter/FileListListAdapter.java index d6d0ec78,5e94e0f2..dcc715f0 --- a/src/com/owncloud/android/ui/adapter/FileListListAdapter.java +++ b/src/com/owncloud/android/ui/adapter/FileListListAdapter.java @@@ -4,6 -4,7 +4,7 @@@ * @author Bartek Przybylski * @author Tobias Kaminsky * @author David A. Velasco + * @author masensio * Copyright (C) 2011 Bartek Przybylski * Copyright (C) 2015 ownCloud Inc. * @@@ -54,6 -55,7 +55,7 @@@ import com.owncloud.android.services.Op import com.owncloud.android.ui.activity.ComponentsGetter; import com.owncloud.android.utils.DisplayUtils; import com.owncloud.android.utils.FileStorageUtils; + import com.owncloud.android.utils.MimetypeIconUtil; /** @@@ -320,24 -322,23 +322,23 @@@ public class FileListListAdapter extend task.execute(file); } } + + if (file.getMimetype().equalsIgnoreCase("image/png")) { + fileIcon.setBackgroundColor(mContext.getResources() + .getColor(R.color.background_color)); + } + + } else { - fileIcon.setImageResource(DisplayUtils.getFileTypeIconId(file.getMimetype(), + fileIcon.setImageResource(MimetypeIconUtil.getFileTypeIconId(file.getMimetype(), file.getFileName())); } } else { // Folder - if (checkIfFileIsSharedWithMe(file)) { - fileIcon.setImageResource(R.drawable.shared_with_me_folder); - } else if (file.isShareByLink()) { - // If folder is sharedByLink, icon folder must be changed to - // folder-public one - fileIcon.setImageResource(R.drawable.folder_public); - } else { - fileIcon.setImageResource( - DisplayUtils.getFileTypeIconId(file.getMimetype(), file.getFileName()) - ); - } + fileIcon.setImageResource( + MimetypeIconUtil.getFolderTypeIconId( + checkIfFileIsSharedWithMe(file), file.isShareByLink())); } } @@@ -486,8 -487,4 +487,8 @@@ public void setGridMode(boolean gridMode) { mGridMode = gridMode; } + + public boolean isGridMode() { + return mGridMode; + } } diff --combined src/com/owncloud/android/ui/fragment/ExtendedListFragment.java index 001d48fd,24015d08..1a19e651 --- a/src/com/owncloud/android/ui/fragment/ExtendedListFragment.java +++ b/src/com/owncloud/android/ui/fragment/ExtendedListFragment.java @@@ -71,8 -71,8 +71,8 @@@ public class ExtendedListFragment exten private ArrayList mTops; private int mHeightCell = 0; - private OnEnforceableRefreshListener mOnRefreshListener = null; - + private SwipeRefreshLayout.OnRefreshListener mOnRefreshListener = null; + protected AbsListView mCurrentListView; private ExtendedListView mListView; private View mListFooterView; @@@ -97,7 -97,7 +97,7 @@@ } - protected void switchToGridView() { + public void switchToGridView() { if ((mCurrentListView == mListView)) { mListView.setAdapter(null); @@@ -112,8 -112,8 +112,8 @@@ mCurrentListView = mGridView; } } - - protected void switchToListView() { + + public void switchToListView() { if (mCurrentListView == mGridView) { mGridView.setAdapter(null); mRefreshGridLayout.setVisibility(View.GONE); @@@ -127,13 -127,6 +127,13 @@@ mCurrentListView = mListView; } } + + public boolean isGridView(){ + if (mAdapter instanceof FileListListAdapter) { + return ((FileListListAdapter) mAdapter).isGridMode(); + } + return false; + } @Override @@@ -359,7 -352,7 +359,7 @@@ mRefreshEmptyLayout.setRefreshing(false); if (mOnRefreshListener != null) { - mOnRefreshListener.onRefresh(ignoreETag); + mOnRefreshListener.onRefresh(); } } diff --combined src/com/owncloud/android/ui/fragment/OCFileListFragment.java index ac06fc7e,02bd845d..1321fa00 --- a/src/com/owncloud/android/ui/fragment/OCFileListFragment.java +++ b/src/com/owncloud/android/ui/fragment/OCFileListFragment.java @@@ -22,8 -22,6 +22,6 @@@ */ package com.owncloud.android.ui.fragment; - import java.io.File; - import android.app.Activity; import android.content.Intent; import android.os.Bundle; @@@ -55,12 -53,14 +53,15 @@@ import com.owncloud.android.ui.dialog.R 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.DisplayUtils; import com.owncloud.android.utils.FileStorageUtils; + import com.owncloud.android.ui.preview.PreviewTextFragment; + + import java.io.File; /** * 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 implements FileActionsDialogFragment.FileActionsDialogFragmentListener { @@@ -69,14 -69,14 +70,14 @@@ 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; @@@ -94,21 -94,21 +95,21 @@@ 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); @@@ -140,7 -140,7 +141,7 @@@ mJustFolders, getActivity(), mContainerActivity - ); + ); setListAdapter(mAdapter); registerLongClickListener(); @@@ -193,7 -193,7 +194,7 @@@ } } - FileActionsDialogFragment dialog = FileActionsDialogFragment.newInstance(menu, fileIndex); + FileActionsDialogFragment dialog = FileActionsDialogFragment.newInstance(menu, fileIndex, targetFile.getFileName()); dialog.setTargetFragment(this, 0); dialog.show(getFragmentManager(), FileActionsDialogFragment.FTAG_FILE_ACTIONS); } @@@ -203,31 -203,31 +204,31 @@@ * 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. - * + * * 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. - * + *

* 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 { @@@ -235,8 -235,8 +236,8 @@@ } 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 @@@ -246,20 -246,20 +247,20 @@@ 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()*/); @@@ -267,48 -267,49 +268,49 @@@ 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); - + } else if (PreviewTextFragment.canBePreviewed(file)){ + ((FileDisplayActivity)mContainerActivity).startTextPreview(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) { 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, @@@ -330,9 -331,6 +332,9 @@@ item.setEnabled(false); } } + +// String.format(mContext.getString(R.string.subject_token), +// getClient().getCredentials().getUsername(), file.getFileName())); } } @@@ -406,6 -404,13 +408,13 @@@ 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 false; } @@@ -429,12 -434,13 +438,13 @@@ /** * 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 */ @@@ -448,12 -454,12 +458,12 @@@ // 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*/) { @@@ -461,8 -467,8 +471,8 @@@ 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("/"); @@@ -470,9 -476,9 +480,9 @@@ } } - + // 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()); } @@@ -499,9 -505,12 +509,12 @@@ if (file.isFolder()) { foldersCount++; } else { - filesCount++; - if (file.isImage()){ - imagesCount++; + if (!file.isHidden()) { + filesCount++; + + if (file.isImage()) { + imagesCount++; + } } } } @@@ -512,7 -521,7 +525,7 @@@ OwnCloudVersion version = AccountUtils.getServerVersion( ((FileActivity)mContainerActivity).getAccount()); if (version != null && version.supportsRemoteThumbnails() && - imagesCount > 0 && imagesCount == filesCount) { + DisplayUtils.isGridView(mFile, mContainerActivity.getStorageManager())) { switchToGridView(); registerLongClickListener(); } else { diff --combined src/com/owncloud/android/utils/DisplayUtils.java index b835f8b6,8a281e92..374a7136 --- a/src/com/owncloud/android/utils/DisplayUtils.java +++ b/src/com/owncloud/android/utils/DisplayUtils.java @@@ -22,102 -22,54 +22,67 @@@ package com.owncloud.android.utils; +import java.io.File; +import java.net.IDN; +import java.text.DateFormat; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; +import java.util.Vector; + import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; +import android.content.SharedPreferences; import android.graphics.Point; import android.graphics.PorterDuff; import android.os.Build; import android.text.format.DateUtils; import android.view.Display; - import android.webkit.MimeTypeMap; import android.widget.ProgressBar; import android.widget.SeekBar; import com.owncloud.android.MainApp; import com.owncloud.android.R; +import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.OCFile; + import java.net.IDN; + import java.text.DateFormat; + import java.util.Calendar; + import java.util.Date; + import java.util.HashMap; + import java.util.Map; + /** * A helper class for some string operations. */ public class DisplayUtils { private static final String OWNCLOUD_APP_NAME = "ownCloud"; - - //private static String TAG = DisplayUtils.class.getSimpleName(); private static final String[] sizeSuffixes = { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" }; - private static HashMap mimeType2HUmanReadable; + private static Map mimeType2HumanReadable; + static { - mimeType2HUmanReadable = new HashMap(); + mimeType2HumanReadable = new HashMap(); // images - mimeType2HUmanReadable.put("image/jpeg", "JPEG image"); - mimeType2HUmanReadable.put("image/jpg", "JPEG image"); - mimeType2HUmanReadable.put("image/png", "PNG image"); - mimeType2HUmanReadable.put("image/bmp", "Bitmap image"); - mimeType2HUmanReadable.put("image/gif", "GIF image"); - mimeType2HUmanReadable.put("image/svg+xml", "JPEG image"); - mimeType2HUmanReadable.put("image/tiff", "TIFF image"); + mimeType2HumanReadable.put("image/jpeg", "JPEG image"); + mimeType2HumanReadable.put("image/jpg", "JPEG image"); + mimeType2HumanReadable.put("image/png", "PNG image"); + mimeType2HumanReadable.put("image/bmp", "Bitmap image"); + mimeType2HumanReadable.put("image/gif", "GIF image"); + mimeType2HumanReadable.put("image/svg+xml", "JPEG image"); + mimeType2HumanReadable.put("image/tiff", "TIFF image"); // music - mimeType2HUmanReadable.put("audio/mpeg", "MP3 music file"); - mimeType2HUmanReadable.put("application/ogg", "OGG music file"); - + mimeType2HumanReadable.put("audio/mpeg", "MP3 music file"); + mimeType2HumanReadable.put("application/ogg", "OGG music file"); } - private static final String TYPE_APPLICATION = "application"; - private static final String TYPE_AUDIO = "audio"; - private static final String TYPE_IMAGE = "image"; - private static final String TYPE_TXT = "text"; - private static final String TYPE_VIDEO = "video"; - - private static final String SUBTYPE_PDF = "pdf"; - private static final String SUBTYPE_XML = "xml"; - private static final String[] SUBTYPES_DOCUMENT = { - "msword", - "vnd.openxmlformats-officedocument.wordprocessingml.document", - "vnd.oasis.opendocument.text", - "rtf", - "javascript" - }; - private static Set SUBTYPES_DOCUMENT_SET = new HashSet(Arrays.asList(SUBTYPES_DOCUMENT)); - private static final String[] SUBTYPES_SPREADSHEET = { - "msexcel", - "vnd.ms-excel", - "vnd.openxmlformats-officedocument.spreadsheetml.sheet", - "vnd.oasis.opendocument.spreadsheet" - }; - private static Set SUBTYPES_SPREADSHEET_SET = new HashSet(Arrays.asList(SUBTYPES_SPREADSHEET)); - private static final String[] SUBTYPES_PRESENTATION = { - "mspowerpoint", - "vnd.ms-powerpoint", - "vnd.openxmlformats-officedocument.presentationml.presentation", - "vnd.oasis.opendocument.presentation" - }; - private static Set SUBTYPES_PRESENTATION_SET = new HashSet(Arrays.asList(SUBTYPES_PRESENTATION)); - private static final String[] SUBTYPES_COMPRESSED = {"x-tar", "x-gzip", "zip"}; - private static final Set SUBTYPES_COMPRESSED_SET = new HashSet(Arrays.asList(SUBTYPES_COMPRESSED)); - private static final String SUBTYPE_OCTET_STREAM = "octet-stream"; - private static final String EXTENSION_RAR = "rar"; - private static final String EXTENSION_RTF = "rtf"; - private static final String EXTENSION_3GP = "3gp"; - private static final String EXTENSION_PY = "py"; - private static final String EXTENSION_JS = "js"; - /** * Converts the file size in bytes to human readable output. * @@@ -143,100 -95,14 +108,14 @@@ * @return A human friendly version of the MIME type */ public static String convertMIMEtoPrettyPrint(String mimetype) { - if (mimeType2HUmanReadable.containsKey(mimetype)) { - return mimeType2HUmanReadable.get(mimetype); + if (mimeType2HumanReadable.containsKey(mimetype)) { + return mimeType2HumanReadable.get(mimetype); } if (mimetype.split("/").length >= 2) return mimetype.split("/")[1].toUpperCase() + " file"; return "Unknown type"; } - - - /** - * Returns the resource identifier of an image to use as icon associated to a known MIME type. - * - * @param mimetype MIME type string; if NULL, the method tries to guess it from the extension in filename - * @param filename Name, with extension. - * @return Identifier of an image resource. - */ - public static int getFileTypeIconId(String mimetype, String filename) { - if (mimetype == null) { - String fileExtension = getExtension(filename); - mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension); - if (mimetype == null) { - mimetype = TYPE_APPLICATION + "/" + SUBTYPE_OCTET_STREAM; - } - } - - if ("DIR".equals(mimetype)) { - return R.drawable.ic_menu_archive; - - } else { - String [] parts = mimetype.split("/"); - String type = parts[0]; - String subtype = (parts.length > 1) ? parts[1] : ""; - - if(TYPE_TXT.equals(type)) { - return R.drawable.file_doc; - - } else if(TYPE_IMAGE.equals(type)) { - return R.drawable.file_image; - - } else if(TYPE_VIDEO.equals(type)) { - return R.drawable.file_movie; - - } else if(TYPE_AUDIO.equals(type)) { - return R.drawable.file_sound; - - } else if(TYPE_APPLICATION.equals(type)) { - - if (SUBTYPE_PDF.equals(subtype)) { - return R.drawable.file_pdf; - - } else if (SUBTYPE_XML.equals(subtype)) { - return R.drawable.file_doc; - - } else if (SUBTYPES_DOCUMENT_SET.contains(subtype)) { - return R.drawable.file_doc; - - } else if (SUBTYPES_SPREADSHEET_SET.contains(subtype)) { - return R.drawable.file_xls; - - } else if (SUBTYPES_PRESENTATION_SET.contains(subtype)) { - return R.drawable.file_ppt; - - } else if (SUBTYPES_COMPRESSED_SET.contains(subtype)) { - return R.drawable.file_zip; - - } else if (SUBTYPE_OCTET_STREAM.equals(subtype) ) { - if (getExtension(filename).equalsIgnoreCase(EXTENSION_RAR)) { - return R.drawable.file_zip; - - } else if (getExtension(filename).equalsIgnoreCase(EXTENSION_RTF)) { - return R.drawable.file_doc; - - } else if (getExtension(filename).equalsIgnoreCase(EXTENSION_3GP)) { - return R.drawable.file_movie; - - } else if ( getExtension(filename).equalsIgnoreCase(EXTENSION_PY) || - getExtension(filename).equalsIgnoreCase(EXTENSION_JS)) { - return R.drawable.file_doc; - } - } - } - } - - // default icon - return R.drawable.file; - } - - - private static String getExtension(String filename) { - String extension = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase(); - return extension; - } - /** * Converts Unix time to human readable format * @param milliseconds that have passed since 01/01/1970 @@@ -248,7 -114,6 +127,6 @@@ return df.format(date); } - public static int getSeasonalIconId() { if (Calendar.getInstance().get(Calendar.DAY_OF_YEAR) >= 354 && MainApp.getAppContext().getString(R.string.app_name).equals(OWNCLOUD_APP_NAME)) { @@@ -380,67 -245,6 +258,67 @@@ } /** + * Determines if user set folder to grid or list view. If folder is not set itself, + * it finds a parent that is set (at least root is set). + * @param file + * @param storageManager + * @return + */ + public static boolean isGridView(OCFile file, FileDataStorageManager storageManager){ + if (file != null) { + OCFile fileToTest = file; + OCFile parentDir = null; + String parentPath = null; + + SharedPreferences setting = MainApp.getAppContext().getSharedPreferences( + "viewMode", Context.MODE_PRIVATE); + + if (setting.contains(fileToTest.getRemoteId())) { + return setting.getBoolean(fileToTest.getRemoteId(), false); + } else { + do { + if (fileToTest.getParentId() != FileDataStorageManager.ROOT_PARENT_ID) { + parentPath = new File(fileToTest.getRemotePath()).getParent(); + parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : + parentPath + OCFile.PATH_SEPARATOR; + parentDir = storageManager.getFileByPath(parentPath); + } else { + parentDir = storageManager.getFileByPath(OCFile.ROOT_PATH); + } + + while (parentDir == null) { + parentPath = new File(parentPath).getParent(); + parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : + parentPath + OCFile.PATH_SEPARATOR; + parentDir = storageManager.getFileByPath(parentPath); + } + fileToTest = parentDir; + } while (endWhile(parentDir, setting)); + return setting.getBoolean(fileToTest.getRemoteId(), false); + } + } else { + return false; + } + } + + private static boolean endWhile(OCFile parentDir, SharedPreferences setting) { + if (parentDir.getRemotePath().compareToIgnoreCase(OCFile.ROOT_PATH) == 0) { + return false; + } else { + return !setting.contains(parentDir.getRemoteId()); + } + } + + public static void setViewMode(OCFile file, boolean setGrid){ + SharedPreferences setting = MainApp.getAppContext().getSharedPreferences( + "viewMode", Context.MODE_PRIVATE); + + SharedPreferences.Editor editor = setting.edit(); + editor.putBoolean(file.getRemoteId(), setGrid); + editor.commit(); + } + + /** * sets the coloring of the given progress bar to color_accent. * * @param progressBar the progress bar to be colored