Implement simple avatar color picking algorithm to align with iOS.

This commit is contained in:
Alex Hart
2023-06-05 10:07:10 -03:00
committed by Cody Henthorne
parent bf7aaddbf9
commit 290c107698
6 changed files with 78 additions and 15 deletions

View File

@@ -98,7 +98,7 @@ public enum AvatarColor {
}
/** Colors that can be assigned via {@link #random()}. */
private static final AvatarColor[] RANDOM_OPTIONS = new AvatarColor[] {
static final AvatarColor[] RANDOM_OPTIONS = new AvatarColor[] {
A100,
A110,
A120,

View File

@@ -0,0 +1,56 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.thoughtcrime.securesms.conversation.colors
import org.thoughtcrime.securesms.groups.GroupId
/**
* Stolen from iOS. Utilizes a simple hash to map different characteristics to an avatar color index.
*/
object AvatarColorHash {
/**
* Utilize Uppercase UUID of ServiceId.
*
* Uppercase is necessary here because iOS utilizes uppercase UUIDs by default.
*/
fun forAddress(serviceId: String?, e164: String?): AvatarColor {
if (!serviceId.isNullOrEmpty()) {
return forSeed(serviceId.toString().uppercase())
}
if (!e164.isNullOrEmpty()) {
return forSeed(e164)
}
return AvatarColor.A100
}
fun forGroupId(group: GroupId): AvatarColor {
return forData(group.decodedId)
}
fun forSeed(seed: String): AvatarColor {
return forData(seed.toByteArray())
}
fun forCallLink(rootKey: ByteArray): AvatarColor {
return forIndex(rootKey.first().toInt())
}
private fun forData(data: ByteArray): AvatarColor {
var hash = 0
for (value in data) {
hash = hash.rotateLeft(3) xor value.toInt()
}
return forIndex(hash)
}
private fun forIndex(index: Int): AvatarColor {
return AvatarColor.RANDOM_OPTIONS[(index.toUInt() % AvatarColor.RANDOM_OPTIONS.size.toUInt()).toInt()]
}
}