-
Notifications
You must be signed in to change notification settings - Fork 479
/
Copy pathMessages.kt
351 lines (313 loc) Β· 14.4 KB
/
Messages.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
package io.scer.pdfx
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Rect
import android.graphics.pdf.PdfRenderer
import android.os.Build
import android.os.ParcelFileDescriptor
import android.util.Log
import android.util.SparseArray
import android.view.Surface
import androidx.annotation.RequiresApi
import dev.flutter.pigeon.Pigeon
import io.flutter.BuildConfig
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.view.TextureRegistry
import io.scer.pdfx.resources.DocumentRepository
import io.scer.pdfx.resources.PageRepository
import io.scer.pdfx.resources.RepositoryItemNotFoundException
import io.scer.pdfx.utils.CreateRendererException
import io.scer.pdfx.utils.randomFilename
import io.scer.pdfx.utils.toFile
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import java.lang.RuntimeException
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
class Messages(private val binding : FlutterPlugin.FlutterPluginBinding,
private val documents: DocumentRepository,
private val pages: PageRepository) : Pigeon.PdfxApi {
private val textures: SparseArray<TextureRegistry.SurfaceProducer> = SparseArray()
override fun openDocumentData(
message: Pigeon.OpenDataMessage,
result: Pigeon.Result<Pigeon.OpenReply>
) {
val resultResponse = Pigeon.OpenReply()
try {
val documentRenderer = openDataDocument(message.data!!)
val document = documents.register(documentRenderer)
resultResponse.id = document.id
resultResponse.pagesCount = document.pagesCount.toLong()
result.success(resultResponse)
} catch (e: IOException) {
result.error(PdfRendererException("pdf_renderer", "Can't open file", null))
} catch (e: CreateRendererException) {
result.error(PdfRendererException("pdf_renderer", "Can't create PDF renderer", null))
} catch (e: Exception) {
result.error(PdfRendererException("pdf_renderer", "Unknown error", null))
}
}
override fun openDocumentFile(
message: Pigeon.OpenPathMessage,
result: Pigeon.Result<Pigeon.OpenReply>
) {
val resultResponse = Pigeon.OpenReply()
try {
val path = message.path
val documentRenderer = openFileDocument(File(path!!))
val document = documents.register(documentRenderer)
resultResponse.id = document.id
resultResponse.pagesCount = document.pagesCount.toLong()
result.success(resultResponse)
} catch (e: NullPointerException) {
result.error(PdfRendererException("pdf_renderer", "Need call arguments: path", null))
} catch (e: FileNotFoundException) {
result.error(PdfRendererException("pdf_renderer", "File not found", null))
} catch (e: IOException) {
result.error(PdfRendererException("pdf_renderer", "Can't open file", null))
} catch (e: CreateRendererException) {
result.error(PdfRendererException("pdf_renderer", "Can't create PDF renderer", null))
} catch (e: Exception) {
result.error(PdfRendererException("pdf_renderer", "Unknown error", null))
}
}
override fun openDocumentAsset(
message: Pigeon.OpenPathMessage,
result: Pigeon.Result<Pigeon.OpenReply>
) {
val resultResponse = Pigeon.OpenReply()
try {
val path = message.path
val documentRenderer = openAssetDocument(path!!)
val document = documents.register(documentRenderer)
resultResponse.id = document.id
resultResponse.pagesCount = document.pagesCount.toLong()
result.success(resultResponse)
} catch (e: NullPointerException) {
result.error(PdfRendererException("pdf_renderer", "Need call arguments: path", null))
} catch (e: FileNotFoundException) {
result.error(PdfRendererException("pdf_renderer", "File not found", null))
} catch (e: IOException) {
result.error(PdfRendererException("pdf_renderer", "Can't open file", null))
} catch (e: CreateRendererException) {
result.error(PdfRendererException("pdf_renderer", "Can't create PDF renderer", null))
} catch (e: Exception) {
result.error(PdfRendererException("pdf_renderer", "Unknown error", null))
}
}
override fun closeDocument(message: Pigeon.IdMessage) {
try {
val id = message.id
documents.close(id!!)
} catch (e: NullPointerException) {
throw PdfRendererException("pdf_renderer", "Need call arguments: id!", null)
} catch (e: RepositoryItemNotFoundException) {
throw PdfRendererException("pdf_renderer", "Document not exist in documents repository", null)
} catch (e: Exception) {
throw PdfRendererException("pdf_renderer", "Unknown error", null)
}
}
override fun getPage(
message: Pigeon.GetPageMessage,
result: Pigeon.Result<Pigeon.GetPageReply>
) {
val resultResponse = Pigeon.GetPageReply()
try {
val documentId = message.documentId!!
val pageNumber = message.pageNumber!!.toInt()
if (message.autoCloseAndroid!!) {
documents.get(documentId).openPage(pageNumber).use { page ->
resultResponse.width = page.width.toDouble()
resultResponse.height = page.height.toDouble()
}
} else {
val pageRenderer = documents.get(documentId).openPage(pageNumber)
val page = pages.register(documentId, pageRenderer)
resultResponse.id = page.id
resultResponse.width = page.width.toDouble()
resultResponse.height = page.height.toDouble()
}
result.success(resultResponse)
} catch (e: NullPointerException) {
result.error(PdfRendererException("pdf_renderer", "Need call arguments: documentId & page!", null))
} catch (e: RepositoryItemNotFoundException) {
result.error(PdfRendererException("pdf_renderer", "Document not exist in documents", null))
} catch (e: Exception) {
result.error(PdfRendererException("pdf_renderer", "Unknown error", null))
}
}
override fun renderPage(
message: Pigeon.RenderPageMessage,
result: Pigeon.Result<Pigeon.RenderPageReply>
) {
val resultResponse = Pigeon.RenderPageReply()
try {
val pageId = message.pageId!!
val width = message.width!!.toInt()
val height = message.height!!.toInt()
val format = message.format?.toInt() ?: 1 //0 Bitmap.CompressFormat.PNG
val forPrint = message.forPrint ?: false;
val backgroundColor = message.backgroundColor
val color = if (backgroundColor != null) Color.parseColor(backgroundColor) else Color.TRANSPARENT
val crop = message.crop!!
val cropX = if (crop) message.cropX!!.toInt() else 0
val cropY = if (crop) message.cropY!!.toInt() else 0
val cropH = if (crop) message.cropHeight!!.toInt() else 0
val cropW = if (crop) message.cropWidth!!.toInt() else 0
val quality = message.quality?.toInt() ?: 100
val page = pages.get(pageId)
val tempOutFileExtension = when (format) {
0 -> "jpg"
1 -> "png"
2 -> "webp"
else -> "jpg"
}
val tempOutFolder = File(binding.applicationContext.cacheDir, "pdf_renderer_cache")
tempOutFolder.mkdirs()
val tempOutFile = File(tempOutFolder, "$randomFilename.$tempOutFileExtension")
val pageImage = page.render(tempOutFile, width, height, color, format, crop, cropX, cropY, cropW, cropH, quality, forPrint)
resultResponse.path = pageImage.path
resultResponse.width = pageImage.width.toLong()
resultResponse.height = pageImage.height.toLong()
result.success(resultResponse)
} catch (e: Exception) {
result.error(PdfRendererException("pdf_renderer", "Unexpected error", e))
}
}
override fun closePage(message: Pigeon.IdMessage) {
try {
val id = message.id!!
pages.close(id)
} catch (e: NullPointerException) {
throw PdfRendererException("pdf_renderer", "Need call arguments: id!", null)
} catch (e: RepositoryItemNotFoundException) {
throw PdfRendererException("pdf_renderer", "Page not exist in pages repository", null)
} catch (e: Exception) {
throw PdfRendererException("pdf_renderer", "Unknown error", null)
}
}
override fun registerTexture(): Pigeon.RegisterTextureReply {
val surfaceTexture = binding.textureRegistry.createSurfaceProducer()
val id = surfaceTexture.id().toInt()
textures.put(id, surfaceTexture)
val result = Pigeon.RegisterTextureReply()
result.id = id.toLong()
return result
}
override fun updateTexture(
message: Pigeon.UpdateTextureMessage,
result: Pigeon.Result<Void>
) {
val texId = message.textureId!!.toInt()
val pageNumber = message.pageNumber!!.toInt()
val tex = textures[texId]
val document = documents.get(message.documentId!!)
document.openPage(pageNumber).use { page ->
val fullWidth = message.fullWidth ?: page.width.toDouble()
val fullHeight = message.fullHeight ?: page.height.toDouble()
val destX = message.destinationX!!.toInt()
val destY = message.destinationY!!.toInt()
val width = message.width!!.toInt()
val height = message.height!!.toInt()
val srcX = message.sourceX!!.toInt()
val srcY = message.sourceY!!.toInt()
val backgroundColor = message.backgroundColor
if (width <= 0 || height <= 0) {
result.error(PdfRendererException("pdf_renderer", "updateTexture width/height == 0", null))
}
val mat = Matrix()
mat.setValues(floatArrayOf((fullWidth / page.width).toFloat(), 0f, -srcX.toFloat(), 0f, (fullHeight / page.height).toFloat(), -srcY.toFloat(), 0f, 0f, 1f))
try {
val bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
if (backgroundColor != null) {
bmp.eraseColor(Color.parseColor(backgroundColor))
}
page.render(bmp, null, mat, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
val texWidth = message.textureWidth!!.toInt()
val texHeight = message.textureHeight!!.toInt()
if (texWidth != 0 && texHeight != 0) {
tex.setSize(texWidth, texHeight)
}
tex.surface.use {
val canvas = it.lockCanvas(Rect(destX, destY, width, height))
canvas.drawBitmap(bmp, destX.toFloat(), destY.toFloat(), null)
bmp.recycle()
it.unlockCanvasAndPost(canvas)
}
result.success(null)
} catch (e: Exception) {
result.error(PdfRendererException("pdf_renderer", "updateTexture Unknown error", null))
}
}
}
override fun resizeTexture(
message: Pigeon.ResizeTextureMessage,
result: Pigeon.Result<Void>
) {
val texId = message.textureId!!.toInt()
val width = message.width!!.toInt()
val height = message.height!!.toInt()
val tex = textures[texId]
tex?.setSize(width, height)
result.success(null)
}
override fun unregisterTexture(message: Pigeon.UnregisterTextureMessage) {
val id = message.id!!.toInt()
val tex = textures[id]
tex?.release()
textures.remove(id)
}
private fun openDataDocument(data: ByteArray): Pair<ParcelFileDescriptor, PdfRenderer> {
val tempDataFile = File(binding.applicationContext.cacheDir, "$randomFilename.pdf")
if (!tempDataFile.exists()) {
tempDataFile.writeBytes(data)
}
Log.d("pdf_renderer", "OpenDataDocument. Created file: " + tempDataFile.path)
return openFileDocument(tempDataFile)
}
private fun openAssetDocument(assetPath: String): Pair<ParcelFileDescriptor, PdfRenderer> {
val fullAssetPath = binding.flutterAssets.getAssetFilePathByName(assetPath)
val tempAssetFile = File(binding.applicationContext.cacheDir, "$randomFilename.pdf")
if (!tempAssetFile.exists()) {
val inputStream = binding.applicationContext.assets.open(fullAssetPath)
inputStream.toFile(tempAssetFile)
inputStream.close()
}
Log.d("pdf_renderer", "OpenAssetDocument. Created file: " + tempAssetFile.path)
return openFileDocument(tempAssetFile)
}
private fun openFileDocument(file: File): Pair<ParcelFileDescriptor, PdfRenderer> {
Log.d("pdf_renderer", "OpenFileDocument. File: " + file.path)
val fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
return if (fileDescriptor != null) {
val pdfRenderer = PdfRenderer(fileDescriptor)
Pair(fileDescriptor, pdfRenderer)
} else throw CreateRendererException()
}
}
class PdfRendererException internal constructor(code: String?, message: String?, details: Any?) :
RuntimeException(message) {
private val code: String?
private var details: Any? = null
companion object {
private const val TAG = "PdfRendererException#"
}
init {
if (BuildConfig.DEBUG && code == null) {
io.flutter.Log.e(TAG, "Parameter code must not be null.")
}
this.code = code
if (details != null) {
this.details = details
}
}
}
fun <R> Surface.use(block: (Surface) -> R): R {
try {
return block(this)
}
finally {
this.release()
}
}