~gardenapple/mitch

ref: c4082deb0c7a0157103ade7b64cee8fb2ea236e7 mitch/app/src/main/java/ua/gardenapple/itchupdater/Utils.kt -rw-r--r-- 8.9 KiB
c4082debgardenapple Adapt to game jam & forum themes 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
package ua.gardenapple.itchupdater

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.ColorStateList
import android.content.res.Configuration
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.Html
import android.text.Spanned
import android.util.Log
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.core.content.FileProvider
import androidx.core.graphics.ColorUtils
import com.github.ajalt.colormath.ConvertibleColor
import com.github.ajalt.colormath.fromCss
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
import java.io.*
import java.util.*
import kotlin.math.min


object Utils {
    class ErrorReport(message: String) : Throwable(message)

    private const val LOG_LIMIT: Int = 1000

    /**
     * Logcat normally has a limit of 1000 characters.
     * This function splits long strings into multiple log entries.
     */
    fun logPrintLong(priority: Int, tag: String, string: String) {
        for (i in string.indices step LOG_LIMIT) {
            Log.println(priority, tag, string.substring(i, min(string.length, i + LOG_LIMIT)))
        }
    }

    /**
     * logPrintLong with Debug priority
     */
    fun logLongD(tag: String, string: String) {
        logPrintLong(Log.DEBUG, tag, string)
    }

    fun getCurrentUnixTime(): Long {
        return System.currentTimeMillis() / 1000
    }

    suspend fun copy(input: InputStream, output: OutputStream) = withContext(Dispatchers.IO) {
        val BUFFER_SIZE = 1024 * 1024

        val buffer = ByteArray(BUFFER_SIZE)
        var n: Int
        while (true) {
            ensureActive()
            n = input.read(buffer)
            if (n == -1)
                break
            output.write(buffer, 0, n)
        }
    }

//        fun Int.hasFlag(flag: Int): Boolean {
//            return this and flag == flag
//        }

    //https://stackoverflow.com/a/10600736/5701177
    fun drawableToBitmap(drawable: Drawable): Bitmap {
        if (drawable is BitmapDrawable && drawable.bitmap != null)
            return drawable.bitmap

        val bitmap: Bitmap
        if (drawable.intrinsicWidth <= 0 || drawable.intrinsicHeight <= 0) {
            // Single color bitmap will be created of 1x1 pixel
            bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
        } else {
            bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight,
                Bitmap.Config.ARGB_8888)
        }

        val canvas = Canvas(bitmap)
        drawable.setBounds(0, 0, canvas.width, canvas.height)
        drawable.draw(canvas)
        return bitmap
    }

    fun toString(bundle: Bundle?): String {
        if (bundle == null)
            return "null"

        val sb = StringBuilder()
        sb.append("[ ")
        for (key in bundle.keySet()) {
            sb.append("$key = ${bundle.get(key)}, ")
        }
        sb.append(" ]")
        return sb.toString()
    }

    fun toString(e: Throwable?): String {
        if (e == null)
            return "Throwable is null"

        val errorWriter = StringWriter()
        errorWriter.appendLine(e.localizedMessage)
        e.printStackTrace(PrintWriter(errorWriter))

        e.cause?.let { cause ->
            errorWriter.append("Cause: ")
            errorWriter.append(toString(cause))
        }

        return errorWriter.toString()
    }

    /**
     * Wrapper method for external library
     * TODO: minimal CSS color parsing without library?
     */
    fun parseCssColor(color: String): Int {
        return ConvertibleColor.fromCss(color).toRGB().toPackedInt()
    }


    fun colorStateListOf(vararg mapping: Pair<IntArray, Int>): ColorStateList {
        val (states, colors) = mapping.unzip()
        return ColorStateList(states.toTypedArray(), colors.toIntArray())
    }

    fun colorStateListOf(@ColorInt color: Int): ColorStateList {
        return ColorStateList.valueOf(color)
    }

    /**
     * Similar to ContextCompat.getColor, except also aware of light/dark themes
     */
    @ColorInt
    @Suppress("DEPRECATION")
    fun getColor(context: Context, @ColorRes id: Int): Int {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            context.getColor(id)
        } else {
            val nightMode =
                context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
            if (nightMode == Configuration.UI_MODE_NIGHT_YES) {
                when (id) {
                    R.color.colorBackground -> context.resources.getColor(R.color.colorPrimaryDark)
                    R.color.colorForeground -> context.resources.getColor(R.color.colorPrimary)
                }
            } else {
                when (id) {
                    R.color.colorBackground -> context.resources.getColor(R.color.colorPrimary)
                    R.color.colorForeground -> context.resources.getColor(R.color.colorPrimaryDark)
                }
            }
            context.resources.getColor(id)
        }
    }

    fun getIntentForFile(context: Context, file: File, fileProvider: String): Intent {
        return Intent(Intent.ACTION_VIEW).apply {
            data = getIntentUriForFile(context, file, fileProvider)
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
    }

    fun getIntentUriForFile(context: Context, file: File, fileProvider: String): Uri {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
            FileProvider.getUriForFile(context, fileProvider, file)
        else
            Uri.fromFile(file)
    }

    fun getInt(bundle: Bundle, key: String): Int? {
        return if (bundle.containsKey(key))
            bundle.getInt(key)
        else
            null
    }

    fun getLong(bundle: Bundle, key: String): Long? {
        return if (bundle.containsKey(key))
            bundle.getLong(key)
        else
            null
    }

    fun isPackageInstalled(packageName: String, packageManager: PackageManager): Boolean {
        try {
            return packageManager.getApplicationInfo(packageName, 0).enabled
        } catch (e: PackageManager.NameNotFoundException) {
            return false
        }
    }

    fun fitsInInt(l: Long): Boolean {
        return l.toInt().toLong() == l
    }

    /**
     * Check if we're connected to some type of Internet network. Doesn't necessarily mean that
     * the connection is working!
     *
     * https://stackoverflow.com/a/53532456/5701177
     */
    fun isNetworkConnected(context: Context): Boolean {
        val connectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val activeNetwork = connectivityManager.activeNetwork ?: return false
            val networkCapabilities =
                connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false
            return when {
                networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
                networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
                networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
                else -> false
            }
        } else {
            @Suppress("DEPRECATION")
            val networkInfo = connectivityManager.activeNetworkInfo ?: return false

            @Suppress("DEPRECATION")
            return when (networkInfo.type) {
                ConnectivityManager.TYPE_WIFI -> true
                ConnectivityManager.TYPE_MOBILE -> true
                ConnectivityManager.TYPE_ETHERNET -> true
                else -> false
            }
        }
    }

    fun spannedFromHtml(htmlString: String): Spanned {
        if (Build.VERSION.SDK_INT >= 24) {
            return Html.fromHtml(htmlString, 0)
        } else {
            @Suppress("DEPRECATION")
            return Html.fromHtml(htmlString)
        }
    }

    fun asHexCode(@ColorInt color: Int): String {
        // https://stackoverflow.com/a/6540378/5701177
        return String.format("#%06X", 0xFFFFFF and color)
    }

    fun getPreferredLocale(config: Configuration): Locale {
        return if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            return config.locales.get(0)
        } else {
            @Suppress("deprecation")
            return config.locale
        }
    }

    fun getPreferredLocale(context: Context): Locale {
        return getPreferredLocale(context.resources.configuration)
    }

    fun shouldUseLightForeground(@ColorInt bgColor: Int): Boolean {
        return ColorUtils.calculateLuminance(bgColor) < 0.5
    }
}