forked from FossifyOrg/File-Manager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadTextActivity.kt
More file actions
385 lines (327 loc) · 12.7 KB
/
ReadTextActivity.kt
File metadata and controls
385 lines (327 loc) · 12.7 KB
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
package org.fossify.filemanager.activities
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.print.PrintAttributes
import android.print.PrintManager
import android.util.Base64
import android.view.inputmethod.EditorInfo
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ImageView
import android.widget.TextView
import org.fossify.commons.dialogs.ConfirmationAdvancedDialog
import org.fossify.commons.extensions.*
import org.fossify.commons.helpers.NavigationIcon
import org.fossify.commons.helpers.REAL_FILE_PATH
import org.fossify.commons.helpers.SAVE_DISCARD_PROMPT_INTERVAL
import org.fossify.commons.helpers.ensureBackgroundThread
import org.fossify.commons.views.MyEditText
import org.fossify.filemanager.R
import org.fossify.filemanager.databinding.ActivityReadTextBinding
import org.fossify.filemanager.dialogs.SaveAsDialog
import org.fossify.filemanager.extensions.openPath
import org.fossify.filemanager.views.GestureEditText
import java.io.File
import java.io.OutputStream
class ReadTextActivity : SimpleActivity() {
companion object {
private const val SELECT_SAVE_FILE_INTENT = 1
private const val SELECT_SAVE_FILE_AND_EXIT_INTENT = 2
private const val KEY_UNSAVED_TEXT = "KEY_UNSAVED_TEXT"
}
private val binding by viewBinding(ActivityReadTextBinding::inflate)
private var filePath = ""
private var originalText = ""
private var searchIndex = 0
private var lastSavePromptTS = 0L
private var searchMatches = emptyList<Int>()
private var isSearchActive = false
private lateinit var searchQueryET: MyEditText
private lateinit var searchPrevBtn: ImageView
private lateinit var searchNextBtn: ImageView
private lateinit var searchClearBtn: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
isMaterialActivity = true
super.onCreate(savedInstanceState)
setContentView(binding.root)
setupOptionsMenu()
binding.apply {
updateMaterialActivityViews(readTextCoordinator, readTextView, useTransparentNavigation = true, useTopSearchMenu = false)
setupMaterialScrollListener(readTextHolder, readTextToolbar)
}
searchQueryET = findViewById(R.id.search_query)
searchPrevBtn = findViewById(R.id.search_previous)
searchNextBtn = findViewById(R.id.search_next)
searchClearBtn = findViewById(R.id.search_clear)
if (checkAppSideloading()) {
return
}
val uri = if (intent.extras?.containsKey(REAL_FILE_PATH) == true) {
Uri.fromFile(File(intent.extras?.get(REAL_FILE_PATH).toString()))
} else {
intent.data
}
if (uri == null) {
finish()
return
}
val filename = getFilenameFromUri(uri)
if (filename.isNotEmpty()) {
binding.readTextToolbar.title = Uri.decode(filename)
}
binding.readTextView.onGlobalLayout {
ensureBackgroundThread {
checkIntent(uri, savedInstanceState)
}
}
setupSearchButtons()
}
override fun onResume() {
super.onResume()
setupToolbar(binding.readTextToolbar, NavigationIcon.Arrow)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
if (originalText != binding.readTextView.text.toString()) {
outState.putString(KEY_UNSAVED_TEXT, binding.readTextView.text.toString())
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
super.onActivityResult(requestCode, resultCode, resultData)
if (requestCode == SELECT_SAVE_FILE_INTENT && resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
val outputStream = contentResolver.openOutputStream(resultData.data!!)
val shouldExitAfterSaving = requestCode == SELECT_SAVE_FILE_AND_EXIT_INTENT
val selectedFilePath = getRealPathFromURI(intent.data!!)
val shouldOverwriteOriginalText = selectedFilePath == filePath
saveTextContent(outputStream, shouldExitAfterSaving, shouldOverwriteOriginalText)
}
}
override fun onBackPressed() {
val hasUnsavedChanges = originalText != binding.readTextView.text.toString()
when {
isSearchActive -> closeSearch()
hasUnsavedChanges && System.currentTimeMillis() - lastSavePromptTS > SAVE_DISCARD_PROMPT_INTERVAL -> {
lastSavePromptTS = System.currentTimeMillis()
ConfirmationAdvancedDialog(this, "", R.string.save_before_closing, R.string.save, R.string.discard) {
if (it) {
saveText(true)
} else {
super.onBackPressed()
}
}
}
else -> super.onBackPressed()
}
}
private fun setupOptionsMenu() {
binding.readTextToolbar.setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.menu_search -> openSearch()
R.id.menu_save -> saveText()
R.id.menu_open_with -> openPath(intent.dataString!!, true)
R.id.menu_print -> printText()
else -> return@setOnMenuItemClickListener false
}
return@setOnMenuItemClickListener true
}
}
private fun openSearch() {
isSearchActive = true
binding.searchWrapper.beVisible()
showKeyboard(searchQueryET)
binding.readTextView.requestFocus()
binding.readTextView.setSelection(0)
searchQueryET.postDelayed({
searchQueryET.requestFocus()
}, 250)
}
private fun saveText(shouldExitAfterSaving: Boolean = false) {
if (filePath.isEmpty()) {
filePath = getRealPathFromURI(intent.data!!) ?: ""
}
if (filePath.isEmpty()) {
SaveAsDialog(this, filePath, true) { _, filename ->
Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
type = "text/plain"
putExtra(Intent.EXTRA_TITLE, filename)
addCategory(Intent.CATEGORY_OPENABLE)
val requestCode = if (shouldExitAfterSaving) {
SELECT_SAVE_FILE_AND_EXIT_INTENT
} else {
SELECT_SAVE_FILE_INTENT
}
startActivityForResult(this, requestCode)
}
}
} else {
SaveAsDialog(this, filePath, false) { path, _ ->
if (hasStoragePermission()) {
val file = File(path)
getFileOutputStream(file.toFileDirItem(this), true) {
val shouldOverwriteOriginalText = path == filePath
saveTextContent(it, shouldExitAfterSaving, shouldOverwriteOriginalText)
}
} else {
toast(R.string.no_storage_permissions)
}
}
}
}
private fun saveTextContent(outputStream: OutputStream?, shouldExitAfterSaving: Boolean, shouldOverwriteOriginalText: Boolean) {
if (outputStream != null) {
val currentText = binding.readTextView.text.toString()
outputStream.bufferedWriter().use { it.write(currentText) }
toast(R.string.file_saved)
hideKeyboard()
if (shouldOverwriteOriginalText) {
originalText = currentText
}
if (shouldExitAfterSaving) {
super.onBackPressed()
}
} else {
toast(R.string.unknown_error_occurred)
}
}
private fun printText() {
try {
val webView = WebView(this)
webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest) = false
override fun onPageFinished(view: WebView, url: String) {
createWebPrintJob(view)
}
}
val text = binding.readTextView.text.toString()
val base64 = Base64.encodeToString(text.toByteArray(), Base64.DEFAULT)
webView.loadData(base64, "text/plain", "base64")
} catch (e: Exception) {
showErrorToast(e)
}
}
private fun createWebPrintJob(webView: WebView) {
val jobName = if (filePath.isNotEmpty()) {
filePath.getFilenameFromPath()
} else {
getString(R.string.app_name)
}
val printAdapter = webView.createPrintDocumentAdapter(jobName)
(getSystemService(Context.PRINT_SERVICE) as? PrintManager)?.apply {
print(jobName, printAdapter, PrintAttributes.Builder().build())
}
}
private fun checkIntent(uri: Uri, savedInstanceState: Bundle?) {
originalText = if (uri.scheme == "file") {
filePath = uri.path!!
val file = File(filePath)
if (file.exists()) {
try {
file.readText()
} catch (e: Exception) {
showErrorToast(e)
""
}
} else {
toast(R.string.unknown_error_occurred)
""
}
} else {
try {
contentResolver.openInputStream(uri)!!.bufferedReader().use { it.readText() }
} catch (e: OutOfMemoryError) {
showErrorToast(e.toString())
return
} catch (e: Exception) {
showErrorToast(e)
finish()
return
}
}
runOnUiThread {
var textToSet = originalText
if (savedInstanceState != null) {
textToSet = savedInstanceState.getString(KEY_UNSAVED_TEXT, originalText)
}
binding.readTextView.setText(textToSet)
if (originalText.isNotEmpty()) {
hideKeyboard()
} else {
showKeyboard(binding.readTextView)
}
}
}
private fun setupSearchButtons() {
searchQueryET.onTextChangeListener {
searchTextChanged(it)
}
searchPrevBtn.setOnClickListener {
goToPrevSearchResult()
}
searchNextBtn.setOnClickListener {
goToNextSearchResult()
}
searchClearBtn.setOnClickListener {
closeSearch()
}
searchQueryET.setOnEditorActionListener(TextView.OnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
searchNextBtn.performClick()
return@OnEditorActionListener true
}
false
})
binding.searchWrapper.setBackgroundColor(getProperPrimaryColor())
val contrastColor = getProperPrimaryColor().getContrastColor()
arrayListOf(searchPrevBtn, searchNextBtn, searchClearBtn).forEach {
it.applyColorFilter(contrastColor)
}
}
private fun searchTextChanged(text: String) {
binding.readTextView.text?.clearBackgroundSpans()
if (text.isNotBlank() && text.length > 1) {
searchMatches = binding.readTextView.text.toString().searchMatches(text)
binding.readTextView.highlightText(text, getProperPrimaryColor())
}
if (searchMatches.isNotEmpty()) {
binding.readTextView.requestFocus()
binding.readTextView.setSelection(searchMatches.getOrNull(searchIndex) ?: 0)
}
searchQueryET.postDelayed({
searchQueryET.requestFocus()
}, 50)
}
private fun goToPrevSearchResult() {
if (searchIndex > 0) {
searchIndex--
} else {
searchIndex = searchMatches.lastIndex
}
selectSearchMatch(binding.readTextView)
}
private fun goToNextSearchResult() {
if (searchIndex < searchMatches.lastIndex) {
searchIndex++
} else {
searchIndex = 0
}
selectSearchMatch(binding.readTextView)
}
private fun closeSearch() {
searchQueryET.text?.clear()
isSearchActive = false
binding.searchWrapper.beGone()
hideKeyboard()
}
private fun selectSearchMatch(editText: GestureEditText) {
if (searchMatches.isNotEmpty()) {
editText.requestFocus()
editText.setSelection(searchMatches.getOrNull(searchIndex) ?: 0)
} else {
hideKeyboard()
}
}
}