Skip to content

Commit

Permalink
Merge branch 'master' into release
Browse files Browse the repository at this point in the history
  • Loading branch information
MaxKless committed Feb 2, 2024
2 parents ea9e21a + 5f43593 commit 74422dd
Show file tree
Hide file tree
Showing 22 changed files with 401 additions and 168 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package dev.nx.console.graph

import NxGraphServer
import com.intellij.ide.ui.UISettingsListener
import com.intellij.notification.NotificationType
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
Expand Down Expand Up @@ -37,7 +38,7 @@ abstract class NxGraphBrowserBase(protected val project: Project) : Disposable {
protected val browser: JBCefBrowser = JBCefBrowser()
protected val graphServer: NxGraphServer = StandardNxGraphServer.getInstance(project)

protected val backgroundColor = getHexColor(UIUtil.getPanelBackground())
protected var backgroundColor = getHexColor(UIUtil.getPanelBackground())
protected val queryMessenger = JBCefJSQuery.create(browser as JBCefBrowserBase)
protected val browserLoadedState: MutableStateFlow<Boolean> = MutableStateFlow(false)

Expand All @@ -51,16 +52,20 @@ abstract class NxGraphBrowserBase(protected val project: Project) : Disposable {
OpenDevToolsContextMenuHandler(),
browser.cefBrowser
)
browser.setPageBackgroundColor(backgroundColor)
browser.setOpenLinksInExternalBrowser(true)

registerThemeListener()
setColors()

queryMessenger.addHandler { msg ->
when (msg) {
"ready" -> browserLoadedState.value = true
else -> {
try {
val messageParsed = Json.decodeFromString<NxGraphRequest>(msg)
CoroutineScope(Dispatchers.Default).launch {
CoroutineScope(Dispatchers.IO).launch {
val response = graphServer.handleGraphRequest(messageParsed)

browser.executeJavaScript(
"window.intellij.handleResponse(${Json.encodeToString(response)})"
)
Expand Down Expand Up @@ -267,6 +272,38 @@ abstract class NxGraphBrowserBase(protected val project: Project) : Disposable {
}
}

private fun registerThemeListener() {
val connection = ApplicationManager.getApplication().messageBus.connect()
connection.subscribe(UISettingsListener.TOPIC, UISettingsListener { setColors() })
}

private fun setColors() {
backgroundColor = getHexColor(UIUtil.getPanelBackground())
browser.setPageBackgroundColor(backgroundColor)
executeWhenLoaded {
browser.executeJavaScript(
"""
const isDark = ${!JBColor.isBright()};
const body = document.body;
const darkClass = 'vscode-dark';
const lightClass = 'vscode-light';
body.classList.remove(darkClass, lightClass);
if (isDark) {
body.classList.add(darkClass);
} else {
body.classList.add(lightClass);
}
console.log("$backgroundColor")
body.style.setProperty('background-color', '$backgroundColor', 'important');
"""
.trimIndent()
)
}
}

override fun dispose() {
browser.dispose()
}
Expand Down
90 changes: 42 additions & 48 deletions apps/intellij/src/main/kotlin/dev/nx/console/graph/NxGraphServer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import com.intellij.openapi.Disposable
import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.util.messages.Topic
import com.intellij.util.io.readLineAsync
import dev.nx.console.graph.NxGraphRequest
import dev.nx.console.nxls.NxWorkspaceRefreshListener
import dev.nx.console.nxls.NxlsService
Expand Down Expand Up @@ -47,8 +47,6 @@ open class NxGraphServer(
var currentPort: Int? = null
private var nxGraphProcess: Process? = null

private val client = HttpClient.newBuilder().build()

private var isStarted = false
private var isStarting = false

Expand All @@ -71,32 +69,46 @@ open class NxGraphServer(
}
}

suspend fun handleGraphRequest(request: NxGraphRequest): NxGraphRequest {
if (nxGraphProcess?.isAlive != true) {
start()
waitForServerReady()
}
if (!isStarted) {
waitForServerReady()
}
suspend fun handleGraphRequest(request: NxGraphRequest, attempt: Int = 0): NxGraphRequest {
try {

var url = "http://localhost:${this.currentPort}/"
url +=
when (request.type) {
"requestProjectGraph" -> "project-graph.json"
"requestTaskGraph" -> "task-graph.json"
"requestExpandedTaskInputs" -> "task-inputs.json?taskId=${request.payload}"
"requestSourceMaps" -> "source-maps.json"
else -> throw Exception("unknown request type ${request.type}")
if (nxGraphProcess?.isAlive != true && !isStarting) {
start()
waitForServerReady()
}
if (!isStarted) {
waitForServerReady()
}

var url = "http://localhost:${this.currentPort}/"
url +=
when (request.type) {
"requestProjectGraph" -> "project-graph.json"
"requestTaskGraph" -> "task-graph.json"
"requestExpandedTaskInputs" -> "task-inputs.json?taskId=${request.payload}"
"requestSourceMaps" -> "source-maps.json"
else -> throw Exception("unknown request type ${request.type}")
}

val httpRequest = HttpRequest.newBuilder().uri(URI.create(url)).build()
val response =
withContext(Dispatchers.IO) {
val client = HttpClient.newBuilder().build()

val response =
withContext(Dispatchers.IO) {
client.send(httpRequest, HttpResponse.BodyHandlers.ofString())
val httpRequest =
HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Accept-Encoding", "gzip, deflate")
.build()
client.send(httpRequest, HttpResponse.BodyHandlers.ofString())
}
return NxGraphRequest(type = request.type, id = request.id, payload = response.body())
} catch (e: Throwable) {
logger.info("error while handling graph request: $e")
if (attempt == 0) {
return handleGraphRequest(request, 1)
}
return NxGraphRequest(type = request.type, id = request.id, payload = response.body())
return request
}
}

fun start() {
Expand All @@ -121,7 +133,6 @@ open class NxGraphServer(
val process = spawnProcess(port)
nxGraphProcess = process
handleGraphProcessError(process)
listenForGraphUpdates()

isStarted = true
isStarting = false
Expand Down Expand Up @@ -160,13 +171,14 @@ open class NxGraphServer(
// wait for process to start - signified by logging the port
val reader = process.inputStream.bufferedReader()
var stopWaiting = false
var line: String? = null
line = reader.readLineAsync()

while (!stopWaiting && reader.ready()) {
val line = reader.readLine()?.trim()?.lowercase()

while (!stopWaiting) {
if (line != null && line.contains(port.toString())) {
stopWaiting = true
}
line = reader.readLineAsync()?.trim()?.lowercase()
}

process
Expand All @@ -183,25 +195,11 @@ open class NxGraphServer(
}
}

private fun listenForGraphUpdates() {
nxGraphProcess?.also {
CoroutineScope(Dispatchers.IO).launch {
it.inputStream.bufferedReader().use { reader ->
while (isActive && it.isAlive) {
val line = reader.readLine()
if (line != null && line.contains("updated")) {
project.messageBus.syncPublisher(NX_GRAPH_SERVER_REFRESH).onRefresh()
}
}
}
}
}
}

private fun handleGraphProcessError(process: Process) {
process.onExit().thenAccept { exitCode ->
logger.debug("graph server exited with code $exitCode")
isStarted = false
isStarting = false
nxGraphProcess = null
process.errorStream.readAllBytes().decodeToString().run { logger.debug(this) }
}
Expand All @@ -217,11 +215,7 @@ open class NxGraphServer(
nxGraphProcess?.destroyForcibly()
nxGraphProcess = null
isStarted = false
}

companion object {
val NX_GRAPH_SERVER_REFRESH: Topic<NxGraphServerRefreshListener> =
Topic("NxGraphServerRefresh", NxGraphServerRefreshListener::class.java)
isStarting = false
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ class OldNxGraphBrowser(
padding: 20px;
}
</style>
<p>Unable to load the project graph. The following error occured:</p>
<p>Unable to load the project graph. The following error occurred:</p>
<pre>${errorMessage}</pre>
"""
.trimIndent()
Expand Down
25 changes: 12 additions & 13 deletions apps/intellij/src/main/kotlin/dev/nx/console/nxls/NxlsService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,9 @@ import dev.nx.console.nxls.server.*
import dev.nx.console.nxls.server.requests.*
import dev.nx.console.utils.Notifier
import dev.nx.console.utils.nxlsWorkingPath
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import java.lang.Runnable
import kotlinx.coroutines.*
import kotlinx.coroutines.future.await
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import org.eclipse.lsp4j.jsonrpc.MessageIssueException
import org.eclipse.lsp4j.jsonrpc.ResponseErrorException

Expand Down Expand Up @@ -45,13 +43,10 @@ class NxlsService(val project: Project) {

suspend fun start() {
wrapper.start()
awaitStarted()
client()?.registerRefreshCallback {
CoroutineScope(Dispatchers.Default).launch {
workspace().run {
project.messageBus
.syncPublisher(NX_WORKSPACE_REFRESH_TOPIC)
.onNxWorkspaceRefresh()
}
project.messageBus.syncPublisher(NX_WORKSPACE_REFRESH_TOPIC).onNxWorkspaceRefresh()
}
}
}
Expand All @@ -64,11 +59,9 @@ class NxlsService(val project: Project) {
CoroutineScope(Dispatchers.Default).launch {
if (!wrapper.isStarted()) {
start()
awaitStarted()
}

workspace().run {
project.messageBus.syncPublisher(NX_WORKSPACE_REFRESH_TOPIC).onNxWorkspaceRefresh()
}
server()?.getNxService()?.refreshWorkspace()
}
}
Expand Down Expand Up @@ -161,7 +154,9 @@ class NxlsService(val project: Project) {
}

suspend fun nxVersion(): NxVersion? {
return this.workspace()?.nxVersion
return withMessageIssueCatch("nx/version") {
server()?.getNxService()?.version()?.await()
}()
}

fun addDocument(editor: Editor) {
Expand All @@ -186,6 +181,10 @@ class NxlsService(val project: Project) {
wrapper.awaitStarted().thenRun(block)
}

suspend fun awaitStarted() {
wrapper.awaitStarted().await()
}

private fun <T> withMessageIssueCatch(
requestName: String,
block: suspend () -> T
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ private val log = logger<NxlsLanguageClient>()
class NxlsLanguageClient : LanguageClient {

val refreshCallbacks: MutableList<() -> Unit> = mutableListOf()

override fun telemetryEvent(`object`: Any?) {
TODO("Not yet implemented")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,11 @@ interface NxService {
throw UnsupportedOperationException()
}

@JsonRequest
fun version(): CompletableFuture<NxVersion> {
throw UnsupportedOperationException()
}

@JsonNotification
fun changeWorkspace(workspacePath: String) {
throw UnsupportedOperationException()
Expand Down
Loading

0 comments on commit 74422dd

Please sign in to comment.