Skip to content

Commit

Permalink
refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
yatli committed Sep 9, 2021
1 parent 6e28667 commit 4549f43
Show file tree
Hide file tree
Showing 7 changed files with 61 additions and 64 deletions.
4 changes: 2 additions & 2 deletions Program.fs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ let buildAvaloniaApp() =
.Configure<App>()
.UsePlatformDetect()
.UseReactiveUI()
//.With(new Win32PlatformOptions(UseDeferredRendering=false, UseWgl=true))
//.With(new Win32PlatformOptions(UseDeferredRendering=true, UseWgl=true))
//.With(new AvaloniaNativePlatformOptions(UseDeferredRendering=false))
//.With(new X11PlatformOptions(UseDeferredRendering=false))
//.With(new MacOSPlatformOptions(ShowInDock=true))
Expand Down Expand Up @@ -161,6 +161,6 @@ let main(args: string[]) =
| Setup -> setup()
| Uninstall -> uninstall()
| Daemon(pipe, nvim, enc) -> daemon pipe nvim enc
| Start(a,b,c) -> startMainWindow app (a,b,c)
| Start(a,b) -> startMainWindow app (a,b)
with
| ex -> startCrashReportWindow app ex
13 changes: 5 additions & 8 deletions def.fs
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,14 @@ type Request =
parameters: obj[]
}

[<Struct>]
type Response =
{
result: Result<obj, obj>
}
type Response = Result<obj, obj>

[<Struct>]
type Event =
| Request of reqId: int32 * req: Request * handler: (int32 -> Response -> unit Task)
| Response of rspId: int32 * rsp: Response
| RpcRequest of reqId: int32 * req: Request * handler: (int32 -> Response -> unit Task)
| RpcResponse of rspId: int32 * rsp: Response
| Notification of nreq: Request
| Error of emsg: string
| StdError of emsg: string
| Crash of ccode: int32
| ByteMessage of bmsg: byte
| UnhandledException of ex: exn
Expand Down Expand Up @@ -389,6 +385,7 @@ type RedrawCommand =
| UnknownCommand of data: obj
/// --------- Custom messages -----------
| MultiRedrawCommand of xs: RedrawCommand []
| ScrollbarUpdate of grid:int * win: int * totalline: int * topline: int * botline: int * curline: int * curcol: int

type EventParseException(data: obj) =
inherit exn()
Expand Down
5 changes: 2 additions & 3 deletions getopt.fs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ type ServerOptions =
| FVimRemote of serverName: string option * transport: FVimRemoteTransport * verb: FVimRemoteVerb * files: string list

type Intent =
| Start of serveropts: ServerOptions * norc: bool * debugMultigrid: bool
| Start of serveropts: ServerOptions * norc: bool
| Setup
| Uninstall
| Daemon of pipe: string option * nvim: string * stderrenc: System.Text.Encoding
Expand Down Expand Up @@ -72,7 +72,6 @@ let parseOptions (args: string[]) =
let daemon = eat1 "--daemon"
let pipe = eat2 "--pipe"
// debug & tracing
let debug_multigrid = eat1 "--debug-multigrid"
let trace_to_stdout = eat1 "--trace-to-stdout"
let trace_to_file = eat1 "--trace-to-file"
let trace_patterns = eat2 "--trace-patterns"
Expand Down Expand Up @@ -148,7 +147,7 @@ let parseOptions (args: string[]) =
in
Embedded(prog, args, enc)
in
Start(serveropts, norc, debug_multigrid)
Start(serveropts, norc)

