aboutsummaryrefslogtreecommitdiff
path: root/library/src/main/kotlin/ca/allanwang/kau/dialogs/color/ColorPickerDialog.kt
blob: f78cde0e50a4463241187ed3a206f17e5c5664e4 (plain)
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package ca.allanwang.kau.dialogs.color

import android.content.Context
import android.graphics.Color
import android.support.annotation.ColorInt
import android.support.v4.content.res.ResourcesCompat
import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.*
import ca.allanwang.kau.R
import ca.allanwang.kau.logging.SL
import ca.allanwang.kau.utils.*
import com.afollestad.materialdialogs.DialogAction
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.Theme
import com.afollestad.materialdialogs.color.CircleView
import com.afollestad.materialdialogs.color.FillGridView
import java.util.*

/**
 * Created by Allan Wang on 2017-06-08.
 */
internal class ColorPickerView @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ScrollView(context, attrs, defStyleAttr) {
    var selectedColor: Int = -1
    var isInSub: Boolean = false
    var isInCustom: Boolean = false
    var circleSize: Int = context.dimen(R.dimen.kau_color_circle_size).toInt()
    lateinit var dialog: MaterialDialog
    lateinit var builder: Builder
    lateinit var colorsTop: IntArray
    var colorsSub: Array<IntArray>? = null
    var topIndex: Int = -1
    var subIndex: Int = -1
    var colorIndex: Int
        get() = if (isInSub) subIndex else topIndex
        set(value) {
            if (isInSub) subIndex = value
            else {
                topIndex = value
                if (colorsSub != null && colorsSub!!.size > value) {
                    dialog.setActionButton(DialogAction.NEGATIVE, builder.backText)
                    isInSub = true
                }
            }
        }


    val gridView: FillGridView by bindView(R.id.md_grid)
    val customFrame: LinearLayout by bindView(R.id.md_colorChooserCustomFrame)
    val customColorIndicator: View by bindView(R.id.md_colorIndicator)
    val hexInput: EditText by bindView(R.id.md_hexInput)
    val alphaLabel: TextView by bindView(R.id.md_colorALabel)
    val alphaSeekbar: SeekBar by bindView(R.id.md_colorA)
    val alphaValue: TextView by bindView(R.id.md_colorAValue)
    val redSeekbar: SeekBar by bindView(R.id.md_colorR)
    val redValue: TextView by bindView(R.id.md_colorRValue)
    val greenSeekbar: SeekBar by bindView(R.id.md_colorG)
    val greenValue: TextView by bindView(R.id.md_colorGValue)
    val blueSeekbar: SeekBar by bindView(R.id.md_colorB)
    val blueValue: TextView by bindView(R.id.md_colorBValue)

    var customHexTextWatcher: TextWatcher? = null
    var customRgbListener: SeekBar.OnSeekBarChangeListener? = null

    init {
        View.inflate(context, R.layout.md_dialog_colorchooser, this)
    }

    fun bind(builder: Builder, dialog: MaterialDialog) {
        this.builder = builder
        this.dialog = dialog
        this.colorsTop = builder.colorsTop()
        this.colorsSub = builder.colorsSub()
        this.selectedColor = builder.defaultColor
        if (builder.allowCustom) {
            if (!builder.allowCustomAlpha) {
                alphaLabel.gone()
                alphaSeekbar.gone()
                alphaValue.gone()
                hexInput.hint = String.format("%06X", selectedColor)
                hexInput.filters = arrayOf(InputFilter.LengthFilter(6))
            } else {
                hexInput.hint = String.format("%08X", selectedColor)
                hexInput.filters = arrayOf(InputFilter.LengthFilter(8))
            }
        }
        if (findColor(builder.defaultColor)) isInCustom = true //when toggled this will be false
        toggleCustom()
    }

    fun backOrCancel() {
        if (isInSub) {
            dialog.setActionButton(DialogAction.NEGATIVE, builder.cancelText)
            //to top
            isInSub = false
            subIndex = -1
            invalidateGrid()
        } else {
            dialog.cancel()
        }
    }

