Add app/src/main/java/space/bloggin/knockpad
This commit is contained in:
@@ -0,0 +1,732 @@
|
|||||||
|
package space.bloggin.knockpad
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.Canvas
|
||||||
|
import android.graphics.DashPathEffect
|
||||||
|
import android.graphics.Matrix
|
||||||
|
import android.graphics.Paint
|
||||||
|
import android.graphics.Path
|
||||||
|
import android.graphics.RectF
|
||||||
|
import android.view.HapticFeedbackConstants
|
||||||
|
import android.view.MotionEvent
|
||||||
|
import android.view.View
|
||||||
|
import kotlin.math.abs
|
||||||
|
import kotlin.math.hypot
|
||||||
|
import kotlin.math.max
|
||||||
|
import kotlin.math.min
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The infinite canvas. World coordinates are stored; the view shows them through scale + offset.
|
||||||
|
* With an S Pen: pen draws, fingers move the page. Without one: one finger draws, two fingers move.
|
||||||
|
*/
|
||||||
|
class InkView(context: Context) : View(context) {
|
||||||
|
|
||||||
|
interface Listener {
|
||||||
|
fun onInkChanged()
|
||||||
|
fun onSelectionChanged(has: Boolean)
|
||||||
|
fun onStylusSeen()
|
||||||
|
}
|
||||||
|
|
||||||
|
var listener: Listener? = null
|
||||||
|
|
||||||
|
var strokes: List<Stroke> = emptyList(); private set
|
||||||
|
var images: List<ImageItem> = emptyList(); private set
|
||||||
|
|
||||||
|
var background = Bg.BLANK
|
||||||
|
set(v) { field = v; cacheDirty = true; invalidate() }
|
||||||
|
var paper = Paper.CREAM
|
||||||
|
set(v) { field = v; cacheDirty = true; invalidate() }
|
||||||
|
var tool = Tool.PEN
|
||||||
|
set(v) { if (v != Tool.LASSO) clearSelection(); field = v; invalidate() }
|
||||||
|
|
||||||
|
var inkColor = 0xFF1B1B1B.toInt()
|
||||||
|
var hiColor = 0xFFFFE14D.toInt()
|
||||||
|
var penWidth = 5f
|
||||||
|
var pencilWidth = 4f
|
||||||
|
var hiWidth = 32f
|
||||||
|
var shapeKind = ShapeKind.CIRCLE
|
||||||
|
var polySides = 6
|
||||||
|
/** 0..1 */
|
||||||
|
var smoothing = 0.5f
|
||||||
|
/** 0 = auto, 1 = finger always draws, 2 = finger always pans */
|
||||||
|
var fingerMode = 0
|
||||||
|
var stylusSeen = false
|
||||||
|
|
||||||
|
private val dens = resources.displayMetrics.density
|
||||||
|
|
||||||
|
// ---- view transform ----
|
||||||
|
var scale = 1f; private set
|
||||||
|
var offX = 0f; private set
|
||||||
|
var offY = 0f; private set
|
||||||
|
private val mtx = Matrix()
|
||||||
|
private val tmpM = Matrix()
|
||||||
|
private fun syncMatrix() { mtx.setScale(scale, scale); mtx.postTranslate(offX, offY) }
|
||||||
|
private fun wx(x: Float) = (x - offX) / scale
|
||||||
|
private fun wy(y: Float) = (y - offY) / scale
|
||||||
|
|
||||||
|
// ---- undo / redo ----
|
||||||
|
private class Snap(val s: List<Stroke>, val i: List<ImageItem>)
|
||||||
|
private val undoStack = ArrayDeque<Snap>()
|
||||||
|
private val redoStack = ArrayDeque<Snap>()
|
||||||
|
|
||||||
|
private fun push() {
|
||||||
|
undoStack.addLast(Snap(strokes, images))
|
||||||
|
if (undoStack.size > 200) undoStack.removeFirst()
|
||||||
|
redoStack.clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun undo(): Boolean {
|
||||||
|
val p = undoStack.removeLastOrNull() ?: return false
|
||||||
|
redoStack.addLast(Snap(strokes, images))
|
||||||
|
strokes = p.s; images = p.i
|
||||||
|
clearSelection(); changed()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun redo(): Boolean {
|
||||||
|
val p = redoStack.removeLastOrNull() ?: return false
|
||||||
|
undoStack.addLast(Snap(strokes, images))
|
||||||
|
strokes = p.s; images = p.i
|
||||||
|
clearSelection(); changed()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun changed() {
|
||||||
|
cacheDirty = true
|
||||||
|
invalidate()
|
||||||
|
listener?.onInkChanged()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setContent(s: List<Stroke>, i: List<ImageItem>) {
|
||||||
|
strokes = s; images = i
|
||||||
|
undoStack.clear(); redoStack.clear()
|
||||||
|
cacheDirty = true
|
||||||
|
needStart = true
|
||||||
|
invalidate()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- selection ----
|
||||||
|
private var selS: Set<Stroke> = emptySet()
|
||||||
|
private var selI: Set<ImageItem> = emptySet()
|
||||||
|
val hasSelection get() = selS.isNotEmpty() || selI.isNotEmpty()
|
||||||
|
|
||||||
|
private fun setSel(s: Set<Stroke>, i: Set<ImageItem>) {
|
||||||
|
val had = hasSelection
|
||||||
|
selS = s; selI = i
|
||||||
|
if (had || hasSelection) listener?.onSelectionChanged(hasSelection)
|
||||||
|
invalidate()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clearSelection() { if (hasSelection) setSel(emptySet(), emptySet()) }
|
||||||
|
|
||||||
|
private fun selBounds(): RectF? {
|
||||||
|
var r: RectF? = null
|
||||||
|
for (s in strokes) if (s in selS) { if (r == null) r = RectF(s.bounds) else r.union(s.bounds) }
|
||||||
|
for (im in images) if (im in selI) { if (r == null) r = im.rect else r.union(im.rect) }
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
fun selectedStrokes(): List<Stroke> = strokes.filter { it in selS }
|
||||||
|
|
||||||
|
fun deleteSelection() {
|
||||||
|
if (!hasSelection) return
|
||||||
|
push()
|
||||||
|
strokes = strokes.filter { it !in selS }
|
||||||
|
images = images.filter { it !in selI }
|
||||||
|
setSel(emptySet(), emptySet())
|
||||||
|
changed()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun copySelection() {
|
||||||
|
if (!hasSelection) return
|
||||||
|
push()
|
||||||
|
val d = 28f
|
||||||
|
val ns = selectedStrokes().map { it.translated(d, d) }
|
||||||
|
val ni = images.filter { it in selI }.map { it.translated(d, d) }
|
||||||
|
strokes = strokes + ns
|
||||||
|
images = images + ni
|
||||||
|
setSel(ns.toHashSet(), ni.toHashSet())
|
||||||
|
changed()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun recolorSelection(c: Int) {
|
||||||
|
if (selS.isEmpty()) return
|
||||||
|
push()
|
||||||
|
mapSel({ it.recolored(c) }, { it })
|
||||||
|
}
|
||||||
|
|
||||||
|
fun scaleSelection(f: Float) {
|
||||||
|
val b = selBounds() ?: return
|
||||||
|
push()
|
||||||
|
mapSel({ it.scaled(b.centerX(), b.centerY(), f) }, { it.scaled(b.centerX(), b.centerY(), f) })
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun mapSel(fs: (Stroke) -> Stroke, fi: (ImageItem) -> ImageItem) {
|
||||||
|
val newS = HashSet<Stroke>()
|
||||||
|
val newI = HashSet<ImageItem>()
|
||||||
|
strokes = strokes.map { old -> if (old in selS) fs(old).also { newS.add(it) } else old }
|
||||||
|
images = images.map { old -> if (old in selI) fi(old).also { newI.add(it) } else old }
|
||||||
|
setSel(newS, newI)
|
||||||
|
changed()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun addImage(bmp: Bitmap, data: ByteArray) {
|
||||||
|
val maxW = (width * 0.6f) / scale
|
||||||
|
val w = min(bmp.width.toFloat(), maxW)
|
||||||
|
val h = w * bmp.height / bmp.width
|
||||||
|
val cx = wx(width / 2f); val cy = wy(height / 2f)
|
||||||
|
val item = ImageItem(bmp, data, cx - w / 2f, cy - h / 2f, w, h)
|
||||||
|
push()
|
||||||
|
images = images + item
|
||||||
|
changed()
|
||||||
|
tool = Tool.LASSO
|
||||||
|
setSel(emptySet(), hashSetOf(item))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- view placement ----
|
||||||
|
private var needStart = true
|
||||||
|
|
||||||
|
/** Shows the top-left of the writing at 100%. */
|
||||||
|
fun goToStart() {
|
||||||
|
scale = 1f
|
||||||
|
val b = Ink.contentBounds(strokes, images)
|
||||||
|
if (b == null) { offX = 0f; offY = 0f } else {
|
||||||
|
offX = 24f * dens - b.left
|
||||||
|
offY = 24f * dens - b.top
|
||||||
|
}
|
||||||
|
cacheDirty = true; invalidate()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Zooms out until all the writing fits. */
|
||||||
|
fun fitAll() {
|
||||||
|
val b = Ink.contentBounds(strokes, images) ?: return goToStart()
|
||||||
|
val m = 24f * dens
|
||||||
|
scale = min((width - 2 * m) / max(b.width(), 1f), (height - 2 * m) / max(b.height(), 1f)).coerceIn(0.1f, 2f)
|
||||||
|
offX = (width - b.width() * scale) / 2f - b.left * scale
|
||||||
|
offY = (height - b.height() * scale) / 2f - b.top * scale
|
||||||
|
cacheDirty = true; invalidate()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onSizeChanged(w: Int, h: Int, ow: Int, oh: Int) {
|
||||||
|
super.onSizeChanged(w, h, ow, oh)
|
||||||
|
if (needStart && w > 0) { needStart = false; goToStart() }
|
||||||
|
cacheDirty = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- cache of committed ink ----
|
||||||
|
private var cache: Bitmap? = null
|
||||||
|
private var cacheDirty = true
|
||||||
|
private var cScale = 0f; private var cOffX = 0f; private var cOffY = 0f
|
||||||
|
private var transforming = false
|
||||||
|
private var moving = false
|
||||||
|
private var mvDx = 0f; private var mvDy = 0f
|
||||||
|
|
||||||
|
private fun rebuildCache() {
|
||||||
|
if (width <= 0 || height <= 0) return
|
||||||
|
var b = cache
|
||||||
|
if (b == null || b.width != width || b.height != height) {
|
||||||
|
b?.recycle()
|
||||||
|
b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
|
||||||
|
cache = b
|
||||||
|
}
|
||||||
|
val cv = Canvas(b!!)
|
||||||
|
cv.save()
|
||||||
|
cv.concat(mtx)
|
||||||
|
val vis = RectF(wx(0f), wy(0f), wx(width.toFloat()), wy(height.toFloat()))
|
||||||
|
Ink.renderAll(cv, strokes, images, background, paper, vis, scale,
|
||||||
|
if (moving) selS else null, if (moving) selI else null)
|
||||||
|
cv.restore()
|
||||||
|
cScale = scale; cOffX = offX; cOffY = offY
|
||||||
|
cacheDirty = false
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- paints for overlays ----
|
||||||
|
private val selPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||||
|
style = Paint.Style.STROKE; color = 0xFF2C62C9.toInt(); strokeWidth = 1.5f * dens
|
||||||
|
pathEffect = DashPathEffect(floatArrayOf(8f * dens, 5f * dens), 0f)
|
||||||
|
}
|
||||||
|
private val lassoPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||||
|
style = Paint.Style.STROKE; color = 0xFF2C62C9.toInt(); strokeWidth = 1.5f * dens
|
||||||
|
pathEffect = DashPathEffect(floatArrayOf(6f * dens, 4f * dens), 0f)
|
||||||
|
}
|
||||||
|
private val eraserPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||||
|
style = Paint.Style.STROKE; color = 0xFF777777.toInt(); strokeWidth = 1.2f * dens
|
||||||
|
}
|
||||||
|
private val lassoPath = Path()
|
||||||
|
|
||||||
|
override fun onDraw(c: Canvas) {
|
||||||
|
if (width <= 0) return
|
||||||
|
syncMatrix()
|
||||||
|
val cb = cache
|
||||||
|
if (transforming && cb != null && !cacheDirty) {
|
||||||
|
c.drawColor(Ink.paperColor(paper))
|
||||||
|
val r = scale / cScale
|
||||||
|
tmpM.setScale(r, r)
|
||||||
|
tmpM.postTranslate(offX - r * cOffX, offY - r * cOffY)
|
||||||
|
c.drawBitmap(cb, tmpM, null)
|
||||||
|
} else {
|
||||||
|
if (cacheDirty || cb == null || cScale != scale || cOffX != offX || cOffY != offY) rebuildCache()
|
||||||
|
cache?.let { c.drawBitmap(it, 0f, 0f, null) }
|
||||||
|
}
|
||||||
|
|
||||||
|
c.save()
|
||||||
|
c.concat(mtx)
|
||||||
|
if (moving) {
|
||||||
|
for (im in images) if (im in selI) Ink.drawImage(c, im, mvDx, mvDy)
|
||||||
|
for (s in strokes) if (s in selS && s.tool == Tool.HIGHLIGHTER) Ink.drawStroke(c, s, mvDx, mvDy)
|
||||||
|
for (s in strokes) if (s in selS && s.tool != Tool.HIGHLIGHTER) Ink.drawStroke(c, s, mvDx, mvDy)
|
||||||
|
}
|
||||||
|
if (mode == M_DRAW && raw.size >= 3) Ink.drawPts(c, liveTool, liveColor, livePts())
|
||||||
|
if (mode == M_SHAPE) shapePts?.let { Ink.drawPts(c, Tool.PEN, inkColor, it) }
|
||||||
|
c.restore()
|
||||||
|
|
||||||
|
if (mode == M_LASSO && lasso.size >= 4) {
|
||||||
|
lassoPath.reset()
|
||||||
|
lassoPath.moveTo(lasso.a[0] * scale + offX, lasso.a[1] * scale + offY)
|
||||||
|
var i = 2
|
||||||
|
while (i < lasso.size) { lassoPath.lineTo(lasso.a[i] * scale + offX, lasso.a[i + 1] * scale + offY); i += 2 }
|
||||||
|
c.drawPath(lassoPath, lassoPaint)
|
||||||
|
}
|
||||||
|
if (hasSelection) {
|
||||||
|
selBounds()?.let { b ->
|
||||||
|
if (moving) b.offset(mvDx, mvDy)
|
||||||
|
mtx.mapRect(b)
|
||||||
|
b.inset(-6f * dens, -6f * dens)
|
||||||
|
c.drawRect(b, selPaint)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (mode == M_ERASE && eraserShow) c.drawCircle(eraserX, eraserY, eraseRadiusPx(), eraserPaint)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- touch handling ----
|
||||||
|
private val M_NONE = 0; private val M_DRAW = 1; private val M_PAN = 2; private val M_GESTURE = 3
|
||||||
|
private val M_LASSO = 4; private val M_MOVE = 5; private val M_ERASE = 6; private val M_DONE = 7
|
||||||
|
private val M_SHAPE = 8
|
||||||
|
private var mode = M_NONE
|
||||||
|
private var activeId = -1
|
||||||
|
private var activeStylus = false
|
||||||
|
|
||||||
|
private var panLastX = 0f; private var panLastY = 0f
|
||||||
|
private var panStartX = 0f; private var panStartY = 0f
|
||||||
|
private var panStarted = false
|
||||||
|
|
||||||
|
private var gStartDist = 1f; private var gStartScale = 1f
|
||||||
|
private var gWorldX = 0f; private var gWorldY = 0f
|
||||||
|
private var gStartCx = 0f; private var gStartCy = 0f
|
||||||
|
|
||||||
|
private var tapT0 = 0L; private var tapMax = 0; private var tapMoved = false; private var tapEligible = false
|
||||||
|
|
||||||
|
private fun fingerDraws() = when (fingerMode) { 1 -> true; 2 -> false; else -> !stylusSeen }
|
||||||
|
|
||||||
|
override fun onTouchEvent(e: MotionEvent): Boolean {
|
||||||
|
when (e.actionMasked) {
|
||||||
|
MotionEvent.ACTION_DOWN -> {
|
||||||
|
tapT0 = e.eventTime; tapMax = 1; tapMoved = false; tapEligible = true
|
||||||
|
val tt = e.getToolType(0)
|
||||||
|
val stylus = tt == MotionEvent.TOOL_TYPE_STYLUS || tt == MotionEvent.TOOL_TYPE_ERASER
|
||||||
|
if (stylus && !stylusSeen) { stylusSeen = true; listener?.onStylusSeen() }
|
||||||
|
activeId = e.getPointerId(0)
|
||||||
|
activeStylus = stylus
|
||||||
|
if (stylus || fingerDraws()) startAction(e, 0)
|
||||||
|
else {
|
||||||
|
mode = M_PAN
|
||||||
|
panLastX = e.x; panLastY = e.y; panStartX = e.x; panStartY = e.y; panStarted = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
MotionEvent.ACTION_POINTER_DOWN -> {
|
||||||
|
tapMax = max(tapMax, e.pointerCount)
|
||||||
|
val ai = e.actionIndex
|
||||||
|
val tt = e.getToolType(ai)
|
||||||
|
val stylus = tt == MotionEvent.TOOL_TYPE_STYLUS || tt == MotionEvent.TOOL_TYPE_ERASER
|
||||||
|
if (stylus && !(isAction() && activeStylus)) {
|
||||||
|
// Palm was down first: ignore the palm, let the pen write.
|
||||||
|
if (isAction()) cancelAction()
|
||||||
|
endTransform()
|
||||||
|
tapEligible = false
|
||||||
|
if (!stylusSeen) { stylusSeen = true; listener?.onStylusSeen() }
|
||||||
|
activeId = e.getPointerId(ai)
|
||||||
|
activeStylus = true
|
||||||
|
startAction(e, ai)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if (isAction()) {
|
||||||
|
if (activeStylus) return true
|
||||||
|
cancelAction()
|
||||||
|
}
|
||||||
|
if (e.pointerCount >= 2) startGesture(e)
|
||||||
|
}
|
||||||
|
MotionEvent.ACTION_MOVE -> when (mode) {
|
||||||
|
M_DRAW, M_LASSO, M_ERASE, M_MOVE, M_SHAPE -> moveAction(e)
|
||||||
|
M_PAN -> {
|
||||||
|
val dx = e.x - panLastX; val dy = e.y - panLastY
|
||||||
|
if (!panStarted && hypot(e.x - panStartX, e.y - panStartY) > 8f * dens) {
|
||||||
|
panStarted = true; transforming = true; tapMoved = true
|
||||||
|
}
|
||||||
|
if (panStarted) { offX += dx; offY += dy; invalidate() }
|
||||||
|
panLastX = e.x; panLastY = e.y
|
||||||
|
}
|
||||||
|
M_GESTURE -> gesture(e)
|
||||||
|
}
|
||||||
|
MotionEvent.ACTION_POINTER_UP -> {
|
||||||
|
val id = e.getPointerId(e.actionIndex)
|
||||||
|
if (isAction() && id == activeId) { finishAction(); mode = M_DONE }
|
||||||
|
else if (mode == M_GESTURE) { endTransform(); mode = M_DONE }
|
||||||
|
}
|
||||||
|
MotionEvent.ACTION_UP -> {
|
||||||
|
if (isAction()) finishAction()
|
||||||
|
if (mode == M_PAN || mode == M_GESTURE) endTransform()
|
||||||
|
if (tapEligible && !tapMoved && e.eventTime - tapT0 < 300 && tapMax >= 2) {
|
||||||
|
if (tapMax == 2) undo() else redo()
|
||||||
|
}
|
||||||
|
mode = M_NONE
|
||||||
|
invalidate()
|
||||||
|
}
|
||||||
|
MotionEvent.ACTION_CANCEL -> {
|
||||||
|
if (isAction()) cancelAction()
|
||||||
|
endTransform()
|
||||||
|
mode = M_NONE
|
||||||
|
invalidate()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isAction() = mode == M_DRAW || mode == M_LASSO || mode == M_ERASE || mode == M_MOVE || mode == M_SHAPE
|
||||||
|
|
||||||
|
private fun startGesture(e: MotionEvent) {
|
||||||
|
val cx = (e.getX(0) + e.getX(1)) / 2f
|
||||||
|
val cy = (e.getY(0) + e.getY(1)) / 2f
|
||||||
|
gStartDist = max(hypot(e.getX(0) - e.getX(1), e.getY(0) - e.getY(1)), 1f)
|
||||||
|
gStartScale = scale
|
||||||
|
gWorldX = wx(cx); gWorldY = wy(cy)
|
||||||
|
gStartCx = cx; gStartCy = cy
|
||||||
|
mode = M_GESTURE
|
||||||
|
transforming = true
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun gesture(e: MotionEvent) {
|
||||||
|
if (e.pointerCount < 2) return
|
||||||
|
val cx = (e.getX(0) + e.getX(1)) / 2f
|
||||||
|
val cy = (e.getY(0) + e.getY(1)) / 2f
|
||||||
|
val dist = max(hypot(e.getX(0) - e.getX(1), e.getY(0) - e.getY(1)), 1f)
|
||||||
|
scale = (gStartScale * dist / gStartDist).coerceIn(0.1f, 8f)
|
||||||
|
offX = cx - gWorldX * scale
|
||||||
|
offY = cy - gWorldY * scale
|
||||||
|
if (hypot(cx - gStartCx, cy - gStartCy) > 20f * dens || abs(dist - gStartDist) > 20f * dens) tapMoved = true
|
||||||
|
invalidate()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun endTransform() {
|
||||||
|
if (transforming) { transforming = false; invalidate() }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- actions ----
|
||||||
|
/** Raw points as they come in (only sensor noise removed). What you see is the smoothed version. */
|
||||||
|
private val raw = FBuf()
|
||||||
|
private var liveCache: FloatArray? = null
|
||||||
|
private var liveTool = Tool.PEN
|
||||||
|
private var liveColor = 0
|
||||||
|
private var sx = 0f; private var sy = 0f; private var sw = 0f
|
||||||
|
private var lastT = 0L; private var lastRawX = 0f; private var lastRawY = 0f
|
||||||
|
private var rawWX = 0f; private var rawWY = 0f
|
||||||
|
private var snapped = false
|
||||||
|
private var anchorX = 0f; private var anchorY = 0f
|
||||||
|
private val snapRunnable = Runnable { trySnap() }
|
||||||
|
private var snapPts: FloatArray? = null
|
||||||
|
|
||||||
|
private var shapeX0 = 0f; private var shapeY0 = 0f
|
||||||
|
private var shapePts: FloatArray? = null
|
||||||
|
|
||||||
|
private fun livePts(): FloatArray {
|
||||||
|
snapPts?.let { return it }
|
||||||
|
liveCache?.let { return it }
|
||||||
|
val p = if (liveTool == Tool.HIGHLIGHTER) Smooth.process(raw.a, max(smoothing, 0.35f), raw.size / 3)
|
||||||
|
else Smooth.process(raw.a, smoothing, raw.size / 3)
|
||||||
|
liveCache = p
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
private val lasso = FBuf()
|
||||||
|
private var moveStartX = 0f; private var moveStartY = 0f
|
||||||
|
private var erasePixel = false
|
||||||
|
private var erasePushed = false
|
||||||
|
private var eraserX = 0f; private var eraserY = 0f; private var eraserShow = false
|
||||||
|
|
||||||
|
private fun startAction(e: MotionEvent, idx: Int) {
|
||||||
|
val x = e.getX(idx); val y = e.getY(idx)
|
||||||
|
val side = (e.buttonState and MotionEvent.BUTTON_STYLUS_PRIMARY) != 0 ||
|
||||||
|
e.getToolType(idx) == MotionEvent.TOOL_TYPE_ERASER
|
||||||
|
if (side) {
|
||||||
|
mode = M_ERASE; erasePixel = false; erasePushed = false
|
||||||
|
eraseAt(x, y)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
when (tool) {
|
||||||
|
Tool.LASSO -> {
|
||||||
|
val b = selBounds()
|
||||||
|
if (b != null) b.inset(-12f * dens / scale, -12f * dens / scale)
|
||||||
|
if (b != null && b.contains(wx(x), wy(y))) {
|
||||||
|
mode = M_MOVE
|
||||||
|
moveStartX = wx(x); moveStartY = wy(y)
|
||||||
|
mvDx = 0f; mvDy = 0f
|
||||||
|
moving = true; cacheDirty = true
|
||||||
|
invalidate()
|
||||||
|
} else {
|
||||||
|
clearSelection()
|
||||||
|
mode = M_LASSO
|
||||||
|
lasso.clear(); lasso.add(wx(x)); lasso.add(wy(y))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Tool.SHAPE -> {
|
||||||
|
mode = M_SHAPE
|
||||||
|
shapeX0 = wx(x); shapeY0 = wy(y)
|
||||||
|
shapePts = null
|
||||||
|
}
|
||||||
|
Tool.ERASE_STROKE, Tool.ERASE_PIXEL -> {
|
||||||
|
mode = M_ERASE; erasePixel = tool == Tool.ERASE_PIXEL; erasePushed = false
|
||||||
|
eraseAt(x, y)
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
mode = M_DRAW
|
||||||
|
beginStroke(x, y, e.getPressure(idx), e.eventTime)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun moveAction(e: MotionEvent) {
|
||||||
|
val idx = e.findPointerIndex(activeId)
|
||||||
|
if (idx < 0) return
|
||||||
|
for (h in 0 until e.historySize) {
|
||||||
|
handlePoint(e.getHistoricalX(idx, h), e.getHistoricalY(idx, h),
|
||||||
|
e.getHistoricalPressure(idx, h), e.getHistoricalEventTime(h))
|
||||||
|
}
|
||||||
|
handlePoint(e.getX(idx), e.getY(idx), e.getPressure(idx), e.eventTime)
|
||||||
|
invalidate()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handlePoint(x: Float, y: Float, p: Float, t: Long) {
|
||||||
|
when (mode) {
|
||||||
|
M_DRAW -> addStrokePoint(x, y, p, t)
|
||||||
|
M_LASSO -> {
|
||||||
|
val lx = lasso.a[lasso.size - 2]; val ly = lasso.a[lasso.size - 1]
|
||||||
|
if (hypot(wx(x) - lx, wy(y) - ly) * scale > 3f * dens) { lasso.add(wx(x)); lasso.add(wy(y)) }
|
||||||
|
}
|
||||||
|
M_ERASE -> eraseAt(x, y)
|
||||||
|
M_MOVE -> { mvDx = wx(x) - moveStartX; mvDy = wy(y) - moveStartY }
|
||||||
|
M_SHAPE -> shapePts = Shapes.fromDrag(shapeKind, polySides, shapeX0, shapeY0, wx(x), wy(y), penWidth)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun finishAction() {
|
||||||
|
when (mode) {
|
||||||
|
M_DRAW -> endStroke()
|
||||||
|
M_LASSO -> finishLasso()
|
||||||
|
M_ERASE -> { eraserShow = false }
|
||||||
|
M_MOVE -> commitMove()
|
||||||
|
M_SHAPE -> {
|
||||||
|
shapePts?.let { pts ->
|
||||||
|
push()
|
||||||
|
strokes = strokes + Stroke(Tool.PEN, inkColor, pts)
|
||||||
|
changed()
|
||||||
|
}
|
||||||
|
shapePts = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tapEligible = false
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun cancelAction() {
|
||||||
|
removeCallbacks(snapRunnable)
|
||||||
|
when (mode) {
|
||||||
|
M_DRAW -> { raw.clear(); liveCache = null; snapPts = null }
|
||||||
|
M_SHAPE -> shapePts = null
|
||||||
|
M_LASSO -> lasso.clear()
|
||||||
|
M_ERASE -> eraserShow = false
|
||||||
|
M_MOVE -> { moving = false; mvDx = 0f; mvDy = 0f; cacheDirty = true }
|
||||||
|
}
|
||||||
|
mode = M_NONE
|
||||||
|
invalidate()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- drawing a stroke ----
|
||||||
|
private fun widthFor(p: Float, speedPxMs: Float): Float {
|
||||||
|
if (liveTool == Tool.HIGHLIGHTER) return hiWidth
|
||||||
|
val base = if (liveTool == Tool.PENCIL) pencilWidth else penWidth
|
||||||
|
return if (activeStylus) {
|
||||||
|
base * (0.45f + 0.95f * p.coerceIn(0f, 1f))
|
||||||
|
} else {
|
||||||
|
val sp = speedPxMs / dens
|
||||||
|
base * (1.25f - 0.25f * sp).coerceIn(0.6f, 1.25f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun beginStroke(x: Float, y: Float, p: Float, t: Long) {
|
||||||
|
liveTool = tool
|
||||||
|
liveColor = if (tool == Tool.HIGHLIGHTER) hiColor else inkColor
|
||||||
|
raw.clear(); liveCache = null; snapPts = null
|
||||||
|
snapped = false
|
||||||
|
sx = wx(x); sy = wy(y)
|
||||||
|
rawWX = sx; rawWY = sy
|
||||||
|
sw = widthFor(p, 0f)
|
||||||
|
lastT = t; lastRawX = x; lastRawY = y
|
||||||
|
anchorX = x; anchorY = y
|
||||||
|
raw.add(sx); raw.add(sy); raw.add(sw)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun addStrokePoint(x: Float, y: Float, p: Float, t: Long) {
|
||||||
|
if (snapped) return
|
||||||
|
val X = wx(x); val Y = wy(y)
|
||||||
|
rawWX = X; rawWY = Y
|
||||||
|
// Light filter for sensor noise only. The real smoothing happens in Smooth.process.
|
||||||
|
sx += 0.75f * (X - sx); sy += 0.75f * (Y - sy)
|
||||||
|
val dt = max(1L, t - lastT).toFloat()
|
||||||
|
val speed = hypot(x - lastRawX, y - lastRawY) / dt
|
||||||
|
sw += 0.35f * (widthFor(p, speed) - sw)
|
||||||
|
lastT = t; lastRawX = x; lastRawY = y
|
||||||
|
val lx = raw.a[raw.size - 3]; val ly = raw.a[raw.size - 2]
|
||||||
|
if (hypot(sx - lx, sy - ly) * scale >= 0.7f) {
|
||||||
|
raw.add(sx); raw.add(sy); raw.add(sw)
|
||||||
|
liveCache = null
|
||||||
|
}
|
||||||
|
if (hypot(x - anchorX, y - anchorY) > 6f * dens) {
|
||||||
|
anchorX = x; anchorY = y
|
||||||
|
removeCallbacks(snapRunnable)
|
||||||
|
if (raw.size / 3 >= 6) postDelayed(snapRunnable, 600)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun trySnap() {
|
||||||
|
if (mode != M_DRAW || snapped) return
|
||||||
|
val shape = Shapes.fit(livePts(), livePts().size / 3) ?: return
|
||||||
|
snapPts = shape
|
||||||
|
snapped = true
|
||||||
|
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
|
||||||
|
invalidate()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun endStroke() {
|
||||||
|
removeCallbacks(snapRunnable)
|
||||||
|
if (!snapped && raw.size >= 3) {
|
||||||
|
val lx = raw.a[raw.size - 3]; val ly = raw.a[raw.size - 2]
|
||||||
|
if (hypot(rawWX - lx, rawWY - ly) * scale > 0.5f) { raw.add(rawWX); raw.add(rawWY); raw.add(sw); liveCache = null }
|
||||||
|
}
|
||||||
|
val pts = if (raw.size == 0) null else livePts()
|
||||||
|
raw.clear(); liveCache = null; snapPts = null
|
||||||
|
if (pts == null || pts.isEmpty()) return
|
||||||
|
push()
|
||||||
|
strokes = strokes + Stroke(liveTool, liveColor, pts)
|
||||||
|
changed()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- lasso ----
|
||||||
|
private fun finishLasso() {
|
||||||
|
val n = lasso.size / 2
|
||||||
|
if (n < 3) { lasso.clear(); return }
|
||||||
|
val poly = lasso.toArray()
|
||||||
|
lasso.clear()
|
||||||
|
val ss = HashSet<Stroke>()
|
||||||
|
for (s in strokes) {
|
||||||
|
var inside = 0
|
||||||
|
val total = s.n
|
||||||
|
for (i in 0 until total) if (inPoly(s.pts[i * 3], s.pts[i * 3 + 1], poly)) inside++
|
||||||
|
if (total > 0 && inside * 2 >= total) ss.add(s)
|
||||||
|
}
|
||||||
|
val ii = HashSet<ImageItem>()
|
||||||
|
for (im in images) if (inPoly(im.x + im.w / 2f, im.y + im.h / 2f, poly)) ii.add(im)
|
||||||
|
setSel(ss, ii)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun inPoly(x: Float, y: Float, p: FloatArray): Boolean {
|
||||||
|
var inside = false
|
||||||
|
val n = p.size / 2
|
||||||
|
var j = n - 1
|
||||||
|
for (i in 0 until n) {
|
||||||
|
val xi = p[i * 2]; val yi = p[i * 2 + 1]; val xj = p[j * 2]; val yj = p[j * 2 + 1]
|
||||||
|
if ((yi > y) != (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi) inside = !inside
|
||||||
|
j = i
|
||||||
|
}
|
||||||
|
return inside
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun commitMove() {
|
||||||
|
moving = false
|
||||||
|
val dx = mvDx; val dy = mvDy
|
||||||
|
mvDx = 0f; mvDy = 0f
|
||||||
|
if (abs(dx) > 0.5f || abs(dy) > 0.5f) {
|
||||||
|
push()
|
||||||
|
mapSel({ it.translated(dx, dy) }, { it.translated(dx, dy) })
|
||||||
|
} else {
|
||||||
|
cacheDirty = true; invalidate()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- erasers ----
|
||||||
|
private fun eraseRadiusPx() = (if (erasePixel) 14f else 10f) * dens
|
||||||
|
|
||||||
|
private fun eraseAt(x: Float, y: Float) {
|
||||||
|
eraserX = x; eraserY = y; eraserShow = true
|
||||||
|
val r = eraseRadiusPx() / scale
|
||||||
|
val X = wx(x); val Y = wy(y)
|
||||||
|
if (!erasePixel) {
|
||||||
|
val keep = strokes.filter { !hits(it, X, Y, r) }
|
||||||
|
if (keep.size != strokes.size) {
|
||||||
|
if (!erasePushed) { push(); erasePushed = true }
|
||||||
|
strokes = keep
|
||||||
|
changed()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
var any = false
|
||||||
|
val out = ArrayList<Stroke>(strokes.size + 4)
|
||||||
|
for (s in strokes) {
|
||||||
|
if (!hits(s, X, Y, r)) { out.add(s); continue }
|
||||||
|
any = true
|
||||||
|
out.addAll(split(s, X, Y, r))
|
||||||
|
}
|
||||||
|
if (any) {
|
||||||
|
if (!erasePushed) { push(); erasePushed = true }
|
||||||
|
strokes = out
|
||||||
|
changed()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
invalidate()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hits(s: Stroke, X: Float, Y: Float, r: Float): Boolean {
|
||||||
|
val b = s.bounds
|
||||||
|
if (X < b.left - r || X > b.right + r || Y < b.top - r || Y > b.bottom + r) return false
|
||||||
|
val a = s.pts
|
||||||
|
val n = s.n
|
||||||
|
if (n == 1) return hypot(a[0] - X, a[1] - Y) <= r + a[2] / 2f
|
||||||
|
for (i in 1 until n) {
|
||||||
|
val d = segDist(X, Y, a[(i - 1) * 3], a[(i - 1) * 3 + 1], a[i * 3], a[i * 3 + 1])
|
||||||
|
if (d <= r + a[i * 3 + 2] / 2f) return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun split(s: Stroke, X: Float, Y: Float, r: Float): List<Stroke> {
|
||||||
|
val out = ArrayList<Stroke>()
|
||||||
|
val run = FBuf()
|
||||||
|
val a = s.pts
|
||||||
|
fun flush() {
|
||||||
|
if (run.size >= 6) out.add(Stroke(s.tool, s.color, run.toArray()))
|
||||||
|
run.clear()
|
||||||
|
}
|
||||||
|
for (i in 0 until s.n) {
|
||||||
|
val gone = hypot(a[i * 3] - X, a[i * 3 + 1] - Y) <= r + a[i * 3 + 2] * 0.25f
|
||||||
|
if (gone) flush() else { run.add(a[i * 3]); run.add(a[i * 3 + 1]); run.add(a[i * 3 + 2]) }
|
||||||
|
}
|
||||||
|
flush()
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun segDist(px: Float, py: Float, ax: Float, ay: Float, bx: Float, by: Float): Float {
|
||||||
|
val vx = bx - ax; val vy = by - ay
|
||||||
|
val l2 = vx * vx + vy * vy
|
||||||
|
if (l2 == 0f) return hypot(px - ax, py - ay)
|
||||||
|
val t = (((px - ax) * vx + (py - ay) * vy) / l2).coerceIn(0f, 1f)
|
||||||
|
return hypot(px - (ax + t * vx), py - (ay + t * vy))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,292 @@
|
|||||||
|
package space.bloggin.knockpad
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.app.AlertDialog
|
||||||
|
import android.content.Intent
|
||||||
|
import android.graphics.BitmapFactory
|
||||||
|
import android.graphics.Typeface
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.text.Editable
|
||||||
|
import android.text.TextWatcher
|
||||||
|
import android.view.Gravity
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.widget.AdapterView
|
||||||
|
import android.widget.BaseAdapter
|
||||||
|
import android.widget.EditText
|
||||||
|
import android.widget.HorizontalScrollView
|
||||||
|
import android.widget.ImageView
|
||||||
|
import android.widget.LinearLayout
|
||||||
|
import android.widget.ListView
|
||||||
|
import android.widget.TextView
|
||||||
|
import java.text.SimpleDateFormat
|
||||||
|
import java.util.Date
|
||||||
|
import java.util.Locale
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
|
class MainActivity : Activity() {
|
||||||
|
|
||||||
|
private lateinit var store: NoteStore
|
||||||
|
private lateinit var search: EditText
|
||||||
|
private lateinit var folderRow: LinearLayout
|
||||||
|
private lateinit var list: ListView
|
||||||
|
private lateinit var empty: TextView
|
||||||
|
private val adapter = NotesAdapter()
|
||||||
|
|
||||||
|
/** null = all notes, "" = unfiled, otherwise a folder name */
|
||||||
|
private var folder: String? = null
|
||||||
|
private var shown: List<NoteMeta> = emptyList()
|
||||||
|
private val thumbs = HashMap<String, android.graphics.Bitmap?>()
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
store = NoteStore(this)
|
||||||
|
buildUi()
|
||||||
|
handleIntent(intent)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onNewIntent(intent: Intent) {
|
||||||
|
super.onNewIntent(intent)
|
||||||
|
handleIntent(intent)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onResume() {
|
||||||
|
super.onResume()
|
||||||
|
thumbs.clear()
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun buildUi() {
|
||||||
|
val root = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; setBackgroundColor(Ui.CHROME) }
|
||||||
|
|
||||||
|
val bar = LinearLayout(this).apply {
|
||||||
|
orientation = LinearLayout.HORIZONTAL
|
||||||
|
gravity = Gravity.CENTER_VERTICAL
|
||||||
|
setPadding(Ui.dpi(context, 16f), Ui.dpi(context, 6f), Ui.dpi(context, 6f), Ui.dpi(context, 2f))
|
||||||
|
}
|
||||||
|
bar.addView(TextView(this).apply {
|
||||||
|
text = "KnockPad"; textSize = 22f; setTextColor(Ui.INK); typeface = Ui.MEDIUM
|
||||||
|
}, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f))
|
||||||
|
bar.addView(Ui.iconBtn(this, Icon.OPEN, "Open a KnockPad file") { openFile() })
|
||||||
|
bar.addView(Ui.iconBtn(this, Icon.PLUS, "New note") { newNote() })
|
||||||
|
root.addView(bar)
|
||||||
|
|
||||||
|
val searchBox = LinearLayout(this).apply {
|
||||||
|
orientation = LinearLayout.HORIZONTAL
|
||||||
|
gravity = Gravity.CENTER_VERTICAL
|
||||||
|
setBackgroundColor(Ui.FIELD)
|
||||||
|
setPadding(Ui.dpi(context, 10f), 0, Ui.dpi(context, 6f), 0)
|
||||||
|
}
|
||||||
|
searchBox.addView(ImageView(this).apply { setImageDrawable(Icon(Icon.SEARCH, Ui.SUB)) },
|
||||||
|
LinearLayout.LayoutParams(Ui.dpi(this, 20f), Ui.dpi(this, 20f)))
|
||||||
|
search = EditText(this).apply {
|
||||||
|
hint = "Search titles, text and handwriting"
|
||||||
|
textSize = 15f
|
||||||
|
isSingleLine = true
|
||||||
|
background = null
|
||||||
|
setTextColor(Ui.INK)
|
||||||
|
val p = Ui.dpi(context, 10f); setPadding(p, p, p, p)
|
||||||
|
addTextChangedListener(object : TextWatcher {
|
||||||
|
override fun beforeTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {}
|
||||||
|
override fun onTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {}
|
||||||
|
override fun afterTextChanged(s: Editable?) { refresh() }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
searchBox.addView(search, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f))
|
||||||
|
root.addView(searchBox, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply {
|
||||||
|
val m = Ui.dpi(this@MainActivity, 14f); setMargins(m, Ui.dpi(this@MainActivity, 6f), m, Ui.dpi(this@MainActivity, 4f))
|
||||||
|
})
|
||||||
|
|
||||||
|
folderRow = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL; setPadding(Ui.dpi(context, 6f), 0, Ui.dpi(context, 8f), 0) }
|
||||||
|
root.addView(HorizontalScrollView(this).apply { isHorizontalScrollBarEnabled = false; addView(folderRow) })
|
||||||
|
root.addView(Ui.hDivider(this))
|
||||||
|
|
||||||
|
empty = TextView(this).apply {
|
||||||
|
text = "No notes yet."
|
||||||
|
textSize = 15f; setTextColor(Ui.SUB); gravity = Gravity.CENTER
|
||||||
|
setPadding(0, Ui.dpi(context, 48f), 0, 0)
|
||||||
|
visibility = View.GONE
|
||||||
|
}
|
||||||
|
root.addView(empty)
|
||||||
|
|
||||||
|
list = ListView(this).apply {
|
||||||
|
adapter = this@MainActivity.adapter
|
||||||
|
divider = android.graphics.drawable.ColorDrawable(0xFFEEEEEE.toInt())
|
||||||
|
dividerHeight = Ui.dpi(context, 1f).coerceAtLeast(1)
|
||||||
|
onItemClickListener = AdapterView.OnItemClickListener { _, _, pos, _ -> open(shown[pos].id) }
|
||||||
|
onItemLongClickListener = AdapterView.OnItemLongClickListener { _, _, pos, _ -> noteMenu(shown[pos]); true }
|
||||||
|
}
|
||||||
|
root.addView(list, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f))
|
||||||
|
Ui.setupWindow(this, root)
|
||||||
|
setContentView(root)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun refresh() {
|
||||||
|
val q = search.text.toString().trim().lowercase()
|
||||||
|
val all = store.list()
|
||||||
|
shown = all.filter { m ->
|
||||||
|
(folder == null || m.folder == folder) &&
|
||||||
|
(q.isEmpty() || m.title.lowercase().contains(q) || m.text.lowercase().contains(q) || m.search.lowercase().contains(q))
|
||||||
|
}
|
||||||
|
adapter.notifyDataSetChanged()
|
||||||
|
empty.visibility = if (shown.isEmpty()) View.VISIBLE else View.GONE
|
||||||
|
empty.text = if (all.isEmpty()) "No notes yet. Tap + to start one." else "Nothing matches."
|
||||||
|
|
||||||
|
folderRow.removeAllViews()
|
||||||
|
fun fb(label: String, f: String?) {
|
||||||
|
val b = Ui.textBtn(this, label) { folder = f; refresh() }
|
||||||
|
if (folder == f) Ui.setActive(b, true) else b.setTextColor(Ui.SUB)
|
||||||
|
folderRow.addView(b)
|
||||||
|
}
|
||||||
|
fb("All", null)
|
||||||
|
fb("Unfiled", "")
|
||||||
|
for (f in store.folders()) fb(f, f)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun newNote() {
|
||||||
|
val n = Note.blank(UUID.randomUUID().toString(), defaultTitle(), folder ?: "")
|
||||||
|
store.save(n, Exporter.thumbnail(n))
|
||||||
|
open(n.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun open(id: String) {
|
||||||
|
startActivity(Intent(this, EditorActivity::class.java).putExtra("id", id))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun noteMenu(m: NoteMeta) {
|
||||||
|
AlertDialog.Builder(this).setTitle(m.title)
|
||||||
|
.setItems(arrayOf("Rename", "Move to folder", "Send KnockPad file", "Delete")) { _, w ->
|
||||||
|
when (w) {
|
||||||
|
0 -> rename(m)
|
||||||
|
1 -> moveToFolder(m)
|
||||||
|
2 -> store.load(m.id)?.let { n -> Exporter.share(this, Exporter.knock(this, n), "application/octet-stream") }
|
||||||
|
3 -> AlertDialog.Builder(this).setMessage("Delete \"${m.title}\"? This can't be undone.")
|
||||||
|
.setPositiveButton("Delete") { _, _ -> store.delete(m.id); refresh() }
|
||||||
|
.setNegativeButton("Cancel", null).show()
|
||||||
|
}
|
||||||
|
}.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun editNote(id: String, change: (Note) -> Unit) {
|
||||||
|
val n = store.load(id) ?: return
|
||||||
|
change(n)
|
||||||
|
store.save(n, null)
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun textDialog(title: String, start: String, done: (String) -> Unit) {
|
||||||
|
val e = EditText(this).apply { setText(start); setSelection(text.length); isSingleLine = true }
|
||||||
|
val box = LinearLayout(this).apply { val p = Ui.dpi(context, 20f); setPadding(p, p / 2, p, 0); addView(e, LinearLayout.LayoutParams(-1, -2)) }
|
||||||
|
AlertDialog.Builder(this).setTitle(title).setView(box)
|
||||||
|
.setPositiveButton("OK") { _, _ -> e.text.toString().trim().let { if (it.isNotEmpty()) done(it) } }
|
||||||
|
.setNegativeButton("Cancel", null).show()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun rename(m: NoteMeta) = textDialog("Rename", m.title) { t -> editNote(m.id) { it.title = t } }
|
||||||
|
|
||||||
|
private fun moveToFolder(m: NoteMeta) {
|
||||||
|
val folders = store.folders()
|
||||||
|
val items = arrayOf("Unfiled") + folders.toTypedArray() + arrayOf("New folder...")
|
||||||
|
AlertDialog.Builder(this).setTitle("Move to folder").setItems(items) { _, w ->
|
||||||
|
when {
|
||||||
|
w == 0 -> editNote(m.id) { it.folder = "" }
|
||||||
|
w == items.size - 1 -> textDialog("New folder", "") { f -> editNote(m.id) { it.folder = f } }
|
||||||
|
else -> editNote(m.id) { it.folder = folders[w - 1] }
|
||||||
|
}
|
||||||
|
}.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------- importing .knock files ----------------
|
||||||
|
private fun openFile() {
|
||||||
|
val i = Intent(Intent.ACTION_OPEN_DOCUMENT).apply { addCategory(Intent.CATEGORY_OPENABLE); type = "*/*" }
|
||||||
|
startActivityForResult(i, REQ_OPEN)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Deprecated("Deprecated in Java")
|
||||||
|
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||||
|
super.onActivityResult(requestCode, resultCode, data)
|
||||||
|
if (requestCode == REQ_OPEN && resultCode == RESULT_OK) data?.data?.let { importUri(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleIntent(i: Intent?) {
|
||||||
|
if (i?.action == Intent.ACTION_VIEW) i.data?.let { importUri(it) }
|
||||||
|
i?.action = null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun importUri(uri: Uri) {
|
||||||
|
val n = try {
|
||||||
|
val txt = contentResolver.openInputStream(uri)!!.bufferedReader().use { it.readText() }
|
||||||
|
NoteIO.fromJson(txt)
|
||||||
|
} catch (_: Exception) {
|
||||||
|
Ui.toast(this, "That isn't a KnockPad file")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (store.exists(n.id)) {
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setMessage("You already have \"${n.title}\". Replace it with this copy?")
|
||||||
|
.setPositiveButton("Replace") { _, _ -> saveImported(n) }
|
||||||
|
.setNeutralButton("Keep both") { _, _ ->
|
||||||
|
n.id = UUID.randomUUID().toString(); n.title = n.title + " (copy)"; saveImported(n)
|
||||||
|
}
|
||||||
|
.setNegativeButton("Cancel", null).show()
|
||||||
|
} else saveImported(n)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun saveImported(n: Note) {
|
||||||
|
store.save(n, Exporter.thumbnail(n))
|
||||||
|
thumbs.remove(n.id)
|
||||||
|
refresh()
|
||||||
|
open(n.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------- list rows ----------------
|
||||||
|
private val dateFmt = SimpleDateFormat("MMM d, yyyy h:mm a", Locale.US)
|
||||||
|
|
||||||
|
inner class NotesAdapter : BaseAdapter() {
|
||||||
|
override fun getCount() = shown.size
|
||||||
|
override fun getItem(p: Int) = shown[p]
|
||||||
|
override fun getItemId(p: Int) = p.toLong()
|
||||||
|
|
||||||
|
override fun getView(pos: Int, convert: View?, parent: ViewGroup?): View {
|
||||||
|
val c = this@MainActivity
|
||||||
|
val row = (convert as? LinearLayout) ?: LinearLayout(c).apply {
|
||||||
|
orientation = LinearLayout.HORIZONTAL
|
||||||
|
gravity = Gravity.CENTER_VERTICAL
|
||||||
|
val p = Ui.dpi(c, 12f); setPadding(Ui.dpi(c, 14f), p, p, p)
|
||||||
|
background = Ui.flat(Ui.CHROME)
|
||||||
|
addView(ImageView(c).apply {
|
||||||
|
scaleType = ImageView.ScaleType.CENTER_CROP
|
||||||
|
setBackgroundColor(0xFFDDDDDD.toInt())
|
||||||
|
val q = Ui.dpi(c, 1f).coerceAtLeast(1); setPadding(q, q, q, q)
|
||||||
|
}, LinearLayout.LayoutParams(Ui.dpi(c, 104f), Ui.dpi(c, 70f)))
|
||||||
|
addView(LinearLayout(c).apply {
|
||||||
|
orientation = LinearLayout.VERTICAL
|
||||||
|
setPadding(Ui.dpi(c, 14f), 0, 0, 0)
|
||||||
|
addView(TextView(c).apply { textSize = 16f; setTextColor(Ui.INK); typeface = Ui.MEDIUM; isSingleLine = true; ellipsize = android.text.TextUtils.TruncateAt.END })
|
||||||
|
addView(TextView(c).apply { textSize = 13f; setTextColor(Ui.SUB); isSingleLine = true; setPadding(0, Ui.dpi(c, 2f), 0, Ui.dpi(c, 2f)) })
|
||||||
|
addView(TextView(c).apply { textSize = 13f; setTextColor(0xFF4A4A4A.toInt()); maxLines = 2; ellipsize = android.text.TextUtils.TruncateAt.END })
|
||||||
|
}, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f))
|
||||||
|
}
|
||||||
|
val m = shown[pos]
|
||||||
|
val img = row.getChildAt(0) as ImageView
|
||||||
|
val col = row.getChildAt(1) as LinearLayout
|
||||||
|
val bmp = thumbs.getOrPut(m.id) {
|
||||||
|
val f = store.thumb(m.id)
|
||||||
|
if (f.exists()) BitmapFactory.decodeFile(f.path) else null
|
||||||
|
}
|
||||||
|
img.setImageBitmap(bmp)
|
||||||
|
(col.getChildAt(0) as TextView).text = m.title
|
||||||
|
(col.getChildAt(1) as TextView).text =
|
||||||
|
(if (m.folder.isNotBlank()) m.folder + " · " else "") + dateFmt.format(Date(m.modified))
|
||||||
|
val snippet = m.text.ifBlank { m.search }.replace('\n', ' ').trim()
|
||||||
|
(col.getChildAt(2) as TextView).apply { text = snippet; visibility = if (snippet.isEmpty()) View.GONE else View.VISIBLE }
|
||||||
|
return row
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val REQ_OPEN = 3
|
||||||
|
fun defaultTitle(): String = "Note " + SimpleDateFormat("MMM d h:mm a", Locale.US).format(Date())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
package space.bloggin.knockpad
|
||||||
|
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.BitmapFactory
|
||||||
|
import android.graphics.RectF
|
||||||
|
import android.util.Base64
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.nio.ByteBuffer
|
||||||
|
import java.nio.ByteOrder
|
||||||
|
|
||||||
|
object Tool {
|
||||||
|
const val PEN = 0
|
||||||
|
const val PENCIL = 1
|
||||||
|
const val HIGHLIGHTER = 2
|
||||||
|
const val ERASE_STROKE = 3
|
||||||
|
const val ERASE_PIXEL = 4
|
||||||
|
const val LASSO = 5
|
||||||
|
const val SHAPE = 6
|
||||||
|
}
|
||||||
|
|
||||||
|
object Paper {
|
||||||
|
const val CREAM = 0
|
||||||
|
const val WHITE = 1
|
||||||
|
const val GRAY = 2
|
||||||
|
const val VELLUM = 3
|
||||||
|
val names = arrayOf("Cream", "White", "Light gray", "Vellum")
|
||||||
|
}
|
||||||
|
|
||||||
|
object ShapeKind {
|
||||||
|
const val CIRCLE = 0
|
||||||
|
const val SQUARE = 1
|
||||||
|
const val POLYGON = 2
|
||||||
|
}
|
||||||
|
|
||||||
|
object Bg {
|
||||||
|
const val BLANK = 0
|
||||||
|
const val LINED = 1
|
||||||
|
const val GRID = 2
|
||||||
|
const val DOTS = 3
|
||||||
|
val names = arrayOf("Blank", "Lined", "Grid", "Dot grid")
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One ink stroke. pts holds x, y, width triples in world units. Never mutated after creation. */
|
||||||
|
class Stroke(val tool: Int, val color: Int, val pts: FloatArray) {
|
||||||
|
val n: Int get() = pts.size / 3
|
||||||
|
val bounds = RectF()
|
||||||
|
|
||||||
|
init {
|
||||||
|
if (pts.isEmpty()) {
|
||||||
|
bounds.set(0f, 0f, 0f, 0f)
|
||||||
|
} else {
|
||||||
|
var l = Float.MAX_VALUE; var t = Float.MAX_VALUE
|
||||||
|
var r = -Float.MAX_VALUE; var b = -Float.MAX_VALUE
|
||||||
|
var mw = 0f
|
||||||
|
var i = 0
|
||||||
|
while (i < pts.size) {
|
||||||
|
val x = pts[i]; val y = pts[i + 1]; val w = pts[i + 2]
|
||||||
|
if (x < l) l = x
|
||||||
|
if (x > r) r = x
|
||||||
|
if (y < t) t = y
|
||||||
|
if (y > b) b = y
|
||||||
|
if (w > mw) mw = w
|
||||||
|
i += 3
|
||||||
|
}
|
||||||
|
val pad = mw / 2f + 1f
|
||||||
|
bounds.set(l - pad, t - pad, r + pad, b + pad)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun translated(dx: Float, dy: Float) = Stroke(tool, color, FloatArray(pts.size) { i ->
|
||||||
|
when (i % 3) { 0 -> pts[i] + dx; 1 -> pts[i] + dy; else -> pts[i] }
|
||||||
|
})
|
||||||
|
|
||||||
|
fun scaled(cx: Float, cy: Float, f: Float) = Stroke(tool, color, FloatArray(pts.size) { i ->
|
||||||
|
when (i % 3) { 0 -> cx + (pts[i] - cx) * f; 1 -> cy + (pts[i] - cy) * f; else -> pts[i] * f }
|
||||||
|
})
|
||||||
|
|
||||||
|
fun recolored(c: Int) = Stroke(tool, c, pts)
|
||||||
|
}
|
||||||
|
|
||||||
|
class ImageItem(val bitmap: Bitmap, val data: ByteArray, val x: Float, val y: Float, val w: Float, val h: Float) {
|
||||||
|
val rect: RectF get() = RectF(x, y, x + w, y + h)
|
||||||
|
fun translated(dx: Float, dy: Float) = ImageItem(bitmap, data, x + dx, y + dy, w, h)
|
||||||
|
fun scaled(cx: Float, cy: Float, f: Float) =
|
||||||
|
ImageItem(bitmap, data, cx + (x - cx) * f, cy + (y - cy) * f, w * f, h * f)
|
||||||
|
}
|
||||||
|
|
||||||
|
class Note(
|
||||||
|
var id: String,
|
||||||
|
var title: String,
|
||||||
|
var folder: String = "",
|
||||||
|
var created: Long,
|
||||||
|
var modified: Long,
|
||||||
|
var background: Int = Bg.BLANK,
|
||||||
|
var paper: Int = Paper.CREAM,
|
||||||
|
var text: String = "",
|
||||||
|
var search: String = "",
|
||||||
|
var strokes: List<Stroke> = emptyList(),
|
||||||
|
var images: List<ImageItem> = emptyList()
|
||||||
|
) {
|
||||||
|
companion object {
|
||||||
|
fun blank(id: String, title: String, folder: String = ""): Note {
|
||||||
|
val t = System.currentTimeMillis()
|
||||||
|
return Note(id, title, folder, t, t)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reads and writes the .knock file format (JSON, ink packed as base64 floats). */
|
||||||
|
object NoteIO {
|
||||||
|
private fun f2b(a: FloatArray): String {
|
||||||
|
val bb = ByteBuffer.allocate(a.size * 4).order(ByteOrder.LITTLE_ENDIAN)
|
||||||
|
bb.asFloatBuffer().put(a)
|
||||||
|
return Base64.encodeToString(bb.array(), Base64.NO_WRAP)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun b2f(s: String): FloatArray {
|
||||||
|
val bytes = Base64.decode(s, Base64.DEFAULT)
|
||||||
|
val fb = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer()
|
||||||
|
val a = FloatArray(fb.remaining())
|
||||||
|
fb.get(a)
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
|
||||||
|
fun toJson(n: Note): String {
|
||||||
|
val o = JSONObject()
|
||||||
|
o.put("format", "knockpad")
|
||||||
|
o.put("version", 1)
|
||||||
|
o.put("id", n.id)
|
||||||
|
o.put("title", n.title)
|
||||||
|
o.put("folder", n.folder)
|
||||||
|
o.put("created", n.created)
|
||||||
|
o.put("modified", n.modified)
|
||||||
|
o.put("background", n.background)
|
||||||
|
o.put("paper", n.paper)
|
||||||
|
o.put("text", n.text)
|
||||||
|
o.put("search", n.search)
|
||||||
|
val sa = JSONArray()
|
||||||
|
for (s in n.strokes) {
|
||||||
|
sa.put(JSONObject().put("t", s.tool).put("c", s.color).put("p", f2b(s.pts)))
|
||||||
|
}
|
||||||
|
o.put("strokes", sa)
|
||||||
|
val ia = JSONArray()
|
||||||
|
for (im in n.images) {
|
||||||
|
ia.put(
|
||||||
|
JSONObject().put("x", im.x.toDouble()).put("y", im.y.toDouble())
|
||||||
|
.put("w", im.w.toDouble()).put("h", im.h.toDouble())
|
||||||
|
.put("d", Base64.encodeToString(im.data, Base64.NO_WRAP))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
o.put("images", ia)
|
||||||
|
return o.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun fromJson(str: String): Note {
|
||||||
|
val o = JSONObject(str)
|
||||||
|
require(o.optString("format") == "knockpad") { "Not a KnockPad file" }
|
||||||
|
val strokes = ArrayList<Stroke>()
|
||||||
|
val sa = o.optJSONArray("strokes") ?: JSONArray()
|
||||||
|
for (i in 0 until sa.length()) {
|
||||||
|
val so = sa.getJSONObject(i)
|
||||||
|
val pts = b2f(so.getString("p"))
|
||||||
|
if (pts.size >= 3) strokes.add(Stroke(so.getInt("t"), so.getInt("c"), pts))
|
||||||
|
}
|
||||||
|
val images = ArrayList<ImageItem>()
|
||||||
|
val ia = o.optJSONArray("images") ?: JSONArray()
|
||||||
|
for (i in 0 until ia.length()) {
|
||||||
|
val io = ia.getJSONObject(i)
|
||||||
|
val data = Base64.decode(io.getString("d"), Base64.DEFAULT)
|
||||||
|
val bmp = BitmapFactory.decodeByteArray(data, 0, data.size) ?: continue
|
||||||
|
images.add(
|
||||||
|
ImageItem(
|
||||||
|
bmp, data, io.getDouble("x").toFloat(), io.getDouble("y").toFloat(),
|
||||||
|
io.getDouble("w").toFloat(), io.getDouble("h").toFloat()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return Note(
|
||||||
|
id = o.getString("id"),
|
||||||
|
title = o.optString("title", "Untitled"),
|
||||||
|
folder = o.optString("folder", ""),
|
||||||
|
created = o.optLong("created", System.currentTimeMillis()),
|
||||||
|
modified = o.optLong("modified", System.currentTimeMillis()),
|
||||||
|
background = o.optInt("background", Bg.BLANK),
|
||||||
|
paper = o.optInt("paper", Paper.CREAM),
|
||||||
|
text = o.optString("text", ""),
|
||||||
|
search = o.optString("search", ""),
|
||||||
|
strokes = strokes,
|
||||||
|
images = images
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Small growable float list for the stroke being drawn. */
|
||||||
|
class FBuf {
|
||||||
|
var a = FloatArray(512)
|
||||||
|
var size = 0
|
||||||
|
fun add(v: Float) {
|
||||||
|
if (size == a.size) a = a.copyOf(a.size * 2)
|
||||||
|
a[size++] = v
|
||||||
|
}
|
||||||
|
fun clear() { size = 0 }
|
||||||
|
fun toArray(): FloatArray = a.copyOf(size)
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package space.bloggin.knockpad
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
class NoteMeta(
|
||||||
|
val id: String,
|
||||||
|
val title: String,
|
||||||
|
val folder: String,
|
||||||
|
val modified: Long,
|
||||||
|
val text: String,
|
||||||
|
val search: String
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Notes live in the app's private storage: <id>.knock, <id>.meta and <id>.png (thumbnail). */
|
||||||
|
class NoteStore(context: Context) {
|
||||||
|
private val dir = File(context.filesDir, "notes").apply { mkdirs() }
|
||||||
|
|
||||||
|
private fun knock(id: String) = File(dir, "$id.knock")
|
||||||
|
private fun meta(id: String) = File(dir, "$id.meta")
|
||||||
|
fun thumb(id: String) = File(dir, "$id.png")
|
||||||
|
|
||||||
|
private fun writeAtomic(f: File, text: String) {
|
||||||
|
val tmp = File(f.parentFile, f.name + ".tmp")
|
||||||
|
tmp.writeText(text)
|
||||||
|
if (!tmp.renameTo(f)) {
|
||||||
|
f.delete()
|
||||||
|
tmp.renameTo(f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun exists(id: String) = knock(id).exists()
|
||||||
|
|
||||||
|
fun list(): List<NoteMeta> {
|
||||||
|
val out = ArrayList<NoteMeta>()
|
||||||
|
dir.listFiles()?.filter { it.name.endsWith(".meta") }?.forEach { f ->
|
||||||
|
try {
|
||||||
|
val o = JSONObject(f.readText())
|
||||||
|
out.add(
|
||||||
|
NoteMeta(
|
||||||
|
o.getString("id"), o.optString("title"), o.optString("folder"),
|
||||||
|
o.optLong("modified"), o.optString("text"), o.optString("search")
|
||||||
|
)
|
||||||
|
)
|
||||||
|
} catch (_: Exception) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out.sortedByDescending { it.modified }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun load(id: String): Note? = try {
|
||||||
|
NoteIO.fromJson(knock(id).readText())
|
||||||
|
} catch (_: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun readRaw(id: String): String? = try { knock(id).readText() } catch (_: Exception) { null }
|
||||||
|
|
||||||
|
fun save(n: Note, thumbnail: Bitmap?) {
|
||||||
|
writeAtomic(knock(n.id), NoteIO.toJson(n))
|
||||||
|
writeMeta(n.id, n.title, n.folder, n.modified, n.text, n.search)
|
||||||
|
if (thumbnail != null) {
|
||||||
|
thumb(n.id).outputStream().use { thumbnail.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun writeMeta(id: String, title: String, folder: String, modified: Long, text: String, search: String) {
|
||||||
|
val o = JSONObject()
|
||||||
|
.put("id", id).put("title", title).put("folder", folder)
|
||||||
|
.put("modified", modified).put("text", text).put("search", search)
|
||||||
|
writeAtomic(meta(id), o.toString())
|
||||||
|
}
|
||||||
|
|
||||||
|
fun updateSearch(id: String, search: String) {
|
||||||
|
val m = list().firstOrNull { it.id == id } ?: return
|
||||||
|
writeMeta(id, m.title, m.folder, m.modified, m.text, search)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun delete(id: String) {
|
||||||
|
knock(id).delete(); meta(id).delete(); thumb(id).delete()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun folders(): List<String> = list().map { it.folder }.filter { it.isNotBlank() }.distinct().sorted()
|
||||||
|
}
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
package space.bloggin.knockpad
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.graphics.Typeface
|
||||||
|
import android.graphics.drawable.ColorDrawable
|
||||||
|
import android.graphics.drawable.Drawable
|
||||||
|
import android.graphics.drawable.GradientDrawable
|
||||||
|
import android.graphics.drawable.LayerDrawable
|
||||||
|
import android.graphics.drawable.StateListDrawable
|
||||||
|
import android.view.Gravity
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.view.WindowInsetsController
|
||||||
|
import android.widget.ImageView
|
||||||
|
import android.widget.LinearLayout
|
||||||
|
import android.widget.TextView
|
||||||
|
import android.widget.Toast
|
||||||
|
|
||||||
|
/** Neutral, flat styling. White chrome, gray dividers, square everything. */
|
||||||
|
object Ui {
|
||||||
|
const val CHROME = 0xFFFFFFFF.toInt()
|
||||||
|
const val DIVIDER = 0xFFDEDEDE.toInt()
|
||||||
|
const val PRESSED = 0xFFEBEBEB.toInt()
|
||||||
|
const val ACTIVE = 0xFFE2E2E2.toInt()
|
||||||
|
const val INK = 0xFF1C1C1C.toInt()
|
||||||
|
const val SUB = 0xFF757575.toInt()
|
||||||
|
const val FIELD = 0xFFF2F2F2.toInt()
|
||||||
|
const val ACCENT = 0xFF1C1C1C.toInt()
|
||||||
|
|
||||||
|
val MEDIUM: Typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
|
||||||
|
|
||||||
|
val INK_COLORS = intArrayOf(
|
||||||
|
0xFF1B1B1B.toInt(), 0xFF1A4FB5.toInt(), 0xFFB3261E.toInt(), 0xFF1E7B34.toInt(),
|
||||||
|
0xFF6A3D9A.toInt(), 0xFF7A4A1E.toInt(), 0xFF6B6B6B.toInt(), 0xFFD2691E.toInt()
|
||||||
|
)
|
||||||
|
val HI_COLORS = intArrayOf(
|
||||||
|
0xFFFFE14D.toInt(), 0xFF8BE38B.toInt(), 0xFFFF9ECF.toInt(), 0xFF8ECBFF.toInt(), 0xFFFFB866.toInt()
|
||||||
|
)
|
||||||
|
|
||||||
|
fun dp(c: Context, v: Float) = v * c.resources.displayMetrics.density
|
||||||
|
fun dpi(c: Context, v: Float) = dp(c, v).toInt()
|
||||||
|
|
||||||
|
/** Flat background that darkens slightly when pressed. */
|
||||||
|
fun flat(fill: Int = Color.TRANSPARENT): Drawable = StateListDrawable().apply {
|
||||||
|
addState(intArrayOf(android.R.attr.state_pressed), ColorDrawable(PRESSED))
|
||||||
|
addState(intArrayOf(), ColorDrawable(fill))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Active tool: light gray square with a dark bar along the bottom. */
|
||||||
|
private fun activeBg(c: Context): Drawable {
|
||||||
|
val bar = dpi(c, 2f)
|
||||||
|
val ld = LayerDrawable(arrayOf(ColorDrawable(ACTIVE), ColorDrawable(INK)))
|
||||||
|
ld.setLayerGravity(1, Gravity.BOTTOM or Gravity.FILL_HORIZONTAL)
|
||||||
|
ld.setLayerHeight(1, bar)
|
||||||
|
return ld
|
||||||
|
}
|
||||||
|
|
||||||
|
fun iconBtn(c: Context, kind: Int, label: String, click: (View) -> Unit): ImageView = ImageView(c).apply {
|
||||||
|
setImageDrawable(Icon(kind, INK))
|
||||||
|
val p = dpi(c, 10f)
|
||||||
|
setPadding(p, p, p, p)
|
||||||
|
background = flat()
|
||||||
|
contentDescription = label
|
||||||
|
tooltipText = label
|
||||||
|
isClickable = true
|
||||||
|
setOnClickListener(click)
|
||||||
|
layoutParams = LinearLayout.LayoutParams(dpi(c, 46f), dpi(c, 46f))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setActive(v: View, on: Boolean) {
|
||||||
|
v.background = if (on) activeBg(v.context) else flat()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Text-only button for bars and dialogs-in-layout. */
|
||||||
|
fun textBtn(c: Context, label: String, click: (View) -> Unit): TextView = TextView(c).apply {
|
||||||
|
text = label
|
||||||
|
textSize = 14f
|
||||||
|
typeface = MEDIUM
|
||||||
|
setTextColor(INK)
|
||||||
|
gravity = Gravity.CENTER
|
||||||
|
val h = dpi(c, 14f)
|
||||||
|
setPadding(h, 0, h, 0)
|
||||||
|
background = flat()
|
||||||
|
isClickable = true
|
||||||
|
setOnClickListener(click)
|
||||||
|
layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, dpi(c, 44f))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun vDivider(c: Context): View = View(c).apply {
|
||||||
|
setBackgroundColor(DIVIDER)
|
||||||
|
layoutParams = LinearLayout.LayoutParams(dpi(c, 1f).coerceAtLeast(1), dpi(c, 26f)).apply {
|
||||||
|
val m = dpi(c, 6f); setMargins(m, 0, m, 0); gravity = Gravity.CENTER_VERTICAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun hDivider(c: Context): View = View(c).apply {
|
||||||
|
setBackgroundColor(DIVIDER)
|
||||||
|
layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dpi(c, 1f).coerceAtLeast(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun swatch(c: Context, color: Int, sizeDp: Float): Drawable = GradientDrawable().apply {
|
||||||
|
setColor(color)
|
||||||
|
setStroke(dpi(c, 1f).coerceAtLeast(1), 0x33000000)
|
||||||
|
cornerRadius = 0f
|
||||||
|
val s = dpi(c, sizeDp)
|
||||||
|
setBounds(0, 0, s, s)
|
||||||
|
setSize(s, s)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun toast(c: Context, msg: String) = Toast.makeText(c, msg, Toast.LENGTH_LONG).show()
|
||||||
|
|
||||||
|
/** White status and nav bars with dark icons, and keep content clear of bars and keyboard. */
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
fun setupWindow(a: Activity, root: View) {
|
||||||
|
a.window.decorView.setBackgroundColor(CHROME)
|
||||||
|
if (android.os.Build.VERSION.SDK_INT >= 30) {
|
||||||
|
a.window.insetsController?.setSystemBarsAppearance(
|
||||||
|
WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS or WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS,
|
||||||
|
WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS or WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
a.window.decorView.systemUiVisibility =
|
||||||
|
View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
|
||||||
|
}
|
||||||
|
root.setOnApplyWindowInsetsListener { v, ins ->
|
||||||
|
if (android.os.Build.VERSION.SDK_INT >= 30) {
|
||||||
|
val b = ins.getInsets(android.view.WindowInsets.Type.systemBars() or android.view.WindowInsets.Type.ime())
|
||||||
|
v.setPadding(b.left, b.top, b.right, b.bottom)
|
||||||
|
} else {
|
||||||
|
v.setPadding(ins.systemWindowInsetLeft, ins.systemWindowInsetTop, ins.systemWindowInsetRight, ins.systemWindowInsetBottom)
|
||||||
|
}
|
||||||
|
ins
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user