/* * This file is part of AndroidIDE. * * AndroidIDE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AndroidIDE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with AndroidIDE. If not, see . */ package com.itsaky.androidide.viewmodel import android.content.Context import android.content.Intent import android.view.Gravity.CENTER import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.google.gson.GsonBuilder import com.itsaky.androidide.models.OpenedFilesCache import com.itsaky.androidide.models.SearchResult import com.itsaky.androidide.projects.IProjectManager import com.itsaky.androidide.projects.ProjectManagerImpl import com.itsaky.androidide.quickbuild.QuickBuildFlashes import com.itsaky.androidide.search.replace.ReplaceSession import com.itsaky.androidide.services.builder.GradleBuildService import com.itsaky.androidide.services.builder.GradleBuildServiceConnnection import com.itsaky.androidide.utils.Environment import com.itsaky.androidide.utils.FileUtils import com.itsaky.androidide.utils.ILogger import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.appdevforall.codeonthego.indexing.service.IndexingState import java.io.File import java.io.IOException import java.util.Collections import java.util.concurrent.atomic.AtomicInteger /** ViewModel for data used in [com.itsaky.androidide.activities.editor.EditorActivityKt] */ @Suppress("PropertyName") class EditorViewModel : ViewModel() { /** * Decides which Quick Build outcomes get a flashbar over the editor (ADFA-4128). Held here * rather than on the activity because the one bit of history it keeps must survive a * configuration change: an activity-scoped instance is rebuilt on rotation, and the rebuilt * one has never seen a failure, so the recovery flash that only fires after one is lost. */ val quickBuildFlashes = QuickBuildFlashes() data class SearchResultSection( val title: String?, val results: Map>, ) data class UiState( val isFullscreen: Boolean = false, ) internal val _isBuildInProgress = MutableLiveData(false) // A build the user never started (Quick Build's proxy app build). Separate from // _isBuildInProgress so it can show progress without offering to cancel. internal val _isInternalBuildInProgress = MutableLiveData(false) internal val _isInitializing = MutableLiveData(false) internal val _statusText = MutableLiveData>("" to CENTER) internal val _displayedFile = MutableLiveData(-1) internal val _startDrawerOpened = MutableLiveData(false) internal val _isSyncNeeded = MutableLiveData(false) internal val _filesModified = MutableLiveData(false) internal val _filesSaving = MutableLiveData(false) private val _openedFiles = MutableLiveData() private val _isBoundToBuildService = MutableLiveData(false) private val _files = MutableLiveData>(ArrayList()) private val _uiState = MutableStateFlow(UiState()) private val _searchResultSections = MutableStateFlow>(emptyList()) val searchResultSections: StateFlow> = _searchResultSections.asStateFlow() private val _replaceSession = MutableStateFlow(null) val replaceSession: StateFlow = _replaceSession.asStateFlow() val uiState: StateFlow = _uiState.asStateFlow() private val searchGeneration = AtomicInteger() /** * Identifies the search whose results are currently displayed. Capture it when starting * an async fan-out and pass it to [onSearchResultSectionsReady] so late results of a * superseded search cannot overwrite a newer one. */ val currentSearchGeneration: Int get() = searchGeneration.get() fun onSearchResultsReady(results: Map>) { searchGeneration.incrementAndGet() _replaceSession.value = null _searchResultSections.value = listOfNotNull( results.takeIf { it.isNotEmpty() }?.let { SearchResultSection(title = null, results = it) }, ) } fun startReplaceSession(session: ReplaceSession) { _replaceSession.value = session } fun toggleReplaceMatch(match: SearchResult) { _replaceSession.update { it?.toggleMatch(match) } } fun toggleReplaceFile(file: File) { _replaceSession.update { it?.toggleFile(file) } } fun clearReplaceSession() { _replaceSession.value = null } /** Publishes [sections] unless [generation] no longer matches [currentSearchGeneration]. */ fun onSearchResultSectionsReady( generation: Int, sections: List, ) { if (generation != searchGeneration.get()) { return } _searchResultSections.value = sections } /** * Holds information about the currently selected editor fragment. First value in the pair is the * index of the editor opened. Second value is the file that is opened. */ private val mCurrentFile = MutableLiveData?>(null) @get:JvmName("currentFileLiveData") val currentFile: LiveData?> get() = mCurrentFile var areFilesModified: Boolean get() = _filesModified.value ?: false set(value) { _filesModified.value = value } var areFilesSaving: Boolean get() = _filesSaving.value ?: false set(value) { _filesSaving.value = value } /** * Saves in flight, paired with [areFilesSaving]. * * Lives here rather than in the editor activity because this ViewModel is retained across * activity recreation while the activity is not: a save started before a dark-mode, locale * or display-size change keeps running under `NonCancellable` against the old instance, and * a per-instance counter would let that completion clear the flag for a save the new * instance had already started. * * Main-thread confined - callers hop to Main before touching it, as the flag itself * requires. */ private var activeSaveCount = 0 /** Raises [areFilesSaving] for the first of any number of overlapping saves. */ fun beginFileSave() { if (++activeSaveCount == 1) { areFilesSaving = true } } /** * Lowers [areFilesSaving] once the last in-flight save finishes. * * Floored at zero: an unbalanced call must not drive the count negative, or the "reached * zero" test never matches again and SaveFileAction stays disabled * (`enabled = areFilesModified && !areFilesSaving`) for the life of this ViewModel. */ fun endFileSave() { activeSaveCount = (activeSaveCount - 1).coerceAtLeast(0) if (activeSaveCount == 0) { areFilesSaving = false val actions = afterSaves.toList() afterSaves.clear() actions.forEach { it() } } } private val afterSaves = mutableListOf<() -> Unit>() /** * Runs [action] once no save is in flight: now, or when the last one finishes. Lives here for * the same reason as [activeSaveCount] - the save that drains the count may belong to either * side of a recreate. Main-thread confined. */ fun whenNoSaves(action: () -> Unit) { if (activeSaveCount == 0) action() else afterSaves += action } var openedFilesCache: OpenedFilesCache? get() = _openedFiles.value set(value) { this._openedFiles.value = value } var isBoundToBuildSerice: Boolean get() = _isBoundToBuildService.value ?: false set(value) { _isBoundToBuildService.value = value } private val buildServiceConnection = GradleBuildServiceConnnection() private var buildServiceContext: Context? = null fun bindBuildService( context: Context, onConnected: (GradleBuildService) -> Unit, ): Boolean { val appContext = context.applicationContext buildServiceConnection.onConnected = onConnected buildServiceContext = appContext return appContext.bindService( Intent(appContext, GradleBuildService::class.java), buildServiceConnection, Context.BIND_AUTO_CREATE or Context.BIND_IMPORTANT, ) } fun clearBuildServiceCallback() { buildServiceConnection.onConnected = null } fun unbindBuildService() { val context = buildServiceContext ?: return buildServiceContext = null buildServiceConnection.onConnected = null isBoundToBuildSerice = false context.unbindService(buildServiceConnection) } override fun onCleared() { unbindBuildService() super.onCleared() } var isBuildInProgress: Boolean get() = _isBuildInProgress.value ?: false set(value) { _isBuildInProgress.value = value } var isInternalBuildInProgress: Boolean get() = _isInternalBuildInProgress.value ?: false set(value) { _isInternalBuildInProgress.value = value } var isInitializing: Boolean get() = _isInitializing.value ?: false set(value) { _isInitializing.value = value } var statusText: CharSequence get() = this._statusText.value?.first ?: "" set(value) { _statusText.value = value to (_statusText.value?.second ?: 0) } var statusGravity: Int get() = this._statusText.value?.second ?: CENTER set(value) { _statusText.value = (_statusText.value?.first ?: "") to value } /** The latest class indexing state the editor has observed. */ var indexingState: IndexingState = IndexingState.Idle private set /** Whether class indexing is in flight, derived from [indexingState]. */ val isIndexing: Boolean get() = indexingState is IndexingState.Indexing /** The indexing text last written to the status slot, or null if none is shown. */ private var shownIndexingStatus: CharSequence? = null /** The message the indexing text replaced in the status slot, restored when indexing ends. */ private var replacedStatus: CharSequence? = null /** Records [state], as reported by the project's indexing service manager. */ internal fun onIndexingStateChanged(state: IndexingState) { indexingState = state } /** * Updates the status slot for [indexingState], formatting its progress with [formatProgress]. * * [isSlotOwnedElsewhere] is true while a build, project initialization or debugger start owns * the slot; see [resolveIndexingStatus]. */ fun updateIndexingStatus( isSlotOwnedElsewhere: Boolean, formatProgress: (done: Int, total: Int) -> CharSequence, ) { val indexingStatus = (indexingState as? IndexingState.Indexing)?.let { formatProgress(it.done, it.total) } val current = statusText val next = resolveIndexingStatus(isSlotOwnedElsewhere, indexingStatus, current, shownIndexingStatus, replacedStatus) ?: return if (indexingStatus != null && shownIndexingStatus?.contentEquals(current) != true) { replacedStatus = current } if (indexingStatus == null) { replacedStatus = null } shownIndexingStatus = indexingStatus _statusText.value = next to CENTER } var displayedFileIndex: Int get() = _displayedFile.value!! set(value) { _displayedFile.value = value } var startDrawerOpened: Boolean get() = _startDrawerOpened.value ?: false set(value) { _startDrawerOpened.value = value } var isSyncNeeded: Boolean get() = _isSyncNeeded.value ?: false set(value) { _isSyncNeeded.value = value } var isFullscreen: Boolean get() = uiState.value.isFullscreen set(value) { updateFullscreen(value) } fun updateFullscreen(value: Boolean) { _uiState.update { current -> if (current.isFullscreen == value) { current } else { current.copy(isFullscreen = value) } } } fun toggleFullscreen() { updateFullscreen(!uiState.value.isFullscreen) } fun exitFullscreen() { updateFullscreen(false) } internal var files: MutableList get() = this._files.value ?: Collections.emptyList() set(value) { this._files.value = value } private inline fun updateFiles(crossinline action: (files: MutableList) -> Unit) { val files = this.files action(files) this.files = files } /** * Add the given file to the list of opened files. * * @param file The file that has been opened. */ fun addFile(file: File) = updateFiles { files -> files.add(file) } /** * Remove the file at the given index from the list of opened files. * * @param index The index of the closed file. */ fun removeFile(index: Int) = updateFiles { files -> files.removeAt(index) if (files.isEmpty()) { mCurrentFile.value = null } } fun removeAllFiles() = updateFiles { files -> files.clear() setCurrentFile(-1, null) } fun setCurrentFile( index: Int, file: File?, ) { displayedFileIndex = index mCurrentFile.value = index to file } fun updateFile( index: Int, newFile: File, ) = updateFiles { files -> files[index] = newFile } /** * Get the opened file at the given index. * * @param index The index of the file. * @return The file at the given index. */ fun getOpenedFile(index: Int): File = files[index] /** * Get the number of files opened. * * @return The number of files opened. */ fun getOpenedFileCount(): Int = files.size /** * Get the list of currently opened files. * * @return The list of opened files. */ fun getOpenedFiles(): List = Collections.unmodifiableList(files) /** * Add an observer to the list of opened files. * * @param lifecycleOwner The lifecycle owner. * @param observer The observer. */ fun observeFiles( lifecycleOwner: LifecycleOwner?, observer: Observer?>?, ) { _files.observe(lifecycleOwner!!, observer!!) } fun getCurrentFileIndex(): Int = mCurrentFile.value?.first ?: -1 fun getCurrentFile(): File? = mCurrentFile.value?.second /** * Get the [OpenedFilesCache] if it is already loaded, otherwise read the cache from the file system * and invoke the given callback. * * If the cache is already loaded, [result] is called on the same thread. Otherwise, it is * always called on the main/UI thread. */ inline fun getOrReadOpenedFilesCache(crossinline result: (OpenedFilesCache?) -> Unit) = openedFilesCache?.let(result) ?: run { viewModelScope .launch(Dispatchers.IO) { val cache = try { val cacheFile = getOpenedFilesCache(false) if (cacheFile.exists() && cacheFile.length() > 0L) { cacheFile.bufferedReader().use(OpenedFilesCache::parse) } else { null } } catch (err: IOException) { // ignore exception null } withContext(Dispatchers.Main) { result(cache) } }.also { job -> handleOpenedFilesCacheJobCompletion(job, "read") } Unit } fun handleOpenedFilesCacheJobCompletion( it: Job, operation: String, ) { it.invokeOnCompletion { err -> if (err != null) { ILogger.ROOT.error( "[EditorViewModel] Failed to {} opened files cache", operation, err, ) } } } fun writeOpenedFiles(cache: OpenedFilesCache?) { viewModelScope .launch(Dispatchers.IO) { val file = getOpenedFilesCache(true) if (cache == null) { file.delete() return@launch } try { file.parentFile?.mkdirs() // Convert data to JSON and write to the file. // `writeText` will create the file if it doesn't exist. val gson = GsonBuilder().setPrettyPrinting().create() val string = gson.toJson(cache) file.writeText(string) } catch (e: IOException) { ILogger.ROOT.error( "[EditorViewModel] Failed to write opened files cache", e, ) } }.also { job -> handleOpenedFilesCacheJobCompletion(job, "write") } } @PublishedApi internal fun getOpenedFilesCache(forWrite: Boolean = false): File { var file = Environment.getProjectCacheDir(IProjectManager.getInstance().projectDir) file = File(file, "editor/openedFiles.json") if (file.exists() && forWrite) { FileUtils.rename(file, "${file.name}.bak") } return file } /** * Returns the open project's directory name, or an empty string when no project path is * available (the process-death recreation state where the project path is uninitialized). */ fun getProjectName(): String { val manager = ProjectManagerImpl.getInstance() val path = manager.projectDirPath if (path.isBlank()) { return "" } return manager.projectDir.name } } /** * Decides what the status slot shows next for class indexing, or returns null to leave it alone. * * While [isSlotOwnedElsewhere] (a build, project initialization or debugger start is running) the * slot is left to that operation. Otherwise [indexingStatus], the progress text or null when * indexing is idle, takes it. When indexing ends the slot goes back to [replacedStatus], the message * the indexing text replaced (a build result, say), or is cleared if there was none. It does so * only if the slot still shows [shownIndexingStatus], the indexing text last written there, so a * newer message survives. */ internal fun resolveIndexingStatus( isSlotOwnedElsewhere: Boolean, indexingStatus: CharSequence?, currentStatus: CharSequence, shownIndexingStatus: CharSequence?, replacedStatus: CharSequence? = null, ): CharSequence? = when { isSlotOwnedElsewhere -> null indexingStatus != null -> indexingStatus.takeUnless { it.contentEquals(currentStatus) } shownIndexingStatus?.contentEquals(currentStatus) == true -> replacedStatus ?: "" else -> null }