Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Unverified Commit 9bca5fac authored by Ricki Hirner's avatar Ricki Hirner
Browse files

Css3Color: treat color names case-insensitive and parse hex values if possible

parent 73058b1c
Loading
Loading
Loading
Loading
+48 −0
Original line number Diff line number Diff line
@@ -5,10 +5,38 @@
package at.bitfire.ical4android

import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test

class Css3ColorTest {

    @Test
    fun testColorFromString() {
        // color name
        assertEquals(0xffffff00.toInt(), Css3Color.colorFromString("yellow"))

        // RGB value
        assertEquals(0xffffff00.toInt(), Css3Color.colorFromString("#ffff00"))

        // ARGB value
        assertEquals(0xffffff00.toInt(), Css3Color.colorFromString("#ffffff00"))

        // invalid value
        assertNull(Css3Color.colorFromString("DoesNotExist"))
    }

    @Test
    fun testFromString() {
        // lower case
        assertEquals(0xffffff00.toInt(), Css3Color.fromString("yellow")?.argb)

        // capitalized
        assertEquals(0xffffff00.toInt(), Css3Color.fromString("Yellow")?.argb)

        // not-existing color
        assertNull(Css3Color.fromString("DoesNotExist"))
    }

    @Test
    fun testNearestMatch() {
        // every color is its own nearest match
+19 −5
Original line number Diff line number Diff line
@@ -4,6 +4,7 @@

package at.bitfire.ical4android

import android.graphics.Color
import kotlin.math.sqrt

/**
@@ -166,16 +167,29 @@ enum class Css3Color(val argb: Int) {
    companion object {

        /**
         * Returns the CSS3 color property of the given name.
         * Parses the given color either as CSS3 color name or as (A)RGB hex value.
         *
         * @param name      color name
         * @return          [Css3Color] object or null if no match was found
         * @param color     CSS3 color name like "blue" or (A)RGB hex value like #0000FF
         * @return          ARGB color value or *null* if the color couldn't be parsed
         */
        fun colorFromString(color: String): Int? =
            fromString(color)?.argb ?:
                try {
                    Color.parseColor(color)
                } catch(e: IllegalArgumentException) {
                    null
                }

        /**
         * Returns the Css3Color object of the given CSS3 color name.
         *
         * @param name      CSS3 color name like "blue"
         * @return          [Css3Color] object or *null* if no match was found
         */
        fun fromString(name: String) =
                try {
                    valueOf(name)
                    valueOf(name.lowercase())
                } catch (e: IllegalArgumentException) {
                    Ical4Android.log.warning("Unknown color: $name")
                    null
                }