fix: ktlint compliant kotlin formatting/code

Signed-off-by: Andy Scherzinger <info@andy-scherzinger.de>
This commit is contained in:
Andy Scherzinger 2024-06-27 19:46:41 +02:00
parent 90934f4ef4
commit 40d45bcb7a
No known key found for this signature in database
GPG key ID: 6CADC7E3523C308B
76 changed files with 272 additions and 362 deletions

View file

@ -42,8 +42,10 @@ trim_trailing_whitespace=false
indent_size=2 indent_size=2
[*.{kt,kts}] [*.{kt,kts}]
ktlint_code_style = android_studio
# IDE does not follow this Ktlint rule strictly, but the default ordering is pretty good anyway, so let's ditch it # IDE does not follow this Ktlint rule strictly, but the default ordering is pretty good anyway, so let's ditch it
ktlint_standard_import-ordering = disabled ktlint_standard_import-ordering = disabled
ktlint_standard_no-consecutive-comments = disabled ktlint_standard_no-consecutive-comments = disabled
ktlint_function_naming_ignore_when_annotated_with = Composable
ij_kotlin_allow_trailing_comma = false ij_kotlin_allow_trailing_comma = false
ij_kotlin_allow_trailing_comma_on_call_site = false ij_kotlin_allow_trailing_comma_on_call_site = false

View file

