Compare commits

..

1 commit

Author SHA1 Message Date
cb6958d78a
ci: [NO BACKPORT] update to 2025.1 EAP 2025-01-30 14:42:36 +01:00
276 changed files with 2501 additions and 7501 deletions

View file

@ -17,204 +17,9 @@ Changelog structure reference:
## [Unreleased] ## [Unreleased]
## [25.2.0]
### Added ### Added
- Debugger - Support for idea 2025.1
- Notify the user if zig run / zig test debugging starts, but a build.zig is present
### Changed
- Project
- Line marker task suggestions for main/test now defer to Zig Build if build.zig file is detected.
### Fixed
- Debugger
- Compilation failures did not open the terminal properly and suppressed the error message
## [25.1.0]
### Added
- IDEA 2025.1 support
- LSP
- Configurable inlay hints file size limit to reduce IDE lag
## [25.0.2]
### Fixed
- Project
- ZLS settings not scrollable in the language server list
## [25.0.1]
### Fixed
- Project
- Zig.iml file created in every project
### Changed
- Project
- BREAKING MAJOR UPDATE: Fully reworked toolchain and language server management
The configuration menu is now very similar to the intellij java toolchain management,
with proper toolchain selection, detection, downloading, etc. This change will require
you to re-configure your toolchains!
- Zig external library root is now no longer shown if zig is not configured
## [24.0.1]
### Added
- Project, Debugging
- TTY support for zig processes
### Removed
- Project
- "Emulate terminal" and "colored output" config options have been removed from zig run/test/build tasks, as they are no longer required for ZigBrains to work.
### Fixed
- Debugger
- Build errors didn't get shown in the console
- Project
- File path browse buttons in zig run configurations didn't work
- Occasional GUI deadlocks
- Zig
- IPC wrapper wasn't passing exit code
## [23.1.2]
### Fixed
- LSP
- IDE warning when renaming symbols
## [23.1.1]
### Fixed
- Project
- New project creation creates a blank ZLS config
## [23.1.0]
### Added
- Project
- Support running file main/tests with hotkey (default: ctrl+shift+f10)
### Changed
- Direnv
- Centralized all direnv toggling into a single project-level option
## [23.0.2]
### Fixed
- Zig
- Documentation comment after regular comment was being highlighted as regular comment
## [23.0.1]
### Fixed
- Project
- mkfifo/bash for zig progress visualization is now detected more reliably (fixes error on macOS)
- Deadlock when launching zig build tasks
## [23.0.0]
### Added
- Project
- Zig std.Progress visualization in the zig tool window (Linux/macOS only)
### Removed
- Project
- Executable / Library new project templates temporarily removed until zig stabilizes
## [22.0.1]
### Fixed
- LSP
- Changing ZLS configs would not restart ZLS
- Project
- Occasional "AWT events are not allowed inside write action" error coming from LSP
- IllegalStateException coming from the standard library handler
## [22.0.0]
### Added
- LSP
- Error/Warning banner at the top of the editor when ZLS is misconfigured/not running
- ZLS version indicator in the zig settings
- Toolchain
- More descriptive error messages when toolchain detection fails
### Changed
- Project
- !!BREAKING CHANGE!! Changed file format of zig tasks to store command line arguments as strings instead of string lists.
This (and newer) versions of the plugin will automatically upgrade tasks from 21.1.0 and before.
### Fixed
- Debugging
- Breakpoints could not be placed inside zig code in Android Studio
- Project
- Zig run/debug configuration command line arguments would lose quotes around arguments
## [21.1.0]
### Added
- Zon
- ZLS integration
### Changed
- Zon
- Fully refactored the parser for parity with the zig parser
## [21.0.0]
### Added
- Zig
- Changing the zig standard library path in the project settings now properly updates the dependency
- ZLS
- All of the config options are now exposed in the GUI
### Changed
- Project
- New project panel is now much more compact
### Fixed
- Zig
- `zig env` failure causes an IDE error
- A local toolchain disappearing (std directory or zig exe deleted) is now handled properly
## [20.3.0]
- Zig
- Improved default colors
## [20.2.2] ## [20.2.2]

53
CODE_OF_CONDUCT.md Normal file
View file

@ -0,0 +1,53 @@
# Code of Merit
1. The project creators, lead developers, core team, constitute
the managing members of the project and have final say in every decision
of the project, technical or otherwise, including overruling previous decisions.
There are no limitations to this decisional power.
2. Contributions are an expected result of your membership on the project.
Don't expect others to do your work or help you with your work forever.
3. All members have the same opportunities to seek any challenge they want
within the project.
4. Authority or position in the project will be proportional
to the accrued contribution. Seniority must be earned.
5. Software is evolutive: the better implementations must supersede lesser
implementations. Technical advantage is the primary evaluation metric.
6. This is a space for technical prowess; topics outside of the project
will not be tolerated.
7. Non technical conflicts will be discussed in a separate space. Disruption
of the project will not be allowed.
8. Individual characteristics, including but not limited to,
body, sex, sexual preference, race, language, religion, nationality,
or political preferences are irrelevant in the scope of the project and
will not be taken into account concerning your value or that of your contribution
to the project.
9. Discuss or debate the idea, not the person.
10. There is no room for ambiguity: Ambiguity will be met with questioning;
further ambiguity will be met with silence. It is the responsibility
of the originator to provide requested context.
11. If something is illegal outside the scope of the project, it is illegal
in the scope of the project. This Code of Merit does not take precedence over
governing law.
12. This Code of Merit governs the technical procedures of the project not the
activities outside of it.
13. Participation on the project equates to agreement of this Code of Merit.
14. No objectives beyond the stated objectives of this project are relevant
to the project. Any intent to deviate the project from its original purpose
of existence will constitute grounds for remedial action which may include
expulsion from the project.
This document is adapted from the Code of Merit, version 1.0.
See: https://codeofmerit.org/.

10
LICENSE
View file