    fun toggleCustom() {
        isInCustom = !isInCustom
        if (isInCustom) {
            isInSub = false
            dialog.setActionButton(DialogAction.NEUTRAL, builder.presetText)
            dialog.setActionButton(DialogAction.NEGATIVE, builder.cancelText)
            customHexTextWatcher = object : TextWatcher {
                override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

                override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                    try {
                        selectedColor = Color.parseColor("#" + s.toString())
                    } catch (e: IllegalArgumentException) {
                        selectedColor = Color.BLACK
                    }

                    customColorIndicator.setBackgroundColor(selectedColor)
                    if (alphaSeekbar.isVisible()) {
                        val alpha = Color.alpha(selectedColor)
                        alphaSeekbar.progress = alpha
                        alphaValue.text = String.format(Locale.CANADA, "%d", alpha)
                    }
                    redSeekbar.progress = Color.red(selectedColor)
                    greenSeekbar.progress = Color.green(selectedColor)
                    blueSeekbar.progress = Color.blue(selectedColor)
                    isInSub = false
                    topIndex = -1
                    subIndex = -1
                    refreshColors()
                }

                override fun afterTextChanged(s: Editable?) {}
            }
            hexInput.setText(selectedColor.toHexString(builder.allowCustomAlpha, false))
            hexInput.addTextChangedListener(customHexTextWatcher)
            customRgbListener = object : SeekBar.OnSeekBarChangeListener {
                override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                    SL.d("Progress $progress")
                    if (fromUser) {
                        val color = if (builder.allowCustomAlpha)
                            Color.argb(alphaSeekbar.progress,
                                    redSeekbar.progress,
                                    greenSeekbar.progress,
                                    blueSeekbar.progress)
                        else Color.rgb(redSeekbar.progress,
                                greenSeekbar.progress,
                                blueSeekbar.progress)

                        hexInput.setText(color.toHexString(builder.allowCustomAlpha, false))
                    }
                    if (builder.allowCustomAlpha) alphaValue.text = alphaSeekbar.progress.toString()
                    redValue.text = redSeekbar.progress.toString()
                    greenValue.text = greenSeekbar.progress.toString()
                    blueValue.text = blueSeekbar.progress.toString()
                }

                override fun onStartTrackingTouch(seekBar: SeekBar) {}

                override fun onStopTrackingTouch(seekBar: SeekBar) {}
            }
            redSeekbar.setOnSeekBarChangeListener(customRgbListener)
            greenSeekbar.setOnSeekBarChangeListener(customRgbListener)
            blueSeekbar.setOnSeekBarChangeListener(customRgbListener)
            if (alphaSeekbar.isVisible())
                alphaSeekbar.setOnSeekBarChangeListener(customRgbListener)
            hexInput.setText(selectedColor.toHexString(alphaSeekbar.isVisible(), false))
            gridView.fadeOut(onFinish = { gridView.gone() })
            customFrame.fadeIn()
        } else {
            findColor(selectedColor)
            dialog.setActionButton(DialogAction.NEUTRAL, builder.customText)
            dialog.setActionButton(DialogAction.NEGATIVE, if (isInSub) builder.backText else builder.cancelText)
            gridView.fadeIn(onStart = { invalidateGrid() })
            customFrame.fadeOut(onFinish = { customFrame.gone() })
            hexInput.removeTextChangedListener(customHexTextWatcher)
            customHexTextWatcher = null
            alphaSeekbar.setOnSeekBarChangeListener(null)
            redSeekbar.setOnSeekBarChangeListener(null)
            greenSeekbar.setOnSeekBarChangeListener(null)
            blueSeekbar.setOnSeekBarChangeListener(null)
            customRgbListener = null
        }
    }

    fun refreshColors() {
        if (!isInCustom) findColor(selectedColor)
        if (builder.dynamicButtonColors) {
            dialog.getActionButton(DialogAction.POSITIVE).setTextColor(selectedColor)
            dialog.getActionButton(DialogAction.NEGATIVE).setTextColor(selectedColor)
            dialog.getActionButton(DialogAction.NEUTRAL).setTextColor(selectedColor)
        }
        if (!builder.allowCustom || !isInCustom) return
        // Once we get close to white or transparent,
        // the action buttons and seekbars will be a very light gray.
        // TODO change by dialog theme
        val visibleColor = if (Color.alpha(selectedColor) < 64 ||
                Color.red(selectedColor) > 247 && Color.green(selectedColor) > 247 && Color.blue(selectedColor) > 247)
            "#DEDEDE".toColor() else selectedColor

        if (builder.allowCustomAlpha)
            alphaSeekbar.visible().tint(visibleColor)
        redSeekbar.tint(visibleColor)
        greenSeekbar.tint(visibleColor)
        blueSeekbar.tint(visibleColor)
        hexInput.tint(visibleColor)
    }

    fun findColor(@ColorInt color: Int): Boolean {
        topIndex = -1
        subIndex = -1
        colorsTop.forEachIndexed {
            index, topColor ->
            if (findSubColor(color, index)) {
                topIndex = index
                return true
            }
            if (topColor == color) { // If no sub colors exists and top color matches
                topIndex = index
                return true
            }
        }
        return false
    }

    fun findSubColor(@ColorInt color: Int, topIndex: Int): Boolean {
        if (colorsSub == null || colorsSub!!.size <= topIndex) return false
        colorsSub!![topIndex].forEachIndexed {
            index, subColor ->
            if (subColor == color) {
                subIndex = index
                return true
            }
        }
        return false
    }

    fun invalidateGrid() {
        if (gridView.adapter == null) {
            gridView.adapter = ColorGridAdapter()
            gridView.selector = ResourcesCompat.getDrawable(resources, R.drawable.kau_transparent, null)
        } else {
            (gridView.adapter as BaseAdapter).notifyDataSetChanged()
        }
    }

    inner class ColorGridAdapter : BaseAdapter(), OnClickListener, OnLongClickListener {
        override fun onClick(v: View) {
            if (v.tag != null && v.tag is String) {
                val tags = (v.tag as String).split(":")
                colorIndex = tags[0].toInt()
                selectedColor = tags[1].toInt()
                refreshColors()
                invalidateGrid()
            }
        }

        override fun onLongClick(v: View): Boolean {
            if (v.tag != null && v.tag is String) {
                val tag = (v.tag as String).split(":")
                val color = tag[1].toInt()
                (v as CircleView).showHint(color)
                return true
            }
            return false
        }

        override fun getItem(position: Int): Any = if (isInSub) colorsSub!![topIndex][position] else colorsTop[position]

        override fun getCount(): Int = if (isInSub) colorsSub!![topIndex].size else colorsTop.size

        override fun getItemId(position: Int): Long = position.toLong()

        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
            val view: CircleView = if (convertView == null)
                CircleView(context).apply { layoutParams = AbsListView.LayoutParams(circleSize, circleSize) }
            else
                convertView as CircleView
            val color: Int = if (isInSub) colorsSub!![topIndex][position] else colorsTop[position]
            return view.apply {
                setBackgroundColor(color)
                isSelected = (if (isInSub) subIndex else topIndex) == position
                tag = "$position:$color"
                setOnClickListener(this@ColorGridAdapter)
                setOnLongClickListener(this@ColorGridAdapter)
            }
        }

    }
}