{
logToStdout = trace_to_stdout
Expand Down
4 changes: 4 additions & 0 deletions input.fs
Original file line number Diff line number Diff line change
Expand Up @@ -306,11 +306,15 @@ let onInput (nvim: Nvim) (input: IObservable<int*InputEvent>) =
let mouse = inputClassifier |> Observable.choose (function | Choice2Of3 x -> Some x | _ -> None)
Disposables.compose [
key |> Observable.subscribe(fun x ->
#if DEBUG
trace "OnInput: key: %A" x
#endif
nvim.input x |> ignore
)
mouse |> Observable.subscribe(fun ((grid, (but, act, r, c, rep), mods) as ev) ->
#if DEBUG
trace "grid #%d: OnInput: mouse: %A" grid ev
#endif
let mods = match mods with Some mods -> mods | _ -> ""
for _ in 1..rep do
nvim.input_mouse but act mods grid r c |> ignore
Expand Down
69 changes: 32 additions & 37 deletions model.fs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ open Avalonia.Layout
open System.Threading.Tasks
open FSharp.Control.Tasks.V2
open System.Reflection
open System.Collections.Concurrent

#nowarn "0025"

Expand Down Expand Up @@ -94,6 +95,17 @@ module private ModelImpl =
if RuntimeInformation.IsOSPlatform(OSPlatform.OSX) then id
else Observable.throttle(TimeSpan.FromMilliseconds 10.0)

let update_scrollbar id win top bot row col =
async {
match! nvim.call { method = "nvim_win_get_buf"; parameters = mkparams1 win } with
| Error(_) -> ()
| Ok(Integer32(buf)) ->
match! nvim.call { method = "nvim_buf_line_count"; parameters = mkparams1 buf} with
| Error(_) -> ()
| Ok(Integer32(cnt)) ->
unicast id (ScrollbarUpdate(id,win,cnt,top,bot,row,col))
} |> Async.Start

let rec redraw cmd =
match cmd with
// Global
Expand All @@ -117,8 +129,8 @@ module private ModelImpl =
-> broadcast cmd
// Unicast
| GridClear id | GridScroll(id,_,_,_,_,_,_)
| WinClose id | WinHide(id)
| WinViewport(id, _, _, _, _, _ ) -> unicast id cmd
| WinClose id | WinHide(id) -> unicast id cmd
| WinViewport(id, win, top, bot, row, col ) -> unicast id cmd // TODO update_scrollbar id win top bot row col
| WinExternalPos(id,_) -> unicast_detach id cmd
| WinFloatPos(id, _, _, pid, _, _, _, _)
-> unicast_change_parent id pid cmd
Expand Down Expand Up @@ -169,7 +181,7 @@ module rpc =

let msg_dispatch =
function
| Request(id, req, reply) ->
| RpcRequest(id, req, reply) ->
match requestHandlers.TryGetValue req.method with
| true, method ->
task {
Expand All @@ -180,12 +192,11 @@ module rpc =
| Failure msg -> error "rpc" "request %d(%s) failed: %s" id req.method msg
} |> run
| _ -> error "rpc" "request handler [%s] not found" req.method

| Notification(req) ->
let event = getNotificationEvent req.method
try event.Trigger req.parameters
with | Failure msg -> error "rpc" "notification trigger [%s] failed: %s" req.method msg
| Error err ->
| StdError err ->
error "rpc" "neovim: %s" err
_errormsgs.Add err
| ByteMessage bmsg ->
Expand Down Expand Up @@ -228,7 +239,7 @@ module rpc =
try fn objs
with x ->
error "Request" "exception thrown: %O" x
Task.FromResult { result = Result.Error(box x) })
Task.FromResult(Error(box x)))

/// Register an event handler.
let notify name (fn: obj[] -> unit) =
Expand Down Expand Up @@ -257,11 +268,9 @@ module rpc =
| _ -> ())
|> ignore
request fullname (fun _ -> task {
let result =
match Helper.GetProp fieldName with
| Some v -> Ok v
| None -> Result.Error(box "not found")
return { result=result }
match Helper.GetProp fieldName with
| Some v -> return Ok v
| None -> return Error(box "not found")
})

let bool = prop<bool> (|Bool|_|)
Expand Down Expand Up @@ -289,23 +298,12 @@ let private UpdateUICapabilities() =
in ()
} |> runAsync

//let private UpdateUIWindows() =
// if ui_windows then
// // TODO maybe also tabline?
// ui_multigrid <- true
// else
// ui_multigrid <- false


