diff --git a/app/src/androidTest/java/com/nextcloud/client/AutoUploadFragmentIT.kt b/app/src/androidTest/java/com/nextcloud/client/AutoUploadFragmentIT.kt index ccfc8243d98d..aa5b626d9669 100644 --- a/app/src/androidTest/java/com/nextcloud/client/AutoUploadFragmentIT.kt +++ b/app/src/androidTest/java/com/nextcloud/client/AutoUploadFragmentIT.kt @@ -22,7 +22,7 @@ import com.owncloud.android.R import com.owncloud.android.datamodel.MediaFolderType import com.owncloud.android.datamodel.SyncedFolder import com.owncloud.android.datamodel.SyncedFolderDisplayItem -import com.owncloud.android.ui.dialog.SyncedFolderPreferencesDialogFragment.Companion.newInstance +import com.owncloud.android.ui.dialog.AutoUploadPreferenceDialogFragment.Companion.newInstance import com.owncloud.android.ui.fragment.autoUpload.AutoUploadFragment import com.owncloud.android.ui.navigation.NavigatorActivity import com.owncloud.android.ui.navigation.NavigatorScreen @@ -86,7 +86,7 @@ class AutoUploadFragmentIT : AbstractIT() { onView(isRoot()).check(matches(isDisplayed())) scenario.onActivity { sut -> - val dialog = newInstance(item, 0) ?: throw IllegalStateException("Dialog could not be created") + val dialog = newInstance(item) dialog.show(findFragment(sut).childFragmentManager, "") findFragment(sut).childFragmentManager.executePendingTransactions() screenshot(dialog.requireDialog().window?.decorView, screenShotName) diff --git a/app/src/main/java/com/nextcloud/client/di/ComponentsModule.kt b/app/src/main/java/com/nextcloud/client/di/ComponentsModule.kt index 745696d45571..4d5eb2399061 100644 --- a/app/src/main/java/com/nextcloud/client/di/ComponentsModule.kt +++ b/app/src/main/java/com/nextcloud/client/di/ComponentsModule.kt @@ -78,6 +78,7 @@ import com.owncloud.android.ui.activity.UploadFilesActivity import com.owncloud.android.ui.activity.UserInfoActivity import com.owncloud.android.ui.dialog.AccountRemovalDialog import com.owncloud.android.ui.dialog.AppPassCodeDialog +import com.owncloud.android.ui.dialog.AutoUploadPreferenceDialogFragment import com.owncloud.android.ui.dialog.ChooseRichDocumentsTemplateDialogFragment import com.owncloud.android.ui.dialog.ChooseTemplateDialogFragment import com.owncloud.android.ui.dialog.ConfirmationDialogFragment @@ -97,7 +98,6 @@ import com.owncloud.android.ui.dialog.SortingOrderDialogFragment import com.owncloud.android.ui.dialog.SslUntrustedCertDialog import com.owncloud.android.ui.dialog.StoragePermissionDialogFragment import com.owncloud.android.ui.dialog.SyncFileNotEnoughSpaceDialogFragment -import com.owncloud.android.ui.dialog.SyncedFolderPreferencesDialogFragment import com.owncloud.android.ui.dialog.TermsOfServiceDialog import com.owncloud.android.ui.dialog.ThemeSelectionDialog import com.owncloud.android.ui.dialog.conflict.ConflictsResolveDialog @@ -428,7 +428,7 @@ internal interface ComponentsModule { fun sharePasswordDialogFragment(): SharePasswordDialogFragment @ContributesAndroidInjector - fun syncedFolderPreferencesDialogFragment(): SyncedFolderPreferencesDialogFragment + fun autoUploadPreferenceDialogFragment(): AutoUploadPreferenceDialogFragment @ContributesAndroidInjector fun toolbarActivity(): ToolbarActivity diff --git a/app/src/main/java/com/owncloud/android/ui/adapter/SyncedFolderAdapter.kt b/app/src/main/java/com/owncloud/android/ui/adapter/SyncedFolderAdapter.kt deleted file mode 100644 index 921492245537..000000000000 --- a/app/src/main/java/com/owncloud/android/ui/adapter/SyncedFolderAdapter.kt +++ /dev/null @@ -1,550 +0,0 @@ -/* - * Nextcloud - Android Client - * - * SPDX-FileCopyrightText: 2016 Andy Scherzinger - * SPDX-FileCopyrightText: 2016 Nextcloud - * SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only - */ -package com.owncloud.android.ui.adapter - -import android.annotation.SuppressLint -import android.content.Context -import android.view.LayoutInflater -import android.view.MenuItem -import android.view.View -import android.view.ViewGroup -import android.widget.PopupMenu -import androidx.annotation.VisibleForTesting -import androidx.core.content.ContextCompat -import androidx.core.view.isVisible -import androidx.lifecycle.LifecycleCoroutineScope -import com.afollestad.sectionedrecyclerview.SectionedRecyclerViewAdapter -import com.afollestad.sectionedrecyclerview.SectionedViewHolder -import com.google.android.material.button.MaterialButton -import com.nextcloud.android.common.ui.theme.utils.ColorRole -import com.nextcloud.client.core.Clock -import com.nextcloud.client.device.PowerManagementService -import com.nextcloud.client.network.ConnectivityService -import com.nextcloud.utils.extensions.calculateScanInterval -import com.nextcloud.utils.extensions.filterEnabledOrWithoutEnabledParent -import com.nextcloud.utils.extensions.hasEnabledParent -import com.nextcloud.utils.extensions.setVisibleIf -import com.nextcloud.utils.thumbnail.job.MediaThumbnailGenerationJob -import com.owncloud.android.R -import com.owncloud.android.databinding.GridSyncItemBinding -import com.owncloud.android.databinding.SyncedFoldersEmptyBinding -import com.owncloud.android.databinding.SyncedFoldersFooterBinding -import com.owncloud.android.databinding.SyncedFoldersItemHeaderBinding -import com.owncloud.android.datamodel.MediaFolderType -import com.owncloud.android.datamodel.SyncedFolder -import com.owncloud.android.datamodel.SyncedFolderDisplayItem -import com.owncloud.android.datamodel.ThumbnailsCacheManager -import com.owncloud.android.utils.FileUtil -import com.owncloud.android.utils.theme.ViewThemeUtils -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext -import java.io.File -import java.util.Locale -import java.util.concurrent.TimeUnit - -/** - * Adapter to display all auto-synced folders and/or instant upload media folders. - */ -class SyncedFolderAdapter( - private val lifecycleScope: LifecycleCoroutineScope, - private val context: Context, - private val clock: Clock, - private val gridWidth: Int, - private val clickListener: ClickListener, - private val light: Boolean, - private val viewThemeUtils: ViewThemeUtils, - private val powerManagementService: PowerManagementService, - private val connectivityService: ConnectivityService -) : SectionedRecyclerViewAdapter() { - - private val gridTotal = gridWidth * 2 - private val syncFolderItems: MutableList = ArrayList() - private val filteredSyncFolderItems: MutableList = ArrayList() - private var hideItems = true - private val mediaThumbnailGenerationJob = MediaThumbnailGenerationJob(context, viewThemeUtils) - - private val minimumSizeForTouchableArea - by lazy { context.resources.getDimensionPixelSize(R.dimen.minimum_size_for_touchable_area) } - private val screenWidth by lazy { context.resources.displayMetrics.widthPixels } - private val standardDoubleMargin - by lazy { context.resources.getDimensionPixelSize(R.dimen.standard_double_margin) } - private val syncedFoldersTitleMargin - by lazy { context.resources.getDimensionPixelSize(R.dimen.synced_folders_title_margin) } - - init { - shouldShowHeadersForEmptySections(true) - shouldShowFooters(true) - } - - @SuppressLint("NotifyDataSetChanged") - fun toggleHiddenItemsVisibility() { - hideItems = !hideItems - - filterHiddenItems(syncFolderItems, hideItems)?.let { - filteredSyncFolderItems.clear() - filteredSyncFolderItems.addAll(it) - notifyDataSetChanged() - } - } - - fun setSyncFolderItems(newList: List) { - val filteredList = newList.filterEnabledOrWithoutEnabledParent() - syncFolderItems.clear() - syncFolderItems.addAll(filteredList) - - filterHiddenItems(syncFolderItems, hideItems)?.let { - filteredSyncFolderItems.clear() - filteredSyncFolderItems.addAll(it) - } - } - - @SuppressLint("NotifyDataSetChanged") - fun setSyncFolderItem(location: Int, syncFolderItem: SyncedFolderDisplayItem) { - if (hideItems && syncFolderItem.isHidden && filteredSyncFolderItems.contains(syncFolderItem)) { - filteredSyncFolderItems.removeAt(location) - } else { - if (filteredSyncFolderItems.contains(syncFolderItem)) { - filteredSyncFolderItems[filteredSyncFolderItems.indexOf(syncFolderItem)] = syncFolderItem - } else { - filteredSyncFolderItems.add(syncFolderItem) - } - } - - if (syncFolderItems.contains(syncFolderItem)) { - syncFolderItems[syncFolderItems.indexOf(syncFolderItem)] = syncFolderItem - } else { - syncFolderItems.add(syncFolderItem) - } - - notifyDataSetChanged() - } - - @SuppressLint("NotifyDataSetChanged") - fun addSyncFolderItem(syncFolderItem: SyncedFolderDisplayItem) { - syncFolderItems.add(syncFolderItem) - - // add item for display when either all items should be shown (!hideItems) - // or if item should be shown (!.isHidden()) - if (!hideItems || !syncFolderItem.isHidden) { - filteredSyncFolderItems.add(syncFolderItem) - notifyDataSetChanged() - } - } - - @SuppressLint("NotifyDataSetChanged") - fun removeItem(section: Int) { - if (filteredSyncFolderItems.contains(syncFolderItems[section])) { - filteredSyncFolderItems.remove(syncFolderItems[section]) - notifyDataSetChanged() - } - - syncFolderItems.removeAt(section) - } - - /** - * Filter for hidden items - * - * @param items Collection of items to filter - * @return Non-hidden items - */ - private fun filterHiddenItems( - items: List?, - hide: Boolean - ): List? { - if (!hide) { - return items - } else { - val result: MutableList = ArrayList() - - for (item in items!!) { - if (!item.isHidden && !result.contains(item)) { - result.add(item) - } - } - - return result - } - } - - override fun getSectionCount(): Int = if (filteredSyncFolderItems.size > 0) { - filteredSyncFolderItems.size + 1 - } else { - 0 - } - - @VisibleForTesting - fun clear() { - filteredSyncFolderItems.clear() - syncFolderItems.clear() - } - - val unfilteredSectionCount: Int - get() = if (syncFolderItems.size > 0) { - syncFolderItems.size + 1 - } else { - 0 - } - - override fun getItemCount(section: Int): Int { - if (section < filteredSyncFolderItems.size) { - val filePaths = filteredSyncFolderItems[section].filePaths - - return if (filePaths != null) { - filteredSyncFolderItems[section].filePaths.size - } else { - 1 - } - } else { - return 1 - } - } - - fun get(section: Int): SyncedFolderDisplayItem? = if (section in filteredSyncFolderItems.indices) { - filteredSyncFolderItems[section] - } else { - null - } - - override fun getItemViewType(section: Int, relativePosition: Int, absolutePosition: Int): Int = - if (isLastSection(section)) { - VIEW_TYPE_EMPTY - } else { - VIEW_TYPE_ITEM - } - - override fun getHeaderViewType(section: Int): Int = if (isLastSection(section)) { - VIEW_TYPE_EMPTY - } else { - VIEW_TYPE_HEADER - } - - override fun getFooterViewType(section: Int): Int = if (isLastSection(section) && showFooter()) { - VIEW_TYPE_FOOTER - } else { - // only show footer after last item and only if folders have been hidden - VIEW_TYPE_EMPTY - } - - private fun showFooter(): Boolean = syncFolderItems.size > filteredSyncFolderItems.size - - /** - * returns the section of a synced folder for the given local path and type. - * - * @param localPath the local path of the synced folder - * @param type the of the synced folder - * @return the section index of the looked up synced folder, `-1` if not present - */ - fun getSectionByLocalPathAndType(localPath: String?, type: Int): Int { - for (i in filteredSyncFolderItems.indices) { - if (filteredSyncFolderItems[i].localPath.equals(localPath, ignoreCase = true) && - filteredSyncFolderItems[i].type.id == type - ) { - return i - } - } - - return -1 - } - - @Suppress("NestedBlockDepth") - override fun onBindHeaderViewHolder(commonHolder: SectionedViewHolder, section: Int, expanded: Boolean) { - if (section < filteredSyncFolderItems.size) { - val holder = commonHolder as HeaderViewHolder - - holder.binding.run { - headerContainer.visibility = View.VISIBLE - - val syncedFolder = filteredSyncFolderItems[section] - - title.text = syncedFolder.folderName - - if (MediaFolderType.VIDEO == syncedFolder.type) { - type.setImageResource(R.drawable.video_32dp) - } else if (MediaFolderType.IMAGE == syncedFolder.type) { - type.setImageResource(R.drawable.image_32dp) - } else { - type.setImageResource(R.drawable.folder_star_32dp) - } - - syncStatusButton.visibility = View.VISIBLE - syncStatusButton.tag = section - syncStatusButton.setOnClickListener { - syncedFolder.setEnabled( - !syncedFolder.isEnabled, - clock.currentTime - ) - setSyncButtonActiveIcon( - syncStatusButton, - syncedFolder.isEnabled - ) - clickListener.onSyncStatusToggleClick(section, syncedFolder) - } - setSyncButtonActiveIcon(syncStatusButton, syncedFolder.isEnabled) - - if (light) { - settingsButton.visibility = View.GONE - } else { - settingsButton.visibility = View.VISIBLE - settingsButton.tag = section - settingsButton.setOnClickListener { v: View -> - onOverflowIconClicked( - section, - syncedFolder, - v - ) - } - } - - initSubFolderWarningButton(holder, section) - initNextScanIndicator(holder, syncedFolder) - } - } - } - - private fun initNextScanIndicator(holder: HeaderViewHolder, syncedFolder: SyncedFolder) { - lifecycleScope.launch(Dispatchers.IO) { - val scanIndicatorText = getNextScanIndicatorText(syncedFolder) - - withContext(Dispatchers.Main) { - holder.binding.scanIndicatorText.setVisibleIf(syncedFolder.isEnabled && (scanIndicatorText != null)) - - if (holder.binding.scanIndicatorText.isVisible) { - setMaxWidthOfScanIndicatorText(holder) - holder.binding.scanIndicatorText.text = scanIndicatorText - } else { - setBottomMarginOfTitle(holder) - } - } - } - } - - private fun setMaxWidthOfScanIndicatorText(holder: HeaderViewHolder) { - var visibleTrailingIconCount = 2 - if (holder.binding.subFolderWarningButton.isVisible) { - visibleTrailingIconCount += 1 - } - - val takenTrailingSpace = minimumSizeForTouchableArea * visibleTrailingIconCount - val maxWidthInPxOfScanIndicatorText = (screenWidth - takenTrailingSpace) - standardDoubleMargin - - holder.binding.scanIndicatorText.maxWidth = maxWidthInPxOfScanIndicatorText - } - - private fun setBottomMarginOfTitle(holder: HeaderViewHolder) { - val layoutParams = holder.binding.title.layoutParams as ViewGroup.MarginLayoutParams - layoutParams.bottomMargin = syncedFoldersTitleMargin - holder.binding.title.layoutParams = layoutParams - } - - private fun getNextScanIndicatorText(syncedFolder: SyncedFolder): String? { - val scanInterval = syncedFolder.calculateScanInterval(connectivityService, powerManagementService) - val nextScanInMillis = scanInterval.first - System.currentTimeMillis() - val minutesLeft = TimeUnit.MILLISECONDS - .toMinutes(nextScanInMillis) - .coerceAtLeast(0) - .toInt() - - return if (minutesLeft <= 0) { - null - } else { - val scanIntervalMessageId = scanInterval.second ?: return null - context.getString(scanIntervalMessageId) - } - } - - private fun initSubFolderWarningButton(holder: HeaderViewHolder, section: Int) { - val syncFolderItem = filteredSyncFolderItems[section] - val isGivenLocalPathHasEnabledParent = - filteredSyncFolderItems.hasEnabledParent(syncFolderItem.localPath) - holder.binding.subFolderWarningButton.run { - setVisibleIf(isGivenLocalPathHasEnabledParent) - if (isVisible) { - setOnClickListener { - clickListener.showSubFolderWarningDialog() - } - } - } - } - - private fun onOverflowIconClicked(section: Int, item: SyncedFolderDisplayItem, view: View) { - val popup = PopupMenu(context, view).apply { - inflate(R.menu.synced_folders_adapter) - setOnMenuItemClickListener { i: MenuItem -> optionsItemSelected(i, section, item) } - menu - .findItem(R.id.action_auto_upload_folder_toggle_visibility) - .setChecked(item.isHidden) - updateDeletionMenuItem( - item, - menu.findItem(R.id.action_auto_upload_folder_delete_uploaded) - ) - } - - popup.show() - } - - private fun optionsItemSelected(menuItem: MenuItem, section: Int, item: SyncedFolderDisplayItem): Boolean { - when (menuItem.itemId) { - R.id.action_auto_upload_folder_toggle_visibility -> clickListener.onVisibilityToggleClick(section, item) - - R.id.action_auto_upload_folder_settings -> clickListener.onSyncFolderSettingsClick(section, item) - - R.id.action_auto_upload_folder_delete_uploaded -> clickListener.onSyncFolderDeleteUploadedClick( - section, - item - ) - } - return true - } - - override fun onBindFooterViewHolder(holder: SectionedViewHolder, section: Int) { - if (isLastSection(section) && showFooter()) { - val footerHolder = holder as FooterViewHolder - footerHolder.binding.footerText.setOnClickListener { toggleHiddenItemsVisibility() } - footerHolder.binding.footerText.text = context.resources.getQuantityString( - R.plurals.synced_folders_show_hidden_folders, - hiddenFolderCount, - hiddenFolderCount - ) - } - } - - override fun onBindViewHolder( - commonHolder: SectionedViewHolder, - section: Int, - relativePosition: Int, - absolutePosition: Int - ) { - if (section < filteredSyncFolderItems.size && filteredSyncFolderItems[section].filePaths != null) { - val holder = commonHolder as MainViewHolder - - val file = File(filteredSyncFolderItems[section].filePaths[relativePosition]) - - val thumbnail = holder.binding.thumbnail - thumbnail.setImageBitmap(ThumbnailsCacheManager.mDefaultImg) - thumbnail.tag = file.hashCode() - lifecycleScope.launch { mediaThumbnailGenerationJob.load(file, thumbnail) } - - holder.itemView.tag = relativePosition % gridWidth - - if (filteredSyncFolderItems[section].numberOfFiles > gridTotal && - relativePosition >= gridTotal - 1 - ) { - holder.binding.counter.text = String.format( - Locale.US, - "%d", - filteredSyncFolderItems[section].numberOfFiles - gridTotal - ) - holder.binding.counterLayout.visibility = View.VISIBLE - holder.binding.thumbnailDarkener.visibility = View.VISIBLE - } else { - holder.binding.counterLayout.visibility = View.GONE - holder.binding.thumbnailDarkener.visibility = View.GONE - } - } - } - - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SectionedViewHolder = when (viewType) { - VIEW_TYPE_HEADER -> { - HeaderViewHolder( - SyncedFoldersItemHeaderBinding.inflate( - LayoutInflater.from(parent.context), - parent, - false - ) - ) - } - - VIEW_TYPE_FOOTER -> { - FooterViewHolder( - SyncedFoldersFooterBinding.inflate( - LayoutInflater.from(parent.context), - parent, - false - ) - ) - } - - VIEW_TYPE_EMPTY -> { - EmptyViewHolder( - SyncedFoldersEmptyBinding.inflate( - LayoutInflater.from(parent.context), - parent, - false - ) - ) - } - - else -> { - MainViewHolder( - GridSyncItemBinding.inflate( - LayoutInflater.from(parent.context), - parent, - false - ) - ) - } - } - - private fun isLastSection(section: Int): Boolean = section >= sectionCount - 1 - - val hiddenFolderCount: Int - get() = syncFolderItems.size - filteredSyncFolderItems.size - - interface ClickListener { - fun onSyncStatusToggleClick(section: Int, item: SyncedFolderDisplayItem?) - fun onSyncFolderSettingsClick(section: Int, syncedFolderDisplayItem: SyncedFolderDisplayItem?) - fun onSyncFolderDeleteUploadedClick(section: Int, syncedFolderDisplayItem: SyncedFolderDisplayItem?) - fun onVisibilityToggleClick(section: Int, item: SyncedFolderDisplayItem?) - fun showSubFolderWarningDialog() - } - - internal class HeaderViewHolder(var binding: SyncedFoldersItemHeaderBinding) : - SectionedViewHolder( - binding.root - ) - - internal class FooterViewHolder(var binding: SyncedFoldersFooterBinding) : - SectionedViewHolder( - binding.root - ) - - internal class EmptyViewHolder(binding: SyncedFoldersEmptyBinding) : SectionedViewHolder(binding.root) - - internal class MainViewHolder(var binding: GridSyncItemBinding) : - SectionedViewHolder( - binding.root - ) - - private fun setSyncButtonActiveIcon(syncStatusButton: MaterialButton, enabled: Boolean) { - if (enabled) { - syncStatusButton.icon = - viewThemeUtils.platform.tintDrawable(context, R.drawable.ic_cloud_sync_on, ColorRole.PRIMARY) - } else { - syncStatusButton.icon = ContextCompat.getDrawable(context, R.drawable.ic_cloud_sync_off) - } - } - - private fun updateDeletionMenuItem(syncedFolder: SyncedFolderDisplayItem, menuItem: MenuItem) { - val folderFile = syncedFolder.localPath?.let { File(it) } - lifecycleScope.launch { - val writable = FileUtil.isFolderWritable(folderFile) - withContext(Dispatchers.Main) { - menuItem.isEnabled = writable - menuItem.isVisible = writable - } - } - } - - companion object { - private const val VIEW_TYPE_EMPTY = Int.MAX_VALUE - private const val VIEW_TYPE_ITEM = 1 - private const val VIEW_TYPE_HEADER = 2 - private const val VIEW_TYPE_FOOTER = 3 - } -} diff --git a/app/src/main/java/com/owncloud/android/ui/dialog/AutoUploadFolderConfigurationListener.kt b/app/src/main/java/com/owncloud/android/ui/dialog/AutoUploadFolderConfigurationListener.kt new file mode 100644 index 000000000000..7a4144e0f552 --- /dev/null +++ b/app/src/main/java/com/owncloud/android/ui/dialog/AutoUploadFolderConfigurationListener.kt @@ -0,0 +1,17 @@ +/* + * Nextcloud - Android Client + * + * SPDX-FileCopyrightText: 2026 Alper Ozturk + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package com.owncloud.android.ui.dialog + +import com.owncloud.android.ui.dialog.parcel.SyncedFolderParcelable + +interface AutoUploadFolderConfigurationListener { + fun onSaveAutoUploadFolderConfiguration(syncedFolder: SyncedFolderParcelable) + fun onCancelAutoUploadFolderConfiguration() + fun onDeleteAutoUploadFolderConfiguration(syncedFolder: SyncedFolderParcelable) + fun onRemoteFolderPickerRequested() + fun onLocalFolderPickerRequested() +} diff --git a/app/src/main/java/com/owncloud/android/ui/dialog/AutoUploadForm.kt b/app/src/main/java/com/owncloud/android/ui/dialog/AutoUploadForm.kt new file mode 100644 index 000000000000..d0886fc06fb5 --- /dev/null +++ b/app/src/main/java/com/owncloud/android/ui/dialog/AutoUploadForm.kt @@ -0,0 +1,262 @@ +/* + * Nextcloud - Android Client + * + * SPDX-FileCopyrightText: 2026 Alper Ozturk + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package com.owncloud.android.ui.dialog + +import android.graphics.Typeface +import android.text.style.StyleSpan +import android.view.View +import android.widget.AdapterView +import android.widget.CompoundButton +import androidx.core.view.isVisible +import androidx.lifecycle.Lifecycle +import com.nextcloud.client.core.Clock +import com.nextcloud.client.preferences.SubFolderRule +import com.nextcloud.utils.text.SpanFormatter +import com.owncloud.android.R +import com.owncloud.android.databinding.DialogAutoUploadPreferenceBinding +import com.owncloud.android.datamodel.MediaFolderType +import com.owncloud.android.datamodel.SyncedFolder +import com.owncloud.android.ui.dialog.extensions.nameCollisionPolicyForDialogSelectionIndex +import com.owncloud.android.ui.dialog.extensions.toDialogSelectionIndex +import com.owncloud.android.ui.dialog.parcel.SyncedFolderParcelable +import com.owncloud.android.utils.FileStorageUtils +import com.owncloud.android.utils.FileUtil +import com.owncloud.android.utils.theme.ViewThemeUtils +import java.io.File + +class AutoUploadForm( + private val binding: DialogAutoUploadPreferenceBinding, + private val syncedFolder: SyncedFolderParcelable, + private val clock: Clock, + private val lifecycle: Lifecycle +) { + + private val context = binding.root.context + + val uploadBehaviourEntries: Array = context.resources.getTextArray(R.array.pref_behaviour_entries) + val nameCollisionPolicyEntries: Array = + context.resources.getTextArray(R.array.pref_name_collision_policy_entries) + private val uploadBehaviourEntryValues = context.resources.getTextArray(R.array.pref_behaviour_entryValues) + + private val isMediaFolder: Boolean + get() = syncedFolder.type != MediaFolderType.CUSTOM + + private val isNewCustomFolder: Boolean + get() = !isMediaFolder && syncedFolder.id == SyncedFolder.UNPERSISTED_ID + + val canDelete: Boolean + get() = !isMediaFolder && !isNewCustomFolder + + val uploadBehaviourIndex: Int + get() = syncedFolder.uploadActionInteger + + val nameCollisionPolicyIndex: Int + get() = syncedFolder.nameCollisionPolicy.toDialogSelectionIndex() + + private val settingContainers: List + get() = with(binding) { + listOf( + settingInstantUploadOnWifiContainer, + settingInstantUploadOnChargingContainer, + settingInstantUploadExistingContainer, + settingInstantUploadPathUseSubfoldersContainer, + settingInstantUploadExcludeHiddenContainer, + remoteFolderContainer, + localFolderContainer, + settingInstantNameCollisionPolicyContainer + ) + } + + private val checkboxes: List + get() = with(binding) { + listOf( + settingInstantUploadOnWifiCheckbox, + settingInstantUploadOnChargingCheckbox, + settingInstantUploadExistingCheckbox, + settingInstantUploadPathUseSubfoldersCheckbox, + settingInstantUploadExcludeHiddenCheckbox + ) + } + + fun setup(viewThemeUtils: ViewThemeUtils) { + setupLayout() + applyUserColor(viewThemeUtils) + render() + setupValueListeners() + } + + fun setRemotePath(path: String) { + syncedFolder.remotePath = path + binding.remoteFolderSummary.text = path + updateSaveButtonState() + } + + fun setLocalPath(path: String) { + syncedFolder.localPath = path + renderLocalFolder() + updateSaveButtonState() + updateBehaviourAvailability() + } + + fun selectUploadBehaviour(index: Int) { + syncedFolder.setUploadAction(uploadBehaviourEntryValues[index].toString()) + binding.settingInstantBehaviourSummary.text = uploadBehaviourEntries[index] + } + + fun selectNameCollisionPolicy(index: Int) { + syncedFolder.nameCollisionPolicy = nameCollisionPolicyForDialogSelectionIndex(index) + binding.settingInstantNameCollisionPolicySummary.text = nameCollisionPolicyEntries[index] + } + + private fun setupLayout() { + binding.localFolderContainer.isVisible = isNewCustomFolder + binding.settingInstantUploadExcludeHiddenContainer.isVisible = !isMediaFolder + binding.syncEnabled.isVisible = !isNewCustomFolder + + if (isNewCustomFolder) { + binding.syncedFoldersSettingsTitle.setText(R.string.autoupload_create_new_custom_folder) + } + } + + private fun applyUserColor(viewThemeUtils: ViewThemeUtils) { + viewThemeUtils.androidx.colorSwitchCompat(binding.syncEnabled) + viewThemeUtils.platform.themeCheckbox( + binding.settingInstantUploadOnWifiCheckbox, + binding.settingInstantUploadOnChargingCheckbox, + binding.settingInstantUploadExistingCheckbox, + binding.settingInstantUploadPathUseSubfoldersCheckbox, + binding.settingInstantUploadExcludeHiddenCheckbox + ) + viewThemeUtils.material.colorMaterialButtonPrimaryTonal(binding.btnPositive) + viewThemeUtils.material.colorMaterialButtonPrimaryBorderless(binding.btnNegative) + viewThemeUtils.material.colorMaterialButtonPrimaryBorderless(binding.btnNeutral) + } + + private fun setupValueListeners() = with(binding) { + bindCheckbox(settingInstantUploadOnWifiContainer, settingInstantUploadOnWifiCheckbox) { + syncedFolder.isWifiOnly = it + } + bindCheckbox(settingInstantUploadOnChargingContainer, settingInstantUploadOnChargingCheckbox) { + syncedFolder.isChargingOnly = it + } + bindCheckbox(settingInstantUploadExistingContainer, settingInstantUploadExistingCheckbox) { + syncedFolder.isExisting = it + } + bindCheckbox(settingInstantUploadPathUseSubfoldersContainer, settingInstantUploadPathUseSubfoldersCheckbox) { + syncedFolder.isSubfolderByDate = it + settingInstantUploadSubfolderRuleContainer.isVisible = it + } + bindCheckbox(settingInstantUploadExcludeHiddenContainer, settingInstantUploadExcludeHiddenCheckbox) { + syncedFolder.isExcludeHidden = it + } + settingInstantUploadSubfolderRuleSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { + syncedFolder.subFolderRule = SubFolderRule.entries[position] + } + + override fun onNothingSelected(parent: AdapterView<*>?) { + syncedFolder.subFolderRule = SubFolderRule.YEAR_MONTH + } + } + syncEnabled.setOnClickListener { + syncedFolder.setEnabled(!syncedFolder.isEnabled, clock.currentTime) + renderEnabledState() + } + } + + private fun bindCheckbox(container: View, checkbox: CompoundButton, onChanged: (Boolean) -> Unit) { + container.setOnClickListener { + checkbox.toggle() + onChanged(checkbox.isChecked) + } + } + + private fun render() { + renderLocalFolder() + + with(binding) { + remoteFolderSummary.text = syncedFolder.remotePath ?: context.getString(R.string.choose_remote_folder) + settingInstantUploadOnWifiCheckbox.isChecked = syncedFolder.isWifiOnly + settingInstantUploadOnChargingCheckbox.isChecked = syncedFolder.isChargingOnly + settingInstantUploadExistingCheckbox.isChecked = syncedFolder.isExisting + settingInstantUploadPathUseSubfoldersCheckbox.isChecked = syncedFolder.isSubfolderByDate + settingInstantUploadExcludeHiddenCheckbox.isChecked = syncedFolder.isExcludeHidden + settingInstantUploadSubfolderRuleSpinner.setSelection(syncedFolder.subFolderRule.ordinal) + settingInstantUploadSubfolderRuleContainer.isVisible = syncedFolder.isSubfolderByDate + settingInstantBehaviourSummary.text = uploadBehaviourEntries[uploadBehaviourIndex] + settingInstantNameCollisionPolicySummary.text = nameCollisionPolicyEntries[nameCollisionPolicyIndex] + } + + renderEnabledState() + updateSaveButtonState() + } + + private fun renderLocalFolder() { + val localPath = syncedFolder.localPath + if (localPath.isNullOrEmpty()) { + binding.localFolderSummary.setText(R.string.choose_local_folder) + return + } + + binding.syncedFoldersSettingsLocalFolderPath.text = SpanFormatter.styleLast( + context.getString(R.string.synced_folders_preferences_folder_path, localPath), + File(localPath).name, + StyleSpan(Typeface.BOLD) + ) + binding.localFolderSummary.text = + FileStorageUtils.pathToUserFriendlyDisplay(localPath, context, context.resources) + } + + private fun renderEnabledState() { + val enabled = syncedFolder.isEnabled + val alpha = if (enabled) ALPHA_ENABLED else ALPHA_DISABLED + + binding.syncEnabled.isChecked = enabled + settingContainers.forEach { + it.isEnabled = enabled + it.alpha = alpha + } + checkboxes.forEach { it.isEnabled = enabled } + + updateBehaviourAvailability() + } + + private fun updateBehaviourAvailability() { + if (!syncedFolder.isEnabled) { + setBehaviourEnabled(false) + return + } + + val localFolder = syncedFolder.localPath?.let(::File) + FileUtil.isFolderWritable(localFolder, lifecycle) { writable -> + setBehaviourEnabled(writable) + + if (writable) { + binding.settingInstantBehaviourSummary.text = uploadBehaviourEntries[uploadBehaviourIndex] + return@isFolderWritable + } + + syncedFolder.setUploadAction(uploadBehaviourEntryValues[KEPT_IN_FOLDER_BEHAVIOUR_INDEX].toString()) + binding.settingInstantBehaviourSummary.setText(R.string.auto_upload_file_behaviour_kept_in_folder) + } + } + + private fun setBehaviourEnabled(enabled: Boolean) { + binding.settingInstantBehaviourContainer.isEnabled = enabled + binding.settingInstantBehaviourContainer.alpha = if (enabled) ALPHA_ENABLED else ALPHA_DISABLED + } + + private fun updateSaveButtonState() { + binding.btnPositive.isEnabled = syncedFolder.localPath != null && syncedFolder.remotePath != null + } + + companion object { + private const val KEPT_IN_FOLDER_BEHAVIOUR_INDEX = 0 + private const val ALPHA_ENABLED = 1.0f + private const val ALPHA_DISABLED = 0.7f + } +} diff --git a/app/src/main/java/com/owncloud/android/ui/dialog/AutoUploadOption.kt b/app/src/main/java/com/owncloud/android/ui/dialog/AutoUploadOption.kt new file mode 100644 index 000000000000..0854a04acd33 --- /dev/null +++ b/app/src/main/java/com/owncloud/android/ui/dialog/AutoUploadOption.kt @@ -0,0 +1,12 @@ +/* + * Nextcloud - Android Client + * + * SPDX-FileCopyrightText: 2026 Alper Ozturk + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package com.owncloud.android.ui.dialog + +enum class AutoUploadOption { + UPLOAD_BEHAVIOUR, + NAME_COLLISION_POLICY +} diff --git a/app/src/main/java/com/owncloud/android/ui/dialog/AutoUploadPreferenceDialogFragment.kt b/app/src/main/java/com/owncloud/android/ui/dialog/AutoUploadPreferenceDialogFragment.kt new file mode 100644 index 000000000000..06361ffb12e8 --- /dev/null +++ b/app/src/main/java/com/owncloud/android/ui/dialog/AutoUploadPreferenceDialogFragment.kt @@ -0,0 +1,188 @@ +/* + * Nextcloud - Android Client + * + * SPDX-FileCopyrightText: 2016 Andy Scherzinger + * SPDX-FileCopyrightText: 2016 Nextcloud + * SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only + */ +package com.owncloud.android.ui.dialog + +import android.app.Dialog +import android.os.Bundle +import androidx.annotation.StringRes +import androidx.appcompat.app.AlertDialog +import androidx.core.os.bundleOf +import androidx.core.view.isVisible +import androidx.fragment.app.DialogFragment +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import com.nextcloud.client.core.Clock +import com.nextcloud.client.di.Injectable +import com.nextcloud.utils.extensions.getParcelableArgument +import com.owncloud.android.R +import com.owncloud.android.databinding.DialogAutoUploadPreferenceBinding +import com.owncloud.android.datamodel.SyncedFolderDisplayItem +import com.owncloud.android.ui.dialog.parcel.SyncedFolderParcelable +import com.owncloud.android.utils.theme.ViewThemeUtils +import javax.inject.Inject + +class AutoUploadPreferenceDialogFragment : + DialogFragment(), + Injectable { + + @Inject + lateinit var viewThemeUtils: ViewThemeUtils + + @Inject + lateinit var clock: Clock + + private lateinit var syncedFolder: SyncedFolderParcelable + private lateinit var form: AutoUploadForm + + private var openOptionDialog: AutoUploadOption? = null + private var optionDialog: AlertDialog? = null + + private val listener: AutoUploadFolderConfigurationListener + get() = parentFragment as? AutoUploadFolderConfigurationListener + ?: requireActivity() as AutoUploadFolderConfigurationListener + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val state = savedInstanceState ?: requireArguments() + syncedFolder = requireNotNull( + state.getParcelableArgument(SYNCED_FOLDER_PARCELABLE, SyncedFolderParcelable::class.java) + ) + openOptionDialog = savedInstanceState?.getString(OPEN_OPTION_DIALOG)?.let(AutoUploadOption::valueOf) + } + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + val binding = DialogAutoUploadPreferenceBinding.inflate(requireActivity().layoutInflater) + form = AutoUploadForm(binding, syncedFolder, clock, lifecycle) + form.setup(viewThemeUtils) + setupButtons(binding) + setupNavigationListeners(binding) + + val builder = MaterialAlertDialogBuilder(requireContext()).setView(binding.root) + viewThemeUtils.dialog.colorMaterialAlertDialogBackground(requireContext(), builder) + + return builder.create() + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putParcelable(SYNCED_FOLDER_PARCELABLE, syncedFolder) + outState.putString(OPEN_OPTION_DIALOG, openOptionDialog?.name) + } + + override fun onStart() { + super.onStart() + val pendingOptionDialog = openOptionDialog ?: return + if (optionDialog?.isShowing == true) { + return + } + + showOptionDialog(pendingOptionDialog) + } + + override fun onDestroyView() { + optionDialog?.dismiss() + super.onDestroyView() + } + + fun setRemoteFolderSummary(path: String) { + form.setRemotePath(path) + } + + fun setLocalFolderSummary(path: String) { + form.setLocalPath(path) + } + + private fun setupButtons(binding: DialogAutoUploadPreferenceBinding) { + binding.btnPositive.setOnClickListener { + dismiss() + listener.onSaveAutoUploadFolderConfiguration(syncedFolder) + } + + val cancelButton = if (form.canDelete) binding.btnNeutral else binding.btnNegative + cancelButton.setText(R.string.common_cancel) + cancelButton.setOnClickListener { + dismiss() + listener.onCancelAutoUploadFolderConfiguration() + } + + if (!form.canDelete) { + binding.btnNeutral.isVisible = false + return + } + + binding.btnNegative.setText(R.string.common_delete) + binding.btnNegative.setOnClickListener { + dismiss() + listener.onDeleteAutoUploadFolderConfiguration(syncedFolder) + } + } + + private fun setupNavigationListeners(binding: DialogAutoUploadPreferenceBinding) { + binding.remoteFolderContainer.setOnClickListener { listener.onRemoteFolderPickerRequested() } + binding.localFolderContainer.setOnClickListener { listener.onLocalFolderPickerRequested() } + binding.settingInstantBehaviourContainer.setOnClickListener { + showOptionDialog(AutoUploadOption.UPLOAD_BEHAVIOUR) + } + binding.settingInstantNameCollisionPolicyContainer.setOnClickListener { + showOptionDialog(AutoUploadOption.NAME_COLLISION_POLICY) + } + } + + private fun showOptionDialog(type: AutoUploadOption) { + when (type) { + AutoUploadOption.UPLOAD_BEHAVIOUR -> showOptionDialog( + type, + R.string.prefs_instant_behaviour_dialogTitle, + form.uploadBehaviourEntries, + form.uploadBehaviourIndex, + form::selectUploadBehaviour + ) + + AutoUploadOption.NAME_COLLISION_POLICY -> showOptionDialog( + type, + R.string.pref_instant_name_collision_policy_dialogTitle, + form.nameCollisionPolicyEntries, + form.nameCollisionPolicyIndex, + form::selectNameCollisionPolicy + ) + } + } + + private fun showOptionDialog( + type: AutoUploadOption, + @StringRes title: Int, + entries: Array, + checkedIndex: Int, + onSelected: (Int) -> Unit + ) { + openOptionDialog = type + val builder = MaterialAlertDialogBuilder(requireActivity()) + .setTitle(title) + .setSingleChoiceItems(entries, checkedIndex) { dialog, which -> + onSelected(which) + openOptionDialog = null + dialog.dismiss() + } + .setOnCancelListener { openOptionDialog = null } + viewThemeUtils.dialog.colorMaterialAlertDialogBackground(requireActivity(), builder) + + optionDialog = builder.create().apply { show() } + } + + companion object { + const val REQUEST_CODE__SELECT_LOCAL_FOLDER = 1 + private const val SYNCED_FOLDER_PARCELABLE = "SyncedFolderParcelable" + private const val OPEN_OPTION_DIALOG = "OPEN_OPTION_DIALOG" + + @JvmStatic + fun newInstance(syncedFolder: SyncedFolderDisplayItem): AutoUploadPreferenceDialogFragment = + AutoUploadPreferenceDialogFragment().apply { + arguments = bundleOf(SYNCED_FOLDER_PARCELABLE to SyncedFolderParcelable(syncedFolder)) + setStyle(STYLE_NORMAL, R.style.Theme_ownCloud_Dialog) + } + } +} diff --git a/app/src/main/java/com/owncloud/android/ui/dialog/SyncedFolderPreferencesDialogFragment.kt b/app/src/main/java/com/owncloud/android/ui/dialog/SyncedFolderPreferencesDialogFragment.kt deleted file mode 100644 index e88b2622fb62..000000000000 --- a/app/src/main/java/com/owncloud/android/ui/dialog/SyncedFolderPreferencesDialogFragment.kt +++ /dev/null @@ -1,591 +0,0 @@ -/* - * Nextcloud - Android Client - * - * SPDX-FileCopyrightText: 2016 Andy Scherzinger - * SPDX-FileCopyrightText: 2016 Nextcloud - * SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only - */ -package com.owncloud.android.ui.dialog - -import android.app.Dialog -import android.content.Context -import android.content.DialogInterface -import android.graphics.Typeface -import android.os.Bundle -import android.text.TextUtils -import android.text.style.StyleSpan -import android.view.View -import android.widget.AdapterView -import androidx.appcompat.app.AlertDialog -import androidx.fragment.app.DialogFragment -import androidx.lifecycle.lifecycleScope -import com.google.android.material.dialog.MaterialAlertDialogBuilder -import com.nextcloud.client.di.Injectable -import com.nextcloud.client.preferences.SubFolderRule -import com.nextcloud.utils.extensions.getParcelableArgument -import com.nextcloud.utils.text.SpanFormatter -import com.owncloud.android.R -import com.owncloud.android.databinding.SyncedFoldersSettingsLayoutBinding -import com.owncloud.android.datamodel.MediaFolderType -import com.owncloud.android.datamodel.SyncedFolder -import com.owncloud.android.datamodel.SyncedFolderDisplayItem -import com.owncloud.android.files.services.NameCollisionPolicy -import com.owncloud.android.lib.common.utils.Log_OC -import com.owncloud.android.ui.dialog.parcel.SyncedFolderParcelable -import com.owncloud.android.utils.FileStorageUtils -import com.owncloud.android.utils.FileUtil -import com.owncloud.android.utils.theme.ViewThemeUtils -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext -import java.io.File -import javax.inject.Inject - -/** - * Dialog to show the preferences/configuration of a synced folder allowing the user to change the different - * parameters. - */ -class SyncedFolderPreferencesDialogFragment : - DialogFragment(), - Injectable { - - @JvmField - @Inject - var viewThemeUtils: ViewThemeUtils? = null - - private lateinit var uploadBehaviorItemStrings: Array - private lateinit var nameCollisionPolicyItemStrings: Array - - private var syncedFolder: SyncedFolderParcelable? = null - private var behaviourDialogShown = false - private var nameCollisionPolicyDialogShown = false - private var behaviourDialog: AlertDialog? = null - private var binding: SyncedFoldersSettingsLayoutBinding? = null - private var isNeutralButtonActive = true - - private val listener: OnSyncedFolderPreferenceListener? - get() = parentFragment as? OnSyncedFolderPreferenceListener - ?: activity as? OnSyncedFolderPreferenceListener - - override fun onAttach(context: Context) { - super.onAttach(context) - requireNotNull(listener) { - "The parent fragment or host activity must implement " + - OnSyncedFolderPreferenceListener::class.java.canonicalName - } - } - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - // keep the state of the fragment on configuration changes - retainInstance = true - binding = null - - val arguments = arguments - if (arguments != null) { - syncedFolder = arguments.getParcelableArgument(SYNCED_FOLDER_PARCELABLE, SyncedFolderParcelable::class.java) - } - - uploadBehaviorItemStrings = resources.getTextArray(R.array.pref_behaviour_entries) - nameCollisionPolicyItemStrings = resources.getTextArray(R.array.pref_name_collision_policy_entries) - } - - override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { - Log_OC.d(TAG, "onCreateView, savedInstanceState is $savedInstanceState") - binding = SyncedFoldersSettingsLayoutBinding.inflate(requireActivity().layoutInflater, null, false) - - setupDialogElements(binding!!) - setupListeners(binding!!) - - val builder = MaterialAlertDialogBuilder(requireContext()) - builder.setView(binding!!.getRoot()) - - viewThemeUtils?.dialog?.colorMaterialAlertDialogBackground(requireContext(), builder) - - return builder.create() - } - - /** - * find all relevant UI elements and set their values. - * - * @param binding the parent binding - */ - private fun setupDialogElements(binding: SyncedFoldersSettingsLayoutBinding) { - setupLayout(binding) - applyUserColor(binding) - setButtonOrder(binding) - setValuesViaSyncedFolder(binding) - } - - private fun setupLayout(binding: SyncedFoldersSettingsLayoutBinding) { - if (syncedFolder!!.type.id > MediaFolderType.CUSTOM.id) { - // hide local folder chooser and delete for non-custom folders - binding.localFolderContainer.visibility = View.GONE - isNeutralButtonActive = false - binding.settingInstantUploadExcludeHiddenContainer.visibility = View.GONE - } else if (syncedFolder!!.id <= SyncedFolder.UNPERSISTED_ID) { - isNeutralButtonActive = false - - // Hide delete/enabled for unpersisted custom folders - binding.syncEnabled.visibility = View.GONE - - // Show exclude hidden checkbox when {@link MediaFolderType#CUSTOM} - binding.settingInstantUploadExcludeHiddenContainer.visibility = View.VISIBLE - - // auto set custom folder to enabled - syncedFolder?.isEnabled = true - - // switch text to create headline - binding.syncedFoldersSettingsTitle.setText(R.string.autoupload_create_new_custom_folder) - - // disable save button - binding.btnPositive.isEnabled = false - } else { - binding.localFolderContainer.visibility = View.GONE - if (MediaFolderType.CUSTOM.id == syncedFolder!!.type.id) { - // Show exclude hidden checkbox when {@link MediaFolderType#CUSTOM} - binding.settingInstantUploadExcludeHiddenContainer.visibility = View.VISIBLE - } - } - } - - private fun applyUserColor(binding: SyncedFoldersSettingsLayoutBinding) { - viewThemeUtils?.androidx?.colorSwitchCompat(binding.syncEnabled) - - viewThemeUtils?.platform?.themeCheckbox( - binding.settingInstantUploadOnWifiCheckbox, - binding.settingInstantUploadOnChargingCheckbox, - binding.settingInstantUploadExistingCheckbox, - binding.settingInstantUploadPathUseSubfoldersCheckbox, - binding.settingInstantUploadExcludeHiddenCheckbox - ) - - viewThemeUtils?.material?.colorMaterialButtonPrimaryTonal(binding.btnPositive) - viewThemeUtils?.material?.colorMaterialButtonPrimaryBorderless(binding.btnNegative) - viewThemeUtils?.material?.colorMaterialButtonPrimaryBorderless(binding.btnNeutral) - } - - private fun setButtonOrder(binding: SyncedFoldersSettingsLayoutBinding) { - // btnNeutral btnNegative btnPositive - if (isNeutralButtonActive) { - // Cancel Delete Save - binding.btnNeutral.setText(R.string.common_cancel) - binding.btnNegative.setText(R.string.common_delete) - } else { - // Cancel Save - binding.btnNeutral.visibility = View.GONE - binding.btnNegative.setText(R.string.common_cancel) - } - } - - private fun setValuesViaSyncedFolder(binding: SyncedFoldersSettingsLayoutBinding) { - syncedFolder?.let { - setEnabled(it.isEnabled) - - if (!TextUtils.isEmpty(it.localPath)) { - binding.syncedFoldersSettingsLocalFolderPath.text = SpanFormatter.styleLast( - String.format( - getString(R.string.synced_folders_preferences_folder_path), - it.localPath - ), - it.folderName, - StyleSpan(Typeface.BOLD) - ) - binding.localFolderSummary.text = FileStorageUtils.pathToUserFriendlyDisplay( - it.localPath, - activity, - resources - ) - } else { - binding.localFolderSummary.setText(R.string.choose_local_folder) - } - - if (!TextUtils.isEmpty(it.localPath)) { - binding.remoteFolderSummary.text = it.remotePath - } else { - binding.remoteFolderSummary.setText(R.string.choose_remote_folder) - } - - binding.settingInstantUploadOnWifiCheckbox.isChecked = it.isWifiOnly - binding.settingInstantUploadOnChargingCheckbox.isChecked = it.isChargingOnly - binding.settingInstantUploadExistingCheckbox.isChecked = it.isExisting - binding.settingInstantUploadPathUseSubfoldersCheckbox.isChecked = it.isSubfolderByDate - binding.settingInstantUploadExcludeHiddenCheckbox.isChecked = it.isExcludeHidden - - binding.settingInstantUploadSubfolderRuleSpinner.setSelection(it.subFolderRule.ordinal) - - binding.settingInstantUploadSubfolderRuleContainer.visibility = - if (binding.settingInstantUploadPathUseSubfoldersCheckbox.isChecked) View.VISIBLE else View.GONE - - binding.settingInstantBehaviourSummary.text = uploadBehaviorItemStrings[it.uploadActionInteger] - val nameCollisionPolicyIndex = getSelectionIndexForNameCollisionPolicy( - it.nameCollisionPolicy - ) - binding.settingInstantNameCollisionPolicySummary.text = - nameCollisionPolicyItemStrings[nameCollisionPolicyIndex] - } - } - - /** - * set correct icon/flag. - * - * @param enabled if enabled or disabled - */ - private fun setEnabled(enabled: Boolean) { - syncedFolder?.isEnabled = enabled - binding?.syncEnabled?.isChecked = enabled - setupViews(binding, enabled) - } - - fun setRemoteFolderSummary(path: String?) { - syncedFolder?.remotePath = path - binding?.remoteFolderSummary?.text = path - checkAndUpdateSaveButtonState() - } - - fun setLocalFolderSummary(path: String?) { - syncedFolder?.localPath = path - binding?.localFolderSummary?.text = FileStorageUtils.pathToUserFriendlyDisplay(path, activity, resources) - binding?.syncedFoldersSettingsLocalFolderPath?.text = SpanFormatter.styleLast( - String.format( - getString(R.string.synced_folders_preferences_folder_path), - syncedFolder!!.localPath - ), - File(syncedFolder!!.localPath).name, - StyleSpan(Typeface.BOLD) - ) - checkAndUpdateSaveButtonState() - } - - private fun checkAndUpdateSaveButtonState() { - binding?.btnPositive?.isEnabled = syncedFolder!!.localPath != null && syncedFolder!!.remotePath != null - checkWritableFolder() - } - - private fun checkWritableFolder() { - if (!syncedFolder!!.isEnabled) { - binding?.settingInstantBehaviourContainer?.isEnabled = false - binding?.settingInstantBehaviourContainer?.alpha = ALPHA_DISABLED - return - } - - val folderFile = syncedFolder?.localPath?.let { File(it) } - lifecycleScope.launch { - val writable = FileUtil.isFolderWritable(folderFile) - withContext(Dispatchers.Main) { - binding?.settingInstantBehaviourContainer?.run { - if (writable) { - isEnabled = true - alpha = ALPHA_ENABLED - binding?.settingInstantBehaviourSummary?.text = - uploadBehaviorItemStrings[syncedFolder!!.uploadActionInteger] - } else { - isEnabled = false - alpha = ALPHA_DISABLED - syncedFolder?.setUploadAction( - resources.getTextArray(R.array.pref_behaviour_entryValues)[0].toString() - ) - binding?.settingInstantBehaviourSummary?.setText( - R.string.auto_upload_file_behaviour_kept_in_folder - ) - } - } - } - } - } - - private fun setupViews(optionalBinding: SyncedFoldersSettingsLayoutBinding?, enable: Boolean) { - val alpha: Float = if (enable) { - ALPHA_ENABLED - } else { - ALPHA_DISABLED - } - - optionalBinding?.let { binding -> - binding.settingInstantUploadOnWifiContainer.isEnabled = enable - binding.settingInstantUploadOnWifiContainer.alpha = alpha - binding.settingInstantUploadOnChargingContainer.isEnabled = enable - binding.settingInstantUploadOnChargingContainer.alpha = alpha - binding.settingInstantUploadExistingContainer.isEnabled = enable - binding.settingInstantUploadExistingContainer.alpha = alpha - binding.settingInstantUploadPathUseSubfoldersContainer.isEnabled = enable - binding.settingInstantUploadPathUseSubfoldersContainer.alpha = alpha - binding.settingInstantUploadExcludeHiddenContainer.isEnabled = enable - binding.settingInstantUploadExcludeHiddenContainer.alpha = alpha - binding.remoteFolderContainer.isEnabled = enable - binding.remoteFolderContainer.alpha = alpha - binding.localFolderContainer.isEnabled = enable - binding.localFolderContainer.alpha = alpha - binding.settingInstantNameCollisionPolicyContainer.isEnabled = enable - binding.settingInstantNameCollisionPolicyContainer.alpha = alpha - binding.settingInstantUploadOnWifiCheckbox.isEnabled = enable - binding.settingInstantUploadOnChargingCheckbox.isEnabled = enable - binding.settingInstantUploadExistingCheckbox.isEnabled = enable - binding.settingInstantUploadPathUseSubfoldersCheckbox.isEnabled = enable - binding.settingInstantUploadExcludeHiddenCheckbox.isEnabled = enable - } - - checkWritableFolder() - } - - /** - * setup all listeners. - * - * @param binding the parent binding - */ - private fun setupListeners(binding: SyncedFoldersSettingsLayoutBinding) { - binding.btnPositive.setOnClickListener(OnSyncedFolderSaveClickListener()) - if (isNeutralButtonActive) { - binding.btnNeutral.setOnClickListener(OnSyncedFolderCancelClickListener()) - binding.btnNegative.setOnClickListener(OnSyncedFolderDeleteClickListener()) - } else { - binding.btnNegative.setOnClickListener(OnSyncedFolderCancelClickListener()) - } - - syncedFolder?.let { syncedFolder -> - binding.settingInstantUploadOnWifiContainer.setOnClickListener { - syncedFolder.isWifiOnly = !syncedFolder.isWifiOnly - binding.settingInstantUploadOnWifiCheckbox.toggle() - } - binding.settingInstantUploadOnChargingContainer.setOnClickListener { - syncedFolder.isChargingOnly = !syncedFolder.isChargingOnly - binding.settingInstantUploadOnChargingCheckbox.toggle() - } - binding.settingInstantUploadExistingContainer.setOnClickListener { - syncedFolder.isExisting = !syncedFolder.isExisting - binding.settingInstantUploadExistingCheckbox.toggle() - } - binding.settingInstantUploadPathUseSubfoldersContainer.setOnClickListener { - syncedFolder.isSubfolderByDate = !syncedFolder.isSubfolderByDate - binding.settingInstantUploadPathUseSubfoldersCheckbox.toggle() - - // Only allow setting subfolder rule if subfolder is allowed - if (binding.settingInstantUploadPathUseSubfoldersCheckbox.isChecked) { - binding.settingInstantUploadSubfolderRuleContainer.visibility = View.VISIBLE - } else { - binding.settingInstantUploadSubfolderRuleContainer.visibility = View.GONE - } - } - binding.settingInstantUploadExcludeHiddenContainer.setOnClickListener { - syncedFolder.isExcludeHidden = !syncedFolder.isExcludeHidden - binding.settingInstantUploadExcludeHiddenCheckbox.toggle() - } - binding.settingInstantUploadSubfolderRuleSpinner.onItemSelectedListener = - object : AdapterView.OnItemSelectedListener { - override fun onItemSelected(adapterView: AdapterView<*>?, view: View, i: Int, l: Long) { - syncedFolder.subFolderRule = SubFolderRule.values()[i] - } - - override fun onNothingSelected(adapterView: AdapterView<*>?) { - syncedFolder.subFolderRule = SubFolderRule.YEAR_MONTH - } - } - - binding.syncEnabled.setOnClickListener { setEnabled(!syncedFolder.isEnabled) } - } - - binding.remoteFolderContainer.setOnClickListener { listener?.onRemoteFolderPickerRequested() } - binding.localFolderContainer.setOnClickListener { listener?.onLocalFolderPickerRequested() } - - binding.settingInstantBehaviourContainer.setOnClickListener { showBehaviourDialog() } - binding.settingInstantNameCollisionPolicyContainer.setOnClickListener { showNameCollisionPolicyDialog() } - } - - private fun showBehaviourDialog() { - val builder = MaterialAlertDialogBuilder(requireActivity()) - - syncedFolder?.let { - val behaviourEntries = resources.getTextArray(R.array.pref_behaviour_entries) - val behaviourEntryValues = resources.getTextArray(R.array.pref_behaviour_entryValues) - builder.setTitle(R.string.prefs_instant_behaviour_dialogTitle) - .setSingleChoiceItems(behaviourEntries, it.uploadActionInteger) { dialog: DialogInterface, which: Int -> - it.setUploadAction(behaviourEntryValues[which].toString()) - binding?.settingInstantBehaviourSummary?.text = uploadBehaviorItemStrings[which] - behaviourDialogShown = false - dialog.dismiss() - } - .setOnCancelListener { behaviourDialogShown = false } - } - - behaviourDialogShown = true - viewThemeUtils?.dialog?.colorMaterialAlertDialogBackground(requireActivity(), builder) - - behaviourDialog = builder.create() - behaviourDialog?.show() - } - - private fun showNameCollisionPolicyDialog() { - syncedFolder?.let { - val builder = MaterialAlertDialogBuilder(requireActivity()) - builder.setTitle(R.string.pref_instant_name_collision_policy_dialogTitle) - .setSingleChoiceItems( - resources.getTextArray(R.array.pref_name_collision_policy_entries), - getSelectionIndexForNameCollisionPolicy(it.nameCollisionPolicy), - OnNameCollisionDialogClickListener() - ) - .setOnCancelListener { nameCollisionPolicyDialogShown = false } - - nameCollisionPolicyDialogShown = true - - viewThemeUtils?.dialog?.colorMaterialAlertDialogBackground(requireActivity(), builder) - behaviourDialog = builder.create() - behaviourDialog?.show() - } - } - - override fun onDestroyView() { - Log_OC.d(TAG, "destroy SyncedFolderPreferencesDialogFragment view") - if (dialog != null && retainInstance) { - dialog?.setDismissMessage(null) - } - if (behaviourDialog != null && behaviourDialog!!.isShowing) { - behaviourDialog?.dismiss() - } - - super.onDestroyView() - } - - override fun onSaveInstanceState(outState: Bundle) { - outState.putBoolean(BEHAVIOUR_DIALOG_STATE, behaviourDialogShown) - outState.putBoolean(NAME_COLLISION_POLICY_DIALOG_STATE, nameCollisionPolicyDialogShown) - } - - override fun onViewStateRestored(savedInstanceState: Bundle?) { - behaviourDialogShown = savedInstanceState != null && - savedInstanceState.getBoolean(BEHAVIOUR_DIALOG_STATE, false) - nameCollisionPolicyDialogShown = savedInstanceState != null && - savedInstanceState.getBoolean(NAME_COLLISION_POLICY_DIALOG_STATE, false) - if (behaviourDialogShown) { - showBehaviourDialog() - } - if (nameCollisionPolicyDialogShown) { - showNameCollisionPolicyDialog() - } - - super.onViewStateRestored(savedInstanceState) - } - - interface OnSyncedFolderPreferenceListener { - fun onSaveSyncedFolderPreference(syncedFolder: SyncedFolderParcelable?) - fun onCancelSyncedFolderPreference() - fun onDeleteSyncedFolderPreference(syncedFolder: SyncedFolderParcelable?) - fun onRemoteFolderPickerRequested() - fun onLocalFolderPickerRequested() - } - - private inner class OnSyncedFolderSaveClickListener : View.OnClickListener { - override fun onClick(v: View) { - dismiss() - listener?.onSaveSyncedFolderPreference(syncedFolder) - } - } - - private inner class OnSyncedFolderCancelClickListener : View.OnClickListener { - override fun onClick(v: View) { - dismiss() - listener?.onCancelSyncedFolderPreference() - } - } - - private inner class OnSyncedFolderDeleteClickListener : View.OnClickListener { - override fun onClick(v: View) { - dismiss() - listener?.onDeleteSyncedFolderPreference(syncedFolder) - } - } - - private inner class OnNameCollisionDialogClickListener : DialogInterface.OnClickListener { - override fun onClick(dialog: DialogInterface, which: Int) { - syncedFolder!!.nameCollisionPolicy = - getNameCollisionPolicyForSelectionIndex(which) - binding?.settingInstantNameCollisionPolicySummary?.text = - nameCollisionPolicyItemStrings[which] - nameCollisionPolicyDialogShown = false - dialog.dismiss() - } - } - - companion object { - const val SYNCED_FOLDER_PARCELABLE = "SyncedFolderParcelable" - const val REQUEST_CODE__SELECT_LOCAL_FOLDER = 1 - private val TAG = SyncedFolderPreferencesDialogFragment::class.java.simpleName - private const val BEHAVIOUR_DIALOG_STATE = "BEHAVIOUR_DIALOG_STATE" - private const val NAME_COLLISION_POLICY_DIALOG_STATE = "NAME_COLLISION_POLICY_DIALOG_STATE" - private const val ALPHA_ENABLED = 1.0f - private const val ALPHA_DISABLED = 0.7f - - @JvmStatic - fun newInstance(syncedFolder: SyncedFolderDisplayItem?, section: Int): SyncedFolderPreferencesDialogFragment? { - if (syncedFolder == null) { - return null - } - - val args = Bundle().apply { - putParcelable(SYNCED_FOLDER_PARCELABLE, SyncedFolderParcelable(syncedFolder, section)) - } - - return SyncedFolderPreferencesDialogFragment().apply { - arguments = args - setStyle(STYLE_NORMAL, R.style.Theme_ownCloud_Dialog) - } - } - - /** - * Converts a [NameCollisionPolicy] enum value into the corresponding - * **UI dialog selection index** used in the dialog. - * - * ⚠️ **Important:** - * These dialog indices are **not** the same as the integer values stored - * in the database or defined in [NameCollisionPolicy]. - * This mapping is purely for UI selection purposes. - * - * | Policy | Dialog Index | - * |---------------------|--------------| - * | ASK_USER (default) | 0 | - * | OVERWRITE | 1 | - * | RENAME | 2 | - * | SKIP | 3 | - * - * @param nameCollisionPolicy The collision handling policy. - * @return The index to preselect in the UI dialog for the given policy. - */ - @Suppress("MagicNumber") - private fun getSelectionIndexForNameCollisionPolicy(nameCollisionPolicy: NameCollisionPolicy): Int = - when (nameCollisionPolicy) { - NameCollisionPolicy.OVERWRITE -> 1 - NameCollisionPolicy.RENAME -> 2 - NameCollisionPolicy.SKIP -> 3 - NameCollisionPolicy.ASK_USER -> 0 - } - - /** - * Converts a **UI dialog selection index** from the dialog - * back into a [NameCollisionPolicy] enum value. - * - * ⚠️ **Important:** - * These indices are defined only for the dialog and are **not** the same as - * the values used in the database or internal enum ordinals. - * Always use this function to translate the dialog result safely. - * - * | Dialog Index | Policy | - * |---------------|--------------------| - * | 0 | ASK_USER (default) | - * | 1 | OVERWRITE | - * | 2 | RENAME | - * | 3 | SKIP | - * - * Any unexpected index value will default to [NameCollisionPolicy.ASK_USER]. - * - * @param index The selected index from the dialog. - * @return The corresponding [NameCollisionPolicy] value. - */ - @Suppress("MagicNumber") - private fun getNameCollisionPolicyForSelectionIndex(index: Int): NameCollisionPolicy = when (index) { - 1 -> NameCollisionPolicy.OVERWRITE - 2 -> NameCollisionPolicy.RENAME - 3 -> NameCollisionPolicy.SKIP - 0 -> NameCollisionPolicy.ASK_USER - else -> NameCollisionPolicy.ASK_USER - } - } -} diff --git a/app/src/main/java/com/owncloud/android/ui/dialog/extensions/NameCollisionPolicyExtensions.kt b/app/src/main/java/com/owncloud/android/ui/dialog/extensions/NameCollisionPolicyExtensions.kt new file mode 100644 index 000000000000..8c644bf877b8 --- /dev/null +++ b/app/src/main/java/com/owncloud/android/ui/dialog/extensions/NameCollisionPolicyExtensions.kt @@ -0,0 +1,65 @@ +/* + * Nextcloud - Android Client + * + * SPDX-FileCopyrightText: 2026 Alper Ozturk + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package com.owncloud.android.ui.dialog.extensions + +import com.owncloud.android.files.services.NameCollisionPolicy + +/** + * Converts a [NameCollisionPolicy] enum value into the corresponding + * **UI dialog selection index** used in the dialog. + * + * ⚠️ **Important:** + * These dialog indices are **not** the same as the integer values stored + * in the database or defined in [NameCollisionPolicy]. + * This mapping is purely for UI selection purposes. + * + * | Policy | Dialog Index | + * |---------------------|--------------| + * | ASK_USER (default) | 0 | + * | OVERWRITE | 1 | + * | RENAME | 2 | + * | SKIP | 3 | + * + * @receiver The collision handling policy. + * @return The index to preselect in the UI dialog for the given policy. + */ +@Suppress("MagicNumber") +fun NameCollisionPolicy.toDialogSelectionIndex(): Int = when (this) { + NameCollisionPolicy.OVERWRITE -> 1 + NameCollisionPolicy.RENAME -> 2 + NameCollisionPolicy.SKIP -> 3 + NameCollisionPolicy.ASK_USER -> 0 +} + +/** + * Converts a **UI dialog selection index** from the dialog + * back into a [NameCollisionPolicy] enum value. + * + * ⚠️ **Important:** + * These indices are defined only for the dialog and are **not** the same as + * the values used in the database or internal enum ordinals. + * Always use this function to translate the dialog result safely. + * + * | Dialog Index | Policy | + * |---------------|--------------------| + * | 0 | ASK_USER (default) | + * | 1 | OVERWRITE | + * | 2 | RENAME | + * | 3 | SKIP | + * + * Any unexpected index value will default to [NameCollisionPolicy.ASK_USER]. + * + * @param index The selected index from the dialog. + * @return The corresponding [NameCollisionPolicy] value. + */ +@Suppress("MagicNumber") +fun nameCollisionPolicyForDialogSelectionIndex(index: Int): NameCollisionPolicy = when (index) { + 1 -> NameCollisionPolicy.OVERWRITE + 2 -> NameCollisionPolicy.RENAME + 3 -> NameCollisionPolicy.SKIP + else -> NameCollisionPolicy.ASK_USER +} diff --git a/app/src/main/java/com/owncloud/android/ui/dialog/parcel/SyncedFolderParcelable.java b/app/src/main/java/com/owncloud/android/ui/dialog/parcel/SyncedFolderParcelable.java index 5e64943f31b4..0f52fe7101dd 100644 --- a/app/src/main/java/com/owncloud/android/ui/dialog/parcel/SyncedFolderParcelable.java +++ b/app/src/main/java/com/owncloud/android/ui/dialog/parcel/SyncedFolderParcelable.java @@ -13,6 +13,7 @@ import com.nextcloud.client.jobs.upload.FileUploadWorker; import com.nextcloud.client.preferences.SubFolderRule; import com.owncloud.android.datamodel.MediaFolderType; +import com.owncloud.android.datamodel.SyncedFolder; import com.owncloud.android.datamodel.SyncedFolderDisplayItem; import com.owncloud.android.files.services.NameCollisionPolicy; @@ -27,6 +28,7 @@ public class SyncedFolderParcelable implements Parcelable { private boolean chargingOnly = false; private boolean existing = true; private boolean enabled = false; + private long enabledTimestampMs = SyncedFolder.EMPTY_ENABLED_TIMESTAMP_MS; private boolean subfolderByDate = false; private Integer uploadAction; private NameCollisionPolicy nameCollisionPolicy = NameCollisionPolicy.ASK_USER; @@ -34,11 +36,11 @@ public class SyncedFolderParcelable implements Parcelable { private boolean hidden = false; private long id; private String account; - private int section; private SubFolderRule subFolderRule; private boolean excludeHidden; + private long lastScanTimestampMs = SyncedFolder.NOT_SCANNED_YET; - public SyncedFolderParcelable(SyncedFolderDisplayItem syncedFolderDisplayItem, int section) { + public SyncedFolderParcelable(SyncedFolderDisplayItem syncedFolderDisplayItem) { id = syncedFolderDisplayItem.getId(); folderName = syncedFolderDisplayItem.getFolderName(); localPath = syncedFolderDisplayItem.getLocalPath(); @@ -47,16 +49,17 @@ public SyncedFolderParcelable(SyncedFolderDisplayItem syncedFolderDisplayItem, i chargingOnly = syncedFolderDisplayItem.isChargingOnly(); existing = syncedFolderDisplayItem.alsoUploadExistingFiles(); enabled = syncedFolderDisplayItem.isEnabled(); + enabledTimestampMs = syncedFolderDisplayItem.getEnabledTimestampMs(); subfolderByDate = syncedFolderDisplayItem.isSubfolderByDate(); type = syncedFolderDisplayItem.getType(); account = syncedFolderDisplayItem.getAccount(); uploadAction = syncedFolderDisplayItem.getUploadAction(); nameCollisionPolicy = NameCollisionPolicy.deserialize( syncedFolderDisplayItem.getNameCollisionPolicyInt()); - this.section = section; hidden = syncedFolderDisplayItem.isHidden(); subFolderRule = syncedFolderDisplayItem.getSubfolderRule(); excludeHidden = syncedFolderDisplayItem.isExcludeHidden(); + lastScanTimestampMs = syncedFolderDisplayItem.getLastScanTimestampMs(); } private SyncedFolderParcelable(Parcel read) { @@ -68,19 +71,16 @@ private SyncedFolderParcelable(Parcel read) { chargingOnly = read.readInt() != 0; existing = read.readInt() != 0; enabled = read.readInt() != 0; + enabledTimestampMs = read.readLong(); subfolderByDate = read.readInt() != 0; type = MediaFolderType.getById(read.readInt()); account = read.readString(); uploadAction = read.readInt(); nameCollisionPolicy = NameCollisionPolicy.deserialize(read.readInt()); - section = read.readInt(); hidden = read.readInt() != 0; subFolderRule = SubFolderRule.values()[read.readInt()]; excludeHidden = read.readInt() != 0; - } - - public SyncedFolderParcelable() { - // empty constructor + lastScanTimestampMs = read.readLong(); } @Override @@ -93,15 +93,16 @@ public void writeToParcel(Parcel dest, int flags) { dest.writeInt(chargingOnly ? 1 : 0); dest.writeInt(existing ? 1 : 0); dest.writeInt(enabled ? 1 : 0); + dest.writeLong(enabledTimestampMs); dest.writeInt(subfolderByDate ? 1 : 0); dest.writeInt(type.id); dest.writeString(account); dest.writeInt(uploadAction); dest.writeInt(nameCollisionPolicy.serialize()); - dest.writeInt(section); dest.writeInt(hidden ? 1 : 0); dest.writeInt(subFolderRule.ordinal()); dest.writeInt(excludeHidden ? 1 : 0); + dest.writeLong(lastScanTimestampMs); } public static final Creator CREATOR = @@ -205,10 +206,6 @@ public String getAccount() { return this.account; } - public int getSection() { - return this.section; - } - public SubFolderRule getSubFolderRule() { return this.subFolderRule; } public void setFolderName(String folderName) { @@ -235,8 +232,13 @@ public void setExisting(boolean existing) { this.existing = existing; } - public void setEnabled(boolean enabled) { + public long getEnabledTimestampMs() { + return this.enabledTimestampMs; + } + + public void setEnabled(boolean enabled, long timestampMs) { this.enabled = enabled; + this.enabledTimestampMs = enabled ? timestampMs : SyncedFolder.EMPTY_ENABLED_TIMESTAMP_MS; } public void setSubfolderByDate(boolean subfolderByDate) { @@ -263,9 +265,6 @@ public void setAccount(String account) { this.account = account; } - public void setSection(int section) { - this.section = section; - } public void setSubFolderRule(SubFolderRule subFolderRule) { this.subFolderRule = subFolderRule; } public boolean isExcludeHidden() { @@ -275,4 +274,8 @@ public boolean isExcludeHidden() { public void setExcludeHidden(boolean excludeHidden) { this.excludeHidden = excludeHidden; } + + public long getLastScanTimestampMs() { + return lastScanTimestampMs; + } } diff --git a/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/AutoUploadFragment.kt b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/AutoUploadFragment.kt index a83065469604..ddb0ba79d506 100644 --- a/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/AutoUploadFragment.kt +++ b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/AutoUploadFragment.kt @@ -29,12 +29,12 @@ import com.owncloud.android.R import com.owncloud.android.databinding.FragmentAutoUploadBinding import com.owncloud.android.databinding.StoragePermissionWarningBannerBinding import com.owncloud.android.datamodel.SyncedFolderProvider -import com.owncloud.android.ui.adapter.SyncedFolderAdapter import com.owncloud.android.ui.adapter.storagePermissionBanner.setup import com.owncloud.android.ui.decoration.MediaGridItemDecoration -import com.owncloud.android.ui.dialog.SyncedFolderPreferencesDialogFragment -import com.owncloud.android.ui.dialog.SyncedFolderPreferencesDialogFragment.OnSyncedFolderPreferenceListener +import com.owncloud.android.ui.dialog.AutoUploadFolderConfigurationListener +import com.owncloud.android.ui.dialog.AutoUploadPreferenceDialogFragment import com.owncloud.android.ui.dialog.parcel.SyncedFolderParcelable +import com.owncloud.android.ui.fragment.autoUpload.adapter.AutoUploadFolderAdapter import com.owncloud.android.ui.fragment.autoUpload.data.AutoUploadDisplayItemFactory import com.owncloud.android.ui.fragment.autoUpload.data.AutoUploadItemsLoader import com.owncloud.android.ui.fragment.autoUpload.data.AutoUploadPersistence @@ -55,7 +55,7 @@ import kotlinx.coroutines.withContext class AutoUploadFragment : Fragment(), - OnSyncedFolderPreferenceListener { + AutoUploadFolderConfigurationListener { @Inject lateinit var powerManagementService: PowerManagementService @@ -73,7 +73,7 @@ class AutoUploadFragment : @Inject lateinit var themeUtils: ThemeUtils - lateinit var adapter: SyncedFolderAdapter + lateinit var adapter: AutoUploadFolderAdapter private var binding: FragmentAutoUploadBinding? = null private var uploadWarningCard: UploadWarningCard? = null @@ -85,8 +85,8 @@ class AutoUploadFragment : private val intentHandler = AutoUploadIntentHandler() private val folderPickers = AutoUploadPickers(this) { - childFragmentManager.findFragmentByTag(AutoUploadClickHandler.SYNCED_FOLDER_PREFERENCES_DIALOG_TAG) - as? SyncedFolderPreferencesDialogFragment + childFragmentManager.findFragmentByTag(AutoUploadClickHandler.AUTO_UPLOAD_PREFERENCE_DIALOG_TAG) + as? AutoUploadPreferenceDialogFragment } private val navigatorActivity: NavigatorActivity? @@ -144,14 +144,14 @@ class AutoUploadFragment : } // endregion - // region OnSyncedFolderPreferenceListener - override fun onSaveSyncedFolderPreference(syncedFolder: SyncedFolderParcelable?) { + // region AutoUploadFolderConfigurationListener + override fun onSaveAutoUploadFolderConfiguration(syncedFolder: SyncedFolderParcelable) { clickHandler.onSaveAutoUploadFolderPreference(syncedFolder) } - override fun onCancelSyncedFolderPreference() = Unit + override fun onCancelAutoUploadFolderConfiguration() = Unit - override fun onDeleteSyncedFolderPreference(syncedFolder: SyncedFolderParcelable?) { + override fun onDeleteAutoUploadFolderConfiguration(syncedFolder: SyncedFolderParcelable) { clickHandler.onDeleteAutoUploadFolderPreference(syncedFolder) } @@ -187,7 +187,6 @@ class AutoUploadFragment : itemFactory, persistence, dialogs, - backgroundJobManager, getAdapter = { adapter }, onItemVisibilityChanged = { emptyContent?.checkAndShowEmptyListContent() } ) @@ -203,7 +202,7 @@ class AutoUploadFragment : private fun setupList(activity: NavigatorActivity, binding: FragmentAutoUploadBinding) { val gridWidth = resources.getInteger(R.integer.media_grid_width) - adapter = SyncedFolderAdapter( + adapter = AutoUploadFolderAdapter( lifecycleScope, activity, clock, @@ -274,8 +273,7 @@ class AutoUploadFragment : val items = itemsLoader.load(activity, perFolderMediaItemLimit, currentAccountName, newItemAccountName) withContext(Dispatchers.Main) { - adapter.setSyncFolderItems(items) - adapter.notifyDataSetChanged() + adapter.setItems(items) emptyContent?.showList() openMediaFolderSettingsFromIntent() } @@ -284,7 +282,7 @@ class AutoUploadFragment : private fun openMediaFolderSettingsFromIntent() { val section = intentHandler.findMediaFolderSection(adapter) ?: return - adapter.get(section)?.let { clickHandler.onSyncFolderSettingsClick(section, it) } + adapter.getItem(section)?.let(clickHandler::onSyncFolderSettingsClick) } // endregion } diff --git a/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/adapter/AutoUploadFolderAdapter.kt b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/adapter/AutoUploadFolderAdapter.kt new file mode 100644 index 000000000000..99768250b3e0 --- /dev/null +++ b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/adapter/AutoUploadFolderAdapter.kt @@ -0,0 +1,226 @@ +/* + * Nextcloud - Android Client + * + * SPDX-FileCopyrightText: 2026 Alper Ozturk + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package com.owncloud.android.ui.fragment.autoUpload.adapter + +import android.annotation.SuppressLint +import android.content.Context +import android.view.LayoutInflater +import android.view.ViewGroup +import androidx.annotation.VisibleForTesting +import androidx.core.view.isVisible +import androidx.lifecycle.LifecycleCoroutineScope +import com.afollestad.sectionedrecyclerview.SectionedRecyclerViewAdapter +import com.afollestad.sectionedrecyclerview.SectionedViewHolder +import com.nextcloud.client.core.Clock +import com.nextcloud.client.device.PowerManagementService +import com.nextcloud.client.network.ConnectivityService +import com.nextcloud.utils.thumbnail.job.MediaThumbnailGenerationJob +import com.owncloud.android.R +import com.owncloud.android.databinding.GridSyncItemBinding +import com.owncloud.android.databinding.SyncedFoldersEmptyBinding +import com.owncloud.android.databinding.SyncedFoldersFooterBinding +import com.owncloud.android.databinding.SyncedFoldersItemHeaderBinding +import com.owncloud.android.datamodel.SyncedFolderDisplayItem +import com.owncloud.android.datamodel.ThumbnailsCacheManager +import com.owncloud.android.utils.theme.ViewThemeUtils +import kotlinx.coroutines.launch +import java.io.File +import java.util.Locale + +class AutoUploadFolderAdapter( + private val lifecycleScope: LifecycleCoroutineScope, + private val context: Context, + private val clock: Clock, + gridWidth: Int, + private val clickListener: AutoUploadFolderClickListener, + private val light: Boolean, + private val viewThemeUtils: ViewThemeUtils, + private val powerManagementService: PowerManagementService, + private val connectivityService: ConnectivityService +) : SectionedRecyclerViewAdapter() { + + private val gridTotal = gridWidth * GRID_ROWS + private val mediaThumbnailGenerationJob = MediaThumbnailGenerationJob(context, viewThemeUtils) + + private var items: List = emptyList() + private var visibleItems: List = emptyList() + private var hideHiddenItems = true + + val hasItems: Boolean + get() = items.isNotEmpty() + + val hasVisibleItems: Boolean + get() = visibleItems.isNotEmpty() + + val hiddenFolderCount: Int + get() = items.size - visibleItems.size + + init { + shouldShowHeadersForEmptySections(true) + shouldShowFooters(true) + } + + fun setItems(newItems: List) { + items = newItems + refreshVisibleItems() + } + + fun addItem(item: SyncedFolderDisplayItem) { + items = items + item + refreshVisibleItems() + } + + fun removeItem(item: SyncedFolderDisplayItem) { + items = items - item + refreshVisibleItems() + } + + @VisibleForTesting + fun clear() { + setItems(emptyList()) + } + + fun toggleHiddenItemsVisibility() { + hideHiddenItems = !hideHiddenItems + refreshVisibleItems() + } + + fun onItemVisibilityChanged(item: SyncedFolderDisplayItem) { + if (item.isHidden) { + hideHiddenItems = true + } + + refreshVisibleItems() + } + + fun getItem(section: Int): SyncedFolderDisplayItem? = visibleItems.getOrNull(section) + + fun getSectionById(id: Long): Int = visibleItems.indexOfFirst { it.id == id } + + fun getSectionByLocalPathAndType(localPath: String?, type: Int): Int = visibleItems.indexOfFirst { + it.localPath.equals(localPath, ignoreCase = true) && it.type.id == type + } + + @SuppressLint("NotifyDataSetChanged") + private fun refreshVisibleItems() { + visibleItems = if (hideHiddenItems) items.filterNot { it.isHidden } else items + notifyDataSetChanged() + } + + private fun isFooterSection(section: Int): Boolean = section >= visibleItems.size + + override fun getSectionCount(): Int = if (visibleItems.isEmpty()) 0 else visibleItems.size + 1 + + override fun getItemCount(section: Int): Int = visibleItems.getOrNull(section)?.filePaths?.size ?: 0 + + override fun getItemViewType(section: Int, relativePosition: Int, absolutePosition: Int): Int = + AutoUploadFolderAdapterType.ITEM.viewType + + override fun getHeaderViewType(section: Int): Int { + val type = if (isFooterSection(section)) { + AutoUploadFolderAdapterType.EMPTY + } else { + AutoUploadFolderAdapterType.HEADER + } + + return type.viewType + } + + override fun getFooterViewType(section: Int): Int { + val showFooter = isFooterSection(section) && hiddenFolderCount > 0 + val type = if (showFooter) AutoUploadFolderAdapterType.FOOTER else AutoUploadFolderAdapterType.EMPTY + + return type.viewType + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SectionedViewHolder { + val inflater = LayoutInflater.from(parent.context) + + return when (AutoUploadFolderAdapterType.fromViewType(viewType)) { + AutoUploadFolderAdapterType.ITEM -> ItemViewHolder(GridSyncItemBinding.inflate(inflater, parent, false)) + + AutoUploadFolderAdapterType.HEADER -> createHeaderViewHolder(inflater, parent) + + AutoUploadFolderAdapterType.FOOTER -> + FooterViewHolder(SyncedFoldersFooterBinding.inflate(inflater, parent, false)) + + AutoUploadFolderAdapterType.EMPTY -> + EmptyViewHolder(SyncedFoldersEmptyBinding.inflate(inflater, parent, false)) + } + } + + private fun createHeaderViewHolder(inflater: LayoutInflater, parent: ViewGroup) = AutoUploadFolderHeaderViewHolder( + SyncedFoldersItemHeaderBinding.inflate(inflater, parent, false), + lifecycleScope, + clock, + light, + viewThemeUtils, + clickListener, + connectivityService, + powerManagementService + ) + + override fun onBindHeaderViewHolder(holder: SectionedViewHolder, section: Int, expanded: Boolean) { + if (holder !is AutoUploadFolderHeaderViewHolder) { + return + } + + val item = visibleItems.getOrNull(section) ?: return + holder.bind(item, visibleItems) + } + + override fun onBindFooterViewHolder(holder: SectionedViewHolder, section: Int) { + if (holder !is FooterViewHolder) { + return + } + + holder.binding.footerText.text = context.resources.getQuantityString( + R.plurals.synced_folders_show_hidden_folders, + hiddenFolderCount, + hiddenFolderCount + ) + holder.binding.footerText.setOnClickListener { toggleHiddenItemsVisibility() } + } + + override fun onBindViewHolder( + holder: SectionedViewHolder, + section: Int, + relativePosition: Int, + absolutePosition: Int + ) { + if (holder !is ItemViewHolder) { + return + } + + val item = visibleItems.getOrNull(section) ?: return + val filePath = item.filePaths?.getOrNull(relativePosition) ?: return + bindThumbnail(holder.binding, item, File(filePath), relativePosition) + } + + private fun bindThumbnail(binding: GridSyncItemBinding, item: SyncedFolderDisplayItem, file: File, position: Int) = + with(binding) { + thumbnail.setImageBitmap(ThumbnailsCacheManager.mDefaultImg) + thumbnail.tag = file.hashCode() + lifecycleScope.launch { mediaThumbnailGenerationJob.load(file, thumbnail) } + + val remainingFileCount = item.numberOfFiles - gridTotal + val showRemainingFileCount = remainingFileCount > 0 && position >= gridTotal - 1 + counter.text = String.format(Locale.US, "%d", remainingFileCount) + counterLayout.isVisible = showRemainingFileCount + thumbnailDarkener.isVisible = showRemainingFileCount + } + + private class ItemViewHolder(val binding: GridSyncItemBinding) : SectionedViewHolder(binding.root) + + private class FooterViewHolder(val binding: SyncedFoldersFooterBinding) : SectionedViewHolder(binding.root) + + private class EmptyViewHolder(binding: SyncedFoldersEmptyBinding) : SectionedViewHolder(binding.root) + + companion object { + private const val GRID_ROWS = 2 + } +} diff --git a/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/adapter/AutoUploadFolderAdapterType.kt b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/adapter/AutoUploadFolderAdapterType.kt new file mode 100644 index 000000000000..c2cd9ad261b1 --- /dev/null +++ b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/adapter/AutoUploadFolderAdapterType.kt @@ -0,0 +1,21 @@ +/* + * Nextcloud - Android Client + * + * SPDX-FileCopyrightText: 2026 Alper Ozturk + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package com.owncloud.android.ui.fragment.autoUpload.adapter + +enum class AutoUploadFolderAdapterType { + ITEM, + HEADER, + FOOTER, + EMPTY; + + val viewType: Int + get() = ordinal + + companion object { + fun fromViewType(viewType: Int): AutoUploadFolderAdapterType = entries[viewType] + } +} diff --git a/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/adapter/AutoUploadFolderClickListener.kt b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/adapter/AutoUploadFolderClickListener.kt new file mode 100644 index 000000000000..2eaf657dd06b --- /dev/null +++ b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/adapter/AutoUploadFolderClickListener.kt @@ -0,0 +1,17 @@ +/* + * Nextcloud - Android Client + * + * SPDX-FileCopyrightText: 2026 Alper Ozturk + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package com.owncloud.android.ui.fragment.autoUpload.adapter + +import com.owncloud.android.datamodel.SyncedFolderDisplayItem + +interface AutoUploadFolderClickListener { + fun onSyncStatusToggleClick(item: SyncedFolderDisplayItem) + fun onSyncFolderSettingsClick(item: SyncedFolderDisplayItem) + fun onSyncFolderDeleteUploadedClick(item: SyncedFolderDisplayItem) + fun onVisibilityToggleClick(item: SyncedFolderDisplayItem) + fun showSubFolderWarningDialog() +} diff --git a/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/adapter/AutoUploadFolderHeaderViewHolder.kt b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/adapter/AutoUploadFolderHeaderViewHolder.kt new file mode 100644 index 000000000000..44d6e69b548b --- /dev/null +++ b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/adapter/AutoUploadFolderHeaderViewHolder.kt @@ -0,0 +1,161 @@ +/* + * Nextcloud - Android Client + * + * SPDX-FileCopyrightText: 2026 Alper Ozturk + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package com.owncloud.android.ui.fragment.autoUpload.adapter + +import android.view.MenuItem +import android.view.View +import android.view.ViewGroup +import android.widget.PopupMenu +import androidx.core.content.ContextCompat +import androidx.core.view.isVisible +import androidx.core.view.updateLayoutParams +import androidx.lifecycle.LifecycleCoroutineScope +import com.afollestad.sectionedrecyclerview.SectionedViewHolder +import com.google.android.material.button.MaterialButton +import com.nextcloud.android.common.ui.theme.utils.ColorRole +import com.nextcloud.client.core.Clock +import com.nextcloud.client.device.PowerManagementService +import com.nextcloud.client.network.ConnectivityService +import com.nextcloud.utils.extensions.calculateScanInterval +import com.nextcloud.utils.extensions.hasEnabledParent +import com.owncloud.android.R +import com.owncloud.android.databinding.SyncedFoldersItemHeaderBinding +import com.owncloud.android.datamodel.SyncedFolder +import com.owncloud.android.datamodel.SyncedFolderDisplayItem +import com.owncloud.android.ui.fragment.autoUpload.util.iconId +import com.owncloud.android.utils.FileUtil +import com.owncloud.android.utils.theme.ViewThemeUtils +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File +import kotlin.time.Duration.Companion.milliseconds + +class AutoUploadFolderHeaderViewHolder( + private val binding: SyncedFoldersItemHeaderBinding, + private val lifecycleScope: LifecycleCoroutineScope, + private val clock: Clock, + private val light: Boolean, + private val viewThemeUtils: ViewThemeUtils, + private val clickListener: AutoUploadFolderClickListener, + private val connectivityService: ConnectivityService, + private val powerManagementService: PowerManagementService +) : SectionedViewHolder(binding.root) { + + private val context = binding.root.context + private val resources = context.resources + private val screenWidth = resources.displayMetrics.widthPixels + private val minimumSizeForTouchableArea = resources.getDimensionPixelSize(R.dimen.minimum_size_for_touchable_area) + private val standardDoubleMargin = resources.getDimensionPixelSize(R.dimen.standard_double_margin) + private val titleBottomMargin = resources.getDimensionPixelSize(R.dimen.synced_folders_title_margin) + + private var detailsJob: Job? = null + + fun bind(item: SyncedFolderDisplayItem, visibleItems: List) = with(binding) { + headerContainer.isVisible = true + title.text = item.folderName + type.setImageResource(item.type.iconId()) + + syncStatusButton.isVisible = true + syncStatusButton.showSyncState(item.isEnabled) + syncStatusButton.setOnClickListener { + item.setEnabled(!item.isEnabled, clock.currentTime) + syncStatusButton.showSyncState(item.isEnabled) + clickListener.onSyncStatusToggleClick(item) + loadDetails(item, visibleItems) + } + + settingsButton.isVisible = !light + settingsButton.setOnClickListener { showOverflowMenu(it, item) } + subFolderWarningButton.setOnClickListener { clickListener.showSubFolderWarningDialog() } + + loadDetails(item, visibleItems) + } + + private fun loadDetails(item: SyncedFolderDisplayItem, visibleItems: List) { + detailsJob?.cancel() + detailsJob = lifecycleScope.launch { + val hasEnabledParent = withContext(Dispatchers.IO) { visibleItems.hasEnabledParent(item.localPath) } + val scanMessage = withContext(Dispatchers.IO) { getNextScanMessage(item) } + showDetails(item, hasEnabledParent, scanMessage) + } + } + + private fun showDetails(item: SyncedFolderDisplayItem, hasEnabledParent: Boolean, scanMessage: String?) = + with(binding) { + val showScanMessage = item.isEnabled && scanMessage != null + + subFolderWarningButton.isVisible = hasEnabledParent + scanIndicatorText.isVisible = showScanMessage + scanIndicatorText.text = scanMessage + scanIndicatorText.maxWidth = getScanMessageMaxWidth(hasEnabledParent) + title.updateLayoutParams { + bottomMargin = if (showScanMessage) 0 else titleBottomMargin + } + } + + private fun getScanMessageMaxWidth(showsSubFolderWarning: Boolean): Int { + val trailingIconCount = if (showsSubFolderWarning) TRAILING_ICON_COUNT + 1 else TRAILING_ICON_COUNT + + return screenWidth - minimumSizeForTouchableArea * trailingIconCount - standardDoubleMargin + } + + private fun getNextScanMessage(folder: SyncedFolder): String? { + val (scanIntervalMs, messageId) = folder.calculateScanInterval(connectivityService, powerManagementService) + messageId ?: return null + + val timeUntilNextScan = (folder.lastScanTimestampMs + scanIntervalMs - clock.currentTime).milliseconds + if (timeUntilNextScan.inWholeMinutes <= 0) { + return null + } + + return context.getString(messageId) + } + + private fun showOverflowMenu(anchor: View, item: SyncedFolderDisplayItem) { + PopupMenu(context, anchor).apply { + inflate(R.menu.synced_folders_adapter) + menu.findItem(R.id.action_auto_upload_folder_toggle_visibility).isChecked = item.isHidden + updateDeleteUploadedMenuItem(menu.findItem(R.id.action_auto_upload_folder_delete_uploaded), item) + setOnMenuItemClickListener { onMenuItemClick(it, item) } + show() + } + } + + private fun onMenuItemClick(menuItem: MenuItem, item: SyncedFolderDisplayItem): Boolean { + when (menuItem.itemId) { + R.id.action_auto_upload_folder_toggle_visibility -> clickListener.onVisibilityToggleClick(item) + R.id.action_auto_upload_folder_settings -> clickListener.onSyncFolderSettingsClick(item) + R.id.action_auto_upload_folder_delete_uploaded -> clickListener.onSyncFolderDeleteUploadedClick(item) + else -> return false + } + + return true + } + + private fun updateDeleteUploadedMenuItem(menuItem: MenuItem, item: SyncedFolderDisplayItem) { + val localFolder = item.localPath?.let(::File) + lifecycleScope.launch { + val writable = FileUtil.isFolderWritable(localFolder) + menuItem.isEnabled = writable + menuItem.isVisible = writable + } + } + + private fun MaterialButton.showSyncState(enabled: Boolean) { + icon = if (enabled) { + viewThemeUtils.platform.tintDrawable(context, R.drawable.ic_cloud_sync_on, ColorRole.PRIMARY) + } else { + ContextCompat.getDrawable(context, R.drawable.ic_cloud_sync_off) + } + } + + companion object { + private const val TRAILING_ICON_COUNT = 2 + } +} diff --git a/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/data/AutoUploadDisplayItemFactory.kt b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/data/AutoUploadDisplayItemFactory.kt index 26efc5256347..c9a2e8be998c 100644 --- a/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/data/AutoUploadDisplayItemFactory.kt +++ b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/data/AutoUploadDisplayItemFactory.kt @@ -80,7 +80,7 @@ class AutoUploadDisplayItemFactory( accountName, FileUploadWorker.LOCAL_BEHAVIOUR_FORGET, NameCollisionPolicy.ASK_USER.serialize(), - false, + true, clock.currentTime, null, MediaFolderType.CUSTOM, @@ -90,8 +90,8 @@ class AutoUploadDisplayItemFactory( SyncedFolder.NOT_SCANNED_YET ) - fun createNewCustomFolder(syncedFolder: SyncedFolderParcelable): SyncedFolderDisplayItem = SyncedFolderDisplayItem( - SyncedFolder.UNPERSISTED_ID, + fun createAutoUploadFolder(syncedFolder: SyncedFolderParcelable): SyncedFolderDisplayItem = SyncedFolderDisplayItem( + syncedFolder.id, syncedFolder.localPath, syncedFolder.remotePath, syncedFolder.isWifiOnly, @@ -102,13 +102,13 @@ class AutoUploadDisplayItemFactory( syncedFolder.uploadAction, syncedFolder.nameCollisionPolicy.serialize(), syncedFolder.isEnabled, - clock.currentTime, + syncedFolder.enabledTimestampMs, File(syncedFolder.localPath).name, syncedFolder.type, syncedFolder.isHidden, syncedFolder.subFolderRule, syncedFolder.isExcludeHidden, - SyncedFolder.NOT_SCANNED_YET + syncedFolder.lastScanTimestampMs ) fun updateAutoUploadFolderItem(item: SyncedFolderDisplayItem, syncedFolder: SyncedFolderParcelable) { @@ -122,7 +122,7 @@ class AutoUploadDisplayItemFactory( isSubfolderByDate = syncedFolder.isSubfolderByDate uploadAction = syncedFolder.uploadAction setNameCollisionPolicy(syncedFolder.nameCollisionPolicy.serialize()) - setEnabled(syncedFolder.isEnabled, clock.currentTime) + setEnabled(syncedFolder.isEnabled, syncedFolder.enabledTimestampMs) setSubFolderRule(syncedFolder.subFolderRule) setExcludeHidden(syncedFolder.isExcludeHidden) } @@ -146,7 +146,7 @@ class AutoUploadDisplayItemFactory( syncedFolder.uploadAction, syncedFolder.nameCollisionPolicyInt, syncedFolder.isEnabled, - clock.currentTime, + syncedFolder.enabledTimestampMs, filePaths, folderName, numberOfFiles, diff --git a/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/data/AutoUploadItemsLoader.kt b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/data/AutoUploadItemsLoader.kt index a04519d34035..4ce92f4ded3b 100644 --- a/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/data/AutoUploadItemsLoader.kt +++ b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/data/AutoUploadItemsLoader.kt @@ -7,6 +7,7 @@ package com.owncloud.android.ui.fragment.autoUpload.data import androidx.appcompat.app.AppCompatActivity +import com.nextcloud.utils.extensions.filterEnabledOrWithoutEnabledParent import com.nextcloud.utils.extensions.sortAutoUploadFolderItems import com.owncloud.android.datamodel.MediaFolder import com.owncloud.android.datamodel.MediaFolderType @@ -31,7 +32,7 @@ class AutoUploadItemsLoader( val mediaFolders = getMediaFolders(activity, perFolderMediaItemLimit) val syncedFolders = getAutoUploadFoldersAndDeleteObsolete(currentAccountName) val items = mergeFolderData(syncedFolders, mediaFolders, newItemAccountName) - return items.sortAutoUploadFolderItems().filterNotNull() + return items.sortAutoUploadFolderItems().filterNotNull().filterEnabledOrWithoutEnabledParent() } private fun getMediaFolders(activity: AppCompatActivity, itemLimit: Int): List { diff --git a/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/data/AutoUploadPersistence.kt b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/data/AutoUploadPersistence.kt index 7259ac5027c2..05c4d8a278eb 100644 --- a/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/data/AutoUploadPersistence.kt +++ b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/data/AutoUploadPersistence.kt @@ -30,15 +30,13 @@ class AutoUploadPersistence( } fun persistSyncStatus(item: SyncedFolderDisplayItem) { - if (item.id > SyncedFolder.UNPERSISTED_ID) { - syncedFolderProvider.updateSyncedFolderEnabled(item.id, item.isEnabled) + if (item.id == SyncedFolder.UNPERSISTED_ID) { + storeAutoUploadFolder(item) return } - val storedId = syncedFolderProvider.storeSyncedFolder(item) - if (storedId != INVALID_ID) { - item.id = storedId - } + syncedFolderProvider.updateSyncedFolderEnabled(item.id, item.isEnabled) + applySyncState(item) } fun deleteAutoUploadFolder(id: Long) { diff --git a/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/handler/AutoUploadClickHandler.kt b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/handler/AutoUploadClickHandler.kt index d6f32116f547..3444adf92495 100644 --- a/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/handler/AutoUploadClickHandler.kt +++ b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/handler/AutoUploadClickHandler.kt @@ -11,15 +11,15 @@ import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import com.nextcloud.client.account.User -import com.nextcloud.client.jobs.BackgroundJobManager import com.nextcloud.client.jobs.upload.FileUploadHelper import com.owncloud.android.datamodel.MediaFolderType import com.owncloud.android.datamodel.SyncedFolder import com.owncloud.android.datamodel.SyncedFolderDisplayItem import com.owncloud.android.lib.common.utils.Log_OC -import com.owncloud.android.ui.adapter.SyncedFolderAdapter -import com.owncloud.android.ui.dialog.SyncedFolderPreferencesDialogFragment +import com.owncloud.android.ui.dialog.AutoUploadPreferenceDialogFragment import com.owncloud.android.ui.dialog.parcel.SyncedFolderParcelable +import com.owncloud.android.ui.fragment.autoUpload.adapter.AutoUploadFolderAdapter +import com.owncloud.android.ui.fragment.autoUpload.adapter.AutoUploadFolderClickListener import com.owncloud.android.ui.fragment.autoUpload.data.AutoUploadDisplayItemFactory import com.owncloud.android.ui.fragment.autoUpload.data.AutoUploadPersistence import com.owncloud.android.ui.fragment.autoUpload.ui.AutoUploadDialogs @@ -33,10 +33,9 @@ class AutoUploadClickHandler( private val itemFactory: AutoUploadDisplayItemFactory, private val persistence: AutoUploadPersistence, private val dialogs: AutoUploadDialogs, - private val backgroundJobManager: BackgroundJobManager, - private val getAdapter: () -> SyncedFolderAdapter, + private val getAdapter: () -> AutoUploadFolderAdapter, private val onItemVisibilityChanged: () -> Unit -) : SyncedFolderAdapter.ClickListener { +) : AutoUploadFolderClickListener { private val fileUploadHelper = FileUploadHelper.instance() @@ -47,47 +46,33 @@ class AutoUploadClickHandler( return } - onSyncFolderSettingsClick(0, itemFactory.createEmptyCustomFolder(accountName)) + onSyncFolderSettingsClick(itemFactory.createEmptyCustomFolder(accountName)) } fun onDeleteAllUploadedClick(user: User) { dialogs.showDeleteAllUploadedDialog(user) } - override fun onSyncStatusToggleClick(section: Int, item: SyncedFolderDisplayItem?) { - item ?: return + override fun onSyncStatusToggleClick(item: SyncedFolderDisplayItem) { persistence.persistSyncStatus(item) - - if (item.isEnabled) { - Log_OC.d(TAG, "auto-upload configuration sync status is enabled: " + item.remotePath) - backgroundJobManager.startAutoUpload(item, overridePowerSaving = false) - dialogs.showBatteryOptimizationDialogIfNeeded() - return - } - - Log_OC.d(TAG, "auto-upload configuration sync status is disabled: " + item.remotePath) - fragment.lifecycleScope.launch(Dispatchers.IO) { - fileUploadHelper.removeEntityFromUploadEntities(item.id) - } + onSyncStateApplied(item) } - override fun onSyncFolderSettingsClick(section: Int, syncedFolderDisplayItem: SyncedFolderDisplayItem?) { + override fun onSyncFolderSettingsClick(item: SyncedFolderDisplayItem) { check(Looper.getMainLooper().isCurrentThread) { "This must be called on the main thread!" } - val dialog = SyncedFolderPreferencesDialogFragment.newInstance(syncedFolderDisplayItem, section) ?: return - dialogs.showDialog(dialog, SYNCED_FOLDER_PREFERENCES_DIALOG_TAG) + val dialog = AutoUploadPreferenceDialogFragment.newInstance(item) + dialogs.showDialog(dialog, AUTO_UPLOAD_PREFERENCE_DIALOG_TAG) } - override fun onSyncFolderDeleteUploadedClick(section: Int, syncedFolderDisplayItem: SyncedFolderDisplayItem?) { - syncedFolderDisplayItem ?: return - dialogs.showDeleteUploadedDialog(syncedFolderDisplayItem) + override fun onSyncFolderDeleteUploadedClick(item: SyncedFolderDisplayItem) { + dialogs.showDeleteUploadedDialog(item) } - override fun onVisibilityToggleClick(section: Int, item: SyncedFolderDisplayItem?) { - item ?: return + override fun onVisibilityToggleClick(item: SyncedFolderDisplayItem) { item.isHidden = !item.isHidden persistence.saveOrUpdateAutoUploadFolder(item) - getAdapter().setSyncFolderItem(section, item) + getAdapter().onItemVisibilityChanged(item) onItemVisibilityChanged() } @@ -95,29 +80,25 @@ class AutoUploadClickHandler( dialogs.showSubFolderWarningDialog() } - fun onSaveAutoUploadFolderPreference(syncedFolder: SyncedFolderParcelable?) { - syncedFolder ?: return - - val isSaved = if (isNewCustomFolder(syncedFolder)) { - addCustomFolder(syncedFolder) + fun onSaveAutoUploadFolderPreference(syncedFolder: SyncedFolderParcelable) { + val item = if (isNewCustomFolder(syncedFolder)) { + addFolder(syncedFolder) } else { - updateExistingFolder(syncedFolder) + updateFolder(syncedFolder) } - if (isSaved && syncedFolder.isEnabled) { - dialogs.showBatteryOptimizationDialogIfNeeded() - } + onSyncStateApplied(item) } - fun onDeleteAutoUploadFolderPreference(syncedFolder: SyncedFolderParcelable?) { - syncedFolder ?: return + fun onDeleteAutoUploadFolderPreference(syncedFolder: SyncedFolderParcelable) { Log_OC.d(TAG, "deleting auto upload configuration: " + syncedFolder.remotePath) fragment.lifecycleScope.launch(Dispatchers.IO) { fileUploadHelper.removeEntityFromUploadEntities(syncedFolder.id) persistence.deleteAutoUploadFolder(syncedFolder.id) withContext(Dispatchers.Main) { - getAdapter().removeItem(syncedFolder.section) + val adapter = getAdapter() + adapter.getItem(findSection(adapter, syncedFolder))?.let(adapter::removeItem) } } } @@ -125,24 +106,48 @@ class AutoUploadClickHandler( private fun isNewCustomFolder(syncedFolder: SyncedFolderParcelable): Boolean = syncedFolder.type == MediaFolderType.CUSTOM && syncedFolder.id == SyncedFolder.UNPERSISTED_ID - private fun addCustomFolder(syncedFolder: SyncedFolderParcelable): Boolean { - val newCustomFolder = itemFactory.createNewCustomFolder(syncedFolder) - persistence.saveOrUpdateAutoUploadFolder(newCustomFolder) - getAdapter().addSyncFolderItem(newCustomFolder) - return true + private fun findSection(adapter: AutoUploadFolderAdapter, syncedFolder: SyncedFolderParcelable): Int = + if (syncedFolder.id == SyncedFolder.UNPERSISTED_ID) { + adapter.getSectionByLocalPathAndType(syncedFolder.localPath, syncedFolder.type.id) + } else { + adapter.getSectionById(syncedFolder.id) + } + + private fun addFolder(syncedFolder: SyncedFolderParcelable): SyncedFolderDisplayItem { + val item = itemFactory.createAutoUploadFolder(syncedFolder) + persistence.saveOrUpdateAutoUploadFolder(item) + getAdapter().addItem(item) + + return item } - private fun updateExistingFolder(syncedFolder: SyncedFolderParcelable): Boolean { + private fun updateFolder(syncedFolder: SyncedFolderParcelable): SyncedFolderDisplayItem { val adapter = getAdapter() - val item = adapter.get(syncedFolder.section) ?: return false + val section = findSection(adapter, syncedFolder) + val item = adapter.getItem(section) ?: return addFolder(syncedFolder) + itemFactory.updateAutoUploadFolderItem(item, syncedFolder) persistence.saveOrUpdateAutoUploadFolder(item) - adapter.notifyItemChanged(adapter.getSectionHeaderIndex(syncedFolder.section)) - return true + adapter.notifyItemChanged(adapter.getSectionHeaderIndex(section)) + + return item + } + + private fun onSyncStateApplied(item: SyncedFolderDisplayItem) { + Log_OC.d(TAG, "auto-upload configuration enabled=${item.isEnabled}: ${item.remotePath}") + + if (item.isEnabled) { + dialogs.showBatteryOptimizationDialogIfNeeded() + return + } + + fragment.lifecycleScope.launch(Dispatchers.IO) { + fileUploadHelper.removeEntityFromUploadEntities(item.id) + } } companion object { private val TAG = AutoUploadClickHandler::class.java.simpleName - const val SYNCED_FOLDER_PREFERENCES_DIALOG_TAG = "SYNCED_FOLDER_PREFERENCES_DIALOG" + const val AUTO_UPLOAD_PREFERENCE_DIALOG_TAG = "AUTO_UPLOAD_PREFERENCE_DIALOG" } } diff --git a/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/handler/AutoUploadIntentHandler.kt b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/handler/AutoUploadIntentHandler.kt index a40aae6a9ad3..4ffe4449b404 100644 --- a/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/handler/AutoUploadIntentHandler.kt +++ b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/handler/AutoUploadIntentHandler.kt @@ -13,7 +13,7 @@ import com.nextcloud.client.account.UserAccountManager import com.nextcloud.client.jobs.MediaFoldersDetectionWork import com.nextcloud.client.jobs.NotificationWork import com.owncloud.android.ui.activity.BaseActivity -import com.owncloud.android.ui.adapter.SyncedFolderAdapter +import com.owncloud.android.ui.fragment.autoUpload.adapter.AutoUploadFolderAdapter class AutoUploadIntentHandler { @@ -29,7 +29,7 @@ class AutoUploadIntentHandler { mediaFolderType = intent.getIntExtra(MediaFoldersDetectionWork.KEY_MEDIA_FOLDER_TYPE, -1) } - fun findMediaFolderSection(adapter: SyncedFolderAdapter): Int? { + fun findMediaFolderSection(adapter: AutoUploadFolderAdapter): Int? { val path = mediaFolderPath if (path.isNullOrEmpty()) { return null diff --git a/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/handler/AutoUploadPickers.kt b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/handler/AutoUploadPickers.kt index 4c8f5bff89dc..8a45ad093c17 100644 --- a/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/handler/AutoUploadPickers.kt +++ b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/handler/AutoUploadPickers.kt @@ -15,11 +15,11 @@ import com.nextcloud.utils.extensions.getParcelableArgument import com.owncloud.android.datamodel.OCFile import com.owncloud.android.ui.activity.FolderPickerActivity import com.owncloud.android.ui.activity.UploadFilesActivity -import com.owncloud.android.ui.dialog.SyncedFolderPreferencesDialogFragment +import com.owncloud.android.ui.dialog.AutoUploadPreferenceDialogFragment class AutoUploadPickers( private val fragment: Fragment, - private val findPreferencesDialog: () -> SyncedFolderPreferencesDialogFragment? + private val findAutoUploadPreferenceDialog: () -> AutoUploadPreferenceDialogFragment? ) { private val remoteFolderLauncher = @@ -44,7 +44,7 @@ class AutoUploadPickers( putExtra(UploadFilesActivity.KEY_LOCAL_FOLDER_PICKER_MODE, true) putExtra( UploadFilesActivity.REQUEST_CODE_KEY, - SyncedFolderPreferencesDialogFragment.REQUEST_CODE__SELECT_LOCAL_FOLDER + AutoUploadPreferenceDialogFragment.REQUEST_CODE__SELECT_LOCAL_FOLDER ) } localFolderLauncher.launch(intent) @@ -55,9 +55,10 @@ class AutoUploadPickers( return } - val dialog = findPreferencesDialog() ?: return + val dialog = findAutoUploadPreferenceDialog() ?: return val chosenFolder = result.data?.getParcelableArgument(FolderPickerActivity.EXTRA_FOLDER, OCFile::class.java) - dialog.setRemoteFolderSummary(chosenFolder?.remotePath) + val remotePath = chosenFolder?.remotePath ?: return + dialog.setRemoteFolderSummary(remotePath) } private fun onLocalFolderPicked(result: ActivityResult) { @@ -65,7 +66,8 @@ class AutoUploadPickers( return } - val dialog = findPreferencesDialog() ?: return - dialog.setLocalFolderSummary(result.data?.getStringExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES)) + val dialog = findAutoUploadPreferenceDialog() ?: return + val localPath = result.data?.getStringExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES) ?: return + dialog.setLocalFolderSummary(localPath) } } diff --git a/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/ui/AutoUploadEmptyContent.kt b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/ui/AutoUploadEmptyContent.kt index 814daf639a3a..7cd001a734e1 100644 --- a/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/ui/AutoUploadEmptyContent.kt +++ b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/ui/AutoUploadEmptyContent.kt @@ -9,12 +9,12 @@ package com.owncloud.android.ui.fragment.autoUpload.ui import android.view.View import com.owncloud.android.R import com.owncloud.android.databinding.FragmentAutoUploadBinding -import com.owncloud.android.ui.adapter.SyncedFolderAdapter +import com.owncloud.android.ui.fragment.autoUpload.adapter.AutoUploadFolderAdapter import com.owncloud.android.utils.theme.ViewThemeUtils class AutoUploadEmptyContent( private val binding: FragmentAutoUploadBinding, - private val adapter: SyncedFolderAdapter, + private val adapter: AutoUploadFolderAdapter, viewThemeUtils: ViewThemeUtils ) { @@ -22,10 +22,10 @@ class AutoUploadEmptyContent( private val resources = binding.root.resources private val hasOnlyHiddenItems: Boolean - get() = adapter.sectionCount == 0 && adapter.unfilteredSectionCount > 0 + get() = !adapter.hasVisibleItems && adapter.hasItems private val hasNoItems: Boolean - get() = adapter.sectionCount == 0 && adapter.unfilteredSectionCount == 0 + get() = !adapter.hasItems init { emptyList.emptyListIcon.setImageResource(R.drawable.nav_synced_folders) diff --git a/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/util/MediaFolderTypeExtensions.kt b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/util/MediaFolderTypeExtensions.kt new file mode 100644 index 000000000000..873ad485edcb --- /dev/null +++ b/app/src/main/java/com/owncloud/android/ui/fragment/autoUpload/util/MediaFolderTypeExtensions.kt @@ -0,0 +1,18 @@ +/* + * Nextcloud - Android Client + * + * SPDX-FileCopyrightText: 2026 Alper Ozturk + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package com.owncloud.android.ui.fragment.autoUpload.util + +import androidx.annotation.DrawableRes +import com.owncloud.android.R +import com.owncloud.android.datamodel.MediaFolderType + +@DrawableRes +fun MediaFolderType?.iconId(): Int = when (this) { + MediaFolderType.VIDEO -> R.drawable.video_32dp + MediaFolderType.IMAGE -> R.drawable.image_32dp + MediaFolderType.CUSTOM, null -> R.drawable.folder_star_32dp +} diff --git a/app/src/main/res/layout/synced_folders_settings_layout.xml b/app/src/main/res/layout/dialog_auto_upload_preference.xml similarity index 100% rename from app/src/main/res/layout/synced_folders_settings_layout.xml rename to app/src/main/res/layout/dialog_auto_upload_preference.xml