Skip to content

Commit

Permalink
Progress
Browse files Browse the repository at this point in the history
  • Loading branch information
Nimaoth committed Oct 20, 2024
1 parent 3668ae2 commit 55e2a31
Show file tree
Hide file tree
Showing 14 changed files with 84 additions and 153 deletions.
Binary file modified config/wasm/harpoon.wasm
Binary file not shown.
Binary file modified config/wasm/keybindings_plugin.wasm
Binary file not shown.
Binary file modified config/wasm/vscode_config_plugin.wasm
Binary file not shown.
10 changes: 0 additions & 10 deletions scripting/editor_api_wasm.nim
Original file line number Diff line number Diff line change
Expand Up @@ -229,16 +229,6 @@ proc addScriptAction*(name: string; docs: string = "";
argsJsonString.cstring)


proc editor_openLocalWorkspace_void_App_string_wasm(arg: cstring): cstring {.
importc.}
proc openLocalWorkspace*(path: string) {.gcsafe, raises: [].} =
var argsJson = newJArray()
argsJson.add path.toJson()
let argsJsonString = $argsJson
let res {.used.} = editor_openLocalWorkspace_void_App_string_wasm(
argsJsonString.cstring)


proc editor_quit_void_App_wasm(arg: cstring): cstring {.importc.}
proc quit*() {.gcsafe, raises: [].} =
var argsJson = newJArray()
Expand Down
67 changes: 21 additions & 46 deletions src/app.nim
Original file line number Diff line number Diff line change
Expand Up @@ -105,14 +105,13 @@ type
registers: Registers
vfsService*: VFSService

workspace*: Workspace
vfs*: VFS

logNextFrameTime*: bool = false
disableLogFrameTime*: bool = true
logBuffer = ""

workspace*: Workspace

wasmScriptContext*: ScriptContextWasm
initializeCalled: bool

Expand Down Expand Up @@ -182,8 +181,6 @@ proc handleKeyRelease*(self: App, input: int64, modifiers: Modifiers)
proc handleRune*(self: App, input: int64, modifiers: Modifiers)
proc handleDropFile*(self: App, path, content: string)

proc setWorkspaceFolder(self: App, workspace: Workspace): Future[bool]

proc handleAction(self: App, action: string, arg: string, record: bool): Option[JsonNode]

