Add app/src/main/java/space/bloggin/knockpad
This commit is contained in:
@@ -0,0 +1,528 @@
|
|||||||
|
package space.bloggin.knockpad
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.app.AlertDialog
|
||||||
|
import android.content.ClipData
|
||||||
|
import android.content.ClipboardManager
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.SharedPreferences
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.ImageDecoder
|
||||||
|
import android.graphics.Typeface
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.text.Editable
|
||||||
|
import android.text.TextUtils
|
||||||
|
import android.text.TextWatcher
|
||||||
|
import android.view.Gravity
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.widget.EditText
|
||||||
|
import android.widget.GridLayout
|
||||||
|
import android.widget.HorizontalScrollView
|
||||||
|
import android.widget.ImageView
|
||||||
|
import android.widget.LinearLayout
|
||||||
|
import android.widget.SeekBar
|
||||||
|
import android.widget.TextView
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.io.File
|
||||||
|
import kotlin.math.max
|
||||||
|
import kotlin.math.min
|
||||||
|
|
||||||
|
class EditorActivity : Activity(), InkView.Listener {
|
||||||
|
|
||||||
|
private lateinit var store: NoteStore
|
||||||
|
private lateinit var prefs: SharedPreferences
|
||||||
|
private lateinit var note: Note
|
||||||
|
private lateinit var ink: InkView
|
||||||
|
private lateinit var selBar: View
|
||||||
|
private lateinit var textPanel: LinearLayout
|
||||||
|
private lateinit var textEdit: EditText
|
||||||
|
private lateinit var colorBtn: ImageView
|
||||||
|
private lateinit var titleView: TextView
|
||||||
|
private val toolBtns = HashMap<Int, View>()
|
||||||
|
|
||||||
|
private var dirty = false
|
||||||
|
private var inkDirty = false
|
||||||
|
private var knockFont: Typeface? = null
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
store = NoteStore(this)
|
||||||
|
prefs = getSharedPreferences("knockpad", MODE_PRIVATE)
|
||||||
|
val id = intent.getStringExtra("id")
|
||||||
|
if (id == null) { finish(); return }
|
||||||
|
note = store.load(id) ?: Note.blank(id, MainActivity.defaultTitle())
|
||||||
|
knockFont = try { resources.getFont(R.font.knock_text) } catch (_: Exception) { null }
|
||||||
|
buildUi()
|
||||||
|
|
||||||
|
ink.inkColor = prefs.getInt("inkColor", Ui.INK_COLORS[0])
|
||||||
|
ink.hiColor = prefs.getInt("hiColor", Ui.HI_COLORS[0])
|
||||||
|
ink.penWidth = prefs.getFloat("penW", 5f)
|
||||||
|
ink.pencilWidth = prefs.getFloat("pencilW", 4f)
|
||||||
|
ink.hiWidth = prefs.getFloat("hiW", 32f)
|
||||||
|
ink.smoothing = prefs.getFloat("smooth2", 0.5f)
|
||||||
|
ink.fingerMode = prefs.getInt("fingerMode", 0)
|
||||||
|
ink.stylusSeen = prefs.getBoolean("stylusSeen", false)
|
||||||
|
ink.shapeKind = prefs.getInt("shapeKind", ShapeKind.CIRCLE)
|
||||||
|
ink.polySides = prefs.getInt("polySides", 6)
|
||||||
|
ink.setContent(note.strokes, note.images)
|
||||||
|
ink.background = note.background
|
||||||
|
ink.paper = note.paper
|
||||||
|
ink.listener = this
|
||||||
|
selectTool(prefs.getInt("tool", Tool.PEN).let { if (it == Tool.LASSO || it == Tool.SHAPE) Tool.PEN else it })
|
||||||
|
|
||||||
|
textEdit.setText(note.text)
|
||||||
|
textEdit.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?) { dirty = true }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------- layout ----------------
|
||||||
|
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, 2f), Ui.dpi(context, 2f), Ui.dpi(context, 4f), Ui.dpi(context, 2f))
|
||||||
|
}
|
||||||
|
bar.addView(Ui.iconBtn(this, Icon.BACK, "Back to notes") { finish() })
|
||||||
|
titleView = TextView(this).apply {
|
||||||
|
text = note.title
|
||||||
|
textSize = 16f
|
||||||
|
typeface = Ui.MEDIUM
|
||||||
|
setTextColor(Ui.INK)
|
||||||
|
maxWidth = Ui.dpi(context, 180f)
|
||||||
|
isSingleLine = true
|
||||||
|
ellipsize = TextUtils.TruncateAt.END
|
||||||
|
setPadding(Ui.dpi(context, 4f), 0, Ui.dpi(context, 8f), 0)
|
||||||
|
setOnClickListener { renameDialog() }
|
||||||
|
}
|
||||||
|
bar.addView(titleView)
|
||||||
|
bar.addView(Ui.vDivider(this))
|
||||||
|
|
||||||
|
fun tb(kind: Int, label: String, t: Int) {
|
||||||
|
val b = Ui.iconBtn(this, kind, label) { selectTool(t) }
|
||||||
|
toolBtns[t] = b; bar.addView(b)
|
||||||
|
}
|
||||||
|
tb(Icon.PEN, "Pen", Tool.PEN)
|
||||||
|
tb(Icon.PENCIL, "Pencil", Tool.PENCIL)
|
||||||
|
tb(Icon.MARKER, "Marker", Tool.HIGHLIGHTER)
|
||||||
|
val shapes = Ui.iconBtn(this, Icon.SHAPES, "Shapes") { shapePicker() }
|
||||||
|
toolBtns[Tool.SHAPE] = shapes; bar.addView(shapes)
|
||||||
|
bar.addView(Ui.vDivider(this))
|
||||||
|
tb(Icon.ERASER, "Eraser (whole strokes)", Tool.ERASE_STROKE)
|
||||||
|
tb(Icon.RUB, "Rub out (part of a stroke)", Tool.ERASE_PIXEL)
|
||||||
|
tb(Icon.LASSO, "Lasso", Tool.LASSO)
|
||||||
|
bar.addView(Ui.vDivider(this))
|
||||||
|
colorBtn = ImageView(this).apply {
|
||||||
|
val p = Ui.dpi(context, 13f); setPadding(p, p, p, p)
|
||||||
|
background = Ui.flat()
|
||||||
|
contentDescription = "Color"; tooltipText = "Color"
|
||||||
|
setOnClickListener { colorDialog(false) }
|
||||||
|
layoutParams = LinearLayout.LayoutParams(Ui.dpi(context, 46f), Ui.dpi(context, 46f))
|
||||||
|
}
|
||||||
|
bar.addView(colorBtn)
|
||||||
|
bar.addView(Ui.iconBtn(this, Icon.SIZE, "Thickness") { sizeDialog() })
|
||||||
|
bar.addView(Ui.vDivider(this))
|
||||||
|
bar.addView(Ui.iconBtn(this, Icon.UNDO, "Undo") { ink.undo() })
|
||||||
|
bar.addView(Ui.iconBtn(this, Icon.REDO, "Redo") { ink.redo() })
|
||||||
|
bar.addView(Ui.vDivider(this))
|
||||||
|
bar.addView(Ui.iconBtn(this, Icon.TEXT, "Converted text") { showText(textPanel.visibility != View.VISIBLE) })
|
||||||
|
bar.addView(Ui.iconBtn(this, Icon.PHOTO, "Insert photo") { pickPhoto() })
|
||||||
|
bar.addView(Ui.iconBtn(this, Icon.MORE, "More") { moreMenu() })
|
||||||
|
root.addView(HorizontalScrollView(this).apply {
|
||||||
|
isHorizontalScrollBarEnabled = false
|
||||||
|
addView(bar)
|
||||||
|
}, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
|
||||||
|
root.addView(Ui.hDivider(this))
|
||||||
|
|
||||||
|
// Selection bar
|
||||||
|
val sel = LinearLayout(this).apply {
|
||||||
|
orientation = LinearLayout.HORIZONTAL
|
||||||
|
gravity = Gravity.CENTER_VERTICAL
|
||||||
|
setPadding(Ui.dpi(context, 6f), 0, Ui.dpi(context, 6f), 0)
|
||||||
|
}
|
||||||
|
sel.addView(TextView(this).apply {
|
||||||
|
text = "Selected"; textSize = 13f; setTextColor(Ui.SUB)
|
||||||
|
setPadding(Ui.dpi(context, 8f), 0, Ui.dpi(context, 6f), 0)
|
||||||
|
})
|
||||||
|
sel.addView(Ui.textBtn(this, "To text") { convertSelection() })
|
||||||
|
sel.addView(Ui.textBtn(this, "Copy") { ink.copySelection() })
|
||||||
|
sel.addView(Ui.textBtn(this, "Color") { colorDialog(true) })
|
||||||
|
sel.addView(Ui.textBtn(this, "Bigger") { ink.scaleSelection(1.15f) })
|
||||||
|
sel.addView(Ui.textBtn(this, "Smaller") { ink.scaleSelection(1f / 1.15f) })
|
||||||
|
sel.addView(Ui.textBtn(this, "Delete") { ink.deleteSelection() })
|
||||||
|
sel.addView(Ui.textBtn(this, "Done") { ink.clearSelection() })
|
||||||
|
selBar = LinearLayout(this).apply {
|
||||||
|
orientation = LinearLayout.VERTICAL
|
||||||
|
visibility = View.GONE
|
||||||
|
addView(HorizontalScrollView(context).apply { isHorizontalScrollBarEnabled = false; addView(sel) })
|
||||||
|
addView(Ui.hDivider(context))
|
||||||
|
}
|
||||||
|
root.addView(selBar)
|
||||||
|
|
||||||
|
// Converted text window
|
||||||
|
textPanel = LinearLayout(this).apply {
|
||||||
|
orientation = LinearLayout.VERTICAL
|
||||||
|
setBackgroundColor(Ui.CHROME)
|
||||||
|
visibility = View.GONE
|
||||||
|
}
|
||||||
|
val head = LinearLayout(this).apply {
|
||||||
|
orientation = LinearLayout.HORIZONTAL
|
||||||
|
gravity = Gravity.CENTER_VERTICAL
|
||||||
|
setPadding(Ui.dpi(context, 6f), 0, Ui.dpi(context, 6f), 0)
|
||||||
|
}
|
||||||
|
head.addView(TextView(this).apply {
|
||||||
|
text = "Converted text"; textSize = 13f; setTextColor(Ui.SUB)
|
||||||
|
setPadding(Ui.dpi(context, 8f), 0, 0, 0)
|
||||||
|
}, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f))
|
||||||
|
head.addView(Ui.textBtn(this, "Copy all") {
|
||||||
|
val cm = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
|
||||||
|
cm.setPrimaryClip(ClipData.newPlainText("KnockPad", textEdit.text.toString()))
|
||||||
|
Ui.toast(this, "Copied")
|
||||||
|
})
|
||||||
|
head.addView(Ui.textBtn(this, "Clear") {
|
||||||
|
AlertDialog.Builder(this).setMessage("Clear the converted text? Your handwriting stays.")
|
||||||
|
.setPositiveButton("Clear") { _, _ -> textEdit.setText("") }
|
||||||
|
.setNegativeButton("Cancel", null).show()
|
||||||
|
})
|
||||||
|
head.addView(Ui.textBtn(this, "Hide") { showText(false) })
|
||||||
|
textPanel.addView(head)
|
||||||
|
textEdit = EditText(this).apply {
|
||||||
|
typeface = knockFont ?: Typeface.SANS_SERIF
|
||||||
|
textSize = 18f
|
||||||
|
setTextColor(Ui.INK)
|
||||||
|
gravity = Gravity.TOP or Gravity.START
|
||||||
|
minLines = 3
|
||||||
|
setBackgroundColor(Ui.FIELD)
|
||||||
|
val p = Ui.dpi(context, 14f)
|
||||||
|
setPadding(p, p, p, p)
|
||||||
|
maxHeight = (resources.displayMetrics.heightPixels * 0.33f).toInt()
|
||||||
|
isVerticalScrollBarEnabled = true
|
||||||
|
}
|
||||||
|
textPanel.addView(textEdit, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
|
||||||
|
textPanel.addView(Ui.hDivider(this))
|
||||||
|
root.addView(textPanel, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
|
||||||
|
|
||||||
|
ink = InkView(this)
|
||||||
|
root.addView(ink, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f))
|
||||||
|
Ui.setupWindow(this, root)
|
||||||
|
setContentView(root)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showText(show: Boolean) {
|
||||||
|
textPanel.visibility = if (show) View.VISIBLE else View.GONE
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun selectTool(t: Int) {
|
||||||
|
ink.tool = t
|
||||||
|
toolBtns.forEach { (k, v) -> Ui.setActive(v, k == t) }
|
||||||
|
prefs.edit().putInt("tool", t).apply()
|
||||||
|
updateColorBtn()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateColorBtn() {
|
||||||
|
val c = if (ink.tool == Tool.HIGHLIGHTER) ink.hiColor else ink.inkColor
|
||||||
|
colorBtn.setImageDrawable(Ui.swatch(this, c, 20f))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------- dialogs ----------------
|
||||||
|
private fun shapePicker() {
|
||||||
|
val items = arrayOf("Circle", "Square", "Triangle", "Pentagon", "Hexagon", "Octagon", "Other number of sides")
|
||||||
|
AlertDialog.Builder(this).setTitle("Shape (drag corner to corner)").setItems(items) { _, w ->
|
||||||
|
fun use(kind: Int, sides: Int = ink.polySides) {
|
||||||
|
ink.shapeKind = kind; ink.polySides = sides
|
||||||
|
prefs.edit().putInt("shapeKind", kind).putInt("polySides", sides).apply()
|
||||||
|
selectTool(Tool.SHAPE)
|
||||||
|
}
|
||||||
|
when (w) {
|
||||||
|
0 -> use(ShapeKind.CIRCLE)
|
||||||
|
1 -> use(ShapeKind.SQUARE)
|
||||||
|
2 -> use(ShapeKind.POLYGON, 3)
|
||||||
|
3 -> use(ShapeKind.POLYGON, 5)
|
||||||
|
4 -> use(ShapeKind.POLYGON, 6)
|
||||||
|
5 -> use(ShapeKind.POLYGON, 8)
|
||||||
|
6 -> sliderDialog("Number of sides", 3f, 12f, ink.polySides.toFloat(), { "${it.toInt()} sides" }, steps = 9) {
|
||||||
|
use(ShapeKind.POLYGON, it.toInt())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun colorDialog(forSelection: Boolean) {
|
||||||
|
val hi = !forSelection && ink.tool == Tool.HIGHLIGHTER
|
||||||
|
val colors = if (hi) Ui.HI_COLORS else Ui.INK_COLORS
|
||||||
|
val grid = GridLayout(this).apply {
|
||||||
|
columnCount = 4
|
||||||
|
val p = Ui.dpi(context, 14f); setPadding(p, p, p, p)
|
||||||
|
}
|
||||||
|
var dlg: AlertDialog? = null
|
||||||
|
for (c in colors) {
|
||||||
|
val v = View(this).apply {
|
||||||
|
background = Ui.swatch(context, c, 48f)
|
||||||
|
setOnClickListener {
|
||||||
|
if (forSelection) ink.recolorSelection(c)
|
||||||
|
else if (hi) { ink.hiColor = c; prefs.edit().putInt("hiColor", c).apply() }
|
||||||
|
else { ink.inkColor = c; prefs.edit().putInt("inkColor", c).apply() }
|
||||||
|
updateColorBtn()
|
||||||
|
dlg?.dismiss()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val s = Ui.dpi(this, 52f)
|
||||||
|
grid.addView(v, GridLayout.LayoutParams().apply {
|
||||||
|
width = s; height = s; val m = Ui.dpi(this@EditorActivity, 6f); setMargins(m, m, m, m)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
dlg = AlertDialog.Builder(this).setTitle(if (hi) "Marker color" else "Ink color").setView(grid).show()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sliderDialog(
|
||||||
|
title: String, min: Float, max: Float, cur: Float, fmt: (Float) -> String,
|
||||||
|
steps: Int = 100, set: (Float) -> Unit
|
||||||
|
) {
|
||||||
|
val box = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; val p = Ui.dpi(context, 22f); setPadding(p, p, p, 0) }
|
||||||
|
val label = TextView(this).apply { textSize = 16f; setTextColor(Ui.INK); text = fmt(cur) }
|
||||||
|
val bar = SeekBar(this).apply {
|
||||||
|
this.max = steps
|
||||||
|
progress = (((cur - min) / (max - min)) * steps).toInt()
|
||||||
|
setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
|
||||||
|
override fun onProgressChanged(s: SeekBar?, p: Int, f: Boolean) { label.text = fmt(min + (max - min) * p / steps) }
|
||||||
|
override fun onStartTrackingTouch(s: SeekBar?) {}
|
||||||
|
override fun onStopTrackingTouch(s: SeekBar?) {}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
box.addView(label); box.addView(bar)
|
||||||
|
AlertDialog.Builder(this).setTitle(title).setView(box)
|
||||||
|
.setPositiveButton("Set") { _, _ -> set(min + (max - min) * bar.progress / steps) }
|
||||||
|
.setNegativeButton("Cancel", null).show()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Thickness for whichever tool is in hand. Shapes use the pen thickness. */
|
||||||
|
private fun sizeDialog() {
|
||||||
|
when (ink.tool) {
|
||||||
|
Tool.PENCIL -> sliderDialog("Pencil thickness", 1f, 14f, ink.pencilWidth, { "%.1f".format(it) }) {
|
||||||
|
ink.pencilWidth = it; prefs.edit().putFloat("pencilW", it).apply()
|
||||||
|
}
|
||||||
|
Tool.HIGHLIGHTER -> sliderDialog("Marker thickness", 10f, 80f, ink.hiWidth, { "%.0f".format(it) }) {
|
||||||
|
ink.hiWidth = it; prefs.edit().putFloat("hiW", it).apply()
|
||||||
|
}
|
||||||
|
else -> sliderDialog("Pen thickness", 1.5f, 20f, ink.penWidth, { "%.1f".format(it) }) {
|
||||||
|
ink.penWidth = it; prefs.edit().putFloat("penW", it).apply()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun moreMenu() {
|
||||||
|
val items = arrayOf(
|
||||||
|
"Paper color", "Lines", "Smoothing", "Finger mode",
|
||||||
|
"Fit everything on screen", "Go to start", "Rename",
|
||||||
|
"Export image (PNG)", "Export PDF", "Export text (.txt)", "Send KnockPad file", "About"
|
||||||
|
)
|
||||||
|
AlertDialog.Builder(this).setItems(items) { _, w ->
|
||||||
|
when (w) {
|
||||||
|
0 -> AlertDialog.Builder(this).setTitle("Paper color")
|
||||||
|
.setSingleChoiceItems(Paper.names, ink.paper) { d, i -> ink.paper = i; dirty = true; d.dismiss() }.show()
|
||||||
|
1 -> AlertDialog.Builder(this).setTitle("Lines")
|
||||||
|
.setSingleChoiceItems(Bg.names, ink.background) { d, i -> ink.background = i; dirty = true; d.dismiss() }.show()
|
||||||
|
2 -> sliderDialog("Smoothing (higher is neater)", 0f, 1f, ink.smoothing, { "${(it * 100).toInt()}%" }) {
|
||||||
|
ink.smoothing = it; prefs.edit().putFloat("smooth2", it).apply()
|
||||||
|
}
|
||||||
|
3 -> {
|
||||||
|
val modes = arrayOf("Automatic (pen draws if an S Pen is used)", "Finger draws", "Finger only moves the page")
|
||||||
|
AlertDialog.Builder(this).setTitle("Finger mode")
|
||||||
|
.setSingleChoiceItems(modes, ink.fingerMode) { d, i ->
|
||||||
|
ink.fingerMode = i; prefs.edit().putInt("fingerMode", i).apply(); d.dismiss()
|
||||||
|
}.show()
|
||||||
|
}
|
||||||
|
4 -> ink.fitAll()
|
||||||
|
5 -> ink.goToStart()
|
||||||
|
6 -> renameDialog()
|
||||||
|
7 -> exportFile("png")
|
||||||
|
8 -> exportFile("pdf")
|
||||||
|
9 -> exportFile("txt")
|
||||||
|
10 -> exportFile("knock")
|
||||||
|
11 -> AlertDialog.Builder(this).setTitle("KnockPad ${BuildConfig.VERSION_NAME}")
|
||||||
|
.setMessage("Yet another knock-off notepad.").setPositiveButton("OK", null).show()
|
||||||
|
}
|
||||||
|
}.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun renameDialog() {
|
||||||
|
val e = EditText(this).apply { setText(note.title); setSelection(text.length) }
|
||||||
|
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("Rename").setView(box)
|
||||||
|
.setPositiveButton("OK") { _, _ ->
|
||||||
|
val t = e.text.toString().trim()
|
||||||
|
if (t.isNotEmpty()) { note.title = t; titleView.text = t; dirty = true }
|
||||||
|
}
|
||||||
|
.setNegativeButton("Cancel", null).show()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------- handwriting to text ----------------
|
||||||
|
private fun withModel(go: () -> Unit) {
|
||||||
|
InkReader.ensure(
|
||||||
|
onDownloading = { Ui.toast(this, "Downloading the handwriting reader (one time, needs internet)...") }
|
||||||
|
) { ok, err ->
|
||||||
|
if (ok) go() else Ui.toast(this, "Couldn't get the handwriting reader. It needs internet the first time. ${err ?: ""}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun convertSelection() {
|
||||||
|
val sel = ink.selectedStrokes().filter { it.tool != Tool.HIGHLIGHTER }
|
||||||
|
if (sel.isEmpty()) { Ui.toast(this, "Lasso some handwriting first"); return }
|
||||||
|
withModel {
|
||||||
|
InkReader.recognize(sel) { txt ->
|
||||||
|
if (txt.isNullOrBlank()) Ui.toast(this, "Couldn't read that")
|
||||||
|
else appendText(txt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun appendText(t: String) {
|
||||||
|
val cur = textEdit.text
|
||||||
|
if (cur.isNotEmpty() && !cur.endsWith("\n")) textEdit.append("\n")
|
||||||
|
textEdit.append(t)
|
||||||
|
showText(true)
|
||||||
|
dirty = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------- photos ----------------
|
||||||
|
private fun pickPhoto() {
|
||||||
|
val i = Intent(Intent.ACTION_GET_CONTENT).apply { type = "image/*"; addCategory(Intent.CATEGORY_OPENABLE) }
|
||||||
|
startActivityForResult(Intent.createChooser(i, "Insert photo"), REQ_PHOTO)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Deprecated("Deprecated in Java")
|
||||||
|
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||||
|
super.onActivityResult(requestCode, resultCode, data)
|
||||||
|
if (requestCode != REQ_PHOTO || resultCode != RESULT_OK) return
|
||||||
|
val uri = data?.data ?: return
|
||||||
|
try {
|
||||||
|
val src = ImageDecoder.createSource(contentResolver, uri)
|
||||||
|
val bmp = ImageDecoder.decodeBitmap(src) { dec, info, _ ->
|
||||||
|
val w = info.size.width; val h = info.size.height
|
||||||
|
val f = min(1f, 1600f / max(w, h))
|
||||||
|
dec.setTargetSize(max(1, (w * f).toInt()), max(1, (h * f).toInt()))
|
||||||
|
dec.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
|
||||||
|
}
|
||||||
|
val out = ByteArrayOutputStream()
|
||||||
|
if (bmp.hasAlpha()) bmp.compress(Bitmap.CompressFormat.PNG, 100, out)
|
||||||
|
else bmp.compress(Bitmap.CompressFormat.JPEG, 88, out)
|
||||||
|
ink.addImage(bmp, out.toByteArray())
|
||||||
|
selectTool(Tool.LASSO)
|
||||||
|
Ui.toast(this, "Drag the photo to move it. Bigger/Smaller to resize.")
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Ui.toast(this, "Couldn't open that image")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------- exports ----------------
|
||||||
|
private fun currentNote(): Note {
|
||||||
|
note.strokes = ink.strokes
|
||||||
|
note.images = ink.images
|
||||||
|
note.background = ink.background
|
||||||
|
note.paper = ink.paper
|
||||||
|
note.text = textEdit.text.toString()
|
||||||
|
return note
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun exportFile(kind: String) {
|
||||||
|
val n = currentNote()
|
||||||
|
when (kind) {
|
||||||
|
"png" -> Exporter.png(this, n)?.let { deliver(it, "image/png") } ?: Ui.toast(this, "Nothing written yet")
|
||||||
|
"pdf" -> Exporter.pdf(this, n)?.let { deliver(it, "application/pdf") } ?: Ui.toast(this, "Nothing written yet")
|
||||||
|
"knock" -> { save(); deliver(Exporter.knock(this, currentNote()), "application/octet-stream") }
|
||||||
|
"txt" -> {
|
||||||
|
val t = textEdit.text.toString()
|
||||||
|
if (t.isNotBlank() || ink.strokes.isEmpty()) {
|
||||||
|
deliver(Exporter.txt(this, n, t), "text/plain")
|
||||||
|
} else {
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setMessage("Nothing has been converted to text yet. Read the whole page now and export that?")
|
||||||
|
.setPositiveButton("Read it") { _, _ ->
|
||||||
|
withModel {
|
||||||
|
InkReader.recognize(ink.strokes) { r ->
|
||||||
|
if (r.isNullOrBlank()) Ui.toast(this, "Couldn't read anything")
|
||||||
|
else { appendText(r); deliver(Exporter.txt(this, currentNote(), r), "text/plain") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.setNegativeButton("Cancel", null).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun deliver(f: File, mime: String) {
|
||||||
|
AlertDialog.Builder(this).setTitle(f.name)
|
||||||
|
.setItems(arrayOf("Send (LocalSend, email, etc.)", "Save to Downloads")) { _, w ->
|
||||||
|
if (w == 0) Exporter.share(this, f, mime)
|
||||||
|
else {
|
||||||
|
val p = try { Exporter.saveToDownloads(this, f, mime) } catch (_: Exception) { null }
|
||||||
|
Ui.toast(this, if (p != null) "Saved to $p" else "Couldn't save to Downloads")
|
||||||
|
}
|
||||||
|
}.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------- saving ----------------
|
||||||
|
private fun save() {
|
||||||
|
if (!::ink.isInitialized) return
|
||||||
|
val t = textEdit.text.toString()
|
||||||
|
if (t != note.text) dirty = true
|
||||||
|
if (!dirty) return
|
||||||
|
currentNote()
|
||||||
|
note.modified = System.currentTimeMillis()
|
||||||
|
store.save(note, Exporter.thumbnail(note))
|
||||||
|
dirty = false
|
||||||
|
if (inkDirty) {
|
||||||
|
inkDirty = false
|
||||||
|
indexInk()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Quietly reads the handwriting so search can find it. Only if the reader is already downloaded. */
|
||||||
|
private fun indexInk() {
|
||||||
|
val snapshot = note.strokes
|
||||||
|
val id = note.id
|
||||||
|
val app = applicationContext
|
||||||
|
InkReader.ifReady { ready ->
|
||||||
|
if (!ready) return@ifReady
|
||||||
|
InkReader.recognize(snapshot) { txt ->
|
||||||
|
if (txt != null) {
|
||||||
|
if (note.id == id) note.search = txt
|
||||||
|
NoteStore(app).updateSearch(id, txt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onPause() {
|
||||||
|
super.onPause()
|
||||||
|
if (!::ink.isInitialized) return
|
||||||
|
val blank = ink.strokes.isEmpty() && ink.images.isEmpty() && textEdit.text.isBlank()
|
||||||
|
if (isFinishing && blank && note.created == note.modified) {
|
||||||
|
store.delete(note.id) // opened and left empty: don't clutter the list
|
||||||
|
return
|
||||||
|
}
|
||||||
|
save()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------- canvas callbacks ----------------
|
||||||
|
override fun onInkChanged() { dirty = true; inkDirty = true }
|
||||||
|
|
||||||
|
override fun onSelectionChanged(has: Boolean) {
|
||||||
|
selBar.visibility = if (has) View.VISIBLE else View.GONE
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStylusSeen() {
|
||||||
|
prefs.edit().putBoolean("stylusSeen", true).apply()
|
||||||
|
if (ink.fingerMode == 0) Ui.toast(this, "S Pen found. Pen writes, fingers move the page.")
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val REQ_PHOTO = 7
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
package space.bloggin.knockpad
|
||||||
|
|
||||||
|
import android.content.ContentValues
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.Canvas
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.graphics.RectF
|
||||||
|
import android.graphics.pdf.PdfDocument
|
||||||
|
import android.net.Uri
|
||||||
|
import android.provider.MediaStore
|
||||||
|
import androidx.core.content.FileProvider
|
||||||
|
import java.io.File
|
||||||
|
import kotlin.math.ceil
|
||||||
|
import kotlin.math.max
|
||||||
|
import kotlin.math.min
|
||||||
|
|
||||||
|
object Exporter {
|
||||||
|
private fun dir(c: Context) = File(c.cacheDir, "exports").apply { mkdirs() }
|
||||||
|
|
||||||
|
fun safeName(title: String): String {
|
||||||
|
val s = title.replace(Regex("[^A-Za-z0-9 ._-]"), "").trim()
|
||||||
|
return if (s.isEmpty()) "KnockPad note" else s.take(60)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Renders the written area (plus a margin) to a bitmap no larger than maxDim on its long side. */
|
||||||
|
fun render(n: Note, maxDim: Int, margin: Float = 40f, withBackground: Boolean = true): Bitmap? {
|
||||||
|
val b = Ink.contentBounds(n.strokes, n.images) ?: return null
|
||||||
|
b.inset(-margin, -margin)
|
||||||
|
val s = min(2f, maxDim / max(b.width(), b.height()))
|
||||||
|
val w = max(1, (b.width() * s).toInt())
|
||||||
|
val h = max(1, (b.height() * s).toInt())
|
||||||
|
val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
|
||||||
|
val c = Canvas(bmp)
|
||||||
|
c.scale(s, s)
|
||||||
|
c.translate(-b.left, -b.top)
|
||||||
|
Ink.renderAll(c, n.strokes, n.images, if (withBackground) n.background else Bg.BLANK,
|
||||||
|
if (withBackground) n.paper else Paper.WHITE, b, s)
|
||||||
|
return bmp
|
||||||
|
}
|
||||||
|
|
||||||
|
fun thumbnail(n: Note): Bitmap {
|
||||||
|
val t = render(n, 360, 30f)
|
||||||
|
if (t != null) return t
|
||||||
|
val b = Bitmap.createBitmap(120, 80, Bitmap.Config.ARGB_8888)
|
||||||
|
b.eraseColor(Ink.paperColor(n.paper))
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
fun png(c: Context, n: Note): File? {
|
||||||
|
val bmp = render(n, 3200) ?: return null
|
||||||
|
val f = File(dir(c), safeName(n.title) + ".png")
|
||||||
|
f.outputStream().use { bmp.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Letter-size pages. Wide notes are scaled to fit the page width; tall notes run onto more pages. */
|
||||||
|
fun pdf(c: Context, n: Note): File? {
|
||||||
|
val b = Ink.contentBounds(n.strokes, n.images) ?: return null
|
||||||
|
b.inset(-12f, -12f)
|
||||||
|
val pageW = 612; val pageH = 792; val m = 36f
|
||||||
|
val areaW = pageW - 2 * m
|
||||||
|
val areaH = pageH - 2 * m
|
||||||
|
val s = min(0.75f, areaW / b.width())
|
||||||
|
val pages = max(1, ceil((b.height() * s) / areaH).toInt())
|
||||||
|
val doc = PdfDocument()
|
||||||
|
for (i in 0 until pages) {
|
||||||
|
val page = doc.startPage(PdfDocument.PageInfo.Builder(pageW, pageH, i + 1).create())
|
||||||
|
val cv = page.canvas
|
||||||
|
cv.drawColor(Color.WHITE)
|
||||||
|
cv.translate(m, m)
|
||||||
|
cv.clipRect(0f, 0f, areaW, areaH)
|
||||||
|
cv.translate(0f, -i * areaH)
|
||||||
|
cv.scale(s, s)
|
||||||
|
cv.translate(-b.left, -b.top)
|
||||||
|
Ink.renderAll(cv, n.strokes, n.images, n.background, n.paper, RectF(b), s)
|
||||||
|
doc.finishPage(page)
|
||||||
|
}
|
||||||
|
val f = File(dir(c), safeName(n.title) + ".pdf")
|
||||||
|
f.outputStream().use { doc.writeTo(it) }
|
||||||
|
doc.close()
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
fun txt(c: Context, n: Note, text: String): File {
|
||||||
|
val f = File(dir(c), safeName(n.title) + ".txt")
|
||||||
|
f.writeText(text)
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
fun knock(c: Context, n: Note): File {
|
||||||
|
val f = File(dir(c), safeName(n.title) + ".knock")
|
||||||
|
f.writeText(NoteIO.toJson(n))
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
fun share(c: Context, f: File, mime: String) {
|
||||||
|
val uri = FileProvider.getUriForFile(c, "space.bloggin.knockpad.files", f)
|
||||||
|
val i = Intent(Intent.ACTION_SEND).apply {
|
||||||
|
type = mime
|
||||||
|
putExtra(Intent.EXTRA_STREAM, uri)
|
||||||
|
putExtra(Intent.EXTRA_TITLE, f.name)
|
||||||
|
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||||
|
}
|
||||||
|
c.startActivity(Intent.createChooser(i, "Send ${f.name}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Copies the file into Download/KnockPad. Returns the folder path shown to the user. */
|
||||||
|
fun saveToDownloads(c: Context, f: File, mime: String): String? {
|
||||||
|
val values = ContentValues().apply {
|
||||||
|
put(MediaStore.Downloads.DISPLAY_NAME, f.name)
|
||||||
|
put(MediaStore.Downloads.MIME_TYPE, mime)
|
||||||
|
put(MediaStore.Downloads.RELATIVE_PATH, "Download/KnockPad")
|
||||||
|
}
|
||||||
|
val uri: Uri = c.contentResolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values) ?: return null
|
||||||
|
c.contentResolver.openOutputStream(uri)?.use { out -> f.inputStream().use { it.copyTo(out) } }
|
||||||
|
return "Download/KnockPad/${f.name}"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
package space.bloggin.knockpad
|
||||||
|
|
||||||
|
import android.graphics.Canvas
|
||||||
|
import android.graphics.ColorFilter
|
||||||
|
import android.graphics.DashPathEffect
|
||||||
|
import android.graphics.Paint
|
||||||
|
import android.graphics.Path
|
||||||
|
import android.graphics.PixelFormat
|
||||||
|
import android.graphics.RectF
|
||||||
|
import android.graphics.drawable.Drawable
|
||||||
|
|
||||||
|
/** Simple line icons, drawn on a 24x24 grid. No image files needed. */
|
||||||
|
class Icon(private val kind: Int, var color: Int = 0xFF222222.toInt()) : Drawable() {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val BACK = 0; const val PEN = 1; const val PENCIL = 2; const val MARKER = 3
|
||||||
|
const val ERASER = 4; const val RUB = 5; const val LASSO = 6; const val SHAPES = 7
|
||||||
|
const val SIZE = 8; const val UNDO = 9; const val REDO = 10; const val TEXT = 11
|
||||||
|
const val PHOTO = 12; const val MORE = 13; const val PLUS = 14; const val OPEN = 15
|
||||||
|
const val SEARCH = 16
|
||||||
|
}
|
||||||
|
|
||||||
|
private val p = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||||
|
style = Paint.Style.STROKE; strokeWidth = 1.7f
|
||||||
|
strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND
|
||||||
|
}
|
||||||
|
private val f = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
|
||||||
|
private val path = Path()
|
||||||
|
|
||||||
|
override fun draw(c: Canvas) {
|
||||||
|
val b = bounds
|
||||||
|
val s = minOf(b.width(), b.height()) / 24f
|
||||||
|
c.save()
|
||||||
|
c.translate(b.left + (b.width() - 24f * s) / 2f, b.top + (b.height() - 24f * s) / 2f)
|
||||||
|
c.scale(s, s)
|
||||||
|
drawTarget = c
|
||||||
|
p.color = color; f.color = color
|
||||||
|
p.pathEffect = null
|
||||||
|
p.strokeWidth = 1.7f
|
||||||
|
when (kind) {
|
||||||
|
BACK -> poly(15f, 5f, 8f, 12f, 15f, 19f)
|
||||||
|
PEN -> {
|
||||||
|
closedPoly(7f, 14f, 16f, 5f, 19f, 8f, 10f, 17f)
|
||||||
|
path.reset(); path.moveTo(7f, 14f); path.lineTo(10f, 17f); path.lineTo(4.5f, 19.5f); path.close()
|
||||||
|
c.drawPath(path, f)
|
||||||
|
c.drawPath(path, p)
|
||||||
|
}
|
||||||
|
PENCIL -> {
|
||||||
|
closedPoly(7f, 14f, 16f, 5f, 19f, 8f, 10f, 17f)
|
||||||
|
closedPoly(7f, 14f, 10f, 17f, 4.5f, 19.5f)
|
||||||
|
c.drawLine(13.5f, 7.5f, 16.5f, 10.5f, p)
|
||||||
|
c.drawCircle(5.6f, 18.4f, 0.9f, f)
|
||||||
|
}
|
||||||
|
MARKER -> {
|
||||||
|
closedPoly(6f, 13f, 14f, 5f, 19f, 10f, 11f, 18f)
|
||||||
|
closedPoly(6f, 13f, 11f, 18f, 8f, 19.5f, 4.5f, 16f)
|
||||||
|
f.alpha = 110
|
||||||
|
c.drawRect(3f, 20.2f, 14f, 22.4f, f)
|
||||||
|
f.alpha = 255
|
||||||
|
}
|
||||||
|
ERASER -> {
|
||||||
|
closedPoly(4f, 15f, 13f, 6f, 19.5f, 12.5f, 10.5f, 21.5f)
|
||||||
|
c.drawLine(8.2f, 10.8f, 14.7f, 17.3f, p)
|
||||||
|
c.drawLine(10.5f, 21.5f, 20f, 21.5f, p)
|
||||||
|
}
|
||||||
|
RUB -> {
|
||||||
|
p.pathEffect = DashPathEffect(floatArrayOf(2.2f, 2f), 0f)
|
||||||
|
c.drawCircle(12f, 12f, 8f, p)
|
||||||
|
p.pathEffect = null
|
||||||
|
c.drawCircle(12f, 12f, 1.6f, f)
|
||||||
|
}
|
||||||
|
LASSO -> {
|
||||||
|
p.pathEffect = DashPathEffect(floatArrayOf(2.4f, 1.9f), 0f)
|
||||||
|
c.drawOval(RectF(4f, 3.5f, 20f, 15.5f), p)
|
||||||
|
p.pathEffect = null
|
||||||
|
path.reset(); path.moveTo(8.5f, 14.5f); path.cubicTo(6f, 17f, 9f, 18.5f, 7f, 21f)
|
||||||
|
c.drawPath(path, p)
|
||||||
|
}
|
||||||
|
SHAPES -> {
|
||||||
|
c.drawRect(3.5f, 10.5f, 13.5f, 20.5f, p)
|
||||||
|
c.drawCircle(15f, 9f, 5.5f, p)
|
||||||
|
}
|
||||||
|
SIZE -> {
|
||||||
|
p.strokeWidth = 1f; c.drawLine(4f, 6f, 20f, 6f, p)
|
||||||
|
p.strokeWidth = 2f; c.drawLine(4f, 11.5f, 20f, 11.5f, p)
|
||||||
|
p.strokeWidth = 3.4f; c.drawLine(4f, 18f, 20f, 18f, p)
|
||||||
|
}
|
||||||
|
UNDO -> {
|
||||||
|
path.reset(); path.moveTo(9f, 14f); path.lineTo(4f, 9f); path.lineTo(9f, 4f)
|
||||||
|
c.drawPath(path, p)
|
||||||
|
path.reset(); path.moveTo(4f, 9f); path.lineTo(14f, 9f)
|
||||||
|
path.arcTo(RectF(9f, 9f, 20f, 20f), -90f, 180f); path.lineTo(10f, 20f)
|
||||||
|
c.drawPath(path, p)
|
||||||
|
}
|
||||||
|
REDO -> {
|
||||||
|
c.save(); c.scale(-1f, 1f, 12f, 12f)
|
||||||
|
path.reset(); path.moveTo(9f, 14f); path.lineTo(4f, 9f); path.lineTo(9f, 4f)
|
||||||
|
c.drawPath(path, p)
|
||||||
|
path.reset(); path.moveTo(4f, 9f); path.lineTo(14f, 9f)
|
||||||
|
path.arcTo(RectF(9f, 9f, 20f, 20f), -90f, 180f); path.lineTo(10f, 20f)
|
||||||
|
c.drawPath(path, p)
|
||||||
|
c.restore()
|
||||||
|
}
|
||||||
|
TEXT -> {
|
||||||
|
p.strokeWidth = 2f
|
||||||
|
c.drawLine(5f, 5f, 19f, 5f, p)
|
||||||
|
c.drawLine(12f, 5f, 12f, 19.5f, p)
|
||||||
|
p.strokeWidth = 1.7f
|
||||||
|
c.drawLine(9f, 19.5f, 15f, 19.5f, p)
|
||||||
|
}
|
||||||
|
PHOTO -> {
|
||||||
|
c.drawRect(3f, 5f, 21f, 19f, p)
|
||||||
|
poly(3.5f, 17f, 9f, 11.5f, 13f, 15.5f, 16f, 12.5f, 20.5f, 17f)
|
||||||
|
c.drawCircle(16f, 8.8f, 1.5f, f)
|
||||||
|
}
|
||||||
|
MORE -> {
|
||||||
|
c.drawCircle(12f, 5.5f, 1.7f, f); c.drawCircle(12f, 12f, 1.7f, f); c.drawCircle(12f, 18.5f, 1.7f, f)
|
||||||
|
}
|
||||||
|
PLUS -> {
|
||||||
|
p.strokeWidth = 2f
|
||||||
|
c.drawLine(12f, 5f, 12f, 19f, p); c.drawLine(5f, 12f, 19f, 12f, p)
|
||||||
|
}
|
||||||
|
OPEN -> {
|
||||||
|
closedPoly(3f, 6f, 9.5f, 6f, 11.5f, 8.5f, 21f, 8.5f, 21f, 19f, 3f, 19f)
|
||||||
|
}
|
||||||
|
SEARCH -> {
|
||||||
|
c.drawCircle(10.5f, 10.5f, 6f, p)
|
||||||
|
c.drawLine(15f, 15f, 20f, 20f, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.restore()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun poly(vararg v: Float) {
|
||||||
|
path.reset(); path.moveTo(v[0], v[1])
|
||||||
|
var i = 2
|
||||||
|
while (i < v.size) { path.lineTo(v[i], v[i + 1]); i += 2 }
|
||||||
|
canvasDraw()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun closedPoly(vararg v: Float) {
|
||||||
|
path.reset(); path.moveTo(v[0], v[1])
|
||||||
|
var i = 2
|
||||||
|
while (i < v.size) { path.lineTo(v[i], v[i + 1]); i += 2 }
|
||||||
|
path.close()
|
||||||
|
canvasDraw()
|
||||||
|
}
|
||||||
|
|
||||||
|
private var drawTarget: Canvas? = null
|
||||||
|
private fun canvasDraw() { drawTarget?.drawPath(path, p) }
|
||||||
|
|
||||||
|
override fun setAlpha(alpha: Int) { p.alpha = alpha; f.alpha = alpha }
|
||||||
|
override fun setColorFilter(cf: ColorFilter?) { p.colorFilter = cf; f.colorFilter = cf }
|
||||||
|
@Deprecated("Deprecated in Java")
|
||||||
|
override fun getOpacity() = PixelFormat.TRANSLUCENT
|
||||||
|
}
|
||||||
@@ -0,0 +1,389 @@
|
|||||||
|
package space.bloggin.knockpad
|
||||||
|
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.BitmapShader
|
||||||
|
import android.graphics.Canvas
|
||||||
|
import android.graphics.Paint
|
||||||
|
import android.graphics.Path
|
||||||
|
import android.graphics.RectF
|
||||||
|
import android.graphics.Shader
|
||||||
|
import java.util.Random
|
||||||
|
import kotlin.math.abs
|
||||||
|
import kotlin.math.ceil
|
||||||
|
import kotlin.math.cos
|
||||||
|
import kotlin.math.exp
|
||||||
|
import kotlin.math.floor
|
||||||
|
import kotlin.math.hypot
|
||||||
|
import kotlin.math.max
|
||||||
|
import kotlin.math.min
|
||||||
|
import kotlin.math.sin
|
||||||
|
import kotlin.math.sqrt
|
||||||
|
|
||||||
|
/** Drawing of paper, strokes, images and page backgrounds. Used by the canvas and by exports. */
|
||||||
|
object Ink {
|
||||||
|
private const val RULE = 0xFFD3D7DD.toInt()
|
||||||
|
|
||||||
|
fun paperColor(p: Int): Int = when (p) {
|
||||||
|
Paper.WHITE -> 0xFFFFFFFF.toInt()
|
||||||
|
Paper.GRAY -> 0xFFECECEC.toInt()
|
||||||
|
Paper.VELLUM -> 0xFFF0F1EC.toInt()
|
||||||
|
else -> 0xFFFBF8EE.toInt()
|
||||||
|
}
|
||||||
|
|
||||||
|
private val line = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||||
|
style = Paint.Style.STROKE; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND
|
||||||
|
}
|
||||||
|
private val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
|
||||||
|
private val rule = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = RULE; style = Paint.Style.STROKE }
|
||||||
|
private val dot = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = 0xFFB4BAC3.toInt(); style = Paint.Style.FILL }
|
||||||
|
private val bmp = Paint(Paint.FILTER_BITMAP_FLAG or Paint.ANTI_ALIAS_FLAG)
|
||||||
|
private val path = Path()
|
||||||
|
|
||||||
|
// Vellum: frosted, slightly fibrous sheet. A small noise tile repeated across the page.
|
||||||
|
private val vellumPaint: Paint by lazy {
|
||||||
|
val size = 160
|
||||||
|
val b = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
|
||||||
|
val r = Random(7)
|
||||||
|
val base = paperColor(Paper.VELLUM)
|
||||||
|
b.eraseColor(base)
|
||||||
|
val c = Canvas(b)
|
||||||
|
val p = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = 0.7f }
|
||||||
|
// fine grain
|
||||||
|
for (i in 0 until 2600) {
|
||||||
|
val v = r.nextInt(255)
|
||||||
|
p.color = if (v > 127) 0x0D000000 else 0x14FFFFFF
|
||||||
|
c.drawPoint(r.nextFloat() * size, r.nextFloat() * size, p)
|
||||||
|
}
|
||||||
|
// faint fibers
|
||||||
|
for (i in 0 until 70) {
|
||||||
|
val x = r.nextFloat() * size; val y = r.nextFloat() * size
|
||||||
|
val a = r.nextFloat() * 6.283f; val l = 4f + r.nextFloat() * 14f
|
||||||
|
p.color = if (r.nextBoolean()) 0x0A000000 else 0x18FFFFFF
|
||||||
|
c.drawLine(x, y, x + cos(a) * l, y + sin(a) * l, p)
|
||||||
|
}
|
||||||
|
Paint().apply { shader = BitmapShader(b, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fills the visible area with the note's paper. Call with the world transform already applied. */
|
||||||
|
fun drawPaper(c: Canvas, paper: Int, vis: RectF) {
|
||||||
|
if (paper == Paper.VELLUM) c.drawRect(vis, vellumPaint)
|
||||||
|
else { fill.color = paperColor(paper); c.drawRect(vis, fill) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun drawStroke(c: Canvas, s: Stroke, dx: Float = 0f, dy: Float = 0f) {
|
||||||
|
drawPts(c, s.tool, s.color, s.pts, dx, dy)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun drawPts(c: Canvas, tool: Int, color: Int, a: FloatArray, dx: Float = 0f, dy: Float = 0f) {
|
||||||
|
val n = a.size / 3
|
||||||
|
if (n == 0) return
|
||||||
|
when (tool) {
|
||||||
|
Tool.HIGHLIGHTER -> {
|
||||||
|
line.color = (color and 0x00FFFFFF) or 0x66000000
|
||||||
|
line.strokeWidth = a[2]
|
||||||
|
buildPath(a, n, dx, dy)
|
||||||
|
c.drawPath(path, line)
|
||||||
|
}
|
||||||
|
Tool.PENCIL -> {
|
||||||
|
line.color = (color and 0x00FFFFFF) or 0xC0000000.toInt()
|
||||||
|
var w = 0f
|
||||||
|
var i = 2
|
||||||
|
while (i < a.size) { w += a[i]; i += 3 }
|
||||||
|
line.strokeWidth = w / n
|
||||||
|
buildPath(a, n, dx, dy)
|
||||||
|
c.drawPath(path, line)
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
if (n == 1) {
|
||||||
|
fill.color = color
|
||||||
|
c.drawCircle(a[0] + dx, a[1] + dy, a[2] / 2f, fill)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
line.color = color
|
||||||
|
var i = 3
|
||||||
|
while (i < a.size) {
|
||||||
|
line.strokeWidth = (a[i - 1] + a[i + 2]) * 0.5f
|
||||||
|
c.drawLine(a[i - 3] + dx, a[i - 2] + dy, a[i] + dx, a[i + 1] + dy, line)
|
||||||
|
i += 3
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Path through the points using midpoint curves, so even sparse points draw smooth. */
|
||||||
|
private fun buildPath(a: FloatArray, n: Int, dx: Float, dy: Float) {
|
||||||
|
path.reset()
|
||||||
|
path.moveTo(a[0] + dx, a[1] + dy)
|
||||||
|
if (n == 1) { path.lineTo(a[0] + dx + 0.01f, a[1] + dy); return }
|
||||||
|
if (n == 2) { path.lineTo(a[3] + dx, a[4] + dy); return }
|
||||||
|
for (i in 1 until n - 1) {
|
||||||
|
val x = a[i * 3] + dx; val y = a[i * 3 + 1] + dy
|
||||||
|
val mx = (x + a[(i + 1) * 3] + dx) / 2f; val my = (y + a[(i + 1) * 3 + 1] + dy) / 2f
|
||||||
|
path.quadTo(x, y, mx, my)
|
||||||
|
}
|
||||||
|
path.lineTo(a[(n - 1) * 3] + dx, a[(n - 1) * 3 + 1] + dy)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun drawImage(c: Canvas, im: ImageItem, dx: Float = 0f, dy: Float = 0f) {
|
||||||
|
c.drawBitmap(im.bitmap, null, RectF(im.x + dx, im.y + dy, im.x + im.w + dx, im.y + im.h + dy), bmp)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun drawBackground(c: Canvas, type: Int, vis: RectF, scale: Float) {
|
||||||
|
if (type == Bg.BLANK) return
|
||||||
|
val sp = 40f
|
||||||
|
if (sp * scale < 7f) return
|
||||||
|
rule.strokeWidth = 1f / scale
|
||||||
|
val x0 = floor(vis.left / sp) * sp
|
||||||
|
val y0 = floor(vis.top / sp) * sp
|
||||||
|
when (type) {
|
||||||
|
Bg.LINED -> {
|
||||||
|
var y = y0
|
||||||
|
while (y <= vis.bottom) { c.drawLine(vis.left, y, vis.right, y, rule); y += sp }
|
||||||
|
}
|
||||||
|
Bg.GRID -> {
|
||||||
|
var y = y0
|
||||||
|
while (y <= vis.bottom) { c.drawLine(vis.left, y, vis.right, y, rule); y += sp }
|
||||||
|
var x = x0
|
||||||
|
while (x <= vis.right) { c.drawLine(x, vis.top, x, vis.bottom, rule); x += sp }
|
||||||
|
}
|
||||||
|
Bg.DOTS -> {
|
||||||
|
if (sp * scale < 12f) return
|
||||||
|
val r = 1.7f / scale.coerceAtMost(1.5f)
|
||||||
|
var y = y0
|
||||||
|
while (y <= vis.bottom) {
|
||||||
|
var x = x0
|
||||||
|
while (x <= vis.right) { c.drawCircle(x, y, r, dot); x += sp }
|
||||||
|
y += sp
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Draws everything visible. Highlighter goes under the ink so it never covers writing. */
|
||||||
|
fun renderAll(
|
||||||
|
c: Canvas, strokes: List<Stroke>, images: List<ImageItem>, bg: Int, paper: Int, vis: RectF, scale: Float,
|
||||||
|
hideS: Set<Stroke>? = null, hideI: Set<ImageItem>? = null
|
||||||
|
) {
|
||||||
|
drawPaper(c, paper, vis)
|
||||||
|
drawBackground(c, bg, vis, scale)
|
||||||
|
for (im in images) {
|
||||||
|
if (hideI != null && im in hideI) continue
|
||||||
|
if (RectF.intersects(im.rect, vis)) drawImage(c, im)
|
||||||
|
}
|
||||||
|
for (s in strokes) {
|
||||||
|
if (s.tool != Tool.HIGHLIGHTER) continue
|
||||||
|
if (hideS != null && s in hideS) continue
|
||||||
|
if (RectF.intersects(s.bounds, vis)) drawStroke(c, s)
|
||||||
|
}
|
||||||
|
for (s in strokes) {
|
||||||
|
if (s.tool == Tool.HIGHLIGHTER) continue
|
||||||
|
if (hideS != null && s in hideS) continue
|
||||||
|
if (RectF.intersects(s.bounds, vis)) drawStroke(c, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun contentBounds(strokes: List<Stroke>, images: List<ImageItem>): RectF? {
|
||||||
|
var r: RectF? = null
|
||||||
|
for (s in strokes) { if (r == null) r = RectF(s.bounds) else r.union(s.bounds) }
|
||||||
|
for (im in images) { if (r == null) r = im.rect else r.union(im.rect) }
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stroke smoothing. The raw points are first respaced evenly along the line, so smoothing acts the
|
||||||
|
* same whether you write fast or slow. Then a gaussian blur runs along the line. The window shrinks
|
||||||
|
* near the ends so the start and finish of a stroke stay exactly where you put them.
|
||||||
|
*/
|
||||||
|
object Smooth {
|
||||||
|
private const val SPACING = 1.4f
|
||||||
|
|
||||||
|
fun process(raw: FloatArray, smoothing: Float, rawCount: Int = raw.size / 3): FloatArray {
|
||||||
|
val n = rawCount
|
||||||
|
if (n < 3 || smoothing <= 0.01f) return raw.copyOf(n * 3)
|
||||||
|
val r = resample(raw, n, SPACING)
|
||||||
|
val m = r.size / 3
|
||||||
|
if (m < 3) return r
|
||||||
|
val sigma = 0.6f + smoothing * 7.5f // in samples
|
||||||
|
val sigmaW = sigma * 1.8f // widths get smoothed harder (pressure jitter)
|
||||||
|
val out = FloatArray(r.size)
|
||||||
|
gauss(r, out, m, sigma, 0)
|
||||||
|
gauss(r, out, m, sigma, 1)
|
||||||
|
gauss(r, out, m, sigmaW, 2)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun gauss(src: FloatArray, dst: FloatArray, n: Int, sigma: Float, k: Int) {
|
||||||
|
val rad = ceil(sigma * 2.5f).toInt()
|
||||||
|
val w = FloatArray(rad + 1) { exp(-(it * it) / (2f * sigma * sigma)) }
|
||||||
|
for (i in 0 until n) {
|
||||||
|
val rr = min(rad, min(i, n - 1 - i))
|
||||||
|
var sum = 0f; var ws = 0f
|
||||||
|
for (j in -rr..rr) {
|
||||||
|
val wt = w[abs(j)]
|
||||||
|
sum += src[(i + j) * 3 + k] * wt
|
||||||
|
ws += wt
|
||||||
|
}
|
||||||
|
dst[i * 3 + k] = sum / ws
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun resample(a: FloatArray, n: Int, sp: Float): FloatArray {
|
||||||
|
var total = 0f
|
||||||
|
for (i in 1 until n) total += hypot(a[i * 3] - a[(i - 1) * 3], a[i * 3 + 1] - a[(i - 1) * 3 + 1])
|
||||||
|
if (total < sp * 2) return a.copyOf(n * 3)
|
||||||
|
val count = (total / sp).toInt() + 1
|
||||||
|
val out = FloatArray((count + 1) * 3)
|
||||||
|
var o = 0
|
||||||
|
out[o++] = a[0]; out[o++] = a[1]; out[o++] = a[2]
|
||||||
|
var seg = 1
|
||||||
|
var segStart = 0f
|
||||||
|
var segLen = hypot(a[3] - a[0], a[4] - a[1])
|
||||||
|
var d = sp
|
||||||
|
while (d < total && o + 3 <= out.size - 3) {
|
||||||
|
while (seg < n - 1 && segStart + segLen < d) {
|
||||||
|
segStart += segLen
|
||||||
|
seg++
|
||||||
|
segLen = hypot(a[seg * 3] - a[(seg - 1) * 3], a[seg * 3 + 1] - a[(seg - 1) * 3 + 1])
|
||||||
|
}
|
||||||
|
val t = if (segLen > 0f) ((d - segStart) / segLen).coerceIn(0f, 1f) else 0f
|
||||||
|
val p = (seg - 1) * 3; val q = seg * 3
|
||||||
|
out[o++] = a[p] + (a[q] - a[p]) * t
|
||||||
|
out[o++] = a[p + 1] + (a[q + 1] - a[p + 1]) * t
|
||||||
|
out[o++] = a[p + 2] + (a[q + 2] - a[p + 2]) * t
|
||||||
|
d += sp
|
||||||
|
}
|
||||||
|
out[o++] = a[(n - 1) * 3]; out[o++] = a[(n - 1) * 3 + 1]; out[o++] = a[(n - 1) * 3 + 2]
|
||||||
|
return out.copyOf(o)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Clean shapes: from the shape tool, and from holding the pen still at the end of a rough stroke. */
|
||||||
|
object Shapes {
|
||||||
|
fun fit(p: FloatArray, n: Int): FloatArray? {
|
||||||
|
if (n < 6) return null
|
||||||
|
var w = 0f
|
||||||
|
var minX = Float.MAX_VALUE; var minY = Float.MAX_VALUE
|
||||||
|
var maxX = -Float.MAX_VALUE; var maxY = -Float.MAX_VALUE
|
||||||
|
var plen = 0f
|
||||||
|
for (i in 0 until n) {
|
||||||
|
val x = p[i * 3]; val y = p[i * 3 + 1]
|
||||||
|
w += p[i * 3 + 2]
|
||||||
|
minX = min(minX, x); maxX = max(maxX, x); minY = min(minY, y); maxY = max(maxY, y)
|
||||||
|
if (i > 0) plen += hypot(x - p[(i - 1) * 3], y - p[(i - 1) * 3 + 1])
|
||||||
|
}
|
||||||
|
w /= n
|
||||||
|
val bw = maxX - minX
|
||||||
|
val bh = maxY - minY
|
||||||
|
// Too small to be a shape; probably a letter you paused on.
|
||||||
|
if (hypot(bw, bh) < 45f) return null
|
||||||
|
val x0 = p[0]; val y0 = p[1]
|
||||||
|
val x1 = p[(n - 1) * 3]; val y1 = p[(n - 1) * 3 + 1]
|
||||||
|
val len = hypot(x1 - x0, y1 - y0)
|
||||||
|
|
||||||
|
if (len > 0.85f * plen && len > 10f) {
|
||||||
|
var dev = 0f
|
||||||
|
for (i in 0 until n) dev = max(dev, segDist(p[i * 3], p[i * 3 + 1], x0, y0, x1, y1))
|
||||||
|
if (dev < 0.06f * len + 2f) return line(x0, y0, x1, y1, w)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (len < 0.25f * plen) {
|
||||||
|
val cx = (minX + maxX) / 2f; val cy = (minY + maxY) / 2f
|
||||||
|
val rx = max(bw / 2f, 1f); val ry = max(bh / 2f, 1f)
|
||||||
|
var ell = 0f
|
||||||
|
var rect = 0f
|
||||||
|
for (i in 0 until n) {
|
||||||
|
val x = p[i * 3]; val y = p[i * 3 + 1]
|
||||||
|
val nx = (x - cx) / rx; val ny = (y - cy) / ry
|
||||||
|
ell += abs(sqrt(nx * nx + ny * ny) - 1f)
|
||||||
|
val dx = min(abs(x - minX), abs(x - maxX)) / max(bw, 1f)
|
||||||
|
val dy = min(abs(y - minY), abs(y - maxY)) / max(bh, 1f)
|
||||||
|
rect += min(dx, dy)
|
||||||
|
}
|
||||||
|
ell /= n; rect /= n
|
||||||
|
val diag = hypot(bw, bh)
|
||||||
|
var worstCorner = 0f
|
||||||
|
for ((qx, qy) in listOf(minX to minY, maxX to minY, maxX to maxY, minX to maxY)) {
|
||||||
|
var best = Float.MAX_VALUE
|
||||||
|
for (i in 0 until n) best = min(best, hypot(p[i * 3] - qx, p[i * 3 + 1] - qy))
|
||||||
|
worstCorner = max(worstCorner, best / diag)
|
||||||
|
}
|
||||||
|
if (worstCorner < 0.08f && rect < 0.08f) return rect(minX, minY, maxX, maxY, w)
|
||||||
|
if (ell < 0.16f) return ellipse(cx, cy, rx, ry, w)
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shape tool: drag from one corner to the other. Circle and square stay perfectly round/square,
|
||||||
|
* sized by the longer side of the drag. Polygons are regular, flat on the bottom.
|
||||||
|
*/
|
||||||
|
fun fromDrag(kind: Int, sides: Int, x0: Float, y0: Float, x1: Float, y1: Float, w: Float): FloatArray? {
|
||||||
|
val side = max(abs(x1 - x0), abs(y1 - y0))
|
||||||
|
if (side < 4f) return null
|
||||||
|
val sx = if (x1 >= x0) 1f else -1f
|
||||||
|
val sy = if (y1 >= y0) 1f else -1f
|
||||||
|
val l = min(x0, x0 + sx * side); val t = min(y0, y0 + sy * side)
|
||||||
|
val cx = l + side / 2f; val cy = t + side / 2f
|
||||||
|
return when (kind) {
|
||||||
|
ShapeKind.CIRCLE -> ellipse(cx, cy, side / 2f, side / 2f, w)
|
||||||
|
ShapeKind.SQUARE -> rect(l, t, l + side, t + side, w)
|
||||||
|
else -> polygon(cx, cy, side / 2f, sides.coerceIn(3, 12), w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun line(x0: Float, y0: Float, x1: Float, y1: Float, w: Float): FloatArray {
|
||||||
|
val len = hypot(x1 - x0, y1 - y0)
|
||||||
|
val steps = max(2, (len / 4f).toInt())
|
||||||
|
val out = FloatArray((steps + 1) * 3)
|
||||||
|
for (i in 0..steps) {
|
||||||
|
val t = i / steps.toFloat()
|
||||||
|
out[i * 3] = x0 + (x1 - x0) * t; out[i * 3 + 1] = y0 + (y1 - y0) * t; out[i * 3 + 2] = w
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun closed(corners: List<Pair<Float, Float>>, w: Float): FloatArray {
|
||||||
|
val out = ArrayList<Float>()
|
||||||
|
for (k in corners.indices) {
|
||||||
|
val (ax, ay) = corners[k]
|
||||||
|
val (bx, by) = corners[(k + 1) % corners.size]
|
||||||
|
val seg = line(ax, ay, bx, by, w)
|
||||||
|
val start = if (k == 0) 0 else 3
|
||||||
|
for (i in start until seg.size) out.add(seg[i])
|
||||||
|
}
|
||||||
|
return out.toFloatArray()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun rect(l: Float, t: Float, r: Float, b: Float, w: Float) =
|
||||||
|
closed(listOf(l to t, r to t, r to b, l to b), w)
|
||||||
|
|
||||||
|
private fun polygon(cx: Float, cy: Float, r: Float, sides: Int, w: Float): FloatArray {
|
||||||
|
// Rotate so the bottom edge is flat.
|
||||||
|
val step = (Math.PI * 2 / sides).toFloat()
|
||||||
|
val start = (Math.PI / 2).toFloat() + step / 2f
|
||||||
|
val pts = (0 until sides).map { i ->
|
||||||
|
val a = start + i * step
|
||||||
|
(cx + r * cos(a)) to (cy + r * sin(a))
|
||||||
|
}
|
||||||
|
return closed(pts, w)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ellipse(cx: Float, cy: Float, rx: Float, ry: Float, w: Float): FloatArray {
|
||||||
|
val steps = max(48, (max(rx, ry) * 0.6f).toInt()).coerceAtMost(240)
|
||||||
|
val out = FloatArray((steps + 1) * 3)
|
||||||
|
for (i in 0..steps) {
|
||||||
|
val a = (i / steps.toFloat()) * (Math.PI * 2).toFloat()
|
||||||
|
out[i * 3] = cx + rx * cos(a); out[i * 3 + 1] = cy + ry * sin(a); out[i * 3 + 2] = w
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
package space.bloggin.knockpad
|
||||||
|
|
||||||
|
import android.graphics.RectF
|
||||||
|
import com.google.mlkit.common.model.DownloadConditions
|
||||||
|
import com.google.mlkit.common.model.RemoteModelManager
|
||||||
|
import com.google.mlkit.vision.digitalink.DigitalInkRecognition
|
||||||
|
import com.google.mlkit.vision.digitalink.DigitalInkRecognitionModel
|
||||||
|
import com.google.mlkit.vision.digitalink.DigitalInkRecognitionModelIdentifier
|
||||||
|
import com.google.mlkit.vision.digitalink.DigitalInkRecognizer
|
||||||
|
import com.google.mlkit.vision.digitalink.DigitalInkRecognizerOptions
|
||||||
|
import com.google.mlkit.vision.digitalink.Ink as MlInk
|
||||||
|
import kotlin.math.abs
|
||||||
|
import kotlin.math.max
|
||||||
|
import kotlin.math.min
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handwriting to text with Google's on-device recognizer.
|
||||||
|
* The English model downloads once (needs internet that one time), then works offline.
|
||||||
|
*/
|
||||||
|
object InkReader {
|
||||||
|
private var recognizer: DigitalInkRecognizer? = null
|
||||||
|
|
||||||
|
private fun model(): DigitalInkRecognitionModel? = try {
|
||||||
|
DigitalInkRecognitionModelIdentifier.fromLanguageTag("en-US")?.let {
|
||||||
|
DigitalInkRecognitionModel.builder(it).build()
|
||||||
|
}
|
||||||
|
} catch (_: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun make(m: DigitalInkRecognitionModel) {
|
||||||
|
recognizer = DigitalInkRecognition.getClient(DigitalInkRecognizerOptions.builder(m).build())
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Makes sure the model is on the device, downloading it if needed. */
|
||||||
|
fun ensure(onDownloading: () -> Unit, done: (Boolean, String?) -> Unit) {
|
||||||
|
if (recognizer != null) return done(true, null)
|
||||||
|
val m = model() ?: return done(false, "model unavailable")
|
||||||
|
val mgr = RemoteModelManager.getInstance()
|
||||||
|
mgr.isModelDownloaded(m)
|
||||||
|
.addOnSuccessListener { has ->
|
||||||
|
if (has) {
|
||||||
|
make(m); done(true, null)
|
||||||
|
} else {
|
||||||
|
onDownloading()
|
||||||
|
mgr.download(m, DownloadConditions.Builder().build())
|
||||||
|
.addOnSuccessListener { make(m); done(true, null) }
|
||||||
|
.addOnFailureListener { done(false, it.message) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.addOnFailureListener { done(false, it.message) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Only reports ready if the model is already downloaded. Never downloads. */
|
||||||
|
fun ifReady(done: (Boolean) -> Unit) {
|
||||||
|
if (recognizer != null) return done(true)
|
||||||
|
val m = model() ?: return done(false)
|
||||||
|
RemoteModelManager.getInstance().isModelDownloaded(m)
|
||||||
|
.addOnSuccessListener { has -> if (has) make(m); done(has) }
|
||||||
|
.addOnFailureListener { done(false) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reads the strokes line by line, top to bottom, and returns the text with line breaks. */
|
||||||
|
fun recognize(strokes: List<Stroke>, done: (String?) -> Unit) {
|
||||||
|
val rec = recognizer ?: return done(null)
|
||||||
|
val lines = clusterLines(strokes.filter { it.tool != Tool.HIGHLIGHTER && it.n > 0 })
|
||||||
|
if (lines.isEmpty()) return done("")
|
||||||
|
val out = ArrayList<String>()
|
||||||
|
fun step(i: Int) {
|
||||||
|
if (i >= lines.size) {
|
||||||
|
done(out.filter { it.isNotBlank() }.joinToString("\n"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rec.recognize(inkOf(lines[i]))
|
||||||
|
.addOnSuccessListener { r -> out.add(r.candidates.firstOrNull()?.text ?: ""); step(i + 1) }
|
||||||
|
.addOnFailureListener { step(i + 1) }
|
||||||
|
}
|
||||||
|
step(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun inkOf(strokes: List<Stroke>): MlInk {
|
||||||
|
val b = MlInk.builder()
|
||||||
|
var t = 0L
|
||||||
|
for (s in strokes) {
|
||||||
|
val sb = MlInk.Stroke.builder()
|
||||||
|
var i = 0
|
||||||
|
while (i < s.pts.size) {
|
||||||
|
sb.addPoint(MlInk.Point.create(s.pts[i], s.pts[i + 1], t))
|
||||||
|
t += 8
|
||||||
|
i += 3
|
||||||
|
}
|
||||||
|
b.addStroke(sb.build())
|
||||||
|
}
|
||||||
|
return b.build()
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Line(val r: RectF, val items: ArrayList<Stroke>)
|
||||||
|
|
||||||
|
/** Groups strokes into lines of writing so the recognizer reads one line at a time. */
|
||||||
|
fun clusterLines(list: List<Stroke>): List<List<Stroke>> {
|
||||||
|
if (list.isEmpty()) return emptyList()
|
||||||
|
val order = HashMap<Stroke, Int>()
|
||||||
|
list.forEachIndexed { i, s -> order[s] = i }
|
||||||
|
val heights = list.map { it.bounds.height() }.sorted()
|
||||||
|
val med = heights[heights.size / 2].coerceAtLeast(6f)
|
||||||
|
val big = list.filter { it.bounds.height() >= med * 0.4f || it.bounds.width() >= med * 1.2f }
|
||||||
|
val bigSet = big.toHashSet()
|
||||||
|
val small = list.filter { it !in bigSet }
|
||||||
|
|
||||||
|
val lines = ArrayList<Line>()
|
||||||
|
for (s in big.sortedBy { it.bounds.centerY() }) {
|
||||||
|
var best: Line? = null
|
||||||
|
var bestOv = 0f
|
||||||
|
for (l in lines) {
|
||||||
|
val ov = min(l.r.bottom, s.bounds.bottom) - max(l.r.top, s.bounds.top)
|
||||||
|
val need = 0.45f * min(s.bounds.height(), l.r.height())
|
||||||
|
if (ov > need && ov > bestOv) { best = l; bestOv = ov }
|
||||||
|
}
|
||||||
|
if (best == null) lines.add(Line(RectF(s.bounds), arrayListOf(s)))
|
||||||
|
else { best.items.add(s); best.r.union(s.bounds) }
|
||||||
|
}
|
||||||
|
for (s in small) {
|
||||||
|
var best: Line? = null
|
||||||
|
var bestD = Float.MAX_VALUE
|
||||||
|
val cy = s.bounds.centerY()
|
||||||
|
for (l in lines) {
|
||||||
|
val d = if (cy < l.r.top) l.r.top - cy else if (cy > l.r.bottom) cy - l.r.bottom else 0f
|
||||||
|
val hx = if (s.bounds.centerX() < l.r.left) l.r.left - s.bounds.centerX()
|
||||||
|
else if (s.bounds.centerX() > l.r.right) s.bounds.centerX() - l.r.right else 0f
|
||||||
|
val score = d + hx * 0.5f
|
||||||
|
if (score < bestD) { bestD = score; best = l }
|
||||||
|
}
|
||||||
|
if (best != null && abs(bestD) < med * 1.5f) best.items.add(s)
|
||||||
|
else lines.add(Line(RectF(s.bounds), arrayListOf(s)))
|
||||||
|
}
|
||||||
|
return lines.sortedBy { it.r.top }.map { l -> l.items.sortedBy { order[it] ?: 0 } }
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user