From 37ebd30a4d8009d8e26de1c1efd0c0fb2a257701 Mon Sep 17 00:00:00 2001 From: SUPERYAO Date: Fri, 24 Sep 2021 20:33:57 +0800 Subject: [PATCH 001/112] Keep the screen on when watching the entry --- .../java/com/kunzisoft/keepass/activities/EntryActivity.kt | 7 +++++++ .../java/com/kunzisoft/keepass/settings/PreferencesUtil.kt | 7 +++++++ app/src/main/res/values-zh-rTW/strings.xml | 2 ++ app/src/main/res/values/donottranslate.xml | 2 ++ app/src/main/res/values/strings.xml | 2 ++ app/src/main/res/xml/preferences_application.xml | 5 +++++ 6 files changed, 25 insertions(+) diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt b/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt index eb03b76da..c9937db75 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt +++ b/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt @@ -282,6 +282,13 @@ class EntryActivity : DatabaseLockActivity() { } } } + + // Keep the screen on + if (PreferencesUtil.isKeepScreenOnEnabled(this)) { + window.addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + } else { + window.clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + } } override fun onPause() { diff --git a/app/src/main/java/com/kunzisoft/keepass/settings/PreferencesUtil.kt b/app/src/main/java/com/kunzisoft/keepass/settings/PreferencesUtil.kt index c2059d234..36efc093e 100644 --- a/app/src/main/java/com/kunzisoft/keepass/settings/PreferencesUtil.kt +++ b/app/src/main/java/com/kunzisoft/keepass/settings/PreferencesUtil.kt @@ -278,6 +278,12 @@ object PreferencesUtil { context.resources.getBoolean(R.bool.enable_auto_save_database_default)) } + fun isKeepScreenOnEnabled(context: Context): Boolean { + val prefs = PreferenceManager.getDefaultSharedPreferences(context) + return prefs.getBoolean(context.getString(R.string.enable_keep_screen_on_key), + context.resources.getBoolean(R.bool.enable_keep_screen_on_default)) + } + fun isAdvancedUnlockEnable(context: Context): Boolean { return isBiometricUnlockEnable(context) || isDeviceCredentialUnlockEnable(context) } @@ -595,6 +601,7 @@ object PreferencesUtil { context.getString(R.string.delete_entered_password_key) -> editor.putBoolean(name, value.toBoolean()) context.getString(R.string.enable_read_only_key) -> editor.putBoolean(name, value.toBoolean()) context.getString(R.string.enable_auto_save_database_key) -> editor.putBoolean(name, value.toBoolean()) + context.getString(R.string.enable_keep_screen_on_key) -> editor.putBoolean(name, value.toBoolean()) context.getString(R.string.omit_backup_search_key) -> editor.putBoolean(name, value.toBoolean()) context.getString(R.string.auto_focus_search_key) -> editor.putBoolean(name, value.toBoolean()) context.getString(R.string.subdomain_search_key) -> editor.putBoolean(name, value.toBoolean()) diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 789f53b15..d3adbc7ea 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -286,6 +286,8 @@ 教學提示 重設教學提示 自動儲存資料庫 + 螢幕常亮 + 當正在閱讀條目時,保持螢幕常亮 刪除密碼 阻止自動填入 網域名稱黑名單 diff --git a/app/src/main/res/values/donottranslate.xml b/app/src/main/res/values/donottranslate.xml index 1d7cbf25e..0efc3422b 100644 --- a/app/src/main/res/values/donottranslate.xml +++ b/app/src/main/res/values/donottranslate.xml @@ -67,6 +67,8 @@ false enable_auto_save_database_key true + enable_keep_screen_on_key + false omit_backup_search_key true auto_focus_search_key diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 005fee3ac..f2a89ff0c 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -510,6 +510,8 @@ Open the database read-only by default Autosave database Save the database after every important action (in \"Modifiable\" mode) + Keep screen on + Keep the screen on when watching the entry Educational hints Highlight elements to learn how the app works Reset educational hints diff --git a/app/src/main/res/xml/preferences_application.xml b/app/src/main/res/xml/preferences_application.xml index 4a96d82bc..ce1c5d8ff 100644 --- a/app/src/main/res/xml/preferences_application.xml +++ b/app/src/main/res/xml/preferences_application.xml @@ -43,6 +43,11 @@ android:title="@string/enable_auto_save_database_title" android:summary="@string/enable_auto_save_database_summary" android:defaultValue="@bool/enable_auto_save_database_default"/> + From 40a893a8c974f321d892a907d49820d68b117fca Mon Sep 17 00:00:00 2001 From: SUPERYAO Date: Fri, 24 Sep 2021 22:30:21 +0800 Subject: [PATCH 002/112] There is no need to clear the flag when the option is not enabled --- .../main/java/com/kunzisoft/keepass/activities/EntryActivity.kt | 2 -- 1 file changed, 2 deletions(-) diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt b/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt index c9937db75..09b72e908 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt +++ b/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt @@ -286,8 +286,6 @@ class EntryActivity : DatabaseLockActivity() { // Keep the screen on if (PreferencesUtil.isKeepScreenOnEnabled(this)) { window.addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) - } else { - window.clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } } From bedc327e6514c47cbc823da673ef5fb2a28ace1d Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Tue, 28 Sep 2021 19:12:34 +0200 Subject: [PATCH 003/112] Manage Tags #633 --- CHANGELOG | 1 + .../keepass/activities/EntryActivity.kt | 17 +++++ .../kunzisoft/keepass/adapters/TagsAdapter.kt | 73 +++++++++++++++++++ .../keepass/database/element/Entry.kt | 2 + .../keepass/database/element/Tags.kt | 22 ++++++ .../com/kunzisoft/keepass/model/EntryInfo.kt | 10 ++- .../res/drawable/ic_bookmark_white_24dp.xml | 9 +++ app/src/main/res/layout/activity_entry.xml | 15 +++- app/src/main/res/layout/item_tag.xml | 44 +++++++++++ .../metadata/android/en-US/changelogs/90.txt | 3 +- .../metadata/android/fr-FR/changelogs/90.txt | 3 +- 11 files changed, 192 insertions(+), 7 deletions(-) create mode 100644 app/src/main/java/com/kunzisoft/keepass/adapters/TagsAdapter.kt create mode 100644 app/src/main/res/drawable/ic_bookmark_white_24dp.xml create mode 100644 app/src/main/res/layout/item_tag.xml diff --git a/CHANGELOG b/CHANGELOG index dc7174086..eb0e1374c 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,7 @@ KeePassDX(3.1.0) * Change default Argon2 parameters #1098 * Add & edit custom icon name #976 + * Manage Tags #633 KeePassDX(3.0.2) * Samsung DeX mode #1114 #245 (Thx @chenxiaolong) diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt b/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt index eb03b76da..114c3ba16 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt +++ b/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt @@ -35,12 +35,15 @@ import android.widget.ProgressBar import androidx.activity.viewModels import androidx.appcompat.widget.Toolbar import androidx.coordinatorlayout.widget.CoordinatorLayout +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView import com.google.android.material.appbar.CollapsingToolbarLayout import com.kunzisoft.keepass.R import com.kunzisoft.keepass.activities.fragments.EntryFragment import com.kunzisoft.keepass.activities.helpers.ExternalFileHelper import com.kunzisoft.keepass.activities.helpers.SpecialMode import com.kunzisoft.keepass.activities.legacy.DatabaseLockActivity +import com.kunzisoft.keepass.adapters.TagsAdapter import com.kunzisoft.keepass.database.element.Attachment import com.kunzisoft.keepass.database.element.Database import com.kunzisoft.keepass.database.element.icon.IconImage @@ -70,6 +73,8 @@ class EntryActivity : DatabaseLockActivity() { private var collapsingToolbarLayout: CollapsingToolbarLayout? = null private var titleIconView: ImageView? = null private var historyView: View? = null + private var tagsListView: RecyclerView? = null + private var tagsAdapter: TagsAdapter? = null private var entryProgress: ProgressBar? = null private var lockView: View? = null private var toolbar: Toolbar? = null @@ -105,6 +110,7 @@ class EntryActivity : DatabaseLockActivity() { collapsingToolbarLayout = findViewById(R.id.toolbar_layout) titleIconView = findViewById(R.id.entry_icon) historyView = findViewById(R.id.history_container) + tagsListView = findViewById(R.id.entry_tags_list_view) entryProgress = findViewById(R.id.entry_progress) lockView = findViewById(R.id.lock_button) loadingView = findViewById(R.id.loading) @@ -118,6 +124,13 @@ class EntryActivity : DatabaseLockActivity() { mIconColor = taIconColor.getColor(0, Color.BLACK) taIconColor.recycle() + // Init Tags adapter + tagsAdapter = TagsAdapter(this) + tagsListView?.apply { + layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) + adapter = tagsAdapter + } + // Get Entry from UUID try { intent.getParcelableExtra?>(KEY_ENTRY)?.let { mainEntryId -> @@ -179,6 +192,10 @@ class EntryActivity : DatabaseLockActivity() { collapsingToolbarLayout?.title = entryTitle toolbar?.title = entryTitle mUrl = entryInfo.url + // Assign tags + val tags = entryInfo.tags + tagsListView?.visibility = if (tags.isEmpty()) View.GONE else View.VISIBLE + tagsAdapter?.setTags(tags) loadingView?.hideByFading() mEntryLoaded = true diff --git a/app/src/main/java/com/kunzisoft/keepass/adapters/TagsAdapter.kt b/app/src/main/java/com/kunzisoft/keepass/adapters/TagsAdapter.kt new file mode 100644 index 000000000..c5a8e24f1 --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/adapters/TagsAdapter.kt @@ -0,0 +1,73 @@ +/* + * Copyright 2021 Jeremy Jamet / Kunzisoft. + * + * This file is part of KeePassDX. + * + * KeePassDX is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * KeePassDX is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with KeePassDX. If not, see . + * + */ +package com.kunzisoft.keepass.adapters + +import android.content.Context +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import androidx.recyclerview.widget.RecyclerView +import com.kunzisoft.keepass.R +import com.kunzisoft.keepass.database.element.Tags + +class TagsAdapter(context: Context) : RecyclerView.Adapter() { + + private val inflater: LayoutInflater = LayoutInflater.from(context) + private var mTags: Tags = Tags() + var onItemClickListener: OnItemClickListener? = null + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TagViewHolder { + val view = inflater.inflate(R.layout.item_tag, parent, false) + return TagViewHolder(view) + } + + override fun onBindViewHolder(holder: TagViewHolder, position: Int) { + val field = mTags.get(position) + holder.name.text = field + holder.bind(field, onItemClickListener) + } + + override fun getItemCount(): Int { + return mTags.size() + } + + fun setTags(tags: Tags) { + mTags.setTags(tags) + notifyDataSetChanged() + } + + fun clear() { + mTags.clear() + } + + interface OnItemClickListener { + fun onItemClick(item: String) + } + + inner class TagViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { + + var name: TextView = itemView.findViewById(R.id.tag_name) + + fun bind(item: String, listener: OnItemClickListener?) { + itemView.setOnClickListener { listener?.onItemClick(item) } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/Entry.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/Entry.kt index 83e2707a0..f23b276d2 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/Entry.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/Entry.kt @@ -419,6 +419,7 @@ class Entry : Node, EntryVersionedInterface { entryInfo.expiryTime = expiryTime entryInfo.url = url entryInfo.notes = notes + entryInfo.tags = tags entryInfo.customFields = getExtraFields().toMutableList() // Add otpElement to generate token entryInfo.otpModel = getOtpElement()?.otpModel @@ -453,6 +454,7 @@ class Entry : Node, EntryVersionedInterface { expiryTime = newEntryInfo.expiryTime url = newEntryInfo.url notes = newEntryInfo.notes + tags = newEntryInfo.tags addExtraFields(newEntryInfo.customFields) database?.attachmentPool?.let { binaryPool -> newEntryInfo.attachments.forEach { attachment -> diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/Tags.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/Tags.kt index bdda16cde..82b2de421 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/Tags.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/Tags.kt @@ -25,10 +25,32 @@ class Tags: Parcelable { return 0 } + fun setTags(tags: Tags) { + mTags.clear() + mTags.addAll(tags.mTags) + } + + fun get(position: Int): String { + return mTags[position] + } + + fun put(tag: String) { + if (!mTags.contains(tag)) + mTags.add(tag) + } + fun isEmpty(): Boolean { return mTags.isEmpty() } + fun size(): Int { + return mTags.size + } + + fun clear() { + mTags.clear() + } + override fun toString(): String { return mTags.joinToString(";") } diff --git a/app/src/main/java/com/kunzisoft/keepass/model/EntryInfo.kt b/app/src/main/java/com/kunzisoft/keepass/model/EntryInfo.kt index 9324ea9a8..4a60e870b 100644 --- a/app/src/main/java/com/kunzisoft/keepass/model/EntryInfo.kt +++ b/app/src/main/java/com/kunzisoft/keepass/model/EntryInfo.kt @@ -22,10 +22,7 @@ package com.kunzisoft.keepass.model import android.os.Parcel import android.os.ParcelUuid import android.os.Parcelable -import com.kunzisoft.keepass.database.element.Attachment -import com.kunzisoft.keepass.database.element.Database -import com.kunzisoft.keepass.database.element.DateInstant -import com.kunzisoft.keepass.database.element.Field +import com.kunzisoft.keepass.database.element.* import com.kunzisoft.keepass.database.element.security.ProtectedString import com.kunzisoft.keepass.database.element.template.TemplateField import com.kunzisoft.keepass.otp.OtpElement @@ -40,6 +37,7 @@ class EntryInfo : NodeInfo { var password: String = "" var url: String = "" var notes: String = "" + var tags: Tags = Tags() var customFields: MutableList = mutableListOf() var attachments: MutableList = mutableListOf() var otpModel: OtpModel? = null @@ -53,6 +51,7 @@ class EntryInfo : NodeInfo { password = parcel.readString() ?: password url = parcel.readString() ?: url notes = parcel.readString() ?: notes + tags = parcel.readParcelable(Tags::class.java.classLoader) ?: tags parcel.readList(customFields, Field::class.java.classLoader) parcel.readList(attachments, Attachment::class.java.classLoader) otpModel = parcel.readParcelable(OtpModel::class.java.classLoader) ?: otpModel @@ -70,6 +69,7 @@ class EntryInfo : NodeInfo { parcel.writeString(password) parcel.writeString(url) parcel.writeString(notes) + parcel.writeParcelable(tags, flags) parcel.writeList(customFields) parcel.writeList(attachments) parcel.writeParcelable(otpModel, flags) @@ -196,6 +196,7 @@ class EntryInfo : NodeInfo { if (password != other.password) return false if (url != other.url) return false if (notes != other.notes) return false + if (tags != other.tags) return false if (customFields != other.customFields) return false if (attachments != other.attachments) return false if (otpModel != other.otpModel) return false @@ -211,6 +212,7 @@ class EntryInfo : NodeInfo { result = 31 * result + password.hashCode() result = 31 * result + url.hashCode() result = 31 * result + notes.hashCode() + result = 31 * result + tags.hashCode() result = 31 * result + customFields.hashCode() result = 31 * result + attachments.hashCode() result = 31 * result + (otpModel?.hashCode() ?: 0) diff --git a/app/src/main/res/drawable/ic_bookmark_white_24dp.xml b/app/src/main/res/drawable/ic_bookmark_white_24dp.xml new file mode 100644 index 000000000..663edd72b --- /dev/null +++ b/app/src/main/res/drawable/ic_bookmark_white_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/layout/activity_entry.xml b/app/src/main/res/layout/activity_entry.xml index fe37fea78..46801b252 100644 --- a/app/src/main/res/layout/activity_entry.xml +++ b/app/src/main/res/layout/activity_entry.xml @@ -112,13 +112,26 @@ android:text="@string/entry_history"/> + + diff --git a/app/src/main/res/layout/item_tag.xml b/app/src/main/res/layout/item_tag.xml new file mode 100644 index 000000000..fd9808b11 --- /dev/null +++ b/app/src/main/res/layout/item_tag.xml @@ -0,0 +1,44 @@ + + + + \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/changelogs/90.txt b/fastlane/metadata/android/en-US/changelogs/90.txt index 037dc1d3e..3f81346d3 100644 --- a/fastlane/metadata/android/en-US/changelogs/90.txt +++ b/fastlane/metadata/android/en-US/changelogs/90.txt @@ -1,2 +1,3 @@ * Change default Argon2 parameters #1098 - * Add & edit custom icon name #976 \ No newline at end of file + * Add & edit custom icon name #976 + * Manage Tags #633 \ No newline at end of file diff --git a/fastlane/metadata/android/fr-FR/changelogs/90.txt b/fastlane/metadata/android/fr-FR/changelogs/90.txt index f1b03ae58..686107704 100644 --- a/fastlane/metadata/android/fr-FR/changelogs/90.txt +++ b/fastlane/metadata/android/fr-FR/changelogs/90.txt @@ -1,2 +1,3 @@ * Changement des paramètres Argon2 par défaut #1098 - * Ajout & édition du nom d'icone customisé #976 \ No newline at end of file + * Ajout & édition du nom d'icone customisé #976 + * Gestion des Tags #633 \ No newline at end of file From 94b6118bf7270d44b68db36c403319b0837457ed Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Tue, 5 Oct 2021 14:30:49 +0200 Subject: [PATCH 004/112] Fix theme and add autocomplete view --- app/build.gradle | 2 + .../activities/fragments/EntryEditFragment.kt | 16 ++++++ .../keepass/adapters/TagsProposalAdapter.kt | 14 +++++ .../keepass/view/TagsCompletionView.kt | 33 ++++++++++++ .../drawable-v21/background_completion.xml | 16 ++++++ .../res/drawable/background_completion.xml | 16 ++++++ ...te_24dp.xml => ic_bookmark_white_12dp.xml} | 6 +-- app/src/main/res/layout/activity_entry.xml | 22 +++----- .../main/res/layout/fragment_entry_edit.xml | 23 +++++++- app/src/main/res/layout/item_tag.xml | 29 +++++----- app/src/main/res/layout/item_tag_edit.xml | 54 +++++++++++++++++++ app/src/main/res/values/strings.xml | 1 + app/src/main/res/values/styles.xml | 12 +++++ 13 files changed, 212 insertions(+), 32 deletions(-) create mode 100644 app/src/main/java/com/kunzisoft/keepass/adapters/TagsProposalAdapter.kt create mode 100644 app/src/main/java/com/kunzisoft/keepass/view/TagsCompletionView.kt create mode 100644 app/src/main/res/drawable-v21/background_completion.xml create mode 100644 app/src/main/res/drawable/background_completion.xml rename app/src/main/res/drawable/{ic_bookmark_white_24dp.xml => ic_bookmark_white_12dp.xml} (77%) create mode 100644 app/src/main/res/layout/item_tag_edit.xml diff --git a/app/build.gradle b/app/build.gradle index 7f97fed16..f89f6d474 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -115,6 +115,8 @@ dependencies { implementation 'androidx.fragment:fragment-ktx:1.2.5' // WARNING: Don't upgrade because slowdown https://github.com/Kunzisoft/KeePassDX/issues/923 implementation 'com.google.android.material:material:1.1.0' + // Token auto complete + implementation "com.splitwise:tokenautocomplete:4.0.0-beta04" // Database implementation "androidx.room:room-runtime:$room_version" kapt "androidx.room:room-compiler:$room_version" diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/fragments/EntryEditFragment.kt b/app/src/main/java/com/kunzisoft/keepass/activities/fragments/EntryEditFragment.kt index 1d8bea4bf..bbba28ce2 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/fragments/EntryEditFragment.kt +++ b/app/src/main/java/com/kunzisoft/keepass/activities/fragments/EntryEditFragment.kt @@ -24,6 +24,7 @@ import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup +import androidx.appcompat.widget.AppCompatAutoCompleteTextView import androidx.core.view.isVisible import androidx.fragment.app.activityViewModels import androidx.recyclerview.widget.LinearLayoutManager @@ -33,6 +34,7 @@ import com.kunzisoft.keepass.R import com.kunzisoft.keepass.activities.dialogs.ReplaceFileDialogFragment import com.kunzisoft.keepass.activities.dialogs.SetOTPDialogFragment import com.kunzisoft.keepass.adapters.EntryAttachmentsItemsAdapter +import com.kunzisoft.keepass.adapters.TagsProposalAdapter import com.kunzisoft.keepass.database.element.Attachment import com.kunzisoft.keepass.database.element.Database import com.kunzisoft.keepass.database.element.template.Template @@ -45,6 +47,8 @@ import com.kunzisoft.keepass.view.collapse import com.kunzisoft.keepass.view.expand import com.kunzisoft.keepass.view.showByFading import com.kunzisoft.keepass.viewmodels.EntryEditViewModel +import com.tokenautocomplete.FilteredArrayAdapter + class EntryEditFragment: DatabaseFragment() { @@ -55,6 +59,8 @@ class EntryEditFragment: DatabaseFragment() { private lateinit var attachmentsContainerView: ViewGroup private lateinit var attachmentsListView: RecyclerView private var attachmentsAdapter: EntryAttachmentsItemsAdapter? = null + private lateinit var tagsCompletionView: AppCompatAutoCompleteTextView + private var tagsAdapter: FilteredArrayAdapter? = null private var mTemplate: Template? = null private var mAllowMultipleAttachments: Boolean = false @@ -87,6 +93,7 @@ class EntryEditFragment: DatabaseFragment() { templateView = view.findViewById(R.id.template_view) attachmentsContainerView = view.findViewById(R.id.entry_attachments_container) attachmentsListView = view.findViewById(R.id.entry_attachments_list) + tagsCompletionView = view.findViewById(R.id.entry_tags_completion_view) attachmentsAdapter = EntryAttachmentsItemsAdapter(requireContext()) attachmentsListView.apply { @@ -95,6 +102,15 @@ class EntryEditFragment: DatabaseFragment() { (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false } + // TODO default tags in pool + tagsAdapter = TagsProposalAdapter(requireContext(), arrayOf("test")) + tagsCompletionView.apply { + //allowCollapse(false) + //setTokenizer(CharacterTokenizer(listOf('.', ','), ",")) + threshold = 1 + setAdapter(tagsAdapter) + } + templateView.apply { setOnIconClickListener { mEntryEditViewModel.requestIconSelection(templateView.getIcon()) diff --git a/app/src/main/java/com/kunzisoft/keepass/adapters/TagsProposalAdapter.kt b/app/src/main/java/com/kunzisoft/keepass/adapters/TagsProposalAdapter.kt new file mode 100644 index 000000000..ba941b524 --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/adapters/TagsProposalAdapter.kt @@ -0,0 +1,14 @@ +package com.kunzisoft.keepass.adapters + +import android.content.Context +import com.tokenautocomplete.FilteredArrayAdapter + +class TagsProposalAdapter(context: Context, proposal: Array) + : FilteredArrayAdapter(context, android.R.layout.simple_list_item_1, proposal) { + + override fun keepObject(obj: String, mask: String?): Boolean { + if (mask == null) + return false + return obj.contains(mask, true) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/kunzisoft/keepass/view/TagsCompletionView.kt b/app/src/main/java/com/kunzisoft/keepass/view/TagsCompletionView.kt new file mode 100644 index 000000000..229ae520c --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/view/TagsCompletionView.kt @@ -0,0 +1,33 @@ +package com.kunzisoft.keepass.view + +import android.app.Activity +import android.content.Context +import android.util.AttributeSet +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import com.kunzisoft.keepass.R +import com.tokenautocomplete.TokenCompleteTextView + + +class TagsCompletionView @JvmOverloads constructor( + context: Context, attrs: AttributeSet? = null +) : TokenCompleteTextView(context, attrs) { + + private val layoutInflater = context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE) + as? LayoutInflater? + + override fun defaultObject(completionText: String): String { + return completionText + } + + override fun getViewForObject(obj: String): View? { + val viewGroup = layoutInflater?.inflate(R.layout.item_tag_edit, parent as ViewGroup, false) + as? ViewGroup? + viewGroup?.findViewById(R.id.tag_name)?.apply { + text = obj + } + return viewGroup + } +} \ No newline at end of file diff --git a/app/src/main/res/drawable-v21/background_completion.xml b/app/src/main/res/drawable-v21/background_completion.xml new file mode 100644 index 000000000..fd13a7f85 --- /dev/null +++ b/app/src/main/res/drawable-v21/background_completion.xml @@ -0,0 +1,16 @@ + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/background_completion.xml b/app/src/main/res/drawable/background_completion.xml new file mode 100644 index 000000000..406ce32ab --- /dev/null +++ b/app/src/main/res/drawable/background_completion.xml @@ -0,0 +1,16 @@ + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_bookmark_white_24dp.xml b/app/src/main/res/drawable/ic_bookmark_white_12dp.xml similarity index 77% rename from app/src/main/res/drawable/ic_bookmark_white_24dp.xml rename to app/src/main/res/drawable/ic_bookmark_white_12dp.xml index 663edd72b..96982c5bd 100644 --- a/app/src/main/res/drawable/ic_bookmark_white_24dp.xml +++ b/app/src/main/res/drawable/ic_bookmark_white_12dp.xml @@ -1,8 +1,8 @@ + android:viewportWidth="24" > diff --git a/app/src/main/res/layout/activity_entry.xml b/app/src/main/res/layout/activity_entry.xml index 46801b252..28edbfd86 100644 --- a/app/src/main/res/layout/activity_entry.xml +++ b/app/src/main/res/layout/activity_entry.xml @@ -95,31 +95,25 @@ android:layout_width="match_parent" android:layout_height="match_parent"> - - - + android:textColor="?attr/textColorInverse" + android:text="@string/entry_history"/> . --> - + + + + + + diff --git a/app/src/main/res/layout/item_tag.xml b/app/src/main/res/layout/item_tag.xml index fd9808b11..6e6926e40 100644 --- a/app/src/main/res/layout/item_tag.xml +++ b/app/src/main/res/layout/item_tag.xml @@ -13,32 +13,35 @@ * See the License for the specific language governing permissions and * limitations under the License. --> - \ No newline at end of file diff --git a/app/src/main/res/layout/item_tag_edit.xml b/app/src/main/res/layout/item_tag_edit.xml new file mode 100644 index 000000000..0f40f81b7 --- /dev/null +++ b/app/src/main/res/layout/item_tag_edit.xml @@ -0,0 +1,54 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3c618e940..8182828e6 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -91,6 +91,7 @@ Modified Could not find entry data. Password + Tags Save Title Set up one-time password diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml index f133a6d60..cc82beac4 100644 --- a/app/src/main/res/values/styles.xml +++ b/app/src/main/res/values/styles.xml @@ -91,6 +91,7 @@ @style/KeepassDXStyle.TextInputLayout + @style/KeepassDXStyle.TextInputLayout.ExposedMenu @@ -244,6 +246,9 @@ + + + + + diff --git a/app/src/main/res/xml/keyboard_password.xml b/app/src/main/res/xml/keyboard_password.xml index 50e128b21..435993f60 100644 --- a/app/src/main/res/xml/keyboard_password.xml +++ b/app/src/main/res/xml/keyboard_password.xml @@ -16,44 +16,44 @@ You should have received a copy of the GNU General Public License along with KeePassDX. If not, see . --> - + app:verticalGap="8dp" + app:horizontalGap="1%p" + app:keyHeight="38dp"> + app:rowEdgeFlags="bottom"> + app:codes="600" + app:keyIcon="@drawable/ic_keyboard_white_24dp" + app:tooltipText="@string/back_to_previous_keyboard" + app:keyWidth="17%p" + app:horizontalGap="1%p" + app:keyEdgeFlags="left" + app:isRepeatable="false" /> + app:codes="620" + app:keyIcon="@drawable/ic_key_white_24dp" + app:tooltipText="@string/select_entry" + app:keyWidth="45%p" + app:horizontalGap="2%p" + app:isRepeatable="false"/> + app:codes="-5" + app:keyIcon="@drawable/ic_backspace_white_24dp" + app:tooltipText="@string/backspace" + app:keyWidth="14%p" + app:horizontalGap="2%p" + app:isRepeatable="true"/> + app:codes="-4" + app:keyIcon="@drawable/ic_keyboard_return_white_24dp" + app:tooltipText="@string/enter" + app:keyWidth="17%p" + app:horizontalGap="1%p" + app:isRepeatable="false" + app:keyEdgeFlags="right"/> \ No newline at end of file diff --git a/app/src/main/res/xml/keyboard_password_entry.xml b/app/src/main/res/xml/keyboard_password_entry.xml index 72dcbe389..3b8571a10 100644 --- a/app/src/main/res/xml/keyboard_password_entry.xml +++ b/app/src/main/res/xml/keyboard_password_entry.xml @@ -17,89 +17,89 @@ along with KeePassDX. If not, see . --> + app:verticalGap="8dp" + app:horizontalGap="1%p" + app:keyHeight="38dp"> + app:codes="520" + app:keyEdgeFlags="left" + app:keyIcon="@drawable/ic_link_black_24dp" + app:tooltipText="@string/entry_url" + app:keyWidth="15%p" + app:horizontalGap="1%p" + app:isRepeatable="false"/> + app:codes="500" + app:keyIcon="@drawable/ic_person_white_24dp" + app:tooltipText="@string/entry_user_name" + app:keyWidth="17%p" + app:horizontalGap="2%p" + app:isRepeatable="false" /> + app:codes="510" + app:keyIcon="@drawable/ic_password_white_24dp" + app:tooltipText="@string/entry_password" + app:keyWidth="28%p" + app:horizontalGap="1%p" + app:isRepeatable="false"/> + app:codes="515" + app:keyIcon="@drawable/ic_otp_white_24dp" + app:tooltipText="@string/entry_otp" + app:keyWidth="17%p" + app:horizontalGap="2%p" + app:isRepeatable="false"/> + app:codes="530" + app:keyIcon="@drawable/ic_list_white_24dp" + app:tooltipText="@string/custom_fields" + app:keyWidth="15%p" + app:horizontalGap="1%p" + app:isRepeatable="false" + app:keyEdgeFlags="right"/> + app:rowEdgeFlags="bottom"> + app:codes="600" + app:keyIcon="@drawable/ic_keyboard_white_24dp" + app:tooltipText="@string/back_to_previous_keyboard" + app:keyWidth="17%p" + app:horizontalGap="1%p" + app:keyEdgeFlags="left" + app:isRepeatable="false"/> + app:codes="611" + app:keyIcon="@drawable/ic_lock_white_24dp" + app:tooltipText="@string/lock" + app:keyWidth="26%p" + app:horizontalGap="2%p" + app:isRepeatable="false" /> + app:codes="620" + app:keyIcon="@drawable/ic_key_white_24dp" + app:tooltipText="@string/select_entry" + app:keyWidth="18%p" + app:horizontalGap="1%p" + app:isRepeatable="false"/> + app:codes="-5" + app:keyIcon="@drawable/ic_backspace_white_24dp" + app:tooltipText="@string/backspace" + app:keyWidth="14%p" + app:horizontalGap="2%p" + app:isRepeatable="true"/> + app:codes="-4" + app:keyIcon="@drawable/ic_keyboard_return_white_24dp" + app:tooltipText="@string/enter" + app:keyWidth="17%p" + app:horizontalGap="1%p" + app:isRepeatable="false" + app:keyEdgeFlags="right"/> \ No newline at end of file From 910c45a6bec514b4f41f2c853e93b49cffa0f519 Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Wed, 26 Jan 2022 14:23:45 +0100 Subject: [PATCH 079/112] Fix key press --- .../keepass/magikeyboard/Keyboard.java | 60 ++++++------ .../keepass/magikeyboard/KeyboardView.java | 95 +++++++++++++++++-- 2 files changed, 113 insertions(+), 42 deletions(-) diff --git a/app/src/main/java/com/kunzisoft/keepass/magikeyboard/Keyboard.java b/app/src/main/java/com/kunzisoft/keepass/magikeyboard/Keyboard.java index 1cab7b514..313fa465f 100644 --- a/app/src/main/java/com/kunzisoft/keepass/magikeyboard/Keyboard.java +++ b/app/src/main/java/com/kunzisoft/keepass/magikeyboard/Keyboard.java @@ -55,10 +55,10 @@ import java.util.StringTokenizer; * </Keyboard> * * - * @attr ref android.R.styleable#Keyboard_keyWidth - * @attr ref android.R.styleable#Keyboard_keyHeight - * @attr ref android.R.styleable#Keyboard_horizontalGap - * @attr ref android.R.styleable#Keyboard_verticalGap + * ref android.R.styleable#Keyboard_keyWidth + * ref android.R.styleable#Keyboard_keyHeight + * ref android.R.styleable#Keyboard_horizontalGap + * ref android.R.styleable#Keyboard_verticalGap */ public class Keyboard { @@ -166,19 +166,19 @@ public class Keyboard { */ private static float SEARCH_DISTANCE = 1.8f; - private ArrayList rows = new ArrayList(); + private ArrayList rows = new ArrayList<>(); /** * Container for keys in the keyboard. All keys in a row are at the same Y-coordinate. * Some of the key size defaults can be overridden per row from what the {@link Keyboard} * defines. * - * @attr ref android.R.styleable#Keyboard_keyWidth - * @attr ref android.R.styleable#Keyboard_keyHeight - * @attr ref android.R.styleable#Keyboard_horizontalGap - * @attr ref android.R.styleable#Keyboard_verticalGap - * @attr ref android.R.styleable#Keyboard_Row_rowEdgeFlags - * @attr ref android.R.styleable#Keyboard_Row_keyboardMode + * ref R.styleable#Keyboard_keyWidth + * ref R.styleable#Keyboard_keyHeight + * ref R.styleable#Keyboard_horizontalGap + * ref R.styleable#Keyboard_verticalGap + * ref R.styleable#Keyboard_Row_rowEdgeFlags + * ref R.styleable#Keyboard_Row_keyboardMode */ public static class Row { /** @@ -229,30 +229,30 @@ public class Keyboard { parent.mDisplayWidth, parent.mDefaultHorizontalGap); verticalGap = getDimensionOrFraction(a, R.styleable.Keyboard_verticalGap, parent.mDisplayHeight, parent.mDefaultVerticalGap); - a.recycle(); a = res.obtainAttributes(Xml.asAttributeSet(parser), R.styleable.Keyboard_Row); rowEdgeFlags = a.getInt(R.styleable.Keyboard_Row_rowEdgeFlags, 0); mode = a.getResourceId(R.styleable.Keyboard_Row_keyboardMode, 0); + a.recycle(); } } /** * Class for describing the position and characteristics of a single key in the keyboard. * - * @attr ref R.styleable#Keyboard_keyWidth - * @attr ref R.styleable#Keyboard_keyHeight - * @attr ref R.styleable#Keyboard_horizontalGap - * @attr ref R.styleable#Keyboard_Key_codes - * @attr ref R.styleable#Keyboard_Key_keyIcon - * @attr ref R.styleable#Keyboard_Key_keyLabel - * @attr ref R.styleable#Keyboard_Key_iconPreview - * @attr ref R.styleable#Keyboard_Key_isSticky - * @attr ref R.styleable#Keyboard_Key_isRepeatable - * @attr ref R.styleable#Keyboard_Key_isModifier - * @attr ref R.styleable#Keyboard_Key_popupKeyboard - * @attr ref R.styleable#Keyboard_Key_popupCharacters - * @attr ref R.styleable#Keyboard_Key_keyOutputText - * @attr ref R.styleable#Keyboard_Key_keyEdgeFlags + * ref R.styleable#Keyboard_keyWidth + * ref R.styleable#Keyboard_keyHeight + * ref R.styleable#Keyboard_horizontalGap + * ref R.styleable#Keyboard_Key_codes + * ref R.styleable#Keyboard_Key_keyIcon + * ref R.styleable#Keyboard_Key_keyLabel + * ref R.styleable#Keyboard_Key_iconPreview + * ref R.styleable#Keyboard_Key_isSticky + * ref R.styleable#Keyboard_Key_isRepeatable + * ref R.styleable#Keyboard_Key_isModifier + * ref R.styleable#Keyboard_Key_popupKeyboard + * ref R.styleable#Keyboard_Key_popupCharacters + * ref R.styleable#Keyboard_Key_keyOutputText + * ref R.styleable#Keyboard_Key_keyEdgeFlags */ public static class Key { /** @@ -512,14 +512,10 @@ public class Keyboard { boolean rightEdge = (edgeFlags & EDGE_RIGHT) > 0; boolean topEdge = (edgeFlags & EDGE_TOP) > 0; boolean bottomEdge = (edgeFlags & EDGE_BOTTOM) > 0; - if ((x >= this.x || (leftEdge && x <= this.x + this.width)) + return (x >= this.x || (leftEdge && x <= this.x + this.width)) && (x < this.x + this.width || (rightEdge && x >= this.x)) && (y >= this.y || (topEdge && y <= this.y + this.height)) - && (y < this.y + this.height || (bottomEdge && y >= this.y))) { - return true; - } else { - return false; - } + && (y < this.y + this.height || (bottomEdge && y >= this.y)); } /** diff --git a/app/src/main/java/com/kunzisoft/keepass/magikeyboard/KeyboardView.java b/app/src/main/java/com/kunzisoft/keepass/magikeyboard/KeyboardView.java index c7ca83654..79c35f8e3 100644 --- a/app/src/main/java/com/kunzisoft/keepass/magikeyboard/KeyboardView.java +++ b/app/src/main/java/com/kunzisoft/keepass/magikeyboard/KeyboardView.java @@ -59,15 +59,15 @@ import java.util.Map; * A view that renders a virtual {@link Keyboard}. It handles rendering of keys and * detecting key presses and touch movements. * - * @attr ref R.styleable#KeyboardView_keyBackground - * @attr ref R.styleable#KeyboardView_keyPreviewLayout - * @attr ref R.styleable#KeyboardView_keyPreviewOffset - * @attr ref R.styleable#KeyboardView_keyPreviewHeight - * @attr ref R.styleable#KeyboardView_labelTextSize - * @attr ref R.styleable#KeyboardView_keyTextSize - * @attr ref R.styleable#KeyboardView_keyTextColor - * @attr ref R.styleable#KeyboardView_verticalCorrection - * @attr ref R.styleable#KeyboardView_popupLayout + * ref R.styleable#KeyboardView_keyBackground + * ref R.styleable#KeyboardView_keyPreviewLayout + * ref R.styleable#KeyboardView_keyPreviewOffset + * ref R.styleable#KeyboardView_keyPreviewHeight + * ref R.styleable#KeyboardView_labelTextSize + * ref R.styleable#KeyboardView_keyTextSize + * ref R.styleable#KeyboardView_keyTextColor + * ref R.styleable#KeyboardView_verticalCorrection + * ref R.styleable#KeyboardView_popupLayout */ public class KeyboardView extends View implements View.OnClickListener { @@ -140,6 +140,7 @@ public class KeyboardView extends View implements View.OnClickListener { private static final int[] LONG_PRESSABLE_STATE_SET = {R.attr.state_long_pressable}; private Keyboard mKeyboard; + private int mCurrentKeyIndex = NOT_A_KEY; private int mLabelTextSize; private int mKeyTextSize; private int mKeyTextColor; @@ -183,6 +184,7 @@ public class KeyboardView extends View implements View.OnClickListener { private int mProximityThreshold; private boolean mPreviewCentered = false; + private boolean mShowPreview = true; private boolean mShowTouchPoints = true; private int mPopupPreviewX; private int mPopupPreviewY; @@ -329,6 +331,8 @@ public class KeyboardView extends View implements View.OnClickListener { mPreviewTextSizeLarge = (int) mPreviewText.getTextSize(); mPreviewPopup.setContentView(mPreviewText); mPreviewPopup.setBackgroundDrawable(null); + } else { + mShowPreview = false; } mPreviewPopup.setTouchable(false); @@ -464,6 +468,9 @@ public class KeyboardView extends View implements View.OnClickListener { * @see #getKeyboard() */ public void setKeyboard(Keyboard keyboard) { + if (mKeyboard != null) { + showPreview(NOT_A_KEY); + } // Remove any pending messages removeMessages(); mKeyboard = keyboard; @@ -522,6 +529,27 @@ public class KeyboardView extends View implements View.OnClickListener { return false; } + /** + * Enables or disables the key feedback popup. This is a popup that shows a magnified + * version of the depressed key. By default the preview is enabled. + * + * @param previewEnabled whether or not to enable the key feedback popup + * @see #isPreviewEnabled() + */ + public void setPreviewEnabled(boolean previewEnabled) { + mShowPreview = previewEnabled; + } + + /** + * Returns the enabled state of the key feedback popup. + * + * @return whether or not the key feedback popup is enabled + * @see #setPreviewEnabled(boolean) + */ + public boolean isPreviewEnabled() { + return mShowPreview; + } + public void setPopupParent(View v) { mPopupParent = v; } @@ -838,6 +866,48 @@ public class KeyboardView extends View implements View.OnClickListener { } } + private void showPreview(int keyIndex) { + int oldKeyIndex = mCurrentKeyIndex; + final PopupWindow previewPopup = mPreviewPopup; + + mCurrentKeyIndex = keyIndex; + // Release the old key and press the new key + final Key[] keys = mKeys; + if (oldKeyIndex != mCurrentKeyIndex) { + if (oldKeyIndex != NOT_A_KEY && keys.length > oldKeyIndex) { + Key oldKey = keys[oldKeyIndex]; + oldKey.onReleased(mCurrentKeyIndex == NOT_A_KEY); + invalidateKey(oldKeyIndex); + } + if (mCurrentKeyIndex != NOT_A_KEY && keys.length > mCurrentKeyIndex) { + Key newKey = keys[mCurrentKeyIndex]; + newKey.onPressed(); + invalidateKey(mCurrentKeyIndex); + } + } + // If key changed and preview is on ... + if (oldKeyIndex != mCurrentKeyIndex && mShowPreview) { + mHandler.removeMessages(MSG_SHOW_PREVIEW); + if (previewPopup.isShowing()) { + if (keyIndex == NOT_A_KEY) { + mHandler.sendMessageDelayed(mHandler + .obtainMessage(MSG_REMOVE_PREVIEW), + DELAY_AFTER_PREVIEW); + } + } + if (keyIndex != NOT_A_KEY) { + if (previewPopup.isShowing() && mPreviewText.getVisibility() == VISIBLE) { + // Show right away, if it's already visible and finger is moving around + showKey(keyIndex); + } else { + mHandler.sendMessageDelayed( + mHandler.obtainMessage(MSG_SHOW_PREVIEW, keyIndex, 0), + DELAY_BEFORE_PREVIEW); + } + } + } + } + private void showKey(final int keyIndex) { final PopupWindow previewPopup = mPreviewPopup; final Key[] keys = mKeys; @@ -872,7 +942,6 @@ public class KeyboardView extends View implements View.OnClickListener { mPopupPreviewX = key.x - mPreviewText.getPaddingLeft() + getPaddingLeft(); mPopupPreviewY = key.y - popupHeight + mPreviewOffset; } else { - // TODO: Fix this if centering is brought back mPopupPreviewX = 160 - mPreviewText.getMeasuredWidth() / 2; mPopupPreviewY = -mPreviewText.getMeasuredHeight(); } @@ -961,6 +1030,7 @@ public class KeyboardView extends View implements View.OnClickListener { boolean result = onLongPress(popupKey); if (result) { mAbortKey = true; + showPreview(NOT_A_KEY); } return result; } @@ -1120,6 +1190,7 @@ public class KeyboardView extends View implements View.OnClickListener { } if (mGestureDetector.onTouchEvent(me)) { + showPreview(NOT_A_KEY); mHandler.removeMessages(MSG_REPEAT); mHandler.removeMessages(MSG_LONGPRESS); return true; @@ -1163,6 +1234,7 @@ public class KeyboardView extends View implements View.OnClickListener { Message msg = mHandler.obtainMessage(MSG_LONGPRESS, me); mHandler.sendMessageDelayed(msg, LONGPRESS_TIMEOUT); } + showPreview(keyIndex); break; case MotionEvent.ACTION_MOVE: @@ -1196,6 +1268,7 @@ public class KeyboardView extends View implements View.OnClickListener { mHandler.sendMessageDelayed(msg, LONGPRESS_TIMEOUT); } } + showPreview(mCurrentKey); mLastMoveTime = eventTime; break; @@ -1216,6 +1289,7 @@ public class KeyboardView extends View implements View.OnClickListener { touchX = mLastCodeX; touchY = mLastCodeY; } + showPreview(NOT_A_KEY); Arrays.fill(mKeyIndices, NOT_A_KEY); // If we're not on a repeating key (which sends on a DOWN event) if (mRepeatKeyIndex == NOT_A_KEY && !mMiniKeyboardOnScreen && !mAbortKey) { @@ -1228,6 +1302,7 @@ public class KeyboardView extends View implements View.OnClickListener { removeMessages(); dismissPopupKeyboard(); mAbortKey = true; + showPreview(NOT_A_KEY); invalidateKey(mCurrentKey); break; } From 6d49cc3577bf662e0ab569bdae5be7e349773036 Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Wed, 26 Jan 2022 15:10:06 +0100 Subject: [PATCH 080/112] Remove unused deprecated attribute --- .../com/kunzisoft/keepass/magikeyboard/MagikeyboardService.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/com/kunzisoft/keepass/magikeyboard/MagikeyboardService.kt b/app/src/main/java/com/kunzisoft/keepass/magikeyboard/MagikeyboardService.kt index 5fb74229b..23766a69b 100644 --- a/app/src/main/java/com/kunzisoft/keepass/magikeyboard/MagikeyboardService.kt +++ b/app/src/main/java/com/kunzisoft/keepass/magikeyboard/MagikeyboardService.kt @@ -32,6 +32,7 @@ import android.view.inputmethod.InputMethodManager import android.widget.FrameLayout import android.widget.PopupWindow import android.widget.TextView +import androidx.core.view.WindowCompat.setDecorFitsSystemWindows import com.kunzisoft.keepass.R import com.kunzisoft.keepass.activities.MagikeyboardLauncherActivity import com.kunzisoft.keepass.adapters.FieldsAdapter @@ -96,7 +97,6 @@ class MagikeyboardService : InputMethodService(), KeyboardView.OnKeyboardActionL popupCustomKeys = PopupWindow(context).apply { width = WindowManager.LayoutParams.WRAP_CONTENT height = WindowManager.LayoutParams.WRAP_CONTENT - softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE inputMethodMode = PopupWindow.INPUT_METHOD_NEEDED contentView = popupFieldsView } From 0084d113d355068c875f2c8bfcb22bf6482e6c04 Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Wed, 26 Jan 2022 15:10:21 +0100 Subject: [PATCH 081/112] Remove unused deprecated attribute --- .../com/kunzisoft/keepass/magikeyboard/MagikeyboardService.kt | 1 - 1 file changed, 1 deletion(-) diff --git a/app/src/main/java/com/kunzisoft/keepass/magikeyboard/MagikeyboardService.kt b/app/src/main/java/com/kunzisoft/keepass/magikeyboard/MagikeyboardService.kt index 23766a69b..96c761803 100644 --- a/app/src/main/java/com/kunzisoft/keepass/magikeyboard/MagikeyboardService.kt +++ b/app/src/main/java/com/kunzisoft/keepass/magikeyboard/MagikeyboardService.kt @@ -32,7 +32,6 @@ import android.view.inputmethod.InputMethodManager import android.widget.FrameLayout import android.widget.PopupWindow import android.widget.TextView -import androidx.core.view.WindowCompat.setDecorFitsSystemWindows import com.kunzisoft.keepass.R import com.kunzisoft.keepass.activities.MagikeyboardLauncherActivity import com.kunzisoft.keepass.adapters.FieldsAdapter From 89a338ac33614b4bf18760b177e85d7e9d5e2e7d Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Wed, 26 Jan 2022 15:11:11 +0100 Subject: [PATCH 082/112] Suppress deprecation --- .../com/kunzisoft/keepass/magikeyboard/MagikeyboardService.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/com/kunzisoft/keepass/magikeyboard/MagikeyboardService.kt b/app/src/main/java/com/kunzisoft/keepass/magikeyboard/MagikeyboardService.kt index 96c761803..2472ab69f 100644 --- a/app/src/main/java/com/kunzisoft/keepass/magikeyboard/MagikeyboardService.kt +++ b/app/src/main/java/com/kunzisoft/keepass/magikeyboard/MagikeyboardService.kt @@ -194,7 +194,6 @@ class MagikeyboardService : InputMethodService(), KeyboardView.OnKeyboardActionL } } - @Suppress("DEPRECATION") private fun switchToPreviousKeyboard() { var imeManager: InputMethodManager? = null try { @@ -202,6 +201,7 @@ class MagikeyboardService : InputMethodService(), KeyboardView.OnKeyboardActionL if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { switchToPreviousInputMethod() } else { + @Suppress("DEPRECATION") window.window?.let { window -> imeManager?.switchToLastInputMethod(window.attributes.token) } From 201d8f8aee5f174d1f455e9341338bcb191af2e9 Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Wed, 26 Jan 2022 17:47:40 +0100 Subject: [PATCH 083/112] Fix merge menu --- .../java/com/kunzisoft/keepass/activities/EntryActivity.kt | 4 +++- .../java/com/kunzisoft/keepass/activities/GroupActivity.kt | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt b/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt index 8f78c6004..a9dc302ba 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt +++ b/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt @@ -379,12 +379,14 @@ class EntryActivity : DatabaseLockActivity() { } if (mEntryIsHistory || mDatabaseReadOnly) { menu?.findItem(R.id.menu_save_database)?.isVisible = false + menu?.findItem(R.id.menu_merge_database)?.isVisible = false menu?.findItem(R.id.menu_edit)?.isVisible = false } - if (!mMergeDataAllowed || mDatabaseReadOnly) { + if (!mMergeDataAllowed) { menu?.findItem(R.id.menu_merge_database)?.isVisible = false } if (mSpecialMode != SpecialMode.DEFAULT) { + menu?.findItem(R.id.menu_merge_database)?.isVisible = false menu?.findItem(R.id.menu_reload_database)?.isVisible = false } applyToolbarColors() diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/GroupActivity.kt b/app/src/main/java/com/kunzisoft/keepass/activities/GroupActivity.kt index 43f8e9f9c..4abb99360 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/GroupActivity.kt +++ b/app/src/main/java/com/kunzisoft/keepass/activities/GroupActivity.kt @@ -969,13 +969,15 @@ class GroupActivity : DatabaseLockActivity(), inflater.inflate(R.menu.database, menu) if (mDatabaseReadOnly) { menu.findItem(R.id.menu_save_database)?.isVisible = false + menu.findItem(R.id.menu_merge_database)?.isVisible = false } - if (!mMergeDataAllowed || mDatabaseReadOnly) { + if (!mMergeDataAllowed) { menu.findItem(R.id.menu_merge_database)?.isVisible = false } if (mSpecialMode == SpecialMode.DEFAULT) { MenuUtil.defaultMenuInflater(inflater, menu) } else { + menu.findItem(R.id.menu_merge_database)?.isVisible = false menu.findItem(R.id.menu_reload_database)?.isVisible = false } From 4e7f7f7fa0d2e9b856cc565a2f79590f32c8152f Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Wed, 26 Jan 2022 18:16:33 +0100 Subject: [PATCH 084/112] Fix lock in settings --- .../settings/NestedDatabaseSettingsFragment.kt | 3 ++- .../kunzisoft/keepass/settings/SettingsActivity.kt | 12 +++++++----- app/src/main/res/layout/activity_toolbar.xml | 1 - 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/com/kunzisoft/keepass/settings/NestedDatabaseSettingsFragment.kt b/app/src/main/java/com/kunzisoft/keepass/settings/NestedDatabaseSettingsFragment.kt index eeed43b49..c55a727f3 100644 --- a/app/src/main/java/com/kunzisoft/keepass/settings/NestedDatabaseSettingsFragment.kt +++ b/app/src/main/java/com/kunzisoft/keepass/settings/NestedDatabaseSettingsFragment.kt @@ -654,8 +654,9 @@ class NestedDatabaseSettingsFragment : NestedSettingsFragment(), DatabaseRetriev inflater.inflate(R.menu.database, menu) if (mDatabaseReadOnly) { menu.findItem(R.id.menu_save_database)?.isVisible = false + menu.findItem(R.id.menu_merge_database)?.isVisible = false } - if (!mMergeDataAllowed || mDatabaseReadOnly) { + if (!mMergeDataAllowed) { menu.findItem(R.id.menu_merge_database)?.isVisible = false } } diff --git a/app/src/main/java/com/kunzisoft/keepass/settings/SettingsActivity.kt b/app/src/main/java/com/kunzisoft/keepass/settings/SettingsActivity.kt index a9197d910..04f19014c 100644 --- a/app/src/main/java/com/kunzisoft/keepass/settings/SettingsActivity.kt +++ b/app/src/main/java/com/kunzisoft/keepass/settings/SettingsActivity.kt @@ -30,6 +30,7 @@ import android.widget.Toast import androidx.appcompat.widget.Toolbar import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.fragment.app.Fragment +import com.google.android.material.floatingactionbutton.FloatingActionButton import com.kunzisoft.keepass.R import com.kunzisoft.keepass.activities.dialogs.AssignMasterKeyDialogFragment import com.kunzisoft.keepass.activities.helpers.ExternalFileHelper @@ -52,7 +53,7 @@ open class SettingsActivity private var coordinatorLayout: CoordinatorLayout? = null private var toolbar: Toolbar? = null - private var lockView: View? = null + private var lockView: FloatingActionButton? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -112,11 +113,12 @@ open class SettingsActivity } if (savedInstanceState == null) { + lockView?.visibility = View.GONE supportFragmentManager.beginTransaction() .add(R.id.fragment_container, retrieveMainFragment()) .commit() } else { - lockView?.visibility = if (savedInstanceState.getBoolean(SHOW_LOCK)) View.VISIBLE else View.GONE + if (savedInstanceState.getBoolean(SHOW_LOCK)) lockView?.show() else lockView?.hide() } backupManager = BackupManager(this) @@ -187,14 +189,14 @@ open class SettingsActivity NestedSettingsFragment.Screen.DATABASE, NestedSettingsFragment.Screen.DATABASE_MASTER_KEY, NestedSettingsFragment.Screen.DATABASE_SECURITY -> { - lockView?.visibility = View.VISIBLE + lockView?.show() } else -> { - lockView?.visibility = View.GONE + lockView?.hide() } } } else { - lockView?.visibility = View.GONE + lockView?.hide() } } diff --git a/app/src/main/res/layout/activity_toolbar.xml b/app/src/main/res/layout/activity_toolbar.xml index 6a8fa665f..be4dd28bd 100644 --- a/app/src/main/res/layout/activity_toolbar.xml +++ b/app/src/main/res/layout/activity_toolbar.xml @@ -44,7 +44,6 @@ layout="@layout/view_button_lock" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:visibility="gone" android:layout_gravity="start|bottom" /> \ No newline at end of file From cdcc9f0affc65ba1043becedafed7b2b498b931f Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Wed, 26 Jan 2022 19:02:54 +0100 Subject: [PATCH 085/112] Change tags views --- app/src/main/res/layout/activity_entry.xml | 1 + app/src/main/res/layout/item_tag.xml | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/app/src/main/res/layout/activity_entry.xml b/app/src/main/res/layout/activity_entry.xml index b72222909..7c264f82d 100644 --- a/app/src/main/res/layout/activity_entry.xml +++ b/app/src/main/res/layout/activity_entry.xml @@ -113,6 +113,7 @@ android:layout_height="wrap_content" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" + android:paddingTop="12dp" android:paddingStart="5dp" android:paddingLeft="5dp" android:paddingEnd="5dp" diff --git a/app/src/main/res/layout/item_tag.xml b/app/src/main/res/layout/item_tag.xml index cb492d3c9..20b544bb7 100644 --- a/app/src/main/res/layout/item_tag.xml +++ b/app/src/main/res/layout/item_tag.xml @@ -22,7 +22,7 @@ android:layout_marginLeft="5dp" android:layout_marginEnd="5dp" android:layout_marginRight="5dp" - android:layout_marginTop="2dp" + android:layout_marginTop="1dp" android:layout_marginBottom="2dp" android:paddingBottom="0dp" android:orientation="horizontal"> From ee3ec4b14d20a5b03e4a37299175dd305333769b Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Wed, 26 Jan 2022 19:40:28 +0100 Subject: [PATCH 086/112] Add tags to group --- .../activities/dialogs/GroupDialogFragment.kt | 14 ++++++++++++ .../dialogs/GroupEditDialogFragment.kt | 22 +++++++++++++++++++ .../activities/fragments/EntryEditFragment.kt | 2 +- .../keepass/database/element/Group.kt | 3 ++- .../com/kunzisoft/keepass/model/GroupInfo.kt | 6 +++++ app/src/main/res/layout/fragment_group.xml | 20 ++++++++++++++--- .../main/res/layout/fragment_group_edit.xml | 17 +++++++++----- 7 files changed, 73 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/GroupDialogFragment.kt b/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/GroupDialogFragment.kt index 1038df7fe..8c1cb5899 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/GroupDialogFragment.kt +++ b/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/GroupDialogFragment.kt @@ -27,7 +27,10 @@ import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.appcompat.app.AlertDialog +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView import com.kunzisoft.keepass.R +import com.kunzisoft.keepass.adapters.TagsAdapter import com.kunzisoft.keepass.database.element.Database import com.kunzisoft.keepass.database.element.icon.IconImage import com.kunzisoft.keepass.model.GroupInfo @@ -43,6 +46,8 @@ class GroupDialogFragment : DatabaseDialogFragment() { private lateinit var iconView: ImageView private var mIconColor: Int = 0 private lateinit var nameTextView: TextView + private lateinit var tagsListView: RecyclerView + private var tagsAdapter: TagsAdapter? = null private lateinit var notesTextLabelView: TextView private lateinit var notesTextView: TextView private lateinit var expirationView: DateTimeFieldView @@ -64,6 +69,7 @@ class GroupDialogFragment : DatabaseDialogFragment() { val root = activity.layoutInflater.inflate(R.layout.fragment_group, null) iconView = root.findViewById(R.id.group_icon) nameTextView = root.findViewById(R.id.group_name) + tagsListView = root.findViewById(R.id.group_tags_list_view) notesTextLabelView = root.findViewById(R.id.group_note_label) notesTextView = root.findViewById(R.id.group_note) expirationView = root.findViewById(R.id.group_expiration) @@ -96,6 +102,14 @@ class GroupDialogFragment : DatabaseDialogFragment() { nameTextView.text = title nameTextView.visibility = View.VISIBLE } + tagsAdapter = TagsAdapter(activity) + tagsListView.apply { + layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) + adapter = tagsAdapter + } + val tags = mGroupInfo.tags + tagsListView.visibility = if (tags.isEmpty()) View.GONE else View.VISIBLE + tagsAdapter?.setTags(tags) val notes = mGroupInfo.notes if (notes == null || notes.isEmpty()) { notesTextLabelView.visibility = View.GONE diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/GroupEditDialogFragment.kt b/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/GroupEditDialogFragment.kt index 482bdb05e..8fc8b6eef 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/GroupEditDialogFragment.kt +++ b/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/GroupEditDialogFragment.kt @@ -31,12 +31,15 @@ import androidx.fragment.app.activityViewModels import com.google.android.material.textfield.TextInputLayout import com.kunzisoft.keepass.R import com.kunzisoft.keepass.activities.dialogs.GroupEditDialogFragment.EditGroupDialogAction.* +import com.kunzisoft.keepass.adapters.TagsProposalAdapter import com.kunzisoft.keepass.database.element.Database import com.kunzisoft.keepass.database.element.DateInstant import com.kunzisoft.keepass.database.element.icon.IconImage import com.kunzisoft.keepass.model.GroupInfo import com.kunzisoft.keepass.view.DateTimeEditFieldView +import com.kunzisoft.keepass.view.TagsCompletionView import com.kunzisoft.keepass.viewmodels.GroupEditViewModel +import com.tokenautocomplete.FilteredArrayAdapter import org.joda.time.DateTime class GroupEditDialogFragment : DatabaseDialogFragment() { @@ -55,6 +58,8 @@ class GroupEditDialogFragment : DatabaseDialogFragment() { private lateinit var notesTextLayoutView: TextInputLayout private lateinit var notesTextView: TextView private lateinit var expirationView: DateTimeEditFieldView + private lateinit var tagsCompletionView: TagsCompletionView + private var tagsAdapter: FilteredArrayAdapter? = null enum class EditGroupDialogAction { CREATION, UPDATE, NONE; @@ -122,6 +127,7 @@ class GroupEditDialogFragment : DatabaseDialogFragment() { notesTextLayoutView = root.findViewById(R.id.group_edit_note_container) notesTextView = root.findViewById(R.id.group_edit_note) expirationView = root.findViewById(R.id.group_edit_expiration) + tagsCompletionView = root.findViewById(R.id.group_tags_completion_view) // Retrieve the textColor to tint the icon val ta = activity.theme.obtainStyledAttributes(intArrayOf(android.R.attr.textColor)) @@ -143,6 +149,13 @@ class GroupEditDialogFragment : DatabaseDialogFragment() { } } + // TODO default tags in pool + tagsAdapter = TagsProposalAdapter(requireContext(), arrayOf()) + tagsCompletionView.apply { + threshold = 1 + setAdapter(tagsAdapter) + } + // populate info in views populateInfoToViews(mGroupInfo) @@ -197,6 +210,14 @@ class GroupEditDialogFragment : DatabaseDialogFragment() { } expirationView.activation = groupInfo.expires expirationView.dateTime = groupInfo.expiryTime + + // Set Tags + groupInfo.tags.let { tags -> + tagsCompletionView.setText("") + for (i in 0 until tags.size()) { + tagsCompletionView.addObjectSync(tags.get(i)) + } + } } private fun retrieveGroupInfoFromViews() { @@ -208,6 +229,7 @@ class GroupEditDialogFragment : DatabaseDialogFragment() { } mGroupInfo.expires = expirationView.activation mGroupInfo.expiryTime = expirationView.dateTime + mGroupInfo.tags = tagsCompletionView.getTags() } override fun onSaveInstanceState(outState: Bundle) { diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/fragments/EntryEditFragment.kt b/app/src/main/java/com/kunzisoft/keepass/activities/fragments/EntryEditFragment.kt index a2decd806..b6f94248a 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/fragments/EntryEditFragment.kt +++ b/app/src/main/java/com/kunzisoft/keepass/activities/fragments/EntryEditFragment.kt @@ -99,7 +99,7 @@ class EntryEditFragment: DatabaseFragment() { } // TODO default tags in pool - tagsAdapter = TagsProposalAdapter(requireContext(), arrayOf("test")) + tagsAdapter = TagsProposalAdapter(requireContext(), arrayOf()) tagsCompletionView.apply { threshold = 1 setAdapter(tagsAdapter) diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/Group.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/Group.kt index 3772026e2..c1d001462 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/Group.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/Group.kt @@ -31,7 +31,6 @@ import com.kunzisoft.keepass.database.element.node.* import com.kunzisoft.keepass.model.EntryInfo import com.kunzisoft.keepass.model.GroupInfo import com.kunzisoft.keepass.settings.PreferencesUtil -import com.kunzisoft.keepass.utils.UuidUtil import java.util.* import kotlin.collections.ArrayList @@ -463,6 +462,7 @@ class Group : Node, GroupVersionedInterface { groupInfo.expires = expires groupInfo.expiryTime = expiryTime groupInfo.notes = notes + groupInfo.tags = tags return groupInfo } @@ -475,6 +475,7 @@ class Group : Node, GroupVersionedInterface { expires = groupInfo.expires expiryTime = groupInfo.expiryTime notes = groupInfo.notes + tags = groupInfo.tags } override fun equals(other: Any?): Boolean { diff --git a/app/src/main/java/com/kunzisoft/keepass/model/GroupInfo.kt b/app/src/main/java/com/kunzisoft/keepass/model/GroupInfo.kt index 96f491462..c7e146d29 100644 --- a/app/src/main/java/com/kunzisoft/keepass/model/GroupInfo.kt +++ b/app/src/main/java/com/kunzisoft/keepass/model/GroupInfo.kt @@ -3,6 +3,7 @@ package com.kunzisoft.keepass.model import android.os.Parcel import android.os.ParcelUuid import android.os.Parcelable +import com.kunzisoft.keepass.database.element.Tags import com.kunzisoft.keepass.database.element.icon.IconImageStandard import com.kunzisoft.keepass.database.element.icon.IconImageStandard.Companion.FOLDER_ID import java.util.* @@ -11,6 +12,7 @@ class GroupInfo : NodeInfo { var id: UUID? = null var notes: String? = null + var tags: Tags = Tags() init { icon.standard = IconImageStandard(FOLDER_ID) @@ -21,6 +23,7 @@ class GroupInfo : NodeInfo { constructor(parcel: Parcel): super(parcel) { id = parcel.readParcelable(ParcelUuid::class.java.classLoader)?.uuid ?: id notes = parcel.readString() + tags = parcel.readParcelable(Tags::class.java.classLoader) ?: tags } override fun writeToParcel(parcel: Parcel, flags: Int) { @@ -28,6 +31,7 @@ class GroupInfo : NodeInfo { val uuid = if (id != null) ParcelUuid(id) else null parcel.writeParcelable(uuid, flags) parcel.writeString(notes) + parcel.writeParcelable(tags, flags) } override fun equals(other: Any?): Boolean { @@ -37,6 +41,7 @@ class GroupInfo : NodeInfo { if (id != other.id) return false if (notes != other.notes) return false + if (tags != other.tags) return false return true } @@ -45,6 +50,7 @@ class GroupInfo : NodeInfo { var result = super.hashCode() result = 31 * result + (id?.hashCode() ?: 0) result = 31 * result + (notes?.hashCode() ?: 0) + result = 31 * result + tags.hashCode() return result } diff --git a/app/src/main/res/layout/fragment_group.xml b/app/src/main/res/layout/fragment_group.xml index d7492167e..9c3cecb9b 100644 --- a/app/src/main/res/layout/fragment_group.xml +++ b/app/src/main/res/layout/fragment_group.xml @@ -17,11 +17,11 @@ You should have received a copy of the GNU General Public License along with KeePassDX. If not, see . --> - + android:layout_height="match_parent" + xmlns:app="http://schemas.android.com/apk/res-auto"> + + + @@ -68,8 +64,17 @@ + + android:hint="@string/tags" + style="@style/KeepassDXStyle.TextInputLayout.ExposedMenu"> + + From 49f9964bc7db0442de870c1bb2394f1eba7a3994 Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Thu, 27 Jan 2022 15:37:37 +0100 Subject: [PATCH 087/112] Add pool of tags --- .../activities/dialogs/GroupEditDialogFragment.kt | 14 +++++++------- .../activities/fragments/EntryEditFragment.kt | 13 ++++++------- .../keepass/adapters/TagsProposalAdapter.kt | 9 +++++++-- .../kunzisoft/keepass/database/element/Database.kt | 5 +++++ .../com/kunzisoft/keepass/database/element/Tags.kt | 12 +++++++++++- .../database/element/database/DatabaseKDBX.kt | 6 ++++++ .../database/file/input/DatabaseInputKDBX.kt | 5 +++-- 7 files changed, 45 insertions(+), 19 deletions(-) diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/GroupEditDialogFragment.kt b/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/GroupEditDialogFragment.kt index 8fc8b6eef..29de1d2c8 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/GroupEditDialogFragment.kt +++ b/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/GroupEditDialogFragment.kt @@ -112,10 +112,17 @@ class GroupEditDialogFragment : DatabaseDialogFragment() { override fun onDatabaseRetrieved(database: Database?) { super.onDatabaseRetrieved(database) + mPopulateIconMethod = { imageView, icon -> database?.iconDrawableFactory?.assignDatabaseIcon(imageView, icon, mIconColor) } mPopulateIconMethod?.invoke(iconButtonView, mGroupInfo.icon) + + tagsAdapter = TagsProposalAdapter(requireContext(), database?.tagPool) + tagsCompletionView.apply { + threshold = 1 + setAdapter(tagsAdapter) + } } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { @@ -149,13 +156,6 @@ class GroupEditDialogFragment : DatabaseDialogFragment() { } } - // TODO default tags in pool - tagsAdapter = TagsProposalAdapter(requireContext(), arrayOf()) - tagsCompletionView.apply { - threshold = 1 - setAdapter(tagsAdapter) - } - // populate info in views populateInfoToViews(mGroupInfo) diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/fragments/EntryEditFragment.kt b/app/src/main/java/com/kunzisoft/keepass/activities/fragments/EntryEditFragment.kt index b6f94248a..46b040868 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/fragments/EntryEditFragment.kt +++ b/app/src/main/java/com/kunzisoft/keepass/activities/fragments/EntryEditFragment.kt @@ -98,13 +98,6 @@ class EntryEditFragment: DatabaseFragment() { (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false } - // TODO default tags in pool - tagsAdapter = TagsProposalAdapter(requireContext(), arrayOf()) - tagsCompletionView.apply { - threshold = 1 - setAdapter(tagsAdapter) - } - templateView.apply { setOnIconClickListener { mEntryEditViewModel.requestIconSelection(templateView.getIcon()) @@ -288,6 +281,12 @@ class EntryEditFragment: DatabaseFragment() { attachmentsContainerView.expand(true) } } + + tagsAdapter = TagsProposalAdapter(requireContext(), database?.tagPool) + tagsCompletionView.apply { + threshold = 1 + setAdapter(tagsAdapter) + } } private fun assignEntryInfo(entryInfo: EntryInfo?) { diff --git a/app/src/main/java/com/kunzisoft/keepass/adapters/TagsProposalAdapter.kt b/app/src/main/java/com/kunzisoft/keepass/adapters/TagsProposalAdapter.kt index ba941b524..03bc72750 100644 --- a/app/src/main/java/com/kunzisoft/keepass/adapters/TagsProposalAdapter.kt +++ b/app/src/main/java/com/kunzisoft/keepass/adapters/TagsProposalAdapter.kt @@ -1,10 +1,15 @@ package com.kunzisoft.keepass.adapters import android.content.Context +import com.kunzisoft.keepass.database.element.Tags import com.tokenautocomplete.FilteredArrayAdapter -class TagsProposalAdapter(context: Context, proposal: Array) - : FilteredArrayAdapter(context, android.R.layout.simple_list_item_1, proposal) { +class TagsProposalAdapter(context: Context, proposal: Tags?) + : FilteredArrayAdapter( + context, + android.R.layout.simple_list_item_1, + (proposal ?: Tags()).toList() +) { override fun keepObject(obj: String, mask: String?): Boolean { if (mask == null) diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/Database.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/Database.kt index 249800f7e..52c11236b 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/Database.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/Database.kt @@ -816,6 +816,11 @@ class Database { }, omitBackup, max) } + val tagPool: Tags + get() { + return mDatabaseKDBX?.tagPool ?: Tags() + } + val attachmentPool: AttachmentPool get() { return mDatabaseKDB?.attachmentPool ?: mDatabaseKDBX?.attachmentPool ?: AttachmentPool() diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/Tags.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/Tags.kt index 7a16dfaa4..ed23507bb 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/Tags.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/Tags.kt @@ -6,7 +6,7 @@ import com.kunzisoft.keepass.utils.StringUtil.removeSpaceChars class Tags: Parcelable { - private val mTags = ArrayList() + private val mTags = mutableListOf() constructor() @@ -40,6 +40,12 @@ class Tags: Parcelable { mTags.add(tag) } + fun put(tags: Tags) { + tags.mTags.forEach { + put(it) + } + } + fun isEmpty(): Boolean { return mTags.isEmpty() } @@ -52,6 +58,10 @@ class Tags: Parcelable { mTags.clear() } + fun toList(): List { + return mTags + } + override fun toString(): String { return mTags.joinToString(DELIMITER.toString()) } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/database/DatabaseKDBX.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/database/DatabaseKDBX.kt index e2006de37..0ab0c90f7 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/database/DatabaseKDBX.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/database/DatabaseKDBX.kt @@ -34,6 +34,7 @@ import com.kunzisoft.keepass.database.crypto.kdf.KdfParameters import com.kunzisoft.keepass.database.element.CustomData import com.kunzisoft.keepass.database.element.DateInstant import com.kunzisoft.keepass.database.element.DeletedObject +import com.kunzisoft.keepass.database.element.Tags import com.kunzisoft.keepass.database.element.binary.BinaryData import com.kunzisoft.keepass.database.element.database.DatabaseKDB.Companion.BACKUP_FOLDER_TITLE import com.kunzisoft.keepass.database.element.entry.EntryKDBX @@ -165,6 +166,8 @@ class DatabaseKDBX : DatabaseVersioned { var publicCustomData = VariantDictionary() val customData = CustomData() + val tagPool = Tags() + var localizedAppName = "KeePassDX" constructor() @@ -833,16 +836,19 @@ class DatabaseKDBX : DatabaseVersioned { override fun addEntryTo(newEntry: EntryKDBX, parent: GroupKDBX?) { super.addEntryTo(newEntry, parent) + tagPool.put(newEntry.tags) mFieldReferenceEngine.clear() } override fun updateEntry(entry: EntryKDBX) { super.updateEntry(entry) + tagPool.put(entry.tags) mFieldReferenceEngine.clear() } override fun removeEntryFrom(entryToRemove: EntryKDBX, parent: GroupKDBX?) { super.removeEntryFrom(entryToRemove, parent) + // Do not remove tags from pool, it's only in temp memory mFieldReferenceEngine.clear() } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/input/DatabaseInputKDBX.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/input/DatabaseInputKDBX.kt index f9cb9d707..35d3a7661 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/input/DatabaseInputKDBX.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/input/DatabaseInputKDBX.kt @@ -24,7 +24,6 @@ import android.util.Log import com.kunzisoft.encrypt.StreamCipher import com.kunzisoft.keepass.database.crypto.CipherEngine import com.kunzisoft.keepass.database.crypto.CrsAlgorithm -import com.kunzisoft.keepass.database.crypto.EncryptionAlgorithm import com.kunzisoft.keepass.database.crypto.HmacBlock import com.kunzisoft.keepass.database.element.* import com.kunzisoft.keepass.database.element.binary.BinaryData @@ -876,7 +875,9 @@ class DatabaseInputKDBX(database: DatabaseKDBX) @Throws(IOException::class, XmlPullParserException::class) private fun readTags(xpp: XmlPullParser): Tags { - return Tags(readString(xpp)) + val tags = Tags(readString(xpp)) + mDatabase.tagPool.put(tags) + return tags } @Throws(XmlPullParserException::class, IOException::class) From 0e699a19180aa77ae420e53a5ced596414e918ea Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Thu, 27 Jan 2022 16:08:34 +0100 Subject: [PATCH 088/112] Add Tokenautocomplete from sources until https://github.com/splitwise/TokenAutoComplete/pull/422 fixed --- app/build.gradle | 4 +- .../tokenautocomplete/CharacterTokenizer.kt | 72 + .../java/com/tokenautocomplete/CountSpan.kt | 33 + .../java/com/tokenautocomplete/DummySpan.kt | 18 + .../tokenautocomplete/FilteredArrayAdapter.kt | 139 ++ .../java/com/tokenautocomplete/HintSpan.kt | 18 + .../main/java/com/tokenautocomplete/Range.kt | 41 + .../java/com/tokenautocomplete/SpanUtils.kt | 69 + .../com/tokenautocomplete/TagTokenizer.kt | 65 + .../TokenCompleteTextView.kt | 1570 +++++++++++++++++ .../java/com/tokenautocomplete/Tokenizer.kt | 34 + .../java/com/tokenautocomplete/ViewSpan.kt | 76 + 12 files changed, 2138 insertions(+), 1 deletion(-) create mode 100644 app/src/main/java/com/tokenautocomplete/CharacterTokenizer.kt create mode 100644 app/src/main/java/com/tokenautocomplete/CountSpan.kt create mode 100644 app/src/main/java/com/tokenautocomplete/DummySpan.kt create mode 100644 app/src/main/java/com/tokenautocomplete/FilteredArrayAdapter.kt create mode 100644 app/src/main/java/com/tokenautocomplete/HintSpan.kt create mode 100644 app/src/main/java/com/tokenautocomplete/Range.kt create mode 100644 app/src/main/java/com/tokenautocomplete/SpanUtils.kt create mode 100644 app/src/main/java/com/tokenautocomplete/TagTokenizer.kt create mode 100644 app/src/main/java/com/tokenautocomplete/TokenCompleteTextView.kt create mode 100644 app/src/main/java/com/tokenautocomplete/Tokenizer.kt create mode 100644 app/src/main/java/com/tokenautocomplete/ViewSpan.kt diff --git a/app/build.gradle b/app/build.gradle index fbb6160d2..c522ff32c 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,5 +1,6 @@ apply plugin: 'com.android.application' apply plugin: 'kotlin-android' +apply plugin: 'kotlin-parcelize' apply plugin: 'kotlin-kapt' android { @@ -116,7 +117,8 @@ dependencies { implementation 'androidx.fragment:fragment-ktx:1.4.0' implementation "com.google.android.material:material:$android_material_version" // Token auto complete - implementation "com.splitwise:tokenautocomplete:4.0.0-beta04" + // From sources until https://github.com/splitwise/TokenAutoComplete/pull/422 fixed + // implementation "com.splitwise:tokenautocomplete:4.0.0-beta04" // Database implementation "androidx.room:room-runtime:$room_version" kapt "androidx.room:room-compiler:$room_version" diff --git a/app/src/main/java/com/tokenautocomplete/CharacterTokenizer.kt b/app/src/main/java/com/tokenautocomplete/CharacterTokenizer.kt new file mode 100644 index 000000000..7c41eeda1 --- /dev/null +++ b/app/src/main/java/com/tokenautocomplete/CharacterTokenizer.kt @@ -0,0 +1,72 @@ +package com.tokenautocomplete + +import android.annotation.SuppressLint +import android.text.SpannableString +import android.text.Spanned +import android.text.TextUtils +import kotlinx.parcelize.Parcelize +import java.util.* + +/** + * Tokenizer with configurable array of characters to tokenize on. + * + * Created on 2/3/15. + * @author mgod + */ +@Parcelize +@SuppressLint("ParcelCreator") +open class CharacterTokenizer(private val splitChar: List, private val tokenTerminator: String) : Tokenizer { + override fun containsTokenTerminator(charSequence: CharSequence): Boolean { + for (element in charSequence) { + if (splitChar.contains(element)) { + return true + } + } + return false + } + + override fun findTokenRanges(charSequence: CharSequence, start: Int, end: Int): List { + val result = ArrayList() + if (start == end) { + //Can't have a 0 length token + return result + } + var tokenStart = start + for (cursor in start until end) { + val character = charSequence[cursor] + + //Avoid including leading whitespace, tokenStart will match the cursor as long as we're at the start + if (tokenStart == cursor && Character.isWhitespace(character)) { + tokenStart = cursor + 1 + } + + //Either this is a split character, or we contain some content and are at the end of input + if (splitChar.contains(character) || cursor == end - 1) { + val hasTokenContent = //There is token content befor the current character + cursor > tokenStart || //If the current single character is valid token content, not a split char or whitespace + cursor == tokenStart && !splitChar.contains(character) + if (hasTokenContent) { + //There is some token content + //Add one to range end as the end of the ranges is not inclusive + result.add(Range(tokenStart, cursor + 1)) + } + tokenStart = cursor + 1 + } + } + return result + } + + override fun wrapTokenValue(unwrappedTokenValue: CharSequence): CharSequence { + val wrappedText: CharSequence = unwrappedTokenValue.toString() + tokenTerminator + return if (unwrappedTokenValue is Spanned) { + val sp = SpannableString(wrappedText) + TextUtils.copySpansFrom( + unwrappedTokenValue, 0, unwrappedTokenValue.length, + Any::class.java, sp, 0 + ) + sp + } else { + wrappedText + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/tokenautocomplete/CountSpan.kt b/app/src/main/java/com/tokenautocomplete/CountSpan.kt new file mode 100644 index 000000000..5df50c1c0 --- /dev/null +++ b/app/src/main/java/com/tokenautocomplete/CountSpan.kt @@ -0,0 +1,33 @@ +package com.tokenautocomplete + +import android.text.Layout +import android.text.TextPaint +import android.text.style.CharacterStyle +import java.util.* + +/** + * Span that displays +[count] + * + * Created on 2/3/15. + * @author mgod + */ +class CountSpan : CharacterStyle() { + var countText = "" + private set + + override fun updateDrawState(textPaint: TextPaint) { + //Do nothing, we are using this span as a location marker + } + + fun setCount(c: Int) { + countText = if (c > 0) { + String.format(Locale.getDefault(), " +%d", c) + } else { + "" + } + } + + fun getCountTextWidthForPaint(paint: TextPaint?): Float { + return Layout.getDesiredWidth(countText, 0, countText.length, paint) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/tokenautocomplete/DummySpan.kt b/app/src/main/java/com/tokenautocomplete/DummySpan.kt new file mode 100644 index 000000000..3078f0c95 --- /dev/null +++ b/app/src/main/java/com/tokenautocomplete/DummySpan.kt @@ -0,0 +1,18 @@ +package com.tokenautocomplete + +import android.text.TextPaint +import android.text.style.MetricAffectingSpan + +/** + * Invisible MetricAffectingSpan that will trigger a redraw when it is being added to or removed from an Editable. + * + * @see TokenCompleteTextView.redrawTokens + */ +internal class DummySpan private constructor() : MetricAffectingSpan() { + override fun updateMeasureState(textPaint: TextPaint) {} + override fun updateDrawState(tp: TextPaint) {} + + companion object { + val INSTANCE = DummySpan() + } +} \ No newline at end of file diff --git a/app/src/main/java/com/tokenautocomplete/FilteredArrayAdapter.kt b/app/src/main/java/com/tokenautocomplete/FilteredArrayAdapter.kt new file mode 100644 index 000000000..d77121127 --- /dev/null +++ b/app/src/main/java/com/tokenautocomplete/FilteredArrayAdapter.kt @@ -0,0 +1,139 @@ +package com.tokenautocomplete + +import android.content.Context +import android.widget.ArrayAdapter +import android.widget.Filter +import java.util.* + +/** + * Simplified custom filtered ArrayAdapter + * override keepObject with your test for filtering + * + * + * Based on gist [ + * FilteredArrayAdapter](https://gist.github.com/tobiasschuerg/3554252/raw/30634bf9341311ac6ad6739ef094222fc5f07fa8/FilteredArrayAdapter.java) by Tobias Schürg + * + * + * Created on 9/17/13. + * @author mgod + */ +abstract class FilteredArrayAdapter +/** + * Constructor + * + * @param context The current context. + * @param resource The resource ID for a layout file containing a layout to use when + * instantiating views. + * @param textViewResourceId The id of the TextView within the layout resource to be populated + * @param objects The objects to represent in the ListView. + */( + context: Context, + resource: Int, + textViewResourceId: Int, + objects: List +) : ArrayAdapter( + context, resource, textViewResourceId, ArrayList(objects) +) { + private val originalObjects: List = objects + private var filter: Filter? = null + + /** + * Constructor + * + * @param context The current context. + * @param resource The resource ID for a layout file containing a TextView to use when + * instantiating views. + * @param objects The objects to represent in the ListView. + */ + constructor(context: Context, resource: Int, objects: Array) : this( + context, + resource, + 0, + objects + ) + + /** + * Constructor + * + * @param context The current context. + * @param resource The resource ID for a layout file containing a layout to use when + * instantiating views. + * @param textViewResourceId The id of the TextView within the layout resource to be populated + * @param objects The objects to represent in the ListView. + */ + constructor( + context: Context, + resource: Int, + textViewResourceId: Int, + objects: Array + ) : this(context, resource, textViewResourceId, ArrayList(listOf(*objects))) + + /** + * Constructor + * + * @param context The current context. + * @param resource The resource ID for a layout file containing a TextView to use when + * instantiating views. + * @param objects The objects to represent in the ListView. + */ + @Suppress("unused") + constructor(context: Context, resource: Int, objects: List) : this( + context, + resource, + 0, + objects + ) + + override fun getFilter(): Filter { + if (filter == null) filter = AppFilter() + return filter!! + } + + /** + * Filter method used by the adapter. Return true if the object should remain in the list + * + * @param obj object we are checking for inclusion in the adapter + * @param mask current text in the edit text we are completing against + * @return true if we should keep the item in the adapter + */ + protected abstract fun keepObject(obj: T, mask: String?): Boolean + + /** + * Class for filtering Adapter, relies on keepObject in FilteredArrayAdapter + * + * based on gist by Tobias Schürg + * in turn inspired by inspired by Alxandr + * (http://stackoverflow.com/a/2726348/570168) + */ + private inner class AppFilter : Filter() { + override fun performFiltering(chars: CharSequence?): FilterResults { + val sourceObjects = ArrayList(originalObjects) + val result = FilterResults() + if (chars != null && chars.isNotEmpty()) { + val mask = chars.toString() + val keptObjects = ArrayList() + for (sourceObject in sourceObjects) { + if (keepObject(sourceObject, mask)) keptObjects.add(sourceObject) + } + result.count = keptObjects.size + result.values = keptObjects + } else { + // add all objects + result.values = sourceObjects + result.count = sourceObjects.size + } + return result + } + + override fun publishResults(constraint: CharSequence?, results: FilterResults) { + clear() + if (results.count > 0) { + @Suppress("unchecked_cast") + this@FilteredArrayAdapter.addAll(results.values as Collection) + notifyDataSetChanged() + } else { + notifyDataSetInvalidated() + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/tokenautocomplete/HintSpan.kt b/app/src/main/java/com/tokenautocomplete/HintSpan.kt new file mode 100644 index 000000000..77f07d0a8 --- /dev/null +++ b/app/src/main/java/com/tokenautocomplete/HintSpan.kt @@ -0,0 +1,18 @@ +package com.tokenautocomplete + +import android.content.res.ColorStateList +import android.text.style.TextAppearanceSpan + +/** + * Subclass of TextAppearanceSpan just to work with how Spans get detected + * + * Created on 2/3/15. + * @author mgod + */ +internal class HintSpan( + family: String?, + style: Int, + size: Int, + color: ColorStateList?, + linkColor: ColorStateList? +) : TextAppearanceSpan(family, style, size, color, linkColor) \ No newline at end of file diff --git a/app/src/main/java/com/tokenautocomplete/Range.kt b/app/src/main/java/com/tokenautocomplete/Range.kt new file mode 100644 index 000000000..e05ac58ab --- /dev/null +++ b/app/src/main/java/com/tokenautocomplete/Range.kt @@ -0,0 +1,41 @@ +package com.tokenautocomplete + +import java.util.* + +class Range(start: Int, end: Int) { + @JvmField + val start: Int + @JvmField + val end: Int + fun length(): Int { + return end - start + } + + override fun equals(other: Any?): Boolean { + if (null == other || other !is Range) { + return false + } + return other.start == start && other.end == end + } + + override fun toString(): String { + return String.format(Locale.US, "[%d..%d]", start, end) + } + + override fun hashCode(): Int { + var result = start + result = 31 * result + end + return result + } + + init { + require(start <= end) { + String.format( + Locale.ENGLISH, + "Start (%d) cannot be greater than end (%d)", start, end + ) + } + this.start = start + this.end = end + } +} \ No newline at end of file diff --git a/app/src/main/java/com/tokenautocomplete/SpanUtils.kt b/app/src/main/java/com/tokenautocomplete/SpanUtils.kt new file mode 100644 index 000000000..d0fcb6400 --- /dev/null +++ b/app/src/main/java/com/tokenautocomplete/SpanUtils.kt @@ -0,0 +1,69 @@ +package com.tokenautocomplete + +import android.text.SpannableStringBuilder +import android.text.Spanned +import android.text.TextPaint +import android.text.TextUtils +import com.tokenautocomplete.TokenCompleteTextView.TokenImageSpan + +internal object SpanUtils { + @JvmStatic + fun ellipsizeWithSpans( + prefix: CharSequence?, countSpan: CountSpan?, + tokenCount: Int, paint: TextPaint, + originalText: CharSequence, maxWidth: Float + ): Spanned? { + var countWidth = 0f + if (countSpan != null) { + //Assume the largest possible number of items for measurement + countSpan.setCount(tokenCount) + countWidth = countSpan.getCountTextWidthForPaint(paint) + } + val ellipsizeCallback = EllipsizeCallback() + val tempEllipsized = TextUtils.ellipsize( + originalText, paint, maxWidth - countWidth, + TextUtils.TruncateAt.END, false, ellipsizeCallback + ) + val ellipsized = SpannableStringBuilder(tempEllipsized) + if (tempEllipsized is Spanned) { + TextUtils.copySpansFrom( + tempEllipsized, + 0, + tempEllipsized.length, + Any::class.java, + ellipsized, + 0 + ) + } + if (prefix != null && prefix.length > ellipsizeCallback.start) { + //We ellipsized part of the prefix, so put it back + ellipsized.replace(0, ellipsizeCallback.start, prefix) + ellipsizeCallback.end = ellipsizeCallback.end + prefix.length - ellipsizeCallback.start + ellipsizeCallback.start = prefix.length + } + if (ellipsizeCallback.start != ellipsizeCallback.end) { + if (countSpan != null) { + val visibleCount = + ellipsized.getSpans(0, ellipsized.length, TokenImageSpan::class.java).size + countSpan.setCount(tokenCount - visibleCount) + ellipsized.replace(ellipsizeCallback.start, ellipsized.length, countSpan.countText) + ellipsized.setSpan( + countSpan, ellipsizeCallback.start, ellipsized.length, + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE + ) + } + return ellipsized + } + //No ellipses necessary + return null + } + + private class EllipsizeCallback : TextUtils.EllipsizeCallback { + var start = 0 + var end = 0 + override fun ellipsized(ellipsedStart: Int, ellipsedEnd: Int) { + start = ellipsedStart + end = ellipsedEnd + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/tokenautocomplete/TagTokenizer.kt b/app/src/main/java/com/tokenautocomplete/TagTokenizer.kt new file mode 100644 index 000000000..8c9713c4c --- /dev/null +++ b/app/src/main/java/com/tokenautocomplete/TagTokenizer.kt @@ -0,0 +1,65 @@ +package com.tokenautocomplete + +import android.annotation.SuppressLint +import kotlinx.parcelize.Parcelize +import java.util.* + +@Parcelize +@SuppressLint("ParcelCreator") +open class TagTokenizer constructor(private val tagPrefixes: List) : Tokenizer { + + internal constructor() : this(listOf('@', '#')) + + @Suppress("MemberVisibilityCanBePrivate") + protected fun isTokenTerminator(character: Char): Boolean { + //Allow letters, numbers and underscores + return !Character.isLetterOrDigit(character) && character != '_' + } + + override fun containsTokenTerminator(charSequence: CharSequence): Boolean { + for (element in charSequence) { + if (isTokenTerminator(element)) { + return true + } + } + return false + } + + override fun findTokenRanges(charSequence: CharSequence, start: Int, end: Int): List { + val result = ArrayList() + if (start == end) { + //Can't have a 0 length token + return result + } + var tokenStart = Int.MAX_VALUE + for (cursor in start until end) { + val character = charSequence[cursor] + + //Either this is a terminator, or we contain some content and are at the end of input + if (isTokenTerminator(character)) { + //Is there some token content? Might just be two terminators in a row + if (cursor - 1 > tokenStart) { + result.add(Range(tokenStart, cursor)) + } + + //mark that we don't have a candidate token start any more + tokenStart = Int.MAX_VALUE + } + + //Set tokenStart when we hit a tag prefix + if (tagPrefixes.contains(character)) { + tokenStart = cursor + } + } + if (end > tokenStart) { + //There was unterminated text after a start of token + result.add(Range(tokenStart, end)) + } + return result + } + + override fun wrapTokenValue(unwrappedTokenValue: CharSequence): CharSequence { + return unwrappedTokenValue + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/tokenautocomplete/TokenCompleteTextView.kt b/app/src/main/java/com/tokenautocomplete/TokenCompleteTextView.kt new file mode 100644 index 000000000..45d9ef868 --- /dev/null +++ b/app/src/main/java/com/tokenautocomplete/TokenCompleteTextView.kt @@ -0,0 +1,1570 @@ +package com.tokenautocomplete + +import android.content.Context +import android.graphics.Rect +import android.graphics.Typeface +import android.os.Build +import android.os.Parcel +import android.os.Parcelable +import android.text.Editable +import android.text.InputFilter +import android.text.InputType +import android.text.Layout +import android.text.NoCopySpan +import android.text.Selection +import android.text.SpanWatcher +import android.text.Spannable +import android.text.SpannableString +import android.text.SpannableStringBuilder +import android.text.Spanned +import android.text.TextUtils +import android.text.TextWatcher +import android.text.style.ForegroundColorSpan +import android.util.AttributeSet +import android.util.Log +import android.view.KeyEvent +import android.view.MotionEvent +import android.view.View +import android.view.accessibility.AccessibilityEvent +import android.view.inputmethod.EditorInfo +import android.view.inputmethod.ExtractedText +import android.view.inputmethod.ExtractedTextRequest +import android.view.inputmethod.InputConnection +import android.view.inputmethod.InputConnectionWrapper +import android.view.inputmethod.InputMethodManager +import android.widget.ListView +import android.widget.TextView +import android.widget.TextView.OnEditorActionListener +import androidx.annotation.UiThread +import androidx.appcompat.widget.AppCompatAutoCompleteTextView +import java.io.Serializable +import java.lang.reflect.ParameterizedType +import java.util.* + +/** + * GMail style auto complete view with easy token customization + * override getViewForObject to provide your token view + *

