Skip to content

Commit

Permalink
Refactor command handling to return the value instead of a bool
Browse files Browse the repository at this point in the history
  • Loading branch information
Nimaoth committed Aug 11, 2024
1 parent 6365e6b commit 2615e86
Show file tree
Hide file tree
Showing 9 changed files with 106 additions and 75 deletions.
4 changes: 2 additions & 2 deletions scripting/absytree_internal.nim
Original file line number Diff line number Diff line change
Expand Up @@ -326,8 +326,8 @@ proc editor_text_setFlag_void_TextDocumentEditor_string_bool_impl*(
proc editor_text_getFlag_bool_TextDocumentEditor_string_impl*(
self: TextDocumentEditor; name: string): bool =
discard
proc editor_text_runAction_bool_TextDocumentEditor_string_JsonNode_impl*(
self: TextDocumentEditor; action: string; args: JsonNode): bool =
proc editor_text_runAction_Option_JsonNode_TextDocumentEditor_string_JsonNode_impl*(
self: TextDocumentEditor; action: string; args: JsonNode): Option[JsonNode] =
discard
proc editor_text_findWordBoundary_Selection_TextDocumentEditor_Cursor_impl*(
self: TextDocumentEditor; cursor: Cursor): Selection =
Expand Down
7 changes: 4 additions & 3 deletions scripting/editor_text_api.nim
Original file line number Diff line number Diff line change
Expand Up @@ -325,9 +325,10 @@ proc setFlag*(self: TextDocumentEditor; name: string; value: bool) =
editor_text_setFlag_void_TextDocumentEditor_string_bool_impl(self, name, value)
proc getFlag*(self: TextDocumentEditor; name: string): bool =
editor_text_getFlag_bool_TextDocumentEditor_string_impl(self, name)
proc runAction*(self: TextDocumentEditor; action: string; args: JsonNode): bool =
editor_text_runAction_bool_TextDocumentEditor_string_JsonNode_impl(self,
action, args)
proc runAction*(self: TextDocumentEditor; action: string; args: JsonNode): Option[
JsonNode] =
editor_text_runAction_Option_JsonNode_TextDocumentEditor_string_JsonNode_impl(
self, action, args)
proc findWordBoundary*(self: TextDocumentEditor; cursor: Cursor): Selection =
editor_text_findWordBoundary_Selection_TextDocumentEditor_Cursor_impl(self,
cursor)
Expand Down
7 changes: 4 additions & 3 deletions scripting/editor_text_api_wasm.nim
Original file line number Diff line number Diff line change
Expand Up @@ -2293,9 +2293,10 @@ proc getFlag*(self: TextDocumentEditor; name: string): bool =
result = parseJson($res).jsonTo(typeof(result))


proc editor_text_runAction_bool_TextDocumentEditor_string_JsonNode_wasm(
proc editor_text_runAction_Option_JsonNode_TextDocumentEditor_string_JsonNode_wasm(
arg: cstring): cstring {.importc.}
proc runAction*(self: TextDocumentEditor; action: string; args: JsonNode): bool =
proc runAction*(self: TextDocumentEditor; action: string; args: JsonNode): Option[
JsonNode] =
var argsJson = newJArray()
argsJson.add block:
when TextDocumentEditor is JsonNode:
Expand All @@ -2313,7 +2314,7 @@ proc runAction*(self: TextDocumentEditor; action: string; args: JsonNode): bool
else:
args.toJson()
let argsJsonString = $argsJson
let res {.used.} = editor_text_runAction_bool_TextDocumentEditor_string_JsonNode_wasm(
let res {.used.} = editor_text_runAction_Option_JsonNode_TextDocumentEditor_string_JsonNode_wasm(
argsJsonString.cstring)
result = parseJson($res).jsonTo(typeof(result))

Expand Down
77 changes: 44 additions & 33 deletions src/app.nim
Original file line number Diff line number Diff line change
Expand Up @@ -457,7 +457,7 @@ proc handleModeChanged*(self: App, editor: DocumentEditor, oldMode: string, newM
log(lvlError, fmt"Failed to run script handleDocumentModeChanged '{oldMode} -> {newMode}': {getCurrentExceptionMsg()}")
log(lvlError, getCurrentException().getStackTrace())

proc handleAction(self: App, action: string, arg: string, record: bool): bool
proc handleAction(self: App, action: string, arg: string, record: bool): Option[JsonNode]
proc getFlag*(self: App, flag: string, default: bool = false): bool

proc createEditorForDocument(self: App, document: Document): DocumentEditor =
Expand Down Expand Up @@ -1063,22 +1063,37 @@ import asynchttpserver, asyncnet
proc processClient(client: AsyncSocket) {.async.} =
log lvlInfo, &"Process client"
let self: App = ({.gcsafe.}: gEditor)
while not client.isClosed:
let line = await client.recvLine()
if line.len == 0:
break

log lvlInfo, &"Run command from client: '{line}'"
let command = line
let (action, arg) = parseAction(command)
discard self.handleAction(action, arg, record=true)
try:
while not client.isClosed:
let line = await client.recvLine()
if line.len == 0:
break

log lvlInfo, &"Run command from client: '{line}'"
let command = line
let (action, arg) = parseAction(command)
let response = self.handleAction(action, arg, record=true)
if response.getSome(r):
await client.send($r & "\n")
else:
await client.send("\n")

except:
log lvlError, &"Failed to read data from connection: {getCurrentExceptionMsg()}"

proc serve(port: Port) {.async.} =
log lvlInfo, &"Listen for connections on port {port.int}"
var server = newAsyncSocket()
server.setSockOpt(OptReuseAddr, true)
server.bindAddr(port)
server.listen()
var server: AsyncSocket

try:
server = newAsyncSocket()
server.setSockOpt(OptReuseAddr, true)
server.bindAddr(port)
server.listen()
except:
log lvlError, &"Failed to create server on port {port.int}: {getCurrentExceptionMsg()}"
return

while true:
let client = await server.accept()
Expand Down Expand Up @@ -1157,7 +1172,7 @@ proc newEditor*(backend: api.Backend, platform: Platform, options = AppOptions()

assignEventHandler(self.eventHandler, self.getEventHandlerConfig("editor")):
onAction:
if self.handleAction(action, arg, record=true):
if self.handleAction(action, arg, record=true).isSome:
Handled
else:
Ignored
Expand All @@ -1166,7 +1181,7 @@ proc newEditor*(backend: api.Backend, platform: Platform, options = AppOptions()

assignEventHandler(self.commandLineEventHandlerHigh, self.getEventHandlerConfig("command-line-high")):
onAction:
if self.handleAction(action, arg, record=true):
if self.handleAction(action, arg, record=true).isSome:
Handled
else:
Ignored
Expand All @@ -1175,7 +1190,7 @@ proc newEditor*(backend: api.Backend, platform: Platform, options = AppOptions()

assignEventHandler(self.commandLineEventHandlerLow, self.getEventHandlerConfig("command-line-low")):
onAction:
if self.handleAction(action, arg, record=true):
if self.handleAction(action, arg, record=true).isSome:
Handled
else:
Ignored
Expand Down Expand Up @@ -2199,7 +2214,7 @@ proc executeCommandLine*(self: App): bool {.expose("editor").} =
if arg.startsWith("\\"):
arg = $newJString(arg[1..^1])

return self.handleAction(action, arg, record=true)
return self.handleAction(action, arg, record=true).isSome

proc writeFile*(self: App, path: string = "", appFile: bool = false) {.expose("editor").} =
defer:
Expand Down Expand Up @@ -3356,7 +3371,7 @@ proc setMode*(self: App, mode: string) {.expose("editor").} =
let config = self.getModeConfig(mode)
assignEventHandler(self.modeEventHandler, config):
onAction:
if self.handleAction(action, arg, record=true):
if self.handleAction(action, arg, record=true).isSome:
Handled
else:
Ignored
Expand Down Expand Up @@ -3951,7 +3966,7 @@ proc recordCommand*(self: App, command: string, args: string) =
self.registers[register].text.add "\n"
self.registers[register].text.add command & " " & args

proc handleAction(self: App, action: string, arg: string, record: bool): bool =
proc handleAction(self: App, action: string, arg: string, record: bool): Option[JsonNode] =
logScope lvlInfo, &"[handleAction] '{action} {arg}'"

if record:
Expand All @@ -3966,43 +3981,39 @@ proc handleAction(self: App, action: string, arg: string, record: bool): bool =
log(lvlError, getCurrentException().getStackTrace())

if action.startsWith("."): # active action
if lsp_client.dispatchEvent(action[1..^1], args):
return true
if lsp_client.dispatchEvent(action[1..^1], args).getSome(r):
return r.some

if self.getActiveEditor().getSome(editor):
return case editor.handleAction(action[1..^1], arg, record=false)
of Handled:
true
else:
false
return editor.handleAction(action[1..^1], arg, record=false)

log lvlError, fmt"No current view"
return false
return JsonNode.none

if debugger.dispatchEvent(action, args):
return true
if debugger.dispatchEvent(action, args).getSome(r):
return r.some

try:
withScriptContext self, self.nimsScriptContext:
let res = self.nimsScriptContext.handleScriptAction(action, args)
if res.isNotNil:
return true
return res.some

withScriptContext self, self.wasmScriptContext:
let res = self.wasmScriptContext.handleScriptAction(action, args)
if res.isNotNil:
return true
return res.some
except CatchableError:
log(lvlError, fmt"Failed to dispatch action '{action} {arg}': {getCurrentExceptionMsg()}")
log(lvlError, getCurrentException().getStackTrace())

try:
return dispatch(action, args).isSome
return dispatch(action, args)
except CatchableError:
log(lvlError, fmt"Failed to dispatch action '{action} {arg}': {getCurrentExceptionMsg()}")
log(lvlError, getCurrentException().getStackTrace())

return true
return JsonNode.none

template createNimScriptContextConstructorAndGenerateBindings*(): untyped =
when enableNimscript and not defined(js):
Expand Down
8 changes: 4 additions & 4 deletions src/ast/model_document.nim
Original file line number Diff line number Diff line change
Expand Up @@ -3660,7 +3660,7 @@ proc findDeclaration*(self: ModelDocumentEditor, global: bool) {.expose("editor.
genDispatcher("editor.model")
addActiveDispatchTable "editor.model", genDispatchTable("editor.model")

method handleAction*(self: ModelDocumentEditor, action: string, arg: string, record: bool): EventResponse =
method handleAction*(self: ModelDocumentEditor, action: string, arg: string, record: bool): Option[JsonNode] =
# log lvlInfo, fmt"[modeleditor]: Handle action {action}, '{arg}'"
# defer:
# log lvlDebug, &"line: {self.cursor.targetCell.line}, cursor: {self.cursor},\ncell: {self.cursor.cell.dump()}\ntargetCell: {self.cursor.targetCell.dump()}"
Expand All @@ -3674,14 +3674,14 @@ method handleAction*(self: ModelDocumentEditor, action: string, arg: string, rec
for a in newStringStream(arg).parseJsonFragments():
args.add a

if dispatch(action, args).isSome:
if dispatch(action, args).getSome(res):
self.markDirty()
return Handled
return res.some
except CatchableError:
log lvlError, fmt"Failed to dispatch action '{action} {args}': {getCurrentExceptionMsg()}"
log lvlError, getCurrentException().getStackTrace()

return Ignored
return JsonNode.none

method getStateJson*(self: ModelDocumentEditor): JsonNode =
return %*{
Expand Down
4 changes: 2 additions & 2 deletions src/document_editor.nim
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import std/[json, tables]
import std/[json, tables, options]
import vmath, bumpy
import misc/[event, custom_logger, id]
import document, events, input, config_provider
Expand Down Expand Up @@ -69,7 +69,7 @@ method createWithDocument*(self: DocumentEditor, document: Document, configProvi

method getDocument*(self: DocumentEditor): Document {.base.} = discard

method handleAction*(self: DocumentEditor, action: string, arg: string, record: bool = true): EventResponse {.base.} = discard
method handleAction*(self: DocumentEditor, action: string, arg: string, record: bool = true): Option[JsonNode] {.base.} = discard

method getEventHandlers*(self: DocumentEditor, inject: Table[string, EventHandler]): seq[EventHandler] {.base.} =
return @[]
Expand Down
4 changes: 2 additions & 2 deletions src/text/language/debugger.nim
Original file line number Diff line number Diff line change
Expand Up @@ -1210,8 +1210,8 @@ proc stepOut*(self: Debugger) {.expose("debugger").} =
genDispatcher("debugger")
addGlobalDispatchTable "debugger", genDispatchTable("debugger")

proc dispatchEvent*(action: string, args: JsonNode): bool =
dispatch(action, args).isSome
proc dispatchEvent*(action: string, args: JsonNode): Option[JsonNode] =
dispatch(action, args)

proc handleAction(self: Debugger, action: string, arg: string): EventResponse =
# debugf"[textedit] handleAction {action}, '{args}'"
Expand Down
11 changes: 7 additions & 4 deletions src/text/language/lsp_client.nim
Original file line number Diff line number Diff line change
Expand Up @@ -418,8 +418,11 @@ proc handleResponses*(client: LSPClient) {.async, gcsafe.} =
future.complete parsedResponse
requests.del(id)
let index = client.requestsPerMethod[meth].find(id)
assert index != -1
client.requestsPerMethod[meth].delete index
if index != -1:
client.requestsPerMethod[meth].delete index
else:
let temp {.inject.} = meth
log lvlError, &"Request not found: {id}, {temp}, {client.requestsPerMethod[temp]}"
elif client.canceledRequests.contains(id):
# Request was canceled
# debugf"[LSP.run] Received response for canceled request {id}"
Expand Down Expand Up @@ -1086,8 +1089,8 @@ proc lspLogServerDebug*(val: bool) {.expose("lsp").} =
genDispatcher("lsp")
addActiveDispatchTable "lsp", genDispatchTable("lsp"), global=true

proc dispatchEvent*(action: string, args: JsonNode): bool =
dispatch(action, args).isSome
proc dispatchEvent*(action: string, args: JsonNode): Option[JsonNode] =
dispatch(action, args)

proc handleGetSymbols(client: LSPClient) {.async, gcsafe.} =
while client != nil:
Expand Down
Loading

0 comments on commit 2615e86

Please sign in to comment.