me puedes decir en que parrafo esta la funcion de "Parcial"? Este mai activity funcina…
- User
me puedes decir en que parrafo esta la funcion de "Parcial"? Este mai activity funcina los dos botones de busquedas. Palabra y parcial, y se arreglo el texeso de datos guardados. Pero se descontrolo el aling, tiene saltos de remglon, no guarda las fuentes. Lo tengo para compara con el que funcina.
package com.example.dito_note
import android.os.Handler import android.os.Looper import android.view.MotionEvent import android.provider.MediaStore import android.app.AlertDialog import android.content.ContentValues import android.content.DialogInterface import android.content.Intent import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Rect import android.graphics.RectF import android.graphics.Typeface import android.graphics.drawable.BitmapDrawable import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Environment import android.text.* import android.text.Html import android.text.TextPaint import android.text.style.* import android.view.Gravity import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import android.widget.* import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate import androidx.core.content.ContextCompat import androidx.documentfile.provider.DocumentFile import androidx.lifecycle.lifecycleScope import com.google.android.material.appbar.MaterialToolbar import java.io.BufferedReader import java.io.InputStreamReader import android.text.Layout import java.util.regex.Pattern import android.content.ClipboardManager import android.content.Context import android.content.ClipData import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.coroutines.delay
class MainActivity : AppCompatActivity() {
private lateinit var toolbar: MaterialToolbar private lateinit var editTextNote: EditText private var treeUri: Uri? = null private var currentFileName: String? = null private var currentFileUri: Uri? = null private var toolbarSubtitle: TextView? = null private lateinit var verticalScrollView: ScrollView private var lastTouchY: Float = 0f private var velocityY: Float = 0f private val frictionFactor: Float = 0.85f private val handler = Handler(Looper.getMainLooper()) private var flingRunnable: Runnable? = null private lateinit var bottomBarEditarTexto: ImageButton private lateinit var bottomBarResaltar: ImageButton private lateinit var bottomBarMayuscula: ImageButton private lateinit var bottomBarFontColor: ImageButton private lateinit var bottomBarUnderline: ImageButton private lateinit var bottomBarAlineacion: ImageButton private var isPartialSearch = false private lateinit var textWordCount: TextView private lateinit var tvFontSize: TextView private lateinit var icDivisor: ImageButton private var isBold = false private var isUnderline = false private var currentFontColor = Color.WHITE private var currentFontSizeSp = 16f private var currentTextAlignment: Int = View.TEXT_ALIGNMENT_TEXT_START private var isFirstTouch = false private var isKeyboardVisible = false private var hasUnsavedChanges = false private val openDocumentTreeLauncher = registerForActivityResult( ActivityResultContracts.OpenDocumentTree() ) { uri -> if (uri != null) { treeUri = uri contentResolver.takePersistableUriPermission( uri, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION ) showStoredFilesDialog() } } private val openDocumentLauncher = registerForActivityResult( ActivityResultContracts.OpenDocument() ) { uri -> if (uri != null) { try { contentResolver.takePersistableUriPermission( uri, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION ) val documentFile = DocumentFile.fromSingleUri(this, uri) if (documentFile != null) { openFile(documentFile) } } catch (e: Exception) { Toast.makeText(this, "Error al abrir el archivo: ${e.message}", Toast.LENGTH_LONG).show() } } } private lateinit var searchIndicators: View private var searchResults = mutableListOf<Pair<Int, Int>>() private lateinit var btnClearSearch: ImageButton private fun startFling() { flingRunnable = object : Runnable { override fun run() { if (kotlin.math.abs(velocityY) > 0.3f) { // Reduce la velocidad para simular fricción velocityY *= frictionFactor // Desplaza verticalScrollView.scrollBy(0, (-velocityY).toInt()) // Repetir handler.postDelayed(this, 16) } else { // Cuando la velocidad es muy baja, detener el movimiento velocityY = 0f } } } handler.post(flingRunnable!!) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) setContentView(R.layout.activity_main) // Enlace de vistas para búsqueda y contador textWordCount = findViewById(R.id.text_word_count) searchIndicators = findViewById(R.id.search_indicators) btnClearSearch = findViewById(R.id.btn_clear_search) editTextNote = findViewById(R.id.etNote) // Rógica existente verticalScrollView = findViewById(R.id.vertical_scroll_view) toolbar = findViewById(R.id.toolbar) bottomBarEditarTexto = findViewById(R.id.ic_editar_texto) bottomBarResaltar = findViewById(R.id.ic_resaltar) bottomBarMayuscula = findViewById(R.id.ic_mayuscula) bottomBarFontColor = findViewById(R.id.ic_font_color) bottomBarUnderline = findViewById(R.id.ic_underline) bottomBarAlineacion = findViewById(R.id.ic_aling) tvFontSize = findViewById(R.id.tv_font_size) icDivisor = findViewById(R.id.ic_divisor) setSupportActionBar(toolbar) btnClearSearch.setOnClickListener { clearSearch() textWordCount.visibility = View.GONE } setupBottomBarListeners() setupToolbarSubtitle(null) updateFontSizeDisplay() setupKeyboardVisibilityListener() setupTextWatcher() // Configurar el manejo de texto pegado editTextNote.customInsertionActionModeCallback = object : android.view.ActionMode.Callback { override fun onCreateActionMode(mode: android.view.ActionMode?, menu: Menu?): Boolean { menu?.add(Menu.NONE, android.R.id.paste, Menu.NONE, "Pegar")?.apply { setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS) } return true } override fun onPrepareActionMode(mode: android.view.ActionMode?, menu: Menu?): Boolean { return false } override fun onActionItemClicked(mode: android.view.ActionMode?, item: MenuItem?): Boolean { when (item?.itemId) { android.R.id.paste -> { val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager clipboard.primaryClip?.getItemAt(0)?.text?.let { pastedText -> // Limpiar el texto pegado val cleanText = pastedText.toString() .replace(Regex("<[^>]*>"), "") // Eliminar etiquetas HTML .replace(Regex("\\s+"), " ") // Normalizar espacios // Insertar el texto limpio en la posición actual val start = editTextNote.selectionStart val end = editTextNote.selectionEnd editTextNote.text.replace(start, end, cleanText) mode?.finish() return true } } } return false } override fun onDestroyActionMode(mode: android.view.ActionMode?) {} } // Configurar el menú de selección normal editTextNote.customSelectionActionModeCallback = object : android.view.ActionMode.Callback { override fun onCreateActionMode(mode: android.view.ActionMode?, menu: Menu?): Boolean { menu?.add(Menu.NONE, android.R.id.copy, Menu.NONE, "Copiar") menu?.add(Menu.NONE, android.R.id.cut, Menu.NONE, "Cortar") menu?.add(Menu.NONE, android.R.id.paste, Menu.NONE, "Pegar") return true } override fun onPrepareActionMode(mode: android.view.ActionMode?, menu: Menu?): Boolean { return false } override fun onActionItemClicked(mode: android.view.ActionMode?, item: MenuItem?): Boolean { val start = editTextNote.selectionStart val end = editTextNote.selectionEnd when (item?.itemId) { android.R.id.copy -> { if (start != end) { val selectedText = editTextNote.text.substring(start, end) val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager clipboard.setPrimaryClip(ClipData.newPlainText("text", selectedText)) mode?.finish() return true } } android.R.id.cut -> { if (start != end) { val selectedText = editTextNote.text.substring(start, end) val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager clipboard.setPrimaryClip(ClipData.newPlainText("text", selectedText)) editTextNote.text.delete(start, end) mode?.finish() return true } } android.R.id.paste -> { val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager clipboard.primaryClip?.getItemAt(0)?.text?.let { pastedText -> val cleanText = pastedText.toString() .replace(Regex("<[^>]*>"), "") .replace(Regex("\\s+"), " ") editTextNote.text.replace(start, end, cleanText) mode?.finish() return true } } } return false } override fun onDestroyActionMode(mode: android.view.ActionMode?) {} } // Agregar listener para clicks editTextNote.setOnClickListener { updateFontSizeDisplay() } editTextNote.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { updateFontSizeDisplay() } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} }) } private fun setupKeyboardVisibilityListener() { val rootView = window.decorView.rootView rootView.viewTreeObserver.addOnGlobalLayoutListener { val r = Rect() rootView.getWindowVisibleDisplayFrame(r) val screenHeight = rootView.height // El teclado está visible si la altura visible es significativamente menor que la altura total val keyboardHeight = screenHeight - r.bottom val isKeyboardNowVisible = keyboardHeight > (screenHeight * 0.15).toInt() if (!isKeyboardVisible && isKeyboardNowVisible) { // El teclado se acaba de mostrar val pos = editTextNote.selectionStart val layout = editTextNote.layout if (layout != null) { val line = layout.getLineForOffset(pos) val y = layout.getLineTop(line) val extraMargin = (200 * resources.displayMetrics.density).toInt() verticalScrollView.postDelayed({ verticalScrollView.smoothScrollTo(0, y - extraMargin) }, 200) } } isKeyboardVisible = isKeyboardNowVisible } } private var isDocumentJustOpened = false private fun setupBottomBarListeners() { bottomBarEditarTexto.setOnClickListener { showTextFormatDialog() } bottomBarResaltar.setOnClickListener { showColorPickerDialog() } bottomBarMayuscula.setOnClickListener { toggleSelectionCase() } bottomBarFontColor.setOnClickListener { showFontColorPickerDialog() } bottomBarUnderline.setOnClickListener { toggleUnderlineOnSelection() } bottomBarAlineacion.setOnClickListener { showAlignPickerDialog() } tvFontSize.setOnClickListener { showFontSizePickerDialog() } icDivisor.setOnClickListener { showDivisorMenu() } } private fun showDivisorMenu() { val paint = editTextNote.paint val editTextWidth = editTextNote.width - editTextNote.paddingLeft - editTextNote.paddingRight if (editTextWidth <= 0) { Toast.makeText(this, "EditText no ha sido layoutedo aún", Toast.LENGTH_SHORT).show() return } val equalCharWidth = paint.measureText("=") val dashCharWidth = paint.measureText("•") val boxdrawingslighthorizontalCharWidth = paint.measureText("─") val equalCharCount = if (equalCharWidth != 0f) (editTextWidth / equalCharWidth).toInt().coerceAtLeast(1) else 20 val dashCharCount = if (dashCharWidth != 0f) (editTextWidth / dashCharWidth).toInt().coerceAtLeast(1) else 20 // Calculamos cuántos "─" caben en la mitad del ancho val halfWidth = editTextWidth / 2 val boxdrawingslighthorizontalCharCount = if (boxdrawingslighthorizontalCharWidth != 0f) (halfWidth / boxdrawingslighthorizontalCharWidth).toInt().coerceAtLeast(1) else 10 val options = arrayOf( "=============== (Ancho completo)", "••••••••••••••••••••••••• (Ancho completo)", "─".repeat(5) + " (Mitad ancho)" ) AlertDialog.Builder(this) .setTitle("Divisor") .setItems(options) { dialog, which -> val cursorPos = editTextNote.selectionStart.coerceAtLeast(0) val divisorText = when (which) { 0 -> "=".repeat(equalCharCount) + "\n" 1 -> "•".repeat(dashCharCount) + "\n" 2 -> "─".repeat(boxdrawingslighthorizontalCharCount) + "\n" else -> null } divisorText?.let { editTextNote.text.insert(cursorPos, it) editTextNote.setSelection(cursorPos + it.length) } dialog.dismiss() } .show() } // Función auxiliar para crear línea con símbolos separados por espacios private fun createSymbolLine(symbol: String, count: Int, space: String, paint: Paint): String { val sb = StringBuilder() for (i in 1..count) { sb.append(symbol) if (i != count) sb.append(space) } return sb.toString() } private fun showAlignPickerDialog() { val icons = arrayOf( R.drawable.ic_align_left, R.drawable.ic_align_center, R.drawable.ic_align_right ) val adapter = object : ArrayAdapter<Int>(this, android.R.layout.select_dialog_item, icons) { override fun getView(position: Int, convertView: View?, parent: android.view.ViewGroup): View { val imageView = ImageView(context) val sizeInDp = 48 val scale = context.resources.displayMetrics.density val sizeInPx = (sizeInDp * scale + 0.5f).toInt() imageView.layoutParams = LinearLayout.LayoutParams(sizeInPx, sizeInPx) imageView.setImageDrawable(ContextCompat.getDrawable(context, icons[position])) imageView.scaleType = ImageView.ScaleType.FIT_CENTER return imageView } } AlertDialog.Builder(this) .setTitle("Alinear") .setAdapter(adapter) { _, which -> val alignment = when (which) { 0 -> Layout.Alignment.ALIGN_NORMAL 1 -> Layout.Alignment.ALIGN_CENTER 2 -> Layout.Alignment.ALIGN_OPPOSITE else -> Layout.Alignment.ALIGN_NORMAL } applyAlignment(alignment) } .setNegativeButton("Cancelar", null) .show() } private fun applyAlignment(alignment: Layout.Alignment) { val start = editTextNote.selectionStart val end = editTextNote.selectionEnd if (start < 0 || end <= start) { Toast.makeText(this, "Selecciona un texto para alinear", Toast.LENGTH_SHORT).show() return } val text = editTextNote.text.toString() val spannable = editTextNote.text as Spannable // Encontrar los límites del párrafo completo var paragraphStart = start var paragraphEnd = end // Retroceder hasta encontrar el inicio del párrafo while (paragraphStart > 0 && text[paragraphStart - 1] != '\n') { paragraphStart-- } // Avanzar hasta encontrar el final del párrafo while (paragraphEnd < text.length && text[paragraphEnd] != '\n') { paragraphEnd++ } if (paragraphEnd < text.length) { paragraphEnd++ // Incluir el salto de línea } // Eliminar alineaciones existentes en el párrafo val spans = spannable.getSpans(paragraphStart, paragraphEnd, AlignmentSpan::class.java) for (span in spans) { spannable.removeSpan(span) } // Aplicar nueva alineación spannable.setSpan( AlignmentSpan.Standard(alignment), paragraphStart, paragraphEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) // Mantener la selección editTextNote.setSelection(start, end) } private fun toggleSelectionCase() { val start = editTextNote.selectionStart val end = editTextNote.selectionEnd if (start < 0 || end <= start) { Toast.makeText(this, "Selecciona un texto para cambiar mayúscula/minúscula", Toast.LENGTH_SHORT).show() return } val text = editTextNote.text val selectedText = text.subSequence(start, end).toString() val isAllUpper = selectedText == selectedText.uppercase() val newText = if (isAllUpper) selectedText.lowercase() else selectedText.uppercase() text.replace(start, end, newText) editTextNote.setSelection(start, start + newText.length) } private fun setupToolbarSubtitle(subtitleText: String?) { if (toolbarSubtitle == null) { toolbarSubtitle = TextView(this).apply { setTextColor(ContextCompat.getColor(context, android.R.color.darker_gray)) textSize = 12f val lp = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ) lp.topMargin = (4 * resources.displayMetrics.density).toInt() // 4dp de margen layoutParams = lp } // Crear un contenedor vertical para el título y subtítulo val container = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) } // Crear el título val titleView = TextView(this).apply { text = "Dito-Note" setTextColor(Color.WHITE) textSize = 20f layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ) } // Agregar título y subtítulo al contenedor container.addView(titleView) container.addView(toolbarSubtitle) // Remover todas las vistas del toolbar y agregar el nuevo contenedor toolbar.removeAllViews() toolbar.addView(container) } toolbarSubtitle?.text = subtitleText ?: "" toolbarSubtitle?.visibility = if (subtitleText.isNullOrEmpty()) View.GONE else View.VISIBLE } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.main_menu, menu) changeMenuItemTextColor(menu, Color.WHITE) return true } private fun changeMenuItemTextColor(menu: Menu?, color: Int) { menu ?: return for (i in 0 until menu.size()) { val menuItem = menu.getItem(i) menuItem.title = menuItem.title?.let { val ss = SpannableStringBuilder(it) ss.setSpan(ForegroundColorSpan(color), 0, ss.length, 0) ss } } } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_search -> { showSearchDialog() true } R.id.action_save -> { if (currentFileName != null && currentFileUri != null) { AlertDialog.Builder(this) .setTitle("Confirmar guardado") .setMessage("¿Lo vas a sobrescribir?") .setPositiveButton("Sí") { dialog, _ -> saveNoteAsHtml(currentFileName!!) dialog.dismiss() } .setNegativeButton("No") { dialog, _ -> dialog.dismiss() showSaveDialog(null) } .show() } else { showSaveDialog(null) } true } R.id.action_open_folder -> { if (hasUnsavedChanges) { AlertDialog.Builder(this) .setTitle("Cambios sin guardar") .setMessage("¿Quieres guardar los cambios antes de abrir otro documento?") .setPositiveButton("Guardar") { _, _ -> if (currentFileName != null) { saveNoteAsHtml(currentFileName!!) openDocumentLauncher.launch(arrayOf("text/html")) } else { showSaveDialogWithCallback { openDocumentLauncher.launch(arrayOf("text/html")) } } } .setNegativeButton("Descartar") { _, _ -> openDocumentLauncher.launch(arrayOf("text/html")) } .setNeutralButton("Cancelar", null) .show() } else { openDocumentLauncher.launch(arrayOf("text/html")) } true } R.id.action_new_doc -> { if (hasUnsavedChanges) { AlertDialog.Builder(this) .setTitle("Cambios sin guardar") .setMessage("¿Quieres guardar los cambios antes de crear un nuevo documento?") .setPositiveButton("Guardar") { _, _ -> if (currentFileName != null) { saveNoteAsHtml(currentFileName!!) clearDocument() } else { showSaveDialogWithCallback { clearDocument() } } } .setNegativeButton("Descartar") { _, _ -> clearDocument() } .setNeutralButton("Cancelar", null) .show() } else { clearDocument() } true } else -> super.onOptionsItemSelected(item) } } private fun newDocument() { if (hasUnsavedChanges) { AlertDialog.Builder(this) .setTitle("Cambios sin guardar") .setMessage("¿Quieres guardar los cambios antes de crear un nuevo documento?") .setPositiveButton("Guardar") { _, _ -> if (currentFileName != null) { saveNoteAsHtml(currentFileName!!) clearDocument() } else { showSaveDialogWithCallback { clearDocument() } } } .setNegativeButton("Descartar") { _, _ -> clearDocument() } .setNeutralButton("Cancelar", null) .show() } else { clearDocument() } } private fun openDocumentsFolder() { if (hasUnsavedChanges) { AlertDialog.Builder(this) .setTitle("Cambios sin guardar") .setMessage("¿Quieres guardar los cambios antes de abrir otro documento?") .setPositiveButton("Guardar") { _, _ -> if (currentFileName != null) { saveNoteAsHtml(currentFileName!!) openDocumentLauncher.launch(arrayOf("text/html")) } else { showSaveDialogWithCallback { openDocumentLauncher.launch(arrayOf("text/html")) } } } .setNegativeButton("Descartar") { _, _ -> openDocumentLauncher.launch(arrayOf("text/html")) } .setNeutralButton("Cancelar", null) .show() } else { openDocumentLauncher.launch(arrayOf("text/html")) } } override fun onPause() { super.onPause() // Guardar el estado actual si es necesario if (currentFileName != null) { saveNoteAsHtml(currentFileName!!) } } override fun onStop() { super.onStop() // Limpiar recursos si es necesario handler.removeCallbacks(flingRunnable ?: return) } override fun onDestroy() { super.onDestroy() // Limpiar todos los recursos handler.removeCallbacksAndMessages(null) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) // Guardar el estado actual outState.putString("current_file_name", currentFileName) outState.putParcelable("current_file_uri", currentFileUri) outState.putString("current_text", editTextNote.text.toString()) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) // Restaurar el estado currentFileName = savedInstanceState.getString("current_file_name") currentFileUri = savedInstanceState.getParcelable("current_file_uri") val savedText = savedInstanceState.getString("current_text") if (savedText != null) { editTextNote.setText(savedText) } setupToolbarSubtitle(currentFileName) } private fun showSaveDialogWithCallback(onSaveComplete: () -> Unit) { val input = EditText(this) input.hint = "Nombre del archivo" input.setTextColor(Color.WHITE) val dialog = AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_NoActionBar) .setTitle("Guardar nota") .setView(input) .setPositiveButton("Guardar", null) .setNegativeButton("Cancelar", null) .create() dialog.setOnShowListener { dialog.getButton(AlertDialog.BUTTON_POSITIVE)?.setTextColor(0xFF00CC00.toInt()) dialog.getButton(AlertDialog.BUTTON_NEGATIVE)?.setTextColor(Color.RED) dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { val filename = input.text.toString().trim() if (filename.isNotEmpty()) { saveNoteAsHtml(filename) dialog.dismiss() onSaveComplete() } else { input.error = "El nombre no puede estar vacío" } } dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener { dialog.dismiss() } } dialog.show() } private fun showSaveDialog(prefillName: String?) { val input = EditText(this) input.hint = "Nombre del archivo" input.setTextColor(Color.WHITE) if (!prefillName.isNullOrEmpty()) { input.setText(prefillName) input.setSelection(prefillName.length) } val dialog = AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_NoActionBar) .setTitle("Guardar nota") .setView(input) .setPositiveButton("Guardar", null) .setNegativeButton("Cancelar", null) .create() dialog.setOnShowListener { dialog.getButton(AlertDialog.BUTTON_POSITIVE)?.setTextColor(0xFF00CC00.toInt()) dialog.getButton(AlertDialog.BUTTON_NEGATIVE)?.setTextColor(Color.RED) dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { val filename = input.text.toString().trim() if (filename.isNotEmpty()) { saveNoteAsHtml(filename) dialog.dismiss() } else { input.error = "El nombre no puede estar vacío" } } dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener { dialog.dismiss() } } dialog.show() } private fun saveNoteAsHtml(filename: String) { try { val text = editTextNote.text val metadata = StringBuilder() val contentSize = text.length val spans = text.getSpans(0, text.length, Any::class.java) // Cabecera de metadatos para identificación metadata.append("<!--DITO-NOTE-FORMAT-START-->\n") spans.forEach { span -> val start = text.getSpanStart(span) val end = text.getSpanEnd(span) when (span) { is AlignmentSpan -> { val alignment = when (span.alignment) { Layout.Alignment.ALIGN_CENTER -> "center" Layout.Alignment.ALIGN_OPPOSITE -> "right" else -> "left" } metadata.append("<!--ALIGN:$start:$end:$alignment-->\n") } is StyleSpan -> { val style = when (span.style) { Typeface.BOLD -> "bold" Typeface.ITALIC -> "italic" else -> null } style?.let { metadata.append("<!--STYLE:$start:$end:$it-->\n") } } is UnderlineSpan -> { metadata.append("<!--UNDERLINE:$start:$end-->\n") } is ForegroundColorSpan -> { metadata.append("<!--COLOR:$start:$end:${span.foregroundColor}-->\n") } is BackgroundColorSpan -> { metadata.append("<!--HIGHLIGHT:$start:$end:${span.backgroundColor}-->\n") } is RelativeSizeSpan -> { val size = (span.sizeChange * 16).toInt() metadata.append("<!--SIZE:$start:$end:$size-->\n") } is TypefaceSpan -> { metadata.append("<!--FONT:$start:$end:${span.family}-->\n") } } } // Fin de metadatos metadata.append("<!--DITO-NOTE-FORMAT-END-->\n") // Convertir a HTML val finalHtml = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Html.toHtml(text, Html.FROM_HTML_MODE_LEGACY) } else { Html.toHtml(text) } // Guardar el archivo if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { val contentValues = ContentValues().apply { put(MediaStore.MediaColumns.DISPLAY_NAME, "$filename.html") put(MediaStore.MediaColumns.MIME_TYPE, "text/html") put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS + "/Dito note") } if (currentFileUri != null && filename == currentFileName) { contentResolver.openOutputStream(currentFileUri!!, "wt")?.use { out -> out.write(finalHtml.toByteArray(Charsets.UTF_8)) } } else { val uri = contentResolver.insert(MediaStore.Files.getContentUri("external"), contentValues) uri?.let { contentResolver.openOutputStream(it).use { out -> out?.write(finalHtml.toByteArray(Charsets.UTF_8)) } currentFileUri = it currentFileName = filename } } } hasUnsavedChanges = false Toast.makeText(this, "Nota guardada", Toast.LENGTH_SHORT).show() setupToolbarSubtitle(filename) } catch (e: Exception) { Toast.makeText(this, "Error al guardar: ${e.message}", Toast.LENGTH_LONG).show() } } private fun clearDocument() { editTextNote.text.clear() currentFileName = null currentFileUri = null setupToolbarSubtitle(null) updateFontSizeDisplay() hasUnsavedChanges = false Toast.makeText(this, "Nuevo documento listo", Toast.LENGTH_SHORT).show() } private fun clearSearch() { val spannable = editTextNote.text as Spannable // Limpiar spans de búsqueda spannable.getSpans(0, spannable.length, SearchWordSpan::class.java).forEach { spannable.removeSpan(it) } // Ocultar indicadores y botón X searchIndicators.visibility = View.GONE btnClearSearch.visibility = View.GONE // Ocultar contador de coincidencias textWordCount.visibility = View.GONE // Limpiar selección editTextNote.setSelection(editTextNote.selectionStart) } private fun showSearchDialog() { val dialogView = layoutInflater.inflate(R.layout.dialog_search, null) val searchInput = dialogView.findViewById<EditText>(R.id.et_search) val searchButton = dialogView.findViewById<Button>(R.id.btn_search) val btnParcial = dialogView.findViewById<Button>(R.id.btn_parcial) val dialog = AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_NoActionBar) .setTitle("Buscar palabra") .setView(dialogView) .create() btnParcial.setOnClickListener { isPartialSearch = true val searchText = searchInput.text.toString().trim() if (searchText.isNotEmpty()) { searchInText(searchText) dialog.dismiss() } else { searchInput.error = "Ingresa una palabra para buscar" } } searchButton.setOnClickListener { isPartialSearch = false val searchText = searchInput.text.toString().trim() if (searchText.isNotEmpty()) { searchInText(searchText) dialog.dismiss() } else { searchInput.error = "Ingresa una palabra para buscar" } } dialog.show() dialog.window?.setBackgroundDrawableResource(android.R.color.transparent) } private fun showTextFormatDialog() { val options = listOf( Pair("Negrita", R.drawable.ic_bold), Pair("FONTS", null) ) val adapter = object : ArrayAdapter<Pair<String, Int?>>(this, android.R.layout.select_dialog_item, options) { override fun getView(position: Int, convertView: View?, parent: android.view.ViewGroup): View { val view = convertView ?: layoutInflater.inflate(android.R.layout.select_dialog_item, parent, false) val textView = view.findViewById<TextView>(android.R.id.text1) val (text, iconRes) = getItem(position)!! textView.text = text if (iconRes != null) { val sizeInDp = 72 val scale = context.resources.displayMetrics.density val sizeInPx = (sizeInDp * scale + 0.5f).toInt() val drawable = ContextCompat.getDrawable(context, iconRes) drawable?.setBounds(0, 0, sizeInPx, sizeInPx) textView.setCompoundDrawables(drawable, null, null, null) textView.compoundDrawablePadding = (8 * resources.displayMetrics.density).toInt() } else { textView.setCompoundDrawables(null, null, null, null) } return view } } AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog) .setTitle("Editar texto") .setAdapter(adapter) { _, which -> when (which) { 0 -> toggleBoldOnSelection() 1 -> showFontsDialog() } } .setNegativeButton("Cancelar", null) .create() .apply { show() } .also { it.getButton(DialogInterface.BUTTON_NEGATIVE)?.setTextColor(Color.WHITE) } } private fun showColorPickerDialog() { val dialogView = layoutInflater.inflate(R.layout.dialog_color_picker, null) val dialogBuilder = AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog) val titleView = layoutInflater.inflate(R.layout.dialog_title_with_close, null) dialogBuilder.setCustomTitle(titleView) dialogBuilder.setView(dialogView) dialogBuilder.setNegativeButton("Cancelar", null) val dialog = dialogBuilder.create() val colorsMap = mapOf( R.id.color_yellow to Pair(Color.YELLOW, Color.BLACK), R.id.color_orange to Pair(0xFFFFA500.toInt(), Color.BLACK), R.id.color_green to Pair(Color.GREEN, Color.BLACK), R.id.color_blue to Pair(Color.BLUE, Color.WHITE), R.id.color_red to Pair(Color.RED, Color.WHITE), R.id.color_black to Pair(Color.BLACK, Color.WHITE) ) titleView.findViewById<ImageButton>(R.id.btn_close).setOnClickListener { val start = editTextNote.selectionStart val end = editTextNote.selectionEnd if (start < 0 || end <= start) { Toast.makeText(this, "Selecciona un texto para quitar el resaltado", Toast.LENGTH_SHORT).show() } else { val spannable = editTextNote.text as Spannable // Eliminar BackgroundColorSpan sólo en la selección exacta removeSpansPartially(spannable, start, end, BackgroundColorSpan::class.java) // Eliminar ForegroundColorSpan sólo en la selección exacta removeSpansPartially(spannable, start, end, ForegroundColorSpan::class.java) } dialog.dismiss() } colorsMap.forEach { (viewId, colorPair) -> dialogView.findViewById<View>(viewId).setOnClickListener { highlightSelectedTextWithContrast(colorPair.first, colorPair.second) dialog.dismiss() } } dialog.setOnShowListener { dialog.getButton(DialogInterface.BUTTON_NEGATIVE)?.setTextColor(Color.WHITE) } dialog.show() } private fun showFontColorPickerDialog() { val dialogView = layoutInflater.inflate(R.layout.dialog_color_picker, null) val dialogBuilder = AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog) val titleView = layoutInflater.inflate(R.layout.dialog_title_with_close, null) val titleText = titleView.findViewById<TextView>(R.id.dialog_title_text) titleText.text = "Qué color?" dialogBuilder.setCustomTitle(titleView) dialogBuilder.setView(dialogView) dialogBuilder.setNegativeButton("Cancelar", null) val dialog = dialogBuilder.create() val colorsMap = mapOf( R.id.color_yellow to Color.YELLOW, R.id.color_orange to 0xFFFFA500.toInt(), R.id.color_green to Color.GREEN, R.id.color_blue to Color.BLUE, R.id.color_red to Color.RED, R.id.color_black to Color.BLACK ) titleView.findViewById<ImageButton>(R.id.btn_close).setOnClickListener { val start = editTextNote.selectionStart val end = editTextNote.selectionEnd if (start < 0 || end <= start) { Toast.makeText(this, "Selecciona un texto para quitar el color de fuente", Toast.LENGTH_SHORT).show() } else { val spannable = editTextNote.text as Spannable removeSpansPartially(spannable, start, end, ForegroundColorSpan::class.java) } dialog.dismiss() } colorsMap.forEach { (viewId, colorInt) -> dialogView.findViewById<View>(viewId).setOnClickListener { applyColorOnSelection(colorInt) dialog.dismiss() } } dialog.setOnShowListener { dialog.getButton(DialogInterface.BUTTON_NEGATIVE)?.setTextColor(Color.WHITE) } dialog.show() } private fun toggleUnderlineOnSelection() { val start = editTextNote.selectionStart val end = editTextNote.selectionEnd if (start < 0 || end <= start) { Toast.makeText(this, "Selecciona un texto para aplicar subrayado", Toast.LENGTH_SHORT).show() return } val spannable = editTextNote.text as Spannable // Obtener todos los spans de subrayado que intersectan con la selección val spans = spannable.getSpans(start, end, UnderlineSpan::class.java) if (spans.isEmpty()) { // Si no hay subrayado, aplicar uno nuevo a la selección spannable.setSpan(UnderlineSpan(), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } else { // Para cada span que intersecta con la selección for (span in spans) { val spanStart = spannable.getSpanStart(span) val spanEnd = spannable.getSpanEnd(span) // Remover el span original spannable.removeSpan(span) // Si el span comenzaba antes de la selección, preservar esa parte if (spanStart < start) { spannable.setSpan(UnderlineSpan(), spanStart, start, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } // Si el span terminaba después de la selección, preservar esa parte if (spanEnd > end) { spannable.setSpan(UnderlineSpan(), end, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } } } } private fun showFontSizePickerDialog() { val sizesList = listOf(6, 8, 10, 12, 14, 16) val dialogView = layoutInflater.inflate(R.layout.dialog_font_size_picker, null) val inputManual = dialogView.findViewById<EditText>(R.id.et_manual_size) val listView = dialogView.findViewById<ListView>(R.id.list_sizes) val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, sizesList.map { "${it}pt" }) listView.adapter = adapter val currentSizeText = tvFontSize.text.toString().replace("pt", "").trim() inputManual.setText(currentSizeText) inputManual.inputType = InputType.TYPE_CLASS_NUMBER inputManual.setOnFocusChangeListener { _, hasFocus -> if (hasFocus) { inputManual.text.clear() } } val dialog = AlertDialog.Builder(this) .setTitle("Seleccionar tamaño de fuente") .setView(dialogView) .setNegativeButton("Cancelar", null) .create() listView.setOnItemClickListener { _, _, position, _ -> val selectedSize = sizesList[position] applySizeOnSelection(selectedSize.toInt()) dialog.dismiss() } inputManual.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE) { val inputText = inputManual.text.toString().toIntOrNull() if (inputText != null && inputText in 6..72) { applySizeOnSelection(inputText) dialog.dismiss() } else { inputManual.error = "Ingresa un valor entre 6 y 72" } true } else { false } } dialog.show() } private fun updateFontSizeDisplay() { val start = editTextNote.selectionStart if (start < 0 || editTextNote.text.isEmpty()) { tvFontSize.text = "16pt" return } val spannable = editTextNote.text as Spannable // Buscar spans que incluyan la posición actual val spans = spannable.getSpans(0, spannable.length, RelativeSizeSpan::class.java) .filter { span -> val spanStart = spannable.getSpanStart(span) val spanEnd = spannable.getSpanEnd(span) start >= spanStart && start < spanEnd } if (spans.isNotEmpty()) { // Tomar el último span aplicado en esa posición val span = spans.last() val size = (span.sizeChange * 16).toInt() tvFontSize.text = "${size}pt" } else { tvFontSize.text = "16pt" } } private fun searchInText(searchText: String) { val text = editTextNote.text.toString() val spannable = editTextNote.text as Spannable // Limpiar spans anteriores spannable.getSpans(0, spannable.length, SearchWordSpan::class.java).forEach { spannable.removeSpan(it) } searchResults.clear() if (isPartialSearch) { // Búsqueda parcial: sin frontera \b val pattern = Pattern.compile(Pattern.quote(searchText), Pattern.CASE_INSENSITIVE) val matcher = pattern.matcher(text) while (matcher.find()) { val start = matcher.start() val end = matcher.end() searchResults.add(Pair(start, end)) spannable.setSpan(SearchWordSpan(), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } } else { // Búsqueda exacta val pattern = Pattern.compile("\\b" + Pattern.quote(searchText) + "\\b", Pattern.CASE_INSENSITIVE) val matcher = pattern.matcher(text) while (matcher.find()) { val start = matcher.start() val end = matcher.end() searchResults.add(Pair(start, end)) spannable.setSpan(SearchWordSpan(), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } } if (searchResults.isNotEmpty()) { // Mostrar y actualizar contador searchIndicators.visibility = View.VISIBLE btnClearSearch.visibility = View.VISIBLE textWordCount.visibility = View.VISIBLE textWordCount.text = searchResults.size.toString() // Opcional: seleccionar la primera coincidencia val firstResult = searchResults[0] editTextNote.setSelection(firstResult.first, firstResult.second) } else { Toast.makeText(this, "No se encontraron coincidencias", Toast.LENGTH_SHORT).show() } } private fun toggleBoldOnSelection() { val start = editTextNote.selectionStart val end = editTextNote.selectionEnd if (start < 0 || end <= start) { Toast.makeText(this, "Selecciona un texto para aplicar negrita", Toast.LENGTH_SHORT).show() return } val spannable = editTextNote.text as Spannable // Obtener todos los spans de negrita que intersectan con la selección val spans = spannable.getSpans(start, end, StyleSpan::class.java) .filter { it.style == Typeface.BOLD } if (spans.isEmpty()) { // Si no hay negrita, aplicar una nueva a la selección spannable.setSpan(StyleSpan(Typeface.BOLD), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } else { // Para cada span que intersecta con la selección for (span in spans) { val spanStart = spannable.getSpanStart(span) val spanEnd = spannable.getSpanEnd(span) // Remover el span original spannable.removeSpan(span) // Si el span comenzaba antes de la selección, preservar esa parte if (spanStart < start) { spannable.setSpan(StyleSpan(Typeface.BOLD), spanStart, start, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } // Si el span terminaba después de la selección, preservar esa parte if (spanEnd > end) { spannable.setSpan(StyleSpan(Typeface.BOLD), end, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } } } } private fun showFontsDialog() { val fonts = arrayOf( "sans-serif", "sans-serif-light", "sans-serif-condensed", "sans-serif-black", "serif", "monospace", "casual", "cursive" ) val adapter = object : ArrayAdapter<String>(this, android.R.layout.select_dialog_item, fonts) { override fun getView(position: Int, convertView: View?, parent: android.view.ViewGroup): View { val view = super.getView(position, convertView, parent) val textView = view.findViewById<TextView>(android.R.id.text1) val fontFamily = getItem(position) textView.typeface = Typeface.create(fontFamily, Typeface.NORMAL) textView.text = fontFamily?.replace("-", " ")?.capitalize() return view } } AlertDialog.Builder(this) .setTitle("Seleccionar fuente") .setAdapter(adapter) { _, which -> val font = fonts[which] applyFontOnSelection(font) } .setNegativeButton("Cancelar", null) .show() } private fun removeSpansPartially(spannable: Spannable, start: Int, end: Int, type: Class<out CharacterStyle>) { val spans = spannable.getSpans(start, end, type) for (span in spans) { val spanStart = spannable.getSpanStart(span) val spanEnd = spannable.getSpanEnd(span) spannable.removeSpan(span) if (spanStart < start) { val newSpan = when (span) { is StyleSpan -> StyleSpan(span.style) is UnderlineSpan -> UnderlineSpan() is ForegroundColorSpan -> ForegroundColorSpan(span.foregroundColor) is BackgroundColorSpan -> BackgroundColorSpan(span.backgroundColor) is RelativeSizeSpan -> RelativeSizeSpan(span.sizeChange) is TypefaceSpan -> TypefaceSpan(span.family) else -> span } spannable.setSpan(newSpan, spanStart, start, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } if (spanEnd > end) { val newSpan = when (span) { is StyleSpan -> StyleSpan(span.style) is UnderlineSpan -> UnderlineSpan() is ForegroundColorSpan -> ForegroundColorSpan(span.foregroundColor) is BackgroundColorSpan -> BackgroundColorSpan(span.backgroundColor) is RelativeSizeSpan -> RelativeSizeSpan(span.sizeChange) is TypefaceSpan -> TypefaceSpan(span.family) else -> span } spannable.setSpan(newSpan, end, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } } } private fun highlightSelectedTextWithContrast(backgroundColor: Int, textColor: Int) { val start = editTextNote.selectionStart val end = editTextNote.selectionEnd if (start < 0 || end <= start) { Toast.makeText(this, "Selecciona un texto para resaltar", Toast.LENGTH_SHORT).show() return } val spannable = editTextNote.text as Spannable spannable.setSpan(BackgroundColorSpan(backgroundColor), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) spannable.setSpan(ForegroundColorSpan(textColor), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } private fun applyColorOnSelection(color: Int) { val start = editTextNote.selectionStart val end = editTextNote.selectionEnd if (start < 0 || end <= start) { Toast.makeText(this, "Selecciona un texto para aplicar color", Toast.LENGTH_SHORT).show() return } val spannable = editTextNote.text as Spannable spannable.setSpan(ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } private fun applyFontOnSelection(fontFamily: String) { val start = editTextNote.selectionStart val end = editTextNote.selectionEnd if (start < 0 || end <= start) { Toast.makeText(this, "Selecciona un texto para cambiar la fuente", Toast.LENGTH_SHORT).show() return } val spannable = editTextNote.text as Spannable spannable.setSpan(TypefaceSpan(fontFamily), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } private fun applySizeOnSelection(size: Int) { val start = editTextNote.selectionStart val end = editTextNote.selectionEnd if (start < 0 || end <= start) { Toast.makeText(this, "Selecciona un texto para cambiar el tamaño", Toast.LENGTH_SHORT).show() return } val spannable = editTextNote.text as Spannable val sizeChange = size / 16f spannable.setSpan(RelativeSizeSpan(sizeChange), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) updateFontSizeDisplay() } private class SearchWordSpan : ReplacementSpan() { override fun getSize( paint: Paint, text: CharSequence?, start: Int, end: Int, fm: Paint.FontMetricsInt? ): Int { return paint.measureText(text, start, end).toInt() } override fun draw( canvas: Canvas, text: CharSequence?, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint ) { // Guardar el estilo original val originalStyle = paint.style val originalColor = paint.color // Dibujar el texto paint.style = Paint.Style.FILL canvas.drawText(text!!, start, end, x, y.toFloat(), paint) // Dibujar el marco blanco paint.style = Paint.Style.STROKE paint.strokeWidth = 2f paint.color = Color.WHITE val textWidth = paint.measureText(text, start, end) val textHeight = paint.fontMetrics.descent - paint.fontMetrics.ascent val padding = 4f // Dibujar el rectángulo canvas.drawRect( x - padding, y + paint.fontMetrics.ascent - padding, x + textWidth + padding, y + paint.fontMetrics.descent + padding, paint ) // Restaurar el estilo original paint.style = originalStyle paint.color = originalColor } } private fun showStoredFilesDialog() { val files = mutableListOf<DocumentFile>() val treeDoc = treeUri?.let { DocumentFile.fromTreeUri(this, it) } treeDoc?.listFiles()?.forEach { file -> if (file.name?.endsWith(".html") == true) { files.add(file) } } if (files.isEmpty()) { Toast.makeText(this, "No hay archivos guardados", Toast.LENGTH_SHORT).show() return } val fileNames = files.map { it.name ?: "Sin nombre" }.toTypedArray() AlertDialog.Builder(this) .setTitle("Archivos guardados") .setItems(fileNames) { _, which -> val selectedFile = files[which] openFile(selectedFile) } .setNegativeButton("Cancelar", null) .show() } private fun openFile(file: DocumentFile) { val progressBar = ProgressBar(this).apply { isIndeterminate = true layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ).apply { gravity = Gravity.CENTER } } val progressText = TextView(this).apply { layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ).apply { gravity = Gravity.CENTER topMargin = (8 * resources.displayMetrics.density).toInt() } setTextColor(Color.WHITE) } val progressContainer = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL gravity = Gravity.CENTER layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT ) addView(progressBar) addView(progressText) } val container = findViewById<ViewGroup>(android.R.id.content).getChildAt(0) as ViewGroup container.addView(progressContainer) lifecycleScope.launch(Dispatchers.IO) { try { val fileContent = StringBuilder() val metadata = mutableListOf<String>() var isMetadata = false var isInMetadataSection = false contentResolver.openInputStream(file.uri)?.use { input -> BufferedReader(InputStreamReader(input), 8192).use { reader -> var line: String? = null while (reader.readLine().also { line = it } != null) { when { line == "<!--DITO-NOTE-FORMAT-START-->" -> { isMetadata = true isInMetadataSection = true } line == "<!--DITO-NOTE-FORMAT-END-->" -> { isMetadata = false isInMetadataSection = false } isInMetadataSection && line?.startsWith("<!--") == true -> { metadata.add(line!!) } !isInMetadataSection -> { fileContent.append(line).append("\n") } } } } } ?: throw Exception("No se pudo abrir el archivo") withContext(Dispatchers.Main) { progressText.text = "Procesando formato..." val spannableString = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Html.fromHtml(fileContent.toString(), Html.FROM_HTML_MODE_LEGACY) } else { Html.fromHtml(fileContent.toString()) } editTextNote.setText(spannableString) val spannable = editTextNote.text as Spannable progressText.text = "Aplicando estilos..." metadata.forEach { meta -> try { when { meta.startsWith("<!--ALIGN:") -> processAlignmentSpan(meta, spannable) meta.startsWith("<!--STYLE:") -> processStyleSpan(meta, spannable) meta.startsWith("<!--UNDERLINE:") -> processUnderlineSpan(meta, spannable) meta.startsWith("<!--COLOR:") -> processColorSpan(meta, spannable) meta.startsWith("<!--HIGHLIGHT:") -> processHighlightSpan(meta, spannable) meta.startsWith("<!--SIZE:") -> processSizeSpan(meta, spannable) meta.startsWith("<!--FONT:") -> processFontSpan(meta, spannable) } } catch (e: Exception) { e.printStackTrace() } } currentFileName = file.name?.removeSuffix(".html") currentFileUri = file.uri setupToolbarSubtitle(currentFileName) hasUnsavedChanges = false isDocumentJustOpened = true updateFontSizeDisplay() } } catch (e: Exception) { withContext(Dispatchers.Main) { Toast.makeText( this@MainActivity, "Error al abrir el archivo: ${e.message}", Toast.LENGTH_LONG ).show() } } finally { withContext(Dispatchers.Main) { container.removeView(progressContainer) } } } } private fun processAlignmentSpan(meta: String, spannable: Spannable) { val parts = meta.removeSurrounding("<!--ALIGN:", "-->").split(":") if (parts.size >= 3) { val start = parts[0].toInt() val end = parts[1].toInt() val alignment = when (parts[2]) { "center" -> Layout.Alignment.ALIGN_CENTER "right" -> Layout.Alignment.ALIGN_OPPOSITE else -> Layout.Alignment.ALIGN_NORMAL } spannable.setSpan( AlignmentSpan.Standard(alignment), start.coerceIn(0, spannable.length), end.coerceIn(0, spannable.length), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) } } private fun processStyleSpan(meta: String, spannable: Spannable) { val parts = meta.removeSurrounding("<!--STYLE:", "-->").split(":") if (parts.size >= 3) { val start = parts[0].toInt() val end = parts[1].toInt() val style = when (parts[2]) { "bold" -> Typeface.BOLD "italic" -> Typeface.ITALIC else -> Typeface.NORMAL } spannable.setSpan( StyleSpan(style), start.coerceIn(0, spannable.length), end.coerceIn(0, spannable.length), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) } } private fun processUnderlineSpan(meta: String, spannable: Spannable) { val parts = meta.removeSurrounding("<!--UNDERLINE:", "-->").split(":") if (parts.size >= 2) { val start = parts[0].toInt() val end = parts[1].toInt() spannable.setSpan( UnderlineSpan(), start.coerceIn(0, spannable.length), end.coerceIn(0, spannable.length), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) } } private fun processColorSpan(meta: String, spannable: Spannable) { val parts = meta.removeSurrounding("<!--COLOR:", "-->").split(":") if (parts.size >= 3) { val start = parts[0].toInt() val end = parts[1].toInt() val color = parts[2].toInt() spannable.setSpan( ForegroundColorSpan(color), start.coerceIn(0, spannable.length), end.coerceIn(0, spannable.length), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) } } private fun processHighlightSpan(meta: String, spannable: Spannable) { val parts = meta.removeSurrounding("<!--HIGHLIGHT:", "-->").split(":") if (parts.size >= 3) { val start = parts[0].toInt() val end = parts[1].toInt() val color = parts[2].toInt() spannable.setSpan( BackgroundColorSpan(color), start.coerceIn(0, spannable.length), end.coerceIn(0, spannable.length), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) } } private fun processSizeSpan(meta: String, spannable: Spannable) { val parts = meta.removeSurrounding("<!--SIZE:", "-->").split(":") if (parts.size >= 3) { val start = parts[0].toInt() val end = parts[1].toInt() val size = parts[2].toInt() spannable.setSpan( RelativeSizeSpan(size / 16f), start.coerceIn(0, spannable.length), end.coerceIn(0, spannable.length), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) } } private fun processFontSpan(meta: String, spannable: Spannable) { val parts = meta.removeSurrounding("<!--FONT:", "-->").split(":") if (parts.size >= 3) { val start = parts[0].toInt() val end = parts[1].toInt() val family = parts[2] spannable.setSpan( TypefaceSpan(family), start.coerceIn(0, spannable.length), end.coerceIn(0, spannable.length), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) } } private fun setupTextWatcher() { editTextNote.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} override fun afterTextChanged(s: Editable?) { if (!isDocumentJustOpened) { hasUnsavedChanges = true } isDocumentJustOpened = false } }) } - Assistant
La función relacionada con "Parcial" está en el método llamado
showSearchDialog(). En ese método se configuran dos botones: uno para búsqueda normal () y otro para búsqueda parcial (), controlando la variable que influye luego en la búsqueda. - User
- Assistant
- User
me lo puedes dar complero y arreglado....MUY INPORTANTE RECORDAR, que NO se cambien ni eliminen partes del código relacionadas con los iconos, los textos, los permisos u otras funcionalidades. No me des soluciones genéricas o que puedan interferir con las funcionalidades.
- Assistant
- User
arregla este porfavor.........
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher_dito_note" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.DitoNote"> <activity android:name=".MainActivity" android:exported="true" android:label="@string/app_name" android:theme="@style/Theme.DitoNote" android:screenOrientation="portrait" android:windowSoftInputMode="adjustResize|stateHidden"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <!-- Filtro para archivos HTML en nuestro directorio --> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:scheme="content" android:host="*" android:pathPattern=".*\\.html" android:mimeType="text/html" /> </intent-filter> </activity> </application> - Assistant
- User
peno la funcionalidad sigue igual y el problrma de la expacion del texto esta arreglado?
- Assistant
- User
ese ajuste no modifica el guardado de los colore sy resaltados del texto?
- Assistant
No, el ajuste para manejar el scroll y que el cursor quede visible al mostrar el teclado no modifica en nada la funcionalidad de guardado de colores, resaltados ni ningún otro estilo de texto.
Por qué:
- El código de desplazamiento que mencioné simplemente usa la posición actual del cursor dentro del EditText para mover el ScrollView y mostrar esa posición al usuario.
- No toca el contenido, ni cambia ni elimina ningún
Spanni formato del texto. - El guardado que tienes con los
Spansy metadata es completamente independiente de cómo se haga el scroll o cómo se gestione la visibilidad del teclado.
En resumen:
- Puedes agregar tranquílamente el ajuste de scroll al mostrar teclado sin temer que afecte a cómo guardas y restauras colores, negritas, fuentes o resaltados.
- Son funcionalidades independientes:
- Grabado / restaurado = manejo de contenido y estilos con spans.
- Scroll automático = manejo visual de la posición de la vista y cursor.
- User
porque removiste este......android:host="*"?
- Assistant
Buena pregunta.
El atributo
android:host="*"no es válido en los filtros de intent en Android. Es decir, no está permitido usar el carácter comodín*para el valor del host en el manifiesto.
Por qué no se puede usar
android:host="*":- En los filtros
<data>,android:hostdebe ser un valor exacto o omitirse. - No existe soporte para "comodines" (wildcards) en
android:host. - Si quieres aceptar cualquier host, simplemente no declares ese atributo.
Por eso, para aceptar cualquier URI con scheme
contentcon un path que termine en.html, el filtro debe expresarse así:<data android:scheme="content" android:pathPattern=".*\\.html" android:mimeType="text/html" /> - En los filtros
- User
lo deje como estaba y funciono bie android:scheme="content" android:host="" android:pathPattern=".\.html" android:mimeType="text/html" />
- Assistant
Gracias por tu comentario. Aunque en la documentación oficial de Android no está soportado usar
android:host="*"como wildcard, algunos dispositivos o versiones específicas de Android pueden tolerarlo sin problemas, y por eso en tu caso parece funcionar.
Consideraciones importantes:
- No es parte de la especificación oficial, por lo que puede no ser portable o funcionar en todos los dispositivos o versiones.
- Puede presentar problemas en ciertas combinaciones de intents, o en futuras actualizaciones de Android.
- En general, la recomendación oficial es omitir el
android:hostsi quieres aceptar cualquier host.
Si en tu contexto funciona bien y no tienes problemas, puedes dejarlo así.**
Pero si buscas la mejor compatibilidad y evitar problemas en el futuro, considera probar también sin ese atributo y verifica que cubre tu caso de uso.
- User
me puedes ayudar con un problema que tengo, es que cuando estoy escribiendo o editando un texto, y minimizo la app y la deslizo par salir de la app, lo que pasa es que cuando la abro de nuevo el documeto queda guardado con la ultima edicion que hice, eso no quiero...lo que quiero es que si cierro la app sin guardar ...que no se guarde los cambios. entendiste. eso donde se arregla del mainativity?
- Assistant
- User
lo arreglas? override fun onPause() { super.onPause() // Guardar el estado actual si es necesario if (currentFileName != null) { saveNoteAsHtml(currentFileName!!) } }
- Assistant
Claro, te lo ajusto para que no guarde automáticamente en
onPause()y así no se persistan los cambios si cierras la app sin guardar explícitamente.Además, te dejo un ejemplo para preguntar al usuario si quiere guardar los cambios cuando intenta salir (solo si hay cambios sin guardar).
Código modificado para
onPause(): - User
es decir qu eremplazo esto---override fun onPause() { super.onPause() if (currentFileName != null) { saveNoteAsHtml(currentFileName!!) } } ---por esto ----override fun onPause() { super.onPause() }
- Assistant
Exacto, eso es justamente lo que debes hacer.
Reemplaza este código:
override fun onPause() { super.onPause() if (currentFileName != null) { saveNoteAsHtml(currentFileName!!) } }
Por este:
override fun onPause() { super.onPause() // No guardar automáticamente para evitar guardar cambios no deseados }
De esta forma, la app ya no guardará automáticamente al minimizar o salir y los cambios se mantendrán solo en memoria hasta que el usuario decida guardarlos explícitamente.
Para asegurarte que el usuario no pierda cambios importantes, te recomiendo implementar el diálogo de confirmación al salir que te mostré antes (en
onBackPressed()), pero si quieres podemos dejarlo opcional.
¿Quieres que te ayude con ese diálogo o alguna otra parte para que quede perfecto?
- User
arregla este override fun onStop() { super.onStop() // Limpiar recursos si es necesario handler.removeCallbacks(flingRunnable ?: return)
- Assistant
Claro, aquí tienes la versión corregida y completa del método
onStop()para que quede correctamente cerrado y sin errores:override fun onStop() { super.onStop() // Limpiar recursos si es necesario handler.removeCallbacks(flingRunnable ?: return) }
Pero la forma en la que está termina abruptamente dentro del
removeCallbackssiflingRunnablees null (?: return).Es mejor evitar usar
returnasí dentro de una expresión y hacerlo más claro, especialmente dentro deonStop.
Versión mejorada y segura:
override fun onStop() { super.onStop() // Limpiar recursos si es necesario flingRunnable?.let { handler.removeCallbacks(it) } }
Explicación
- Usamos el operador seguro
?.letpara remover callbacks solo siflingRunnableno es null. - Evitamos el
?: returnque interrumpe el método dentro de la expresión. - Así el método siempre se ejecuta completo, limpiando el runnable si existe.
- Usamos el operador seguro
- User
perfecto! funciona......tengo otro problemita, que en mi resaltado el fondo queda muy ancho verticalmete ablanco...es decir cuando engo 2 renglones quiero que se distinga . entiendes? te mando el private fun highlightSelectedTextWithContrast o que otra cosa nececitas?
- Assistant
- User
private fun highlightSelectedTextWithContrast(backgroundColor: Int, textColor: Int) { val start = editTextNote.selectionStart val end = editTextNote.selectionEnd if (start < 0 || end <= start) { Toast.makeText(this, "No hay Selección ", Toast.LENGTH_SHORT).show() return } val spannable = editTextNote.text as Spannable spannable.setSpan(BackgroundColorSpan(backgroundColor), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) spannable.setSpan(ForegroundColorSpan(textColor), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) }
- Assistant
- User
- Assistant
- User
Task :app:compileDebugKotlin FAILED e: file:///C:/Users/D10/AndroidStudioProjects/DitoNote/app/src/main/java/com/example/dito_note/MainActivity.kt:1303:53 Argument type mismatch: actual type is 'java.lang.Class<com.example.dito_note.CustomLineBackgroundSpan>', but 'java.lang.Class' was expected.
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.