package com.anas4tech.noteable import android.appwidget.AppWidgetManager import android.content.Context import android.content.Intent import android.net.Uri import android.widget.RemoteViews import android.widget.RemoteViewsService /** Supplies one row per paragraph for vertically scrollable selected-note widget content. */ class SelectedNoteLinesRemoteViewsService : RemoteViewsService() { override fun onGetViewFactory(intent: Intent): RemoteViewsFactory { val widgetId = intent.getIntExtra( AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID ) return SelectedNoteLinesFactory(applicationContext, widgetId) } } private class SelectedNoteLinesFactory( private val context: Context, private val widgetId: Int ) : RemoteViewsService.RemoteViewsFactory { private var lines: List = emptyList() private var noteId: Int = -1 override fun onCreate() = Unit override fun onDataSetChanged() { val prefs = context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE) noteId = prefs.getInt("selected_note_${widgetId}_id", -1) val description = prefs.getString( "selected_note_${widgetId}_description", "" ).orEmpty() lines = if (description.isEmpty()) { emptyList() } else { description.split('\n').map { line -> // Keep empty paragraphs visible in the widget. if (line.isEmpty()) "\u00A0" else line } } } override fun onDestroy() { lines = emptyList() } override fun getCount(): Int = lines.size override fun getViewAt(position: Int): RemoteViews? { val line = lines.getOrNull(position) ?: return null val prefs = context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE) val palette = WidgetTheme.palette(context, prefs) return RemoteViews(context.packageName, R.layout.selected_note_widget_line).apply { setTextViewText(R.id.selected_note_line_text, line) if (!palette.followsSystem) { setTextColor(R.id.selected_note_line_text, palette.secondaryText) } setOnClickFillInIntent( R.id.selected_note_line, Intent().apply { action = WidgetItemClickReceiver.ACTION_OPEN_NOTE putExtra(WidgetItemClickReceiver.EXTRA_NOTE_ID, noteId) data = Uri.parse("noteable://open-note/$noteId?source=widget_view") } ) } } override fun getLoadingView(): RemoteViews? = null override fun getViewTypeCount(): Int = 1 override fun getItemId(position: Int): Long = position.toLong() override fun hasStableIds(): Boolean = false private companion object { const val PREFERENCES = "HomeWidgetPreferences" } }