import text/[text_editor, text_document]
Expand Down Expand Up @@ -683,6 +680,7 @@ proc newApp*(backend: api.Backend, platform: Platform, services: Services, optio
self.plugins = services.getService(PluginService).get
self.registers = services.getService(Registers).get
self.vfsService = services.getService(VFSService).get
self.workspace = services.getService(Workspace).get
self.vfs = self.vfsService.vfs

self.platform.fontSize = 16
Expand Down Expand Up @@ -759,9 +757,9 @@ proc newApp*(backend: api.Backend, platform: Platform, services: Services, optio
var state = EditorState()
if not options.dontRestoreConfig:
if options.sessionOverride.getSome(session):
self.sessionFile = os.absolutePath(session)
self.sessionFile = os.absolutePath(session).normalizePathUnix
elif options.fileToOpen.getSome(file):
let path = os.absolutePath(file)
let path = os.absolutePath(file).normalizePathUnix
if self.vfs.getFileKind(path).await.getSome(kind):
case kind
of FileKind.File:
Expand All @@ -774,7 +772,7 @@ proc newApp*(backend: api.Backend, platform: Platform, services: Services, optio
self.sessionFile = path // defaultSessionName

elif fileExists(defaultSessionName):
self.sessionFile = os.absolutePath(defaultSessionName)
self.sessionFile = os.absolutePath(defaultSessionName).normalizePathUnix

if self.sessionFile != "":
await self.restoreStateFromConfig(state.addr)
Expand Down Expand Up @@ -804,21 +802,22 @@ proc finishInitialization*(self: App, state: EditorState) {.async.} =

if self.config.getFlag("editor.restore-open-workspaces", true):
for wf in state.workspaceFolders:
var workspace: Workspace = newWorkspace(wf.settings)

workspace.id = wf.id.parseId
workspace.name = wf.name
if self.setWorkspaceFolder(workspace).await:
log(lvlInfo, fmt"Restoring workspace {workspace.name} ({workspace.id})")
log(lvlInfo, fmt"Restoring workspace")
self.workspace.restore(wf.settings)
await self.loadOptionsFromWorkspace()

# Open current working dir as local workspace if no workspace exists yet
if self.workspace.isNil:
if self.workspace.path == "":
log lvlInfo, "No workspace open yet, opening current working directory as local workspace"
discard await self.setWorkspaceFolder newWorkspace(".")
self.workspace.addWorkspaceFolder(getCurrentDir().normalizePathUnix)
await self.loadOptionsFromWorkspace()

# Restore open editors
if self.appOptions.fileToOpen.getSome(filePath):
discard self.layout.openFile(filePath)
try:
discard self.layout.openFile(os.absolutePath(filePath).normalizePathUnix)
except CatchableError as e:
log lvlError, &"Failed to open file '{filePath}': {e.msg}"

elif self.config.getFlag("editor.restore-open-editors", true):
for editorState in state.openEditors:
Expand Down Expand Up @@ -1094,20 +1093,6 @@ proc setConsumeAllActions*(self: App, context: string, value: bool) {.expose("ed
proc setConsumeAllInput*(self: App, context: string, value: bool) {.expose("editor").} =
self.events.getEventHandlerConfig(context).setConsumeAllInput(value)

proc setWorkspaceFolder(self: App, workspace: Workspace): Future[bool] {.async.} =
log(lvlInfo, fmt"Opening workspace {workspace.name}")

if workspace.id == idNone():
workspace.id = newId()

self.workspace = workspace

self.services.getService(WorkspaceService).get.workspace = workspace

await self.loadOptionsFromWorkspace()

return true

proc clearWorkspaceCaches*(self: App) {.expose("editor").} =
self.workspace.clearDirectoryCache()

Expand Down Expand Up @@ -1151,13 +1136,6 @@ proc addScriptAction*(self: App, name: string, docs: string = "",
else:
extendGlobalDispatchTable context, ExposedFunction(name: name, docs: docs, dispatch: dispatch, params: params, returnType: returnType, signature: signature)

proc openLocalWorkspaceAsync(self: App, path: string) {.async.} =
discard await self.setWorkspaceFolder newWorkspace(path)

proc openLocalWorkspace*(self: App, path: string) {.expose("editor").} =
let path = if path.isAbsolute: path else: path.absolutePath.catch().valueOr(path)
asyncSpawn self.openLocalWorkspaceAsync(path)

proc quit*(self: App) {.expose("editor").} =
self.closeRequested = true

Expand Down Expand Up @@ -1423,7 +1401,7 @@ proc chooseTheme*(self: App) {.expose("editor").} =

proc createFile*(self: App, path: string) {.expose("editor").} =
let fullPath = if path.isAbsolute:
path.normalizePathUnix
path.normalizeNativePath
else:
path.absolutePath.catch().valueOr(path).normalizePathUnix

Expand Down Expand Up @@ -1542,14 +1520,12 @@ proc chooseFile*(self: App, preview: bool = true, scaleX: float = 0.8, scaleY: f
defer:
self.platform.requestRender()

let workspace = self.workspace

let previewer = if preview:
newWorkspaceFilePreviewer(self.vfs, self.services).Previewer.toDisposableRef.some
else:
DisposableRef[Previewer].none

let finder = newFinder(newWorkspaceFilesDataSource(workspace), filterAndSort=true)
let finder = newFinder(newWorkspaceFilesDataSource(self.workspace), filterAndSort=true)
var popup = newSelectorPopup(self.services, "file".some, finder.some, previewer)
popup.scale.x = scaleX
popup.scale.y = scaleY
Expand Down Expand Up @@ -1868,10 +1844,8 @@ proc searchGlobal*(self: App, query: string) {.expose("editor").} =
defer:
self.platform.requestRender()

let workspace = self.workspace

let maxResults = self.config.getOption[:int]("editor.max-search-results", 1000)
let source = newAsyncCallbackDataSource () => workspace.searchWorkspaceItemList(query, maxResults)
let source = newAsyncCallbackDataSource () => self.workspace.searchWorkspaceItemList(query, maxResults)
var finder = newFinder(source, filterAndSort=true)

var popup = newSelectorPopup(self.services, "search".some, finder.some,
Expand Down Expand Up @@ -1941,6 +1915,7 @@ proc installTreesitterParserAsync*(self: App, language: string, host: string) {.
block:
log lvlInfo, &"Copy highlight queries"

# todo: don't use VFSLocal directly, move copyFile to VFS
let vfsLocal = self.vfs.getVFS("").vfs.VFSLocal

let queryDirs = if queriesSubDir != "":
Expand All @@ -1955,7 +1930,7 @@ proc installTreesitterParserAsync*(self: App, language: string, host: string) {.
if f.endsWith(".scm"):
let fileName = f.splitPath.tail
log lvlInfo, &"Copy '{f}' to '{queryDir}'"
discard await vfsLocal.copyFile(f, queryDir // fileName)
discard await vfsLocal.copyFile(path // f, queryDir // fileName)

block:
let (output, err) = await runProcessAsyncOutput("tree-sitter", @["build", "--wasm", grammarPath],
Expand Down Expand Up @@ -2181,7 +2156,7 @@ proc saveSession*(self: App, sessionFile: string = "") {.expose("editor").} =
## Reloads some of the state stored in the session file (default: config/config.json)
let sessionFile = if sessionFile == "": defaultSessionName else: sessionFile
try:
self.sessionFile = os.absolutePath(sessionFile)
self.sessionFile = os.absolutePath(sessionFile).normalizePathUnix
self.saveAppState()
self.requestRender()
except Exception as e:
Expand Down
13 changes: 2 additions & 11 deletions src/ast/project.nim
Original file line number Diff line number Diff line change
Expand Up @@ -23,22 +23,13 @@ type

func serviceName*(_: typedesc[AstProjectService]): string = "AstProjectService"

addBuiltinService(AstProjectService, WorkspaceService)
addBuiltinService(AstProjectService, Workspace)

proc loadModelAsync*(self: AstProjectService, path: string): Future[Option[Model]] {.async: (raises: []).}

method init*(self: AstProjectService): Future[Result[void, ref CatchableError]] {.async: (raises: []).} =
log lvlInfo, &"AstProjectService.init"
let workspaceService = self.services.getService(WorkspaceService).get

while workspaceService.workspace.isNil:
try:
sleepAsync(10.milliseconds).await
except CancelledError:
discard

log lvlInfo, &"AstProjectService.init 2"
self.workspace = workspaceService.workspace
self.workspace = self.services.getService(Workspace).get

let projectPath = self.workspace.getAbsolutePath("./model/playground.ast-project")
log lvlInfo, fmt"[getGlobalProject] Loading project source file '{projectPath}'"
Expand Down
14 changes: 2 additions & 12 deletions src/layout.nim
Original file line number Diff line number Diff line change
Expand Up @@ -54,17 +54,7 @@ var gPushSelectorPopupImpl*: PushSelectorPopupImpl

func serviceName*(_: typedesc[LayoutService]): string = "LayoutService"

addBuiltinService(LayoutService, PlatformService, ConfigService, DocumentEditorService, WorkspaceService)

proc waitForWorkspace(self: LayoutService) {.async: (raises: []).} =
let ws = self.services.getService(WorkspaceService).get
while ws.workspace.isNil:
try:
await sleepAsync(10.milliseconds)
except CancelledError:
discard

self.workspace = ws.workspace
addBuiltinService(LayoutService, PlatformService, ConfigService, DocumentEditorService, Workspace)

method init*(self: LayoutService): Future[Result[void, ref CatchableError]] {.async: (raises: []).} =
log lvlInfo, &"LayoutService.init"
Expand All @@ -75,7 +65,7 @@ method init*(self: LayoutService): Future[Result[void, ref CatchableError]] {.as
self.layout = HorizontalLayout()
self.layout_props = LayoutProperties(props: {"main-split": 0.5.float32}.toTable)
self.pushSelectorPopupImpl = ({.gcsafe.}: gPushSelectorPopupImpl)
asyncSpawn self.waitForWorkspace()
self.workspace = self.services.getService(Workspace).get
return ok()

method activate*(view: EditorView) =
Expand Down
2 changes: 1 addition & 1 deletion src/text/language/debugger.nim
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ method init*(self: Debugger): Future[Result[void, ref CatchableError]] {.async:
self.config = self.services.getService(ConfigService).get
self.plugins = self.services.getService(PluginService).get
self.platform = self.services.getService(PlatformService).get.platform
self.workspace = self.services.getService(WorkspaceService).get.workspace # todo
self.workspace = self.services.getService(Workspace).get

discard self.services.getService(SessionService).get.onSessionRestored.subscribe (session: SessionService) => self.handleSessionRestored(session)

Expand Down
2 changes: 1 addition & 1 deletion src/text/language/language_server_lsp.nim
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ proc getOrCreateLanguageServerLSP*(languageId: string, workspaces: seq[string],
"lsp." & languageId & "." & initializationOptionsName, newJNull())

let workspaceInfo = if workspace.getSome(workspace):
workspace.info.await.some
workspace.info.some
else:
ws.WorkspaceInfo.none

Expand Down
2 changes: 1 addition & 1 deletion src/text/language/lsp_client.nim
Original file line number Diff line number Diff line change
Expand Up @@ -487,7 +487,7 @@ proc cancelAllOf*(client: LSPClient, meth: string) =

proc initialize(client: LSPClient): Future[Response[JsonNode]] {.async, gcsafe.} =
var workspacePath = if client.workspaceFolders.len > 0:
client.workspaceFolders[0].normalizePathUnix.some
client.workspaceFolders[0].some
else:
string.none

Expand Down
10 changes: 5 additions & 5 deletions src/text/text_document.nim
Original file line number Diff line number Diff line change
Expand Up @@ -1101,10 +1101,10 @@ proc newTextDocument*(
allTextDocuments.add result

var self = result
self.filename = filename.normalizePathUnix
self.filename = filename
self.currentTree = TSTree()
self.appFile = app
self.workspace = services.getService(WorkspaceService).get.workspace
self.workspace = services.getService(Workspace).get
self.services = services
self.configProvider = services.getService(ConfigService).get.asConfigProvider
self.vfs = services.getService(VFSService).get.vfs
Expand Down Expand Up @@ -1184,7 +1184,7 @@ proc saveAsync(self: TextDocument) {.async.} =
self.onSaved.invoke()

method save*(self: TextDocument, filename: string = "", app: bool = false) =
self.filename = if filename.len > 0: filename.normalizePathUnix else: self.filename
self.filename = if filename.len > 0: filename else: self.filename
logScope lvlInfo, &"[save] '{self.filename}'"

if self.filename.len == 0:
Expand Down Expand Up @@ -1316,7 +1316,7 @@ proc setFileReadOnlyAsync*(self: TextDocument, readOnly: bool): Future[bool] {.a
return false

proc setFileAndContent*[S: string | Rope](self: TextDocument, filename: string, content: sink S) =
let filename = if filename.len > 0: filename.normalizePathUnix else: self.filename
let filename = if filename.len > 0: filename else: self.filename
if filename.len == 0:
log lvlError, &"save: Missing filename"
return
Expand All @@ -1341,7 +1341,7 @@ proc setFileAndContent*[S: string | Rope](self: TextDocument, filename: string,
self.onLoaded.invoke self

method load*(self: TextDocument, filename: string = "") =
let filename = if filename.len > 0: filename.normalizePathUnix else: self.filename
let filename = if filename.len > 0: filename else: self.filename
if filename.len == 0:
log lvlError, &"save: Missing filename"
return
Expand Down
4 changes: 1 addition & 3 deletions src/text/text_editor.nim
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ type TextDocumentEditor* = ref object of DocumentEditor
plugins: PluginService
registers: Registers
workspace: Workspace
workspaceService: WorkspaceService

vfs: VFS

Expand Down Expand Up @@ -3594,8 +3593,7 @@ proc newTextEditor*(document: TextDocument, services: Services):
self.events = self.services.getService(EventHandlerService).get
self.plugins = self.services.getService(PluginService).get
self.registers = self.services.getService(Registers).get
self.workspaceService = self.services.getService(WorkspaceService).get
self.workspace = self.workspaceService.workspace
self.workspace = self.services.getService(Workspace).get
self.vfs = self.services.getService(VFSService).get.vfs

self.setDocument(document)
Expand Down
28 changes: 8 additions & 20 deletions src/vcs/vcs.nim
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import std/[options, strutils, os]
import misc/[custom_async, custom_logger, util]
import std/[options, strutils, os, sugar]
import misc/[custom_async, custom_logger, util, event]
import text/diff
import workspaces/workspace
import service, config_provider, vfs, vfs_service
Expand Down Expand Up @@ -27,7 +27,7 @@ type
vfs*: VFS

func serviceName*(_: typedesc[VCSService]): string = "VCSService"
addBuiltinService(VCSService, WorkspaceService, ConfigService, VFSService)
addBuiltinService(VCSService, Workspace, ConfigService, VFSService)

func isUntracked*(fileInfo: VCSFileInfo): bool = fileInfo.unstagedStatus == Untracked

Expand Down Expand Up @@ -66,31 +66,19 @@ proc detectVersionControlSystemIn(path: string): Option[VersionControlSystem] =
let vcs = newVersionControlSystemPerforce(path)
return vcs.VersionControlSystem.some

proc waitForWorkspace(self: VCSService) {.async: (raises: []).} =
let workspaceService = self.services.getService(WorkspaceService).get
while workspaceService.workspace.isNil:
try:
sleepAsync(10.milliseconds).await
except CancelledError:
discard

self.workspace = workspaceService.workspace

proc handleWorkspaceFolderAdded(self: VCSService, path: string) {.async: (raises: []).} =
try:
let info = self.workspace.info.await

for (path, _) in info.folders:
if detectVersionControlSystemIn(path).getSome(vcs):
self.versionControlSystems.add vcs
if detectVersionControlSystemIn(path).getSome(vcs):
self.versionControlSystems.add vcs
except CatchableError as e:
log lvlError, &"Failed to detect version control systems: {e.msg}\n{e.getStackTrace()}"


method init*(self: VCSService): Future[Result[void, ref CatchableError]] {.async: (raises: []).} =
log lvlInfo, &"VCSService.init"
self.config = self.services.getService(ConfigService).get
self.vfs = self.services.getService(VFSService).get.vfs
asyncSpawn self.waitForWorkspace()
self.workspace = self.services.getService(Workspace).get
discard self.workspace.onWorkspaceFolderAdded.subscribe (path: string) => asyncSpawn(self.handleWorkspaceFolderAdded(path))

return ok()

Expand Down
Loading

0 comments on commit 55e2a31

Please sign in to comment.