/// <summary>
/// Call this once at initialization.
/// </summary>
let Start (serveropts, norc, debugMultigrid) =
let Start (serveropts, norc) =
trace "starting neovim instance..."
trace "opts = %A" serveropts
if debugMultigrid then
states.ui_multigrid <- true
//states.ui_windows <- true
nvim.start serveropts
nvim.subscribe
(AvaloniaSynchronizationContext.Current)
Expand Down Expand Up @@ -354,7 +352,6 @@ let Start (serveropts, norc, debugMultigrid) =
|> Observable.subscribe(UpdateUICapabilities)
rpc.register.notify "redraw" (Array.map parse_redrawcmd >> Array.iter redraw)
rpc.register.notify "remote.detach" (fun _ -> Detach())
//rpc.register.watch "ui.windows" UpdateUIWindows
rpc.register.watch "ui" ev_uiopt.Trigger
rpc.register.watch "font" theme.fontConfig
rpc.register.watch "font" ui.InvalidateFontCache
Expand All @@ -366,7 +363,7 @@ let Start (serveropts, norc, debugMultigrid) =
let text = String.Join("\n", lines)
let! _ = Avalonia.Application.Current.Clipboard.SetTextAsync(text)
trace "set-clipboard called. regtype=%s" regtype
return { result = Ok(box [||]) }
return Ok(box [||])
})

rpc.register.request "get-clipboard" (fun _ -> task {
Expand All @@ -383,7 +380,7 @@ let Start (serveropts, norc, debugMultigrid) =
trace "get-clipboard: mismatch, using system clipboard"
sysClipboardLines, "v"

return { result = Ok(box [| box lines; box regtype |])}
return Ok(box [| box lines; box regtype |])
})

trace "commencing early initialization..."
Expand All @@ -393,13 +390,13 @@ let Start (serveropts, norc, debugMultigrid) =

let! api_info = nvim.call { method = "nvim_get_api_info"; parameters = [||] }
let api_query_result =
match api_info.result with
match api_info with
| Ok(ObjArray [| Integer32 _; metadata |]) -> Ok metadata
| _ -> Result.Error("nvim_get_api_info")
| _ -> Error("nvim_get_api_info")
>?= fun metadata ->
match metadata with
| FindKV "ui_options" (P (|String|_|) ui_options) -> Ok(Set.ofArray ui_options)
| _ -> Result.Error("find ui_options")
| _ -> Error("find ui_options")
>?= fun ui_options ->
trace "available ui options: %A" ui_options
ui_available_opts <- ui_options
Expand All @@ -409,7 +406,7 @@ let Start (serveropts, norc, debugMultigrid) =
if not (ui_available_opts.Contains uiopt_ext_linegrid) ||
not (ui_available_opts.Contains uiopt_rgb) then
failwithf "api_query_result: your NeoVim version is too low. fvim requires \"rgb\" and \"ext_linegrid\" options, got: %A" ui_available_opts
| Result.Error(msg) ->
| Error(msg) ->
failwithf "api_query_result: %s" msg

// for remote, send open file args as edit commands
Expand All @@ -429,7 +426,7 @@ let Start (serveropts, norc, debugMultigrid) =
let clientVersion =
hashmap [
"major", "0"
"minor", "2"
"minor", "3"
"prerelease", "dev"
]
let clientType = "ui"
Expand Down Expand Up @@ -645,12 +642,10 @@ let InsertText text =

let GetBufferPath (win: int) =
async {
let! rsp = nvim.call { method = "nvim_win_get_buf"; parameters = mkparams1 win }
match rsp.result with
match! nvim.call { method = "nvim_win_get_buf"; parameters = mkparams1 win } with
| Error(_) -> return ""
| Ok(Integer32 bufnr) ->
let! rsp = nvim.call { method = "nvim_buf_get_name"; parameters = mkparams1 bufnr }
match rsp.result with
| Ok(String path) -> return path
| _ -> return ""
match! nvim.call { method = "nvim_buf_get_name"; parameters = mkparams1 bufnr } with
| Ok(String path) -> return path
| _ -> return ""
}
24 changes: 11 additions & 13 deletions neovim.fs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ let private default_notify (e: Request) =
task { return () }

