mirror of
https://github.com/D-Modem/app.git
synced 2026-11-28 17:38:05 -08:00
Fax in the app: send documents, answer calls as faxes, received faxes as PDFs
- Home has a Fax section: send a PDF, image or text to a number, answer a ringing call as a fax, the call as it goes (Cancel), the last faxes; Settings has this fax's number, answering every call as a fax, fine resolution and the fastest rate - a call has the modem's DTE to itself (DteHub.claim) while it lasts - documents become pages at the fax's resolution (PdfRenderer, images dithered, text set in a monospace font); received pages are saved as a PDF in the fax's own coding (CCITTFaxDecode) in Download/D-Modem Tested: the app's fax on the hub to our T.30 on fax_line both ways, the saved PDF read back by poppler, every pel as sent. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0172Hejd12i4aYikYW9vgpZs
This commit is contained in:
13 files changed
+1130
-2
No files matched your search
@@ -22,6 +22,8 @@ class DModemApp : Application() {
|
||||
getSystemService(NotificationManager::class.java).createNotificationChannel(ch)
|
||||
|
||||
Terminal.init(this)
|
||||
// fax calls: their settings and files, and calls that ring answered as faxes when they say so
|
||||
com.neodesktop.dmodem.fax.Fax.init(this)
|
||||
|
||||
// what the modem sends its DTE, as text, for the status screen's console
|
||||
ModemState.dte.addListener { data, length ->
|
||||
|
||||
@@ -44,6 +44,12 @@ class Class1(private val io: TransferIo, private val log: (String) -> Unit = {})
|
||||
return result(ms)
|
||||
}
|
||||
|
||||
/** a command out (without its AT), its result left for [result] */
|
||||
fun send(cmd: String) {
|
||||
log("-> AT$cmd")
|
||||
io.write("AT$cmd\r".toByteArray())
|
||||
}
|
||||
|
||||
/** the next result line (the command's echo, and anything else that isn't one, passed over) */
|
||||
fun result(ms: Long): String? {
|
||||
val end = System.currentTimeMillis() + ms
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.fax
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import com.neodesktop.dmodem.bridge.Bridges
|
||||
import com.neodesktop.dmodem.modem.ModemState
|
||||
import com.neodesktop.dmodem.settings.FaxSettings
|
||||
import com.neodesktop.dmodem.settings.FaxSettingsStore
|
||||
import com.neodesktop.dmodem.terminal.JsonListStore
|
||||
import com.neodesktop.dmodem.terminal.TerminalLink
|
||||
import com.neodesktop.dmodem.transfer.DownloadsIncoming
|
||||
import com.neodesktop.dmodem.transfer.TransferCancelled
|
||||
import com.neodesktop.dmodem.transfer.TransferIo
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/** a fax sent or received, for the list of them */
|
||||
data class FaxRecord(
|
||||
val id: String,
|
||||
val time: Long,
|
||||
val sending: Boolean,
|
||||
/** the number dialled (sending), the other machine's identity */
|
||||
val number: String,
|
||||
val remote: String,
|
||||
val pages: Int,
|
||||
/** "": it went through; else why not */
|
||||
val result: String,
|
||||
/** the received fax's file in Downloads (its name) */
|
||||
val file: String = "",
|
||||
) {
|
||||
fun toJson(): JSONObject = JSONObject().put("id", id).put("time", time).put("sending", sending).put("number", number)
|
||||
.put("remote", remote).put("pages", pages).put("result", result).put("file", file)
|
||||
|
||||
companion object {
|
||||
fun fromJson(o: JSONObject) = FaxRecord(
|
||||
o.getString("id"), o.getLong("time"), o.getBoolean("sending"), o.optString("number"), o.optString("remote"),
|
||||
o.optInt("pages"), o.optString("result"), o.optString("file"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fax calls on the modem: a document sent to a number, a ringing call
|
||||
* answered as a fax (by hand, or each one when the settings say so),
|
||||
* the received pages saved as a PDF in Downloads/D-Modem. A call has the
|
||||
* modem's DTE to itself while it lasts (the terminal and the bridges
|
||||
* see nothing of it).
|
||||
*/
|
||||
object Fax {
|
||||
/** what the fax call is doing; null when none is (or has been) */
|
||||
data class State(
|
||||
val sending: Boolean,
|
||||
val progress: FaxProgress,
|
||||
val result: String? = null,
|
||||
/** the received fax's file name (in Downloads/D-Modem) */
|
||||
val file: String = "",
|
||||
val number: String = "",
|
||||
) {
|
||||
val running: Boolean get() = result == null
|
||||
}
|
||||
|
||||
private val _state = MutableStateFlow<State?>(null)
|
||||
val state: StateFlow<State?> = _state.asStateFlow()
|
||||
|
||||
@Volatile private var io: TransferIo? = null
|
||||
@Volatile private var thread: Thread? = null
|
||||
private var history: JsonListStore<FaxRecord>? = null
|
||||
private var watching = false
|
||||
|
||||
fun history(context: Context): JsonListStore<FaxRecord> = synchronized(this) {
|
||||
history ?: JsonListStore(File(context.applicationContext.filesDir, "faxes.json"), FaxRecord::toJson, FaxRecord::fromJson, FaxRecord::id)
|
||||
.also { history = it }
|
||||
}
|
||||
|
||||
val running: Boolean get() = _state.value?.running == true
|
||||
|
||||
/** why a fax can't start now, or null */
|
||||
private fun busy(): String? = when {
|
||||
ModemState.run.value != ModemState.Run.RUNNING -> "the modem is off"
|
||||
running -> "a fax call is going on"
|
||||
ModemState.status.value.offhook -> "the modem is in a call"
|
||||
Bridges.serial.client.value != null -> "the modem is in use by ${Bridges.serial.client.value?.name}"
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** [uris]' pages faxed to [number]: null when it's started, else why it can't */
|
||||
fun send(context: Context, number: String, uris: List<Uri>): String? {
|
||||
busy()?.let { return it }
|
||||
if (number.isBlank()) return "no number"
|
||||
val app = context.applicationContext
|
||||
start(sending = true, number = number.trim()) { c, s ->
|
||||
update(FaxProgress("Preparing the document"))
|
||||
val pages = uris.flatMap { FaxDocuments.pages(app, it, s.fine) }
|
||||
if (pages.isEmpty()) throw FaxException("the document has no pages")
|
||||
update(FaxProgress("Dialling $number", total = pages.size))
|
||||
val r = c.command("D$number", 120_000)
|
||||
if (r != "CONNECT") throw FaxException(dialResult(r))
|
||||
val p = T30.send(c, pages, s.ident, rates) { update(it) }
|
||||
record(app, true, number, p, "", "")
|
||||
p to ""
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** the call ringing now answered as a fax: null when it's started, else why it can't */
|
||||
fun answer(context: Context): String? {
|
||||
busy()?.takeIf { !it.startsWith("the modem is in a call") }?.let { return it }
|
||||
val app = context.applicationContext
|
||||
start(sending = false, number = "") { c, s ->
|
||||
update(FaxProgress("Answering"))
|
||||
val r = c.command("A", 30_000)
|
||||
if (r != "CONNECT") throw FaxException(if (r == null) "no fax answered" else "no fax: $r")
|
||||
val got = ArrayList<FaxPage>()
|
||||
val p = try {
|
||||
T30.receive(c, s.ident, rates, { update(it) }) { pg, _ -> got.add(pg) }
|
||||
} catch (e: IOException) {
|
||||
// the pages that came are kept
|
||||
if (got.isEmpty()) throw e
|
||||
FaxProgress("Received part", pages = got.size)
|
||||
}
|
||||
val name = save(app, got)
|
||||
record(app, false, "", p, "", name)
|
||||
p to name
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** the call stopped (hung up) */
|
||||
fun cancel() {
|
||||
io?.cancel("cancelled")
|
||||
}
|
||||
|
||||
/** (for the screenshots: a call's state shown) */
|
||||
internal fun show(s: State?) {
|
||||
_state.value = s
|
||||
}
|
||||
|
||||
fun dismiss() {
|
||||
if (!running) _state.value = null
|
||||
}
|
||||
|
||||
private var rates: List<T30.Rate> = emptyList()
|
||||
|
||||
private fun update(p: FaxProgress) {
|
||||
_state.value = _state.value?.copy(progress = p)
|
||||
}
|
||||
|
||||
private fun dialResult(r: String?) = when (r) {
|
||||
null -> "no answer"
|
||||
"BUSY" -> "busy"
|
||||
"NO ANSWER" -> "no answer"
|
||||
"NO CARRIER" -> "no fax machine answered"
|
||||
"NO DIALTONE", "NO DIAL TONE" -> "no line"
|
||||
else -> r.lowercase()
|
||||
}
|
||||
|
||||
/** a call on the modem, its DTE ours while it lasts: [body] given the class 1 modem, set up */
|
||||
private fun start(sending: Boolean, number: String, body: (Class1, FaxSettings) -> Pair<FaxProgress, String>) {
|
||||
val hub = ModemState.dte
|
||||
lateinit var listener: TerminalLink.Listener
|
||||
val line = TransferIo { b -> if (!hub.writeAs(listener, b)) throw IOException("the modem has gone") }
|
||||
listener = TerminalLink.Listener { d, n -> line.feed(d, 0, n) }
|
||||
if (!hub.claim(listener)) {
|
||||
_state.value = State(sending, FaxProgress(), "the modem is in use", number = number)
|
||||
return
|
||||
}
|
||||
io = line
|
||||
_state.value = State(sending, FaxProgress("Starting"), number = number)
|
||||
thread = Thread({
|
||||
var result = ""
|
||||
var file = ""
|
||||
var last = FaxProgress()
|
||||
val c = Class1(line) { ModemState.log.add("fax: $it") }
|
||||
try {
|
||||
val s = runBlocking { FaxSettingsStore(contextOrThrow()).current() }
|
||||
// (X3: a SIP line has no dial tone to wait for)
|
||||
if (c.command("E0V1X3") != "OK" || c.command("+FCLASS=1") != "OK") throw FaxException("the modem has no fax mode")
|
||||
rates = T30.modemRates(c, s.maxBps)
|
||||
val (p, f) = body(c, s)
|
||||
last = p
|
||||
file = f
|
||||
} catch (e: TransferCancelled) {
|
||||
result = "cancelled"
|
||||
} catch (e: IOException) {
|
||||
result = e.message ?: e.toString()
|
||||
} catch (e: RuntimeException) {
|
||||
result = e.toString()
|
||||
} finally {
|
||||
// the call over, the modem back to data: around the cancel (the line's own writes refused then)
|
||||
fun raw(s: String) { hub.writeAs(listener, s.toByteArray()) }
|
||||
raw("\u0018")
|
||||
Thread.sleep(300)
|
||||
raw("ATH\r")
|
||||
Thread.sleep(500)
|
||||
raw("AT+FCLASS=0\r")
|
||||
Thread.sleep(300)
|
||||
io = null
|
||||
hub.release(listener)
|
||||
val st = _state.value
|
||||
if (result.isNotEmpty() && st != null) {
|
||||
contextOrNull()?.let { record(it, st.sending, st.number, st.progress, result, "") }
|
||||
}
|
||||
_state.value = st?.copy(progress = if (result.isEmpty()) last else st.progress, result = result, file = file)
|
||||
}
|
||||
}, "fax").apply { isDaemon = true; start() }
|
||||
}
|
||||
|
||||
// (the application's context, for the settings and the files: set by init)
|
||||
@android.annotation.SuppressLint("StaticFieldLeak")
|
||||
private var app: Context? = null
|
||||
|
||||
private fun contextOrThrow(): Context = app ?: throw FaxException("not set up")
|
||||
private fun contextOrNull(): Context? = app
|
||||
|
||||
/** the application's context; ringing calls watched for (answered as faxes when the settings say so) */
|
||||
fun init(context: Context) {
|
||||
app = context.applicationContext
|
||||
if (watching) return
|
||||
watching = true
|
||||
ModemState.dte.addListener(TerminalLink.Listener { data, n ->
|
||||
if (String(data, 0, n, Charsets.ISO_8859_1).contains("RING") && !running) {
|
||||
val a = app ?: return@Listener
|
||||
val s = runCatching { runBlocking { FaxSettingsStore(a).current() } }.getOrNull() ?: return@Listener
|
||||
if (s.answer) Thread { answer(a) }.start()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private fun save(context: Context, pages: List<FaxPage>): String {
|
||||
val name = "fax-" + SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date()) + ".pdf"
|
||||
val into = DownloadsIncoming(context)
|
||||
val (out, actual) = into.create(name, -1)
|
||||
try {
|
||||
out.use { FaxPdf.write(pages, it) }
|
||||
into.done(actual, System.currentTimeMillis() / 1000)
|
||||
} catch (e: IOException) {
|
||||
into.abandon(actual)
|
||||
throw e
|
||||
}
|
||||
return actual
|
||||
}
|
||||
|
||||
private fun record(context: Context, sending: Boolean, number: String, p: FaxProgress, result: String, file: String) {
|
||||
history(context).put(
|
||||
FaxRecord(java.util.UUID.randomUUID().toString(), System.currentTimeMillis(), sending, number, p.remote, p.pages, result, file),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.fax
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Rect
|
||||
import android.graphics.Typeface
|
||||
import android.graphics.pdf.PdfRenderer
|
||||
import android.net.Uri
|
||||
import java.io.IOException
|
||||
|
||||
/**
|
||||
* Documents as fax pages, and fax pages as a document: a PDF's pages,
|
||||
* an image, plain text, each scaled to the fax's width (1728 pels, 204
|
||||
* to the inch; 196 or 98 lines to the inch down) and made black and
|
||||
* white (text and PDFs at a threshold, photographs dithered). (Received
|
||||
* pages become a PDF in [FaxPdf].)
|
||||
*/
|
||||
object FaxDocuments {
|
||||
|
||||
/** the pages of the document at [uri] (a PDF, an image, text) */
|
||||
fun pages(context: Context, uri: Uri, fine: Boolean): List<FaxPage> {
|
||||
val r = context.contentResolver
|
||||
val type = r.getType(uri) ?: ""
|
||||
val name = uri.lastPathSegment.orEmpty().lowercase()
|
||||
return when {
|
||||
type == "application/pdf" || name.endsWith(".pdf") -> pdf(context, uri, fine)
|
||||
type.startsWith("image/") || Regex("\\.(png|jpe?g|gif|bmp|webp)$").containsMatchIn(name) -> {
|
||||
val bmp = r.openInputStream(uri)?.use { decodeScaled(it.readBytes()) } ?: throw IOException("can't read the image")
|
||||
listOf(fromBitmap(bmp, fine, dither = true)).also { bmp.recycle() }
|
||||
}
|
||||
type.startsWith("text/") || name.endsWith(".txt") -> {
|
||||
val text = r.openInputStream(uri)?.use { it.readBytes().decodeToString() } ?: throw IOException("can't read the text")
|
||||
text(text, fine)
|
||||
}
|
||||
else -> throw IOException("not a PDF, an image or text: ${type.ifEmpty { name }}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun pdf(context: Context, uri: Uri, fine: Boolean): List<FaxPage> {
|
||||
val fd = context.contentResolver.openFileDescriptor(uri, "r") ?: throw IOException("can't open the PDF")
|
||||
return fd.use { pfd ->
|
||||
PdfRenderer(pfd).use { pdf ->
|
||||
(0 until pdf.pageCount).map { i ->
|
||||
pdf.openPage(i).use { pg ->
|
||||
// the page at the fax's width; its height in the fax's lines
|
||||
val h = (pg.height.toDouble() / pg.width * FaxPage.WIDTH * lpi(fine) / 204).toInt().coerceIn(1, 4000)
|
||||
val bmp = Bitmap.createBitmap(FaxPage.WIDTH, h, Bitmap.Config.ARGB_8888)
|
||||
bmp.eraseColor(Color.WHITE)
|
||||
pg.render(bmp, null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT)
|
||||
threshold(bmp, fine).also { bmp.recycle() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun lpi(fine: Boolean) = if (fine) 196 else 98
|
||||
|
||||
/** an image decoded no bigger than it need be for a fax page */
|
||||
private fun decodeScaled(b: ByteArray): Bitmap {
|
||||
val o = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeByteArray(b, 0, b.size, o)
|
||||
var s = 1
|
||||
while (o.outWidth / (s * 2) >= FaxPage.WIDTH) s *= 2
|
||||
return BitmapFactory.decodeByteArray(b, 0, b.size, BitmapFactory.Options().apply { inSampleSize = s })
|
||||
?: throw IOException("not an image")
|
||||
}
|
||||
|
||||
/** [b] as a page: scaled to the width, black and white ([dither]: for photographs) */
|
||||
fun fromBitmap(b: Bitmap, fine: Boolean, dither: Boolean): FaxPage {
|
||||
val h = (b.height.toDouble() / b.width * FaxPage.WIDTH * lpi(fine) / 204).toInt().coerceIn(1, 4000)
|
||||
val s = Bitmap.createBitmap(FaxPage.WIDTH, h, Bitmap.Config.ARGB_8888)
|
||||
val c = Canvas(s)
|
||||
c.drawColor(Color.WHITE)
|
||||
c.drawBitmap(b, Rect(0, 0, b.width, b.height), Rect(0, 0, FaxPage.WIDTH, h), Paint(Paint.FILTER_BITMAP_FLAG))
|
||||
return (if (dither) dither(s, fine) else threshold(s, fine)).also { s.recycle() }
|
||||
}
|
||||
|
||||
private fun luma(p: Int): Int = (Color.red(p) * 299 + Color.green(p) * 587 + Color.blue(p) * 114) / 1000
|
||||
|
||||
private fun threshold(b: Bitmap, fine: Boolean): FaxPage {
|
||||
val page = FaxPage(b.width, b.height, fine)
|
||||
val row = IntArray(b.width)
|
||||
for (y in 0 until b.height) {
|
||||
b.getPixels(row, 0, b.width, 0, y, b.width, 1)
|
||||
for (x in 0 until b.width) if (Color.alpha(row[x]) > 127 && luma(row[x]) < 128) page.set(x, y, true)
|
||||
}
|
||||
return page
|
||||
}
|
||||
|
||||
/** Floyd–Steinberg: the greys as dots */
|
||||
private fun dither(b: Bitmap, fine: Boolean): FaxPage {
|
||||
val w = b.width
|
||||
val page = FaxPage(w, b.height, fine)
|
||||
val row = IntArray(w)
|
||||
var cur = IntArray(w + 2)
|
||||
var next = IntArray(w + 2)
|
||||
for (y in 0 until b.height) {
|
||||
b.getPixels(row, 0, w, 0, y, w, 1)
|
||||
for (x in 0 until w) cur[x + 1] += luma(row[x]) * 16
|
||||
for (x in 0 until w) {
|
||||
val v = cur[x + 1]
|
||||
val black = v < 128 * 16
|
||||
if (black) page.set(x, y, true)
|
||||
val e = v - (if (black) 0 else 255 * 16)
|
||||
cur[x + 2] += e * 7 / 16
|
||||
next[x] += e * 3 / 16
|
||||
next[x + 1] += e * 5 / 16
|
||||
next[x + 2] += e / 16
|
||||
}
|
||||
val t = cur; cur = next; next = t
|
||||
java.util.Arrays.fill(next, 0)
|
||||
}
|
||||
return page
|
||||
}
|
||||
|
||||
/** plain text on A4 pages: monospaced, 66 lines and 80 columns to a page */
|
||||
fun text(text: String, fine: Boolean): List<FaxPage> {
|
||||
val lines = text.replace("\r\n", "\n").replace('\t', ' ').split('\n').flatMap { l ->
|
||||
if (l.isEmpty()) listOf("") else l.chunked(80)
|
||||
}
|
||||
val rows = FaxPage.a4Rows(fine)
|
||||
val perPage = 66
|
||||
return lines.chunked(perPage).ifEmpty { listOf(emptyList()) }.map { chunk ->
|
||||
// (drawn at fine resolution's proportions, then as the page's)
|
||||
val bmp = Bitmap.createBitmap(FaxPage.WIDTH, FaxPage.a4Rows(true), Bitmap.Config.ARGB_8888)
|
||||
val c = Canvas(bmp)
|
||||
c.drawColor(Color.WHITE)
|
||||
val p = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
typeface = Typeface.MONOSPACE
|
||||
color = Color.BLACK
|
||||
textSize = 1500f / 80 / 0.6f
|
||||
}
|
||||
val top = 120f
|
||||
val step = (FaxPage.a4Rows(true) - 2 * top) / perPage
|
||||
for ((i, l) in chunk.withIndex()) c.drawText(l, 110f, top + (i + 1) * step, p)
|
||||
val page = if (fine) threshold(bmp, true) else {
|
||||
val half = Bitmap.createScaledBitmap(bmp, FaxPage.WIDTH, rows, true)
|
||||
threshold(half, false).also { half.recycle() }
|
||||
}
|
||||
bmp.recycle()
|
||||
page
|
||||
}
|
||||
}
|
||||
|
||||
/** a page as a bitmap, black on white */
|
||||
fun toBitmap(p: FaxPage): Bitmap {
|
||||
val bmp = Bitmap.createBitmap(p.width, p.rows.coerceAtLeast(1), Bitmap.Config.ARGB_8888)
|
||||
val row = IntArray(p.width)
|
||||
for (y in 0 until p.rows) {
|
||||
for (x in 0 until p.width) row[x] = if (p.black(x, y)) Color.BLACK else Color.WHITE
|
||||
bmp.setPixels(row, 0, p.width, 0, y, p.width, 1)
|
||||
}
|
||||
return bmp
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.fax
|
||||
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.OutputStream
|
||||
|
||||
/**
|
||||
* Fax pages as a PDF, as fax software has them: each page an image in
|
||||
* the fax's own coding (CCITTFaxDecode, T.4 MH with its EOLs), the size
|
||||
* the fax had it (215 mm across, its rows at 196 or 98 to the inch).
|
||||
* Small, and the pels exactly those that came.
|
||||
*/
|
||||
object FaxPdf {
|
||||
fun write(pages: List<FaxPage>, out: OutputStream) {
|
||||
val o = ByteArrayOutputStream()
|
||||
val offsets = ArrayList<Int>()
|
||||
fun obj(body: ByteArray) {
|
||||
offsets.add(o.size())
|
||||
o.write("${offsets.size} 0 obj\n".toByteArray())
|
||||
o.write(body)
|
||||
o.write("\nendobj\n".toByteArray())
|
||||
}
|
||||
fun obj(s: String) = obj(s.toByteArray(Charsets.ISO_8859_1))
|
||||
fun stream(dict: String, data: ByteArray) =
|
||||
obj("<< $dict /Length ${data.size} >>\nstream\n".toByteArray() + data + "\nendstream".toByteArray())
|
||||
|
||||
o.write("%PDF-1.4\n%âãÏÓ\n".toByteArray(Charsets.ISO_8859_1))
|
||||
// 1: the catalogue, 2: the page tree; then each page's three: the page, its contents, its image
|
||||
val kids = pages.indices.joinToString(" ") { "${3 + it * 3} 0 R" }
|
||||
obj("<< /Type /Catalog /Pages 2 0 R >>")
|
||||
obj("<< /Type /Pages /Kids [$kids] /Count ${pages.size} >>")
|
||||
for ((i, p) in pages.withIndex()) {
|
||||
val page = 3 + i * 3
|
||||
val w = "%.2f".format(java.util.Locale.ROOT, p.width / 204.0 * 72)
|
||||
val h = "%.2f".format(java.util.Locale.ROOT, p.rows.coerceAtLeast(1).toDouble() / (if (p.fine) 196 else 98) * 72)
|
||||
obj("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 $w $h] /Resources << /XObject << /Im0 ${page + 2} 0 R >> >> /Contents ${page + 1} 0 R >>")
|
||||
stream("", "q $w 0 0 $h 0 0 cm /Im0 Do Q".toByteArray())
|
||||
// (the fax's bits, the first in the bottom bit, the other way round: PDF's first in the top bit)
|
||||
val data = T4.encode(p).also { d -> for (k in d.indices) d[k] = reverse(d[k]) }
|
||||
stream(
|
||||
"/Type /XObject /Subtype /Image /Width ${p.width} /Height ${p.rows} /ColorSpace /DeviceGray /BitsPerComponent 1 " +
|
||||
"/Filter /CCITTFaxDecode /DecodeParms << /K 0 /Columns ${p.width} /Rows ${p.rows} /EndOfLine true >>",
|
||||
data,
|
||||
)
|
||||
}
|
||||
val xref = o.size()
|
||||
o.write("xref\n0 ${offsets.size + 1}\n0000000000 65535 f \n".toByteArray())
|
||||
for (off in offsets) o.write("%010d 00000 n \n".format(off).toByteArray())
|
||||
o.write("trailer\n<< /Size ${offsets.size + 1} /Root 1 0 R >>\nstartxref\n$xref\n%%EOF\n".toByteArray())
|
||||
out.write(o.toByteArray())
|
||||
}
|
||||
|
||||
private fun reverse(b: Byte): Byte {
|
||||
var c = b.toInt() and 0xff
|
||||
c = (c and 0xf0 shr 4) or (c and 0x0f shl 4)
|
||||
c = (c and 0xcc shr 2) or (c and 0x33 shl 2)
|
||||
c = (c and 0xaa shr 1) or (c and 0x55 shl 1)
|
||||
return c.toByte()
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,27 @@ import java.util.concurrent.CopyOnWriteArrayList
|
||||
class DteHub : TerminalLink {
|
||||
|
||||
private val listeners = CopyOnWriteArrayList<TerminalLink.Listener>()
|
||||
|
||||
/** who has the modem to itself now (a fax call): only it hears the modem, only it may write */
|
||||
@Volatile private var owner: TerminalLink.Listener? = null
|
||||
|
||||
/** the modem to [l] alone until [release] (false: someone else has it) */
|
||||
@Synchronized
|
||||
fun claim(l: TerminalLink.Listener): Boolean {
|
||||
if (owner != null) return false
|
||||
owner = l
|
||||
return true
|
||||
}
|
||||
|
||||
fun release(l: TerminalLink.Listener) {
|
||||
synchronized(this) { if (owner === l) owner = null }
|
||||
}
|
||||
|
||||
val claimed: Boolean get() = owner != null
|
||||
|
||||
/** octets to the modem from its owner ([claim]) */
|
||||
fun writeAs(l: TerminalLink.Listener, data: ByteArray): Boolean =
|
||||
if (owner === l) writeRaw(data, 0, data.size) else false
|
||||
private val _state = MutableStateFlow<TerminalLink.State>(TerminalLink.State.Closed(null))
|
||||
/** open while a modem is attached */
|
||||
override val state: StateFlow<TerminalLink.State> = _state.asStateFlow()
|
||||
@@ -82,8 +103,11 @@ class DteHub : TerminalLink {
|
||||
|
||||
val attached: Boolean get() = synchronized(outLock) { output != null }
|
||||
|
||||
/** Octets to the modem: false if there is no modem, or it has gone. */
|
||||
/** Octets to the modem: false if there is no modem, or it has gone (or a fax call has it). */
|
||||
override fun write(data: ByteArray, offset: Int, length: Int): Boolean =
|
||||
if (owner != null) false else writeRaw(data, offset, length)
|
||||
|
||||
private fun writeRaw(data: ByteArray, offset: Int, length: Int): Boolean =
|
||||
synchronized(outLock) {
|
||||
val o = output ?: return false
|
||||
try {
|
||||
@@ -107,7 +131,8 @@ class DteHub : TerminalLink {
|
||||
}
|
||||
if (n < 0) break
|
||||
if (n == 0) continue
|
||||
for (l in listeners) l.onData(buf, n)
|
||||
val o = owner
|
||||
if (o != null) o.onData(buf, n) else for (l in listeners) l.onData(buf, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.settings
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.MutablePreferences
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.intPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
|
||||
/** How the modem faxes. */
|
||||
data class FaxSettings(
|
||||
/** this fax machine's number, as the other one is told (its TSI and CSI: digits, + and spaces) */
|
||||
val ident: String = "",
|
||||
/** calls that ring are answered as faxes (else they're the terminal's) */
|
||||
val answer: Boolean = false,
|
||||
/** the rate at most (14400 V.17, 9600 V.29, 4800 V.27ter) */
|
||||
val maxBps: Int = 14400,
|
||||
/** pages sent at 196 lines to the inch (else 98) */
|
||||
val fine: Boolean = true,
|
||||
)
|
||||
|
||||
private val Context.faxStore: DataStore<Preferences> by preferencesDataStore("fax")
|
||||
|
||||
class FaxSettingsStore(private val context: Context) {
|
||||
private object K {
|
||||
val ident = stringPreferencesKey("ident")
|
||||
val answer = booleanPreferencesKey("answer")
|
||||
val maxBps = intPreferencesKey("max_bps")
|
||||
val fine = booleanPreferencesKey("fine")
|
||||
}
|
||||
|
||||
val settings: Flow<FaxSettings> = context.faxStore.data.map { p ->
|
||||
val d = FaxSettings()
|
||||
FaxSettings(p[K.ident] ?: d.ident, p[K.answer] ?: d.answer, p[K.maxBps] ?: d.maxBps, p[K.fine] ?: d.fine)
|
||||
}
|
||||
|
||||
suspend fun current(): FaxSettings = settings.first()
|
||||
|
||||
suspend fun update(change: (FaxSettings) -> FaxSettings) {
|
||||
context.faxStore.edit { p ->
|
||||
val d = FaxSettings()
|
||||
val s = change(FaxSettings(p[K.ident] ?: d.ident, p[K.answer] ?: d.answer, p[K.maxBps] ?: d.maxBps, p[K.fine] ?: d.fine))
|
||||
write(p, s)
|
||||
}
|
||||
}
|
||||
|
||||
private fun write(p: MutablePreferences, s: FaxSettings) {
|
||||
p[K.ident] = s.ident.filter { it.isDigit() || it == '+' || it == ' ' }.take(20)
|
||||
p[K.answer] = s.answer
|
||||
p[K.maxBps] = s.maxBps
|
||||
p[K.fine] = s.fine
|
||||
}
|
||||
}
|
||||
@@ -153,6 +153,9 @@ fun DashboardScreen(
|
||||
}
|
||||
}
|
||||
|
||||
SectionTitle("Fax")
|
||||
FaxSection()
|
||||
|
||||
SectionTitle("Open")
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Shortcut(">_", "Terminal", "VT100 / ANSI-BBS", Modifier.weight(1f), onOpenTerminal)
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.ui
|
||||
|
||||
import android.content.ContentUris
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.provider.MediaStore
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.RadioButton
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.neodesktop.dmodem.fax.Fax
|
||||
import com.neodesktop.dmodem.fax.FaxRecord
|
||||
import com.neodesktop.dmodem.modem.ModemState
|
||||
import com.neodesktop.dmodem.settings.FaxSettingsStore
|
||||
import com.neodesktop.dmodem.transfer.DownloadsIncoming
|
||||
import kotlinx.coroutines.launch
|
||||
import java.text.DateFormat
|
||||
import java.util.Date
|
||||
|
||||
/** The home screen's fax: send one, answer a ringing call as one, the call as it goes, the last few. */
|
||||
@Composable
|
||||
fun FaxSection() {
|
||||
val context = LocalContext.current
|
||||
val state by Fax.state.collectAsStateWithLifecycle()
|
||||
val run by ModemState.run.collectAsStateWithLifecycle()
|
||||
val history by remember { Fax.history(context) }.items.collectAsStateWithLifecycle()
|
||||
var sendDialog by remember { mutableStateOf(false) }
|
||||
val on = run == ModemState.Run.RUNNING
|
||||
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
state?.let { st -> FaxCallCard(st) }
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Button(onClick = { sendDialog = true }, enabled = on && state?.running != true) { Text("Send a fax…") }
|
||||
OutlinedButton(onClick = {
|
||||
Fax.answer(context)?.let { Toast.makeText(context, it, Toast.LENGTH_LONG).show() }
|
||||
}, enabled = on && state?.running != true) { Text("Answer as fax") }
|
||||
}
|
||||
if (!on) Text("The modem is off: start it to fax", style = MaterialTheme.typography.bodySmall)
|
||||
for (r in history.sortedByDescending { it.time }.take(3)) FaxRow(r)
|
||||
}
|
||||
if (sendDialog) {
|
||||
SendFaxDialog(onDismiss = { sendDialog = false }) { number, docs ->
|
||||
sendDialog = false
|
||||
Fax.send(context, number, docs)?.let { Toast.makeText(context, it, Toast.LENGTH_LONG).show() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FaxCallCard(st: Fax.State) {
|
||||
val context = LocalContext.current
|
||||
Card(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
val p = st.progress
|
||||
val what = if (st.sending) "Sending a fax" + (st.number.takeIf { it.isNotEmpty() }?.let { " to $it" } ?: "") else "Receiving a fax"
|
||||
Text(what, style = MaterialTheme.typography.titleSmall)
|
||||
Text(
|
||||
when {
|
||||
st.running -> p.phase
|
||||
st.result == "" -> if (st.sending) "Sent ${p.pages} page(s)" else "Received ${p.pages} page(s)"
|
||||
else -> "Stopped: ${st.result}"
|
||||
} + (if (p.remote.isNotEmpty()) " · ${p.remote}" else "") + (if (p.bps > 0 && st.running) " · ${p.bps} bit/s" else ""),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
if (st.running) {
|
||||
if (p.total > 0) LinearProgressIndicator(progress = { p.pages.toFloat() / p.total }, modifier = Modifier.fillMaxWidth())
|
||||
else LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (st.running) {
|
||||
TextButton(onClick = { Fax.cancel() }) { Text("Cancel") }
|
||||
} else {
|
||||
if (st.file.isNotEmpty()) TextButton(onClick = { open(context, st.file) }) { Text("Open") }
|
||||
TextButton(onClick = { Fax.dismiss() }) { Text("OK") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FaxRow(r: FaxRecord) {
|
||||
val context = LocalContext.current
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable(enabled = r.file.isNotEmpty()) { open(context, r.file) }.padding(vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(if (r.sending) "↗" else "↙", Modifier.padding(end = 12.dp), style = MaterialTheme.typography.titleMedium)
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
(r.number.ifEmpty { r.remote }.ifEmpty { if (r.sending) "Sent" else "Received" }) +
|
||||
" · ${r.pages} page${if (r.pages == 1) "" else "s"}",
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(Date(r.time)) +
|
||||
if (r.result.isNotEmpty()) " · ${r.result}" else "",
|
||||
style = MaterialTheme.typography.bodySmall, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** a number and the documents to fax there */
|
||||
@Composable
|
||||
private fun SendFaxDialog(onDismiss: () -> Unit, onSend: (String, List<Uri>) -> Unit) {
|
||||
var number by remember { mutableStateOf("") }
|
||||
var docs by remember { mutableStateOf<List<Uri>>(emptyList()) }
|
||||
val pick = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { docs = docs + it }
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("Send a fax") },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OutlinedTextField(
|
||||
value = number, onValueChange = { number = it }, label = { Text("Fax number") }, singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone), modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
OutlinedButton(onClick = { pick.launch(arrayOf("application/pdf", "image/*", "text/plain")) }) {
|
||||
Text(if (docs.isEmpty()) "Pick a PDF, image or text…" else "Add more…")
|
||||
}
|
||||
for (d in docs) Text(d.lastPathSegment?.substringAfterLast('/') ?: d.toString(), maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
},
|
||||
confirmButton = { Button(onClick = { onSend(number, docs) }, enabled = number.isNotBlank() && docs.isNotEmpty()) { Text("Send") } },
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
|
||||
)
|
||||
}
|
||||
|
||||
/** a received fax (by its name in Downloads/D-Modem) opened in a PDF viewer */
|
||||
private fun open(context: Context, name: String) {
|
||||
val uri: Uri? = if (Build.VERSION.SDK_INT >= 29) {
|
||||
context.contentResolver.query(
|
||||
MediaStore.Downloads.EXTERNAL_CONTENT_URI, arrayOf(MediaStore.MediaColumns._ID),
|
||||
"${MediaStore.MediaColumns.DISPLAY_NAME} = ?", arrayOf(name), null,
|
||||
)?.use { c -> if (c.moveToFirst()) ContentUris.withAppendedId(MediaStore.Downloads.EXTERNAL_CONTENT_URI, c.getLong(0)) else null }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
if (uri == null) {
|
||||
Toast.makeText(context, "$name is in ${DownloadsIncoming.where(context)}", Toast.LENGTH_LONG).show()
|
||||
return
|
||||
}
|
||||
runCatching {
|
||||
context.startActivity(Intent(Intent.ACTION_VIEW).setDataAndType(uri, "application/pdf").addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION))
|
||||
}.onFailure { Toast.makeText(context, "No app to open PDFs", Toast.LENGTH_LONG).show() }
|
||||
}
|
||||
|
||||
/** The settings' fax section: this machine's number, answering calls as faxes, the resolution, the rate. */
|
||||
@Composable
|
||||
fun FaxSettingsSection() {
|
||||
val context = LocalContext.current
|
||||
val store = remember { FaxSettingsStore(context.applicationContext) }
|
||||
val scope = rememberCoroutineScope()
|
||||
val current by store.settings.collectAsStateWithLifecycle(initialValue = null)
|
||||
val s = current ?: return
|
||||
var ident by remember(s.ident) { mutableStateOf(s.ident) }
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text("Fax", style = MaterialTheme.typography.titleMedium)
|
||||
OutlinedTextField(
|
||||
value = ident,
|
||||
onValueChange = { v ->
|
||||
ident = v.filter { it.isDigit() || it == '+' || it == ' ' }.take(20)
|
||||
scope.launch { store.update { it.copy(ident = ident) } }
|
||||
},
|
||||
label = { Text("This fax's number (sent to the other machine)") }, singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone), modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("Answer calls that ring as faxes", Modifier.weight(1f))
|
||||
Switch(checked = s.answer, onCheckedChange = { v -> scope.launch { store.update { it.copy(answer = v) } } })
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("Fine resolution (196 lines per inch)", Modifier.weight(1f))
|
||||
Switch(checked = s.fine, onCheckedChange = { v -> scope.launch { store.update { it.copy(fine = v) } } })
|
||||
}
|
||||
Text("Fastest rate", style = MaterialTheme.typography.bodyMedium)
|
||||
for ((bps, label) in listOf(14400 to "14400 (V.17)", 9600 to "9600 (V.29)", 4800 to "4800 (V.27ter: poor lines)")) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { scope.launch { store.update { it.copy(maxBps = bps) } } },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
RadioButton(selected = s.maxBps == bps, onClick = null)
|
||||
Text(label, Modifier.padding(start = 8.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -107,6 +107,8 @@ fun SettingsScreen(modifier: Modifier = Modifier, onOpenTerminal: () -> Unit = {
|
||||
androidx.compose.material3.HorizontalDivider(Modifier.padding(vertical = 8.dp))
|
||||
BridgeSection()
|
||||
androidx.compose.material3.HorizontalDivider(Modifier.padding(vertical = 8.dp))
|
||||
FaxSettingsSection()
|
||||
androidx.compose.material3.HorizontalDivider(Modifier.padding(vertical = 8.dp))
|
||||
AppearanceSection()
|
||||
androidx.compose.material3.HorizontalDivider(Modifier.padding(vertical = 8.dp))
|
||||
TerminalSettingsSection()
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.fax
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.os.Environment
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.neodesktop.dmodem.modem.ModemState
|
||||
import com.neodesktop.dmodem.settings.FaxSettingsStore
|
||||
import com.neodesktop.dmodem.transfer.TransferIo
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
import java.util.concurrent.CopyOnWriteArrayList
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* The app's fax ([Fax]) on the modem's DTE hub as the service has it,
|
||||
* the hub on one of fax_line's modems (native-test), our T.30 on the
|
||||
* other: a text document sent, a fax answered and saved as a PDF in
|
||||
* Downloads (the app's folder, before Android 10).
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(sdk = [28])
|
||||
class FaxAppTest {
|
||||
|
||||
private val ctx: Context = ApplicationProvider.getApplicationContext()
|
||||
private var line: Process? = null
|
||||
private val log = CopyOnWriteArrayList<String>()
|
||||
private lateinit var a: String
|
||||
private lateinit var b: String
|
||||
private val closers = ArrayList<() -> Unit>()
|
||||
|
||||
private fun faxLine(): File? = listOfNotNull(System.getenv("DMODEM_FAX_LINE"), "../build-host/fax_line", "build-host/fax_line")
|
||||
.map { File(it) }.firstOrNull { it.canExecute() }
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
val fl = faxLine()
|
||||
assumeTrue("fax_line isn't built (native-test)", fl != null)
|
||||
val p = ProcessBuilder(fl!!.path).redirectErrorStream(true).start()
|
||||
line = p
|
||||
Thread { p.inputStream.bufferedReader().forEachLine { log.add(it) } }.apply { isDaemon = true; start() }
|
||||
val end = System.currentTimeMillis() + 10_000
|
||||
while (System.currentTimeMillis() < end && log.none { it.startsWith("created modemB: ") }) Thread.sleep(20)
|
||||
a = log.first { it.startsWith("created modemA: ") }.substringAfter(": ")
|
||||
b = log.first { it.startsWith("created modemB: ") }.substringAfter(": ")
|
||||
// the app's modem: modemA's pty on the hub, as the service attaches the native modem
|
||||
ProcessBuilder("stty", "-F", a, "raw", "-echo").start().waitFor()
|
||||
ModemState.dte.attach(FileInputStream(a), FileOutputStream(a))
|
||||
ModemState.setRun(ModemState.Run.RUNNING)
|
||||
Fax.init(ctx)
|
||||
runBlocking { FaxSettingsStore(ctx).update { it.copy(ident = "+1 555 0100", fine = true, maxBps = 14400) } }
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
// (both sides' logs, for a failing run: build/fax-app-log.txt)
|
||||
File("build/fax-app-log.txt").writeText((ModemState.log.flow.value + listOf("----") + log).joinToString("\n"))
|
||||
Fax.cancel()
|
||||
closers.forEach { runCatching { it() } }
|
||||
ModemState.dte.detach()
|
||||
ModemState.setRun(ModemState.Run.STOPPED)
|
||||
line?.destroy()
|
||||
line?.waitFor(5, TimeUnit.SECONDS)
|
||||
}
|
||||
|
||||
/** the other fax machine, on modemB */
|
||||
private fun other(): Class1 {
|
||||
ProcessBuilder("stty", "-F", b, "raw", "-echo").start().waitFor()
|
||||
val input = FileInputStream(b)
|
||||
val output = FileOutputStream(b)
|
||||
closers.add { input.close(); output.close() }
|
||||
val io = TransferIo { bytes -> output.write(bytes); output.flush() }
|
||||
Thread {
|
||||
val buf = ByteArray(4096)
|
||||
while (true) {
|
||||
val n = try { input.read(buf) } catch (_: Exception) { -1 }
|
||||
if (n < 0) break
|
||||
io.feed(buf, 0, n)
|
||||
}
|
||||
}.apply { isDaemon = true; start() }
|
||||
return Class1(io) { log.add("B: $it") }
|
||||
}
|
||||
|
||||
private fun waitLog(what: String, secs: Int = 30): Boolean {
|
||||
val end = System.currentTimeMillis() + secs * 1000L
|
||||
while (System.currentTimeMillis() < end) {
|
||||
if (log.any { it.contains(what) }) return true
|
||||
Thread.sleep(5)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun waitDone(secs: Int): Fax.State {
|
||||
val end = System.currentTimeMillis() + secs * 1000L
|
||||
while (System.currentTimeMillis() < end) {
|
||||
val s = Fax.state.value
|
||||
if (s != null && !s.running) return s
|
||||
Thread.sleep(100)
|
||||
}
|
||||
throw AssertionError("still going: ${Fax.state.value}\n" + (ModemState.log.flow.value.takeLast(40) + log.takeLast(40)).joinToString("\n"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aTextDocumentSent() {
|
||||
val doc = File(ctx.cacheDir, "letter.txt").apply {
|
||||
writeText((1..90).joinToString("\n") { "Line $it of a letter faxed from D-Modem, the phone's own modem." })
|
||||
}
|
||||
val c = other()
|
||||
assertEquals("OK", c.command("E0"))
|
||||
assertEquals("OK", c.command("+FCLASS=1"))
|
||||
val rates = T30.modemRates(c)
|
||||
val err = Fax.send(ctx, "5551234", listOf(Uri.fromFile(doc)))
|
||||
assertEquals(null, err)
|
||||
// the app dials; the other machine answers
|
||||
assertTrue(waitLog("modemA: run cmd: ATD5551234"))
|
||||
assertEquals("CONNECT", c.command("A", 30_000))
|
||||
val got = ArrayList<FaxPage>()
|
||||
val rx = T30.receive(c, "+1 555 0199", rates) { pg, _ -> got.add(pg) }
|
||||
val st = waitDone(60)
|
||||
assertEquals(st.toString(), "", st.result)
|
||||
assertEquals("+1 555 0100", rx.remote)
|
||||
assertEquals("+1 555 0199", st.progress.remote)
|
||||
// 90 lines of text: two A4 pages at fine resolution, with text on them
|
||||
assertEquals(2, got.size)
|
||||
for (pg in got) {
|
||||
assertEquals(FaxPage.a4Rows(true), pg.rows)
|
||||
val black = pg.bits.sumOf { Integer.bitCount(it.toInt() and 0xff) }
|
||||
assertTrue("text on the page: $black black pels", black > 20_000)
|
||||
}
|
||||
// in the list of faxes
|
||||
val h = Fax.history(ctx).items.value.last()
|
||||
assertTrue(h.sending)
|
||||
assertEquals("5551234", h.number)
|
||||
assertEquals(2, h.pages)
|
||||
assertEquals("", h.result)
|
||||
// the modem back to data mode, the hub the terminal's again
|
||||
assertTrue(!ModemState.dte.claimed)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFaxAnsweredAndSaved() {
|
||||
val c = other()
|
||||
assertEquals("OK", c.command("E0"))
|
||||
assertEquals("OK", c.command("X3+FCLASS=1"))
|
||||
val rates = T30.modemRates(c)
|
||||
val pages = listOf(T4Test.testPage(true, rows = 800, seed = 7), T4Test.testPage(true, rows = 400, seed = 8))
|
||||
// the other machine dials, the app answers
|
||||
c.send("D5550100")
|
||||
assertEquals(null, Fax.answer(ctx))
|
||||
assertEquals("CONNECT", c.result(60_000))
|
||||
val sent = T30.send(c, pages, "+1 555 0199", rates)
|
||||
assertEquals(2, sent.pages)
|
||||
val st = waitDone(30)
|
||||
assertEquals(st.toString(), "", st.result)
|
||||
assertEquals(2, st.progress.pages)
|
||||
assertEquals("+1 555 0199", st.progress.remote)
|
||||
// the PDF in Downloads (the app's own, before Android 10)
|
||||
val f = File(ctx.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), st.file)
|
||||
assertTrue("$f", f.isFile && f.length() > 1000)
|
||||
assertTrue(String(f.readBytes().copyOf(5)).startsWith("%PDF"))
|
||||
// its pages the ones sent, every pel (poppler reading it, where it's installed)
|
||||
if (File("/usr/bin/pdfimages").canExecute()) {
|
||||
val dir = File(ctx.cacheDir, "pdf-images").apply { mkdirs() }
|
||||
val back = FaxPdfTest.images(f, dir)
|
||||
assertEquals(2, back.size)
|
||||
for (i in pages.indices) org.junit.Assert.assertArrayEquals("page ${i + 1}", pages[i].bits, back[i].bits)
|
||||
}
|
||||
val h = Fax.history(ctx).items.value.last()
|
||||
assertTrue(!h.sending)
|
||||
assertEquals(st.file, h.file)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.fax
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.File
|
||||
|
||||
/** Received pages as a PDF: poppler (pdfimages, pdftoppm) reads them back, every pel as it came. */
|
||||
class FaxPdfTest {
|
||||
@get:Rule
|
||||
val tmp = TemporaryFolder()
|
||||
|
||||
companion object {
|
||||
/** a PDF's pages' images, as poppler's pdfimages takes them out (PBM, 1 black) */
|
||||
fun images(pdf: File, dir: File): List<FaxPage> {
|
||||
val p = ProcessBuilder("pdfimages", pdf.path, File(dir, "img").path).redirectErrorStream(true).start()
|
||||
val out = p.inputStream.readBytes().decodeToString()
|
||||
assertEquals(out, 0, p.waitFor())
|
||||
return dir.listFiles { f -> f.name.startsWith("img-") }!!.sortedBy { it.name }.map { readPbm(it) }
|
||||
}
|
||||
|
||||
fun readPbm(f: File): FaxPage {
|
||||
val d = f.readBytes()
|
||||
var i = 0
|
||||
val fields = ArrayList<String>()
|
||||
while (fields.size < 3) {
|
||||
while (d[i].toInt().toChar().isWhitespace()) i++
|
||||
if (d[i].toInt().toChar() == '#') { while (d[i].toInt() != '\n'.code) i++; continue }
|
||||
val s = i
|
||||
while (!d[i].toInt().toChar().isWhitespace()) i++
|
||||
fields.add(String(d, s, i - s))
|
||||
}
|
||||
i++
|
||||
assertEquals("P4", fields[0])
|
||||
val page = FaxPage(fields[1].toInt(), fields[2].toInt(), true)
|
||||
System.arraycopy(d, i, page.bits, 0, minOf(page.bits.size, d.size - i))
|
||||
return page
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun pagesReadBackExactly() {
|
||||
assumeTrue("poppler-utils isn't installed", File("/usr/bin/pdfimages").canExecute())
|
||||
val pages = listOf(T4Test.testPage(true, rows = 700, seed = 1), T4Test.testPage(false, rows = 350, seed = 2))
|
||||
val f = tmp.newFile("fax.pdf")
|
||||
f.outputStream().use { FaxPdf.write(pages, it) }
|
||||
// small: the fax's own coding
|
||||
assertTrue("${f.length()} bytes", f.length() < 200_000)
|
||||
val back = images(f, tmp.newFolder("img"))
|
||||
assertEquals(2, back.size)
|
||||
for (i in pages.indices) {
|
||||
assertEquals(pages[i].rows, back[i].rows)
|
||||
assertArrayEquals("page ${i + 1}", pages[i].bits, back[i].bits)
|
||||
}
|
||||
// and drawn: pdftoppm at the fax's resolution, the page's size (8.47 in across: 1728 at 204 dpi)
|
||||
val ppm = ProcessBuilder("pdftoppm", "-r", "204", "-mono", "-f", "1", "-l", "1", f.path, File(tmp.root, "page").path)
|
||||
.redirectErrorStream(true).start()
|
||||
assertEquals(0, ppm.waitFor())
|
||||
val drawn = tmp.root.listFiles { x -> x.name.startsWith("page") }!!.single()
|
||||
val head = drawn.readBytes().copyOf(20).decodeToString()
|
||||
assertTrue(head, head.startsWith("P4\n1728 "))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.ui
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import androidx.compose.ui.graphics.asAndroidBitmap
|
||||
import androidx.compose.ui.test.captureToImage
|
||||
import androidx.compose.ui.test.isDialog
|
||||
import androidx.compose.ui.test.junit4.createAndroidComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.onRoot
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.test.performScrollTo
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.neodesktop.dmodem.NativeModem
|
||||
import com.neodesktop.dmodem.fax.Fax
|
||||
import com.neodesktop.dmodem.fax.FaxProgress
|
||||
import com.neodesktop.dmodem.fax.FaxRecord
|
||||
import com.neodesktop.dmodem.modem.ModemState
|
||||
import com.neodesktop.dmodem.settings.ModemSettings
|
||||
import com.neodesktop.dmodem.settings.SettingsStore
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
import java.io.File
|
||||
|
||||
/** The fax on Home (a call going, the last ones), and its settings: build/screens/fax-*.png. */
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(sdk = [35], qualifiers = "w411dp-h891dp-xxhdpi")
|
||||
class FaxShotsTest {
|
||||
@get:Rule
|
||||
val compose = createAndroidComposeRule<MainActivity>()
|
||||
|
||||
private fun shot(name: String, dialog: Boolean = false) {
|
||||
compose.waitForIdle()
|
||||
val node = if (dialog) compose.onNode(isDialog()) else compose.onRoot()
|
||||
val bmp = node.captureToImage().asAndroidBitmap()
|
||||
val dir = File("build/screens").apply { mkdirs() }
|
||||
File(dir, "$name.png").outputStream().use { bmp.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun faxOnHome() {
|
||||
val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()
|
||||
runBlocking { SettingsStore(ctx).save(ModemSettings(user = "alice", password = "x", domain = "sip.example.net")) }
|
||||
ModemState.setRun(ModemState.Run.RUNNING)
|
||||
ModemState.setStatus(ModemState.IDLE)
|
||||
val h = Fax.history(ctx)
|
||||
val now = System.currentTimeMillis()
|
||||
h.put(FaxRecord("1", now - 86_400_000, true, "18005550142", "+1 800 555 0142", 3, ""))
|
||||
h.put(FaxRecord("2", now - 7_200_000, false, "", "+44 20 7946 0958", 2, "", "fax-20261016-101500.pdf"))
|
||||
h.put(FaxRecord("3", now - 600_000, true, "5550100", "", 0, "busy"))
|
||||
Fax.show(Fax.State(true, FaxProgress("Sending page 2 of 3", pages = 1, total = 3, bps = 14400, remote = "+1 800 555 0142"), number = "18005550142"))
|
||||
compose.onNodeWithText("Answer as fax").performScrollTo()
|
||||
shot("fax-1-home")
|
||||
Fax.show(null)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun faxSettings() {
|
||||
compose.onNodeWithText("Settings").performClick()
|
||||
compose.onNodeWithText("Fastest rate").performScrollTo()
|
||||
shot("fax-3-settings")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user