@ -1,5 +1,5 @@
ZigBrains ZigBrains
Copyright (C) 2023-2025 FalsePattern Copyright (C) 2023-2024 FalsePattern
All Rights Reserved All Rights Reserved
The above copyright notice and this permission notice shall be included The above copyright notice and this permission notice shall be included
@ -25,11 +25,6 @@ which are the property of the Zig Software Foundation.
(https://github.com/ziglang/logo) (https://github.com/ziglang/logo)
These art assets are licensed under Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0). These art assets are licensed under Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0).
-------------------------------- --------------------------------
The art assets inside src/art/zls, and all copies of them, are derived from the Zig Language Server,
which are the property of the zigtools organization.
(https://github.com/zigtools/zls)
These art assets are licensed under MIT license.
--------------------------------
Parts of the codebase are based on the intellij-zig plugin, Parts of the codebase are based on the intellij-zig plugin,
developed by HTGAzureX1212 (https://github.com/HTGAzureX1212), licensed under the Apache 2.0 license. developed by HTGAzureX1212 (https://github.com/HTGAzureX1212), licensed under the Apache 2.0 license.
-------------------------------- --------------------------------
@ -42,5 +37,4 @@ All of the licenses listed here are available in the following files, bundled wi
- licenses/CC_BY_SA_4.0.LICENSE - licenses/CC_BY_SA_4.0.LICENSE
- licenses/GPL3.LICENSE - licenses/GPL3.LICENSE
- licenses/INTELLIJ-RUST.LICENSE - licenses/INTELLIJ-RUST.LICENSE
- licenses/LGPL3.LICENSE - licenses/LGPL3.LICENSE
- licenses/ZLS.LICENSE

View file

@ -15,7 +15,6 @@ through the built-in plugin browser:
1. Go to `Settings -> Plugins` 1. Go to `Settings -> Plugins`
2. To the right of the `Installed` button at the top, click on the `...` dropdown menu, then select `Manage Plugin Repositories...` 2. To the right of the `Installed` button at the top, click on the `...` dropdown menu, then select `Manage Plugin Repositories...`
3. Click the add button, and then enter the ZigBrains updater URL, based on your IDE version: 3. Click the add button, and then enter the ZigBrains updater URL, based on your IDE version:
- `2025.1.*` or newer: https://falsepattern.com/zigbrains/updatePlugins-251.xml
- `2024.3.*`: https://falsepattern.com/zigbrains/updatePlugins-243.xml - `2024.3.*`: https://falsepattern.com/zigbrains/updatePlugins-243.xml
- `2024.2.*`: https://falsepattern.com/zigbrains/updatePlugins-242.xml - `2024.2.*`: https://falsepattern.com/zigbrains/updatePlugins-242.xml
- `2024.1.*`: https://falsepattern.com/zigbrains/updatePlugins-241.xml - `2024.1.*`: https://falsepattern.com/zigbrains/updatePlugins-241.xml
@ -39,7 +38,6 @@ and might as well utilize the full semver string for extra information.
## Supporters ## Supporters
- ### [Techatrix](https://github.com/Techatrix) - ### [Techatrix](https://github.com/Techatrix)
- ### [nuxusr](https://github.com/nuxusr)
- gree7 - gree7
- xceno - xceno
- AnErrupTion - AnErrupTion
@ -72,7 +70,11 @@ excellent example on how to write debugger support that doesn't depend on CLion.
<!-- Plugin description --> <!-- Plugin description -->
Adds support for the Zig Language, utilizing the ZLS language server for advanced coding assistance. Adds support for the Zig Language, utilizing the ZLS language server for advanced coding assistance.
Before you can properly use the plugin, you need to select or download the Zig toolchain and language server in `Settings` -> `Languages & Frameworks` -> `Zig`. ## Quick setup guide for Zig and ZLS
1. Download the latest version of Zig from https://ziglang.org/download
2. Download and compile the ZLS language server, available at https://github.com/zigtools/zls
3. Go to `Settings` -> `Languages & Frameworks` -> `Zig`, and point the `Toolchain Location` and `ZLS path` to the correct places
## Debugging ## Debugging
@ -86,7 +88,6 @@ Debugging Zig code is supported in any native debugging capable IDE. The followi
- RustRover (including the non-commercial free version too) - RustRover (including the non-commercial free version too)
- GoLand - GoLand
- PyCharm Professional - PyCharm Professional
- Android Studio
Additionally, in CLion, the plugin uses the C++ Toolchains for sourcing the debugger (this can be toggled off in the settings). Additionally, in CLion, the plugin uses the C++ Toolchains for sourcing the debugger (this can be toggled off in the settings).

View file

@ -6,15 +6,15 @@ import org.jetbrains.kotlin.gradle.dsl.KotlinJvmProjectExtension
import org.jetbrains.kotlin.gradle.tasks.KotlinCompilationTask import org.jetbrains.kotlin.gradle.tasks.KotlinCompilationTask
plugins { plugins {
kotlin("jvm") version "2.1.10" apply false kotlin("jvm") version "2.1.0" apply false
kotlin("plugin.serialization") version "2.1.10" apply false kotlin("plugin.serialization") version "2.1.0" apply false
id("org.jetbrains.intellij.platform") version "2.5.0" id("org.jetbrains.intellij.platform") version "2.2.1"
id("org.jetbrains.changelog") version "2.2.1" id("org.jetbrains.changelog") version "2.2.1"
id("org.jetbrains.grammarkit") version "2022.3.2.2" apply false id("org.jetbrains.grammarkit") version "2022.3.2.2" apply false
idea idea
`maven-publish` `maven-publish`
} }
val publishVersions = listOf("241", "242", "243", "251") val publishVersions = listOf("241", "242", "243")
val pluginVersionFull get() = "$pluginVersion-$pluginSinceBuild" val pluginVersionFull get() = "$pluginVersion-$pluginSinceBuild"
val pluginVersion: String by project val pluginVersion: String by project
val pluginSinceBuild: String by project val pluginSinceBuild: String by project
@ -60,6 +60,7 @@ tasks {
allprojects { allprojects {
idea { idea {
module { module {
isDownloadJavadoc = false
isDownloadSources = true isDownloadSources = true
} }
} }
@ -109,7 +110,6 @@ dependencies {
runtimeOnly(project(":core")) runtimeOnly(project(":core"))
runtimeOnly(project(":cidr")) runtimeOnly(project(":cidr"))
runtimeOnly(project(":lsp"))
} }
intellijPlatform { intellijPlatform {
@ -205,7 +205,6 @@ publishVersions.forEach {
archiveFile = distFile(it) archiveFile = distFile(it)
token = providers.environmentVariable("IJ_PUBLISH_TOKEN") token = providers.environmentVariable("IJ_PUBLISH_TOKEN")
channels = if (pluginVersion.contains("-")) listOf("nightly") else listOf("default") channels = if (pluginVersion.contains("-")) listOf("nightly") else listOf("default")
setDependsOn(dependsOn.filter { if (it is TaskProvider<*>) it.name != "signPlugin" && it.name != "buildPlugin" else true })
} }
tasks.named("publish").configure { tasks.named("publish").configure {
dependsOn("jbpublish-$it") dependsOn("jbpublish-$it")

View file

@ -1,29 +1,23 @@
#!/bin/sh #!/bin/sh
# #
# This file is part of ZigBrains. # Copyright 2023-2024 FalsePattern
# #
# Copyright (C) 2023-2025 FalsePattern # Licensed under the Apache License, Version 2.0 (the "License");
# All Rights Reserved # you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# #
# The above copyright notice and this permission notice shall be included # http://www.apache.org/licenses/LICENSE-2.0
# in all copies or substantial portions of the Software.
# #
# ZigBrains is free software: you can redistribute it and/or modify # Unless required by applicable law or agreed to in writing, software
# it under the terms of the GNU Lesser General Public License as published by # distributed under the License is distributed on an "AS IS" BASIS,
# the Free Software Foundation, only version 3 of the License. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# # See the License for the specific language governing permissions and
# ZigBrains is distributed in the hope that it will be useful, # limitations under the License.
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with ZigBrains. If not, see <https://www.gnu.org/licenses/>.
# #
set -e set -e
declare -a branches=("master" "243" "242" "241") declare -a branches=("master" "242" "241")
DEFAULT_BRANCH="${branches[0]}" DEFAULT_BRANCH="${branches[0]}"

View file

@ -14,8 +14,6 @@ sourceSets["main"].resources.srcDir(genOutputDir)
tasks { tasks {
register<Download>("downloadProps") { register<Download>("downloadProps") {
onlyIfModified(true)
useETag(true)
src("https://falsepattern.com/zigbrains/msvc.properties") src("https://falsepattern.com/zigbrains/msvc.properties")
dest(genOutputDir.map { it.file("msvc.properties") }) dest(genOutputDir.map { it.file("msvc.properties") })
} }
@ -29,9 +27,7 @@ dependencies {
create(IntelliJPlatformType.CLion, clionVersion, useInstaller = useInstaller) create(IntelliJPlatformType.CLion, clionVersion, useInstaller = useInstaller)
bundledPlugins("com.intellij.clion", "com.intellij.cidr.base", "com.intellij.nativeDebug") bundledPlugins("com.intellij.clion", "com.intellij.cidr.base", "com.intellij.nativeDebug")
} }
implementation(project(":core")) { implementation(project(":core"))
isTransitive = false
}
implementation("org.eclipse.lsp4j:org.eclipse.lsp4j.debug:$lsp4jVersion") { implementation("org.eclipse.lsp4j:org.eclipse.lsp4j.debug:$lsp4jVersion") {
exclude("org.eclipse.lsp4j", "org.eclipse.lsp4j") exclude("org.eclipse.lsp4j", "org.eclipse.lsp4j")
exclude("org.eclipse.lsp4j", "org.eclipse.lsp4j.jsonrpc") exclude("org.eclipse.lsp4j", "org.eclipse.lsp4j.jsonrpc")

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -24,6 +24,7 @@ package com.falsepattern.zigbrains.clion
import com.falsepattern.zigbrains.debugger.ZigDebuggerDriverConfigurationProvider import com.falsepattern.zigbrains.debugger.ZigDebuggerDriverConfigurationProvider
import com.falsepattern.zigbrains.debugger.settings.ZigDebuggerSettings import com.falsepattern.zigbrains.debugger.settings.ZigDebuggerSettings
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project import com.intellij.openapi.project.Project
import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.SystemInfo
@ -57,9 +58,8 @@ class ZigClionDebuggerDriverConfigurationProvider: ZigDebuggerDriverConfiguratio
} }
return when(toolchain.debuggerKind) { return when(toolchain.debuggerKind) {
CPPDebugger.Kind.BUNDLED_GDB, CPPDebugger.Kind.BUNDLED_GDB,
CPPDebugger.Kind.CUSTOM_GDB -> CLionGDBDriverConfiguration(project, toolchain, isEmulateTerminal = emulateTerminal) CPPDebugger.Kind.CUSTOM_GDB -> CLionGDBDriverConfiguration(project, toolchain)
CPPDebugger.Kind.BUNDLED_LLDB, CPPDebugger.Kind.BUNDLED_LLDB -> CLionLLDBDriverConfiguration(project, toolchain)
CPPDebugger.Kind.CUSTOM_LLDB -> CLionLLDBDriverConfiguration(project, toolchain, isEmulateTerminal = emulateTerminal)
} }
} }
} }

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -27,7 +27,6 @@ import com.falsepattern.zigbrains.debugger.toolchain.*
import com.falsepattern.zigbrains.debugger.win.MSVCDriverConfiguration import com.falsepattern.zigbrains.debugger.win.MSVCDriverConfiguration
import com.falsepattern.zigbrains.shared.coroutine.withEDTContext import com.falsepattern.zigbrains.shared.coroutine.withEDTContext
import com.falsepattern.zigbrains.zig.ZigLanguage import com.falsepattern.zigbrains.zig.ZigLanguage
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.project.Project import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DoNotAskOption import com.intellij.openapi.ui.DoNotAskOption
import com.intellij.openapi.ui.MessageDialogBuilder import com.intellij.openapi.ui.MessageDialogBuilder
@ -86,7 +85,7 @@ private suspend fun availabilityCheck(project: Project, kind: DebuggerKind): Boo
} }
if (downloadDebugger) { if (downloadDebugger) {
val result = withEDTContext(ModalityState.any()) { val result = withEDTContext {
service.downloadDebugger(project, kind) service.downloadDebugger(project, kind)
} }
if (result is ZigDebuggerToolchainService.DownloadResult.Ok) { if (result is ZigDebuggerToolchainService.DownloadResult.Ok) {
@ -105,7 +104,7 @@ private suspend fun showDialog(project: Project, message: String, action: String
} }
} }
return withEDTContext(ModalityState.any()) { return withEDTContext {
MessageDialogBuilder MessageDialogBuilder
.okCancel(ZigDebugBundle.message("debugger.run.unavailable"), message) .okCancel(ZigDebugBundle.message("debugger.run.unavailable"), message)
.yesText(action) .yesText(action)

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -22,10 +22,9 @@
package com.falsepattern.zigbrains.debugger package com.falsepattern.zigbrains.debugger
import com.intellij.execution.filters.Filter
import com.intellij.execution.filters.TextConsoleBuilder import com.intellij.execution.filters.TextConsoleBuilder
import com.intellij.xdebugger.XDebugSession import com.intellij.xdebugger.XDebugSession
import com.jetbrains.cidr.execution.RunParameters import com.jetbrains.cidr.execution.RunParameters
import com.jetbrains.cidr.execution.debugger.CidrLocalDebugProcess import com.jetbrains.cidr.execution.debugger.CidrLocalDebugProcess
class ZigLocalDebugProcess(parameters: RunParameters, session: XDebugSession, consoleBuilder: TextConsoleBuilder) : CidrLocalDebugProcess(parameters, session, consoleBuilder, { Filter.EMPTY_ARRAY }, true) class ZigLocalDebugProcess(parameters: RunParameters, session: XDebugSession, consoleBuilder: TextConsoleBuilder) : CidrLocalDebugProcess(parameters, session, consoleBuilder)

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -26,7 +26,11 @@ import com.falsepattern.zigbrains.project.run.ZigProcessHandler
import com.falsepattern.zigbrains.shared.zigCoroutineScope import com.falsepattern.zigbrains.shared.zigCoroutineScope
import com.intellij.execution.ExecutionException import com.intellij.execution.ExecutionException
import com.intellij.execution.configurations.PtyCommandLine import com.intellij.execution.configurations.PtyCommandLine
import com.intellij.execution.process.* import com.intellij.execution.process.BaseProcessHandler
import com.intellij.execution.process.ProcessAdapter
import com.intellij.execution.process.ProcessEvent
import com.intellij.execution.process.ProcessListener
import com.intellij.execution.process.ProcessOutputType
import com.intellij.openapi.util.Key import com.intellij.openapi.util.Key
import com.intellij.openapi.util.KeyWithDefaultValue import com.intellij.openapi.util.KeyWithDefaultValue
import com.intellij.openapi.util.io.toNioPathOrNull import com.intellij.openapi.util.io.toNioPathOrNull
@ -41,12 +45,9 @@ import com.jetbrains.cidr.execution.debugger.memory.AddressRange
import com.jetbrains.cidr.system.HostMachine import com.jetbrains.cidr.system.HostMachine
import com.jetbrains.cidr.system.LocalHost import com.jetbrains.cidr.system.LocalHost
import io.ktor.util.* import io.ktor.util.*
import kotlinx.coroutines.Job import kotlinx.coroutines.*
import kotlinx.coroutines.async
import kotlinx.coroutines.future.asCompletableFuture import kotlinx.coroutines.future.asCompletableFuture
import kotlinx.coroutines.future.asDeferred import kotlinx.coroutines.future.asDeferred
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.eclipse.lsp4j.debug.* import org.eclipse.lsp4j.debug.*
import org.eclipse.lsp4j.debug.services.IDebugProtocolClient import org.eclipse.lsp4j.debug.services.IDebugProtocolClient
import org.eclipse.lsp4j.debug.services.IDebugProtocolServer import org.eclipse.lsp4j.debug.services.IDebugProtocolServer
@ -57,7 +58,8 @@ import java.io.ByteArrayOutputStream
import java.io.File import java.io.File
import java.io.OutputStream import java.io.OutputStream
import java.io.PipedOutputStream import java.io.PipedOutputStream
import java.util.* import java.lang.Exception
import java.util.TreeMap
import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executors import java.util.concurrent.Executors
import kotlin.math.min import kotlin.math.min
@ -211,7 +213,7 @@ abstract class DAPDriver<Server : IDebugProtocolServer, Client : IDebugProtocolC
val cli = installer.install() val cli = installer.install()
val args = HashMap<String, Any>() val args = HashMap<String, Any>()
args["program"] = Util.toWinPath(cli.exePath) args["program"] = Util.toWinPath(cli.exePath)
args["cmd"] = cli.workingDirectory.toString() args["cmd"] = cli.workDirectory.toString()
args["name"] = "CPP Debug" args["name"] = "CPP Debug"
args["type"] = "cppvsdbg" args["type"] = "cppvsdbg"
args["request"] = "launch" args["request"] = "launch"
@ -951,7 +953,7 @@ abstract class DAPDriver<Server : IDebugProtocolServer, Client : IDebugProtocolC
fun runInTerminalAsync(args: RunInTerminalRequestArguments): RunInTerminalResponse { fun runInTerminalAsync(args: RunInTerminalRequestArguments): RunInTerminalResponse {
val cli = PtyCommandLine(args.args.toList()) val cli = PtyCommandLine(args.args.toList())
cli.withCharset(Charsets.UTF_8) cli.charset = Charsets.UTF_8
val cwd = args.cwd?.ifBlank { null }?.toNioPathOrNull() val cwd = args.cwd?.ifBlank { null }?.toNioPathOrNull()
if (cwd != null) { if (cwd != null) {
cli.withWorkingDirectory(cwd) cli.withWorkingDirectory(cwd)

View file

@ -1,23 +1,17 @@
/* /*
* This file is part of ZigBrains. * Copyright 2023-2024 FalsePattern
* *
* Copyright (C) 2023-2025 FalsePattern * Licensed under the Apache License, Version 2.0 (the "License");
* All Rights Reserved * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* The above copyright notice and this permission notice shall be included * http://www.apache.org/licenses/LICENSE-2.0
* in all copies or substantial portions of the Software.
* *
* ZigBrains is free software: you can redistribute it and/or modify * Unless required by applicable law or agreed to in writing, software
* it under the terms of the GNU Lesser General Public License as published by * distributed under the License is distributed on an "AS IS" BASIS,
* the Free Software Foundation, only version 3 of the License. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* ZigBrains is distributed in the hope that it will be useful, * limitations under the License.
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ZigBrains. If not, see <https://www.gnu.org/licenses/>.
*/ */
package com.falsepattern.zigbrains.debugger.dap package com.falsepattern.zigbrains.debugger.dap

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -39,7 +39,7 @@ class ZigExecConfigBinary(project: Project, factory: ConfigurationFactory) : Zig
get() = ZigDebugBundle.message("configuration.binary.suggested-name") get() = ZigDebugBundle.message("configuration.binary.suggested-name")
override suspend fun buildCommandLineArgs(debug: Boolean): List<String> { override suspend fun buildCommandLineArgs(debug: Boolean): List<String> {
return args.argsSplit() return args.args
} }
override fun getConfigurables(): List<ZigConfigurable<*>> { override fun getConfigurables(): List<ZigConfigurable<*>> {

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -24,14 +24,14 @@ package com.falsepattern.zigbrains.debugger.execution.binary
import com.falsepattern.zigbrains.debugger.ZigDebugBundle import com.falsepattern.zigbrains.debugger.ZigDebugBundle
import com.falsepattern.zigbrains.project.execution.base.ZigProfileState import com.falsepattern.zigbrains.project.execution.base.ZigProfileState
import com.falsepattern.zigbrains.project.toolchain.base.ZigToolchain import com.falsepattern.zigbrains.project.toolchain.AbstractZigToolchain
import com.intellij.execution.ExecutionException import com.intellij.execution.ExecutionException
import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.runners.ExecutionEnvironment
import kotlin.io.path.pathString import kotlin.io.path.pathString
class ZigProfileStateBinary(environment: ExecutionEnvironment, configuration: ZigExecConfigBinary) : ZigProfileState<ZigExecConfigBinary>(environment, configuration) { class ZigProfileStateBinary(environment: ExecutionEnvironment, configuration: ZigExecConfigBinary) : ZigProfileState<ZigExecConfigBinary>(environment, configuration) {
override suspend fun getCommandLine(toolchain: ZigToolchain, debug: Boolean): GeneralCommandLine { override suspend fun getCommandLine(toolchain: AbstractZigToolchain, debug: Boolean): GeneralCommandLine {
val cli = GeneralCommandLine() val cli = GeneralCommandLine()
val cfg = configuration val cfg = configuration
cfg.workingDirectory.path?.let { cli.withWorkingDirectory(it) } cfg.workingDirectory.path?.let { cli.withWorkingDirectory(it) }

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -23,7 +23,6 @@
package com.falsepattern.zigbrains.debugger.runner.base package com.falsepattern.zigbrains.debugger.runner.base
import com.falsepattern.zigbrains.project.run.ZigProcessHandler import com.falsepattern.zigbrains.project.run.ZigProcessHandler
import com.falsepattern.zigbrains.shared.cli.startIPCAwareProcess
import com.intellij.execution.ExecutionException import com.intellij.execution.ExecutionException
import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.ProcessEvent import com.intellij.execution.process.ProcessEvent
@ -31,7 +30,6 @@ import com.intellij.execution.process.ProcessHandler
import com.intellij.execution.process.ProcessListener import com.intellij.execution.process.ProcessListener
import com.intellij.execution.ui.ConsoleView import com.intellij.execution.ui.ConsoleView
import com.intellij.execution.ui.ConsoleViewContentType import com.intellij.execution.ui.ConsoleViewContentType
import com.intellij.openapi.project.Project
import com.intellij.platform.util.progress.withProgressText import com.intellij.platform.util.progress.withProgressText
import com.intellij.util.io.awaitExit import com.intellij.util.io.awaitExit
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
@ -41,17 +39,17 @@ import kotlinx.coroutines.withContext
class PreLaunchProcessListener(val console: ConsoleView) : ProcessListener { class PreLaunchProcessListener(val console: ConsoleView) : ProcessListener {
var isBuildFailed: Boolean = false var isBuildFailed: Boolean = false
private set private set
lateinit var processHandler: ZigProcessHandler.IPCAware lateinit var processHandler: ProcessHandler
private set private set
@Throws(ExecutionException::class) @Throws(ExecutionException::class)
suspend fun executeCommandLineWithHook(project: Project, commandLine: GeneralCommandLine): Boolean { suspend fun executeCommandLineWithHook(commandLine: GeneralCommandLine): Boolean {
return withProgressText(commandLine.commandLineString) { return withProgressText(commandLine.commandLineString) {
val processHandler = commandLine.startIPCAwareProcess(project) val processHandler = ZigProcessHandler(commandLine)
this@PreLaunchProcessListener.processHandler = processHandler this@PreLaunchProcessListener.processHandler = processHandler
hook(processHandler) hook(processHandler)
processHandler.startNotify() processHandler.startNotify()
withContext(Dispatchers.IO) { withContext(Dispatchers.Default) {
processHandler.process.awaitExit() processHandler.process.awaitExit()
} }
runInterruptible { runInterruptible {
@ -68,6 +66,10 @@ class PreLaunchProcessListener(val console: ConsoleView) : ProcessListener {
override fun processTerminated(event: ProcessEvent) { override fun processTerminated(event: ProcessEvent) {
if (event.exitCode != 0) { if (event.exitCode != 0) {
console.print(
"Process finished with exit code " + event.exitCode,
ConsoleViewContentType.NORMAL_OUTPUT
)
isBuildFailed = true isBuildFailed = true
} else { } else {
isBuildFailed = false isBuildFailed = false

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -23,10 +23,9 @@
package com.falsepattern.zigbrains.debugger.runner.base package com.falsepattern.zigbrains.debugger.runner.base
import com.falsepattern.zigbrains.project.execution.base.ZigProfileState import com.falsepattern.zigbrains.project.execution.base.ZigProfileState
import com.falsepattern.zigbrains.project.toolchain.base.ZigToolchain import com.falsepattern.zigbrains.project.toolchain.AbstractZigToolchain
import com.falsepattern.zigbrains.shared.zigCoroutineScope import com.falsepattern.zigbrains.shared.zigCoroutineScope
import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.configurations.PtyCommandLine
import com.jetbrains.cidr.execution.Installer import com.jetbrains.cidr.execution.Installer
import kotlinx.coroutines.async import kotlinx.coroutines.async
import kotlinx.coroutines.future.asCompletableFuture import kotlinx.coroutines.future.asCompletableFuture
@ -34,13 +33,13 @@ import java.io.File
class ZigDebugEmitBinaryInstaller<ProfileState: ZigProfileState<*>>( class ZigDebugEmitBinaryInstaller<ProfileState: ZigProfileState<*>>(
private val profileState: ProfileState, private val profileState: ProfileState,
private val toolchain: ZigToolchain, private val toolchain: AbstractZigToolchain,
private val executableFile: File, private val executableFile: File,
private val exeArgs: List<String> private val exeArgs: List<String>
): Installer { ): Installer {
override fun install(): GeneralCommandLine { override fun install(): GeneralCommandLine {
val cfg = profileState.configuration val cfg = profileState.configuration
val cli = PtyCommandLine().withConsoleMode(false).withExePath(executableFile.absolutePath) val cli = GeneralCommandLine().withExePath(executableFile.absolutePath)
cfg.workingDirectory.path?.let { x -> cli.withWorkingDirectory(x) } cfg.workingDirectory.path?.let { x -> cli.withWorkingDirectory(x) }
cli.addParameters(exeArgs) cli.addParameters(exeArgs)
cli.withCharset(Charsets.UTF_8) cli.withCharset(Charsets.UTF_8)

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -23,7 +23,7 @@
package com.falsepattern.zigbrains.debugger.runner.base package com.falsepattern.zigbrains.debugger.runner.base
import com.falsepattern.zigbrains.project.execution.base.ZigProfileState import com.falsepattern.zigbrains.project.execution.base.ZigProfileState
import com.falsepattern.zigbrains.project.toolchain.base.ZigToolchain import com.falsepattern.zigbrains.project.toolchain.AbstractZigToolchain
import com.intellij.util.system.CpuArch import com.intellij.util.system.CpuArch
import com.jetbrains.cidr.ArchitectureType import com.jetbrains.cidr.ArchitectureType
import com.jetbrains.cidr.execution.RunParameters import com.jetbrains.cidr.execution.RunParameters
@ -31,7 +31,7 @@ import com.jetbrains.cidr.execution.debugger.backend.DebuggerDriverConfiguration
abstract class ZigDebugParametersBase<ProfileState: ZigProfileState<*>>( abstract class ZigDebugParametersBase<ProfileState: ZigProfileState<*>>(
private val driverConfiguration: DebuggerDriverConfiguration, private val driverConfiguration: DebuggerDriverConfiguration,
protected val toolchain: ZigToolchain, protected val toolchain: AbstractZigToolchain,
protected val profileState: ProfileState protected val profileState: ProfileState
): RunParameters() { ): RunParameters() {
override fun getDebuggerDriverConfiguration(): DebuggerDriverConfiguration { override fun getDebuggerDriverConfiguration(): DebuggerDriverConfiguration {

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -24,10 +24,9 @@ package com.falsepattern.zigbrains.debugger.runner.base
import com.falsepattern.zigbrains.debugger.ZigDebugBundle import com.falsepattern.zigbrains.debugger.ZigDebugBundle
import com.falsepattern.zigbrains.project.execution.base.ZigProfileState import com.falsepattern.zigbrains.project.execution.base.ZigProfileState
import com.falsepattern.zigbrains.project.toolchain.base.ZigToolchain import com.falsepattern.zigbrains.project.toolchain.AbstractZigToolchain
import com.intellij.execution.ExecutionException import com.intellij.execution.ExecutionException
import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.toNioPathOrNull
import com.intellij.platform.util.progress.withProgressText import com.intellij.platform.util.progress.withProgressText
import com.intellij.util.containers.orNull import com.intellij.util.containers.orNull
import com.jetbrains.cidr.execution.debugger.backend.DebuggerDriverConfiguration import com.jetbrains.cidr.execution.debugger.backend.DebuggerDriverConfiguration
@ -37,11 +36,10 @@ import java.io.File
import java.nio.file.Files import java.nio.file.Files
import kotlin.io.path.absolutePathString import kotlin.io.path.absolutePathString
import kotlin.io.path.isExecutable import kotlin.io.path.isExecutable
import kotlin.io.path.pathString
abstract class ZigDebugParametersEmitBinaryBase<ProfileState: ZigProfileState<*>>( abstract class ZigDebugParametersEmitBinaryBase<ProfileState: ZigProfileState<*>>(
driverConfiguration: DebuggerDriverConfiguration, driverConfiguration: DebuggerDriverConfiguration,
toolchain: ZigToolchain, toolchain: AbstractZigToolchain,
profileState: ProfileState, profileState: ProfileState,
) : ZigDebugParametersBase<ProfileState>(driverConfiguration, toolchain, profileState), PreLaunchAware { ) : ZigDebugParametersBase<ProfileState>(driverConfiguration, toolchain, profileState), PreLaunchAware {
@Volatile @Volatile
@ -51,14 +49,13 @@ abstract class ZigDebugParametersEmitBinaryBase<ProfileState: ZigProfileState<*>
@Throws(ExecutionException::class) @Throws(ExecutionException::class)
private suspend fun compileExe(listener: PreLaunchProcessListener): File { private suspend fun compileExe(listener: PreLaunchProcessListener): File {
val commandLine = profileState.getCommandLine(toolchain, true) val commandLine = profileState.getCommandLine(toolchain, true)
val cliString = commandLine.getCommandLineString(commandLine.exePath.toNioPathOrNull()?.fileName?.pathString)
val tmpDir = FileUtil.createTempDirectory("zigbrains_debug", "", true).toPath() val tmpDir = FileUtil.createTempDirectory("zigbrains_debug", "", true).toPath()
val exe = tmpDir.resolve("executable") val exe = tmpDir.resolve("executable")
commandLine.addParameters("-femit-bin=${exe.absolutePathString()}") commandLine.addParameters("-femit-bin=${exe.absolutePathString()}")
if (listener.executeCommandLineWithHook(profileState.environment.project, commandLine)) if (listener.executeCommandLineWithHook(commandLine))
throw ExecutionException(ZigDebugBundle.message("debug.base.compile.failed.generic", cliString)) throw ExecutionException(ZigDebugBundle.message("debug.base.compile.failed.generic"))
return withContext(Dispatchers.IO) { return withContext(Dispatchers.IO) {
Files.list(tmpDir).use { stream -> Files.list(tmpDir).use { stream ->

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -24,10 +24,9 @@ package com.falsepattern.zigbrains.debugger.runner.base
import com.falsepattern.zigbrains.debugbridge.ZigDebuggerDriverConfigurationProviderBase import com.falsepattern.zigbrains.debugbridge.ZigDebuggerDriverConfigurationProviderBase
import com.falsepattern.zigbrains.debugger.ZigLocalDebugProcess import com.falsepattern.zigbrains.debugger.ZigLocalDebugProcess
import com.falsepattern.zigbrains.debugger.runner.build.ZigDebugRunnerBuild
import com.falsepattern.zigbrains.project.execution.base.ZigProfileState import com.falsepattern.zigbrains.project.execution.base.ZigProfileState
import com.falsepattern.zigbrains.project.run.ZigProgramRunner import com.falsepattern.zigbrains.project.run.ZigProgramRunner
import com.falsepattern.zigbrains.project.toolchain.base.ZigToolchain import com.falsepattern.zigbrains.project.toolchain.AbstractZigToolchain
import com.falsepattern.zigbrains.shared.coroutine.runInterruptibleEDT import com.falsepattern.zigbrains.shared.coroutine.runInterruptibleEDT
import com.falsepattern.zigbrains.shared.coroutine.withEDTContext import com.falsepattern.zigbrains.shared.coroutine.withEDTContext
import com.intellij.execution.DefaultExecutionResult import com.intellij.execution.DefaultExecutionResult
@ -41,8 +40,6 @@ import com.intellij.execution.runners.RunContentBuilder
import com.intellij.execution.ui.ConsoleView import com.intellij.execution.ui.ConsoleView
import com.intellij.execution.ui.ConsoleViewContentType import com.intellij.execution.ui.ConsoleViewContentType
import com.intellij.execution.ui.RunContentDescriptor import com.intellij.execution.ui.RunContentDescriptor
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.project.guessProjectDir
import com.intellij.platform.util.progress.reportProgress import com.intellij.platform.util.progress.reportProgress
import com.intellij.xdebugger.XDebugProcess import com.intellij.xdebugger.XDebugProcess
import com.intellij.xdebugger.XDebugProcessStarter import com.intellij.xdebugger.XDebugProcessStarter
@ -54,13 +51,13 @@ abstract class ZigDebugRunnerBase<ProfileState : ZigProfileState<*>> : ZigProgra
@Throws(ExecutionException::class) @Throws(ExecutionException::class)
override suspend fun execute( override suspend fun execute(
state: ProfileState, state: ProfileState,
toolchain: ZigToolchain, toolchain: AbstractZigToolchain,
environment: ExecutionEnvironment environment: ExecutionEnvironment
): RunContentDescriptor? { ): RunContentDescriptor? {
val project = environment.project val project = environment.project
val driverProviders = ZigDebuggerDriverConfigurationProviderBase.EXTENSION_POINT_NAME.extensionList val driverProviders = ZigDebuggerDriverConfigurationProviderBase.EXTENSION_POINT_NAME.extensionList
for (provider in driverProviders) { for (provider in driverProviders) {
val driver = provider.getDebuggerConfiguration(project, isElevated = false, emulateTerminal = true, DebuggerDriverConfiguration::class.java) ?: continue val driver = provider.getDebuggerConfiguration(project, isElevated = false, emulateTerminal = false, DebuggerDriverConfiguration::class.java) ?: continue
return executeWithDriver(state, toolchain, environment, driver) ?: continue return executeWithDriver(state, toolchain, environment, driver) ?: continue
} }
return null return null
@ -69,7 +66,7 @@ abstract class ZigDebugRunnerBase<ProfileState : ZigProfileState<*>> : ZigProgra
@Throws(ExecutionException::class) @Throws(ExecutionException::class)
private suspend fun executeWithDriver( private suspend fun executeWithDriver(
state: ProfileState, state: ProfileState,
toolchain: ZigToolchain, toolchain: AbstractZigToolchain,
environment: ExecutionEnvironment, environment: ExecutionEnvironment,
debuggerDriver: DebuggerDriverConfiguration debuggerDriver: DebuggerDriverConfiguration
): RunContentDescriptor? { ): RunContentDescriptor? {
@ -84,25 +81,22 @@ abstract class ZigDebugRunnerBase<ProfileState : ZigProfileState<*>> : ZigProgra
} }
} catch (e: ExecutionException) { } catch (e: ExecutionException) {
console.print("\n", ConsoleViewContentType.ERROR_OUTPUT) console.print("\n", ConsoleViewContentType.ERROR_OUTPUT)
e.message?.let { listener.console.print(it, ConsoleViewContentType.ERROR_OUTPUT) } e.message?.let { listener.console.print(it, ConsoleViewContentType.SYSTEM_OUTPUT) }
if (this !is ZigDebugRunnerBuild && environment.project.guessProjectDir()?.children?.any { it.name == "build.zig" } == true) {
console.print("\n Warning: build.zig file detected in project.\n Did you want to use a Zig Build task instead?", ConsoleViewContentType.ERROR_OUTPUT)
}
} }
if (listener.isBuildFailed) { if (listener.isBuildFailed) {
val executionResult = DefaultExecutionResult(console, listener.processHandler.unwrap()) val executionResult = DefaultExecutionResult(console, listener.processHandler)
return@reportProgress withEDTContext(ModalityState.any()) { return@reportProgress withEDTContext {
val runContentBuilder = RunContentBuilder(executionResult, environment) val runContentBuilder = RunContentBuilder(executionResult, environment)
runContentBuilder.showRunContent(null) runContentBuilder.showRunContent(null)
} }
} }
} }
return@reportProgress runInterruptibleEDT(ModalityState.any()) { return@reportProgress runInterruptibleEDT {
val debuggerManager = XDebuggerManager.getInstance(environment.project) val debuggerManager = XDebuggerManager.getInstance(environment.project)
debuggerManager.startSession(environment, object: XDebugProcessStarter() { debuggerManager.startSession(environment, object: XDebugProcessStarter() {
override fun start(session: XDebugSession): XDebugProcess { override fun start(session: XDebugSession): XDebugProcess {
val project = session.project val project = session.project
val textConsoleBuilder = state.consoleBuilder val textConsoleBuilder = SharedConsoleBuilder(console)
val debugProcess = ZigLocalDebugProcess(runParameters, session, textConsoleBuilder) val debugProcess = ZigLocalDebugProcess(runParameters, session, textConsoleBuilder)
ProcessTerminatedListener.attach(debugProcess.processHandler, project) ProcessTerminatedListener.attach(debugProcess.processHandler, project)
debugProcess.start() debugProcess.start()
@ -117,7 +111,7 @@ abstract class ZigDebugRunnerBase<ProfileState : ZigProfileState<*>> : ZigProgra
protected abstract fun getDebugParameters( protected abstract fun getDebugParameters(
state: ProfileState, state: ProfileState,
debuggerDriver: DebuggerDriverConfiguration, debuggerDriver: DebuggerDriverConfiguration,
toolchain: ZigToolchain toolchain: AbstractZigToolchain
): ZigDebugParametersBase<ProfileState> ): ZigDebugParametersBase<ProfileState>
private class SharedConsoleBuilder(private val console: ConsoleView) : TextConsoleBuilder() { private class SharedConsoleBuilder(private val console: ConsoleView) : TextConsoleBuilder() {

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -26,16 +26,16 @@ import com.falsepattern.zigbrains.debugger.ZigDebugBundle
import com.falsepattern.zigbrains.debugger.execution.binary.ZigProfileStateBinary import com.falsepattern.zigbrains.debugger.execution.binary.ZigProfileStateBinary
import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugEmitBinaryInstaller import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugEmitBinaryInstaller
import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugParametersBase import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugParametersBase
import com.falsepattern.zigbrains.project.toolchain.base.ZigToolchain import com.falsepattern.zigbrains.project.toolchain.AbstractZigToolchain
import com.intellij.execution.ExecutionException import com.intellij.execution.ExecutionException
import com.jetbrains.cidr.execution.Installer import com.jetbrains.cidr.execution.Installer
import com.jetbrains.cidr.execution.debugger.backend.DebuggerDriverConfiguration import com.jetbrains.cidr.execution.debugger.backend.DebuggerDriverConfiguration
class ZigDebugParametersBinary @Throws(ExecutionException::class) constructor(driverConfiguration: DebuggerDriverConfiguration, toolchain: ZigToolchain, profileState: ZigProfileStateBinary) : class ZigDebugParametersBinary @Throws(ExecutionException::class) constructor(driverConfiguration: DebuggerDriverConfiguration, toolchain: AbstractZigToolchain, profileState: ZigProfileStateBinary) :
ZigDebugParametersBase<ZigProfileStateBinary>(driverConfiguration, toolchain, profileState) { ZigDebugParametersBase<ZigProfileStateBinary>(driverConfiguration, toolchain, profileState) {
private val executableFile = profileState.configuration.exePath.path?.toFile() ?: throw ExecutionException(ZigDebugBundle.message("exception.missing-exe-path")) private val executableFile = profileState.configuration.exePath.path?.toFile() ?: throw ExecutionException(ZigDebugBundle.message("exception.missing-exe-path"))
override fun getInstaller(): Installer { override fun getInstaller(): Installer {
return ZigDebugEmitBinaryInstaller(profileState, toolchain, executableFile, profileState.configuration.args.argsSplit()) return ZigDebugEmitBinaryInstaller(profileState, toolchain, executableFile, profileState.configuration.args.args)
} }
} }

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -27,8 +27,8 @@ import com.falsepattern.zigbrains.debugger.execution.binary.ZigProfileStateBinar
import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugParametersBase import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugParametersBase
import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugRunnerBase import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugRunnerBase
import com.falsepattern.zigbrains.project.execution.base.ZigProfileState import com.falsepattern.zigbrains.project.execution.base.ZigProfileState
import com.falsepattern.zigbrains.project.toolchain.base.ZigToolchain import com.falsepattern.zigbrains.project.toolchain.AbstractZigToolchain
import com.falsepattern.zigbrains.project.toolchain.local.LocalZigToolchain import com.falsepattern.zigbrains.project.toolchain.LocalZigToolchain
import com.intellij.execution.configurations.RunProfile import com.intellij.execution.configurations.RunProfile
import com.jetbrains.cidr.execution.debugger.backend.DebuggerDriverConfiguration import com.jetbrains.cidr.execution.debugger.backend.DebuggerDriverConfiguration
@ -36,7 +36,7 @@ class ZigDebugRunnerBinary: ZigDebugRunnerBase<ZigProfileStateBinary>() {
override fun getDebugParameters( override fun getDebugParameters(
state: ZigProfileStateBinary, state: ZigProfileStateBinary,
debuggerDriver: DebuggerDriverConfiguration, debuggerDriver: DebuggerDriverConfiguration,
toolchain: ZigToolchain toolchain: AbstractZigToolchain
): ZigDebugParametersBase<ZigProfileStateBinary> { ): ZigDebugParametersBase<ZigProfileStateBinary> {
return ZigDebugParametersBinary(debuggerDriver, LocalZigToolchain.ensureLocal(toolchain), state) return ZigDebugParametersBinary(debuggerDriver, LocalZigToolchain.ensureLocal(toolchain), state)
} }

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -28,7 +28,7 @@ import com.falsepattern.zigbrains.debugger.runner.base.PreLaunchProcessListener
import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugEmitBinaryInstaller import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugEmitBinaryInstaller
import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugParametersBase import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugParametersBase
import com.falsepattern.zigbrains.project.execution.build.ZigProfileStateBuild import com.falsepattern.zigbrains.project.execution.build.ZigProfileStateBuild
import com.falsepattern.zigbrains.project.toolchain.base.ZigToolchain import com.falsepattern.zigbrains.project.toolchain.AbstractZigToolchain
import com.intellij.execution.ExecutionException import com.intellij.execution.ExecutionException
import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.SystemInfo
import com.intellij.platform.util.progress.withProgressText import com.intellij.platform.util.progress.withProgressText
@ -46,14 +46,14 @@ import kotlin.io.path.isRegularFile
class ZigDebugParametersBuild( class ZigDebugParametersBuild(
driverConfiguration: DebuggerDriverConfiguration, driverConfiguration: DebuggerDriverConfiguration,
toolchain: ZigToolchain, toolchain: AbstractZigToolchain,
profileState: ZigProfileStateBuild profileState: ZigProfileStateBuild
) : ZigDebugParametersBase<ZigProfileStateBuild>(driverConfiguration, toolchain, profileState), PreLaunchAware { ) : ZigDebugParametersBase<ZigProfileStateBuild>(driverConfiguration, toolchain, profileState), PreLaunchAware {
@Volatile @Volatile
private lateinit var executableFile: File private lateinit var executableFile: File
override fun getInstaller(): Installer { override fun getInstaller(): Installer {
return ZigDebugEmitBinaryInstaller(profileState, toolchain, executableFile, profileState.configuration.exeArgs.argsSplit()) return ZigDebugEmitBinaryInstaller(profileState, toolchain, executableFile, profileState.configuration.exeArgs.args)
} }
@Throws(ExecutionException::class) @Throws(ExecutionException::class)
@ -61,8 +61,8 @@ class ZigDebugParametersBuild(
withProgressText("Building zig project") { withProgressText("Building zig project") {
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
val commandLine = profileState.getCommandLine(toolchain, true) val commandLine = profileState.getCommandLine(toolchain, true)
if (listener.executeCommandLineWithHook(profileState.environment.project, commandLine)) if (listener.executeCommandLineWithHook(commandLine))
return@withContext throw ExecutionException(ZigDebugBundle.message("debug.build.compile.failed.generic"))
val cfg = profileState.configuration val cfg = profileState.configuration
val workingDir = cfg.workingDirectory.path val workingDir = cfg.workingDirectory.path
val exe = profileState.configuration.exePath.path ?: run { val exe = profileState.configuration.exePath.path ?: run {

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -27,8 +27,8 @@ import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugRunnerBase
import com.falsepattern.zigbrains.project.execution.base.ZigProfileState import com.falsepattern.zigbrains.project.execution.base.ZigProfileState
import com.falsepattern.zigbrains.project.execution.build.ZigExecConfigBuild import com.falsepattern.zigbrains.project.execution.build.ZigExecConfigBuild
import com.falsepattern.zigbrains.project.execution.build.ZigProfileStateBuild import com.falsepattern.zigbrains.project.execution.build.ZigProfileStateBuild
import com.falsepattern.zigbrains.project.toolchain.base.ZigToolchain import com.falsepattern.zigbrains.project.toolchain.AbstractZigToolchain
import com.falsepattern.zigbrains.project.toolchain.local.LocalZigToolchain import com.falsepattern.zigbrains.project.toolchain.LocalZigToolchain
import com.intellij.execution.configurations.RunProfile import com.intellij.execution.configurations.RunProfile
import com.jetbrains.cidr.execution.debugger.backend.DebuggerDriverConfiguration import com.jetbrains.cidr.execution.debugger.backend.DebuggerDriverConfiguration
@ -36,7 +36,7 @@ class ZigDebugRunnerBuild: ZigDebugRunnerBase<ZigProfileStateBuild>() {
override fun getDebugParameters( override fun getDebugParameters(
state: ZigProfileStateBuild, state: ZigProfileStateBuild,
debuggerDriver: DebuggerDriverConfiguration, debuggerDriver: DebuggerDriverConfiguration,
toolchain: ZigToolchain toolchain: AbstractZigToolchain
): ZigDebugParametersBase<ZigProfileStateBuild> { ): ZigDebugParametersBase<ZigProfileStateBuild> {
return ZigDebugParametersBuild(debuggerDriver, LocalZigToolchain.ensureLocal(toolchain), state) return ZigDebugParametersBuild(debuggerDriver, LocalZigToolchain.ensureLocal(toolchain), state)
} }

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -25,13 +25,13 @@ package com.falsepattern.zigbrains.debugger.runner.run
import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugEmitBinaryInstaller import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugEmitBinaryInstaller
import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugParametersEmitBinaryBase import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugParametersEmitBinaryBase
import com.falsepattern.zigbrains.project.execution.run.ZigProfileStateRun import com.falsepattern.zigbrains.project.execution.run.ZigProfileStateRun
import com.falsepattern.zigbrains.project.toolchain.base.ZigToolchain import com.falsepattern.zigbrains.project.toolchain.AbstractZigToolchain
import com.jetbrains.cidr.execution.Installer import com.jetbrains.cidr.execution.Installer
import com.jetbrains.cidr.execution.debugger.backend.DebuggerDriverConfiguration import com.jetbrains.cidr.execution.debugger.backend.DebuggerDriverConfiguration
class ZigDebugParametersRun(driverConfiguration: DebuggerDriverConfiguration, toolchain: ZigToolchain, profileState: ZigProfileStateRun) : class ZigDebugParametersRun(driverConfiguration: DebuggerDriverConfiguration, toolchain: AbstractZigToolchain, profileState: ZigProfileStateRun) :
ZigDebugParametersEmitBinaryBase<ZigProfileStateRun>(driverConfiguration, toolchain, profileState) { ZigDebugParametersEmitBinaryBase<ZigProfileStateRun>(driverConfiguration, toolchain, profileState) {
override fun getInstaller(): Installer { override fun getInstaller(): Installer {
return ZigDebugEmitBinaryInstaller(profileState, toolchain, executableFile, profileState.configuration.exeArgs.argsSplit()) return ZigDebugEmitBinaryInstaller(profileState, toolchain, executableFile, profileState.configuration.exeArgs.args)
} }
} }

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -27,8 +27,8 @@ import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugRunnerBase
import com.falsepattern.zigbrains.project.execution.base.ZigProfileState import com.falsepattern.zigbrains.project.execution.base.ZigProfileState
import com.falsepattern.zigbrains.project.execution.run.ZigExecConfigRun import com.falsepattern.zigbrains.project.execution.run.ZigExecConfigRun
import com.falsepattern.zigbrains.project.execution.run.ZigProfileStateRun import com.falsepattern.zigbrains.project.execution.run.ZigProfileStateRun
import com.falsepattern.zigbrains.project.toolchain.base.ZigToolchain import com.falsepattern.zigbrains.project.toolchain.AbstractZigToolchain
import com.falsepattern.zigbrains.project.toolchain.local.LocalZigToolchain import com.falsepattern.zigbrains.project.toolchain.LocalZigToolchain
import com.intellij.execution.configurations.RunProfile import com.intellij.execution.configurations.RunProfile
import com.jetbrains.cidr.execution.debugger.backend.DebuggerDriverConfiguration import com.jetbrains.cidr.execution.debugger.backend.DebuggerDriverConfiguration
@ -36,7 +36,7 @@ class ZigDebugRunnerRun: ZigDebugRunnerBase<ZigProfileStateRun>() {
override fun getDebugParameters( override fun getDebugParameters(
state: ZigProfileStateRun, state: ZigProfileStateRun,
debuggerDriver: DebuggerDriverConfiguration, debuggerDriver: DebuggerDriverConfiguration,
toolchain: ZigToolchain toolchain: AbstractZigToolchain
): ZigDebugParametersBase<ZigProfileStateRun> { ): ZigDebugParametersBase<ZigProfileStateRun> {
return ZigDebugParametersRun(debuggerDriver, LocalZigToolchain.ensureLocal(toolchain), state) return ZigDebugParametersRun(debuggerDriver, LocalZigToolchain.ensureLocal(toolchain), state)
} }

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -25,11 +25,11 @@ package com.falsepattern.zigbrains.debugger.runner.test
import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugEmitBinaryInstaller import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugEmitBinaryInstaller
import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugParametersEmitBinaryBase import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugParametersEmitBinaryBase
import com.falsepattern.zigbrains.project.execution.test.ZigProfileStateTest import com.falsepattern.zigbrains.project.execution.test.ZigProfileStateTest
import com.falsepattern.zigbrains.project.toolchain.base.ZigToolchain import com.falsepattern.zigbrains.project.toolchain.AbstractZigToolchain
import com.jetbrains.cidr.execution.Installer import com.jetbrains.cidr.execution.Installer
import com.jetbrains.cidr.execution.debugger.backend.DebuggerDriverConfiguration import com.jetbrains.cidr.execution.debugger.backend.DebuggerDriverConfiguration
class ZigDebugParametersTest(driverConfiguration: DebuggerDriverConfiguration, toolchain: ZigToolchain, profileState: ZigProfileStateTest) : class ZigDebugParametersTest(driverConfiguration: DebuggerDriverConfiguration, toolchain: AbstractZigToolchain, profileState: ZigProfileStateTest) :
ZigDebugParametersEmitBinaryBase<ZigProfileStateTest>(driverConfiguration, toolchain, profileState) { ZigDebugParametersEmitBinaryBase<ZigProfileStateTest>(driverConfiguration, toolchain, profileState) {
override fun getInstaller(): Installer { override fun getInstaller(): Installer {
return ZigDebugEmitBinaryInstaller(profileState, toolchain, executableFile, listOf()) return ZigDebugEmitBinaryInstaller(profileState, toolchain, executableFile, listOf())

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -27,8 +27,8 @@ import com.falsepattern.zigbrains.debugger.runner.base.ZigDebugRunnerBase
import com.falsepattern.zigbrains.project.execution.base.ZigProfileState import com.falsepattern.zigbrains.project.execution.base.ZigProfileState
import com.falsepattern.zigbrains.project.execution.test.ZigExecConfigTest import com.falsepattern.zigbrains.project.execution.test.ZigExecConfigTest
import com.falsepattern.zigbrains.project.execution.test.ZigProfileStateTest import com.falsepattern.zigbrains.project.execution.test.ZigProfileStateTest
import com.falsepattern.zigbrains.project.toolchain.base.ZigToolchain import com.falsepattern.zigbrains.project.toolchain.AbstractZigToolchain
import com.falsepattern.zigbrains.project.toolchain.local.LocalZigToolchain import com.falsepattern.zigbrains.project.toolchain.LocalZigToolchain
import com.intellij.execution.configurations.RunProfile import com.intellij.execution.configurations.RunProfile
import com.jetbrains.cidr.execution.debugger.backend.DebuggerDriverConfiguration import com.jetbrains.cidr.execution.debugger.backend.DebuggerDriverConfiguration
@ -36,7 +36,7 @@ class ZigDebugRunnerTest: ZigDebugRunnerBase<ZigProfileStateTest>() {
override fun getDebugParameters( override fun getDebugParameters(
state: ZigProfileStateTest, state: ZigProfileStateTest,
debuggerDriver: DebuggerDriverConfiguration, debuggerDriver: DebuggerDriverConfiguration,
toolchain: ZigToolchain toolchain: AbstractZigToolchain
): ZigDebugParametersBase<ZigProfileStateTest> { ): ZigDebugParametersBase<ZigProfileStateTest> {
return ZigDebugParametersTest(debuggerDriver, LocalZigToolchain.ensureLocal(toolchain), state) return ZigDebugParametersTest(debuggerDriver, LocalZigToolchain.ensureLocal(toolchain), state)
} }

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -31,7 +31,6 @@ import com.falsepattern.zigbrains.shared.coroutine.launchWithEDT
import com.falsepattern.zigbrains.shared.coroutine.runModalOrBlocking import com.falsepattern.zigbrains.shared.coroutine.runModalOrBlocking
import com.falsepattern.zigbrains.shared.zigCoroutineScope import com.falsepattern.zigbrains.shared.zigCoroutineScope
import com.intellij.ide.plugins.PluginManager import com.intellij.ide.plugins.PluginManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.observable.util.whenItemSelected import com.intellij.openapi.observable.util.whenItemSelected
import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.ComboBox
@ -89,7 +88,7 @@ class ZigDebuggerToolchainConfigurableUi : ZigDebuggerUiComponent {
row(ZigDebugBundle.message("settings.debugger.toolchain.debugger.label")) { row(ZigDebugBundle.message("settings.debugger.toolchain.debugger.label")) {
comment = cell(debuggerKindComboBox) comment = cell(debuggerKindComboBox)
.comment("", DEFAULT_COMMENT_WIDTH) { .comment("", DEFAULT_COMMENT_WIDTH) {
zigCoroutineScope.launchWithEDT(ModalityState.defaultModalityState()) { zigCoroutineScope.launchWithEDT {
withModalProgress(ModalTaskOwner.component(debuggerKindComboBox), "Downloading debugger", TaskCancellation.cancellable()) { withModalProgress(ModalTaskOwner.component(debuggerKindComboBox), "Downloading debugger", TaskCancellation.cancellable()) {
downloadDebugger() downloadDebugger()
} }
@ -97,7 +96,7 @@ class ZigDebuggerToolchainConfigurableUi : ZigDebuggerUiComponent {
} }
.applyToComponent { .applyToComponent {
whenItemSelected(null) { whenItemSelected(null) {
zigCoroutineScope.launchWithEDT(ModalityState.defaultModalityState()) { zigCoroutineScope.launchWithEDT {
this@ZigDebuggerToolchainConfigurableUi.update() this@ZigDebuggerToolchainConfigurableUi.update()
} }
} }
@ -112,7 +111,7 @@ class ZigDebuggerToolchainConfigurableUi : ZigDebuggerUiComponent {
cell(useClion) cell(useClion)
} }
} }
zigCoroutineScope.launchWithEDT(ModalityState.defaultModalityState()) { zigCoroutineScope.launchWithEDT {
update() update()
} }
} }

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -27,8 +27,10 @@ import com.falsepattern.zigbrains.debugger.settings.MSVCDownloadPermission
import com.falsepattern.zigbrains.debugger.settings.ZigDebuggerSettings import com.falsepattern.zigbrains.debugger.settings.ZigDebuggerSettings
import com.falsepattern.zigbrains.debugger.toolchain.ZigDebuggerToolchainService.Companion.downloadPath import com.falsepattern.zigbrains.debugger.toolchain.ZigDebuggerToolchainService.Companion.downloadPath
import com.falsepattern.zigbrains.shared.coroutine.withCurrentEDTModalityContext import com.falsepattern.zigbrains.shared.coroutine.withCurrentEDTModalityContext
import com.falsepattern.zigbrains.shared.coroutine.withEDTContext
import com.intellij.notification.Notification import com.intellij.notification.Notification
import com.intellij.notification.NotificationType import com.intellij.notification.NotificationType
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.progress.coroutineToIndicator import com.intellij.openapi.progress.coroutineToIndicator
import com.intellij.openapi.ui.DialogBuilder import com.intellij.openapi.ui.DialogBuilder
import com.intellij.platform.util.progress.withProgressText import com.intellij.platform.util.progress.withProgressText

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -23,7 +23,6 @@
package com.falsepattern.zigbrains.debugger.toolchain package com.falsepattern.zigbrains.debugger.toolchain
import com.falsepattern.zigbrains.debugger.ZigDebugBundle import com.falsepattern.zigbrains.debugger.ZigDebugBundle
import com.falsepattern.zigbrains.shared.Unarchiver
import com.intellij.notification.Notification import com.intellij.notification.Notification
import com.intellij.notification.NotificationType import com.intellij.notification.NotificationType
import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.PathManager
@ -35,20 +34,22 @@ import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogBuilder import com.intellij.openapi.ui.DialogBuilder
import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.toNioPathOrNull import com.intellij.openapi.util.io.toNioPathOrNull
import com.intellij.platform.util.progress.reportSequentialProgress
import com.intellij.ui.BrowserHyperlinkListener import com.intellij.ui.BrowserHyperlinkListener
import com.intellij.ui.HyperlinkLabel import com.intellij.ui.HyperlinkLabel
import com.intellij.ui.components.JBPanel import com.intellij.ui.components.JBPanel
import com.intellij.util.application import com.intellij.util.application
import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.download.DownloadableFileService import com.intellij.util.download.DownloadableFileService
import com.intellij.util.io.Decompressor
import com.intellij.util.system.CpuArch import com.intellij.util.system.CpuArch
import com.intellij.util.system.OS import com.intellij.util.system.OS
import com.jetbrains.cidr.execution.debugger.CidrDebuggerPathManager import com.jetbrains.cidr.execution.debugger.CidrDebuggerPathManager
import com.jetbrains.cidr.execution.debugger.backend.bin.UrlProvider import com.jetbrains.cidr.execution.debugger.backend.bin.UrlProvider
import com.jetbrains.cidr.execution.debugger.backend.lldb.LLDBDriverConfiguration import com.jetbrains.cidr.execution.debugger.backend.lldb.LLDBDriverConfiguration
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runInterruptible
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import java.io.File
import java.io.IOException import java.io.IOException
import java.net.URL import java.net.URL
import java.nio.file.Path import java.nio.file.Path
@ -168,9 +169,7 @@ class ZigDebuggerToolchainService {
} }
try { try {
withContext(Dispatchers.IO) { downloadAndUnArchive(baseDir, downloadableBinaries)
downloadAndUnArchive(baseDir, downloadableBinaries)
}
return DownloadResult.Ok(baseDir) return DownloadResult.Ok(baseDir)
} catch (e: IOException) { } catch (e: IOException) {
//TODO logging //TODO logging
@ -209,40 +208,34 @@ class ZigDebuggerToolchainService {
@Throws(IOException::class) @Throws(IOException::class)
@RequiresEdt @RequiresEdt
private suspend fun downloadAndUnArchive(baseDir: Path, binariesToDownload: List<DownloadableDebuggerBinary>) { private suspend fun downloadAndUnArchive(baseDir: Path, binariesToDownload: List<DownloadableDebuggerBinary>) {
reportSequentialProgress { reporter -> val service = DownloadableFileService.getInstance()
val service = DownloadableFileService.getInstance()
val downloadDir = baseDir.toFile() val downloadDir = baseDir.toFile()
downloadDir.deleteRecursively() downloadDir.deleteRecursively()
val descriptions = binariesToDownload.map { val descriptions = binariesToDownload.map {
service.createFileDescription(it.url, fileName(it.url)) service.createFileDescription(it.url, fileName(it.url))
}
val downloader = service.createDownloader(descriptions, "Debugger downloading")
val downloadDirectory = downloadPath().toFile()
val downloadResults = reporter.sizedStep(100) {
coroutineToIndicator {
downloader.download(downloadDirectory)
}
}
val versions = Properties()
for (result in downloadResults) {
val downloadUrl = result.second.downloadUrl
val binaryToDownload = binariesToDownload.first { it.url == downloadUrl }
val propertyName = binaryToDownload.propertyName
val archiveFile = result.first
reporter.indeterminateStep {
coroutineToIndicator {
Unarchiver.unarchive(archiveFile.toPath(), baseDir, binaryToDownload.prefix)
}
}
archiveFile.delete()
versions[propertyName] = binaryToDownload.version
}
saveVersionsFile(baseDir, versions)
} }
val downloader = service.createDownloader(descriptions, "Debugger downloading")
val downloadDirectory = downloadPath().toFile()
val downloadResults = withContext(Dispatchers.IO) {
coroutineToIndicator {
downloader.download(downloadDirectory)
}
}
val versions = Properties()
for (result in downloadResults) {
val downloadUrl = result.second.downloadUrl
val binaryToDownload = binariesToDownload.first { it.url == downloadUrl }
val propertyName = binaryToDownload.propertyName
val archiveFile = result.first
Unarchiver.unarchive(archiveFile, downloadDir, binaryToDownload.prefix)
archiveFile.delete()
versions[propertyName] = binaryToDownload.version
}
saveVersionsFile(baseDir, versions)
} }
private fun lldbUrls(): Pair<URL, URL>? { private fun lldbUrls(): Pair<URL, URL>? {
@ -337,6 +330,38 @@ class ZigDebuggerToolchainService {
} }
} }
private enum class Unarchiver {
ZIP {
override val extension = "zip"
override fun createDecompressor(file: File) = Decompressor.Zip(file)
},
TAR {
override val extension = "tar.gz"
override fun createDecompressor(file: File) = Decompressor.Tar(file)
},
VSIX {
override val extension = "vsix"
override fun createDecompressor(file: File) = Decompressor.Zip(file)
};
protected abstract val extension: String
protected abstract fun createDecompressor(file: File): Decompressor
companion object {
@Throws(IOException::class)
suspend fun unarchive(archivePath: File, dst: File, prefix: String? = null) {
runInterruptible {
val unarchiver = entries.find { archivePath.name.endsWith(it.extension) } ?: error("Unexpected archive type: $archivePath")
val dec = unarchiver.createDecompressor(archivePath)
if (prefix != null) {
dec.removePrefixPath(prefix)
}
dec.extract(dst)
}
}
}
}
sealed class DownloadResult { sealed class DownloadResult {
class Ok(val baseDir: Path): DownloadResult() class Ok(val baseDir: Path): DownloadResult()
data object NoUrls: DownloadResult() data object NoUrls: DownloadResult()

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -40,7 +40,7 @@ abstract class MSVCDriverConfiguration: DAPDebuggerDriverConfiguration() {
override fun createDriverCommandLine(driver: DebuggerDriver, arch: ArchitectureType): GeneralCommandLine { override fun createDriverCommandLine(driver: DebuggerDriver, arch: ArchitectureType): GeneralCommandLine {
val path = debuggerExecutable val path = debuggerExecutable
val cli = GeneralCommandLine() val cli = GeneralCommandLine()
cli.withExePath(path.pathString) cli.exePath = path.pathString
cli.addParameters("--interpreter=vscode", "--extconfigdir=%USERPROFILE%\\.cppvsdbg\\extensions") cli.addParameters("--interpreter=vscode", "--extconfigdir=%USERPROFILE%\\.cppvsdbg\\extensions")
cli.withWorkingDirectory(path.parent) cli.withWorkingDirectory(path.parent)
return cli return cli

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -39,8 +39,9 @@ import org.eclipse.lsp4j.jsonrpc.debug.messages.DebugResponseMessage
import org.eclipse.lsp4j.jsonrpc.messages.Message import org.eclipse.lsp4j.jsonrpc.messages.Message
import org.eclipse.lsp4j.jsonrpc.services.JsonRequest import org.eclipse.lsp4j.jsonrpc.services.JsonRequest
import java.io.InputStream import java.io.InputStream
import java.lang.RuntimeException
import java.security.MessageDigest import java.security.MessageDigest
import java.util.* import java.util.Base64
import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletableFuture
import java.util.zip.Inflater import java.util.zip.Inflater

View file

@ -1,5 +1,5 @@
<idea-plugin package="com.falsepattern.zigbrains.debugger"> <idea-plugin package="com.falsepattern.zigbrains.debugger">
<depends>com.intellij.modules.cidr.debugger</depends> <depends>com.intellij.nativeDebug</depends>
<extensions defaultExtensionNs="com.intellij"> <extensions defaultExtensionNs="com.intellij">
<configurationType <configurationType

View file

@ -15,7 +15,7 @@ debugger.run.unavailable.reason.download.button=Download
debugger.run.unavailable.reason.update=Debugger is outdated debugger.run.unavailable.reason.update=Debugger is outdated
debugger.run.unavailable.reason.update.button=Update debugger.run.unavailable.reason.update.button=Update
debug.build.compile.failed.boilerplate={0}\nPlease edit this intellij build configuration and specify the path of the executable created by "zig build" directly! debug.build.compile.failed.boilerplate={0}\nPlease edit this intellij build configuration and specify the path of the executable created by "zig build" directly!
debug.base.compile.failed.generic=Failed to compile executable with command: {0} debug.base.compile.failed.generic=Failed to compile executable
debug.base.compile.failed.no-exe=Failed to find compiled binary debug.base.compile.failed.no-exe=Failed to find compiled binary
debug.build.compile.failed.multiple-exe=Multiple compiled binaries found debug.build.compile.failed.multiple-exe=Multiple compiled binaries found
debug.build.compile.failed.no-workdir=Cannot find working directory to run debugged executable debug.build.compile.failed.no-workdir=Cannot find working directory to run debugged executable

View file

@ -7,17 +7,18 @@ plugins {
kotlin("plugin.serialization") kotlin("plugin.serialization")
} }
val lsp4ijVersion: String by project
val lsp4jVersion: String by project
val ideaCommunityVersion: String by project val ideaCommunityVersion: String by project
val useInstaller = property("useInstaller").toString().toBoolean() val useInstaller = property("useInstaller").toString().toBoolean()
val serializationVersion: String by project
dependencies { dependencies {
intellijPlatform { intellijPlatform {
create(IntelliJPlatformType.IntellijIdeaCommunity, ideaCommunityVersion, useInstaller = useInstaller) create(IntelliJPlatformType.IntellijIdeaCommunity, ideaCommunityVersion, useInstaller = useInstaller)
} }
compileOnly("org.jetbrains.kotlinx:kotlinx-serialization-core-jvm:$serializationVersion") { compileOnly("com.redhat.devtools.intellij:lsp4ij:$lsp4ijVersion")
isTransitive = false compileOnly("org.eclipse.lsp4j:org.eclipse.lsp4j:$lsp4jVersion")
} compileOnly("org.jetbrains.kotlinx:kotlinx-serialization-core:1.7.3")
} }
//region grammars //region grammars

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -34,12 +34,9 @@ import static com.falsepattern.zigbrains.zig.psi.ZigTypes.*;
%implements FlexLexer %implements FlexLexer
%function advance %function advance
%type IElementType %type IElementType
%unicode
WHITE_SPACE=\s+ CRLF=\R
WHITE_SPACE=[\s]+
// visual studio parity
LF=\r\n?|[\n\u0085\u2028\u2029]
bin=[01] bin=[01]
bin_="_"? {bin} bin_="_"? {bin}
@ -56,13 +53,13 @@ dec_int={dec} {dec_}*
hex_int={hex} {hex_}* hex_int={hex} {hex_}*
char_char= \\ . char_char= \\ .
| [^\'\r\n\u0085\u2028\u2029] | [^\'\n]
string_char= \\ . string_char= \\ .
| [^\"\r\n\u0085\u2028\u2029] | [^\"\n]
nl_wrap={LF} (\s|{LF})* all_nl_wrap=[^\n]* [ \n]*
all_no_nl=[^\r\n\u0085\u2028\u2029]+ all_no_nl=[^\n]+
FLOAT= "0x" {hex_int} "." {hex_int} ([pP] [-+]? {dec_int})? FLOAT= "0x" {hex_int} "." {hex_int} ([pP] [-+]? {dec_int})?
@ -86,35 +83,30 @@ BUILTINIDENTIFIER="@"[A-Za-z_][A-Za-z0-9_]*
%state UNT_SQUOT %state UNT_SQUOT
%state UNT_DQUOT %state UNT_DQUOT
%state CMT_LINE %state CDOC_CMT
%state CMT_DOC %state DOC_CMT
%state CMT_CDOC %state LINE_CMT
%% %%
//Comments //Comments
<YYINITIAL> "//!" { yybegin(CMT_CDOC); } <YYINITIAL> "//!" { yybegin(CDOC_CMT); }
<YYINITIAL> "////" { yybegin(CMT_LINE); } <CDOC_CMT> {all_nl_wrap} "//!" { }
<YYINITIAL> "///" { yybegin(CMT_DOC); } <CDOC_CMT> {all_no_nl} { }
<YYINITIAL> "//" { yybegin(CMT_LINE); } <CDOC_CMT> \n { yybegin(YYINITIAL); return CONTAINER_DOC_COMMENT; }
<CDOC_CMT> <<EOF>> { yybegin(YYINITIAL); return CONTAINER_DOC_COMMENT; }
<CMT_LINE> {all_no_nl} { } <YYINITIAL> "///" { yybegin(DOC_CMT); }
<CMT_LINE> {nl_wrap} "////" { } <DOC_CMT> {all_nl_wrap} "///" { }
<CMT_LINE> {nl_wrap} "///" { yypushback(yylength()); yybegin(YYINITIAL); return LINE_COMMENT; } <DOC_CMT> {all_no_nl} { }
<CMT_LINE> {nl_wrap} "//" { } <DOC_CMT> \n { yybegin(YYINITIAL); return DOC_COMMENT; }
<CMT_LINE> {LF} { yybegin(YYINITIAL); return LINE_COMMENT; } <DOC_CMT> <<EOF>> { yybegin(YYINITIAL); return DOC_COMMENT; }
<CMT_LINE> <<EOF>> { yybegin(YYINITIAL); return LINE_COMMENT; }
<CMT_DOC> {all_no_nl} { } <YYINITIAL> "//" { yybegin(LINE_CMT); }
<CMT_DOC> {nl_wrap} "////" { yypushback(yylength()); yybegin(YYINITIAL); return DOC_COMMENT; } <LINE_CMT> {all_nl_wrap} "//" { }
<CMT_DOC> {nl_wrap} "///" { } <LINE_CMT> {all_no_nl} { }
<CMT_DOC> {LF} { yybegin(YYINITIAL); return DOC_COMMENT; } <LINE_CMT> \n { yybegin(YYINITIAL); return LINE_COMMENT; }
<CMT_DOC> <<EOF>> { yybegin(YYINITIAL); return DOC_COMMENT; } <LINE_CMT> <<EOF>> { yybegin(YYINITIAL); return LINE_COMMENT; }
<CMT_CDOC> {all_no_nl} { }
<CMT_CDOC> {nl_wrap} "//!" { }
<CMT_CDOC> {LF} { yybegin(YYINITIAL); return CONTAINER_DOC_COMMENT; }
<CMT_CDOC> <<EOF>> { yybegin(YYINITIAL); return CONTAINER_DOC_COMMENT; }
//Symbols //Symbols
<YYINITIAL> "&" { return AMPERSAND; } <YYINITIAL> "&" { return AMPERSAND; }
@ -234,31 +226,24 @@ BUILTINIDENTIFIER="@"[A-Za-z_][A-Za-z0-9_]*
<YYINITIAL> "volatile" { return KEYWORD_VOLATILE; } <YYINITIAL> "volatile" { return KEYWORD_VOLATILE; }
<YYINITIAL> "while" { return KEYWORD_WHILE; } <YYINITIAL> "while" { return KEYWORD_WHILE; }
//Strings
<YYINITIAL> "'" { yybegin(CHAR_LIT); } <YYINITIAL> "'" { yybegin(CHAR_LIT); }
<CHAR_LIT> {char_char}*"'" { yybegin(YYINITIAL); return CHAR_LITERAL; } <CHAR_LIT> {char_char}*"'" { yybegin(YYINITIAL); return CHAR_LITERAL; }
<CHAR_LIT> <<EOF>> { yybegin(YYINITIAL); return BAD_SQUOT; } <CHAR_LIT> <<EOF>> { yybegin(YYINITIAL); return BAD_SQUOT; }
<CHAR_LIT> [^] { yypushback(1); yybegin(UNT_SQUOT); } <CHAR_LIT> [^] { yypushback(1); yybegin(UNT_SQUOT); }
<YYINITIAL> {FLOAT} { return FLOAT; }
<YYINITIAL> {INTEGER} { return INTEGER; }
<YYINITIAL> "\"" { yybegin(STR_LIT); } <YYINITIAL> "\"" { yybegin(STR_LIT); }
<STR_LIT> {string_char}*"\"" { yybegin(YYINITIAL); return STRING_LITERAL_SINGLE; } <STR_LIT> {string_char}*"\"" { yybegin(YYINITIAL); return STRING_LITERAL_SINGLE; }
<STR_LIT> <<EOF>> { yybegin(YYINITIAL); return BAD_DQUOT; } <STR_LIT> <<EOF>> { yybegin(YYINITIAL); return BAD_DQUOT; }
<STR_LIT> [^] { yypushback(1); yybegin(UNT_DQUOT); } <STR_LIT> [^] { yypushback(1); yybegin(UNT_DQUOT); }
<YYINITIAL> "\\\\" { yybegin(STR_MULT_LINE); } <YYINITIAL> "\\\\" { yybegin(STR_MULT_LINE); }
<STR_MULT_LINE> {all_no_nl} { } <STR_MULT_LINE> {all_nl_wrap} "\\\\" { }
<STR_MULT_LINE> {nl_wrap} "\\\\" { } <STR_MULT_LINE> {all_no_nl} { }
<STR_MULT_LINE> {LF} { yybegin(YYINITIAL); return STRING_LITERAL_MULTI; } <STR_MULT_LINE> \n { yybegin(YYINITIAL); return STRING_LITERAL_MULTI; }
<STR_MULT_LINE> <<EOF>> { yybegin(YYINITIAL); return STRING_LITERAL_MULTI; } <STR_MULT_LINE> <<EOF>> { yybegin(YYINITIAL); return STRING_LITERAL_MULTI; }
//Numbers
<YYINITIAL> {FLOAT} { return FLOAT; }
<YYINITIAL> {INTEGER} { return INTEGER; }
//Identifiers
<YYINITIAL> {IDENTIFIER_PLAIN} { return IDENTIFIER; } <YYINITIAL> {IDENTIFIER_PLAIN} { return IDENTIFIER; }
<YYINITIAL> "@\"" { yybegin(ID_QUOT); } <YYINITIAL> "@\"" { yybegin(ID_QUOT); }
<ID_QUOT> {string_char}*"\"" { yybegin(YYINITIAL); return IDENTIFIER; } <ID_QUOT> {string_char}*"\"" { yybegin(YYINITIAL); return IDENTIFIER; }
@ -267,17 +252,13 @@ BUILTINIDENTIFIER="@"[A-Za-z_][A-Za-z0-9_]*
<YYINITIAL> {BUILTINIDENTIFIER} { return BUILTINIDENTIFIER; } <YYINITIAL> {BUILTINIDENTIFIER} { return BUILTINIDENTIFIER; }
//Error handling
<UNT_SQUOT> <<EOF>> { yybegin(YYINITIAL); return BAD_SQUOT; } <UNT_SQUOT> <<EOF>> { yybegin(YYINITIAL); return BAD_SQUOT; }
<UNT_SQUOT> {LF} { yybegin(YYINITIAL); return BAD_SQUOT; } <UNT_SQUOT> {CRLF} { yybegin(YYINITIAL); return BAD_SQUOT; }
<UNT_SQUOT> {all_no_nl} { } <UNT_SQUOT> {all_no_nl} { }
<UNT_DQUOT> <<EOF>> { yybegin(YYINITIAL); return BAD_DQUOT; } <UNT_DQUOT> <<EOF>> { yybegin(YYINITIAL); return BAD_DQUOT; }
<UNT_DQUOT> {LF} { yybegin(YYINITIAL); return BAD_DQUOT; } <UNT_DQUOT> {CRLF} { yybegin(YYINITIAL); return BAD_DQUOT; }
<UNT_DQUOT> {all_no_nl} { } <UNT_DQUOT> {all_no_nl} { }
//Misc
<YYINITIAL> {WHITE_SPACE} { return WHITE_SPACE; } <YYINITIAL> {WHITE_SPACE} { return WHITE_SPACE; }
[^] { return BAD_CHARACTER; } [^] { return BAD_CHARACTER; }

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -34,57 +34,46 @@
elementTypeClass="com.falsepattern.zigbrains.zon.parser.ZonElementType" elementTypeClass="com.falsepattern.zigbrains.zon.parser.ZonElementType"
tokenTypeClass="com.falsepattern.zigbrains.zon.parser.ZonTokenType" tokenTypeClass="com.falsepattern.zigbrains.zon.parser.ZonTokenType"
tokens=[ tokens=[
LINE_COMMENT='comment'
DOT='.' DOT='.'
EQUAL='='
LBRACE='{' LBRACE='{'
RBRACE='}' RBRACE='}'
EQ='='
COMMA=',' COMMA=','
KEYWORD_FALSE='false' COMMENT='comment'
KEYWORD_TRUE='true' ID='identifier'
KEYWORD_NULL='null' STRING_LITERAL_SINGLE='string'
NUM_NAN='nan' LINE_STRING='multiline string'
NUM_INF='inf' BAD_STRING='unterminated string'
CHAR_LITERAL='char literal' BOOL_TRUE='true'
STRING_LITERAL_SINGLE='string literal' BOOL_FALSE='false'
STRING_LITERAL_MULTI='multiline string literal'
FLOAT='float'
INTEGER='integer'
IDENTIFIER='identifier'
BAD_SQUOT='unterminated quote'
BAD_DQUOT='unterminated double quote'
] ]
//Mixins
mixin("entry")="com.falsepattern.zigbrains.zon.psi.impl.mixins.ZonEntryMixinImpl"
implements("entry")="com.falsepattern.zigbrains.zon.psi.mixins.ZonEntryMixin"
mixin("identifier")="com.falsepattern.zigbrains.zon.psi.impl.mixins.ZonIdentifierMixinImpl"
implements("identifier")="com.falsepattern.zigbrains.zon.psi.mixins.ZonIdentifierMixin"
} }
Root ::= Expr zonFile ::= entry
Expr entry ::= DOT LBRACE (list | struct | ()) RBRACE
::= CHAR_LITERAL
| StringLiteral
| DOT IDENTIFIER
| DOT InitList
| Bool
| Number
| KEYWORD_NULL
struct ::= (property | property_placeholder) (COMMA (property_placeholder? property property_placeholder? | property_placeholder))* COMMA?
InitList list ::= value (COMMA value)* COMMA?
::= LBRACE ZB_InitList_Body RBRACE {pin=1}
private ZB_InitList_Body property ::= DOT identifier EQ value
::= FieldInit (COMMA ZB_InitList_FieldInit)* COMMA?
| Expr (COMMA ZB_InitList_Expr)* COMMA?
| ()
private ZB_InitList_FieldInit ::= FieldInit {recoverWhile="ZB_InitList_Recover"} identifier ::= ID
private ZB_InitList_Expr ::= Expr {recoverWhile="ZB_InitList_Recover"}
private ZB_InitList_Recover ::= !(COMMA | RBRACE) property_placeholder ::= DOT? INTELLIJ_COMPLETION_DUMMY
FieldInit ::= DOT IDENTIFIER EQUAL Expr private value ::= entry | boolean | STRING_LITERAL | value_placeholder
Bool ::= KEYWORD_TRUE | KEYWORD_FALSE value_placeholder ::= INTELLIJ_COMPLETION_DUMMY
Number ::= FLOAT | INTEGER | NUM_NAN | NUM_INF boolean ::= BOOL_TRUE | BOOL_FALSE
StringLiteral ::= STRING_LITERAL_SINGLE | STRING_LITERAL_MULTI STRING_LITERAL ::= STRING_LITERAL_SINGLE | LINE_STRING+

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -36,124 +36,54 @@ import static com.falsepattern.zigbrains.zon.psi.ZonTypes.*;
%type IElementType %type IElementType
%unicode %unicode
WHITE_SPACE=\s+ CRLF=\R
WHITE_SPACE=[\s]+
LINE_COMMENT="//" [^\n]* | "////" [^\n]*
COMMENT="///".*
// visual studio parity ID=[A-Za-z_][A-Za-z0-9_]*
LF=\r\n?|[\n\u0085\u2028\u2029]
bin=[01]
bin_="_"? {bin}
oct=[0-7]
oct_="_"? {oct}
hex=[0-9a-fA-F] hex=[0-9a-fA-F]
hex_="_"? {hex} char_escape
dec=[0-9] = "\\x" {hex} {hex}
dec_="_"? {dec} | "\\u{" {hex}+ "}"
| "\\" [nr\\t'\"]
bin_int={bin} {bin_}* string_char
oct_int={oct} {oct_}* = {char_escape}
dec_int={dec} {dec_}* | [^\\\"\n]
hex_int={hex} {hex_}*
char_char= \\ . LINE_STRING=("\\\\" [^\n]* [ \n]*)+
| [^\'\r\n\u0085\u2028\u2029]
string_char= \\ . %state STRING_LITERAL
| [^\"\r\n\u0085\u2028\u2029] %state ID_STRING
%state UNCLOSED_STRING
nl_wrap={LF} (\s|{LF})*
all_no_nl=[^\r\n\u0085\u2028\u2029]+
FLOAT= "0x" {hex_int} "." {hex_int} ([pP] [-+]? {dec_int})?
| {dec_int} "." {dec_int} ([eE] [-+]? {dec_int})?
| "0x" {hex_int} [pP] [-+]? {dec_int}
| {dec_int} [eE] [-+]? {dec_int}
INTEGER= "0b" {bin_int}
| "0o" {oct_int}
| "0x" {hex_int}
| {dec_int}
IDENTIFIER_PLAIN=[A-Za-z_][A-Za-z0-9_]*
%state STR_LIT
%state STR_MULT_LINE
%state CHAR_LIT
%state ID_QUOT
%state UNT_SQUOT
%state UNT_DQUOT
%state CMT_LINE
%% %%
//Comments
<YYINITIAL> "//" { yybegin(CMT_LINE); }
<CMT_LINE> {all_no_nl} { }
<CMT_LINE> {nl_wrap} "//" { }
<CMT_LINE> \R { yybegin(YYINITIAL); return LINE_COMMENT; }
<CMT_LINE> <<EOF>> { yybegin(YYINITIAL); return LINE_COMMENT; }
//Symbols
<YYINITIAL> "." { return DOT; }
<YYINITIAL> "=" { return EQUAL; }
<YYINITIAL> "{" { return LBRACE; }
<YYINITIAL> "}" { return RBRACE; }
<YYINITIAL> "," { return COMMA; }
//Keywords
<YYINITIAL> "false" { return KEYWORD_FALSE; }
<YYINITIAL> "true" { return KEYWORD_TRUE; }
<YYINITIAL> "null" { return KEYWORD_NULL; }
<YYINITIAL> "nan" { return NUM_NAN; }
<YYINITIAL> "inf" { return NUM_INF; }
//Strings
<YYINITIAL> "'" { yybegin(CHAR_LIT); }
<CHAR_LIT> {char_char}*"'" { yybegin(YYINITIAL); return CHAR_LITERAL; }
<CHAR_LIT> <<EOF>> { yybegin(YYINITIAL); return BAD_SQUOT; }
<CHAR_LIT> [^] { yypushback(1); yybegin(UNT_SQUOT); }
<YYINITIAL> "\"" { yybegin(STR_LIT); }
<STR_LIT> {string_char}*"\"" { yybegin(YYINITIAL); return STRING_LITERAL_SINGLE; }
<STR_LIT> <<EOF>> { yybegin(YYINITIAL); return BAD_DQUOT; }
<STR_LIT> [^] { yypushback(1); yybegin(UNT_DQUOT); }
<YYINITIAL> "\\\\" { yybegin(STR_MULT_LINE); }
<STR_MULT_LINE> {all_no_nl} { }
<STR_MULT_LINE> {nl_wrap} "\\\\" { }
<STR_MULT_LINE> {LF} { yybegin(YYINITIAL); return STRING_LITERAL_MULTI; }
<STR_MULT_LINE> <<EOF>> { yybegin(YYINITIAL); return STRING_LITERAL_MULTI; }
//Numbers
<YYINITIAL> {FLOAT} { return FLOAT; }
<YYINITIAL> {INTEGER} { return INTEGER; }
//Identifiers
<YYINITIAL> {IDENTIFIER_PLAIN} { return IDENTIFIER; }
<YYINITIAL> "@\"" { yybegin(ID_QUOT); }
<ID_QUOT> {string_char}*"\"" { yybegin(YYINITIAL); return IDENTIFIER; }
<ID_QUOT> <<EOF>> { yybegin(YYINITIAL); return BAD_DQUOT; }
<ID_QUOT> [^] { yypushback(1); yybegin(UNT_DQUOT); }
//Error handling
<UNT_SQUOT> <<EOF>> { yybegin(YYINITIAL); return BAD_SQUOT; }
<UNT_SQUOT> {LF} { yybegin(YYINITIAL); return BAD_SQUOT; }
<UNT_SQUOT> {all_no_nl} { }
<UNT_DQUOT> <<EOF>> { yybegin(YYINITIAL); return BAD_DQUOT; }
<UNT_DQUOT> {LF} { yybegin(YYINITIAL); return BAD_DQUOT; }
<UNT_DQUOT> {all_no_nl} { }
//Misc
<YYINITIAL> {WHITE_SPACE} { return WHITE_SPACE; } <YYINITIAL> {WHITE_SPACE} { return WHITE_SPACE; }
<YYINITIAL> "." { return DOT; }
<YYINITIAL> "IntellijIdeaRulezzz" { return INTELLIJ_COMPLETION_DUMMY; }
<YYINITIAL> "{" { return LBRACE; }
<YYINITIAL> "}" { return RBRACE; }
<YYINITIAL> "=" { return EQ; }
<YYINITIAL> "," { return COMMA; }
<YYINITIAL> "true" { return BOOL_TRUE; }
<YYINITIAL> "false" { return BOOL_FALSE; }
<YYINITIAL> {COMMENT} { return COMMENT; }
<YYINITIAL> {LINE_COMMENT} { return COMMENT; }
<YYINITIAL> {ID} { return ID; }
<YYINITIAL> "@\"" { yybegin(ID_STRING); }
<ID_STRING> {string_char}*"\"" { yybegin(YYINITIAL); return ID; }
<ID_STRING> [^] { yypushback(1); yybegin(UNCLOSED_STRING); }
<YYINITIAL> "\"" { yybegin(STRING_LITERAL); }
<STRING_LITERAL> {string_char}*"\"" { yybegin(YYINITIAL); return STRING_LITERAL_SINGLE; }
<STRING_LITERAL> [^] { yypushback(1); yybegin(UNCLOSED_STRING); }
<UNCLOSED_STRING>[^\n]*{CRLF} { yybegin(YYINITIAL); return BAD_STRING; }
<YYINITIAL> {LINE_STRING} { return LINE_STRING; }
[^] { return BAD_CHARACTER; } [^] { return BAD_CHARACTER; }

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -22,6 +22,13 @@
package com.falsepattern.zigbrains package com.falsepattern.zigbrains
import com.falsepattern.zigbrains.direnv.DirenvCmd
import com.falsepattern.zigbrains.direnv.emptyEnv
import com.falsepattern.zigbrains.direnv.getDirenv
import com.falsepattern.zigbrains.lsp.settings.zlsSettings
import com.falsepattern.zigbrains.project.settings.zigProjectSettings
import com.falsepattern.zigbrains.project.toolchain.LocalZigToolchain
import com.falsepattern.zigbrains.project.toolchain.ZigToolchainProvider
import com.intellij.ide.BrowserUtil import com.intellij.ide.BrowserUtil
import com.intellij.ide.plugins.PluginManager import com.intellij.ide.plugins.PluginManager
import com.intellij.notification.Notification import com.intellij.notification.Notification
@ -33,8 +40,10 @@ import com.intellij.openapi.options.Configurable
import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.project.Project import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.ProjectActivity import com.intellij.openapi.startup.ProjectActivity
import com.intellij.openapi.util.UserDataHolderBase
import java.lang.reflect.Constructor import java.lang.reflect.Constructor
import java.lang.reflect.Method import java.lang.reflect.Method
import kotlin.io.path.pathString
class ZBStartup: ProjectActivity { class ZBStartup: ProjectActivity {
var firstInit = true var firstInit = true
@ -67,6 +76,30 @@ class ZBStartup: ProjectActivity {
notif.notify(null) notif.notify(null)
} }
} }
//Autodetection
val zigProjectState = project.zigProjectSettings.state
if (zigProjectState.toolchainPath.isNullOrBlank()) {
val data = UserDataHolderBase()
data.putUserData(LocalZigToolchain.DIRENV_KEY,
DirenvCmd.direnvInstalled() && !project.isDefault && zigProjectState.direnv
)
val tc = ZigToolchainProvider.suggestToolchain(project, data) ?: return
if (tc is LocalZigToolchain) {
zigProjectState.toolchainPath = tc.location.pathString
project.zigProjectSettings.state = zigProjectState
}
}
val zlsState = project.zlsSettings.state
if (zlsState.zlsPath.isBlank()) {
val env = if (DirenvCmd.direnvInstalled() && !project.isDefault && zlsState.direnv)
project.getDirenv()
else
emptyEnv
env.findExecutableOnPATH("zls")?.let {
zlsState.zlsPath = it.pathString
project.zlsSettings.state = zlsState
}
}
} }
} }

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -29,53 +29,23 @@ import com.intellij.ide.impl.isTrusted
import com.intellij.notification.Notification import com.intellij.notification.Notification
import com.intellij.notification.NotificationType import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications import com.intellij.notification.Notifications
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project import com.intellij.openapi.project.Project
import com.intellij.openapi.project.guessProjectDir import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UserDataHolder
import com.intellij.openapi.vfs.toNioPathOrNull
import com.intellij.platform.util.progress.withProgressText import com.intellij.platform.util.progress.withProgressText
import com.intellij.util.io.awaitExit import com.intellij.util.io.awaitExit
import com.intellij.util.xmlb.annotations.Attribute
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
import java.nio.file.Path import java.nio.file.Path
import kotlin.io.path.isRegularFile
@Service(Service.Level.PROJECT) object DirenvCmd {
@State( suspend fun importDirenv(project: Project): Env {
name = "Direnv", if (!direnvInstalled() || !project.isTrusted())
storages = [Storage("zigbrains.xml")] return emptyEnv
) val workDir = project.guessProjectDir()?.toNioPath() ?: return emptyEnv
class DirenvService(val project: Project): SerializablePersistentStateComponent<DirenvService.State>(State()), IDirenvService {
private val mutex = Mutex()
override val isInstalled: Boolean by lazy { val runOutput = run(project, workDir, "export", "json")
// Using the builtin stuff here instead of Env because it should only scan for direnv on the process path
PathEnvironmentVariableUtil.findExecutableInPathOnAnyOS("direnv") != null
}
var isEnabledRaw: DirenvState
get() = state.enabled
set(value) {
updateState {
it.copy(enabled = value)
}
}
override val isEnabled: DirenvState
get() = isEnabledRaw
override suspend fun import(): Env {
if (!isInstalled || !project.isTrusted() || project.isDefault)
return Env.empty
val workDir = project.guessProjectDir()?.toNioPath() ?: return Env.empty
val runOutput = run(workDir, "export", "json")
if (runOutput.error) { if (runOutput.error) {
if (runOutput.output.contains("is blocked")) { if (runOutput.output.contains("is blocked")) {
Notifications.Bus.notify(Notification( Notifications.Bus.notify(Notification(
@ -84,7 +54,7 @@ class DirenvService(val project: Project): SerializablePersistentStateComponent<
ZigBrainsBundle.message("notification.content.direnv-blocked"), ZigBrainsBundle.message("notification.content.direnv-blocked"),
NotificationType.ERROR NotificationType.ERROR
)) ))
return Env.empty return emptyEnv
} else { } else {
Notifications.Bus.notify(Notification( Notifications.Bus.notify(Notification(
GROUP_DISPLAY_ID, GROUP_DISPLAY_ID,
@ -92,22 +62,22 @@ class DirenvService(val project: Project): SerializablePersistentStateComponent<
ZigBrainsBundle.message("notification.content.direnv-error", runOutput.output), ZigBrainsBundle.message("notification.content.direnv-error", runOutput.output),
NotificationType.ERROR NotificationType.ERROR
)) ))
return Env.empty return emptyEnv
} }
} }
return if (runOutput.output.isBlank()) { return if (runOutput.output.isBlank()) {
Env.empty emptyEnv
} else { } else {
Env(Json.decodeFromString<Map<String, String>>(runOutput.output)) Env(Json.decodeFromString<Map<String, String>>(runOutput.output))
} }
} }
private suspend fun run(workDir: Path, vararg args: String): DirenvOutput { private suspend fun run(project: Project, workDir: Path, vararg args: String): DirenvOutput {
val cli = GeneralCommandLine("direnv", *args).withWorkingDirectory(workDir) val cli = GeneralCommandLine("direnv", *args).withWorkingDirectory(workDir)
val (process, exitCode) = withProgressText("Running ${cli.commandLineString}") { val (process, exitCode) = withProgressText("Running ${cli.commandLineString}") {
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
mutex.withLock { project.direnvService.mutex.withLock {
val process = cli.createProcess() val process = cli.createProcess()
val exitCode = process.awaitExit() val exitCode = process.awaitExit()
process to exitCode process to exitCode
@ -124,39 +94,17 @@ class DirenvService(val project: Project): SerializablePersistentStateComponent<
return DirenvOutput(stdOut, false) return DirenvOutput(stdOut, false)
} }
fun hasDotEnv(): Boolean { private const val GROUP_DISPLAY_ID = "zigbrains-direnv"
if (!isInstalled)
return false private val _direnvInstalled by lazy {
val projectDir = project.guessProjectDir()?.toNioPathOrNull() ?: return false // Using the builtin stuff here instead of Env because it should only scan for direnv on the process path
return envFiles.any { projectDir.resolve(it).isRegularFile() } PathEnvironmentVariableUtil.findExecutableInPathOnAnyOS("direnv") != null
}
data class State(
@JvmField
@Attribute
var enabled: DirenvState = DirenvState.Auto
)
companion object {
private const val GROUP_DISPLAY_ID = "zigbrains-direnv"
fun getInstance(project: Project): IDirenvService = project.service<DirenvService>()
private val STATE_KEY = Key.create<DirenvState>("DIRENV_STATE")
fun getStateFor(data: UserDataHolder?, project: Project?): DirenvState {
return data?.getUserData(STATE_KEY) ?: project?.let { getInstance(project).isEnabled } ?: DirenvState.Disabled
}
fun setStateFor(data: UserDataHolder, state: DirenvState) {
data.putUserData(STATE_KEY, state)
}
} }
fun direnvInstalled() = _direnvInstalled
} }
sealed interface IDirenvService { suspend fun Project?.getDirenv(): Env {
val isInstalled: Boolean if (this == null)
val isEnabled: DirenvState return emptyEnv
suspend fun import(): Env return DirenvCmd.importDirenv(this)
} }
private val envFiles = listOf(".envrc", ".env")

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -22,19 +22,14 @@
package com.falsepattern.zigbrains.direnv package com.falsepattern.zigbrains.direnv
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project import com.intellij.openapi.project.Project
import kotlinx.coroutines.sync.Mutex
enum class DirenvState { @Service(Service.Level.PROJECT)
Auto, class DirenvProjectService {
Enabled, val mutex = Mutex()
Disabled; }
fun isEnabled(project: Project?): Boolean { val Project.direnvService get() = service<DirenvProjectService>()
return when(this) {
Enabled -> true
Disabled -> false
Auto -> project?.service<DirenvService>()?.hasDotEnv() == true
}
}
}

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -25,26 +25,20 @@ package com.falsepattern.zigbrains.direnv
import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.toNioPathOrNull import com.intellij.openapi.util.io.toNioPathOrNull
import com.intellij.util.EnvironmentUtil import com.intellij.util.EnvironmentUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.NonNls
import java.io.File import java.io.File
import kotlin.io.path.absolute import java.nio.file.Path
import kotlin.io.path.isDirectory import kotlin.io.path.*
import kotlin.io.path.isExecutable
import kotlin.io.path.isRegularFile
@JvmRecord
data class Env(val env: Map<String, String>) { data class Env(val env: Map<String, String>) {
private val path get() = getVariable("PATH")?.split(File.pathSeparatorChar) private val path get() = getVariable("PATH")?.split(File.pathSeparatorChar)
private fun getVariable(name: @NonNls String) = private fun getVariable(name: @NonNls String) =
env.getOrElse(name) { EnvironmentUtil.getValue(name) } env.getOrElse(name) { EnvironmentUtil.getValue(name) }
fun findAllExecutablesOnPATH(exe: @NonNls String) = flow { fun findExecutableOnPATH(exe: @NonNls String): Path? {
val exeName = if (SystemInfo.isWindows) "$exe.exe" else exe val exeName = if (SystemInfo.isWindows) "$exe.exe" else exe
val paths = path ?: return@flow val paths = path ?: return null
for (dir in paths) { for (dir in paths) {
val path = dir.toNioPathOrNull()?.absolute() ?: continue val path = dir.toNioPathOrNull()?.absolute() ?: continue
if (!path.toFile().exists() || !path.isDirectory()) if (!path.toFile().exists() || !path.isDirectory())
@ -52,11 +46,10 @@ data class Env(val env: Map<String, String>) {
val exePath = path.resolve(exeName).absolute() val exePath = path.resolve(exeName).absolute()
if (!exePath.isRegularFile() || !exePath.isExecutable()) if (!exePath.isRegularFile() || !exePath.isExecutable())
continue continue
emit(exePath) return exePath
} }
}.flowOn(Dispatchers.IO) return null
companion object {
val empty = Env(emptyMap())
} }
} }
val emptyEnv = Env(emptyMap())

View file

@ -1,101 +0,0 @@
/*
* This file is part of ZigBrains.
*
* Copyright (C) 2023-2025 FalsePattern
* All Rights Reserved
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* ZigBrains is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, only version 3 of the License.
*
* ZigBrains 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ZigBrains. If not, see <https://www.gnu.org/licenses/>.
*/
package com.falsepattern.zigbrains.direnv.ui
import com.falsepattern.zigbrains.ZigBrainsBundle
import com.falsepattern.zigbrains.direnv.DirenvService
import com.falsepattern.zigbrains.direnv.DirenvState
import com.falsepattern.zigbrains.project.settings.ZigProjectConfigurationProvider
import com.falsepattern.zigbrains.project.settings.ZigProjectConfigurationProvider.Companion.PROJECT_KEY
import com.falsepattern.zigbrains.shared.SubConfigurable
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComboBox
import com.intellij.ui.dsl.builder.Panel
import java.awt.event.ItemEvent
abstract class DirenvEditor<T>(private val sharedState: ZigProjectConfigurationProvider.IUserDataBridge?): SubConfigurable<T> {
private var cb: ComboBox<DirenvState>? = null
override fun attach(panel: Panel): Unit = with(panel) {
row(ZigBrainsBundle.message("settings.direnv.enable.label")) {
comboBox(DirenvState.entries).component.let {
cb = it
if (sharedState != null) {
it.addItemListener { e ->
if (e.stateChange != ItemEvent.SELECTED)
return@addItemListener
val item = e.item
if (item !is DirenvState)
return@addItemListener
DirenvService.setStateFor(sharedState, item)
}
}
}
}
}
override fun isModified(context: T): Boolean {
return isEnabled(context) != cb?.selectedItem as DirenvState
}
override fun apply(context: T) {
setEnabled(context, cb?.selectedItem as DirenvState)
}
override fun reset(context: T?) {
if (context == null) {
cb?.selectedItem = DirenvState.Auto
return
}
cb?.selectedItem = isEnabled(context)
}
override fun dispose() {
}
abstract fun isEnabled(context: T): DirenvState
abstract fun setEnabled(context: T, value: DirenvState)
class ForProject(sharedState: ZigProjectConfigurationProvider.IUserDataBridge) : DirenvEditor<Project>(sharedState) {
override fun isEnabled(context: Project): DirenvState {
return DirenvService.getInstance(context).isEnabled
}
override fun setEnabled(context: Project, value: DirenvState) {
context.service<DirenvService>().isEnabledRaw = value
}
}
class Provider: ZigProjectConfigurationProvider {
override fun create(sharedState: ZigProjectConfigurationProvider.IUserDataBridge): SubConfigurable<Project>? {
if (sharedState.getUserData(PROJECT_KEY)?.isDefault != false) {
return null
}
DirenvService.setStateFor(sharedState, DirenvState.Auto)
return ForProject(sharedState)
}
override val index: Int
get() = 100
}
}

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -22,28 +22,57 @@
package com.falsepattern.zigbrains.lsp package com.falsepattern.zigbrains.lsp
import com.falsepattern.zigbrains.direnv.emptyEnv
import com.falsepattern.zigbrains.direnv.getDirenv
import com.falsepattern.zigbrains.lsp.config.ZLSConfigProviderBase import com.falsepattern.zigbrains.lsp.config.ZLSConfigProviderBase
import com.falsepattern.zigbrains.lsp.zls.zls import com.falsepattern.zigbrains.lsp.settings.zlsSettings
import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.notification.Notification import com.intellij.notification.Notification
import com.intellij.notification.NotificationType import com.intellij.notification.NotificationType
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project import com.intellij.openapi.project.Project
import com.intellij.openapi.project.guessProjectDir import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.toNioPathOrNull import com.intellij.openapi.util.io.toNioPathOrNull
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.toNioPathOrNull import com.intellij.openapi.vfs.toNioPathOrNull
import com.redhat.devtools.lsp4ij.server.OSProcessStreamConnectionProvider import com.redhat.devtools.lsp4ij.server.OSProcessStreamConnectionProvider
import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
import kotlinx.serialization.json.encodeToStream import kotlinx.serialization.json.encodeToStream
import org.eclipse.lsp4j.InlayHint
import org.eclipse.lsp4j.jsonrpc.messages.Message
import org.eclipse.lsp4j.jsonrpc.messages.ResponseMessage
import org.eclipse.lsp4j.services.LanguageServer
import java.nio.file.Path import java.nio.file.Path
import kotlin.io.path.isExecutable import kotlin.io.path.isExecutable
import kotlin.io.path.isRegularFile import kotlin.io.path.isRegularFile
import kotlin.io.path.pathString import kotlin.io.path.pathString
class ZLSStreamConnectionProvider private constructor(private val project: Project, commandLine: GeneralCommandLine?) : OSProcessStreamConnectionProvider(commandLine) { class ZLSStreamConnectionProvider private constructor(private val project: Project, commandLine: GeneralCommandLine?) : OSProcessStreamConnectionProvider(commandLine) {
override fun handleMessage(message: Message?, languageServer: LanguageServer?, rootUri: VirtualFile?) {
if (project.zlsSettings.state.inlayHintsCompact) {
if (message is ResponseMessage) {
val res = message.result
if (res is Collection<*>) {
res.forEach { e ->
if (e is InlayHint) {
tryMutateInlayHint(e)
}
}
} else if (res is InlayHint) {
tryMutateInlayHint(res)
}
}
}
super.handleMessage(message, languageServer, rootUri)
}
companion object { companion object {
private val LOG = Logger.getInstance(ZLSStreamConnectionProvider::class.java)
private val ERROR_BLOCK = Regex("error\\{.*?}", RegexOption.DOT_MATCHES_ALL)
suspend fun create(project: Project): ZLSStreamConnectionProvider { suspend fun create(project: Project): ZLSStreamConnectionProvider {
val projectDir = project.guessProjectDir()?.toNioPathOrNull() val projectDir = project.guessProjectDir()?.toNioPathOrNull()
val commandLine = getCommand(project)?.let { GeneralCommandLine(it) }?.withWorkingDirectory(projectDir) val commandLine = getCommand(project)?.let { GeneralCommandLine(it) }?.withWorkingDirectory(projectDir)
@ -52,8 +81,30 @@ class ZLSStreamConnectionProvider private constructor(private val project: Proje
@OptIn(ExperimentalSerializationApi::class) @OptIn(ExperimentalSerializationApi::class)
suspend fun getCommand(project: Project): List<String>? { suspend fun getCommand(project: Project): List<String>? {
val zls = project.zls ?: return null val svc = project.zlsSettings
val zlsPath: Path = zls.path val state = svc.state
val zlsPath: Path = state.zlsPath.let { zlsPath ->
if (zlsPath.isEmpty()) {
val env = if (state.direnv) project.getDirenv() else emptyEnv
env.findExecutableOnPATH("zls") ?: run {
Notification(
"zigbrains-lsp",
ZLSBundle.message("notification.message.could-not-detect.content"),
NotificationType.ERROR
).notify(project)
return null
}
} else {
zlsPath.toNioPathOrNull() ?: run {
Notification(
"zigbrains-lsp",
ZLSBundle.message("notification.message.zls-exe-path-invalid.content", zlsPath),
NotificationType.ERROR
).notify(project)
return null
}
}
}
if (!zlsPath.toFile().exists()) { if (!zlsPath.toFile().exists()) {
Notification( Notification(
"zigbrains-lsp", "zigbrains-lsp",
@ -70,7 +121,7 @@ class ZLSStreamConnectionProvider private constructor(private val project: Proje
).notify(project) ).notify(project)
return null return null
} }
val configPath: Path? = "".let { configPath -> val configPath: Path? = state.zlsConfigPath.let { configPath ->
if (configPath.isNotBlank()) { if (configPath.isNotBlank()) {
configPath.toNioPathOrNull()?.let { nioPath -> configPath.toNioPathOrNull()?.let { nioPath ->
if (!nioPath.toFile().exists()) { if (!nioPath.toFile().exists()) {
@ -103,7 +154,7 @@ class ZLSStreamConnectionProvider private constructor(private val project: Proje
} }
} ?: run { } ?: run {
val config = ZLSConfigProviderBase.findEnvironment(project) val config = ZLSConfigProviderBase.findEnvironment(project)
if (config.zig_exe_path.isNullOrEmpty() || config.zig_lib_path.isNullOrEmpty()) { if (config.zigExePath.isNullOrEmpty() || config.zigLibPath.isNullOrEmpty()) {
Notification( Notification(
"zigbrains-lsp", "zigbrains-lsp",
ZLSBundle.message("notification.message.zls-config-autogen-failed.content"), ZLSBundle.message("notification.message.zls-config-autogen-failed.content"),
@ -123,6 +174,14 @@ class ZLSStreamConnectionProvider private constructor(private val project: Proje
cmd.add(configPath.pathString) cmd.add(configPath.pathString)
} }
if (state.debug) {
cmd.add("--enable-debug-log")
}
if (state.messageTrace) {
cmd.add("--enable-message-tracing")
}
if (SystemInfo.isWindows) { if (SystemInfo.isWindows) {
val sb: StringBuilder by lazy { StringBuilder() } val sb: StringBuilder by lazy { StringBuilder() }
for (i in 0..<cmd.size) { for (i in 0..<cmd.size) {
@ -135,6 +194,12 @@ class ZLSStreamConnectionProvider private constructor(private val project: Proje
} }
return cmd return cmd
} }
private fun tryMutateInlayHint(inlayHint: InlayHint) {
val str = inlayHint.label?.left ?: return
val shortened = ERROR_BLOCK.replace(str, "error{...}")
inlayHint.setLabel(shortened)
}
} }
} }

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -22,7 +22,7 @@
package com.falsepattern.zigbrains.lsp package com.falsepattern.zigbrains.lsp
import com.falsepattern.zigbrains.lsp.zls.zls import com.falsepattern.zigbrains.lsp.settings.zlsSettings
import com.falsepattern.zigbrains.shared.zigCoroutineScope import com.falsepattern.zigbrains.shared.zigCoroutineScope
import com.intellij.openapi.components.service import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project import com.intellij.openapi.project.Project
@ -39,11 +39,8 @@ import com.redhat.devtools.lsp4ij.client.features.LSPClientFeatures
import com.redhat.devtools.lsp4ij.client.features.LSPFormattingFeature import com.redhat.devtools.lsp4ij.client.features.LSPFormattingFeature
import com.redhat.devtools.lsp4ij.client.features.LSPInlayHintFeature import com.redhat.devtools.lsp4ij.client.features.LSPInlayHintFeature
import com.redhat.devtools.lsp4ij.server.StreamConnectionProvider import com.redhat.devtools.lsp4ij.server.StreamConnectionProvider
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
class ZigLanguageServerFactory: LanguageServerFactory, LanguageServerEnablementSupport { class ZigLanguageServerFactory: LanguageServerFactory, LanguageServerEnablementSupport {
override fun createConnectionProvider(project: Project): StreamConnectionProvider { override fun createConnectionProvider(project: Project): StreamConnectionProvider {
@ -68,92 +65,32 @@ class ZigLanguageServerFactory: LanguageServerFactory, LanguageServerEnablementS
} }
features.inlayHintFeature = object: LSPInlayHintFeature() { features.inlayHintFeature = object: LSPInlayHintFeature() {
override fun isEnabled(file: PsiFile): Boolean { override fun isEnabled(file: PsiFile): Boolean {
val settings = project.zls?.settings ?: return false return features.project.zlsSettings.state.inlayHints
if (!settings.inlayHints)
return false
val maxFileSizeKb = settings.inlayHintsMaxFileSizeKb
if (maxFileSizeKb == 0)
return true
val fileSizeKb = file.fileDocument.textLength / 1024
return fileSizeKb <= maxFileSizeKb
} }
} }
return features return features
} }
override fun isEnabled(project: Project) = project.zlsEnabled() override fun isEnabled(project: Project): Boolean {
return (project.getUserData(ENABLED_KEY) != false) && project.zlsSettings.validate()
}
override fun setEnabled(enabled: Boolean, project: Project) { override fun setEnabled(enabled: Boolean, project: Project) {
project.zlsEnabled(enabled) project.putUserData(ENABLED_KEY, enabled)
} }
} }
fun Project.zlsEnabled(): Boolean {
return (getUserData(ENABLED_KEY) != false) && zls?.isValid() == true
}
fun Project.zlsEnabled(value: Boolean) {
putUserData(ENABLED_KEY, value)
}
fun Project.zlsRunning(): Boolean {
if (!zlsEnabled())
return false
return lsm.isRunning
}
private val Project.lsm get() = service<LanguageServerManager>()
private val LanguageServerManager.isRunning get(): Boolean {
val status = getServerStatus("ZigBrains")
return status == ServerStatus.started || status == ServerStatus.starting
}
private val START_MUTEX = Mutex()
class ZLSStarter: LanguageServerStarter { class ZLSStarter: LanguageServerStarter {
override fun startLSP(project: Project, restart: Boolean) { override fun startLSP(project: Project, restart: Boolean) {
project.zigCoroutineScope.launch { project.zigCoroutineScope.launch {
START_MUTEX.withLock { val manager = project.service<LanguageServerManager>()
if (restart) { val status = manager.getServerStatus("ZigBrains")
project.putUserData(RESTART_KEY, Unit) if ((status == ServerStatus.started || status == ServerStatus.starting) && !restart)
} else { return@launch
project.putUserData(START_KEY, Unit) manager.start("ZigBrains")
}
}
} }
} }
} }
private suspend fun doStart(project: Project, restart: Boolean) { private val ENABLED_KEY = Key.create<Boolean>("ZLS_ENABLED")
if (!restart && project.lsm.isRunning)
return
while (!project.isDisposed && project.lsm.isRunning) {
project.lsm.stop("ZigBrains")
delay(250)
}
if (project.zls?.isValid() == true) {
delay(250)
project.lsm.start("ZigBrains")
}
}
suspend fun handleStartLSP(project: Project) = START_MUTEX.withLock {
if (project.getUserData(RESTART_KEY) != null) {
project.putUserData(RESTART_KEY, null)
project.putUserData(START_KEY, null)
doStart(project, true)
true
} else if (project.getUserData(START_KEY) != null) {
project.putUserData(START_KEY, null)
doStart(project, false)
true
} else {
false
}
}
private val ENABLED_KEY = Key.create<Boolean>("ZLS_ENABLED")
private val RESTART_KEY = Key.create<Unit>("ZLS_RESTART_REQUEST")
private val START_KEY = Key.create<Unit>("ZLS_START_REQUEST")

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -20,24 +20,20 @@
* along with ZigBrains. If not, see <https://www.gnu.org/licenses/>. * along with ZigBrains. If not, see <https://www.gnu.org/licenses/>.
*/ */
package com.falsepattern.zigbrains.project.toolchain.ui @file:Suppress("HardCodedStringLiteral")
import com.falsepattern.zigbrains.ZigBrainsBundle package com.falsepattern.zigbrains.lsp.config
import com.intellij.ui.components.JBTextField
import com.intellij.ui.dsl.builder.AlignX
import com.intellij.ui.dsl.builder.Panel
abstract class ImmutableNamedElementPanelBase<T>: ImmutableElementPanel<T> { import kotlinx.serialization.SerialName
private val nameField = JBTextField(25) import kotlinx.serialization.Serializable
import org.jetbrains.annotations.NonNls
protected var nameFieldValue: String? @Serializable
get() = nameField.text.ifBlank { null } data class ZLSConfig(
set(value) {nameField.text = value ?: ""} @SerialName("zig_exe_path") val zigExePath: @NonNls String? = null,
@SerialName("zig_lib_path") val zigLibPath: @NonNls String? = null,
override fun attach(panel: Panel): Unit = with(panel) { @SerialName("enable_build_on_save") val buildOnSave: Boolean? = null,
row(ZigBrainsBundle.message("settings.toolchain.base.name.label")) { @SerialName("build_on_save_step") val buildOnSaveStep: @NonNls String? = null,
cell(nameField).resizableColumn().align(AlignX.FILL) @SerialName("dangerous_comptime_experiments_do_not_enable") val comptimeInterpreter: Boolean? = null,
} @SerialName("highlight_global_var_declarations") val globalVarDeclarations: Boolean? = null
separator() )
}
}

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -0,0 +1,119 @@
/*
* This file is part of ZigBrains.
*
* Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* ZigBrains is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, only version 3 of the License.
*
* ZigBrains 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ZigBrains. If not, see <https://www.gnu.org/licenses/>.
*/
package com.falsepattern.zigbrains.lsp.settings
import com.falsepattern.zigbrains.direnv.emptyEnv
import com.falsepattern.zigbrains.direnv.getDirenv
import com.falsepattern.zigbrains.lsp.ZLSBundle
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.toNioPathOrNull
import com.intellij.platform.ide.progress.ModalTaskOwner
import com.intellij.platform.ide.progress.runWithModalProgressBlocking
import com.intellij.util.application
import kotlinx.coroutines.runBlocking
import java.nio.file.Path
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
import kotlin.io.path.isExecutable
import kotlin.io.path.isRegularFile
@Service(Service.Level.PROJECT)
@State(
name = "ZLSSettings",
storages = [Storage(value = "zigbrains.xml")]
)
class ZLSProjectSettingsService(val project: Project): PersistentStateComponent<ZLSSettings> {
@Volatile
private var state = ZLSSettings()
@Volatile
private var dirty = true
@Volatile
private var valid = false
private val mutex = ReentrantLock()
override fun getState(): ZLSSettings {
return state.copy()
}
fun setState(value: ZLSSettings) {
mutex.withLock {
this.state = value
dirty = true
}
}
override fun loadState(state: ZLSSettings) {
mutex.withLock {
this.state = state
dirty = true
}
}
fun isModified(otherData: ZLSSettings): Boolean {
return state != otherData
}
fun validate(): Boolean {
mutex.withLock {
if (dirty) {
val state = this.state
valid = if (application.isDispatchThread) {
runWithModalProgressBlocking(ModalTaskOwner.project(project), ZLSBundle.message("progress.title.validate")) {
doValidate(project, state)
}
} else {
runBlocking {
doValidate(project, state)
}
}
dirty = false
}
return valid
}
}
}
private suspend fun doValidate(project: Project, state: ZLSSettings): Boolean {
val zlsPath: Path = state.zlsPath.let { zlsPath ->
if (zlsPath.isEmpty()) {
val env = if (state.direnv) project.getDirenv() else emptyEnv
env.findExecutableOnPATH("zls") ?: run {
return false
}
} else {
zlsPath.toNioPathOrNull() ?: run {
return false
}
}
}
if (!zlsPath.toFile().exists()) {
return false
}
if (!zlsPath.isRegularFile() || !zlsPath.isExecutable()) {
return false
}
return true
}
val Project.zlsSettings get() = service<ZLSProjectSettingsService>()

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -20,18 +20,20 @@
* along with ZigBrains. If not, see <https://www.gnu.org/licenses/>. * along with ZigBrains. If not, see <https://www.gnu.org/licenses/>.
*/ */
package com.falsepattern.zigbrains.project.execution package com.falsepattern.zigbrains.lsp.settings
import com.intellij.execution.filters.TextConsoleBuilderImpl import org.jetbrains.annotations.NonNls
import com.intellij.execution.ui.ConsoleView
import com.intellij.openapi.project.Project
import com.intellij.terminal.TerminalExecutionConsole
class ZigConsoleBuilder(private val project: Project, private val emulateTerminal: Boolean = false): TextConsoleBuilderImpl(project) { data class ZLSSettings(
override fun createConsole(): ConsoleView { var direnv: Boolean = false,
return if (emulateTerminal) var zlsPath: @NonNls String = "",
TerminalExecutionConsole(project, null) var zlsConfigPath: @NonNls String = "",
else var debug: Boolean = false,
super.createConsole() var messageTrace: Boolean = false,
} var buildOnSave: Boolean = false,
} var buildOnSaveStep: @NonNls String = "install",
var globalVarDeclarations: Boolean = false,
var comptimeInterpreter: Boolean = false,
var inlayHints: Boolean = true,
var inlayHintsCompact: Boolean = true
)

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -20,21 +20,20 @@
* along with ZigBrains. If not, see <https://www.gnu.org/licenses/>. * along with ZigBrains. If not, see <https://www.gnu.org/licenses/>.
*/ */
package com.falsepattern.zigbrains.project.toolchain.local package com.falsepattern.zigbrains.lsp.settings
import com.falsepattern.zigbrains.project.settings.ZigProjectConfigurationProvider import com.falsepattern.zigbrains.lsp.config.ZLSConfig
import com.falsepattern.zigbrains.project.toolchain.base.ZigToolchainConfigurable import com.falsepattern.zigbrains.lsp.config.ZLSConfigProvider
import java.util.* import com.intellij.openapi.project.Project
class LocalZigToolchainConfigurable( class ZLSSettingsConfigProvider: ZLSConfigProvider {
uuid: UUID, override fun getEnvironment(project: Project, previous: ZLSConfig): ZLSConfig {
toolchain: LocalZigToolchain, val state = project.zlsSettings.state
data: ZigProjectConfigurationProvider.IUserDataBridge?, return previous.copy(
modal: Boolean buildOnSave = state.buildOnSave,
): ZigToolchainConfigurable<LocalZigToolchain>(uuid, toolchain, data, modal) { buildOnSaveStep = state.buildOnSaveStep,
override fun createPanel() = LocalZigToolchainPanel() globalVarDeclarations = state.globalVarDeclarations,
comptimeInterpreter = state.comptimeInterpreter
override fun setDisplayName(name: String?) { )
toolchain = toolchain.copy(name = name)
} }
} }

View file

@ -0,0 +1,59 @@
/*
* This file is part of ZigBrains.
*
* Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* ZigBrains is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, only version 3 of the License.
*
* ZigBrains 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ZigBrains. If not, see <https://www.gnu.org/licenses/>.
*/
package com.falsepattern.zigbrains.lsp.settings
import com.falsepattern.zigbrains.lsp.startLSP
import com.falsepattern.zigbrains.shared.SubConfigurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.ui.dsl.builder.Panel
class ZLSSettingsConfigurable(private val project: Project): SubConfigurable {
private var appSettingsComponent: ZLSSettingsPanel? = null
override fun createComponent(panel: Panel) {
appSettingsComponent = ZLSSettingsPanel(project).apply { attach(panel) }.also { Disposer.register(this, it) }
}
override fun isModified(): Boolean {
val data = appSettingsComponent?.data ?: return false
return project.zlsSettings.state != data
}
override fun apply() {
val data = appSettingsComponent?.data ?: return
val settings = project.zlsSettings
val reloadZLS = settings.isModified(data)
settings.state = data
if (reloadZLS) {
startLSP(project, true)
}
}
override fun reset() {
appSettingsComponent?.data = project.zlsSettings.state
}
override fun dispose() {
appSettingsComponent = null
}
}

View file

@ -0,0 +1,146 @@
/*
* This file is part of ZigBrains.
*
* Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* ZigBrains is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, only version 3 of the License.
*
* ZigBrains 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ZigBrains. If not, see <https://www.gnu.org/licenses/>.
*/
package com.falsepattern.zigbrains.lsp.settings
import com.falsepattern.zigbrains.direnv.DirenvCmd
import com.falsepattern.zigbrains.direnv.Env
import com.falsepattern.zigbrains.direnv.emptyEnv
import com.falsepattern.zigbrains.direnv.getDirenv
import com.falsepattern.zigbrains.lsp.ZLSBundle
import com.falsepattern.zigbrains.shared.coroutine.launchWithEDT
import com.falsepattern.zigbrains.shared.zigCoroutineScope
import com.intellij.openapi.Disposable
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.platform.ide.progress.ModalTaskOwner
import com.intellij.platform.ide.progress.TaskCancellation
import com.intellij.platform.ide.progress.withModalProgress
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.fields.ExtendableTextField
import com.intellij.ui.components.textFieldWithBrowseButton
import com.intellij.ui.dsl.builder.AlignX
import com.intellij.ui.dsl.builder.Panel
import kotlin.io.path.pathString
class ZLSSettingsPanel(private val project: Project?) : Disposable {
private val zlsPath = textFieldWithBrowseButton(
project,
FileChooserDescriptorFactory.createSingleFileDescriptor().withTitle(ZLSBundle.message("settings.zls-path.browse.title")),
).also { Disposer.register(this, it) }
private val zlsConfigPath = textFieldWithBrowseButton(
project,
FileChooserDescriptorFactory.createSingleFileDescriptor().withTitle(ZLSBundle.message("settings.zls-config-path.browse.title"))
).also { Disposer.register(this, it) }
private val buildOnSave = JBCheckBox().apply { toolTipText = ZLSBundle.message("settings.build-on-save.tooltip") }
private val buildOnSaveStep = ExtendableTextField().apply { toolTipText = ZLSBundle.message("settings.build-on-save-step.tooltip") }
private val globalVarDeclarations = JBCheckBox()
private val comptimeInterpreter = JBCheckBox()
private val inlayHints = JBCheckBox()
private val inlayHintsCompact = JBCheckBox().apply { toolTipText = ZLSBundle.message("settings.inlay-hints-compact.tooltip") }
private val messageTrace = JBCheckBox()
private val debug = JBCheckBox()
private val direnv = JBCheckBox(ZLSBundle.message("settings.zls-path.use-direnv.label")).apply { addActionListener {
dispatchAutodetect(true)
} }
fun attach(panel: Panel) = with(panel) {
group(ZLSBundle.message("settings.group.title")) {
row(ZLSBundle.message("settings.zls-path.label")) {
cell(zlsPath).resizableColumn().align(AlignX.FILL)
if (DirenvCmd.direnvInstalled() && project?.isDefault == false) {
cell(direnv)
}
}
row(ZLSBundle.message("settings.zls-config-path.label")) { cell(zlsConfigPath).align(AlignX.FILL) }
row(ZLSBundle.message("settings.inlay-hints.label")) { cell(inlayHints) }
row(ZLSBundle.message("settings.inlay-hints-compact.label")) { cell(inlayHintsCompact) }
row(ZLSBundle.message("settings.build-on-save.label")) { cell(buildOnSave) }
row(ZLSBundle.message("settings.build-on-save-step.label")) { cell(buildOnSaveStep).resizableColumn().align(AlignX.FILL) }
row(ZLSBundle.message("settings.global-var-declarations.label")) { cell(globalVarDeclarations) }
row(ZLSBundle.message("settings.comptime-interpreter.label")) { cell(comptimeInterpreter) }
}
group(ZLSBundle.message("dev-settings.group.title")) {
row(ZLSBundle.message("dev-settings.debug.label")) { cell(debug) }
row(ZLSBundle.message("dev-settings.message-trace.label")) { cell(messageTrace) }
}
dispatchAutodetect(false)
}
var data
get() = ZLSSettings(
direnv.isSelected,
zlsPath.text,
zlsConfigPath.text,
debug.isSelected,
messageTrace.isSelected,
buildOnSave.isSelected,
buildOnSaveStep.text,
globalVarDeclarations.isSelected,
comptimeInterpreter.isSelected,
inlayHints.isSelected,
inlayHintsCompact.isSelected
)
set(value) {
direnv.isSelected = value.direnv
zlsPath.text = value.zlsPath
zlsConfigPath.text = value.zlsConfigPath
debug.isSelected = value.debug
messageTrace.isSelected = value.messageTrace
buildOnSave.isSelected = value.buildOnSave
buildOnSaveStep.text = value.buildOnSaveStep
globalVarDeclarations.isSelected = value.globalVarDeclarations
comptimeInterpreter.isSelected = value.comptimeInterpreter
inlayHints.isSelected = value.inlayHints
inlayHintsCompact.isSelected = value.inlayHintsCompact
}
private fun dispatchAutodetect(force: Boolean) {
project.zigCoroutineScope.launchWithEDT {
withModalProgress(ModalTaskOwner.component(zlsPath), "Detecting ZLS...", TaskCancellation.cancellable()) {
autodetect(force)
}
}
}
suspend fun autodetect(force: Boolean) {
if (force || zlsPath.text.isBlank()) {
getDirenv().findExecutableOnPATH("zls")?.let {
if (force || zlsPath.text.isBlank()) {
zlsPath.text = it.pathString
}
}
}
}
override fun dispose() {
}
private suspend fun getDirenv(): Env {
if (DirenvCmd.direnvInstalled() && project?.isDefault == false && direnv.isSelected)
return project.getDirenv()
return emptyEnv
}
}

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,90 +0,0 @@
/*
* This file is part of ZigBrains.
*
* Copyright (C) 2023-2025 FalsePattern
* All Rights Reserved
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* ZigBrains is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, only version 3 of the License.
*
* ZigBrains 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ZigBrains. If not, see <https://www.gnu.org/licenses/>.
*/
package com.falsepattern.zigbrains.project.actions
import com.falsepattern.zigbrains.project.execution.base.ZigExecConfig
import com.falsepattern.zigbrains.project.execution.run.ZigConfigProducerRun
import com.falsepattern.zigbrains.project.execution.run.ZigExecConfigRun
import com.falsepattern.zigbrains.project.execution.test.ZigConfigProducerTest
import com.falsepattern.zigbrains.project.execution.test.ZigExecConfigTest
import com.intellij.execution.ExecutionManager
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.actions.RunConfigurationProducer
import com.intellij.execution.executors.DefaultRunExecutor
import com.intellij.execution.runners.ExecutionEnvironmentBuilder
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.project.DumbAwareAction
class ZigRunFileAction: DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
val file = e.getData(CommonDataKeys.PSI_FILE) ?: return
val config = getConfig(e) ?: return
val project = file.project
val builder = ExecutionEnvironmentBuilder.createOrNull(DefaultRunExecutor.getRunExecutorInstance(), config) ?: return
ExecutionManager.getInstance(project).restartRunProfile(builder.build())
}
private fun getConfig(e: AnActionEvent): ZigExecConfig<*>? {
val context = ConfigurationContext.getFromContext(e.dataContext, e.place)
return getRunConfiguration(context) ?: getTestConfiguration(context)
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = getConfig(e) != null
}
private fun getRunConfiguration(context: ConfigurationContext): ZigExecConfigRun? {
try {
val configProducer = RunConfigurationProducer.getInstance(ZigConfigProducerRun::class.java)
val settings = configProducer.findExistingConfiguration(context)
if (settings != null) {
return settings.configuration as? ZigExecConfigRun
}
val fromContext = configProducer.createConfigurationFromContext(context)
if (fromContext != null) {
return fromContext.configuration as? ZigExecConfigRun
}
} catch (_: NullPointerException) {}
return null
}
private fun getTestConfiguration(context: ConfigurationContext): ZigExecConfigTest? {
try {
val configProducer = RunConfigurationProducer.getInstance(ZigConfigProducerTest::class.java)
val settings = configProducer.findExistingConfiguration(context)
if (settings != null) {
return settings.configuration as? ZigExecConfigTest
}
val fromContext = configProducer.createConfigurationFromContext(context)
if (fromContext != null) {
return fromContext.configuration as? ZigExecConfigTest
}
} catch (_: NullPointerException) {}
return null
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
}

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -24,17 +24,20 @@ package com.falsepattern.zigbrains.project.execution.base
import com.falsepattern.zigbrains.ZigBrainsBundle import com.falsepattern.zigbrains.ZigBrainsBundle
import com.falsepattern.zigbrains.project.execution.base.ZigConfigurable.ZigConfigModule import com.falsepattern.zigbrains.project.execution.base.ZigConfigurable.ZigConfigModule
import com.falsepattern.zigbrains.project.settings.zigProjectSettings
import com.falsepattern.zigbrains.shared.cli.translateCommandline import com.falsepattern.zigbrains.shared.cli.translateCommandline
import com.falsepattern.zigbrains.shared.element.* import com.falsepattern.zigbrains.shared.element.*
import com.intellij.openapi.Disposable import com.intellij.openapi.Disposable
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.options.SettingsEditor import com.intellij.openapi.options.SettingsEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.TextBrowseFolderListener
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.toNioPathOrNull import com.intellij.openapi.util.io.toNioPathOrNull
import com.intellij.ui.components.JBCheckBox import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBTextField import com.intellij.ui.components.JBTextField
import com.intellij.ui.components.textFieldWithBrowseButton
import com.intellij.ui.dsl.builder.AlignX import com.intellij.ui.dsl.builder.AlignX
import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.dsl.builder.Panel
import com.intellij.ui.dsl.builder.panel import com.intellij.ui.dsl.builder.panel
@ -158,10 +161,12 @@ class WorkDirectoryConfigurable(@Transient override val serializedName: String)
} }
class WorkDirectoryConfigModule(private val serializedName: String) : PathConfigModule<WorkDirectoryConfigurable>() { class WorkDirectoryConfigModule(private val serializedName: String) : PathConfigModule<WorkDirectoryConfigurable>() {
private val field = textFieldWithBrowseButton( private val field = TextFieldWithBrowseButton(
null, TextBrowseFolderListener(
FileChooserDescriptorFactory.createSingleFolderDescriptor().withTitle(ZigBrainsBundle.message("dialog.title.working-directory")) FileChooserDescriptorFactory.createSingleFolderDescriptor().withTitle(ZigBrainsBundle.message("dialog.title.working-directory"))
).also { Disposer.register(this, it) } ),
this
)
override var stringValue by field::text override var stringValue by field::text
@ -196,9 +201,9 @@ class FilePathConfigurable(
} }
class FilePathConfigModule(private val serializedName: String, @Nls private val label: String) : PathConfigModule<FilePathConfigurable>() { class FilePathConfigModule(private val serializedName: String, @Nls private val label: String) : PathConfigModule<FilePathConfigurable>() {
private val field = textFieldWithBrowseButton( private val field = TextFieldWithBrowseButton(
null, TextBrowseFolderListener(FileChooserDescriptorFactory.createSingleFileDescriptor()),
FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(), this
) )
override var stringValue by field::text override var stringValue by field::text
@ -269,6 +274,18 @@ open class CheckboxConfigurable(
} }
} }
class ColoredConfigurable(serializedName: String): CheckboxConfigurable(serializedName, ZigBrainsBundle.message("exec.option.label.colored-terminal"), true) {
override fun clone(): ColoredConfigurable {
return super.clone() as ColoredConfigurable
}
}
class DirenvConfigurable(serializedName: String, project: Project): CheckboxConfigurable(serializedName, ZigBrainsBundle.message("exec.option.label.direnv"), project.zigProjectSettings.state.direnv) {
override fun clone(): DirenvConfigurable {
return super.clone() as DirenvConfigurable
}
}
class OptimizationConfigurable( class OptimizationConfigurable(
@Transient private val serializedName: String, @Transient private val serializedName: String,
var level: OptimizationLevel = OptimizationLevel.Debug, var level: OptimizationLevel = OptimizationLevel.Debug,
@ -330,18 +347,14 @@ class ArgsConfigurable(
@Transient private val serializedName: String, @Transient private val serializedName: String,
@Transient @Nls private val guiName: String @Transient @Nls private val guiName: String
) : ZigConfigurable<ArgsConfigurable>, Cloneable { ) : ZigConfigurable<ArgsConfigurable>, Cloneable {
var args: String = "" var args: List<String> = emptyList()
override fun readExternal(element: Element) { override fun readExternal(element: Element) {
args = element.readString(serializedName) ?: element.readStrings(serializedName)?.joinToString(separator = " ") { if (it.contains(' ')) "\"$it\"" else it } ?: "" args = element.readStrings(serializedName) ?: return
}
fun argsSplit(): List<String> {
return translateCommandline(args)
} }
override fun writeExternal(element: Element) { override fun writeExternal(element: Element) {
element.writeString(serializedName, args) element.writeStrings(serializedName, args)
} }
override fun createEditor(): ZigConfigModule<ArgsConfigurable> { override fun createEditor(): ZigConfigModule<ArgsConfigurable> {
@ -363,12 +376,12 @@ class ArgsConfigurable(
} }
override fun apply(configurable: ArgsConfigurable): Boolean { override fun apply(configurable: ArgsConfigurable): Boolean {
configurable.args = argsField.text ?: "" configurable.args = translateCommandline(argsField.text)
return true return true
} }
override fun reset(configurable: ArgsConfigurable) { override fun reset(configurable: ArgsConfigurable) {
argsField.text = configurable.args argsField.text = configurable.args.joinToString(separator = " ")
} }
override fun construct(p: Panel): Unit = with(p) { override fun construct(p: Panel): Unit = with(p) {

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -41,7 +41,7 @@ abstract class ZigConfigProducer<T: ZigExecConfig<T>>: LazyRunConfigurationProdu
val psiFile = element.containingFile as? ZigFile ?: return false val psiFile = element.containingFile as? ZigFile ?: return false
val theFile = psiFile.virtualFile ?: return false val theFile = psiFile.virtualFile ?: return false
val filePath = theFile.toNioPathOrNull() ?: return false val filePath = theFile.toNioPathOrNull() ?: return false
return setupConfigurationFromContext(configuration, element, psiFile, filePath, theFile) return setupConfigurationFromContext(configuration, element, filePath, theFile)
} }
override fun isConfigurationFromContext(configuration: T, context: ConfigurationContext): Boolean { override fun isConfigurationFromContext(configuration: T, context: ConfigurationContext): Boolean {
@ -49,7 +49,7 @@ abstract class ZigConfigProducer<T: ZigExecConfig<T>>: LazyRunConfigurationProdu
val psiFile = element.containingFile as? ZigFile ?: return false val psiFile = element.containingFile as? ZigFile ?: return false
val theFile = psiFile.virtualFile ?: return false val theFile = psiFile.virtualFile ?: return false
val filePath = theFile.toNioPathOrNull() ?: return false val filePath = theFile.toNioPathOrNull() ?: return false
return isConfigurationFromContext(configuration, element, psiFile, filePath, theFile) return isConfigurationFromContext(configuration, element, filePath, theFile)
} }
/* /*
@ -78,7 +78,7 @@ abstract class ZigConfigProducer<T: ZigExecConfig<T>>: LazyRunConfigurationProdu
} }
*/ */
protected abstract fun setupConfigurationFromContext(configuration: T, element: PsiElement, psiFile: ZigFile, filePath: Path, theFile: VirtualFile): Boolean protected abstract fun setupConfigurationFromContext(configuration: T, element: PsiElement, filePath: Path, theFile: VirtualFile): Boolean
protected abstract fun isConfigurationFromContext(configuration: T, element: PsiElement, psiFile: ZigFile, filePath: Path, theFile: VirtualFile): Boolean protected abstract fun isConfigurationFromContext(configuration: T, element: PsiElement, filePath: Path, theFile: VirtualFile): Boolean
abstract override fun shouldReplace(self: ConfigurationFromContext, other: ConfigurationFromContext): Boolean abstract override fun shouldReplace(self: ConfigurationFromContext, other: ConfigurationFromContext): Boolean
} }

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -22,7 +22,8 @@
package com.falsepattern.zigbrains.project.execution.base package com.falsepattern.zigbrains.project.execution.base
import com.falsepattern.zigbrains.direnv.DirenvService import com.falsepattern.zigbrains.ZigBrainsBundle
import com.falsepattern.zigbrains.direnv.DirenvCmd
import com.intellij.execution.ExecutionException import com.intellij.execution.ExecutionException
import com.intellij.execution.Executor import com.intellij.execution.Executor
import com.intellij.execution.configurations.ConfigurationFactory import com.intellij.execution.configurations.ConfigurationFactory
@ -41,6 +42,10 @@ import org.jetbrains.annotations.Nls
abstract class ZigExecConfig<T: ZigExecConfig<T>>(project: Project, factory: ConfigurationFactory, @Nls name: String): LocatableConfigurationBase<ZigProfileState<T>>(project, factory, name) { abstract class ZigExecConfig<T: ZigExecConfig<T>>(project: Project, factory: ConfigurationFactory, @Nls name: String): LocatableConfigurationBase<ZigProfileState<T>>(project, factory, name) {
var workingDirectory = WorkDirectoryConfigurable("workingDirectory").apply { path = project.guessProjectDir()?.toNioPathOrNull() } var workingDirectory = WorkDirectoryConfigurable("workingDirectory").apply { path = project.guessProjectDir()?.toNioPathOrNull() }
private set private set
var pty = CheckboxConfigurable("pty", ZigBrainsBundle.message("exec.option.label.emulate-terminal"), false)
private set
var direnv = DirenvConfigurable("direnv", project)
private set
abstract val suggestedName: @ActionText String abstract val suggestedName: @ActionText String
@Throws(ExecutionException::class) @Throws(ExecutionException::class)
@ -63,19 +68,24 @@ abstract class ZigExecConfig<T: ZigExecConfig<T>>(project: Project, factory: Con
suspend fun patchCommandLine(commandLine: GeneralCommandLine): GeneralCommandLine { suspend fun patchCommandLine(commandLine: GeneralCommandLine): GeneralCommandLine {
val direnv = DirenvService.getInstance(project) if (direnv.value) {
if (direnv.isEnabled.isEnabled(project)) { commandLine.withEnvironment(DirenvCmd.importDirenv(project).env)
commandLine.withEnvironment(direnv.import().env)
} }
return commandLine return commandLine
} }
fun emulateTerminal(): Boolean {
return pty.value
}
override fun clone(): T { override fun clone(): T {
val myClone = super.clone() as ZigExecConfig<*> val myClone = super.clone() as ZigExecConfig<*>
myClone.workingDirectory = workingDirectory.clone() myClone.workingDirectory = workingDirectory.clone()
myClone.pty = pty.clone()
myClone.direnv = direnv.clone()
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
return myClone as T return myClone as T
} }
open fun getConfigurables(): List<ZigConfigurable<*>> = listOf(workingDirectory) open fun getConfigurables(): List<ZigConfigurable<*>> = listOf(workingDirectory, pty, direnv)
} }

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -23,16 +23,18 @@
package com.falsepattern.zigbrains.project.execution.base package com.falsepattern.zigbrains.project.execution.base
import com.falsepattern.zigbrains.ZigBrainsBundle import com.falsepattern.zigbrains.ZigBrainsBundle
import com.falsepattern.zigbrains.project.execution.ZigConsoleBuilder import com.falsepattern.zigbrains.project.run.ZigProcessHandler
import com.falsepattern.zigbrains.project.toolchain.ZigToolchainService import com.falsepattern.zigbrains.project.settings.zigProjectSettings
import com.falsepattern.zigbrains.project.toolchain.base.ZigToolchain import com.falsepattern.zigbrains.project.toolchain.AbstractZigToolchain
import com.falsepattern.zigbrains.shared.cli.startIPCAwareProcess
import com.falsepattern.zigbrains.shared.coroutine.runModalOrBlocking import com.falsepattern.zigbrains.shared.coroutine.runModalOrBlocking
import com.intellij.build.BuildTextConsoleView
import com.intellij.execution.DefaultExecutionResult
import com.intellij.execution.ExecutionException import com.intellij.execution.ExecutionException
import com.intellij.execution.configurations.CommandLineState import com.intellij.execution.configurations.CommandLineState
import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.configurations.PtyCommandLine import com.intellij.execution.configurations.PtyCommandLine
import com.intellij.execution.process.ProcessHandler import com.intellij.execution.process.ProcessHandler
import com.intellij.execution.process.ProcessTerminatedListener
import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.platform.ide.progress.ModalTaskOwner import com.intellij.platform.ide.progress.ModalTaskOwner
import kotlin.io.path.pathString import kotlin.io.path.pathString
@ -42,10 +44,6 @@ abstract class ZigProfileState<T: ZigExecConfig<T>> (
val configuration: T val configuration: T
): CommandLineState(environment) { ): CommandLineState(environment) {
init {
consoleBuilder = ZigConsoleBuilder(environment.project, true)
}
@Throws(ExecutionException::class) @Throws(ExecutionException::class)
override fun startProcess(): ProcessHandler { override fun startProcess(): ProcessHandler {
return runModalOrBlocking({ModalTaskOwner.project(environment.project)}, {"ZigProfileState.startProcess"}) { return runModalOrBlocking({ModalTaskOwner.project(environment.project)}, {"ZigProfileState.startProcess"}) {
@ -55,20 +53,37 @@ abstract class ZigProfileState<T: ZigExecConfig<T>> (
@Throws(ExecutionException::class) @Throws(ExecutionException::class)
suspend fun startProcessSuspend(): ProcessHandler { suspend fun startProcessSuspend(): ProcessHandler {
val toolchain = ZigToolchainService.getInstance(environment.project).toolchain ?: throw ExecutionException(ZigBrainsBundle.message("exception.zig-profile-state.start-process.no-toolchain")) val toolchain = environment.project.zigProjectSettings.state.toolchain ?: throw ExecutionException(ZigBrainsBundle.message("exception.zig-profile-state.start-process.no-toolchain"))
return getCommandLine(toolchain, false).startIPCAwareProcess(environment.project, emulateTerminal = true) return ZigProcessHandler(getCommandLine(toolchain, false))
} }
@Throws(ExecutionException::class) @Throws(ExecutionException::class)
open suspend fun getCommandLine(toolchain: ZigToolchain, debug: Boolean): GeneralCommandLine { open suspend fun getCommandLine(toolchain: AbstractZigToolchain, debug: Boolean): GeneralCommandLine {
val workingDir = configuration.workingDirectory val workingDir = configuration.workingDirectory
val zigExePath = toolchain.zig.path() val zigExePath = toolchain.zig.path()
val cli = PtyCommandLine().withConsoleMode(false) // TODO remove this check once JetBrains implements colored terminal in the debugger
cli.withExePath(zigExePath.pathString) // https://youtrack.jetbrains.com/issue/CPP-11622/ANSI-color-codes-not-honored-in-Debug-Run-Configuration-output-window
val cli = if (configuration.emulateTerminal() && !debug) PtyCommandLine().withConsoleMode(true).withParentEnvironmentType(GeneralCommandLine.ParentEnvironmentType.CONSOLE) else GeneralCommandLine()
cli.exePath = zigExePath.pathString
workingDir.path?.let { cli.withWorkingDirectory(it) } workingDir.path?.let { cli.withWorkingDirectory(it) }
cli.withCharset(Charsets.UTF_8) cli.charset = Charsets.UTF_8
cli.addParameters(configuration.buildCommandLineArgs(debug)) cli.addParameters(configuration.buildCommandLineArgs(debug))
return configuration.patchCommandLine(cli) return configuration.patchCommandLine(cli)
} }
}
@Throws(ExecutionException::class)
fun executeCommandLine(commandLine: GeneralCommandLine, environment: ExecutionEnvironment): DefaultExecutionResult {
val handler = startProcess(commandLine)
val console = BuildTextConsoleView(environment.project, false, emptyList())
console.attachToProcess(handler)
return DefaultExecutionResult(console, handler)
}
@Throws(ExecutionException::class)
fun startProcess(commandLine: GeneralCommandLine): ProcessHandler {
val handler = ZigProcessHandler(commandLine)
ProcessTerminatedListener.attach(handler)
return handler
} }

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,56 +0,0 @@
/*
* This file is part of ZigBrains.
*
* Copyright (C) 2023-2025 FalsePattern
* All Rights Reserved
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* ZigBrains is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, only version 3 of the License.
*
* ZigBrains 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ZigBrains. If not, see <https://www.gnu.org/licenses/>.
*/
package com.falsepattern.zigbrains.project.execution.base
import com.falsepattern.zigbrains.zig.psi.ZigContainerMembers
import com.falsepattern.zigbrains.zig.psi.ZigFile
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.isFile
import com.intellij.psi.util.childrenOfType
fun ZigFile.hasMainFunction(): Boolean {
val members = childrenOfType<ZigContainerMembers>().firstOrNull() ?: return false
return members.containerDeclarationList.any { it.decl?.fnProto?.identifier?.textMatches("main") == true }
}
fun ZigFile.hasTests(): Boolean {
val members = childrenOfType<ZigContainerMembers>().firstOrNull() ?: return false
return members.containerDeclarationList.any { it.testDecl != null }
}
fun VirtualFile.findBuildZig(): VirtualFile? {
var parent = this.parent
while (parent != null) {
parent.children.forEach {
if (it.isFile && it.name == "build.zig") {
return it
}
}
parent = parent.parent
}
return null
}
fun VirtualFile.isBuildZig(): Boolean {
return name == "build.zig"
}

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -24,16 +24,11 @@ package com.falsepattern.zigbrains.project.execution.build
import com.falsepattern.zigbrains.ZigBrainsBundle import com.falsepattern.zigbrains.ZigBrainsBundle
import com.falsepattern.zigbrains.project.execution.base.ZigConfigProducer import com.falsepattern.zigbrains.project.execution.base.ZigConfigProducer
import com.falsepattern.zigbrains.project.execution.base.findBuildZig
import com.falsepattern.zigbrains.project.execution.base.isBuildZig
import com.falsepattern.zigbrains.project.execution.firstConfigFactory import com.falsepattern.zigbrains.project.execution.firstConfigFactory
import com.falsepattern.zigbrains.zig.psi.ZigFile
import com.falsepattern.zigbrains.zig.psi.ZigTypes
import com.intellij.execution.actions.ConfigurationFromContext import com.intellij.execution.actions.ConfigurationFromContext
import com.intellij.execution.configurations.ConfigurationFactory import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement import com.intellij.psi.PsiElement
import com.intellij.psi.util.elementType
import java.nio.file.Path import java.nio.file.Path
class ZigConfigProducerBuild: ZigConfigProducer<ZigExecConfigBuild>() { class ZigConfigProducerBuild: ZigConfigProducer<ZigExecConfigBuild>() {
@ -41,43 +36,21 @@ class ZigConfigProducerBuild: ZigConfigProducer<ZigExecConfigBuild>() {
return firstConfigFactory<ZigConfigTypeBuild>() return firstConfigFactory<ZigConfigTypeBuild>()
} }
override fun setupConfigurationFromContext(configuration: ZigExecConfigBuild, element: PsiElement, psiFile: ZigFile, filePath: Path, theFile: VirtualFile): Boolean { override fun setupConfigurationFromContext(configuration: ZigExecConfigBuild, element: PsiElement, filePath: Path, theFile: VirtualFile): Boolean {
if (theFile.isBuildZig()) { if (LINE_MARKER.elementMatches(element)) {
configuration.name = ZigBrainsBundle.message("configuration.build.marker-run") configuration.name = ZigBrainsBundle.message("configuration.build.marker-name")
configuration.buildSteps.args = "run"
configuration.debugBuildSteps.args = "install"
return true
}
val buildZig = theFile.findBuildZig() ?: return false
configuration.workingDirectory.path = buildZig.parent.toNioPath()
if (element.elementType == ZigTypes.KEYWORD_TEST) {
configuration.name = ZigBrainsBundle.message("configuration.build.marker-test")
configuration.buildSteps.args = "test"
configuration.debugBuildSteps.args = "install_test"
return true
} else {
configuration.name = ZigBrainsBundle.message("configuration.build.marker-run")
configuration.buildSteps.args = "run"
configuration.debugBuildSteps.args = "install"
return true return true
} }
return false
} }
override fun isConfigurationFromContext(configuration: ZigExecConfigBuild, element: PsiElement, psiFile: ZigFile, filePath: Path, theFile: VirtualFile): Boolean { override fun isConfigurationFromContext(configuration: ZigExecConfigBuild, element: PsiElement, filePath: Path, theFile: VirtualFile): Boolean {
val dir = configuration.workingDirectory.path ?: return false return filePath.parent == (configuration.workingDirectory.path ?: return false)
if (theFile.isBuildZig()) {
return filePath.parent == dir
} else {
if (element.elementType == ZigTypes.KEYWORD_TEST) {
if (configuration.buildSteps.args != "test")
return false
}
val buildZig = theFile.findBuildZig() ?: return false
return buildZig.parent.toNioPath() == dir
}
} }
override fun shouldReplace(self: ConfigurationFromContext, other: ConfigurationFromContext): Boolean { override fun shouldReplace(self: ConfigurationFromContext, other: ConfigurationFromContext): Boolean {
return self.configurationType is ZigConfigTypeBuild return self.configurationType is ZigConfigTypeBuild
} }
} }
private val LINE_MARKER = ZigLineMarkerBuild()

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included
@ -25,6 +25,7 @@ package com.falsepattern.zigbrains.project.execution.build
import com.falsepattern.zigbrains.ZigBrainsBundle import com.falsepattern.zigbrains.ZigBrainsBundle
import com.falsepattern.zigbrains.project.execution.base.* import com.falsepattern.zigbrains.project.execution.base.*
import com.falsepattern.zigbrains.shared.ZBFeatures import com.falsepattern.zigbrains.shared.ZBFeatures
import com.falsepattern.zigbrains.shared.cli.coloredCliFlags
import com.intellij.execution.ExecutionException import com.intellij.execution.ExecutionException
import com.intellij.execution.Executor import com.intellij.execution.Executor
import com.intellij.execution.configurations.ConfigurationFactory import com.intellij.execution.configurations.ConfigurationFactory
@ -36,9 +37,7 @@ class ZigExecConfigBuild(project: Project, factory: ConfigurationFactory): ZigEx
private set private set
var extraArgs = ArgsConfigurable("compilerArgs", ZigBrainsBundle.message("exec.option.label.build.args")) var extraArgs = ArgsConfigurable("compilerArgs", ZigBrainsBundle.message("exec.option.label.build.args"))
private set private set
var debugBuildSteps = ArgsConfigurable("debugBuildSteps", ZigBrainsBundle.message("exec.option.label.build.steps-debug")) var colored = ColoredConfigurable("colored")
private set
var debugExtraArgs = ArgsConfigurable("debugCompilerArgs", ZigBrainsBundle.message("exec.option.label.build.args-debug"))
private set private set
var exePath = FilePathConfigurable("exePath", ZigBrainsBundle.message("exec.option.label.build.exe-path-debug")) var exePath = FilePathConfigurable("exePath", ZigBrainsBundle.message("exec.option.label.build.exe-path-debug"))
private set private set
@ -49,9 +48,22 @@ class ZigExecConfigBuild(project: Project, factory: ConfigurationFactory): ZigEx
override suspend fun buildCommandLineArgs(debug: Boolean): List<String> { override suspend fun buildCommandLineArgs(debug: Boolean): List<String> {
val result = ArrayList<String>() val result = ArrayList<String>()
result.add("build") result.add("build")
val steps = if (debug) debugBuildSteps.argsSplit() else buildSteps.argsSplit() val steps = if (debug) {
val truncatedSteps = ArrayList<String>()
for (step in buildSteps.args) {
if (step == "run")
continue
if (step == "test")
throw ExecutionException(ZigBrainsBundle.message("exception.zig-build.debug.test-not-supported"))
truncatedSteps.add(step)
}
truncatedSteps
} else buildSteps.args
result.addAll(steps) result.addAll(steps)
result.addAll(if (debug) debugExtraArgs.argsSplit() else extraArgs.argsSplit()) result.addAll(coloredCliFlags(colored.value, debug))
result.addAll(extraArgs.args)
return result return result
} }
@ -62,15 +74,16 @@ class ZigExecConfigBuild(project: Project, factory: ConfigurationFactory): ZigEx
val clone = super.clone() val clone = super.clone()
clone.buildSteps = buildSteps.clone() clone.buildSteps = buildSteps.clone()
clone.exeArgs = exeArgs.clone() clone.exeArgs = exeArgs.clone()
clone.colored = colored.clone()
clone.exePath = exePath.clone() clone.exePath = exePath.clone()
clone.exeArgs = exeArgs.clone() clone.exeArgs = exeArgs.clone()
return clone return clone
} }
override fun getConfigurables(): List<ZigConfigurable<*>> { override fun getConfigurables(): List<ZigConfigurable<*>> {
val baseCfg = super.getConfigurables() + listOf(buildSteps, extraArgs) val baseCfg = super.getConfigurables() + listOf(buildSteps, extraArgs, colored)
return if (ZBFeatures.debug()) { return if (ZBFeatures.debug()) {
baseCfg + listOf(debugBuildSteps, debugExtraArgs, exePath, exeArgs) baseCfg + listOf(exePath, exeArgs)
} else { } else {
baseCfg baseCfg
} }

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

View file

@ -1,7 +1,7 @@
/* /*
* This file is part of ZigBrains. * This file is part of ZigBrains.
* *
* Copyright (C) 2023-2025 FalsePattern * Copyright (C) 2023-2024 FalsePattern
* All Rights Reserved * All Rights Reserved
* *
* The above copyright notice and this permission notice shall be included * The above copyright notice and this permission notice shall be included

Some files were not shown because too many files have changed in this diff Show more