|
| 1 | +package io.truby.intellij.watcher |
| 2 | + |
| 3 | +import com.intellij.openapi.Disposable |
| 4 | +import com.intellij.openapi.application.ApplicationManager |
| 5 | +import com.intellij.openapi.components.Service |
| 6 | +import com.intellij.openapi.diagnostic.Logger |
| 7 | +import com.intellij.openapi.project.Project |
| 8 | +import com.intellij.openapi.vfs.LocalFileSystem |
| 9 | +import com.intellij.openapi.vfs.VfsUtil |
| 10 | +import io.truby.intellij.config.TrbConfig |
| 11 | +import java.io.File |
| 12 | +import java.nio.file.* |
| 13 | +import java.util.concurrent.atomic.AtomicBoolean |
| 14 | +import kotlin.concurrent.thread |
| 15 | + |
| 16 | +/** |
| 17 | + * Watches the T-Ruby output directory for changes and triggers VFS refresh. |
| 18 | + * This ensures that files compiled by `trc -w` are immediately visible in the IDE. |
| 19 | + */ |
| 20 | +@Service(Service.Level.PROJECT) |
| 21 | +class OutputDirectoryWatcher(private val project: Project) : Disposable { |
| 22 | + private val logger = Logger.getInstance(OutputDirectoryWatcher::class.java) |
| 23 | + private var watchThread: Thread? = null |
| 24 | + private var watchService: WatchService? = null |
| 25 | + private val isRunning = AtomicBoolean(false) |
| 26 | + private var currentWatchDir: String? = null |
| 27 | + |
| 28 | + /** |
| 29 | + * Start watching the output directory. |
| 30 | + * Called automatically when project opens. |
| 31 | + */ |
| 32 | + fun start() { |
| 33 | + if (isRunning.get()) { |
| 34 | + logger.info("OutputDirectoryWatcher already running") |
| 35 | + return |
| 36 | + } |
| 37 | + |
| 38 | + val outputDir = TrbConfig.getOutputDir(project) |
| 39 | + val basePath = project.basePath ?: return |
| 40 | + |
| 41 | + val watchPath = File(basePath, outputDir).toPath() |
| 42 | + |
| 43 | + // Create directory if it doesn't exist |
| 44 | + if (!Files.exists(watchPath)) { |
| 45 | + try { |
| 46 | + Files.createDirectories(watchPath) |
| 47 | + } catch (e: Exception) { |
| 48 | + logger.warn("Failed to create output directory: $watchPath", e) |
| 49 | + return |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + currentWatchDir = watchPath.toString() |
| 54 | + startWatching(watchPath) |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Stop watching and clean up resources. |
| 59 | + */ |
| 60 | + fun stop() { |
| 61 | + isRunning.set(false) |
| 62 | + watchService?.close() |
| 63 | + watchThread?.interrupt() |
| 64 | + watchThread = null |
| 65 | + watchService = null |
| 66 | + currentWatchDir = null |
| 67 | + logger.info("OutputDirectoryWatcher stopped") |
| 68 | + } |
| 69 | + |
| 70 | + /** |
| 71 | + * Restart watching (e.g., when config changes). |
| 72 | + */ |
| 73 | + fun restart() { |
| 74 | + stop() |
| 75 | + start() |
| 76 | + } |
| 77 | + |
| 78 | + private fun startWatching(watchPath: Path) { |
| 79 | + try { |
| 80 | + watchService = FileSystems.getDefault().newWatchService() |
| 81 | + registerRecursively(watchPath) |
| 82 | + |
| 83 | + isRunning.set(true) |
| 84 | + logger.info("Started watching: $watchPath") |
| 85 | + |
| 86 | + watchThread = thread(name = "T-Ruby-OutputWatcher", isDaemon = true) { |
| 87 | + watchLoop() |
| 88 | + } |
| 89 | + } catch (e: Exception) { |
| 90 | + logger.error("Failed to start watching: $watchPath", e) |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + private fun registerRecursively(path: Path) { |
| 95 | + if (!Files.isDirectory(path)) return |
| 96 | + |
| 97 | + path.register( |
| 98 | + watchService, |
| 99 | + StandardWatchEventKinds.ENTRY_CREATE, |
| 100 | + StandardWatchEventKinds.ENTRY_MODIFY, |
| 101 | + StandardWatchEventKinds.ENTRY_DELETE |
| 102 | + ) |
| 103 | + |
| 104 | + // Register subdirectories |
| 105 | + Files.list(path).use { stream -> |
| 106 | + stream.filter { Files.isDirectory(it) } |
| 107 | + .forEach { registerRecursively(it) } |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + private fun watchLoop() { |
| 112 | + while (isRunning.get()) { |
| 113 | + try { |
| 114 | + val key = watchService?.poll(500, java.util.concurrent.TimeUnit.MILLISECONDS) |
| 115 | + ?: continue |
| 116 | + |
| 117 | + val events = key.pollEvents() |
| 118 | + if (events.isNotEmpty()) { |
| 119 | + // Debounce: collect all events before refresh |
| 120 | + Thread.sleep(100) |
| 121 | + |
| 122 | + // Process events |
| 123 | + for (event in events) { |
| 124 | + val kind = event.kind() |
| 125 | + val context = event.context() as? Path ?: continue |
| 126 | + |
| 127 | + logger.debug("File event: $kind - $context") |
| 128 | + |
| 129 | + // Register new directories for recursive watching |
| 130 | + if (kind == StandardWatchEventKinds.ENTRY_CREATE) { |
| 131 | + val watchable = key.watchable() as? Path |
| 132 | + val fullPath = watchable?.resolve(context) |
| 133 | + if (fullPath != null && Files.isDirectory(fullPath)) { |
| 134 | + registerRecursively(fullPath) |
| 135 | + } |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + // Trigger VFS refresh |
| 140 | + refreshVfs() |
| 141 | + } |
| 142 | + |
| 143 | + if (!key.reset()) { |
| 144 | + logger.warn("Watch key is no longer valid") |
| 145 | + break |
| 146 | + } |
| 147 | + } catch (e: InterruptedException) { |
| 148 | + logger.info("Watch thread interrupted") |
| 149 | + break |
| 150 | + } catch (e: ClosedWatchServiceException) { |
| 151 | + logger.info("Watch service closed") |
| 152 | + break |
| 153 | + } catch (e: Exception) { |
| 154 | + logger.warn("Error in watch loop", e) |
| 155 | + } |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + private fun refreshVfs() { |
| 160 | + val watchDir = currentWatchDir ?: return |
| 161 | + |
| 162 | + ApplicationManager.getApplication().invokeLater { |
| 163 | + if (project.isDisposed) return@invokeLater |
| 164 | + |
| 165 | + val virtualFile = LocalFileSystem.getInstance().findFileByPath(watchDir) |
| 166 | + if (virtualFile != null) { |
| 167 | + VfsUtil.markDirtyAndRefresh( |
| 168 | + true, // async |
| 169 | + true, // recursive |
| 170 | + true, // reload children |
| 171 | + virtualFile |
| 172 | + ) |
| 173 | + logger.debug("VFS refreshed: $watchDir") |
| 174 | + } |
| 175 | + } |
| 176 | + } |
| 177 | + |
| 178 | + override fun dispose() { |
| 179 | + stop() |
| 180 | + } |
| 181 | + |
| 182 | + companion object { |
| 183 | + fun getInstance(project: Project): OutputDirectoryWatcher { |
| 184 | + return project.getService(OutputDirectoryWatcher::class.java) |
| 185 | + } |
| 186 | + } |
| 187 | +} |
0 commit comments