Skip to content

Commit

Permalink
properly re-sort the list when copying an existing clipboard entry
Browse files Browse the repository at this point in the history
  • Loading branch information
Helium314 committed Apr 12, 2024
1 parent f915e46 commit a9411b3
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ package helium314.keyboard.latin
import android.content.ClipboardManager
import android.content.Context
import android.text.TextUtils
import androidx.preference.PreferenceManager
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import helium314.keyboard.compat.ClipboardManagerCompat
Expand Down Expand Up @@ -51,15 +50,23 @@ class ClipboardHistoryManager(
val clipData = clipboardManager.primaryClip ?: return
if (clipData.itemCount == 0) return
clipData.getItemAt(0)?.let { clipItem ->
// Starting from API 30, onPrimaryClipChanged() can be called multiple times
// for the same clip. We can identify clips with their timestamps since API 26.
// We use that to prevent unwanted duplicates.
val timeStamp = ClipboardManagerCompat.getClipTimestamp(clipData)?.also { stamp ->
if (historyEntries.any { it.timeStamp == stamp }) return
} ?: System.currentTimeMillis()

val timeStamp = ClipboardManagerCompat.getClipTimestamp(clipData) ?: System.currentTimeMillis()
val content = clipItem.coerceToText(latinIME)
if (TextUtils.isEmpty(content)) return

val duplicateEntryIndex = historyEntries.indexOfFirst { it.content.toString() == content.toString() }
if (duplicateEntryIndex != -1) {
val existingEntry = historyEntries[duplicateEntryIndex]
if (existingEntry.timeStamp == timeStamp) return // nothing to change (may occur frequently starting with API 30)
// older entry with the same text already exists, update the timestamp and re-sort the list
existingEntry.timeStamp = timeStamp
historyEntries.removeAt(duplicateEntryIndex)
historyEntries.add(0, existingEntry)
sortHistoryEntries()
val newIndex = historyEntries.indexOf(existingEntry)
onHistoryChangeListener?.onClipboardHistoryEntryMoved(duplicateEntryIndex, newIndex)
return
}
if (historyEntries.any { it.content.toString() == content.toString() }) return

val entry = ClipboardHistoryEntry(timeStamp, content)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -719,6 +719,7 @@ private void handleFunctionalEvent(final Event event, final InputTransaction inp
case KeyCode.CLIPBOARD_CUT:
if (mConnection.hasSelection()) {
mConnection.copyText();
// fake delete keypress to remove the text
final Event backspaceEvent = LatinIME.createSoftwareKeypressEvent(KeyCode.DELETE,
event.getMX(), event.getMY(), event.isKeyRepeat());
handleBackspaceEvent(backspaceEvent, inputTransaction, currentKeyboardScript);
Expand Down

0 comments on commit a9411b3

Please sign in to comment.