class Builder {
    var title: String? = null
    var titleRes: Int = -1
    var allowCustom: Boolean = true
    var allowCustomAlpha: Boolean = false
    var isAccent: Boolean = false
    var defaultColor: Int = Color.BLACK
    var doneText: Int = R.string.kau_done
    var backText: Int = R.string.kau_back
    var cancelText: Int = R.string.kau_cancel
    var presetText: Int = R.string.kau_md_presets
    var customText: Int = R.string.kau_md_custom
        get() = if (allowCustom) field else 0
    var dynamicButtonColors: Boolean = true
    var circleSizeRes: Int = R.dimen.kau_color_circle_size
    var colorCallbacks: MutableList<((selectedColor: Int) -> Unit)> = mutableListOf()
    var colorsTop: IntArray? = null
    internal fun colorsTop(): IntArray =
            if (colorsTop != null) colorsTop!!
            else if (isAccent) ColorPalette.ACCENT_COLORS
            else ColorPalette.PRIMARY_COLORS

    var colorsSub: Array<IntArray>? = null
    internal fun colorsSub(): Array<IntArray>? =
            if (colorsTop != null) colorsSub
            else if (isAccent) ColorPalette.ACCENT_COLORS_SUB
            else ColorPalette.PRIMARY_COLORS_SUB

    var theme: Theme? = null

}


fun Context.colorPickerDialog(action: Builder.() -> Unit): MaterialDialog {
    val b = Builder()
    b.action()
    val view = ColorPickerView(this)
    val dialog = with(MaterialDialog.Builder(this)) {
        title(string(b.titleRes, b.title) ?: string(R.string.kau_md_color_palette))
        customView(view, false)
        autoDismiss(false)
        positiveText(b.doneText)
        negativeText(b.cancelText)
        neutralText(b.presetText)
        onPositive { dialog, _ -> b.colorCallbacks.forEach { it.invoke(view.selectedColor) }; dialog.dismiss() }
        onNegative { dialog, _ -> view.backOrCancel() }
        if (b.allowCustom) onNeutral { dialog, _ -> view.toggleCustom() }
        showListener { view.refreshColors() }
        if (b.theme != null) theme(b.theme!!)
        build()
    }
    view.bind(b, dialog)
    return dialog
}