+ * Created by mgod on 9/12/13. + * + * @author mgod + */ +abstract class TokenCompleteTextView : AppCompatAutoCompleteTextView, OnEditorActionListener, + ViewSpan.Layout { + //When the user clicks on a token... + enum class TokenClickStyle(val isSelectable: Boolean) { + None(false), //...do nothing, but make sure the cursor is not in the token + Delete(false), //...delete the token + Select(true), //...select the token. A second click will delete it. + SelectDeselect(true); + + } + + private var tokenizer: Tokenizer? = null + private var selectedObject: T? = null + private var listener: TokenListener? = null + private var spanWatcher: TokenSpanWatcher = TokenSpanWatcher() + private var textWatcher: TokenTextWatcher = TokenTextWatcher() + private var countSpan: CountSpan = CountSpan() + private var hiddenContent: SpannableStringBuilder? = null + private var tokenClickStyle: TokenClickStyle? = TokenClickStyle.None + private var prefix: CharSequence? = null + private var lastLayout: Layout? = null + private var initialized = false + private var performBestGuess = true + private var preventFreeFormText = true + private var savingState = false + private var shouldFocusNext = false + private var allowCollapse = true + private var internalEditInProgress = false + private var inBatchEditAPI26to29Workaround = false + private var tokenLimit = -1 + + /** + * Android M/API 30 introduced a change to the SpannableStringBuilder that triggers additional + * text change callbacks when we do our token replacement. It's supposed to report if it's a + * recursive call to the callbacks to let the recipient handle nested calls differently, but + * for some reason, in our case the first and second callbacks both report a depth of 1 and only + * on the third callback do we get a depth of 2, so we need to track this ourselves. + */ + private var ignoreNextTextCommit = false + + @Transient + private var lastCompletionText: String? = null + + private val hintVisible: Boolean + get() { + return text.getSpans(0, text.length, HintSpan::class.java).isNotEmpty() + } + + /** + * Add the TextChangedListeners + */ + protected open fun addListeners() { + val text = text + if (text != null) { + text.setSpan(spanWatcher, 0, text.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE) + addTextChangedListener(textWatcher) + } + } + + /** + * Remove the TextChangedListeners + */ + protected open fun removeListeners() { + val text = text + if (text != null) { + val spanWatchers = text.getSpans(0, text.length, TokenSpanWatcher::class.java) + for (watcher in spanWatchers) { + text.removeSpan(watcher) + } + removeTextChangedListener(textWatcher) + } + } + + /** + * Initialise the variables and various listeners + */ + private fun init() { + if (initialized) return + + // Initialise variables + setTokenizer(CharacterTokenizer(listOf(',', ';'), ",")) + + // Initialise TextChangedListeners + addListeners() + setTextIsSelectable(false) + isLongClickable = false + + //In theory, get the soft keyboard to not supply suggestions. very unreliable + inputType = inputType or + InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or + InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE + setHorizontallyScrolling(false) + + // Listen to IME action keys + setOnEditorActionListener(this) + + // Initialise the text filter (listens for the split chars) + filters = + arrayOf(InputFilter { source, _, _, _, destinationStart, destinationEnd -> + if (internalEditInProgress) { + return@InputFilter null + } + + // Token limit check + if (tokenLimit != -1 && objects.size == tokenLimit) { + return@InputFilter "" + } + + //Detect split characters, remove them and complete the current token instead + if (tokenizer!!.containsTokenTerminator(source)) { + //Only perform completion if we don't allow free form text, or if there's enough + //content to believe this should be a token + if (preventFreeFormText || currentCompletionText().isNotEmpty()) { + performCompletion() + return@InputFilter "" + } + } + + //We need to not do anything when we would delete the prefix + prefix?.also { prefix -> + if (destinationStart < prefix.length) { + //when setText is called, which should only be called during restoring, + //destinationStart and destinationEnd are 0. If not checked, it will clear out + //the prefix. + //This is why we need to return null in this if condition to preserve state. + if (destinationStart == 0 && destinationEnd == 0) { + return@InputFilter null + } else return@InputFilter if (destinationEnd <= prefix.length) { + //Don't do anything + prefix.subSequence(destinationStart, destinationEnd) + } else { + //Delete everything up to the prefix + prefix.subSequence(destinationStart, prefix.length) + } + } + } + null + }) + initialized = true + } + + constructor(context: Context) : super(context) { + init() + } + + constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { + init() + } + + constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super( + context, + attrs, + defStyle + ) { + init() + } + + override fun performFiltering(text: CharSequence, keyCode: Int) { + val filter = filter + filter?.filter(currentCompletionText(), this) + } + + fun setTokenizer(t: Tokenizer) { + tokenizer = t + } + + /** + * Set the action to be taken when a Token is clicked + * + * @param cStyle The TokenClickStyle + */ + fun setTokenClickStyle(cStyle: TokenClickStyle) { + tokenClickStyle = cStyle + } + + /** + * Set the listener that will be notified of changes in the Token list + * + * @param l The TokenListener + */ + fun setTokenListener(l: TokenListener?) { + listener = l + } + + /** + * Override if you want to prevent a token from being added. Defaults to false. + * @param token the token to check + * @return true if the token should not be added, false if it's ok to add it. + */ + open fun shouldIgnoreToken(token: T): Boolean { + return false + } + + /** + * Override if you want to prevent a token from being removed. Defaults to true. + * @param token the token to check + * @return false if the token should not be removed, true if it's ok to remove it. + */ + open fun isTokenRemovable(@Suppress("unused_parameter") token: T): Boolean { + return true + } + + /** + * A String of text that is shown before all the tokens inside the EditText + * (Think "To: " in an email address field. I would advise against this: use a label and a hint. + * + * @param p String with the hint + */ + @Suppress("MemberVisibilityCanBePrivate") + fun setPrefix(p: CharSequence) { + //Have to clear and set the actual text before saving the prefix to avoid the prefix filter + val prevPrefix = prefix + prefix = p + val text = text + if (text != null) { + internalEditInProgress = true + if (prevPrefix.isNullOrEmpty()) { + text.insert(0, p) + } else { + text.replace(0, prevPrefix.length, p) + } + internalEditInProgress = false + } + //prefix = p; + updateHint() + } + + /** + * + * You can get a color integer either using + * [androidx.core.content.ContextCompat.getColor] + * or with [android.graphics.Color.parseColor]. + * + * [android.graphics.Color.parseColor] + * accepts these formats (copied from android.graphics.Color): + * You can use: '#RRGGBB', '#AARRGGBB' + * or one of the following names: 'red', 'blue', 'green', 'black', 'white', + * 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray', 'grey', + * 'lightgrey', 'darkgrey', 'aqua', 'fuchsia', 'lime', 'maroon', 'navy', + * 'olive', 'purple', 'silver', 'teal'. + * + * @param prefix prefix + * @param color A single color value in the form 0xAARRGGBB. + */ + fun setPrefix(prefix: CharSequence, color: Int) { + val spannablePrefix = SpannableString(prefix) + spannablePrefix.setSpan(ForegroundColorSpan(color), 0, spannablePrefix.length, 0) + setPrefix(spannablePrefix) + } + + /** + * Get the list of Tokens + * + * @return List of tokens + */ + val objects: List + get() { + val objects = ArrayList() + var text = text + if (hiddenContent != null) { + text = hiddenContent + } + for (span in text.getSpans(0, text.length, TokenImageSpan::class.java)) { + @Suppress("unchecked_cast") + objects.add(span.token as T) + } + return objects + } + + /** + * Get the content entered in the text field, including hidden text when ellipsized + * + * @return CharSequence of the entered content + */ + val contentText: CharSequence + get() = hiddenContent ?: text + + /** + * Set whether we try to guess an entry from the autocomplete spinner or just use the + * defaultObject implementation for inline token completion. + * + * @param guess true to enable guessing + */ + fun performBestGuess(guess: Boolean) { + performBestGuess = guess + } + + /** + * If set to true, the only content in this view will be the tokens and the current completion + * text. Use this setting to create things like lists of email addresses. If false, it the view + * will allow text in addition to tokens. Use this if you want to use the token search to find + * things like user names or hash tags to put in with text. + * + * @param prevent true to prevent non-token text. Defaults to true. + */ + fun preventFreeFormText(prevent: Boolean) { + preventFreeFormText = prevent + } + + /** + * Set whether the view should collapse to a single line when it loses focus. + * + * @param allowCollapse true if it should collapse + */ + fun allowCollapse(allowCollapse: Boolean) { + this.allowCollapse = allowCollapse + } + + /** + * Set a number of tokens limit. + * + * @param tokenLimit The number of tokens permitted. -1 value disables limit. + */ + @Suppress("unused") + fun setTokenLimit(tokenLimit: Int) { + this.tokenLimit = tokenLimit + } + + /** + * A token view for the object + * + * @param obj the object selected by the user from the list + * @return a view to display a token in the text field for the object + */ + protected abstract fun getViewForObject(obj: T): View? + + /** + * Provides a default completion when the user hits , and there is no item in the completion + * list + * + * @param completionText the current text we are completing against + * @return a best guess for what the user meant to complete or null if you don't want a guess + */ + protected abstract fun defaultObject(completionText: String): T? + + //Replace token spans + //Need to take the existing tet buffer and + // - replace all tokens with a decent string representation of the object + // - set the selection span to the corresponding location in the new CharSequence + /** + * Correctly build accessibility string for token contents + * + * This seems to be a hidden API, but there doesn't seem to be another reasonable way + * @return custom string for accessibility + */ + @Suppress("MemberVisibilityCanBePrivate") + open val textForAccessibility: CharSequence + get() { + if (objects.isEmpty()) { + return text + } + var description = SpannableStringBuilder() + val text = text + var selectionStart = -1 + var selectionEnd = -1 + var i: Int + //Need to take the existing tet buffer and + // - replace all tokens with a decent string representation of the object + // - set the selection span to the corresponding location in the new CharSequence + i = 0 + while (i < text.length) { + + //See if this is where we should start the selection + val origSelectionStart = Selection.getSelectionStart(text) + if (i == origSelectionStart) { + selectionStart = description.length + } + val origSelectionEnd = Selection.getSelectionEnd(text) + if (i == origSelectionEnd) { + selectionEnd = description.length + } + + //Replace token spans + val tokens = text.getSpans(i, i, TokenImageSpan::class.java) + if (tokens.isNotEmpty()) { + val token = tokens[0] + description = + description.append(tokenizer!!.wrapTokenValue(token.token.toString())) + i = text.getSpanEnd(token) + ++i + continue + } + description = description.append(text.subSequence(i, i + 1)) + ++i + } + val origSelectionStart = Selection.getSelectionStart(text) + if (i == origSelectionStart) { + selectionStart = description.length + } + val origSelectionEnd = Selection.getSelectionEnd(text) + if (i == origSelectionEnd) { + selectionEnd = description.length + } + if (selectionStart >= 0 && selectionEnd >= 0) { + Selection.setSelection(description, selectionStart, selectionEnd) + } + return description + } + + /** + * Clear the completion text only. + */ + @Suppress("unused") + fun clearCompletionText() { + //Respect currentCompletionText in case hint is visible or if other checks are added. + if (currentCompletionText().isEmpty()) { + return + } + val currentRange = currentCandidateTokenRange + internalEditInProgress = true + text.delete(currentRange.start, currentRange.end) + internalEditInProgress = false + } + + override fun onInitializeAccessibilityEvent(event: AccessibilityEvent) { + super.onInitializeAccessibilityEvent(event) + if (event.eventType == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) { + val text = textForAccessibility + event.fromIndex = Selection.getSelectionStart(text) + event.toIndex = Selection.getSelectionEnd(text) + event.itemCount = text.length + } + } + //Don't try to search the hint for possible tokenizable strings + + //We want to find the largest string that contains the selection end that is not already tokenized + private val currentCandidateTokenRange: Range + get() { + val editable = text + val cursorEndPosition = selectionEnd + var candidateStringStart = prefix?.length ?: 0 + var candidateStringEnd = editable.length + if (hintVisible) { + //Don't try to search the hint for possible tokenizable strings + candidateStringEnd = candidateStringStart + } + + //We want to find the largest string that contains the selection end that is not already tokenized + val spans = editable.getSpans(prefix?.length ?: 0, editable.length, TokenImageSpan::class.java) + for (span in spans) { + val spanEnd = editable.getSpanEnd(span) + if (spanEnd in (candidateStringStart + 1)..cursorEndPosition) { + candidateStringStart = spanEnd + } + val spanStart = editable.getSpanStart(span) + if (candidateStringEnd > spanStart && cursorEndPosition <= spanEnd) { + candidateStringEnd = spanStart + } + } + val tokenRanges = + tokenizer!!.findTokenRanges(editable, candidateStringStart, candidateStringEnd) + for (range in tokenRanges) { + @Suppress("unused") + if (range.start <= cursorEndPosition && cursorEndPosition <= range.end) { + return range + } + } + return Range(cursorEndPosition, cursorEndPosition) + } + + /** + * Override if you need custom logic to provide a sting representation of a token + * @param token the token to convert + * @return the string representation of the token. Defaults to [Object.toString] + */ + @Suppress("MemberVisibilityCanBePrivate") + protected open fun tokenToString(token: T): CharSequence { + return token.toString() + } + + protected open fun currentCompletionText(): String { + if (hintVisible) return "" //Can't have any text if the hint is visible + val editable = text + val currentRange = currentCandidateTokenRange + val result = TextUtils.substring(editable, currentRange.start, currentRange.end) + Log.d(TAG, "Current completion text: $result") + return result + } + + @Suppress("MemberVisibilityCanBePrivate") + protected open fun maxTextWidth(): Float { + return (width - paddingLeft - paddingRight).toFloat() + } + + override val maxViewSpanWidth: Int + get() = maxTextWidth().toInt() + + fun redrawTokens() { + // There's no straight-forward way to convince the widget to redraw the text and spans. We trigger a redraw by + // making an invisible change (either adding or removing a dummy span). + val text = text ?: return + val textLength = text.length + val dummySpans = text.getSpans(0, textLength, DummySpan::class.java) + if (dummySpans.isNotEmpty()) { + text.removeSpan(DummySpan.INSTANCE) + } else { + text.setSpan( + DummySpan.INSTANCE, + 0, + textLength, + Spannable.SPAN_INCLUSIVE_INCLUSIVE + ) + } + } + + override fun enoughToFilter(): Boolean { + if (tokenizer == null || hintVisible) { + return false + } + val cursorPosition = selectionEnd + if (cursorPosition < 0) { + return false + } + val currentCandidateRange = currentCandidateTokenRange + + //Don't allow 0 length entries to filter + @Suppress("MemberVisibilityCanBePrivate") + return currentCandidateRange.length() >= threshold.coerceAtLeast(1) + } + + override fun performCompletion() { + if ((adapter == null || listSelection == ListView.INVALID_POSITION) && enoughToFilter()) { + val bestGuess: Any? = if (adapter != null && adapter.count > 0 && performBestGuess) { + adapter.getItem(0) + } else { + defaultObject(currentCompletionText()) + } + replaceText(convertSelectionToString(bestGuess)) + } else { + super.performCompletion() + } + } + + override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection { + val superConn = super.onCreateInputConnection(outAttrs) + val conn = TokenInputConnection(superConn, true) + outAttrs.imeOptions = outAttrs.imeOptions and EditorInfo.IME_FLAG_NO_ENTER_ACTION.inv() + outAttrs.imeOptions = outAttrs.imeOptions or EditorInfo.IME_FLAG_NO_EXTRACT_UI + return conn + } + + /** + * Create a token and hide the keyboard when the user sends the DONE IME action + * Use IME_NEXT if you want to create a token and go to the next field + */ + private fun handleDone() { + // Attempt to complete the current token token + performCompletion() + + // Hide the keyboard + val imm = context.getSystemService( + Context.INPUT_METHOD_SERVICE + ) as InputMethodManager + imm.hideSoftInputFromWindow(windowToken, 0) + } + + override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean { + val handled = super.onKeyUp(keyCode, event) + if (shouldFocusNext) { + shouldFocusNext = false + handleDone() + } + return handled + } + + override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { + var handled = false + when (keyCode) { + KeyEvent.KEYCODE_TAB, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_DPAD_CENTER -> if (event?.hasNoModifiers() == true) { + shouldFocusNext = true + handled = true + } + KeyEvent.KEYCODE_DEL -> handled = !canDeleteSelection(1) || deleteSelectedObject() + } + return handled || super.onKeyDown(keyCode, event) + } + + private fun deleteSelectedObject(): Boolean { + if (tokenClickStyle?.isSelectable == true) { + val text = text ?: return false + @Suppress("unchecked_cast") + val spans: Array = + text.getSpans(0, text.length, TokenImageSpan::class.java) as Array + for (span in spans) { + if (span.view.isSelected) { + removeSpan(text, span) + return true + } + } + } + return false + } + + override fun onEditorAction(view: TextView, action: Int, keyEvent: KeyEvent?): Boolean { + if (action == EditorInfo.IME_ACTION_DONE) { + handleDone() + return true + } + return false + } + + override fun onTouchEvent(event: MotionEvent): Boolean { + val action = event.actionMasked + val text = text + var handled = false + if (tokenClickStyle == TokenClickStyle.None) { + handled = super.onTouchEvent(event) + } + if (isFocused && text != null && lastLayout != null && action == MotionEvent.ACTION_UP) { + val offset = getOffsetForPosition(event.x, event.y) + if (offset != -1) { + @Suppress("unchecked_cast") + val links: Array = + text.getSpans(offset, offset, TokenImageSpan::class.java) as Array + if (links.isNotEmpty()) { + links[0].onClick() + handled = true + } else { + //We didn't click on a token, so if any are selected, we should clear that + clearSelections() + } + } + } + if (!handled && tokenClickStyle != TokenClickStyle.None) { + handled = super.onTouchEvent(event) + } + return handled + } + + override fun onSelectionChanged(selStart: Int, selEnd: Int) { + var selectionStart = selStart + if (hintVisible) { + //Don't let users select the hint + selectionStart = 0 + } + //Never let users select text + val selectionEnd = selectionStart + if (tokenClickStyle?.isSelectable == true) { + val text = text + if (text != null) { + clearSelections() + } + } + if (selectionStart < prefix?.length ?: 0 || selectionEnd < prefix?.length ?: 0) { + //Don't let users select the prefix + setSelection(prefix?.length ?: 0) + } else { + val text = text + if (text != null) { + //Make sure if we are in a span, we select the spot 1 space after the span end + @Suppress("unchecked_cast") + val spans: Array = + text.getSpans(selectionStart, selectionEnd, TokenImageSpan::class.java) as Array + for (span in spans) { + val spanEnd = text.getSpanEnd(span) + if (selectionStart <= spanEnd && text.getSpanStart(span) < selectionStart) { + if (spanEnd == text.length) setSelection(spanEnd) else setSelection(spanEnd + 1) + return + } + } + } + super.onSelectionChanged(selectionStart, selectionEnd) + } + } + + override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { + super.onLayout(changed, left, top, right, bottom) + lastLayout = layout //Used for checking text positions + } + + /** + * Collapse the view by removing all the tokens not on the first line. Displays a "+x" token. + * Restores the hidden tokens when the view gains focus. + * + * @param hasFocus boolean indicating whether we have the focus or not. + */ + open fun performCollapse(hasFocus: Boolean) { + internalEditInProgress = true + if (!hasFocus) { + // Display +x thingy/ellipse if appropriate + val text = text + if (text != null && hiddenContent == null && lastLayout != null) { + + //Ellipsize copies spans, so we need to stop listening to span changes here + text.removeSpan(spanWatcher) + val temp = if (preventFreeFormText) countSpan else null + val ellipsized = SpanUtils.ellipsizeWithSpans( + prefix, temp, objects.size, + lastLayout!!.paint, text, maxTextWidth() + ) + if (ellipsized != null) { + hiddenContent = SpannableStringBuilder(text) + setText(ellipsized) + TextUtils.copySpansFrom( + ellipsized, 0, ellipsized.length, + TokenImageSpan::class.java, getText(), 0 + ) + TextUtils.copySpansFrom( + text, 0, hiddenContent!!.length, + TokenImageSpan::class.java, hiddenContent, 0 + ) + hiddenContent!!.setSpan( + spanWatcher, + 0, + hiddenContent!!.length, + Spanned.SPAN_INCLUSIVE_INCLUSIVE + ) + } else { + getText().setSpan( + spanWatcher, + 0, + getText().length, + Spanned.SPAN_INCLUSIVE_INCLUSIVE + ) + } + } + } else { + if (hiddenContent != null) { + text = hiddenContent + TextUtils.copySpansFrom( + hiddenContent, 0, hiddenContent!!.length, + TokenImageSpan::class.java, text, 0 + ) + hiddenContent = null + if (hintVisible) { + setSelection(prefix?.length ?: 0) + } else { + post { setSelection(text.length) } + } + @Suppress("unchecked_cast") + val watchers: Array = + text.getSpans(0, text.length, TokenSpanWatcher::class.java) as Array + if (watchers.isEmpty()) { + //Span watchers can get removed in setText + text.setSpan(spanWatcher, 0, text.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE) + } + } + } + internalEditInProgress = false + } + + public override fun onFocusChanged(hasFocus: Boolean, direction: Int, previous: Rect?) { + super.onFocusChanged(hasFocus, direction, previous) + + // Clear sections when focus changes to avoid a token remaining selected + clearSelections() + + // Collapse the view to a single line + if (allowCollapse) performCollapse(hasFocus) + } + + override fun convertSelectionToString(selectedObject: Any?): CharSequence { + @Suppress("unchecked_cast") + this.selectedObject = selectedObject as T? + return "" + } + + @Suppress("MemberVisibilityCanBePrivate") + protected open fun buildSpanForObject(obj: T?): TokenImageSpan? { + if (obj == null) { + return null + } + return getViewForObject(obj)?.let { TokenImageSpan(it, obj) } + } + + override fun replaceText(ignore: CharSequence) { + clearComposingText() + + // Don't build a token for an empty String + if (selectedObject?.toString().isNullOrEmpty()) return + val tokenSpan = buildSpanForObject(selectedObject) + val editable = text + val candidateRange = currentCandidateTokenRange + val original = TextUtils.substring(editable, candidateRange.start, candidateRange.end) + + //Keep track of replacements for a bug workaround + if (original.isNotEmpty()) { + lastCompletionText = original + } + if (editable != null) { + internalEditInProgress = true + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + ignoreNextTextCommit = true + } + if (tokenSpan == null) { + editable.replace(candidateRange.start, candidateRange.end, "") + } else if (shouldIgnoreToken(tokenSpan.token)) { + editable.replace(candidateRange.start, candidateRange.end, "") + if (listener != null) { + listener?.onTokenIgnored(tokenSpan.token) + } + } else { + val ssb = SpannableStringBuilder(tokenizer!!.wrapTokenValue(tokenToString(tokenSpan.token))) + editable.replace(candidateRange.start, candidateRange.end, ssb) + editable.setSpan( + tokenSpan, + candidateRange.start, + candidateRange.start + ssb.length, + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE + ) + editable.insert(candidateRange.start + ssb.length, " ") + } + internalEditInProgress = false + } + } + + override fun extractText(request: ExtractedTextRequest, outText: ExtractedText): Boolean { + return try { + super.extractText(request, outText) + } catch (ex: IndexOutOfBoundsException) { + Log.d(TAG, "extractText hit IndexOutOfBoundsException. This may be normal.", ex) + false + } + } + + /** + * Append a token object to the object list. May only be called from the main thread. + * + * @param obj the object to add to the displayed tokens + */ + @UiThread + fun addObjectSync(obj: T) { + if (shouldIgnoreToken(obj)) { + if (listener != null) { + listener?.onTokenIgnored(obj) + } + return + } + if (tokenLimit != -1 && objects.size == tokenLimit) return + buildSpanForObject(obj)?.also { insertSpan(it) } + if (text != null && isFocused) setSelection(text.length) + } + + /** + * Append a token object to the object list. Object will be added on the main thread. + * + * @param obj the object to add to the displayed tokens + */ + fun addObjectAsync(obj: T) { + post { addObjectSync(obj) } + } + + /** + * Remove an object from the token list. Will remove duplicates if present or do nothing if no + * object is present in the view. Uses [Object.equals] to find objects. May only + * be called from the main thread + * + * @param obj object to remove, may be null or not in the view + */ + @UiThread + fun removeObjectSync(obj: T) { + //To make sure all the appropriate callbacks happen, we just want to piggyback on the + //existing code that handles deleting spans when the text changes + val texts = ArrayList() + //If there is hidden content, it's important that we update it first + hiddenContent?.also { texts.add(it) } + if (text != null) { + texts.add(text) + } + + // If the object is currently visible, remove it + for (text in texts) { + @Suppress("unchecked_cast") + val spans: Array = + text.getSpans(0, text.length, TokenImageSpan::class.java) as Array + for (span in spans) { + if (span.token == obj) { + removeSpan(text, span) + } + } + } + updateCountSpan() + } + + /** + * Remove an object from the token list. Will remove duplicates if present or do nothing if no + * object is present in the view. Uses [Object.equals] to find objects. Object + * will be added on the main thread + * + * @param obj object to remove, may be null or not in the view + */ + fun removeObjectAsync(obj: T) { + post { removeObjectSync(obj) } + } + + /** + * Remove all objects from the token list. Objects will be removed on the main thread. + */ + fun clearAsync() { + post { + for (obj in objects) { + removeObjectSync(obj) + } + } + } + + /** + * Set the count span the current number of hidden objects + */ + private fun updateCountSpan() { + //No count span with free form text + if (!preventFreeFormText) { + return + } + val text = text + val visibleCount = getText().getSpans(0, getText().length, TokenImageSpan::class.java).size + countSpan.setCount(objects.size - visibleCount) + val spannedCountText = SpannableStringBuilder(countSpan.countText) + spannedCountText.setSpan( + countSpan, + 0, + spannedCountText.length, + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE + ) + internalEditInProgress = true + val countStart = text.getSpanStart(countSpan) + if (countStart != -1) { + //Span is in the text, replace existing text + //This will also remove the span if the count is 0 + text.replace(countStart, text.getSpanEnd(countSpan), spannedCountText) + } else { + text.append(spannedCountText) + } + internalEditInProgress = false + } + + /** + * Remove a span from the current EditText and fire the appropriate callback + * + * @param text Editable to remove the span from + * @param span TokenImageSpan to be removed + */ + private fun removeSpan(text: Editable, span: TokenImageSpan) { + //We usually add whitespace after a token, so let's try to remove it as well if it's present + var end = text.getSpanEnd(span) + if (end < text.length && text[end] == ' ') { + end += 1 + } + internalEditInProgress = true + text.delete(text.getSpanStart(span), end) + internalEditInProgress = false + if (allowCollapse && !isFocused) { + updateCountSpan() + } + } + + /** + * Insert a new span for an Object + * + * @param tokenSpan span to insert + */ + private fun insertSpan(tokenSpan: TokenImageSpan) { + val ssb = tokenizer!!.wrapTokenValue(tokenToString(tokenSpan.token)) + val editable = text ?: return + + // If we haven't hidden any objects yet, we can try adding it + if (hiddenContent == null) { + internalEditInProgress = true + var offset = editable.length + //There might be a hint visible... + if (hintVisible) { + //...so we need to put the object in in front of the hint + offset = prefix?.length ?: 0 + } else { + val currentRange = currentCandidateTokenRange + if (currentRange.length() > 0) { + // The user has entered some text that has not yet been tokenized. + // Find the beginning of this text and insert the new token there. + offset = currentRange.start + } + } + editable.insert(offset, ssb) + editable.insert(offset + ssb.length, " ") + editable.setSpan( + tokenSpan, + offset, + offset + ssb.length, + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE + ) + internalEditInProgress = false + } else { + val tokenText = tokenizer!!.wrapTokenValue( + tokenToString( + tokenSpan.token + ) + ) + val start = hiddenContent!!.length + hiddenContent!!.append(tokenText) + hiddenContent!!.append(" ") + hiddenContent!!.setSpan( + tokenSpan, + start, + start + tokenText.length, + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE + ) + updateCountSpan() + } + } + + private fun updateHint() { + val text = text + val hintText = hint + if (text == null || hintText == null) { + return + } + + //Show hint if we need to + if (prefix?.isNotEmpty() == true) { + val hints = text.getSpans(0, text.length, HintSpan::class.java) + var hint: HintSpan? = null + var testLength = prefix?.length ?: 0 + if (hints.isNotEmpty()) { + hint = hints[0] + testLength += text.getSpanEnd(hint) - text.getSpanStart(hint) + } + if (text.length == testLength) { + if (hint != null) { + return //hint already visible + } + + //We need to display the hint manually + val tf = typeface + var style = Typeface.NORMAL + if (tf != null) { + style = tf.style + } + val colors = hintTextColors + val hintSpan = HintSpan(null, style, textSize.toInt(), colors, colors) + internalEditInProgress = true + val spannedHint = SpannableString(hintText) + spannedHint.setSpan(hintSpan, 0, spannedHint.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) + text.insert(prefix?.length ?: 0, spannedHint) + internalEditInProgress = false + setSelection(prefix?.length ?: 0) + } else { + if (hint == null) { + return //hint already removed + } + + //Remove the hint. There should only ever be one + val sStart = text.getSpanStart(hint) + val sEnd = text.getSpanEnd(hint) + internalEditInProgress = true + text.removeSpan(hint) + text.replace(sStart, sEnd, "") + setSelection(sStart) + internalEditInProgress = false + } + } + } + + private fun clearSelections() { + if (tokenClickStyle?.isSelectable != true) return + val text = text ?: return + @Suppress("unchecked_cast") + val tokens: Array = + text.getSpans(0, text.length, TokenImageSpan::class.java) as Array + var shouldRedrawTokens = false + for (token in tokens) { + if (token.view.isSelected) { + token.view.isSelected = false + shouldRedrawTokens = true + } + } + if (shouldRedrawTokens) { + redrawTokens() + } + } + + inner class TokenImageSpan(d: View, val token: T) : ViewSpan(d, this@TokenCompleteTextView), + NoCopySpan { + fun onClick() { + val text = text ?: return + when (tokenClickStyle) { + TokenClickStyle.Select, TokenClickStyle.SelectDeselect -> { + if (!view.isSelected) { + clearSelections() + view.isSelected = true + redrawTokens() + } else if (tokenClickStyle == TokenClickStyle.SelectDeselect || !isTokenRemovable(token)) { + view.isSelected = false + redrawTokens() + } else if (isTokenRemovable(token)) { + removeSpan(text, this) + } + } + TokenClickStyle.Delete -> if (isTokenRemovable(token)) { + removeSpan(text, this) + } + TokenClickStyle.None -> if (selectionStart != text.getSpanEnd(this)) { + //Make sure the selection is not in the middle of the span + setSelection(text.getSpanEnd(this)) + } + else -> {} + } + } + } + + interface TokenListener { + fun onTokenAdded(token: T) + fun onTokenRemoved(token: T) + fun onTokenIgnored(token: T) + } + + private inner class TokenSpanWatcher : SpanWatcher { + override fun onSpanAdded(text: Spannable, what: Any, start: Int, end: Int) { + if (what is TokenCompleteTextView<*>.TokenImageSpan && !savingState) { + + // If we're not focused: collapse the view if necessary + if (!isFocused && allowCollapse) performCollapse(false) + @Suppress("unchecked_cast") + if (listener != null) listener?.onTokenAdded(what.token as T) + } + } + + override fun onSpanRemoved(text: Spannable, what: Any, start: Int, end: Int) { + if (what is TokenCompleteTextView<*>.TokenImageSpan && !savingState) { + @Suppress("unchecked_cast") + if (listener != null) listener?.onTokenRemoved(what.token as T) + } + } + + override fun onSpanChanged( + text: Spannable, what: Any, + oldStart: Int, oldEnd: Int, newStart: Int, newEnd: Int + ) { + } + } + + private inner class TokenTextWatcher : TextWatcher { + var spansToRemove = ArrayList() + override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { + if (internalEditInProgress || ignoreNextTextCommit) return + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + if (s is SpannableStringBuilder && s.textWatcherDepth > 1) return + } + + // count > 0 means something will be deleted + if (count > 0 && text != null) { + val text = text + val end = start + count + @Suppress("unchecked_cast") + val spans = text.getSpans(start, end, TokenImageSpan::class.java) as Array.TokenImageSpan> + + //NOTE: I'm not completely sure this won't cause problems if we get stuck in a text changed loop + //but it appears to work fine. Spans will stop getting removed if this breaks. + val spansToRemove = ArrayList() + for (token in spans) { + if (text.getSpanStart(token) < end && start < text.getSpanEnd(token)) { + spansToRemove.add(token) + } + } + this.spansToRemove = spansToRemove + } + } + + override fun afterTextChanged(text: Editable) { + if (!internalEditInProgress) { + val spansCopy = ArrayList(spansToRemove) + spansToRemove.clear() + for (token in spansCopy) { + //Only remove it if it's still present + if (text.getSpanStart(token) != -1 && text.getSpanEnd(token) != -1) { + removeSpan(text, token) + } + } + ignoreNextTextCommit = false + } + + clearSelections() + + if (!inBatchEditAPI26to29Workaround) { + updateHint() + } + } + + override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {} + } + + @Suppress("MemberVisibilityCanBePrivate") + protected open fun getSerializableObjects(): List { + val serializables = ArrayList() + for (obj in objects) { + if (obj is Serializable) { + serializables.add(obj as Serializable) + } else { + Log.e(TAG, "Unable to save '$obj'") + } + } + if (serializables.size != objects.size) { + val message = """ + You should make your objects Serializable or Parcelable or + override getSerializableObjects and convertSerializableArrayToObjectArray + """.trimIndent() + Log.e(TAG, message) + } + return serializables + } + + @Suppress("MemberVisibilityCanBePrivate") + protected open fun convertSerializableObjectsToTypedObjects(s: List<*>?): List? { + @Suppress("unchecked_cast") + return s as List? + } + + //Used to determine if we can use the Parcelable interface + private fun reifyParameterizedTypeClass(): Class<*> { + //Borrowed from http://codyaray.com/2013/01/finding-generic-type-parameters-with-guava + + //Figure out what class of objects we have + var viewClass: Class<*> = javaClass + while (viewClass.superclass != TokenCompleteTextView::class.java) { + viewClass = viewClass.superclass as Class<*> + } + + // This operation is safe. Because viewClass is a direct sub-class, getGenericSuperclass() will + // always return the Type of this class. Because this class is parameterized, the cast is safe + val superclass = viewClass.genericSuperclass as ParameterizedType + val type = superclass.actualTypeArguments[0] + return type as Class<*> + } + + override fun onSaveInstanceState(): Parcelable { + //We don't want to save the listeners as part of the parent + //onSaveInstanceState, so remove them first + removeListeners() + + //Apparently, saving the parent state on 2.3 mutates the spannable + //prevent this mutation from triggering add or removes of token objects ~mgod + savingState = true + val superState = super.onSaveInstanceState() + savingState = false + val state = SavedState(superState) + state.prefix = prefix + state.allowCollapse = allowCollapse + state.performBestGuess = performBestGuess + state.preventFreeFormText = preventFreeFormText + state.tokenClickStyle = tokenClickStyle + val parameterizedClass = reifyParameterizedTypeClass() + //Our core array is Parcelable, so use that interface + if (Parcelable::class.java.isAssignableFrom(parameterizedClass)) { + state.parcelableClassName = parameterizedClass.name + state.baseObjects = objects + } else { + //Fallback on Serializable + state.parcelableClassName = SavedState.SERIALIZABLE_PLACEHOLDER + state.baseObjects = getSerializableObjects() + } + state.tokenizer = tokenizer + + //So, when the screen is locked or some other system event pauses execution, + //onSaveInstanceState gets called, but it won't restore state later because the + //activity is still in memory, so make sure we add the listeners again + //They should not be restored in onInstanceState if the app is actually killed + //as we removed them before the parent saved instance state, so our adding them in + //onRestoreInstanceState is good. + addListeners() + return state + } + + override fun onRestoreInstanceState(state: Parcelable) { + if (state !is SavedState) { + super.onRestoreInstanceState(state) + return + } + super.onRestoreInstanceState(state.superState) + internalEditInProgress = true + setText(state.prefix) + prefix = state.prefix + internalEditInProgress = false + updateHint() + allowCollapse = state.allowCollapse + performBestGuess = state.performBestGuess + preventFreeFormText = state.preventFreeFormText + tokenClickStyle = state.tokenClickStyle + tokenizer = state.tokenizer + addListeners() + val objects: List? = if (SavedState.SERIALIZABLE_PLACEHOLDER == state.parcelableClassName) { + convertSerializableObjectsToTypedObjects(state.baseObjects) + } else { + @Suppress("unchecked_cast") + state.baseObjects as List? + } + + //TODO: change this to keep object spans in the correct locations based on ranges. + if (objects != null) { + for (obj in objects) { + addObjectSync(obj) + } + } + + // Collapse the view if necessary + if (!isFocused && allowCollapse) { + post { //Resize the view and display the +x if appropriate + performCollapse(isFocused) + } + } + } + + /** + * Handle saving the token state + */ + private class SavedState : BaseSavedState { + var prefix: CharSequence? = null + var allowCollapse = false + var performBestGuess = false + var preventFreeFormText = false + var tokenClickStyle: TokenClickStyle? = null + var parcelableClassName: String = SERIALIZABLE_PLACEHOLDER + var baseObjects: List<*>? = null + var tokenizerClassName: String? = null + var tokenizer: Tokenizer? = null + + constructor(parcel: Parcel) : super(parcel) { + prefix = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel) + allowCollapse = parcel.readInt() != 0 + performBestGuess = parcel.readInt() != 0 + preventFreeFormText = parcel.readInt() != 0 + tokenClickStyle = TokenClickStyle.values()[parcel.readInt()] + parcelableClassName = parcel.readString() ?: SERIALIZABLE_PLACEHOLDER + baseObjects = if (SERIALIZABLE_PLACEHOLDER == parcelableClassName) { + parcel.readSerializable() as ArrayList<*> + } else { + try { + val loader = Class.forName(parcelableClassName).classLoader + parcel.readArrayList(loader) + } catch (ex: ClassNotFoundException) { + //This should really never happen, class had to be available to get here + throw RuntimeException(ex) + } + } + tokenizerClassName = parcel.readString() + tokenizer = try { + val loader = Class.forName(tokenizerClassName!!).classLoader + parcel.readParcelable(loader) + } catch (ex: ClassNotFoundException) { + //This should really never happen, class had to be available to get here + throw RuntimeException(ex) + } + } + + constructor(superState: Parcelable?) : super(superState) + + override fun writeToParcel(out: Parcel, flags: Int) { + super.writeToParcel(out, flags) + TextUtils.writeToParcel(prefix, out, 0) + out.writeInt(if (allowCollapse) 1 else 0) + out.writeInt(if (performBestGuess) 1 else 0) + out.writeInt(if (preventFreeFormText) 1 else 0) + out.writeInt((tokenClickStyle ?: TokenClickStyle.None).ordinal) + if (SERIALIZABLE_PLACEHOLDER == parcelableClassName) { + out.writeString(SERIALIZABLE_PLACEHOLDER) + out.writeSerializable(baseObjects as Serializable?) + } else { + out.writeString(parcelableClassName) + out.writeList(baseObjects) + } + out.writeString(tokenizer!!.javaClass.canonicalName) + out.writeParcelable(tokenizer, 0) + } + + override fun toString(): String { + val str = ("TokenCompleteTextView.SavedState{" + + Integer.toHexString(System.identityHashCode(this)) + + " tokens=" + baseObjects) + return "$str}" + } + + companion object { + const val SERIALIZABLE_PLACEHOLDER = "Serializable" + @Suppress("unused") + @JvmField + val CREATOR: Parcelable.Creator = object : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel): SavedState { + return SavedState(parcel) + } + + override fun newArray(size: Int): Array { + return arrayOfNulls(size) + } + } + } + } + + /** + * Checks if selection can be deleted. This method is called from TokenInputConnection . + * @param beforeLength the number of characters before the current selection end to check + * @return true if there are no non-deletable pieces of the section + */ + fun canDeleteSelection(beforeLength: Int): Boolean { + if (objects.isEmpty()) return true + + // if beforeLength is 1, we either have no selection or the call is coming from OnKey Event. + // In these scenarios, getSelectionStart() will return the correct value. + val endSelection = selectionEnd + val startSelection = if (beforeLength == 1) selectionStart else endSelection - beforeLength + val text = text + val spans = text.getSpans(0, text.length, TokenImageSpan::class.java) + + // Iterate over all tokens and allow the deletion + // if there are no tokens not removable in the selection + for (span in spans) { + val startTokenSelection = text.getSpanStart(span) + val endTokenSelection = text.getSpanEnd(span) + + // moving on, no need to check this token + @Suppress("unchecked_cast") + if (isTokenRemovable(span.token as T)) continue + if (startSelection == endSelection) { + // Delete single + if (endTokenSelection + 1 == endSelection) { + return false + } + } else { + // Delete range + // Don't delete if a non removable token is in range + if (startSelection <= startTokenSelection + && endTokenSelection + 1 <= endSelection + ) { + return false + } + } + } + return true + } + + private inner class TokenInputConnection( + target: InputConnection?, + mutable: Boolean + ) : InputConnectionWrapper(target, mutable) { + + private val needsWorkaround: Boolean + get() { + return Build.VERSION_CODES.O <= Build.VERSION.SDK_INT && + Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q + + } + + override fun beginBatchEdit(): Boolean { + if (needsWorkaround) { + inBatchEditAPI26to29Workaround = true + } + return super.beginBatchEdit() + } + + override fun endBatchEdit(): Boolean { + val result = super.endBatchEdit() + if (needsWorkaround) { + inBatchEditAPI26to29Workaround = false + post { updateHint() } + } + return result + } + + // This will fire if the soft keyboard delete key is pressed. + // The onKeyPressed method does not always do this. + override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean { + // Shouldn't be able to delete any text with tokens that are not removable + var fixedBeforeLength = beforeLength + if (!canDeleteSelection(fixedBeforeLength)) return false + + //Shouldn't be able to delete prefix, so don't do anything + if (selectionStart <= prefix?.length ?: 0) { + fixedBeforeLength = 0 + return deleteSelectedObject() || super.deleteSurroundingText( + fixedBeforeLength, + afterLength + ) + } + return super.deleteSurroundingText(fixedBeforeLength, afterLength) + } + + override fun setComposingRegion(start: Int, end: Int): Boolean { + //The hint is displayed inline as regular text, but we want to disable normal compose + //functionality on it, so if we attempt to set a composing region on the hint, set the + //composing region to have length of 0, which indicates there is no composing region + //Without this, on many software keyboards, the first word of the hint will be underlined + var fixedStart = start + var fixedEnd = end + if (hintVisible) { + fixedEnd = 0 + fixedStart = fixedEnd + } + return super.setComposingRegion(fixedStart, fixedEnd) + } + + override fun setComposingText(text: CharSequence, newCursorPosition: Int): Boolean { + //There's an issue with some keyboards where they will try to insert the first word + //of the prefix as the composing text + var fixedText: CharSequence? = text + val hint = hint + if (hint != null && fixedText != null) { + val firstWord = hint.toString().trim { it <= ' ' }.split(" ").toTypedArray()[0] + if (firstWord.isNotEmpty() && firstWord == fixedText.toString()) { + fixedText = "" //It was trying to use th hint, so clear that text + } + } + + //Also, some keyboards don't correctly respect the replacement if the replacement + //is the same number of characters as the replacement span + //We need to ignore this value if it's available + lastCompletionText?.also { lastCompletion -> + fixedText?.also { fixed -> + if (fixed.length == lastCompletion.length + 1 && fixed.toString().startsWith(lastCompletion)) { + fixedText = fixed.subSequence(fixed.length - 1, fixed.length) + lastCompletionText = null + } + } + } + return super.setComposingText(fixedText, newCursorPosition) + } + } + + companion object { + //Logging + const val TAG = "TokenAutoComplete" + } +} \ No newline at end of file diff --git a/app/src/main/java/com/tokenautocomplete/Tokenizer.kt b/app/src/main/java/com/tokenautocomplete/Tokenizer.kt new file mode 100644 index 000000000..024d0c82d --- /dev/null +++ b/app/src/main/java/com/tokenautocomplete/Tokenizer.kt @@ -0,0 +1,34 @@ +package com.tokenautocomplete + +import android.os.Parcelable + +interface Tokenizer : Parcelable { + /** + * Find all ranges that can be tokenized. This system should detect possible tokens + * both with and without having had wrapTokenValue called on the token string representation + * + * @param charSequence the string to search in + * @param start where the tokenizer should start looking for tokens + * @param end where the tokenizer should stop looking for tokens + * @return all ranges of characters that are valid tokens + */ + fun findTokenRanges(charSequence: CharSequence, start: Int, end: Int): List + + /** + * Return a complete string representation of the token. Often used to add commas after email + * addresses when creating tokens + * + * This value must NOT include any leading or trailing whitespace + * + * @param unwrappedTokenValue the value to wrap + * @return the token value with any expected delimiter characters + */ + fun wrapTokenValue(unwrappedTokenValue: CharSequence): CharSequence + + /** + * Return true if there is a character in the charSequence that should trigger token detection + * @param charSequence source text to look at + * @return true if charSequence contains a value that should end a token + */ + fun containsTokenTerminator(charSequence: CharSequence): Boolean +} \ No newline at end of file diff --git a/app/src/main/java/com/tokenautocomplete/ViewSpan.kt b/app/src/main/java/com/tokenautocomplete/ViewSpan.kt new file mode 100644 index 000000000..a742cb363 --- /dev/null +++ b/app/src/main/java/com/tokenautocomplete/ViewSpan.kt @@ -0,0 +1,76 @@ +package com.tokenautocomplete + +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.Paint.FontMetricsInt +import android.text.style.ReplacementSpan +import android.view.View +import android.view.ViewGroup +import androidx.annotation.IntRange + +/** + * Span that holds a view it draws when rendering + * + * Created on 2/3/15. + * @author mgod + */ +open class ViewSpan(var view: View, private val layout: Layout) : ReplacementSpan() { + private var cachedMaxWidth = -1 + private fun prepView() { + if (layout.maxViewSpanWidth != cachedMaxWidth || view.isLayoutRequested) { + cachedMaxWidth = layout.maxViewSpanWidth + var spec = View.MeasureSpec.AT_MOST + if (cachedMaxWidth == 0) { + //If the width is 0, allow the view to choose it's own content size + spec = View.MeasureSpec.UNSPECIFIED + } + val widthSpec = View.MeasureSpec.makeMeasureSpec(cachedMaxWidth, spec) + val heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) + view.measure(widthSpec, heightSpec) + view.layout(0, 0, view.measuredWidth, view.measuredHeight) + } + } + + override fun draw( + canvas: Canvas, text: CharSequence, @IntRange(from = 0) start: Int, + @IntRange(from = 0) end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint + ) { + prepView() + canvas.save() + canvas.translate(x, top.toFloat()) + view.draw(canvas) + canvas.restore() + } + + override fun getSize( + paint: Paint, charSequence: CharSequence, @IntRange(from = 0) start: Int, + @IntRange(from = 0) end: Int, fontMetricsInt: FontMetricsInt? + ): Int { + prepView() + if (fontMetricsInt != null) { + //We need to make sure the layout allots enough space for the view + val height = view.measuredHeight + var adjustedBaseline = view.baseline + //-1 means the view doesn't support baseline alignment, so align bottom to font baseline + if (adjustedBaseline == -1) { + adjustedBaseline = height + } + fontMetricsInt.top = -adjustedBaseline + fontMetricsInt.ascent = fontMetricsInt.top + fontMetricsInt.bottom = height - adjustedBaseline + fontMetricsInt.descent = fontMetricsInt.bottom + } + return view.right + } + + interface Layout { + val maxViewSpanWidth: Int + } + + init { + view.layoutParams = ViewGroup.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT + ) + } +} \ No newline at end of file From d7c90601d0b1d39853bbbb24f4425e6cb75294a4 Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Thu, 27 Jan 2022 16:47:47 +0100 Subject: [PATCH 089/112] Add warning integrity message when keyfile is an image #1188 --- .../keepass/view/KeyFileSelectionView.kt | 15 +++++++++++++-- app/src/main/res/values/strings.xml | 1 + 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/kunzisoft/keepass/view/KeyFileSelectionView.kt b/app/src/main/java/com/kunzisoft/keepass/view/KeyFileSelectionView.kt index 182623ac7..0745442e9 100644 --- a/app/src/main/java/com/kunzisoft/keepass/view/KeyFileSelectionView.kt +++ b/app/src/main/java/com/kunzisoft/keepass/view/KeyFileSelectionView.kt @@ -2,7 +2,10 @@ package com.kunzisoft.keepass.view import android.content.Context import android.net.Uri +import android.os.Build +import android.os.Parcel import android.os.Parcelable +import android.os.Parcelable.Creator import android.util.AttributeSet import android.view.LayoutInflater import android.widget.TextView @@ -10,8 +13,6 @@ import androidx.constraintlayout.widget.ConstraintLayout import com.google.android.material.textfield.TextInputLayout import com.kunzisoft.keepass.R import com.kunzisoft.keepass.utils.UriUtil -import android.os.Parcel -import android.os.Parcelable.Creator class KeyFileSelectionView @JvmOverloads constructor(context: Context, @@ -54,6 +55,16 @@ class KeyFileSelectionView @JvmOverloads constructor(context: Context, } set(value) { mUri = value + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + value?.let { keyFileUri -> + val mimeType = context?.contentResolver?.getType(keyFileUri) + error = if (mimeType?.contains("image") == true) { + context.getString(R.string.warning_keyfile_integrity) + } else { + null + } + } + } keyFileNameView.text = value?.let { UriUtil.getFileData(context, value)?.name ?: value.path } ?: "" diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 66573e11d..18897cd1d 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -332,6 +332,7 @@ Reloading the database will delete the locally modified data. Access to the file revoked by the file manager, close the database and reopen it from its location. You have not allowed the app to use an exact alarm. As a result, the features requiring a timer will not be done with an exact time. + The hash of the file is not guaranteed because Android can change its data on the fly. Change the file extension to .bin for correct integrity. Permission Version %1$s Build %1$s From 9110a1aca60f8d02f7b878207e0b92b58f965f3d Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Thu, 27 Jan 2022 16:51:19 +0100 Subject: [PATCH 090/112] Fix checkboxes position with an error --- app/src/main/res/layout/activity_password.xml | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/app/src/main/res/layout/activity_password.xml b/app/src/main/res/layout/activity_password.xml index a1b8f7a56..e562b9381 100644 --- a/app/src/main/res/layout/activity_password.xml +++ b/app/src/main/res/layout/activity_password.xml @@ -136,8 +136,7 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/password_input_layout" - android:layout_alignBottom="@+id/password_input_layout" - android:layout_marginTop="8dp" + android:layout_marginTop="22dp" android:contentDescription="@string/content_description_password_checkbox" android:focusable="false" android:gravity="center_vertical" /> @@ -181,8 +180,7 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/keyfile_selection" - android:layout_alignBottom="@+id/keyfile_selection" - android:layout_marginTop="8dp" + android:layout_marginTop="22dp" android:contentDescription="@string/content_description_keyfile_checkbox" android:focusable="false" android:gravity="center_vertical" /> From d06829ff7be7aff349eef223a7a7707238cc2432 Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Thu, 27 Jan 2022 17:33:05 +0100 Subject: [PATCH 091/112] Fix empty tag --- .../java/com/kunzisoft/keepass/database/element/Tags.kt | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/Tags.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/Tags.kt index ed23507bb..f9bc4f1f8 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/Tags.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/Tags.kt @@ -11,7 +11,10 @@ class Tags: Parcelable { constructor() constructor(values: String): this() { - mTags.addAll(values.removeSpaceChars().split(DELIMITER, DELIMITER1)) + mTags.addAll(values + .split(DELIMITER, DELIMITER1) + .filter { it.removeSpaceChars().isNotEmpty() } + ) } constructor(parcel: Parcel) : this() { @@ -36,7 +39,7 @@ class Tags: Parcelable { } fun put(tag: String) { - if (tag.isNotEmpty() && !mTags.contains(tag)) + if (tag.removeSpaceChars().isNotEmpty() && !mTags.contains(tag)) mTags.add(tag) } From d22defcd83d0a67d831fbbf9577a26cc89ca6324 Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Thu, 27 Jan 2022 18:06:38 +0100 Subject: [PATCH 092/112] Move settings position --- .../settings/NestedAppSettingsFragment.kt | 4 ++-- .../keepass/settings/PreferencesUtil.kt | 20 +++++++++---------- app/src/main/res/values/donottranslate.xml | 8 ++++---- app/src/main/res/values/strings.xml | 8 ++++---- .../main/res/xml/preferences_appearance.xml | 20 +++++++++---------- 5 files changed, 30 insertions(+), 30 deletions(-) diff --git a/app/src/main/java/com/kunzisoft/keepass/settings/NestedAppSettingsFragment.kt b/app/src/main/java/com/kunzisoft/keepass/settings/NestedAppSettingsFragment.kt index 10bbb3c8a..aaa7d6ddc 100644 --- a/app/src/main/java/com/kunzisoft/keepass/settings/NestedAppSettingsFragment.kt +++ b/app/src/main/java/com/kunzisoft/keepass/settings/NestedAppSettingsFragment.kt @@ -445,11 +445,11 @@ class NestedAppSettingsFragment : NestedSettingsFragment() { getString(R.string.setting_icon_pack_choose_key), getString(R.string.list_entries_show_username_key), getString(R.string.list_groups_show_number_entries_key), + getString(R.string.show_otp_token_key), + getString(R.string.show_uuid_key), getString(R.string.list_size_key), getString(R.string.monospace_font_fields_enable_key), getString(R.string.hide_expired_entries_key), - getString(R.string.show_otp_token_key), - getString(R.string.show_uuid_key), getString(R.string.enable_education_screens_key), getString(R.string.reset_education_screens_key) -> { DATABASE_PREFERENCE_CHANGED = true diff --git a/app/src/main/java/com/kunzisoft/keepass/settings/PreferencesUtil.kt b/app/src/main/java/com/kunzisoft/keepass/settings/PreferencesUtil.kt index 36efc093e..84e1b30ed 100644 --- a/app/src/main/java/com/kunzisoft/keepass/settings/PreferencesUtil.kt +++ b/app/src/main/java/com/kunzisoft/keepass/settings/PreferencesUtil.kt @@ -122,22 +122,22 @@ object PreferencesUtil { context.resources.getBoolean(R.bool.list_groups_show_number_entries_default)) } - fun showExpiredEntries(context: Context): Boolean { - val prefs = PreferenceManager.getDefaultSharedPreferences(context) - return ! prefs.getBoolean(context.getString(R.string.hide_expired_entries_key), - context.resources.getBoolean(R.bool.hide_expired_entries_default)) - } - fun showOTPToken(context: Context): Boolean { val prefs = PreferenceManager.getDefaultSharedPreferences(context) return prefs.getBoolean(context.getString(R.string.show_otp_token_key), - context.resources.getBoolean(R.bool.show_otp_token_default)) + context.resources.getBoolean(R.bool.show_otp_token_default)) } fun showUUID(context: Context): Boolean { val prefs = PreferenceManager.getDefaultSharedPreferences(context) return prefs.getBoolean(context.getString(R.string.show_uuid_key), - context.resources.getBoolean(R.bool.show_uuid_default)) + context.resources.getBoolean(R.bool.show_uuid_default)) + } + + fun showExpiredEntries(context: Context): Boolean { + val prefs = PreferenceManager.getDefaultSharedPreferences(context) + return ! prefs.getBoolean(context.getString(R.string.hide_expired_entries_key), + context.resources.getBoolean(R.bool.hide_expired_entries_default)) } fun getStyle(context: Context): String { @@ -654,11 +654,11 @@ object PreferencesUtil { context.getString(R.string.setting_icon_pack_choose_key) -> editor.putString(name, value) context.getString(R.string.list_entries_show_username_key) -> editor.putBoolean(name, value.toBoolean()) context.getString(R.string.list_groups_show_number_entries_key) -> editor.putBoolean(name, value.toBoolean()) + context.getString(R.string.show_otp_token_key) -> editor.putBoolean(name, value.toBoolean()) + context.getString(R.string.show_uuid_key) -> editor.putBoolean(name, value.toBoolean()) context.getString(R.string.list_size_key) -> editor.putString(name, value) context.getString(R.string.monospace_font_fields_enable_key) -> editor.putBoolean(name, value.toBoolean()) context.getString(R.string.hide_expired_entries_key) -> editor.putBoolean(name, value.toBoolean()) - context.getString(R.string.show_otp_token_key) -> editor.putBoolean(name, value.toBoolean()) - context.getString(R.string.show_uuid_key) -> editor.putBoolean(name, value.toBoolean()) context.getString(R.string.enable_education_screens_key) -> editor.putBoolean(name, value.toBoolean()) context.getString(R.string.sort_node_key) -> editor.putString(name, value) diff --git a/app/src/main/res/values/donottranslate.xml b/app/src/main/res/values/donottranslate.xml index 0efc3422b..1ec0c1055 100644 --- a/app/src/main/res/values/donottranslate.xml +++ b/app/src/main/res/values/donottranslate.xml @@ -187,15 +187,15 @@ true list_groups_show_number_entries_key true + show_otp_token_key + true + show_uuid_key + false list_size_key monospace_font_extra_fields_enable_key true hide_expired_entries_key false - show_otp_token_key - true - show_uuid_key - false enable_education_screens_key true relaunch_education_screens_key diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 18897cd1d..4076e1f75 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -200,6 +200,10 @@ Show usernames Show usernames in entry lists Show number of entries + Show OTP Token + Displays OTP tokens in the list of entries + Show UUID + Displays the UUID linked to an entry or a group Show the number of entries in a group Size of list items Text size in the element list @@ -639,8 +643,4 @@ Icon pack used in the app Hide expired entries Expired entries are not shown - Show UUID - Displays the UUID linked to an entry or a group - Show OTP Token - Displays OTP tokens in the list of entries \ No newline at end of file diff --git a/app/src/main/res/xml/preferences_appearance.xml b/app/src/main/res/xml/preferences_appearance.xml index a9307a983..52b22383e 100644 --- a/app/src/main/res/xml/preferences_appearance.xml +++ b/app/src/main/res/xml/preferences_appearance.xml @@ -56,6 +56,16 @@ android:title="@string/list_groups_show_number_entries_title" android:summary="@string/list_groups_show_number_entries_summary" android:defaultValue="@bool/list_groups_show_number_entries_default"/> + + - - Date: Thu, 27 Jan 2022 18:26:01 +0100 Subject: [PATCH 093/112] Add entry colors setting --- .../java/com/kunzisoft/keepass/activities/EntryActivity.kt | 5 +++-- .../java/com/kunzisoft/keepass/adapters/NodesAdapter.kt | 6 ++++-- .../keepass/settings/NestedAppSettingsFragment.kt | 1 + .../java/com/kunzisoft/keepass/settings/PreferencesUtil.kt | 7 +++++++ app/src/main/res/values/donottranslate.xml | 2 ++ app/src/main/res/values/strings.xml | 2 ++ app/src/main/res/xml/preferences_appearance.xml | 5 +++++ 7 files changed, 24 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt b/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt index f461db19a..10edbbba9 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt +++ b/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt @@ -231,8 +231,9 @@ class EntryActivity : DatabaseLockActivity() { tagsListView?.visibility = if (tags.isEmpty()) View.GONE else View.VISIBLE tagsAdapter?.setTags(tags) // Assign colors - mBackgroundColor = entryInfo.backgroundColor - mForegroundColor = entryInfo.foregroundColor + val showEntryColors = PreferencesUtil.showEntryColors(this) + mBackgroundColor = if (showEntryColors) entryInfo.backgroundColor else null + mForegroundColor = if (showEntryColors) entryInfo.foregroundColor else null loadingView?.hideByFading() mEntryLoaded = true diff --git a/app/src/main/java/com/kunzisoft/keepass/adapters/NodesAdapter.kt b/app/src/main/java/com/kunzisoft/keepass/adapters/NodesAdapter.kt index 6f3a9b162..bc304c8ee 100644 --- a/app/src/main/java/com/kunzisoft/keepass/adapters/NodesAdapter.kt +++ b/app/src/main/java/com/kunzisoft/keepass/adapters/NodesAdapter.kt @@ -74,6 +74,7 @@ class NodesAdapter (private val context: Context, private var mNumberChildrenTextDefaultDimension: Float = 0F private var mIconDefaultDimension: Float = 0F + private var mShowEntryColors: Boolean = true private var mShowUserNames: Boolean = true private var mShowNumberEntries: Boolean = true private var mShowOTP: Boolean = false @@ -150,6 +151,7 @@ class NodesAdapter (private val context: Context, ) ) + this.mShowEntryColors = PreferencesUtil.showEntryColors(context) this.mShowUserNames = PreferencesUtil.showUsernamesListEntries(context) this.mShowNumberEntries = PreferencesUtil.showNumberEntries(context) this.mShowOTP = PreferencesUtil.showOTPToken(context) @@ -436,7 +438,7 @@ class NodesAdapter (private val context: Context, if (entry.containsAttachment()) View.VISIBLE else View.GONE // Assign colors - val backgroundColor = entry.backgroundColor + val backgroundColor = if (mShowEntryColors) entry.backgroundColor else null if (!holder.container.isSelected) { if (backgroundColor != null) { holder.container.setBackgroundColor(backgroundColor) @@ -446,7 +448,7 @@ class NodesAdapter (private val context: Context, } else { holder.container.setBackgroundColor(mColorAccentLight) } - val foregroundColor = entry.foregroundColor + val foregroundColor = if (mShowEntryColors) entry.foregroundColor else null if (!holder.container.isSelected) { if (foregroundColor != null) { holder.text.setTextColor(foregroundColor) diff --git a/app/src/main/java/com/kunzisoft/keepass/settings/NestedAppSettingsFragment.kt b/app/src/main/java/com/kunzisoft/keepass/settings/NestedAppSettingsFragment.kt index aaa7d6ddc..588410864 100644 --- a/app/src/main/java/com/kunzisoft/keepass/settings/NestedAppSettingsFragment.kt +++ b/app/src/main/java/com/kunzisoft/keepass/settings/NestedAppSettingsFragment.kt @@ -443,6 +443,7 @@ class NestedAppSettingsFragment : NestedSettingsFragment() { getString(R.string.setting_style_key), getString(R.string.setting_style_brightness_key), getString(R.string.setting_icon_pack_choose_key), + getString(R.string.show_entry_colors_key), getString(R.string.list_entries_show_username_key), getString(R.string.list_groups_show_number_entries_key), getString(R.string.show_otp_token_key), diff --git a/app/src/main/java/com/kunzisoft/keepass/settings/PreferencesUtil.kt b/app/src/main/java/com/kunzisoft/keepass/settings/PreferencesUtil.kt index 84e1b30ed..822101ee3 100644 --- a/app/src/main/java/com/kunzisoft/keepass/settings/PreferencesUtil.kt +++ b/app/src/main/java/com/kunzisoft/keepass/settings/PreferencesUtil.kt @@ -110,6 +110,12 @@ object PreferencesUtil { context.resources.getBoolean(R.bool.subdomain_search_default)) } + fun showEntryColors(context: Context): Boolean { + val prefs = PreferenceManager.getDefaultSharedPreferences(context) + return prefs.getBoolean(context.getString(R.string.show_entry_colors_key), + context.resources.getBoolean(R.bool.show_entry_colors_default)) + } + fun showUsernamesListEntries(context: Context): Boolean { val prefs = PreferenceManager.getDefaultSharedPreferences(context) return prefs.getBoolean(context.getString(R.string.list_entries_show_username_key), @@ -652,6 +658,7 @@ object PreferencesUtil { context.getString(R.string.setting_style_key) -> setStyle(context, value) context.getString(R.string.setting_style_brightness_key) -> editor.putString(name, value) context.getString(R.string.setting_icon_pack_choose_key) -> editor.putString(name, value) + context.getString(R.string.show_entry_colors_key) -> editor.putBoolean(name, value.toBoolean()) context.getString(R.string.list_entries_show_username_key) -> editor.putBoolean(name, value.toBoolean()) context.getString(R.string.list_groups_show_number_entries_key) -> editor.putBoolean(name, value.toBoolean()) context.getString(R.string.show_otp_token_key) -> editor.putBoolean(name, value.toBoolean()) diff --git a/app/src/main/res/values/donottranslate.xml b/app/src/main/res/values/donottranslate.xml index 1ec0c1055..0e146ac90 100644 --- a/app/src/main/res/values/donottranslate.xml +++ b/app/src/main/res/values/donottranslate.xml @@ -183,6 +183,8 @@ setting_style_key setting_style_brightness_key setting_icon_pack_choose_key + show_entry_colors_key + true list_entries_show_username_key true list_groups_show_number_entries_key diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 4076e1f75..0f2aebb89 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -641,6 +641,8 @@ Custom Icon pack Icon pack used in the app + Entry colors + Displays foreground and background colors in an entry Hide expired entries Expired entries are not shown \ No newline at end of file diff --git a/app/src/main/res/xml/preferences_appearance.xml b/app/src/main/res/xml/preferences_appearance.xml index 52b22383e..1e5bf7258 100644 --- a/app/src/main/res/xml/preferences_appearance.xml +++ b/app/src/main/res/xml/preferences_appearance.xml @@ -40,6 +40,11 @@ android:key="@string/setting_icon_pack_choose_key" android:title="@string/icon_pack_choose_title" android:summary="@string/icon_pack_choose_summary" /> + From 805c728e921cd01532a9336d4a60c27626b05370 Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Thu, 27 Jan 2022 18:29:00 +0100 Subject: [PATCH 094/112] Change "show" strings by "displays" --- app/src/main/res/values/strings.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0f2aebb89..4f5e1c691 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -198,13 +198,13 @@ The keyfile is empty. Length Show usernames - Show usernames in entry lists + Displays usernames in entry lists Show number of entries Show OTP Token Displays OTP tokens in the list of entries Show UUID Displays the UUID linked to an entry or a group - Show the number of entries in a group + Displays the number of entries in a group Size of list items Text size in the element list Creating database… From c9527ddacdeea7629880b86fe6afb8cdf49acaa2 Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Thu, 27 Jan 2022 18:31:20 +0100 Subject: [PATCH 095/112] Update CHANGELOG --- CHANGELOG | 1 + fastlane/metadata/android/en-US/changelogs/93.txt | 1 + fastlane/metadata/android/fr-FR/changelogs/93.txt | 1 + 3 files changed, 3 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index d2bcddba4..db2e8b4d3 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -2,6 +2,7 @@ KeePassDX(3.2.0) * Manage data merge #840 #977 * Manage Tags #633 * Inherit colors and icon from template #1213 #1130 + * Entry colors setting #1207 * Setting to keep the screen on when watching the entry #1119 * Add path in quick search * Small fixes diff --git a/fastlane/metadata/android/en-US/changelogs/93.txt b/fastlane/metadata/android/en-US/changelogs/93.txt index ba3334421..cc1543c18 100644 --- a/fastlane/metadata/android/en-US/changelogs/93.txt +++ b/fastlane/metadata/android/en-US/changelogs/93.txt @@ -1,6 +1,7 @@ * Manage data merge #840 #977 * Manage Tags #633 * Inherit colors and icon from template #1213 #1130 + * Entry colors setting #1207 * Setting to keep the screen on when watching the entry #1119 * Add path in quick search * Small fixes \ No newline at end of file diff --git a/fastlane/metadata/android/fr-FR/changelogs/93.txt b/fastlane/metadata/android/fr-FR/changelogs/93.txt index a36a8b416..b11975fa3 100644 --- a/fastlane/metadata/android/fr-FR/changelogs/93.txt +++ b/fastlane/metadata/android/fr-FR/changelogs/93.txt @@ -1,6 +1,7 @@ * Gestion de la fusion des données #840 #977 * Gestion des Tags #633 * Héritage des couleurs et icone du gabarit #1213 + * Paramètre des couleurs d'entrée #1207 * Paramètre pour garder l'écran allumé sur une entrée #1119 * Ajout du chemin dans la recherche rapide * Petits correctifs \ No newline at end of file From 94b3f66e1407a2ed546273de3d9089d56e162f14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20Mesk=C3=B3?= Date: Thu, 27 Jan 2022 14:03:18 +0000 Subject: [PATCH 096/112] Translated using Weblate (Hungarian) Currently translated at 100.0% (576 of 576 strings) Translation: KeePassDX/Strings Translate-URL: https://hosted.weblate.org/projects/keepass-dx/strings/hu/ --- app/src/main/res/values-hu/strings.xml | 91 +++++++++++++++++++++----- 1 file changed, 73 insertions(+), 18 deletions(-) diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index ea418e8e1..c0ed36ef0 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -46,7 +46,7 @@ \nA program jelen állapotában kerül közreadásra, <strong>GPLv3</strong> licenc alatt, bármilyen garancia nélkül.
Létező adatbázis megnyitása Utolsó hozzáférés - Mégsem + Mégse Megjegyzések Jelszó megerősítése Létrehozva @@ -206,7 +206,7 @@ Ujjlenyomat-alapú feloldás Lehetővé teszi, hogy leolvassa az ujjlenyomatát az adatbázis megnyitásához Titkosítási kulcsok törlése - Az összes ujjlenyomat-felismeréssel kapcsolatos titkosítási kulcs törlése + Az összes, a speciális feloldásfelisméreshez tartozó titkosítási kulcs törlése A funkciót nem sikerült elindítani. Az eszköz Android %1$s rendszert futtat, de %2$s vagy újabb szükséges. Nem található a megfelelő hardver. @@ -224,7 +224,7 @@ Adatbázis leírása Adatbázis verzió Szöveg - Alkalmazás + Felhasználói felület Egyéb Billentyűzet Mágikus billentyűzet @@ -250,7 +250,7 @@ Mesterkulcs elhagyásának engedélyezése A „Megnyitás” gomb engedélyezése, ha nincsenek hitelesítő adatok kiválasztva Írásvédett - Az adatbázis megnyitása alapértelmezetten csak olvasható módban + Az adatbázis megnyitása alapértelmezetten írásvédett módban Oktatóképernyők Elemek kiemelése, hogy megtudja hogyan működik az alkalmazás Oktatóképernyők visszaállítása @@ -316,8 +316,8 @@ Mesterkulcs Kulcsfájl jelölőnégyzet Ezzel a jelszó és kulcsfájl kombinációval nem hozható létre adatbázis. - Egyszer használatos jelszókezelés (HOTP / TOTP) beállítása, hogy tokent állítson elő a kétfaktoros hitelesítéshez (2FA). - OPT beállítása + Állítson be egyszer használatos jelszókezelést (HOTP/TOTP), hogy tokent állítson elő a kétfaktoros hitelesítéshez (2FA). + OTP beállítása Keresési találatok automatikus javaslata a webes domain vagy az alkalmazásazonosító alapján Automatikus keresés Az adatbázis zárolása, ha a vágólap ideje lejár, vagy ha a használata után bezárja az értesítést @@ -349,7 +349,7 @@ Gyors keresés Közreműködés Kapcsolat - A lejárt bejegyzések rejtettek + A lejárt bejegyzések nem jelennek meg Lejárt bejegyzések elrejtése Kész! Befejezés… @@ -368,7 +368,7 @@ Biztos, hogy végleg törli a kiválasztott csomópontokat\? Parancs végrehajtása… Kuka ürítése - Adatbázis mentése + Adatok mentése Az adatbázis mentése sikertelen. Eszköz billentyűzetének beállításai Gzip @@ -396,12 +396,12 @@ Mesterkulcs beállítások Biztonsági beállítások Adatbázis létrehozása… - Már létezik %1$d ugyanazzal a(z) %2$s UUID azonosítóval. + Már létezik %1$s ugyanazzal a(z) %2$s UUID azonosítóval. A tokennek %1$d és %2$d közötti számú számjegyet kell tartalmaznia. Az időtartamnak %1$d és %2$d másodperc között kell lennie. A számlálónak %1$d és %2$d között kell lennie. A titkos kulcsnak Base32 formátumban kell lennie. - Ide nem másolhat csoportot. + Csoport nem másolható ide. Legalább egy hitelesíti módot be kell állítani. Érvénytelen OTP titok. OTP @@ -423,26 +423,26 @@ Frissítés A csoportban szereplő bejegyzések számának megjelenítése Bejegyzések számának megjelenítése - Bejegyzés ide nem másolható. - Bejegyzés ide nem helyezhető át. + Bejegyzés nem másolható ide. + Bejegyzés nem helyezhető át ide. UUID Mező eltávolítása Jelszó hossza Bejegyzésikon Jelszó láthatóságának átváltásának megismétlése Csomópont gyermekei - Törli a beírt jelszót a kapcsolódási kísérlet után + Törli a beírt jelszót az adatbázishoz való kapcsolódási kísérlet után Jelszó törlése - A bemeneti mezők megjelenítése egy bejegyzés megtekintésekor a Mágikus billentyűzeten + A Mágikus billentyűzet kitöltése azzal a bejegyzéssel, amelyet megtekint a KeePassDX-ben Bejegyzés kiválasztása Kuka Nyomja meg a „Vissza” gombot a zároláshoz Ne lője ki az alkalmazást… Kiválasztási mód - Adatbázishitelesítő-adatok képernyője + Adatbázis-hitelesítőadatok képernyője Billentyűzet váltása Megosztott információk mentése - Megosztott információk automatikus keresése a billentyűzet kitöltéséhez + Ha egy URL-t oszt meg a KeePassDX-szel, akkor az elemek szűrése arra az URL domainnel Megosztott információk keresése Értesítés Eltávolítja azokat a mellékleteket, melyek az adatbázisban szerepelnek, de nem tartoznak bejegyzéshez @@ -476,7 +476,7 @@ Alkalmazástulajdonságok importálása Külső ikon Speciális feloldási kulcs törlése - Adatbázis újratöltése + Adatok újratöltése Hiba történt az adatbázison végzett művelet során. Hiba történt a fájladatok eltávolítása során. A fájladatok már léteznek. @@ -528,7 +528,7 @@ Hiba történt az alkalmazástulajdonságok importálása során Ikon neve Válasszon bejegyzést… - Írja felül a külső módosításokat az adatbázis mentésével, vagy töltse újra a legfrissebb változtatásokkal. + Adatok egyesítése, majd a külső módosítások felülírása az adatbázis mentésével, vagy az adatbázis újratöltése a legfrissebb változtatásokkal. Nyissa meg a speciális feloldási képernyőt az adatbázis feloldásához Speciális feloldásfelismerés Figyelmeztetés: Továbbra is meg kell jegyeznie a mesterjelszót, ha a speciális feloldásfelismerést használja. @@ -553,4 +553,59 @@ Eszköz hitelesítő adataival történő feloldás Lehetővé teszi, hogy az eszköz hitelesítő adataival nyissa meg az adatbázist Letiltott alkalmazások + Adatok egyesítése + Adatbázis bezárása + A speciális feloldás használata ideje, mielőtt a tartalma törölve lesz + Speciális feloldás időtúllépése + Sablonok használata + Dinamikus sablonok használata a bejegyzés mezőinek kitöltéséhez + Sabloncsoport + Automatikus kulcsművelet + Automatikus visszaváltás az előző billentyűzetre az „Automatikus kulcsművelet” végrehajtása után + Adatbázis zárolása + Automatikus visszaváltás az előző billentyűzetre az adatbázis zárolása után + Válasszon bejegyzést + Törlés + Enter + Adatbázis zárolása az automatikus kitöltés után + Soron belüli javaslatok + Automatikus kitöltési javaslatok megjelenítésének kísérlete a kompatibilis billentyűzeteknél + Kézi kiválasztás + Lehetőség megjelenítése, hogy a felhasználó válasszon adatbázis-bejegyzést + Keresési információk mentése + A keresési információk mentésének kísérlete kézi bejegyzéskiválasztásnál + Az adatok mentésének kérése az űrlapok ellenőrzésekor + Tiltólista, amely megakadályozza a webes domainek automatikus kitöltését + Automatikus kitöltés letiltása + Indítsa újra az űrlapot tartalmazó alkalmazást a tiltás aktiválásához. + Az adatmentés nem engedélyezett, mert az adatbázis írásvédettként van megnyitva. + Automatikus kitöltési javaslatok hozzáadva. + Töltsön fel egy mellékletet a bejegyzéséhez, hogy mentse a fontos külső adatokat. + Megszakítva! + B + Válasszon a világos vagy sötét témák közül + Szokásos + Egyéni + UUID megjelenítése + Téma fényereje + Megjeleníti a bejegyzéshez vagy csoporthoz tartozó UUID-t + OTP token megjelenítése + Törli az összes, a speciális feloldásfelisméreshez tartozó titkosítási kulcsot\? + Egy URL KeePassDX-be történő megosztásakor, ha kiválaszt egy bejegyzést, akkor megpróbálja megjegyezni a bejegyzés a további használathoz + Egyéni mezők + Vissza az előző billentyűzethez + %1$s feltöltése + KiB + MiB + GiB + Tiltólista, amely megakadályozza az alkalmazások automatikus kitöltését + Letiltott webes domainek + Adatok mentésének kérése + Speciális adatbázis-feloldás + A jelszó összekötése a leolvasott biometrikus adatokkal vagy eszköz-hitelesítőadatokkal, hogy gyorsan feloldhassa az adatbázist. + Megjeleníti az OTP tokeneket a bejegyzések között + Melléklet hozzáadása + Automatikus visszaváltás az előző billentyűzetre az adatbázis-hitelesítőadatok képernyőn + Az adatbázis újratöltése törli a helyileg módosított adatokat. + Sablonok \ No newline at end of file From 94d30fc7ec228e32cd4545ecd026247d9a4128f1 Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Thu, 27 Jan 2022 18:43:12 +0100 Subject: [PATCH 097/112] Change string --- app/src/main/res/values/strings.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 4f5e1c691..11a48e5aa 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -332,7 +332,7 @@ It is not recommended to add an empty keyfile. The content of the keyfile should never be changed, and in the best case, should contain randomly generated data. The information contained in your database file has been modified outside the app. - Merge the data, overwrite the external modifications by saving the database or reload the database with the latest changes. + Merge the data, overwrite the external modifications by saving the database or reload it with the latest changes. Reloading the database will delete the locally modified data. Access to the file revoked by the file manager, close the database and reopen it from its location. You have not allowed the app to use an exact alarm. As a result, the features requiring a timer will not be done with an exact time. From 8291e94de4f8214bbaefc2f0e52671dfe13900b0 Mon Sep 17 00:00:00 2001 From: Retrial Date: Thu, 27 Jan 2022 17:35:36 +0000 Subject: [PATCH 098/112] Translated using Weblate (Greek) Currently translated at 100.0% (582 of 582 strings) Translation: KeePassDX/Strings Translate-URL: https://hosted.weblate.org/projects/keepass-dx/strings/el/ --- app/src/main/res/values-el/strings.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index d80915986..0f513aeb2 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -610,4 +610,10 @@ Χρώμα φόντου καταχώρησης Η επαναφόρτωση της βάσης δεδομένων θα διαγράψει τα τοπικά τροποποιημένα δεδομένα. Συγχώνευση δεδομένων + Ετικέτες + Ο κατακερματισμός του αρχείου δεν είναι εγγυημένος επειδή το Android μπορεί να αλλάξει τα δεδομένα του αμέσως. Αλλάξτε την επέκταση αρχείου σε .bin για σωστή ακεραιότητα. + Κρατήστε την οθόνη ενεργή όταν παρακολουθείτε την καταχώρηση + Διατηρήστε την οθόνη ενεργή + Χρώματα καταχώρησης + Εμφανίζει τα χρώματα του προσκηνίου και του φόντου σε μια καταχώρηση \ No newline at end of file From 7468db5269989af4ba3a735ebda82ccf3837a796 Mon Sep 17 00:00:00 2001 From: Kunzisoft Date: Thu, 27 Jan 2022 17:36:48 +0000 Subject: [PATCH 099/112] Translated using Weblate (French) Currently translated at 99.6% (580 of 582 strings) Translation: KeePassDX/Strings Translate-URL: https://hosted.weblate.org/projects/keepass-dx/strings/fr/ --- app/src/main/res/values-fr/strings.xml | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 033dde9c8..76b1f5872 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -410,7 +410,7 @@ Gzip Paramètres du clavier de l’appareil Impossible d’enregistrer la base de données. - Enregistrer la base de données + Enregistrer les données Vider la corbeille Exécution de la commande… Supprimer définitivement les nœuds sélectionnés \? @@ -543,10 +543,10 @@ Suggestions de remplissage automatique ajoutées. Tente d\'afficher des suggestions de remplissage automatique dans la barre de suggestions des claviers compatibles Suggestions en ligne - Écraser les modifications externes en sauvegardant la base de données ou recharger-la avec les dernières modifications. + Fusionner les données, écraser les modifications externes en sauvegardant la base de données ou recharger-la avec les dernières modifications. Accès au dossier révoqué par le gestionnaire de fichiers, fermer la base de données et la rouvrir à partir de son emplacement. Les informations contenues dans votre fichier de base de données ont été modifiées en dehors de l\'application. - Recharger la base de données + Recharger les données Gibioctets Mébioctets Kibioctets @@ -615,4 +615,12 @@ Permission Vous n\'avez pas autorisé l\'application à utiliser une alarme exacte. Par conséquent, les fonctions nécessitant une minuterie ne seront pas effectuées avec une heure exacte. Couleur d\'arrière plan de l\'entrée + Étiquettes + Fusionner les données + Maintiens l\'écran allumé lorsque l\'entrée est visionnée + Le hachage du fichier n\'est pas garanti car Android peut modifier ses données à la volée. Changez l\'extension du fichier en .bin pour une intégrité correcte. + Maintenir l\'écran allumé + Affiche les couleurs de premier plan et d\'arrière-plan dans une entrée + Le rechargement de la base de données supprimera les données modifiées localement. + Couleurs d\'entrée \ No newline at end of file From ed6456599bbf56c6b832b3d1b345e5bfd31da4a7 Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Thu, 27 Jan 2022 18:47:48 +0100 Subject: [PATCH 100/112] Update string --- app/src/main/res/values/strings.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 11a48e5aa..62cd620f1 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -156,9 +156,9 @@ This label already exists. Enter a positive integer number in the \"Length\" field. Could not enable autofill service. - You can not move a group here. - You can not move an entry here. - You can not copy an entry here. + You cannot move a group here. + You cannot move an entry here. + You cannot copy an entry here. You cannot copy a group here. Unable to create database file. Unable to create database with this password and keyfile. From 065fd9632c0db621f66dce2b33ada4800c106a3e Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Thu, 27 Jan 2022 18:56:13 +0100 Subject: [PATCH 101/112] Update string --- app/src/main/res/values/strings.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 62cd620f1..536aff4d5 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -350,7 +350,7 @@ Open database with advanced unlock recognition Extract database credential with advanced unlock data Encrypted password stored - Can not read the advanced unlock key. Please delete it and repeat the unlock recognition procedure. + Cannot read the advanced unlock key. Please delete it and repeat the unlock recognition procedure. Could not recognize advanced unlock print Advanced unlock error: %1$s This database does not have stored credential yet. From e876e89b41e7cb0a9a912c6fc805245f091c14be Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Fri, 28 Jan 2022 10:09:45 +0100 Subject: [PATCH 102/112] Upgrade version code --- app/build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index c522ff32c..19c824473 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -12,8 +12,8 @@ android { applicationId "com.kunzisoft.keepass" minSdkVersion 15 targetSdkVersion 31 - versionCode = 93 - versionName = "3.2.0" + versionCode = 94 + versionName = "3.2.0_beta2" multiDexEnabled true testApplicationId = "com.kunzisoft.keepass.tests" From 3c7c88e0f54b9c30158e17528c4282af4f5fc488 Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Fri, 28 Jan 2022 12:01:32 +0100 Subject: [PATCH 103/112] Hot fix for search #1219 --- .../java/com/kunzisoft/keepass/activities/GroupActivity.kt | 5 +++-- app/src/main/res/menu/search.xml | 3 +-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/GroupActivity.kt b/app/src/main/java/com/kunzisoft/keepass/activities/GroupActivity.kt index 4abb99360..2e92138eb 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/GroupActivity.kt +++ b/app/src/main/java/com/kunzisoft/keepass/activities/GroupActivity.kt @@ -1091,9 +1091,10 @@ class GroupActivity : DatabaseLockActivity(), // TODO change database return true } - R.id.menu_search -> - //onSearchRequested(); + R.id.menu_search -> { + onSearchRequested() return true + } R.id.menu_save_database -> { saveDatabase() return true diff --git a/app/src/main/res/menu/search.xml b/app/src/main/res/menu/search.xml index b742492f6..4ed608470 100644 --- a/app/src/main/res/menu/search.xml +++ b/app/src/main/res/menu/search.xml @@ -25,6 +25,5 @@ app:showAsAction="always|collapseActionView" android:orderInCategory="31" android:iconifiedByDefault="true" - app:iconTint="?attr/colorControlNormal" - app:actionViewClass="androidx.appcompat.widget.SearchView" /> + app:iconTint="?attr/colorControlNormal" /> \ No newline at end of file From 7b0c31c641f9a84f95bec392856e2d98b3e49d2d Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Fri, 28 Jan 2022 15:49:00 +0100 Subject: [PATCH 104/112] Fix search #1219 --- .../kunzisoft/keepass/activities/GroupActivity.kt | 2 +- .../keepass/adapters/SearchEntryCursorAdapter.kt | 13 ++++++++----- app/src/main/res/menu/search.xml | 5 +++-- app/src/main/res/values/styles.xml | 2 -- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/GroupActivity.kt b/app/src/main/java/com/kunzisoft/keepass/activities/GroupActivity.kt index 2e92138eb..0391243dd 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/GroupActivity.kt +++ b/app/src/main/java/com/kunzisoft/keepass/activities/GroupActivity.kt @@ -1092,7 +1092,7 @@ class GroupActivity : DatabaseLockActivity(), return true } R.id.menu_search -> { - onSearchRequested() + //onSearchRequested() return true } R.id.menu_save_database -> { diff --git a/app/src/main/java/com/kunzisoft/keepass/adapters/SearchEntryCursorAdapter.kt b/app/src/main/java/com/kunzisoft/keepass/adapters/SearchEntryCursorAdapter.kt index 88cdb8862..d5e15cff7 100644 --- a/app/src/main/java/com/kunzisoft/keepass/adapters/SearchEntryCursorAdapter.kt +++ b/app/src/main/java/com/kunzisoft/keepass/adapters/SearchEntryCursorAdapter.kt @@ -78,7 +78,7 @@ class SearchEntryCursorAdapter(private val context: Context, return view } - override fun bindView(view: View, context: Context, cursor: Cursor) { + override fun bindView(view: View, context: Context, cursor: Cursor?) { getEntryFrom(cursor)?.let { currentEntry -> val viewHolder = view.tag as ViewHolder @@ -111,16 +111,19 @@ class SearchEntryCursorAdapter(private val context: Context, } } - private fun getEntryFrom(cursor: Cursor): Entry? { - val entryCursor = cursor as EntryCursor - return database.getEntryById(entryCursor.getNodeId()) + private fun getEntryFrom(cursor: Cursor?): Entry? { + val entryCursor = cursor as? EntryCursor? + entryCursor?.getNodeId()?.let { + return database?.getEntryById(it) + } + return null } override fun runQueryOnBackgroundThread(constraint: CharSequence): Cursor? { return searchEntries(context, constraint.toString()) } - private fun searchEntries(context: Context, query: String): Cursor? { + private fun searchEntries(context: Context, query: String): Cursor { val cursor = EntryCursor() val searchGroup = database.createVirtualGroupFromSearch(query, mOmitBackup, diff --git a/app/src/main/res/menu/search.xml b/app/src/main/res/menu/search.xml index 4ed608470..17698f9d3 100644 --- a/app/src/main/res/menu/search.xml +++ b/app/src/main/res/menu/search.xml @@ -22,8 +22,9 @@ + app:iconTint="?attr/colorControlNormal" + app:showAsAction="always|collapseActionView" + app:actionViewClass="androidx.appcompat.widget.SearchView" /> \ No newline at end of file diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml index 220af43bf..cf3910235 100644 --- a/app/src/main/res/values/styles.xml +++ b/app/src/main/res/values/styles.xml @@ -94,7 +94,6 @@ @style/KeepassDXStyle.TextInputLayout - @style/KeepassDXStyle.TextInputLayout.ExposedMenu From cebba5a09d268434ee2f30684e35de8ef162500f Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Fri, 28 Jan 2022 15:49:59 +0100 Subject: [PATCH 105/112] Upgrade to 3.2.0 beta3 --- app/build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 19c824473..8de665d31 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -12,8 +12,8 @@ android { applicationId "com.kunzisoft.keepass" minSdkVersion 15 targetSdkVersion 31 - versionCode = 94 - versionName = "3.2.0_beta2" + versionCode = 95 + versionName = "3.2.0_beta3" multiDexEnabled true testApplicationId = "com.kunzisoft.keepass.tests" From ba0e87f32a8fb23631d07c8093d778e07f57fb52 Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Fri, 28 Jan 2022 15:56:16 +0100 Subject: [PATCH 106/112] Fix warning --- .../com/kunzisoft/keepass/adapters/SearchEntryCursorAdapter.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/com/kunzisoft/keepass/adapters/SearchEntryCursorAdapter.kt b/app/src/main/java/com/kunzisoft/keepass/adapters/SearchEntryCursorAdapter.kt index d5e15cff7..06d576f21 100644 --- a/app/src/main/java/com/kunzisoft/keepass/adapters/SearchEntryCursorAdapter.kt +++ b/app/src/main/java/com/kunzisoft/keepass/adapters/SearchEntryCursorAdapter.kt @@ -114,7 +114,7 @@ class SearchEntryCursorAdapter(private val context: Context, private fun getEntryFrom(cursor: Cursor?): Entry? { val entryCursor = cursor as? EntryCursor? entryCursor?.getNodeId()?.let { - return database?.getEntryById(it) + return database.getEntryById(it) } return null } From 0f021fae9f6d9e9313c628593f2721a929892e6c Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Sun, 30 Jan 2022 19:34:59 +0100 Subject: [PATCH 107/112] Fix Kdbx4 tag in Kdbx3 database #1222 --- .../keepass/database/element/database/DatabaseKDBX.kt | 9 ++++++++- .../database/file/output/DatabaseOutputKDBX.kt | 11 ++++------- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/database/DatabaseKDBX.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/database/DatabaseKDBX.kt index 0ab0c90f7..d9244b1a1 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/database/DatabaseKDBX.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/database/DatabaseKDBX.kt @@ -122,6 +122,12 @@ class DatabaseKDBX : DatabaseVersioned { throw unknownKDFException } + fun randomizeKdfParameters() { + kdfParameters?.let { + kdfEngine?.randomize(it) + } + } + override val kdfAvailableList: List = listOf( KdfFactory.aesKdf, KdfFactory.argon2dKdf, @@ -245,7 +251,8 @@ class DatabaseKDBX : DatabaseVersioned { // https://keepass.info/help/kb/kdbx_4.html // If AES is not use, it's at least 4.0 - val kdfIsNotAes = kdfParameters?.uuid != AesKdf.CIPHER_UUID + val keyDerivationFunction = kdfEngine + val kdfIsNotAes = keyDerivationFunction != null && keyDerivationFunction.uuid != AesKdf.CIPHER_UUID val containsHeaderCustomData = customData.isNotEmpty() val containsNodeCustomData = entryHandler.containsCustomData || groupHandler.containsCustomData diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/output/DatabaseOutputKDBX.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/output/DatabaseOutputKDBX.kt index 1ae6cdc65..ffdf94d8e 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/output/DatabaseOutputKDBX.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/output/DatabaseOutputKDBX.kt @@ -230,7 +230,9 @@ class DatabaseOutputKDBX(private val mDatabaseKDBX: DatabaseKDBX, writeString(DatabaseKDBXXML.ElemHeaderHash, String(Base64.encode(hashOfHeader!!, BASE_64_FLAG))) } - writeDateInstant(DatabaseKDBXXML.ElemSettingsChanged, mDatabaseKDBX.settingsChanged) + if (!header!!.version.isBefore(FILE_VERSION_40)) { + writeDateInstant(DatabaseKDBXXML.ElemSettingsChanged, mDatabaseKDBX.settingsChanged) + } writeString(DatabaseKDBXXML.ElemDbName, mDatabaseKDBX.name, true) writeDateInstant(DatabaseKDBXXML.ElemDbNameChanged, mDatabaseKDBX.nameChanged) writeString(DatabaseKDBXXML.ElemDbDesc, mDatabaseKDBX.description, true) @@ -296,12 +298,7 @@ class DatabaseOutputKDBX(private val mDatabaseKDBX: DatabaseKDBX, mDatabaseKDBX.kdfParameters = KdfFactory.aesKdf.defaultParameters } - try { - val kdf = mDatabaseKDBX.getEngineKDBX4(mDatabaseKDBX.kdfParameters) - kdf.randomize(mDatabaseKDBX.kdfParameters!!) - } catch (unknownKDF: UnknownKDF) { - Log.e(TAG, "Unable to retrieve header", unknownKDF) - } + mDatabaseKDBX.randomizeKdfParameters() if (header.version.isBefore(FILE_VERSION_40)) { header.innerRandomStream = CrsAlgorithm.Salsa20 From 858d6c8723d937ba154d114f2787aca753bdfccc Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Sun, 30 Jan 2022 19:44:46 +0100 Subject: [PATCH 108/112] Upgrade to 3.2.0_beta4 --- app/build.gradle | 4 ++-- fastlane/README.md | 46 +++++++++++++++++++++++++++++----------------- 2 files changed, 31 insertions(+), 19 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 8de665d31..c5f4feb3d 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -12,8 +12,8 @@ android { applicationId "com.kunzisoft.keepass" minSdkVersion 15 targetSdkVersion 31 - versionCode = 95 - versionName = "3.2.0_beta3" + versionCode = 96 + versionName = "3.2.0_beta4" multiDexEnabled true testApplicationId = "com.kunzisoft.keepass.tests" diff --git a/fastlane/README.md b/fastlane/README.md index 336d7fec5..f39d095b8 100644 --- a/fastlane/README.md +++ b/fastlane/README.md @@ -1,44 +1,56 @@ fastlane documentation -================ +---- + # Installation Make sure you have the latest version of the Xcode command line tools installed: -``` +```sh xcode-select --install ``` -Install _fastlane_ using -``` -[sudo] gem install fastlane -NV -``` -or alternatively using `brew install fastlane` +For _fastlane_ installation instructions, see [Installing _fastlane_](https://docs.fastlane.tools/#installing-fastlane) # Available Actions + ## Android + ### android tests + +```sh +[bundle exec] fastlane android tests ``` -fastlane android tests -``` + Runs all the tests + ### android build_beta + +```sh +[bundle exec] fastlane android build_beta ``` -fastlane android build_beta -``` + Build a new Beta version + ### android deploy_beta_free + +```sh +[bundle exec] fastlane android deploy_beta_free ``` -fastlane android deploy_beta_free -``` + Deploy a new Free Beta version to the Google Play + ### android deploy_beta_pro + +```sh +[bundle exec] fastlane android deploy_beta_pro ``` -fastlane android deploy_beta_pro -``` + Deploy a new Pro Beta version to the Google Play ---- This README.md is auto-generated and will be re-generated every time [_fastlane_](https://fastlane.tools) is run. -More information about fastlane can be found on [fastlane.tools](https://fastlane.tools). -The documentation of fastlane can be found on [docs.fastlane.tools](https://docs.fastlane.tools). + +More information about _fastlane_ can be found on [fastlane.tools](https://fastlane.tools). + +The documentation of _fastlane_ can be found on [docs.fastlane.tools](https://docs.fastlane.tools). From ce8e532f6106755f5b6372c53978e7b49d134a91 Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Tue, 1 Feb 2022 15:50:20 +0100 Subject: [PATCH 109/112] Larger view for breadcrumb --- app/src/main/res/layout/activity_group.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/res/layout/activity_group.xml b/app/src/main/res/layout/activity_group.xml index f7c3cffaf..41472db86 100644 --- a/app/src/main/res/layout/activity_group.xml +++ b/app/src/main/res/layout/activity_group.xml @@ -125,7 +125,7 @@ From 80cf4f05f8d98e2ae0b0210fd59d10e8160ef098 Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Tue, 1 Feb 2022 16:03:54 +0100 Subject: [PATCH 110/112] Better unknown KDF exception --- .../database/element/database/DatabaseKDBX.kt | 19 +++++---------- .../keepass/database/exception/UnknownKDF.kt | 24 ------------------- .../file/output/DatabaseOutputKDBX.kt | 1 - 3 files changed, 6 insertions(+), 38 deletions(-) delete mode 100644 app/src/main/java/com/kunzisoft/keepass/database/exception/UnknownKDF.kt diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/database/DatabaseKDBX.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/database/DatabaseKDBX.kt index d9244b1a1..3a1fa3c8b 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/database/DatabaseKDBX.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/database/DatabaseKDBX.kt @@ -49,7 +49,6 @@ import com.kunzisoft.keepass.database.element.node.NodeVersioned import com.kunzisoft.keepass.database.element.security.MemoryProtectionConfig import com.kunzisoft.keepass.database.element.template.Template import com.kunzisoft.keepass.database.element.template.TemplateEngineCompatible -import com.kunzisoft.keepass.database.exception.UnknownKDF import com.kunzisoft.keepass.database.file.DatabaseHeaderKDBX.Companion.FILE_VERSION_31 import com.kunzisoft.keepass.database.file.DatabaseHeaderKDBX.Companion.FILE_VERSION_40 import com.kunzisoft.keepass.database.file.DatabaseHeaderKDBX.Companion.FILE_VERSION_41 @@ -92,12 +91,7 @@ class DatabaseKDBX : DatabaseVersioned { var kdfParameters: KdfParameters? = null override var kdfEngine: KdfEngine? - get() = try { - getEngineKDBX4(kdfParameters) - } catch (unknownKDF: UnknownKDF) { - Log.i(TAG, "Unable to retrieve KDF engine", unknownKDF) - null - } + get() = getKdfEngineFromParameters(kdfParameters) set(value) { value?.let { if (kdfParameters?.uuid != value.defaultParameters.uuid) @@ -108,18 +102,16 @@ class DatabaseKDBX : DatabaseVersioned { } } - @Throws(UnknownKDF::class) - fun getEngineKDBX4(kdfParameters: KdfParameters?): KdfEngine { - val unknownKDFException = UnknownKDF() + private fun getKdfEngineFromParameters(kdfParameters: KdfParameters?): KdfEngine? { if (kdfParameters == null) { - throw unknownKDFException + return null } for (engine in kdfAvailableList) { if (engine.uuid == kdfParameters.uuid) { return engine } } - throw unknownKDFException + return null } fun randomizeKdfParameters() { @@ -553,7 +545,8 @@ class DatabaseKDBX : DatabaseVersioned { fun makeFinalKey(masterSeed: ByteArray) { kdfParameters?.let { keyDerivationFunctionParameters -> - val kdfEngine = getEngineKDBX4(keyDerivationFunctionParameters) + val kdfEngine = getKdfEngineFromParameters(keyDerivationFunctionParameters) + ?: throw IOException("Unknown key derivation function") var transformedMasterKey = kdfEngine.transform(masterKey, keyDerivationFunctionParameters) if (transformedMasterKey.size != 32) { diff --git a/app/src/main/java/com/kunzisoft/keepass/database/exception/UnknownKDF.kt b/app/src/main/java/com/kunzisoft/keepass/database/exception/UnknownKDF.kt deleted file mode 100644 index 5daf59459..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/exception/UnknownKDF.kt +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2019 Jeremy Jamet / Kunzisoft. - * - * This file is part of KeePassDX. - * - * KeePassDX is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * KeePassDX is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with KeePassDX. If not, see . - * - */ -package com.kunzisoft.keepass.database.exception - -import java.io.IOException - -class UnknownKDF : IOException("Unknown key derivation function") diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/output/DatabaseOutputKDBX.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/output/DatabaseOutputKDBX.kt index ffdf94d8e..6677e6fb8 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/output/DatabaseOutputKDBX.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/output/DatabaseOutputKDBX.kt @@ -37,7 +37,6 @@ import com.kunzisoft.keepass.database.element.group.GroupKDBX import com.kunzisoft.keepass.database.element.node.NodeKDBXInterface import com.kunzisoft.keepass.database.element.security.MemoryProtectionConfig import com.kunzisoft.keepass.database.exception.DatabaseOutputException -import com.kunzisoft.keepass.database.exception.UnknownKDF import com.kunzisoft.keepass.database.file.DatabaseHeaderKDBX import com.kunzisoft.keepass.database.file.DatabaseHeaderKDBX.Companion.FILE_VERSION_40 import com.kunzisoft.keepass.database.file.DatabaseHeaderKDBX.Companion.FILE_VERSION_41 From 5fb4c4c20c85f176f3e71b4f7561062271634350 Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Tue, 1 Feb 2022 17:06:51 +0100 Subject: [PATCH 111/112] Fix dialog when no modification performed --- .../keepass/database/element/Database.kt | 15 ++++++++++----- .../keepass/database/search/SearchHelper.kt | 3 +-- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/Database.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/Database.kt index 52c11236b..c28438ea6 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/Database.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/Database.kt @@ -994,20 +994,25 @@ class Database { return null } - fun createGroup(): Group? { - dataModifiedSinceLastLoading = true + fun createGroup(virtual: Boolean = false): Group? { + if (!virtual) { + dataModifiedSinceLastLoading = true + } + var group: Group? = null mDatabaseKDB?.let { database -> - return Group(database.createGroup()).apply { + group = Group(database.createGroup()).apply { setNodeId(database.newGroupId()) } } mDatabaseKDBX?.let { database -> - return Group(database.createGroup()).apply { + group = Group(database.createGroup()).apply { setNodeId(database.newGroupId()) } } + if (virtual) + group?.isVirtual = virtual - return null + return group } fun getEntryById(id: NodeId): Entry? { diff --git a/app/src/main/java/com/kunzisoft/keepass/database/search/SearchHelper.kt b/app/src/main/java/com/kunzisoft/keepass/database/search/SearchHelper.kt index 6553523bc..594f077e4 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/search/SearchHelper.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/search/SearchHelper.kt @@ -40,8 +40,7 @@ class SearchHelper { omitBackup: Boolean, max: Int): Group? { - val searchGroup = database.createGroup() - searchGroup?.isVirtual = true + val searchGroup = database.createGroup(virtual = true) searchGroup?.title = "\"" + searchParameters.searchQuery + "\"" // Search all entries From a152a48402d2b65a263f748bbda18376d3d05cff Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Tue, 1 Feb 2022 17:10:04 +0100 Subject: [PATCH 112/112] Upgrade to 3.2.0 --- app/build.gradle | 4 ++-- fastlane/metadata/android/en-US/changelogs/{93.txt => 97.txt} | 0 fastlane/metadata/android/fr-FR/changelogs/{93.txt => 97.txt} | 0 3 files changed, 2 insertions(+), 2 deletions(-) rename fastlane/metadata/android/en-US/changelogs/{93.txt => 97.txt} (100%) rename fastlane/metadata/android/fr-FR/changelogs/{93.txt => 97.txt} (100%) diff --git a/app/build.gradle b/app/build.gradle index c5f4feb3d..dd8c95f4b 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -12,8 +12,8 @@ android { applicationId "com.kunzisoft.keepass" minSdkVersion 15 targetSdkVersion 31 - versionCode = 96 - versionName = "3.2.0_beta4" + versionCode = 97 + versionName = "3.2.0" multiDexEnabled true testApplicationId = "com.kunzisoft.keepass.tests" diff --git a/fastlane/metadata/android/en-US/changelogs/93.txt b/fastlane/metadata/android/en-US/changelogs/97.txt similarity index 100% rename from fastlane/metadata/android/en-US/changelogs/93.txt rename to fastlane/metadata/android/en-US/changelogs/97.txt diff --git a/fastlane/metadata/android/fr-FR/changelogs/93.txt b/fastlane/metadata/android/fr-FR/changelogs/97.txt similarity index 100% rename from fastlane/metadata/android/fr-FR/changelogs/93.txt rename to fastlane/metadata/android/fr-FR/changelogs/97.txt