@ -177,8 +177,7 @@ object DocumentsProviderUtils {
*/ */
@Suppress("EXPERIMENTAL_API_USAGE") @Suppress("EXPERIMENTAL_API_USAGE")
@VisibleForTesting @VisibleForTesting
internal suspend fun getLoadedCursor(timeout: Long = 15_000, query: () -> Cursor?) = internal suspend fun getLoadedCursor(timeout: Long = 15_000, query: () -> Cursor?) = withTimeout(timeout) {
withTimeout(timeout) {
suspendCancellableCoroutine<Cursor> { cont -> suspendCancellableCoroutine<Cursor> { cont ->
val cursor = query() ?: throw IOException("Initial query returned no results") val cursor = query() ?: throw IOException("Initial query returned no results")
cont.invokeOnCancellation { cursor.close() } cont.invokeOnCancellation { cursor.close() }

View file

@ -21,8 +21,8 @@ import com.owncloud.android.R
import com.owncloud.android.ui.TextDrawable import com.owncloud.android.ui.TextDrawable
internal class AvatarTestFragment : Fragment() { internal class AvatarTestFragment : Fragment() {
lateinit var list1: LinearLayout private lateinit var list1: LinearLayout
lateinit var list2: LinearLayout private lateinit var list2: LinearLayout
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view: View = inflater.inflate(R.layout.avatar_fragment, null) val view: View = inflater.inflate(R.layout.avatar_fragment, null)
@ -34,7 +34,7 @@ internal class AvatarTestFragment : Fragment() {
} }
fun addAvatar(name: String, avatarRadius: Float, width: Int, targetContext: Context) { fun addAvatar(name: String, avatarRadius: Float, width: Int, targetContext: Context) {
val margin = padding val margin = PADDING
val imageView = ImageView(targetContext) val imageView = ImageView(targetContext)
imageView.setImageDrawable(TextDrawable.createNamedAvatar(name, avatarRadius)) imageView.setImageDrawable(TextDrawable.createNamedAvatar(name, avatarRadius))
@ -47,7 +47,7 @@ internal class AvatarTestFragment : Fragment() {
} }
fun addBitmap(bitmap: Bitmap, width: Int, list: Int, targetContext: Context) { fun addBitmap(bitmap: Bitmap, width: Int, list: Int, targetContext: Context) {
val margin = padding val margin = PADDING
val imageView = ImageView(targetContext) val imageView = ImageView(targetContext)
imageView.setImageBitmap(bitmap) imageView.setImageBitmap(bitmap)
@ -64,6 +64,6 @@ internal class AvatarTestFragment : Fragment() {
} }
companion object { companion object {
private const val padding = 10 private const val PADDING = 10
} }
} }

View file

@ -672,10 +672,7 @@ class FileDetailSharingFragmentIT : AbstractIT() {
} }
// open bottom sheet with actions // open bottom sheet with actions
private fun openAdvancedPermissions( private fun openAdvancedPermissions(sut: FileDetailSharingFragment, userShare: OCShare) {
sut: FileDetailSharingFragment,
userShare: OCShare
) {
activity.handler.post { activity.handler.post {
sut.showSharingMenuActionSheet(userShare) sut.showSharingMenuActionSheet(userShare)
} }
@ -723,10 +720,7 @@ class FileDetailSharingFragmentIT : AbstractIT() {
/** /**
* verify send new email note text * verify send new email note text
*/ */
private fun verifySendNewEmail( private fun verifySendNewEmail(sut: FileDetailSharingFragment, userShare: OCShare) {
sut: FileDetailSharingFragment,
userShare: OCShare
) {
activity.runOnUiThread { sut.showSharingMenuActionSheet(userShare) } activity.runOnUiThread { sut.showSharingMenuActionSheet(userShare) }
waitForIdleSync() waitForIdleSync()

View file

@ -20,7 +20,9 @@ import org.junit.Test
class TrashbinActivityIT : AbstractIT() { class TrashbinActivityIT : AbstractIT() {
enum class TestCase { enum class TestCase {
ERROR, EMPTY, FILES ERROR,
EMPTY,
FILES
} }
@get:Rule @get:Rule

View file

@ -36,8 +36,10 @@ class TrashbinLocalRepository(private val testCase: TrashbinActivityIT.TestCase)
"image/png", "image/png",
"/trashbin/test.png", "/trashbin/test.png",
"subFolder/test.png", "subFolder/test.png",
1395847838, // random date // random date
1395847908 // random date 1395847838,
// random date
1395847908
) )
) )
files.add( files.add(
@ -46,8 +48,10 @@ class TrashbinLocalRepository(private val testCase: TrashbinActivityIT.TestCase)
"image/jpeg", "image/jpeg",
"/trashbin/image.jpg", "/trashbin/image.jpg",
"image.jpg", "image.jpg",
1395841858, // random date // random date
1395837858 // random date 1395841858,
// random date
1395837858
) )
) )
files.add( files.add(
@ -56,8 +60,10 @@ class TrashbinLocalRepository(private val testCase: TrashbinActivityIT.TestCase)
"DIR", "DIR",
"/trashbin/folder/", "/trashbin/folder/",
"folder", "folder",
1395347858, // random date // random date
1395849858 // random date 1395347858,
// random date
1395849858
) )
) )

View file

@ -290,7 +290,8 @@ class EncryptionUtilsV2IT : EncryptionIT() {
mimeType = MimeType.JPEG mimeType = MimeType.JPEG
}, },
EncryptionUtils.generateIV(), EncryptionUtils.generateIV(),
EncryptionUtils.generateUid(), // random string, not real tag // random string, not real tag
EncryptionUtils.generateUid(),
EncryptionUtils.generateKey(), EncryptionUtils.generateKey(),
metadataFile, metadataFile,
storageManager storageManager

View file

@ -85,11 +85,7 @@ class InAppReviewHelperImpl(val appPreferences: AppPreferences) : InAppReviewHel
} }
} }
private fun launchAppReviewFlow( private fun launchAppReviewFlow(manager: ReviewManager, activity: AppCompatActivity, reviewInfo: ReviewInfo) {
manager: ReviewManager,
activity: AppCompatActivity,
reviewInfo: ReviewInfo
) {
val flow = manager.launchReviewFlow(activity, reviewInfo) val flow = manager.launchReviewFlow(activity, reviewInfo)
flow.addOnCompleteListener { _ -> flow.addOnCompleteListener { _ ->
// The flow has finished. The API does not indicate whether the user // The flow has finished. The API does not indicate whether the user

View file

@ -44,7 +44,7 @@ class AssistantViewModel(
private val _taskTypes = MutableStateFlow<List<TaskType>?>(null) private val _taskTypes = MutableStateFlow<List<TaskType>?>(null)
val taskTypes: StateFlow<List<TaskType>?> = _taskTypes val taskTypes: StateFlow<List<TaskType>?> = _taskTypes
private var _taskList: List<Task>? = null private var taskList: List<Task>? = null
private val _filteredTaskList = MutableStateFlow<List<Task>?>(null) private val _filteredTaskList = MutableStateFlow<List<Task>?>(null)
val filteredTaskList: StateFlow<List<Task>?> = _filteredTaskList val filteredTaskList: StateFlow<List<Task>?> = _filteredTaskList
@ -55,10 +55,7 @@ class AssistantViewModel(
} }
@Suppress("MagicNumber") @Suppress("MagicNumber")
fun createTask( fun createTask(input: String, type: String) {
input: String,
type: String
) {
viewModelScope.launch(Dispatchers.IO) { viewModelScope.launch(Dispatchers.IO) {
val result = repository.createTask(input, type) val result = repository.createTask(input, type)
@ -111,7 +108,7 @@ class AssistantViewModel(
viewModelScope.launch(Dispatchers.IO) { viewModelScope.launch(Dispatchers.IO) {
val result = repository.getTaskList(appId) val result = repository.getTaskList(appId)
if (result.isSuccess) { if (result.isSuccess) {
_taskList = result.resultData.tasks taskList = result.resultData.tasks
filterTaskList(_selectedTaskType.value?.id) filterTaskList(_selectedTaskType.value?.id)
@ -157,11 +154,11 @@ class AssistantViewModel(
private fun filterTaskList(taskTypeId: String?) { private fun filterTaskList(taskTypeId: String?) {
if (taskTypeId == null) { if (taskTypeId == null) {
_filteredTaskList.update { _filteredTaskList.update {
_taskList taskList
} }
} else { } else {
_filteredTaskList.update { _filteredTaskList.update {
_taskList?.filter { it.type == taskTypeId } taskList?.filter { it.type == taskTypeId }
} }
} }

View file

@ -151,11 +151,7 @@ fun AssistantScreen(viewModel: AssistantViewModel, activity: Activity) {
} }
@Composable @Composable
private fun ScreenState( private fun ScreenState(state: AssistantViewModel.State, activity: Activity, viewModel: AssistantViewModel) {
state: AssistantViewModel.State,
activity: Activity,
viewModel: AssistantViewModel
) {
val messageId: Int? = when (state) { val messageId: Int? = when (state) {
is AssistantViewModel.State.Error -> { is AssistantViewModel.State.Error -> {
state.messageId state.messageId

View file

@ -22,10 +22,7 @@ class AssistantRepository(private val client: NextcloudClient) : AssistantReposi
return GetTaskTypesRemoteOperation().execute(client) return GetTaskTypesRemoteOperation().execute(client)
} }
override fun createTask( override fun createTask(input: String, type: String): RemoteOperationResult<Void> {
input: String,
type: String
): RemoteOperationResult<Void> {
return CreateTaskRemoteOperation(input, type).execute(client) return CreateTaskRemoteOperation(input, type).execute(client)
} }

View file

@ -14,10 +14,7 @@ import com.owncloud.android.lib.resources.assistant.model.TaskTypes
interface AssistantRepositoryType { interface AssistantRepositoryType {
fun getTaskTypes(): RemoteOperationResult<TaskTypes> fun getTaskTypes(): RemoteOperationResult<TaskTypes>
fun createTask( fun createTask(input: String, type: String): RemoteOperationResult<Void>
input: String,
type: String
): RemoteOperationResult<Void>
fun getTaskList(appId: String): RemoteOperationResult<TaskList> fun getTaskList(appId: String): RemoteOperationResult<TaskList>

View file

@ -41,10 +41,7 @@ import com.owncloud.android.lib.resources.assistant.model.Task
@OptIn(ExperimentalFoundationApi::class) @OptIn(ExperimentalFoundationApi::class)
@Suppress("LongMethod", "MagicNumber") @Suppress("LongMethod", "MagicNumber")
@Composable @Composable
fun TaskView( fun TaskView(task: Task, showDeleteTaskAlertDialog: (Long) -> Unit) {
task: Task,
showDeleteTaskAlertDialog: (Long) -> Unit
) {
var showTaskDetailBottomSheet by remember { mutableStateOf(false) } var showTaskDetailBottomSheet by remember { mutableStateOf(false) }
var showMoreActionsBottomSheet by remember { mutableStateOf(false) } var showMoreActionsBottomSheet by remember { mutableStateOf(false) }

View file

@ -55,21 +55,16 @@ fun TaskDetailBottomSheet(task: Task, dismiss: () -> Unit) {
ModalBottomSheet( ModalBottomSheet(
modifier = Modifier.padding(top = 32.dp), modifier = Modifier.padding(top = 32.dp),
containerColor = Color.White, containerColor = Color.White,
onDismissRequest = { onDismissRequest = { dismiss() },
dismiss()
},
sheetState = sheetState sheetState = sheetState
) { ) {
LazyColumn( LazyColumn(modifier = Modifier.fillMaxSize().padding(16.dp)) {
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
stickyHeader { stickyHeader {
Row( Row(
modifier = Modifier modifier = Modifier.fillMaxWidth().background(
.fillMaxWidth() color = colorResource(id = R.color.light_grey),
.background(color = colorResource(id = R.color.light_grey), shape = RoundedCornerShape(8.dp)) shape = RoundedCornerShape(8.dp)
)
) { ) {
TextInputSelectButton( TextInputSelectButton(
Modifier.weight(1f), Modifier.weight(1f),
@ -95,10 +90,10 @@ fun TaskDetailBottomSheet(task: Task, dismiss: () -> Unit) {
Spacer(modifier = Modifier.height(16.dp)) Spacer(modifier = Modifier.height(16.dp))
Column( Column(
modifier = Modifier modifier = Modifier.fillMaxSize().background(
.fillMaxSize() color = colorResource(id = R.color.light_grey),
.background(color = colorResource(id = R.color.light_grey), shape = RoundedCornerShape(8.dp)) shape = RoundedCornerShape(8.dp)
.padding(16.dp) ).padding(16.dp)
) { ) {
Text( Text(
text = if (showInput) { text = if (showInput) {

View file

@ -71,7 +71,7 @@ abstract class NextcloudDatabase : RoomDatabase() {
companion object { companion object {
const val FIRST_ROOM_DB_VERSION = 65 const val FIRST_ROOM_DB_VERSION = 65
private var INSTANCE: NextcloudDatabase? = null private var instance: NextcloudDatabase? = null
@JvmStatic @JvmStatic
@Suppress("DeprecatedCallableAddReplaceWith") @Suppress("DeprecatedCallableAddReplaceWith")
@ -82,8 +82,8 @@ abstract class NextcloudDatabase : RoomDatabase() {
@JvmStatic @JvmStatic
fun getInstance(context: Context, clock: Clock): NextcloudDatabase { fun getInstance(context: Context, clock: Clock): NextcloudDatabase {
if (INSTANCE == null) { if (instance == null) {
INSTANCE = Room instance = Room
.databaseBuilder(context, NextcloudDatabase::class.java, ProviderMeta.DB_NAME) .databaseBuilder(context, NextcloudDatabase::class.java, ProviderMeta.DB_NAME)
.allowMainThreadQueries() .allowMainThreadQueries()
.addLegacyMigrations(clock, context) .addLegacyMigrations(clock, context)
@ -92,7 +92,7 @@ abstract class NextcloudDatabase : RoomDatabase() {
.fallbackToDestructiveMigration() .fallbackToDestructiveMigration()
.build() .build()
} }
return INSTANCE!! return instance!!
} }
} }
} }

View file

@ -46,11 +46,7 @@ object DatabaseMigrationUtil {
/** /**
* Utility method to create a new table with the given columns * Utility method to create a new table with the given columns
*/ */
private fun createNewTable( private fun createNewTable(database: SupportSQLiteDatabase, newTableName: String, columns: Map<String, String>) {
database: SupportSQLiteDatabase,
newTableName: String,
columns: Map<String, String>
) {
val columnsString = columns.entries.joinToString(",") { "${it.key} ${it.value}" } val columnsString = columns.entries.joinToString(",") { "${it.key} ${it.value}" }
database.execSQL("CREATE TABLE $newTableName ($columnsString)") database.execSQL("CREATE TABLE $newTableName ($columnsString)")
} }
@ -80,11 +76,7 @@ object DatabaseMigrationUtil {
/** /**
* Utility method to replace an old table with a new one, essentially deleting the old one and renaming the new one * Utility method to replace an old table with a new one, essentially deleting the old one and renaming the new one
*/ */
private fun replaceTable( private fun replaceTable(database: SupportSQLiteDatabase, tableName: String, newTableTempName: String) {
database: SupportSQLiteDatabase,
tableName: String,
newTableTempName: String
) {
database.execSQL("DROP TABLE $tableName") database.execSQL("DROP TABLE $tableName")
database.execSQL("ALTER TABLE $newTableTempName RENAME TO $tableName") database.execSQL("ALTER TABLE $newTableTempName RENAME TO $tableName")
} }

View file

@ -12,11 +12,7 @@ import androidx.fragment.app.FragmentManager
import dagger.android.support.AndroidSupportInjection import dagger.android.support.AndroidSupportInjection
internal class FragmentInjector : FragmentManager.FragmentLifecycleCallbacks() { internal class FragmentInjector : FragmentManager.FragmentLifecycleCallbacks() {
override fun onFragmentPreAttached( override fun onFragmentPreAttached(fragmentManager: FragmentManager, fragment: Fragment, context: Context) {
fragmentManager: FragmentManager,
fragment: Fragment,
context: Context
) {
super.onFragmentPreAttached(fragmentManager, fragment, context) super.onFragmentPreAttached(fragmentManager, fragment, context)
if (fragment is Injectable) { if (fragment is Injectable) {
try { try {

View file

@ -39,10 +39,8 @@ class DocumentPageListAdapter :
} }
private class DiffItemCallback : DiffUtil.ItemCallback<String>() { private class DiffItemCallback : DiffUtil.ItemCallback<String>() {
override fun areItemsTheSame(oldItem: String, newItem: String) = override fun areItemsTheSame(oldItem: String, newItem: String) = oldItem == newItem
oldItem == newItem
override fun areContentsTheSame(oldItem: String, newItem: String) = override fun areContentsTheSame(oldItem: String, newItem: String) = oldItem == newItem
oldItem == newItem
} }
} }

View file

@ -36,10 +36,7 @@ class GeneratePDFUseCase @Inject constructor(private val logger: Logger) {
/** /**
* @return `true` if the PDF was generated successfully, `false` otherwise * @return `true` if the PDF was generated successfully, `false` otherwise
*/ */
private fun writePdfToFile( private fun writePdfToFile(filePath: String, document: PdfDocument): Boolean {
filePath: String,
document: PdfDocument
): Boolean {
return try { return try {
val fileOutputStream = FileOutputStream(filePath) val fileOutputStream = FileOutputStream(filePath)
document.writeTo(fileOutputStream) document.writeTo(fileOutputStream)
@ -52,10 +49,7 @@ class GeneratePDFUseCase @Inject constructor(private val logger: Logger) {
} }
} }
private fun fillDocumentPages( private fun fillDocumentPages(document: PdfDocument, imagePaths: List<String>) {
document: PdfDocument,
imagePaths: List<String>
) {
imagePaths.forEach { path -> imagePaths.forEach { path ->
val bitmap = BitmapFactory.decodeFile(path) val bitmap = BitmapFactory.decodeFile(path)
val pageInfo = PdfDocument.PageInfo.Builder(bitmap.width, bitmap.height, 1).create() val pageInfo = PdfDocument.PageInfo.Builder(bitmap.width, bitmap.height, 1).create()

View file

@ -112,7 +112,8 @@ class GeneratePdfFromImagesWork(
user, user,
arrayOf(pdfPath), arrayOf(pdfPath),
arrayOf(uploadPath), arrayOf(uploadPath),
FileUploadWorker.LOCAL_BEHAVIOUR_DELETE, // MIME type will be detected from file name // MIME type will be detected from file name
FileUploadWorker.LOCAL_BEHAVIOUR_DELETE,
true, true,
UploadFileOperation.CREATED_BY_USER, UploadFileOperation.CREATED_BY_USER,
false, false,

View file

@ -20,7 +20,7 @@ import com.owncloud.android.databinding.FragmentEtmAccountsBinding
class EtmAccountsFragment : EtmBaseFragment() { class EtmAccountsFragment : EtmBaseFragment() {
private var _binding: FragmentEtmAccountsBinding? = null private var _binding: FragmentEtmAccountsBinding? = null
private val binding get() = _binding!! val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)

View file

@ -20,7 +20,7 @@ import java.util.Locale
class EtmMigrations : EtmBaseFragment() { class EtmMigrations : EtmBaseFragment() {
private var _binding: FragmentEtmMigrationsBinding? = null private var _binding: FragmentEtmMigrationsBinding? = null
private val binding get() = _binding!! val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)

View file

@ -20,7 +20,7 @@ import com.owncloud.android.databinding.FragmentEtmPreferencesBinding
class EtmPreferencesFragment : EtmBaseFragment() { class EtmPreferencesFragment : EtmBaseFragment() {
private var _binding: FragmentEtmPreferencesBinding? = null private var _binding: FragmentEtmPreferencesBinding? = null
private val binding get() = _binding!! val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)

View file

@ -25,8 +25,5 @@ interface DeckApi {
* value otherwise * value otherwise
* @see [Deck Server App](https://apps.nextcloud.com/apps/deck) * @see [Deck Server App](https://apps.nextcloud.com/apps/deck)
*/ */
fun createForwardToDeckActionIntent( fun createForwardToDeckActionIntent(notification: Notification, user: User): Optional<PendingIntent>
notification: Notification,
user: User
): Optional<PendingIntent>
} }

View file

@ -100,10 +100,7 @@ class BackgroundJobFactory @Inject constructor(
} }
} }
private fun createFilesExportWork( private fun createFilesExportWork(context: Context, params: WorkerParameters): ListenableWorker {
context: Context,
params: WorkerParameters
): ListenableWorker {
return FilesExportWork( return FilesExportWork(
context, context,
accountManager.user, accountManager.user,
@ -113,10 +110,7 @@ class BackgroundJobFactory @Inject constructor(
) )
} }
private fun createContentObserverJob( private fun createContentObserverJob(context: Context, workerParameters: WorkerParameters): ListenableWorker {
context: Context,
workerParameters: WorkerParameters
): ListenableWorker {
return ContentObserverWork( return ContentObserverWork(
context, context,
workerParameters, workerParameters,

View file

@ -409,9 +409,7 @@ internal class BackgroundJobManagerImpl(
workManager.isWorkRunning(JOB_IMMEDIATE_FILES_SYNC + "_" + syncedFolderID) workManager.isWorkRunning(JOB_IMMEDIATE_FILES_SYNC + "_" + syncedFolderID)
} }
override fun schedulePeriodicFilesSyncJob( override fun schedulePeriodicFilesSyncJob(syncedFolderID: Long) {
syncedFolderID: Long
) {
val arguments = Data.Builder() val arguments = Data.Builder()
.putLong(FilesSyncWork.SYNCED_FOLDER_ID, syncedFolderID) .putLong(FilesSyncWork.SYNCED_FOLDER_ID, syncedFolderID)
.build() .build()

View file

@ -250,7 +250,8 @@ class FilesSyncWork(
localPaths, localPaths,
remotePaths, remotePaths,
uploadAction!!, uploadAction!!,
true, // create parent folder if not existent // create parent folder if not existent
true,
UploadFileOperation.CREATED_AS_INSTANT_PICTURE, UploadFileOperation.CREATED_AS_INSTANT_PICTURE,
needsWifi, needsWifi,
needsCharging, needsCharging,

View file

@ -8,5 +8,6 @@
package com.nextcloud.client.jobs.download package com.nextcloud.client.jobs.download
enum class FileDownloadError { enum class FileDownloadError {
Failed, Cancelled Failed,
Cancelled
} }

View file

@ -81,11 +81,7 @@ class FileDownloadHelper {
backgroundJobManager.cancelFilesDownloadJob(currentUser, currentFile.fileId) backgroundJobManager.cancelFilesDownloadJob(currentUser, currentFile.fileId)
} }
fun saveFile( fun saveFile(file: OCFile, currentDownload: DownloadFileOperation?, storageManager: FileDataStorageManager?) {
file: OCFile,
currentDownload: DownloadFileOperation?,
storageManager: FileDataStorageManager?
) {
val syncDate = System.currentTimeMillis() val syncDate = System.currentTimeMillis()
file.apply { file.apply {

View file

@ -22,10 +22,7 @@ import com.owncloud.android.ui.preview.PreviewImageFragment
class FileDownloadIntents(private val context: Context) { class FileDownloadIntents(private val context: Context) {
fun newDownloadIntent( fun newDownloadIntent(download: DownloadFileOperation, linkedToRemotePath: String): Intent {
download: DownloadFileOperation,
linkedToRemotePath: String
): Intent {
return Intent(FileDownloadWorker.getDownloadAddedMessage()).apply { return Intent(FileDownloadWorker.getDownloadAddedMessage()).apply {
putExtra(FileDownloadWorker.EXTRA_ACCOUNT_NAME, download.user.accountName) putExtra(FileDownloadWorker.EXTRA_ACCOUNT_NAME, download.user.accountName)
putExtra(FileDownloadWorker.EXTRA_REMOTE_PATH, download.remotePath) putExtra(FileDownloadWorker.EXTRA_REMOTE_PATH, download.remotePath)

View file

@ -369,10 +369,7 @@ class FileDownloadWorker(
notificationManager.showNewNotification(text) notificationManager.showNewNotification(text)
} }
private fun notifyDownloadResult( private fun notifyDownloadResult(download: DownloadFileOperation, downloadResult: RemoteOperationResult<*>) {
download: DownloadFileOperation,
downloadResult: RemoteOperationResult<*>
) {
if (downloadResult.isCancelled) { if (downloadResult.isCancelled) {
return return
} }

View file

@ -282,17 +282,11 @@ class FileUploadHelper {
cancelAndRestartUploadJob(accountManager.getUser(accountName).get()) cancelAndRestartUploadJob(accountManager.getUser(accountName).get())
} }
fun addUploadTransferProgressListener( fun addUploadTransferProgressListener(listener: OnDatatransferProgressListener, targetKey: String) {
listener: OnDatatransferProgressListener,
targetKey: String
) {
mBoundListeners[targetKey] = listener mBoundListeners[targetKey] = listener
} }
fun removeUploadTransferProgressListener( fun removeUploadTransferProgressListener(listener: OnDatatransferProgressListener, targetKey: String) {
listener: OnDatatransferProgressListener,
targetKey: String
) {
if (mBoundListeners[targetKey] === listener) { if (mBoundListeners[targetKey] === listener) {
mBoundListeners.remove(targetKey) mBoundListeners.remove(targetKey)
} }

View file

@ -269,7 +269,10 @@ class FileUploadWorker(
// Only notify if it is not same file on remote that causes conflict // Only notify if it is not same file on remote that causes conflict
if (uploadResult.code == ResultCode.SYNC_CONFLICT && FileUploadHelper().isSameFileOnRemote( if (uploadResult.code == ResultCode.SYNC_CONFLICT && FileUploadHelper().isSameFileOnRemote(
uploadFileOperation.user, File(uploadFileOperation.storagePath), uploadFileOperation.remotePath, context uploadFileOperation.user,
File(uploadFileOperation.storagePath),
uploadFileOperation.remotePath,
context
) )
) { ) {
context.showToast(R.string.file_upload_worker_same_file_already_exists) context.showToast(R.string.file_upload_worker_same_file_already_exists)

View file

@ -329,7 +329,7 @@ public final class AppPreferencesImpl implements AppPreferences {
userAccountManager.getUser(), userAccountManager.getUser(),
PREF__FOLDER_SORT_ORDER, PREF__FOLDER_SORT_ORDER,
folder, folder,
FileSortOrder.sort_a_to_z.name)); FileSortOrder.SORT_A_TO_Z.name));
} }
@Override @Override
@ -343,7 +343,7 @@ public final class AppPreferencesImpl implements AppPreferences {
@Override @Override
public FileSortOrder getSortOrderByType(FileSortOrder.Type type) { public FileSortOrder getSortOrderByType(FileSortOrder.Type type) {
return getSortOrderByType(type, FileSortOrder.sort_a_to_z); return getSortOrderByType(type, FileSortOrder.SORT_A_TO_Z);
} }
@Override @Override

View file

@ -11,5 +11,7 @@
package com.nextcloud.client.preferences package com.nextcloud.client.preferences
enum class SubFolderRule { enum class SubFolderRule {
YEAR_MONTH, YEAR, YEAR_MONTH_DAY YEAR_MONTH,
YEAR,
YEAR_MONTH_DAY
} }

View file

@ -15,23 +15,20 @@ import com.owncloud.android.datamodel.OCFile
object IntentUtil { object IntentUtil {
@JvmStatic @JvmStatic
public fun createSendIntent(context: Context, file: OCFile): Intent = public fun createSendIntent(context: Context, file: OCFile): Intent = createBaseSendFileIntent().apply {
createBaseSendFileIntent().apply {
action = Intent.ACTION_SEND action = Intent.ACTION_SEND
type = file.mimeType type = file.mimeType
putExtra(Intent.EXTRA_STREAM, file.getExposedFileUri(context)) putExtra(Intent.EXTRA_STREAM, file.getExposedFileUri(context))
} }
@JvmStatic @JvmStatic
public fun createSendIntent(context: Context, files: Array<OCFile>): Intent = public fun createSendIntent(context: Context, files: Array<OCFile>): Intent = createBaseSendFileIntent().apply {
createBaseSendFileIntent().apply {
action = Intent.ACTION_SEND_MULTIPLE action = Intent.ACTION_SEND_MULTIPLE
type = getUniqueMimetype(files) type = getUniqueMimetype(files)
putParcelableArrayListExtra(Intent.EXTRA_STREAM, getExposedFileUris(context, files)) putParcelableArrayListExtra(Intent.EXTRA_STREAM, getExposedFileUris(context, files))
} }
private fun createBaseSendFileIntent(): Intent = private fun createBaseSendFileIntent(): Intent = Intent().apply {
Intent().apply {
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
} }

View file

@ -6,7 +6,6 @@
* *
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only * SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
*/ */
package com.nextcloud.ui package com.nextcloud.ui
import android.annotation.SuppressLint import android.annotation.SuppressLint
@ -55,7 +54,7 @@ class ChooseAccountDialogFragment :
private var currentStatus: Status? = null private var currentStatus: Status? = null
private var _binding: DialogChooseAccountBinding? = null private var _binding: DialogChooseAccountBinding? = null
private val binding get() = _binding!! val binding get() = _binding!!
@Inject @Inject
lateinit var clientFactory: ClientFactory lateinit var clientFactory: ClientFactory
@ -187,8 +186,7 @@ class ChooseAccountDialogFragment :
*/ */
companion object { companion object {
@JvmStatic @JvmStatic
fun newInstance(user: User) = fun newInstance(user: User) = ChooseAccountDialogFragment().apply {
ChooseAccountDialogFragment().apply {
arguments = Bundle().apply { arguments = Bundle().apply {
putParcelable(ARG_CURRENT_USER_PARAM, user) putParcelable(ARG_CURRENT_USER_PARAM, user)
} }

View file

@ -93,7 +93,8 @@ class ImageDetailFragment : Fragment(), Injectable {
} }
nominatimClient = NominatimClient( nominatimClient = NominatimClient(
getString(R.string.osm_geocoder_url), getString(R.string.osm_geocoder_contact) getString(R.string.osm_geocoder_url),
getString(R.string.osm_geocoder_contact)
) )
return binding.root return binding.root

View file

@ -37,11 +37,7 @@ import kotlinx.coroutines.launch
@SuppressLint("ResourceAsColor") @SuppressLint("ResourceAsColor")
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun MoreActionsBottomSheet( fun MoreActionsBottomSheet(title: String? = null, actions: List<Triple<Int, Int, () -> Unit>>, dismiss: () -> Unit) {
title: String? = null,
actions: List<Triple<Int, Int, () -> Unit>>,
dismiss: () -> Unit
) {
val sheetState = rememberModalBottomSheetState() val sheetState = rememberModalBottomSheetState()
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()

View file

@ -67,7 +67,7 @@ class FileActionsBottomSheet : BottomSheetDialogFragment(), Injectable {
private lateinit var viewModel: FileActionsViewModel private lateinit var viewModel: FileActionsViewModel
private var _binding: FileActionsBottomSheetBinding? = null private var _binding: FileActionsBottomSheetBinding? = null
private val binding val binding
get() = _binding!! get() = _binding!!
private lateinit var componentsGetter: ComponentsGetter private lateinit var componentsGetter: ComponentsGetter
@ -99,9 +99,7 @@ class FileActionsBottomSheet : BottomSheetDialogFragment(), Injectable {
return binding.root return binding.root
} }
private fun handleState( private fun handleState(state: FileActionsViewModel.UiState) {
state: FileActionsViewModel.UiState
) {
toggleLoadingOrContent(state) toggleLoadingOrContent(state)
when (state) { when (state) {
is FileActionsViewModel.UiState.LoadedForSingleFile -> { is FileActionsViewModel.UiState.LoadedForSingleFile -> {
@ -192,9 +190,7 @@ class FileActionsBottomSheet : BottomSheetDialogFragment(), Injectable {
} }
} }
private fun displayActions( private fun displayActions(actions: List<FileAction>) {
actions: List<FileAction>
) {
if (binding.fileActionsList.isEmpty()) { if (binding.fileActionsList.isEmpty()) {
actions.forEach { action -> actions.forEach { action ->
val view = inflateActionView(action) val view = inflateActionView(action)

View file

@ -54,10 +54,7 @@ class FileActionsViewModel @Inject constructor(
@IdRes @IdRes
get() = _clickActionId get() = _clickActionId
fun load( fun load(arguments: Bundle, componentsGetter: ComponentsGetter) {
arguments: Bundle,
componentsGetter: ComponentsGetter
) {
val files: List<OCFile>? = arguments.getParcelableArrayList(ARG_FILES) val files: List<OCFile>? = arguments.getParcelableArrayList(ARG_FILES)
val numberOfAllFiles: Int = arguments.getInt(ARG_ALL_FILES_COUNT, 1) val numberOfAllFiles: Int = arguments.getInt(ARG_ALL_FILES_COUNT, 1)
val isOverflow = arguments.getBoolean(ARG_IS_OVERFLOW, false) val isOverflow = arguments.getBoolean(ARG_IS_OVERFLOW, false)
@ -104,17 +101,11 @@ class FileActionsViewModel @Inject constructor(
.getToHide(inSingleFileFragment) .getToHide(inSingleFileFragment)
} }
private fun getActionsToShow( private fun getActionsToShow(additionalFilter: IntArray?, toHide: List<Int>) = FileAction.SORTED_VALUES
additionalFilter: IntArray?,
toHide: List<Int>
) = FileAction.SORTED_VALUES
.filter { additionalFilter == null || it.id !in additionalFilter } .filter { additionalFilter == null || it.id !in additionalFilter }
.filter { it.id !in toHide } .filter { it.id !in toHide }
private fun updateStateLoaded( private fun updateStateLoaded(files: Collection<OCFile>, availableActions: List<FileAction>) {
files: Collection<OCFile>,
availableActions: List<FileAction>
) {
val state: UiState = when (files.size) { val state: UiState = when (files.size) {
1 -> { 1 -> {
val file = files.first() val file = files.first()

View file

@ -14,7 +14,7 @@ import com.owncloud.android.lib.common.utils.Log_OC
import java.io.Serializable import java.io.Serializable
@Suppress("TopLevelPropertyNaming") @Suppress("TopLevelPropertyNaming")
private const val tag = "BundleExtension" private const val TAG = "BundleExtension"
fun <T : Serializable?> Bundle?.getSerializableArgument(key: String, type: Class<T>): T? { fun <T : Serializable?> Bundle?.getSerializableArgument(key: String, type: Class<T>): T? {
if (this == null) { if (this == null) {
@ -33,7 +33,7 @@ fun <T : Serializable?> Bundle?.getSerializableArgument(key: String, type: Class
} }
} }
} catch (e: ClassCastException) { } catch (e: ClassCastException) {
Log_OC.e(tag, e.localizedMessage) Log_OC.e(TAG, e.localizedMessage)
null null
} }
} }
@ -51,7 +51,7 @@ fun <T : Parcelable?> Bundle?.getParcelableArgument(key: String, type: Class<T>)
this.getParcelable(key) this.getParcelable(key)
} }
} catch (e: ClassCastException) { } catch (e: ClassCastException) {
Log_OC.e(tag, e.localizedMessage) Log_OC.e(TAG, e.localizedMessage)
e.printStackTrace() e.printStackTrace()
null null
} }

View file

@ -14,7 +14,7 @@ import com.owncloud.android.lib.common.utils.Log_OC
import java.io.Serializable import java.io.Serializable
@Suppress("TopLevelPropertyNaming") @Suppress("TopLevelPropertyNaming")
private const val tag = "IntentExtension" private const val TAG = "IntentExtension"
fun <T : Serializable?> Intent?.getSerializableArgument(key: String, type: Class<T>): T? { fun <T : Serializable?> Intent?.getSerializableArgument(key: String, type: Class<T>): T? {
if (this == null) { if (this == null) {
@ -33,7 +33,7 @@ fun <T : Serializable?> Intent?.getSerializableArgument(key: String, type: Class
} }
} }
} catch (e: ClassCastException) { } catch (e: ClassCastException) {
Log_OC.e(tag, e.localizedMessage) Log_OC.e(TAG, e.localizedMessage)
null null
} }
} }
@ -51,7 +51,7 @@ fun <T : Parcelable?> Intent?.getParcelableArgument(key: String, type: Class<T>)
this.getParcelableExtra(key) this.getParcelableExtra(key)
} }
} catch (e: ClassCastException) { } catch (e: ClassCastException) {
Log_OC.e(tag, e.localizedMessage) Log_OC.e(TAG, e.localizedMessage)
null null
} }
} }

View file

@ -10,7 +10,5 @@ package com.nextcloud.utils.extensions
import com.owncloud.android.lib.common.network.OnDatatransferProgressListener import com.owncloud.android.lib.common.network.OnDatatransferProgressListener
@Suppress("MagicNumber") @Suppress("MagicNumber")
fun OnDatatransferProgressListener.getPercent( fun OnDatatransferProgressListener.getPercent(totalTransferredSoFar: Long, totalToTransfer: Long): Int =
totalTransferredSoFar: Long, ((100.0 * totalTransferredSoFar.toDouble() / totalToTransfer.toDouble()).toInt()).coerceAtMost(100)
totalToTransfer: Long
): Int = ((100.0 * totalTransferredSoFar.toDouble() / totalToTransfer.toDouble()).toInt()).coerceAtMost(100)

View file

@ -17,10 +17,7 @@ import javax.inject.Inject
class FastScrollUtils @Inject constructor(private val viewThemeUtils: ViewThemeUtils) { class FastScrollUtils @Inject constructor(private val viewThemeUtils: ViewThemeUtils) {
@JvmOverloads @JvmOverloads
fun applyFastScroll( fun applyFastScroll(recyclerView: RecyclerView, viewHelper: FastScroller.ViewHelper? = null) {
recyclerView: RecyclerView,
viewHelper: FastScroller.ViewHelper? = null
) {
val builder = val builder =
FastScrollerBuilder(recyclerView).let { FastScrollerBuilder(recyclerView).let {
viewThemeUtils.files.themeFastScrollerBuilder( viewThemeUtils.files.themeFastScrollerBuilder(

View file

@ -33,7 +33,8 @@ class DeepLinkLoginActivity : AuthenticatorActivity(), Injectable {
val loginUrlInfo = parseLoginDataUrl(prefix, it.toString()) val loginUrlInfo = parseLoginDataUrl(prefix, it.toString())
val loginText = findViewById<TextView>(R.id.loginInfo) val loginText = findViewById<TextView>(R.id.loginInfo)
loginText.text = String.format( loginText.text = String.format(
getString(R.string.direct_login_text), loginUrlInfo.username, getString(R.string.direct_login_text),
loginUrlInfo.username,
loginUrlInfo.serverAddress loginUrlInfo.serverAddress
) )
} catch (e: IllegalArgumentException) { } catch (e: IllegalArgumentException) {

View file

@ -18,7 +18,8 @@ import androidx.annotation.RequiresApi
* This wrapper is designed for compatibility on those versions. * This wrapper is designed for compatibility on those versions.
*/ */
enum class ForegroundServiceType { enum class ForegroundServiceType {
DataSync, MediaPlayback; DataSync,
MediaPlayback;
@RequiresApi(Build.VERSION_CODES.Q) @RequiresApi(Build.VERSION_CODES.Q)
fun getId(): Int { fun getId(): Int {

View file

@ -12,7 +12,9 @@ import android.util.SparseArray
* Types of media folder. * Types of media folder.
*/ */
enum class MediaFolderType(@JvmField val id: Int) { enum class MediaFolderType(@JvmField val id: Int) {
CUSTOM(0), IMAGE(1), VIDEO(2); CUSTOM(0),
IMAGE(1),
VIDEO(2);
companion object { companion object {
private val reverseMap = SparseArray<MediaFolderType>(3) private val reverseMap = SparseArray<MediaFolderType>(3)

View file

@ -22,7 +22,10 @@ data class Template(
val extension: String val extension: String
) : Parcelable { ) : Parcelable {
enum class Type { enum class Type {
DOCUMENT, SPREADSHEET, PRESENTATION, UNKNOWN; DOCUMENT,
SPREADSHEET,
PRESENTATION,
UNKNOWN;
companion object { companion object {
@JvmStatic @JvmStatic

View file

@ -227,10 +227,20 @@ class MediaControlView(context: Context, attrs: AttributeSet?) :
context, context,
if (playerControl?.isPlaying == true) { if (playerControl?.isPlaying == true) {
R.drawable.ic_pause R.drawable.ic_pause
} else { R.drawable.ic_play } } else {
R.drawable.ic_play
}
) )
binding.forwardBtn.visibility = if (playerControl?.canSeekForward() == true) { VISIBLE } else { INVISIBLE } binding.forwardBtn.visibility = if (playerControl?.canSeekForward() == true) {
binding.rewindBtn.visibility = if (playerControl?.canSeekBackward() == true) { VISIBLE } else { INVISIBLE } VISIBLE
} else {
INVISIBLE
}
binding.rewindBtn.visibility = if (playerControl?.canSeekBackward() == true) {
VISIBLE
} else {
INVISIBLE
}
} }
private fun doPauseResume() { private fun doPauseResume() {

View file

@ -254,13 +254,7 @@ class ConflictsResolveActivity : FileActivity(), OnConflictDecisionMadeListener
private val TAG = ConflictsResolveActivity::class.java.simpleName private val TAG = ConflictsResolveActivity::class.java.simpleName
@JvmStatic @JvmStatic
fun createIntent( fun createIntent(file: OCFile?, user: User?, conflictUploadId: Long, flag: Int?, context: Context?): Intent {
file: OCFile?,
user: User?,
conflictUploadId: Long,
flag: Int?,
context: Context?
): Intent {
val intent = Intent(context, ConflictsResolveActivity::class.java) val intent = Intent(context, ConflictsResolveActivity::class.java)
if (flag != null) { if (flag != null) {
intent.flags = intent.flags or flag intent.flags = intent.flags or flag

View file

@ -475,10 +475,7 @@ open class FolderPickerActivity :
* @param operation Creation operation performed. * @param operation Creation operation performed.
* @param result Result of the creation. * @param result Result of the creation.
*/ */
private fun onCreateFolderOperationFinish( private fun onCreateFolderOperationFinish(operation: CreateFolderOperation, result: RemoteOperationResult<*>) {
operation: CreateFolderOperation,
result: RemoteOperationResult<*>
) {
if (result.isSuccess) { if (result.isSuccess) {
val fileListFragment = listOfFilesFragment val fileListFragment = listOfFilesFragment
fileListFragment?.onItemClicked(storageManager.getFileByPath(operation.remotePath)) fileListFragment?.onItemClicked(storageManager.getFileByPath(operation.remotePath))

View file

@ -343,11 +343,7 @@ class NotificationsActivity : DrawerActivity(), NotificationsContract.View {
} }
} }
override fun onActionCallback( override fun onActionCallback(isSuccess: Boolean, notification: Notification, holder: NotificationViewHolder) {
isSuccess: Boolean,
notification: Notification,
holder: NotificationViewHolder
) {
if (isSuccess) { if (isSuccess) {
adapter?.removeNotification(holder) adapter?.removeNotification(holder)
} else { } else {

View file

@ -801,11 +801,7 @@ class SyncedFoldersActivity :
item.setExcludeHidden(excludeHidden) item.setExcludeHidden(excludeHidden)
} }
override fun onRequestPermissionsResult( override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
when (requestCode) { when (requestCode) {
PermissionUtil.PERMISSIONS_EXTERNAL_STORAGE -> { PermissionUtil.PERMISSIONS_EXTERNAL_STORAGE -> {
// If request is cancelled, result arrays are empty. // If request is cancelled, result arrays are empty.

View file

@ -83,7 +83,7 @@ public class TrashbinListAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
files.addAll(trashbinFiles); files.addAll(trashbinFiles);
files = preferences.getSortOrderByType(FileSortOrder.Type.trashBinView, files = preferences.getSortOrderByType(FileSortOrder.Type.trashBinView,
FileSortOrder.sort_new_to_old).sortTrashbinFiles(files); FileSortOrder.SORT_NEW_TO_OLD).sortTrashbinFiles(files);
notifyDataSetChanged(); notifyDataSetChanged();
} }

View file

@ -78,10 +78,7 @@ class UnifiedSearchItemViewHolder(
binding.unifiedSearchItemLayout.setOnClickListener { listInterface.onSearchResultClicked(entry) } binding.unifiedSearchItemLayout.setOnClickListener { listInterface.onSearchResultClicked(entry) }
} }
private fun getPlaceholder( private fun getPlaceholder(entry: SearchResultEntry, mimetype: String?): Drawable {
entry: SearchResultEntry,
mimetype: String?
): Drawable {
val drawable = with(entry.icon) { val drawable = with(entry.icon) {
when { when {
equals("icon-folder") -> equals("icon-folder") ->

View file

@ -40,7 +40,7 @@ class AccountRemovalDialog : DialogFragment(), AvatarGenerationListener, Injecta
private var user: User? = null private var user: User? = null
private lateinit var alertDialog: AlertDialog private lateinit var alertDialog: AlertDialog
private var _binding: AccountRemovalDialogBinding? = null private var _binding: AccountRemovalDialogBinding? = null
private val binding get() = _binding!! val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)

View file

@ -80,11 +80,13 @@ class ChooseTemplateDialogFragment : DialogFragment(), View.OnClickListener, Tem
private var creator: Creator? = null private var creator: Creator? = null
enum class Type { enum class Type {
DOCUMENT, SPREADSHEET, PRESENTATION DOCUMENT,
SPREADSHEET,
PRESENTATION
} }
private var _binding: ChooseTemplateBinding? = null private var _binding: ChooseTemplateBinding? = null
private val binding get() = _binding!! val binding get() = _binding!!
override fun onStart() { override fun onStart() {
super.onStart() super.onStart()

View file

@ -52,11 +52,7 @@ class SendFilesDialog : BottomSheetDialogFragment(R.layout.send_files_fragment),
} }
} }
override fun onCreateView( override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = SendFilesFragmentBinding.inflate(inflater, container, false) binding = SendFilesFragmentBinding.inflate(inflater, container, false)
setupSendButtonRecyclerView() setupSendButtonRecyclerView()
@ -102,7 +98,8 @@ class SendFilesDialog : BottomSheetDialogFragment(R.layout.send_files_fragment),
icon = match.loadIcon(requireActivity().packageManager) icon = match.loadIcon(requireActivity().packageManager)
label = match.loadLabel(requireActivity().packageManager) label = match.loadLabel(requireActivity().packageManager)
sendButtonData = SendButtonData( sendButtonData = SendButtonData(
icon, label, icon,
label,
match.activityInfo.packageName, match.activityInfo.packageName,
match.activityInfo.name match.activityInfo.name
) )

View file

@ -200,7 +200,8 @@ class SendShareDialog : BottomSheetDialogFragment(R.layout.send_share_fragment),
icon = match.loadIcon(requireActivity().packageManager) icon = match.loadIcon(requireActivity().packageManager)
label = match.loadLabel(requireActivity().packageManager) label = match.loadLabel(requireActivity().packageManager)
sendButtonData = SendButtonData( sendButtonData = SendButtonData(
icon, label, icon,
label,
match.activityInfo.packageName, match.activityInfo.packageName,
match.activityInfo.name match.activityInfo.name
) )

View file

@ -41,7 +41,7 @@ class SortingOrderDialogFragment : DialogFragment(), Injectable {
retainInstance = true retainInstance = true
binding = null binding = null
currentSortOrderName = requireArguments().getString(KEY_SORT_ORDER, FileSortOrder.sort_a_to_z.name) currentSortOrderName = requireArguments().getString(KEY_SORT_ORDER, FileSortOrder.SORT_A_TO_Z.name)
} }
/** /**
@ -51,12 +51,12 @@ class SortingOrderDialogFragment : DialogFragment(), Injectable {
*/ */
private fun setupDialogElements(binding: SortingOrderFragmentBinding) { private fun setupDialogElements(binding: SortingOrderFragmentBinding) {
val bindings = listOf( val bindings = listOf(
binding.sortByNameAscending to FileSortOrder.sort_a_to_z, binding.sortByNameAscending to FileSortOrder.SORT_A_TO_Z,
binding.sortByNameDescending to FileSortOrder.sort_z_to_a, binding.sortByNameDescending to FileSortOrder.SORT_Z_TO_A,
binding.sortByModificationDateAscending to FileSortOrder.sort_old_to_new, binding.sortByModificationDateAscending to FileSortOrder.SORT_OLD_TO_NEW,
binding.sortByModificationDateDescending to FileSortOrder.sort_new_to_old, binding.sortByModificationDateDescending to FileSortOrder.SORT_NEW_TO_OLD,
binding.sortBySizeAscending to FileSortOrder.sort_small_to_big, binding.sortBySizeAscending to FileSortOrder.SORT_SMALL_TO_BIG,
binding.sortBySizeDescending to FileSortOrder.sort_big_to_small binding.sortBySizeDescending to FileSortOrder.SORT_BIG_TO_SMALL
) )
bindings.forEach { (view, sortOrder) -> bindings.forEach { (view, sortOrder) ->

View file

@ -97,7 +97,9 @@ class StoragePermissionDialogFragment : DialogFragment(), Injectable {
@Parcelize @Parcelize
enum class Result : Parcelable { enum class Result : Parcelable {
CANCEL, FULL_ACCESS, MEDIA_READ_ONLY CANCEL,
FULL_ACCESS,
MEDIA_READ_ONLY
} }
companion object { companion object {

View file

@ -274,17 +274,17 @@ class SyncedFolderPreferencesDialogFragment : DialogFragment(), Injectable {
private fun checkWritableFolder() { private fun checkWritableFolder() {
if (!syncedFolder!!.isEnabled) { if (!syncedFolder!!.isEnabled) {
binding?.settingInstantBehaviourContainer?.isEnabled = false binding?.settingInstantBehaviourContainer?.isEnabled = false
binding?.settingInstantBehaviourContainer?.alpha = alphaDisabled binding?.settingInstantBehaviourContainer?.alpha = ALPHA_DISABLED
return return
} }
if (syncedFolder!!.localPath != null && File(syncedFolder!!.localPath).canWrite()) { if (syncedFolder!!.localPath != null && File(syncedFolder!!.localPath).canWrite()) {
binding?.settingInstantBehaviourContainer?.isEnabled = true binding?.settingInstantBehaviourContainer?.isEnabled = true
binding?.settingInstantBehaviourContainer?.alpha = alphaEnabled binding?.settingInstantBehaviourContainer?.alpha = ALPHA_ENABLED
binding?.settingInstantBehaviourSummary?.text = binding?.settingInstantBehaviourSummary?.text =
uploadBehaviorItemStrings[syncedFolder!!.uploadActionInteger] uploadBehaviorItemStrings[syncedFolder!!.uploadActionInteger]
} else { } else {
binding?.settingInstantBehaviourContainer?.isEnabled = false binding?.settingInstantBehaviourContainer?.isEnabled = false
binding?.settingInstantBehaviourContainer?.alpha = alphaDisabled binding?.settingInstantBehaviourContainer?.alpha = ALPHA_DISABLED
syncedFolder?.setUploadAction( syncedFolder?.setUploadAction(
resources.getTextArray(R.array.pref_behaviour_entryValues)[0].toString() resources.getTextArray(R.array.pref_behaviour_entryValues)[0].toString()
) )
@ -294,9 +294,9 @@ class SyncedFolderPreferencesDialogFragment : DialogFragment(), Injectable {
private fun setupViews(optionalBinding: SyncedFoldersSettingsLayoutBinding?, enable: Boolean) { private fun setupViews(optionalBinding: SyncedFoldersSettingsLayoutBinding?, enable: Boolean) {
val alpha: Float = if (enable) { val alpha: Float = if (enable) {
alphaEnabled ALPHA_ENABLED
} else { } else {
alphaDisabled ALPHA_DISABLED
} }
optionalBinding?.let { binding -> optionalBinding?.let { binding ->
@ -518,8 +518,8 @@ class SyncedFolderPreferencesDialogFragment : DialogFragment(), Injectable {
private val TAG = SyncedFolderPreferencesDialogFragment::class.java.simpleName private val TAG = SyncedFolderPreferencesDialogFragment::class.java.simpleName
private const val BEHAVIOUR_DIALOG_STATE = "BEHAVIOUR_DIALOG_STATE" 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 NAME_COLLISION_POLICY_DIALOG_STATE = "NAME_COLLISION_POLICY_DIALOG_STATE"
private const val alphaEnabled = 1.0f private const val ALPHA_ENABLED = 1.0f
private const val alphaDisabled = 0.7f private const val ALPHA_DISABLED = 0.7f
@JvmStatic @JvmStatic
fun newInstance(syncedFolder: SyncedFolderDisplayItem?, section: Int): SyncedFolderPreferencesDialogFragment? { fun newInstance(syncedFolder: SyncedFolderDisplayItem?, section: Int): SyncedFolderPreferencesDialogFragment? {

View file

@ -91,8 +91,12 @@ class FileDetailsSharingProcessFragment :
* fragment instance to be called while modifying existing share information * fragment instance to be called while modifying existing share information
*/ */
@JvmStatic @JvmStatic
fun newInstance(share: OCShare, screenType: Int, isReshareShown: Boolean, isExpirationDateShown: Boolean): fun newInstance(
FileDetailsSharingProcessFragment { share: OCShare,
screenType: Int,
isReshareShown: Boolean,
isExpirationDateShown: Boolean
): FileDetailsSharingProcessFragment {
val args = Bundle() val args = Bundle()
args.putParcelable(ARG_OCSHARE, share) args.putParcelable(ARG_OCSHARE, share)
args.putInt(ARG_SCREEN_TYPE, screenType) args.putInt(ARG_SCREEN_TYPE, screenType)

View file

@ -40,7 +40,7 @@ class ProfileBottomSheetDialog(
private var _binding: ProfileBottomSheetFragmentBinding? = null private var _binding: ProfileBottomSheetFragmentBinding? = null
// This property is only valid between onCreateView and onDestroyView. // This property is only valid between onCreateView and onDestroyView.
private val binding get() = _binding!! val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)

View file

@ -59,7 +59,7 @@ class UnifiedSearchFragment :
UnifiedSearchItemViewHolder.FilesAction { UnifiedSearchItemViewHolder.FilesAction {
private lateinit var adapter: UnifiedSearchListAdapter private lateinit var adapter: UnifiedSearchListAdapter
private var _binding: ListFragmentBinding? = null private var _binding: ListFragmentBinding? = null
private val binding get() = _binding!! val binding get() = _binding!!
private var searchView: SearchView? = null private var searchView: SearchView? = null
lateinit var vm: IUnifiedSearchViewModel lateinit var vm: IUnifiedSearchViewModel

View file

@ -53,7 +53,11 @@ class UriUploader(
) { ) {
enum class UriUploaderResultCode { enum class UriUploaderResultCode {
OK, ERROR_UNKNOWN, ERROR_NO_FILE_TO_UPLOAD, ERROR_READ_PERMISSION_NOT_GRANTED, ERROR_SENSITIVE_PATH OK,
ERROR_UNKNOWN,
ERROR_NO_FILE_TO_UPLOAD,
ERROR_READ_PERMISSION_NOT_GRANTED,
ERROR_SENSITIVE_PATH
} }
fun uploadUris(): UriUploaderResultCode { fun uploadUris(): UriUploaderResultCode {
@ -121,11 +125,12 @@ class UriUploader(
arrayOf(localPath ?: ""), arrayOf(localPath ?: ""),
arrayOf(remotePath), arrayOf(remotePath),
mBehaviour, mBehaviour,
false, // do not create parent folder if not existent // do not create parent folder if not existent
false,
UploadFileOperation.CREATED_BY_USER, UploadFileOperation.CREATED_BY_USER,
false, requiresWifi = false,
false, requiresCharging = false,
NameCollisionPolicy.ASK_USER nameCollisionPolicy = NameCollisionPolicy.ASK_USER
) )
} }

View file

@ -86,7 +86,7 @@ class PreviewPdfFragment : Fragment(), Injectable {
requireContext().startActivity(intent) requireContext().startActivity(intent)
} }
} }
viewModel.shouldShowZoomTip.observe(viewLifecycleOwner) { shouldShow -> viewModel.showZoomTip.observe(viewLifecycleOwner) { shouldShow ->
if (shouldShow) { if (shouldShow) {
snack = DisplayUtils.showSnackMessage(binding.root, R.string.pdf_zoom_tip) snack = DisplayUtils.showSnackMessage(binding.root, R.string.pdf_zoom_tip)
viewModel.onZoomTipShown() viewModel.onZoomTipShown()
@ -100,8 +100,7 @@ class PreviewPdfFragment : Fragment(), Injectable {
setHasOptionsMenu(true) setHasOptionsMenu(true)
} }
private fun getScreenWidth(): Int = private fun getScreenWidth(): Int = requireContext().resources.displayMetrics.widthPixels
requireContext().resources.displayMetrics.widthPixels
override fun onPrepareOptionsMenu(menu: Menu) { override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu) super.onPrepareOptionsMenu(menu)

View file

@ -36,7 +36,7 @@ class PreviewPdfViewModel @Inject constructor(val appPreferences: AppPreferences
get() = _previewImagePath get() = _previewImagePath
private var _showZoomTip = MutableLiveData<Boolean>() private var _showZoomTip = MutableLiveData<Boolean>()
val shouldShowZoomTip: LiveData<Boolean> val showZoomTip: LiveData<Boolean>
get() = _showZoomTip get() = _showZoomTip
override fun onCleared() { override fun onCleared() {

View file

@ -159,7 +159,7 @@ class TrashbinActivity :
supportFragmentManager, supportFragmentManager,
preferences?.getSortOrderByType( preferences?.getSortOrderByType(
FileSortOrder.Type.trashBinView, FileSortOrder.Type.trashBinView,
FileSortOrder.sort_new_to_old FileSortOrder.SORT_NEW_TO_OLD
) )
) )
} }
@ -247,10 +247,10 @@ class TrashbinActivity :
onBackPressedCallback.isEnabled = !isRoot onBackPressedCallback.isEnabled = !isRoot
} }
override fun onSortingOrderChosen(sortOrder: FileSortOrder?) { override fun onSortingOrderChosen(selection: FileSortOrder?) {
val sortButton = findViewById<TextView>(R.id.sort_button) val sortButton = findViewById<TextView>(R.id.sort_button)
sortButton.setText(DisplayUtils.getSortOrderStringId(sortOrder)) sortButton.setText(DisplayUtils.getSortOrderStringId(selection))
trashbinListAdapter?.setSortOrder(sortOrder) trashbinListAdapter?.setSortOrder(selection)
} }
override fun showTrashbinFolder(trashbinFiles: List<TrashbinFile?>?) { override fun showTrashbinFolder(trashbinFiles: List<TrashbinFile?>?) {

View file

@ -110,12 +110,12 @@ import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction; import androidx.fragment.app.FragmentTransaction;
import static com.owncloud.android.ui.dialog.SortingOrderDialogFragment.SORTING_ORDER_FRAGMENT; import static com.owncloud.android.ui.dialog.SortingOrderDialogFragment.SORTING_ORDER_FRAGMENT;
import static com.owncloud.android.utils.FileSortOrder.sort_a_to_z_id; import static com.owncloud.android.utils.FileSortOrder.SORT_A_TO_Z_ID;
import static com.owncloud.android.utils.FileSortOrder.sort_big_to_small_id; import static com.owncloud.android.utils.FileSortOrder.SORT_BIG_TO_SMALL_ID;
import static com.owncloud.android.utils.FileSortOrder.sort_new_to_old_id; import static com.owncloud.android.utils.FileSortOrder.SORT_NEW_TO_OLD_ID;
import static com.owncloud.android.utils.FileSortOrder.sort_old_to_new_id; import static com.owncloud.android.utils.FileSortOrder.SORT_OLD_TO_NEW_ID;
import static com.owncloud.android.utils.FileSortOrder.sort_small_to_big_id; import static com.owncloud.android.utils.FileSortOrder.SORT_SMALL_TO_BIG_ID;
import static com.owncloud.android.utils.FileSortOrder.sort_z_to_a_id; import static com.owncloud.android.utils.FileSortOrder.SORT_Z_TO_A_ID;
/** /**
* A helper class for UI/display related operations. * A helper class for UI/display related operations.
@ -819,17 +819,17 @@ public final class DisplayUtils {
public static @StringRes int getSortOrderStringId(FileSortOrder sortOrder) { public static @StringRes int getSortOrderStringId(FileSortOrder sortOrder) {
switch (sortOrder.name) { switch (sortOrder.name) {
case sort_z_to_a_id: case SORT_Z_TO_A_ID:
return R.string.menu_item_sort_by_name_z_a; return R.string.menu_item_sort_by_name_z_a;
case sort_new_to_old_id: case SORT_NEW_TO_OLD_ID:
return R.string.menu_item_sort_by_date_newest_first; return R.string.menu_item_sort_by_date_newest_first;
case sort_old_to_new_id: case SORT_OLD_TO_NEW_ID:
return R.string.menu_item_sort_by_date_oldest_first; return R.string.menu_item_sort_by_date_oldest_first;
case sort_big_to_small_id: case SORT_BIG_TO_SMALL_ID:
return R.string.menu_item_sort_by_size_biggest_first; return R.string.menu_item_sort_by_size_biggest_first;
case sort_small_to_big_id: case SORT_SMALL_TO_BIG_ID:
return R.string.menu_item_sort_by_size_smallest_first; return R.string.menu_item_sort_by_size_smallest_first;
case sort_a_to_z_id: case SORT_A_TO_Z_ID:
default: default:
return R.string.menu_item_sort_by_name_a_z; return R.string.menu_item_sort_by_name_a_z;
} }

View file

@ -196,7 +196,8 @@ class EncryptionUtilsV2 {
DecryptedFolderMetadataFile( DecryptedFolderMetadataFile(
decryptedMetadata, decryptedMetadata,
mutableListOf(), // subfolder do not store user array // subfolder do not store user array
mutableListOf(),
mutableMapOf() mutableMapOf()
) )
} else { } else {
@ -530,20 +531,13 @@ class EncryptionUtilsV2 {
} }
@Throws(IllegalStateException::class) @Throws(IllegalStateException::class)
fun removeFileFromMetadata( fun removeFileFromMetadata(fileName: String, metadata: DecryptedFolderMetadataFile) {
fileName: String,
metadata: DecryptedFolderMetadataFile
) {
metadata.metadata.files.remove(fileName) metadata.metadata.files.remove(fileName)
?: throw IllegalStateException("File $fileName not found in metadata!") ?: throw IllegalStateException("File $fileName not found in metadata!")
} }
@Throws(IllegalStateException::class) @Throws(IllegalStateException::class)
fun renameFile( fun renameFile(key: String, newName: String, metadataFile: DecryptedFolderMetadataFile) {
key: String,
newName: String,
metadataFile: DecryptedFolderMetadataFile
) {
if (!metadataFile.metadata.files.containsKey(key)) { if (!metadataFile.metadata.files.containsKey(key)) {
throw IllegalStateException("File with key $key not found in metadata!") throw IllegalStateException("File with key $key not found in metadata!")
} }
@ -956,7 +950,8 @@ class EncryptionUtilsV2 {
encryptedFolderMetadataFile: EncryptedFolderMetadataFile, encryptedFolderMetadataFile: EncryptedFolderMetadataFile,
decryptedFolderMetadataFile: DecryptedFolderMetadataFile, decryptedFolderMetadataFile: DecryptedFolderMetadataFile,
oldCounter: Long, oldCounter: Long,
ans: String // base 64 encoded BER // base 64 encoded BER
ans: String
) { ) {
// check counter // check counter
if (decryptedFolderMetadataFile.metadata.counter < oldCounter) { if (decryptedFolderMetadataFile.metadata.counter < oldCounter) {

View file

@ -25,13 +25,7 @@ import java.io.InputStream
class FileExportUtils { class FileExportUtils {
@Throws(IllegalStateException::class) @Throws(IllegalStateException::class)
fun exportFile( fun exportFile(fileName: String, mimeType: String, contentResolver: ContentResolver, ocFile: OCFile?, file: File?) {
fileName: String,
mimeType: String,
contentResolver: ContentResolver,
ocFile: OCFile?,
file: File?
) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
exportFileAndroid10AndAbove( exportFileAndroid10AndAbove(
fileName, fileName,

View file

@ -29,44 +29,46 @@ open class FileSortOrder(@JvmField var name: String, var isAscending: Boolean) {
} }
enum class SortType { enum class SortType {
SIZE, ALPHABET, DATE SIZE,
ALPHABET,
DATE
} }
companion object { companion object {
const val sort_a_to_z_id = "sort_a_to_z" const val SORT_A_TO_Z_ID = "sort_a_to_z"
const val sort_z_to_a_id = "sort_z_to_a" const val SORT_Z_TO_A_ID = "sort_z_to_a"
const val sort_old_to_new_id = "sort_old_to_new" const val SORT_OLD_TO_NEW_ID = "sort_old_to_new"
const val sort_new_to_old_id = "sort_new_to_old" const val SORT_NEW_TO_OLD_ID = "sort_new_to_old"
const val sort_small_to_big_id = "sort_small_to_big" const val SORT_SMALL_TO_BIG_ID = "sort_small_to_big"
const val sort_big_to_small_id = "sort_big_to_small" const val SORT_BIG_TO_SMALL_ID = "sort_big_to_small"
@JvmField @JvmField
val sort_a_to_z: FileSortOrder = FileSortOrderByName(sort_a_to_z_id, true) val SORT_A_TO_Z: FileSortOrder = FileSortOrderByName(SORT_A_TO_Z_ID, true)
@JvmField @JvmField
val sort_z_to_a: FileSortOrder = FileSortOrderByName(sort_z_to_a_id, false) val SORT_Z_TO_A: FileSortOrder = FileSortOrderByName(SORT_Z_TO_A_ID, false)
@JvmField @JvmField
val sort_old_to_new: FileSortOrder = FileSortOrderByDate(sort_old_to_new_id, true) val SORT_OLD_TO_NEW: FileSortOrder = FileSortOrderByDate(SORT_OLD_TO_NEW_ID, true)
@JvmField @JvmField
val sort_new_to_old: FileSortOrder = FileSortOrderByDate(sort_new_to_old_id, false) val SORT_NEW_TO_OLD: FileSortOrder = FileSortOrderByDate(SORT_NEW_TO_OLD_ID, false)
@JvmField @JvmField
val sort_small_to_big: FileSortOrder = FileSortOrderBySize(sort_small_to_big_id, true) val SORT_SMALL_TO_BIG: FileSortOrder = FileSortOrderBySize(SORT_SMALL_TO_BIG_ID, true)
@JvmField @JvmField
val sort_big_to_small: FileSortOrder = FileSortOrderBySize(sort_big_to_small_id, false) val SORT_BIG_TO_SMALL: FileSortOrder = FileSortOrderBySize(SORT_BIG_TO_SMALL_ID, false)
@JvmField @JvmField
val sortOrders: Map<String, FileSortOrder> = Collections.unmodifiableMap( val sortOrders: Map<String, FileSortOrder> = Collections.unmodifiableMap(
mapOf( mapOf(
sort_a_to_z.name to sort_a_to_z, SORT_A_TO_Z.name to SORT_A_TO_Z,
sort_z_to_a.name to sort_z_to_a, SORT_Z_TO_A.name to SORT_Z_TO_A,
sort_old_to_new.name to sort_old_to_new, SORT_OLD_TO_NEW.name to SORT_OLD_TO_NEW,
sort_new_to_old.name to sort_new_to_old, SORT_NEW_TO_OLD.name to SORT_NEW_TO_OLD,
sort_small_to_big.name to sort_small_to_big, SORT_SMALL_TO_BIG.name to SORT_SMALL_TO_BIG,
sort_big_to_small.name to sort_big_to_small SORT_BIG_TO_SMALL.name to SORT_BIG_TO_SMALL
) )
) )
@ -103,14 +105,14 @@ open class FileSortOrder(@JvmField var name: String, var isAscending: Boolean) {
open fun getType(): SortType { open fun getType(): SortType {
return when (name) { return when (name) {
sort_z_to_a_id, SORT_Z_TO_A_ID,
sort_a_to_z_id -> SortType.ALPHABET SORT_A_TO_Z_ID -> SortType.ALPHABET
sort_small_to_big_id, SORT_SMALL_TO_BIG_ID,
sort_big_to_small_id -> SortType.SIZE SORT_BIG_TO_SMALL_ID -> SortType.SIZE
sort_new_to_old_id, SORT_NEW_TO_OLD_ID,
sort_old_to_new_id -> SortType.DATE SORT_OLD_TO_NEW_ID -> SortType.DATE
else -> SortType.ALPHABET else -> SortType.ALPHABET
} }

View file

@ -108,9 +108,7 @@ class FilesSpecificViewThemeUtils @Inject constructor(
} }
} }
private fun getThumbDrawable( private fun getThumbDrawable(context: Context): Drawable {
context: Context
): Drawable {
val thumbDrawable = val thumbDrawable =
ResourcesCompat.getDrawable( ResourcesCompat.getDrawable(
context.resources, context.resources,

View file

@ -33,7 +33,7 @@ class OCFileSortTest {
fun testFileSortOrder() { fun testFileSortOrder() {
val toSort = getShuffledList() val toSort = getShuffledList()
FileSortOrder.sort_a_to_z.sortCloudFiles(toSort) FileSortOrder.SORT_A_TO_Z.sortCloudFiles(toSort)
verifySort(toSort) verifySort(toSort)
} }