let private default_call (e: Request) =
task { return {result=Result.Error(box "not connected")} }
task { return Result.Error(box "not connected") }

type NvimIO =
| Disconnected
Expand Down Expand Up @@ -122,7 +122,7 @@ type Nvim() as nvim =
let stdin = proc.StandardInput.BaseStream
let stderr =
proc.ErrorDataReceived
|> Observable.map (fun data -> Error data.Data )
|> Observable.map (fun data -> StdError data.Data )
proc.BeginErrorReadLine()
stdin, stdout, stderr
| RemoteSession stream ->
Expand Down Expand Up @@ -167,9 +167,9 @@ type Nvim() as nvim =

let reply (id: int) (rsp: Response) = task {
let result, error =
match rsp.result with
match rsp with
| Ok r -> null, r
| Result.Error e -> e, null
| Error e -> e, null
do! MessagePackSerializer.SerializeAsync(stdin, mkparams4 1 id result error)
do! stdin.FlushAsync()
}
Expand All @@ -181,10 +181,10 @@ type Nvim() as nvim =
match data with
// request
| [| (Integer32 0); (Integer32 msg_id) ; (String method); :? (obj[]) as parameters |]
-> Request(msg_id, { method = method; parameters = parameters }, reply)
-> RpcRequest(msg_id, { method = method; parameters = parameters }, reply)
// response
| [| (Integer32 1); (Integer32 msg_id) ; err; result |]
-> Response(msg_id, { result = if err = null then Ok result else Result.Error err })
-> RpcResponse(msg_id, if err = null then Ok result else Error err)
// notification
| [| (Integer32 2); (String method); :? (obj[]) as parameters |]
-> Notification { method = method; parameters = parameters }
Expand All @@ -196,10 +196,10 @@ type Nvim() as nvim =

let intercept (ev: Event) =
match ev with
| Response(msgid, rsp) ->
| RpcResponse(msgid, rsp) ->
// intercept response message, if it can be completed successfully
match rsp.result with
| Result.Error err -> trace "call %d: error response %A" msgid err
match rsp with
| Error err -> trace "call %d: error response %A" msgid err
| _ -> ()

match pending.TryRemove msgid with
Expand Down Expand Up @@ -332,7 +332,7 @@ type Nvim() as nvim =
let! response = nvim.call { method = "nvim_call_function"; parameters = mkparams2 "exists" (mkparams1 var) }
//return response
trace "exists: response = %A" response
match response.result with
match response with
| Ok(Integer32 1) -> return true
| _ -> return false
}
Expand Down Expand Up @@ -368,9 +368,7 @@ type Nvim() as nvim =

member __.list_chans() =
async {
let! rsp = nvim.call { method = "nvim_list_chans"; parameters = [||] }

match rsp.result with
match! nvim.call { method = "nvim_list_chans"; parameters = [||] } with
| Ok(ObjArray arr) -> return arr
| _ -> return [||]
}
6 changes: 5 additions & 1 deletion theme.fs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ do
default_fg <- fg
default_sp <- sp

let getSemanticHighlightGroup x =
semhl.TryFind x
|> Option.defaultValue 1
|> GetDrawAttrs

let setSemanticHighlightGroups grp =
semhl <- grp
Expand All @@ -88,7 +92,7 @@ let setSemanticHighlightGroups grp =
SemanticHighlightGroup.VertSplit
SemanticHighlightGroup.Folded
]
|> List.map (semhl.TryFind >> Option.defaultValue 1 >> GetDrawAttrs)
|> List.map getSemanticHighlightGroup

themeconfig_ev.Trigger(nfg, nbg, sfg, sbg, scfg, scbg, bbg, ifg)

Expand Down

0 comments on commit 4549f43

Please sign in to comment.