Add app/src/main/java/space/bloggin/knockpad

This commit is contained in:
2026-12-03 01:19:48 +00:00
parent 435921b339
commit 2621c7cca9
5 changed files with 1331 additions and 0 deletions
@@ -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
}
}