-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathplugin_api.nim
More file actions
1683 lines (1404 loc) · 71.9 KB
/
plugin_api.nim
File metadata and controls
1683 lines (1404 loc) · 71.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import std/[macros, strutils, os, strformat, sequtils, json, sets, tables, atomics, locks]
import misc/[custom_logger, custom_async, util, event, jsonex, timer, myjsonutils, render_command, binary_encoder, async_process, rope_utils, regex, rope_regex, generational_seq, shared_buffer]
import nimsumtree/[rope, sumtree, arc, clock, buffer]
import service
import layout
import text/[text_editor, text_document, overlay_map]
import view
import render_view as rv
import platform/platform, platform_service
import config_provider, command_service, command_service_api, compilation_config
import plugin_service, document_editor, vfs, vfs_service, channel, register, move_database, popup, event_service, session
import "../../modules/terminal"/terminal
import decoration_component, command_component
import wasmtime, wit_host_module, plugin_api_base, wasi, plugin_thread_pool
import lisp
import vmath
from scripting_api as sca import nil
{.push gcsafe, raises: [].}
logCategory "plugin-api-v0"
const apiVersion: int32 = 0
type Resource = object of RootObj
type SharedBufferResource = object of Resource
buffer: SharedBuffer
type RopeResource = object of Resource
rope: RopeSlice[Point]
type RenderViewResource = object of Resource
setRender: bool = false
view: rv.RenderView
type ReadChannelResource = object of Resource
channel: Arc[BaseChannel]
listenId: ListenId
type WriteChannelResource = object of Resource
channel: Arc[BaseChannel]
type ProcessResource = object of Resource
process: AsyncProcess
stdin: Arc[BaseChannel]
stdout: Arc[BaseChannel]
stderr: Arc[BaseChannel]
type
HostContext* = ref object
services: Services
platform: Platform
commands*: CommandServiceImpl
registers*: Registers
mTerminals*: TerminalService
editors*: DocumentEditorService
layout*: LayoutService
plugins*: PluginService
settings*: ConfigStore
vfsService*: VFSService
events*: EventService
sessions*: SessionService
vfs*: VFS
moves*: MoveDatabase
timer*: Timer
InstanceData* = object of InstanceDataWasi
resources*: WasmModuleResources
isMainThread: bool
engine: ptr WasmEngineT
linker: ptr LinkerT
module: ptr ModuleT
instance: InstanceT
store: ptr StoreT
host: HostContext
vfs: VFS
permissions: PluginPermissions
commands: seq[CommandId]
customRenderers: seq[tuple[editor: TextDocumentEditor, id: CustomRendererId]]
namespace: string
args: string
destroyRequested: Atomic[bool]
timer*: Timer
eventsId*: Id
ResourceRegistry* = object
lock*: Lock
resources*: Table[string, ptr Resource]
var gResourceRegistry = ResourceRegistry()
gResourceRegistry.lock.initLock()
proc openGlobalResource*(path: string, T: typedesc): Option[T] {.gcsafe.} =
var resource: ptr Resource = nil
var registry = ({.gcsafe.}: gResourceRegistry.addr)
withLock(registry.lock):
if registry.resources.take(path, resource):
if not (resource[] of T):
registry.resources[path] = resource
return T.none
else:
return T.none
assert resource != nil
let typedResource = cast[ptr T](resource)
var res: T
swap(res, typedResource[])
freeShared(typedResource)
return res.some
proc mountGlobalResource*[T: Resource](path: string, resource: sink T, unique: bool): string {.gcsafe.} =
var path = path
if unique:
path.add "-" & $newId()
var resourcePtr = createShared(T)
resourcePtr[] = resource.ensureMove
let registry = ({.gcsafe.}: gResourceRegistry.addr)
withLock(registry.lock):
registry.resources[path] = resourcePtr
return path
proc getMemoryFor(instance: ptr InstanceData, caller: ptr CallerT): Option[ExternT] =
ExternT.none
# var item: ExternT
# item.kind = WASMTIME_EXTERN_SHAREDMEMORY
# item.of_field.sharedmemory = host.sharedMemory
# item.some
proc getMemoryFor(host: HostContext, caller: ptr CallerT): Option[ExternT] =
ExternT.none
# var item: ExternT
# item.kind = WASMTIME_EXTERN_SHAREDMEMORY
# item.of_field.sharedmemory = host.sharedMemory
# item.some
proc getMemory*(caller: ptr CallerT, store: ptr ContextT, host: HostContext): WasmMemory =
var mainMemory = caller.getExport("memory")
if mainMemory.isNone:
mainMemory = host.getMemoryFor(caller)
if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY:
return initWasmMemory(mainMemory.get.of_field.sharedmemory)
elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY:
return initWasmMemory(store, mainMemory.get.of_field.memory.addr)
else:
assert false
func createRope(str: string): Rope =
Rope.new(str)
proc `=destroy`*(self: RenderViewResource) =
if self.setRender and self.view != nil:
self.view.onRender = nil
proc `=destroy`*(self: ReadChannelResource) =
if self.channel.isNotNil:
when defined(debugChannelDestroy):
echo "=destroy ReadChannelResource ", self.channel.count
`=destroy`(self.channel)
proc `=destroy`*(self: WriteChannelResource) =
if self.channel.isNotNil:
when defined(debugChannelDestroy):
echo "=destroy WriteChannelResource ", self.channel.count
`=destroy`(self.channel)
when defined(witRebuild):
static: hint("Rebuilding plugin_api.wit")
importWit "../../wit/v0/api.wit", InstanceData:
world = "plugin"
cacheFile = "../generated/plugin_api_host.nim"
mapName "rope", RopeResource
mapName "render-view", RenderViewResource
mapName "read-channel", ReadChannelResource
mapName "write-channel", WriteChannelResource
mapName "process", ProcessResource
mapName "shared-buffer", SharedBufferResource
else:
static: hint("Using cached plugin_api.wit (plugin_api_host.nim)")
{.push hint[XDeclaredButNotUsed]:off.}
include generated/plugin_api_host
{.pop.}
type
InstanceDataImpl = object of InstanceData
funcs: ExportedFuncs
WasmModuleInstanceImpl* = ref object of WasmModuleInstance
instance*: Arc[InstanceDataImpl]
###################################### PluginApi #####################################
type
PluginApi* = ref object of PluginApiBase
engine: ptr WasmEngineT
linkerWasiNone: ptr LinkerT
linkerWasiReduced: ptr LinkerT
linkerWasiFull: ptr LinkerT
host: HostContext
instances: seq[WasmModuleInstanceImpl]
dynamicInstanceData: Arc[InstanceDataImpl]
proc terminals(host: HostContext): TerminalService =
if host.mTerminals == nil:
host.mTerminals = host.services.getService(TerminalService).get(nil)
return host.mTerminals
method init*(self: PluginApi, services: Services, engine: ptr WasmEngineT) =
self.host = HostContext()
self.host.services = services
self.host.platform = services.getService(PlatformService).get.platform
self.host.commands = services.getService(CommandServiceImpl).get
self.host.registers = services.getService(Registers).get
self.host.editors = services.getService(DocumentEditorService).get
self.host.layout = services.getService(LayoutService).get
self.host.plugins = services.getService(PluginService).get
self.host.settings = services.getService(ConfigService).get.runtime
self.host.vfsService = services.getService(VFSService).get
self.host.events = services.getService(EventService).get
self.host.sessions = services.getService(SessionService).get
self.host.vfs = self.host.vfsService.vfs
self.host.moves = services.getService(MoveDatabase).get
self.host.timer = startTimer()
self.engine = engine
self.linkerWasiNone = engine.newLinker()
self.linkerWasiReduced = engine.newLinker()
self.linkerWasiFull = engine.newLinker()
proc getMemory(caller: ptr CallerT, store: ptr ContextT): WasmMemory =
var mainMemory = caller.getExport("memory")
# if mainMemory.isNone:
# mainMemory = host.getMemoryFor(caller)
if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY:
return initWasmMemory(mainMemory.get.of_field.sharedmemory)
elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY:
return initWasmMemory(store, mainMemory.get.of_field.memory.addr)
else:
assert false
# Link wasi
self.linkerWasiReduced.definePluginWasi(getMemory).okOr(e):
log lvlError, "Failed to define wasi imports: " & e.msg
return
self.linkerWasiFull.defineWasi().okOr(e):
log lvlError, "Failed to define wasi imports: " & e.msg
return
# Link plugin API
defineComponent(self.linkerWasiNone).okOr(err):
log lvlError, "Failed to define component: " & err.msg
return
defineComponent(self.linkerWasiReduced).okOr(err):
log lvlError, "Failed to define component: " & err.msg
return
defineComponent(self.linkerWasiFull).okOr(err):
log lvlError, "Failed to define component: " & err.msg
return
var instanceData = Arc[InstanceDataImpl].new()
instanceData.getMut.isMainThread = true
instanceData.getMut.store = self.engine.newStore(instanceData.get.addr, nil)
instanceData.getMut.engine = self.engine
# instanceData.getMut.module = module
# instanceData.getMut.permissions = instance.permissions
instanceData.getMut.namespace = "#dynamic"
instanceData.getMut.host = self.host
instanceData.getMut.stdin = newInMemoryChannel()
instanceData.getMut.stdout = newInMemoryChannel()
instanceData.getMut.stderr = newInMemoryChannel()
instanceData.getMut.timer = startTimer()
self.dynamicInstanceData = instanceData
method setPermissions*(instance: WasmModuleInstanceImpl, permissions: PluginPermissions) =
instance.instance.getMut.permissions = permissions
method createModule*(self: PluginApi, module: ptr ModuleT, plugin: Plugin, state: seq[uint8]): WasmModuleInstance =
var instanceData = Arc[InstanceDataImpl].new()
instanceData.getMut.isMainThread = true
instanceData.getMut.store = self.engine.newStore(instanceData.get.addr, nil)
instanceData.getMut.engine = self.engine
instanceData.getMut.module = module
instanceData.getMut.permissions = plugin.permissions
instanceData.getMut.namespace = plugin.manifest.id
instanceData.getMut.host = self.host
instanceData.getMut.stdin = newInMemoryChannel()
instanceData.getMut.stdout = newInMemoryChannel()
instanceData.getMut.stderr = newInMemoryChannel()
instanceData.getMut.timer = startTimer()
instanceData.getMut.eventsId = newId()
let ctx = instanceData.get.store.context
let wasiConfig = newWasiConfig()
wasiConfig.inheritStdin()
wasiConfig.inheritStderr()
wasiConfig.inheritStdout()
if not plugin.permissions.filesystemRead.disallowAll.get(false):
for dir in plugin.permissions.wasiPreopenDirs:
var dirPermissions: csize_t = 0
var filePermissions: csize_t = 0
if dir.read:
dirPermissions = dirPermissions or WasiDirPermsRead.csize_t
filePermissions = filePermissions or WasiFilePermsRead.csize_t
if dir.write:
dirPermissions = dirPermissions or WasiDirPermsWrite.csize_t
filePermissions = filePermissions or WasiFilePermsWrite.csize_t
discard wasiConfig.preopenDir(dir.host.cstring, dir.guest.cstring, dirPermissions, filePermissions)
ctx.setWasi(wasiConfig).toResult(void).okOr(err):
log lvlError, "Failed to setup wasi: " & err.msg
return
let linker = case plugin.permissions.wasi.get(Reduced)
of None: self.linkerWasiNone
of Reduced: self.linkerWasiReduced
of Full: self.linkerWasiFull
instanceData.getMut.linker = linker
var trap: ptr WasmTrapT = nil
instanceData.getMut.instance = linker.instantiate(ctx, module, trap.addr).okOr(err):
log lvlError, "Failed to create module instance: " & err.msg
return
trap.okOr(err):
log lvlError, "Failed to create module instance: " & err.msg
return
let errors = collectExports(instanceData.getMut.funcs, instanceData.get.instance, ctx)
if errors.len > 0:
for e in errors:
log lvlWarn, e
let instance = WasmModuleInstanceImpl(instance: instanceData)
self.instances.add(instance)
instanceData.get.funcs.initPlugin().okOr(err):
log lvlError, "Failed to call init-plugin: " & err.msg
self.instances.removeShift(instance)
return
if state.len > 0:
instanceData.get.funcs.loadPluginState(state).okOr(err):
log lvlError, "Failed to call load-plugin-state: " & err.msg
self.instances.removeShift(instance)
return
let options = sca.CreateTerminalOptions(
group: plugin.manifest.id,
)
if self.host.terminals != nil:
let view = self.host.terminals.createTerminalView(instanceData.get.stdin, instanceData.get.stdout, options)
self.host.layout.registerView(view, last = false)
return instance
method savePluginState*(self: PluginApi, instance: WasmModuleInstance): seq[uint8] =
return instance.WasmModuleInstanceImpl.instance.get.funcs.savePluginState().okOr(@[])
method destroyInstance*(self: PluginApi, instance: WasmModuleInstance) =
let instance = instance.WasmModuleInstanceImpl
let instanceData = instance.instance
self.host.events.stopListen(instanceData.get.eventsId)
for commandId in instanceData.get.commands:
self.host.commands.unregisterCommand(commandId)
for cmd in instanceData.get.customRenderers:
cmd.editor.decorations.removeCustomRenderer(cmd.id)
instanceData.getMutUnsafe.resources.dropResources(instanceData.get.store.context, callDestroy = true)
instanceData.get.store.delete()
self.instances.removeShift(instance)
template funcs(instance: ptr InstanceData): var ExportedFuncs = cast[ptr InstanceDataImpl](instance).funcs
proc cloneInstance*(instance: ptr InstanceData): Arc[InstanceDataImpl] =
var instanceData = Arc[InstanceDataImpl].new()
instanceData.getMut.isMainThread = false
instanceData.getMut.store = instance.engine.newStore(instanceData.get.addr, nil)
instanceData.getMut.engine = instance.engine
instanceData.getMut.linker = instance.linker
instanceData.getMut.module = instance.module
instanceData.getMut.permissions = instance.permissions
instanceData.getMut.namespace = instance.namespace
instanceData.getMut.host = instance.host
instanceData.getMut.timer = startTimer()
instanceData.getMut.eventsId = newId()
let ctx = instanceData.get.store.context
let wasiConfig = newWasiConfig()
wasiConfig.inheritStdin()
wasiConfig.inheritStderr()
wasiConfig.inheritStdout()
if not instance.permissions.filesystemRead.disallowAll.get(false):
for dir in instance.permissions.wasiPreopenDirs:
var dirPermissions: csize_t = 0
var filePermissions: csize_t = 0
if dir.read:
dirPermissions = dirPermissions or WasiDirPermsRead.csize_t
filePermissions = filePermissions or WasiFilePermsRead.csize_t
if dir.write:
dirPermissions = dirPermissions or WasiDirPermsWrite.csize_t
filePermissions = filePermissions or WasiFilePermsWrite.csize_t
discard wasiConfig.preopenDir(dir.host.cstring, dir.guest.cstring, dirPermissions, filePermissions)
ctx.setWasi(wasiConfig).toResult(void).okOr(err):
log lvlError, "Failed to setup wasi: " & err.msg
return
var trap: ptr WasmTrapT = nil
instanceData.getMut.instance = instance.linker.instantiate(ctx, instance.module, trap.addr).okOr(err):
log lvlError, "Failed to create module instance: " & err.msg
return
trap.okOr(err):
log lvlError, "Failed to create module instance: " & err.msg
return
discard collectExports(instanceData.getMut.funcs, instanceData.get.instance, ctx)
return instanceData
proc runInstanceThread(instance: sink Arc[InstanceDataImpl]) =
instance.getMutUnsafe.isMainThread = false
instance.get.funcs.initPlugin().okOr(_):
return
while not instance.getMutUnsafe.destroyRequested.load():
poll(5)
instance.getMutUnsafe.resources.dropResources(instance.get.store.context, callDestroy = true)
instance.get.store.delete()
# todo: make the size configurable
var threadPool = newPluginThreadPool[InstanceDataImpl](10, runInstanceThread)
###################################### Conversion functions #####################################
converter toPoint(c: Cursor): Point = point(c.line.int, c.column.int)
converter toInternal(c: Cursor): sca.Cursor = (c.line.int, c.column.int)
converter toInternal(c: Selection): sca.Selection = (c.first.toInternal, c.last.toInternal)
converter toInternal(c: Lamport): clock.Lamport = clock.Lamport(replicaId: clock.ReplicaId(c.replicaId), value: clock.SeqNumber(c.value))
converter toInternal(c: Bias): sumtree.Bias =
case c
of Left: sumtree.Left
of Right: sumtree.Right
converter toInternal(c: Anchor): buffer.Anchor = buffer.Anchor(timestamp: c.timestamp, offset: c.offset.int, bias: c.bias)
converter toInternal(c: (Anchor, Anchor)): (buffer.Anchor, buffer.Anchor) = (c[0].toInternal, c[1].toInternal)
converter toInternal(c: ScrollBehaviour): sca.ScrollBehaviour =
case c
of CenterAlways: sca.CenterAlways
of CenterOffscreen: sca.CenterOffscreen
of CenterMargin: sca.CenterMargin
of ScrollToMargin: sca.ScrollToMargin
of TopOfScreen: sca.TopOfScreen
converter toInternal(c: OverlayRenderLocation): overlay_map.OverlayRenderLocation =
case c
of Inline: overlay_map.OverlayRenderLocation.Inline
of Below: overlay_map.OverlayRenderLocation.Below
of Above: overlay_map.OverlayRenderLocation.Above
converter toWasm(c: sca.Cursor): Cursor = Cursor(line: c.line.int32, column: c.column.int32)
converter toWasm(c: sca.Selection): Selection = Selection(first: c.first.toWasm, last: c.last.toWasm)
converter toWasm(c: clock.Lamport): Lamport = Lamport(replicaId: c.replicaId.uint16, value: c.value.uint32)
converter toWasm(c: sumtree.Bias): Bias =
case c
of sumtree.Left: Left
of sumtree.Right: Right
converter toWasm(c: buffer.Anchor): Anchor = Anchor(timestamp: c.timestamp, offset: c.offset.uint32, bias: c.bias)
converter toWasm(c: (buffer.Anchor, buffer.Anchor)): (Anchor, Anchor) = (c[0].toWasm, c[1].toWasm)
converter toWasm(c: vmath.Vec2): Vec2f = Vec2f(x: c.x, y: c.y)
converter toInternal(flags: ReadFlags): set[vfs.ReadFlag] =
result = {}
if ReadFlag.Binary in flags:
result.incl vfs.ReadFlag.Binary
###################################### API implementations #####################################
proc editorActiveEditor*(instance: ptr InstanceData, options: ActiveEditorFlags): Option[Editor] =
if instance.host == nil:
return
if ActiveEditorFlag.IncludeCommandLine in options and instance.host.commands.commandLineMode():
return Editor(id: instance.host.commands.commandLineEditor.id.uint64).some
if ActiveEditorFlag.IncludePopups in options and instance.host.layout.popups.len > 0 and instance.host.layout.popups.last.getActiveEditor().getSome(editor):
return Editor(id: editor.id.uint64).some
if instance.host.layout.tryGetCurrentEditorView().getSome(view):
return Editor(id: view.editor.id.uint64).some
return Editor.none
proc editorGetDocument*(instance: ptr InstanceData; editor: Editor): Option[Document] =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor):
let document = editor.getDocument()
if document != nil:
return Document(id: document.id.uint64).some
return Document.none
proc textEditorActiveTextEditor*(instance: ptr InstanceData, options: ActiveEditorFlags): Option[TextEditor] =
if instance.host == nil:
return
if ActiveEditorFlag.IncludeCommandLine in options and instance.host.commands.commandLineMode() and instance.host.commands.commandLineEditor of TextDocumentEditor:
return TextEditor(id: instance.host.commands.commandLineEditor.id.uint64).some
if ActiveEditorFlag.IncludePopups in options and instance.host.layout.popups.len > 0 and instance.host.layout.popups.last.getActiveEditor().getSome(editor) and editor of TextDocumentEditor:
return TextEditor(id: editor.id.uint64).some
if instance.host.layout.tryGetCurrentEditorView().getSome(view) and view.editor of TextDocumentEditor:
return TextEditor(id: view.editor.TextDocumentEditor.id.uint64).some
return TextEditor.none
proc textEditorGetDocument*(instance: ptr InstanceData; editor: TextEditor): Option[TextDocument] =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor):
let document = editor.getDocument()
if document != nil and document of text_document.TextDocument:
return TextDocument(id: document.id.uint64).some
return TextDocument.none
proc textEditorAllTextEditors*(instance: ptr InstanceData): seq[TextEditor] =
if instance.host == nil:
return
for editor in instance.host.editors.allEditors:
if editor of TextDocumentEditor:
result.add TextEditor(id: editor.TextDocumentEditor.id.uint64)
proc textEditorAsTextEditor*(instance: ptr InstanceData; editor: Editor): Option[TextEditor] =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
return TextEditor(id: editor.TextDocumentEditor.id.uint64).some
return TextEditor.none
proc textEditorAsTextDocument*(instance: ptr InstanceData; document: Document): Option[TextDocument] =
if instance.host == nil:
return
if instance.host.editors.getDocument(document.id.DocumentId).getSome(document) and document of text_document.TextDocument:
return TextDocument(id: text_document.TextDocument(document).id.uint64).some
return TextDocument.none
proc textEditorLineLength*(instance: ptr InstanceData; editor: TextEditor; line: int32): int32 =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
return editor.TextDocumentEditor.lineLength(line.int).int32
proc textEditorClearTabStops*(instance: ptr InstanceData; editor: TextEditor): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
editor.TextDocumentEditor.clearTabStops()
proc textEditorUndo*(instance: ptr InstanceData; editor: TextEditor): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
editor.TextDocumentEditor.undo()
proc textEditorRedo*(instance: ptr InstanceData; editor: TextEditor): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
editor.TextDocumentEditor.redo()
proc textEditorStartTransaction*(instance: ptr InstanceData; editor: TextEditor): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
editor.TextDocumentEditor.startTransaction()
proc textEditorEndTransaction*(instance: ptr InstanceData; editor: TextEditor): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
editor.TextDocumentEditor.endTransaction()
proc textEditorCopy*(instance: ptr InstanceData; editor: TextEditor, register: sink string, inclusiveEnd: bool): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
editor.TextDocumentEditor.copy(register, inclusiveEnd)
proc textEditorPaste*(instance: ptr InstanceData; editor: TextEditor; selections: sink seq[Selection], register: sink string, inclusiveEnd: bool): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
asyncSpawn editor.TextDocumentEditor.pasteAsync(selections.mapIt(it.toInternal), register, inclusiveEnd)
proc textEditorAutoShowCompletions*(instance: ptr InstanceData; editor: TextEditor): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
editor.TextDocumentEditor.autoShowCompletions()
proc textEditorApplyMove*(instance: ptr InstanceData; editor: TextEditor; selection: Selection; move: sink string; count: int32; wrap: bool; includeEol: bool): seq[Selection] =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
let textEditor = editor.TextDocumentEditor
return textEditor.getSelectionsForMove(@[selection.toInternal], move, count, includeEol, wrap).mapIt(it.toWasm)
proc textEditorMultiMove*(instance: ptr InstanceData; editor: TextEditor; selections: sink seq[Selection]; move: sink string; count: int32; wrap: bool; includeEol: bool): seq[Selection] =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
let textEditor = editor.TextDocumentEditor
return textEditor.getSelectionsForMove(selections.mapIt(it.toInternal), move, count, includeEol, wrap).mapIt(it.toWasm)
proc textEditorSetSelection*(instance: ptr InstanceData; editor: TextEditor; s: Selection): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
let textEditor = editor.TextDocumentEditor
textEditor.selection = ((s.first.line.int, s.first.column.int), (s.last.line.int, s.last.column.int))
proc textEditorSetSelections*(instance: ptr InstanceData; editor: TextEditor; s: sink seq[Selection]): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
let textEditor = editor.TextDocumentEditor
if s.len > 0:
textEditor.selections = s.mapIt(it.toInternal)
proc textEditorGetSelection*(instance: ptr InstanceData; editor: TextEditor): Selection =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
let textEditor = editor.TextDocumentEditor
let s = textEditor.selection
Selection(first: Cursor(line: s.first.line.int32, column: s.first.column.int32), last: Cursor(line: s.last.line.int32, column: s.last.column.int32))
else:
Selection(first: Cursor(line: 1, column: 2), last: Cursor(line: 6, column: 9))
proc textEditorGetSelections*(instance: ptr InstanceData; editor: TextEditor): seq[Selection] =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
return editor.TextDocumentEditor.selections.mapIt(it.toWasm)
proc textEditorEdit*(instance: ptr InstanceData; editor: TextEditor; selections: sink seq[Selection]; contents: sink seq[string], inclusive: bool): seq[Selection] =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
let selections = selections.mapIt(it.toInternal)
let res = editor.TextDocumentEditor.edit(selections, contents, inclusiveEnd = inclusive)
return res.mapIt(it.toWasm)
return selections
proc textEditorDefineMove*(instance: ptr InstanceData; move: sink string; fun: uint32; data: uint32): void =
if instance.host == nil:
return
proc moveImpl(rope: Rope, move: string, selections: openArray[sca.Selection], count: int, includeEol: bool): seq[sca.Selection] {.gcsafe, raises: [].} =
var ropeRes = RopeResource(rope: rope.slice().suffix(Point()))
let index = instance.resources.resourceNew(instance.store.context, ropeRes)
if index.isOk:
let res = instance.funcs.handleMove(fun, data, index.val.uint32, selections.mapIt(it.toWasm), count.int32, includeEol)
if res.isErr:
log lvlError, "Failed to call handleMove: " & res.err.msg
else:
return res.val.mapIt(it.toInternal)
return @[]
instance.host.moves.registerMove(move, moveImpl)
proc textEditor_addModeChangedHandler*(instance: ptr InstanceData, fun: uint32): int32 =
if instance.host == nil:
return
if instance.host.layout.tryGetCurrentEditorView().getSome(view) and view.editor of TextDocumentEditor:
let editor = view.editor.TextDocumentEditor
discard editor.onModeChanged.subscribe proc(args: tuple[removed: seq[string], added: seq[string]]) =
let res = instance.funcs.handleModeChanged(fun, $args.removed, $args.added)
if res.isErr:
log lvlError, "Failed to call handleModeChanged: " & res.err.msg
return 0
proc textEditorSetMode*(instance: ptr InstanceData; editor: TextEditor, mode: sink string, exclusive: bool): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
editor.TextDocumentEditor.setMode(mode, exclusive)
proc textEditorMode*(instance: ptr InstanceData; editor: TextEditor): string =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
return editor.TextDocumentEditor.mode()
proc textEditorModes*(instance: ptr InstanceData; editor: TextEditor): seq[string] =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
return editor.TextDocumentEditor.modes()
proc textEditorHideCompletions*(instance: ptr InstanceData; editor: TextEditor) =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
editor.TextDocumentEditor.hideCompletions()
proc textEditorScrollToCursor*(instance: ptr InstanceData; editor: TextEditor; behaviour: Option[ScrollBehaviour]; relativePosition: float32): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
editor.TextDocumentEditor.scrollToCursor(sca.SelectionCursor.Last, scrollBehaviour = behaviour.mapIt(it.toInternal), relativePosition=relativePosition)
proc textEditorUpdateTargetColumn*(instance: ptr InstanceData; editor: TextEditor): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
editor.TextDocumentEditor.updateTargetColumn()
proc textEditorCommand*(instance: ptr InstanceData; editor: TextEditor, name: sink string, arguments: sink string): Result[string, CommandError] =
if instance.host == nil:
return
if not instance.host.commands.checkPermissions(name, instance.permissions.commands):
result.err(CommandError.NotAllowed)
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
if editor.handleAction(name, arguments, true).getSome(res):
return results.ok($res)
result.err(CommandError.NotFound)
proc textEditorRecordCurrentCommand*(instance: ptr InstanceData; editor: TextEditor; registers: sink seq[string]): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
editor.TextDocumentEditor.commandComponent.recordCurrentCommand(registers)
proc textEditorGetUsage*(instance: ptr InstanceData; editor: TextEditor): string =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
return editor.TextDocumentEditor.getUsage()
proc textEditorGetRevision*(instance: ptr InstanceData; editor: TextEditor): int32 =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
return editor.TextDocumentEditor.getRevision().int32
proc textEditorContent*(instance: ptr InstanceData; editor: TextEditor): RopeResource =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
let textEditor = editor.TextDocumentEditor
if textEditor.document != nil:
return RopeResource(rope: textEditor.document.rope.clone().slice().suffix(Point()))
return RopeResource(rope: createRope("").slice().suffix(Point()))
proc textDocumentContent*(instance: ptr InstanceData; document: TextDocument): RopeResource =
if instance.host == nil:
return
if instance.host.editors.getDocument(document.id.DocumentId).getSome(document) and document of text_document.TextDocument:
let textDocument = text_document.TextDocument(document)
return RopeResource(rope: textDocument.rope.clone().slice().suffix(Point()))
return RopeResource(rope: createRope("").slice().suffix(Point()))
proc textDocumentPath*(instance: ptr InstanceData; document: TextDocument): string =
if instance.host == nil:
return
if instance.host.editors.getDocument(document.id.DocumentId).getSome(document):
return document.filename
return ""
proc textEditorGetSettingRaw*(instance: ptr InstanceData, editor: TextEditor, name: sink string): string =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
return $editor.TextDocumentEditor.config.get(name, newJexNull())
proc textEditorSetSettingRaw*(instance: ptr InstanceData, editor: TextEditor, name: sink string, value: sink string) =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
try:
# todo: permissions
editor.TextDocumentEditor.config.set(name, parseJsonex(value))
except CatchableError as e:
log lvlError, &"set-setting-raw: Failed to set setting '{name}' to {value}: {e.msg}"
proc textEditorSetSearchQueryFromMove*(instance: ptr InstanceData, editor: TextEditor, move: sink string, count: int32, prefix: sink string, suffix: sink string): Selection =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
return editor.TextDocumentEditor.setSearchQueryFromMove(move, count, prefix, suffix)
proc textEditorSetSearchQuery*(instance: ptr InstanceData, editor: TextEditor, query: sink string, escapeRegex: bool, prefix: sink string, suffix: sink string): bool =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
return editor.TextDocumentEditor.setSearchQuery(query, escapeRegex, prefix, suffix)
proc textEditorGetSearchQuery*(instance: ptr InstanceData, editor: TextEditor): string =
if instance.host == nil:
return ""
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
return editor.TextDocumentEditor.getSearchQuery()
return ""
proc textEditorToggleLineComment*(instance: ptr InstanceData, editor: TextEditor) =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
editor.TextDocumentEditor.toggleLineComment()
proc textEditorInsertText*(instance: ptr InstanceData, editor: TextEditor, text: sink string, autoIndent: bool) =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
editor.TextDocumentEditor.insertText(text, autoIndent)
proc textEditorOpenSearchBar*(instance: ptr InstanceData; editor: TextEditor; query: sink string; scrollToPreview: bool; selectResult: bool): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
editor.TextDocumentEditor.openSearchBar(query, scrollToPreview, selectResult)
proc textEditorEvaluateExpressions*(instance: ptr InstanceData; editor: TextEditor; selections: sink seq[Selection]; inclusive: bool; prefix: sink string; suffix: sink string; addSelectionIndex: bool): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
editor.TextDocumentEditor.evaluateExpressions(selections.mapIt(it.toInternal), inclusive, prefix, suffix, addSelectionIndex)
proc textEditorIndent*(instance: ptr InstanceData; editor: TextEditor; delta: int32): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
if delta >= 0:
for i in 0..<delta:
editor.TextDocumentEditor.indent()
else:
for i in 0..<(-delta):
editor.TextDocumentEditor.unindent()
proc textEditorGetCommandCount*(instance: ptr InstanceData; editor: TextEditor): int32 =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
return editor.TextDocumentEditor.getCommandCount().int32
proc textEditorGetVisibleLineCount*(instance: ptr InstanceData; editor: TextEditor): int32 =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
return editor.TextDocumentEditor.screenLineCount().int32
proc textEditorSetCursorScrollOffset*(instance: ptr InstanceData; editor: TextEditor; cursor: Cursor; scrollOffset: float32): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
editor.TextDocumentEditor.setCursorScrollOffset(cursor.toInternal, scrollOffset)
proc textEditorCreateAnchors*(instance: ptr InstanceData; editor: TextEditor; selections: sink seq[Selection]): seq[(Anchor, Anchor)] =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
return editor.TextDocumentEditor.createAnchors(selections.mapIt(it.toInternal)).mapIt(it.toWasm)
proc textEditorResolveAnchors*(instance: ptr InstanceData; editor: TextEditor; anchors: sink seq[(Anchor, Anchor)]): seq[Selection] =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
return editor.TextDocumentEditor.resolveAnchors(anchors.mapIt(it.toInternal)).mapIt(it.toWasm)
proc textEditorAddCustomRenderCallback*(instance: ptr InstanceData; editor: TextEditor; fun: uint32; data: uint32): int64 =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
let id = editor.TextDocumentEditor.decorations.addCustomRenderer proc(id: int, size: Vec2, localOffset: int, commands: var RenderCommands): Vec2 =
try:
let ret = instance.funcs.handleTextOverlayRender(fun, data, id, size.toWasm, localOffset.int32).okOr(err):
log lvlWarn, "Failed to call custom render callback: " & err.msg
return
let wasmBufferLen = (ret shr 32).uint32.int
let wasmBufferAddr = cast[uint32](ret)
discard instance.funcs.mem[(wasmBufferAddr.int + wasmBufferLen - 1).WasmPtr] # crash if out of bounds. todo: replace this with bounds check
let width = instance.funcs.mem.read[:float32](wasmBufferAddr.WasmPtr)
let height = instance.funcs.mem.read[:float32]((wasmBufferAddr.int + sizeof(float32)).WasmPtr)
let wasmBuffer = cast[ptr UncheckedArray[byte]](instance.funcs.mem.getRawPtr((wasmBufferAddr + sizeof(float32) * 2).WasmPtr))
if wasmBuffer != nil:
var decoder = BinaryDecoder.init(wasmBuffer.toOpenArray(0, wasmBufferLen - sizeof(float32) * 2 - 1))
for command in decoder.decodeRenderCommands():
commands.commands.add(command)
else:
log lvlWarn, &"failed to get wasm buffer address"
return vec2(width, height)
except CatchableError as e:
log lvlWarn, &"Failed to run custom render: {e.msg}"
echo e.getStackTrace()
instance.customRenderers.add((editor.TextDocumentEditor, id))
return id.int64
proc textEditorRemoveCustomRenderCallback*(instance: ptr InstanceData; editor: TextEditor; cb: int64): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
editor.TextDocumentEditor.decorations.removeCustomRenderer(cb.CustomRendererId)
for i in 0..instance.customRenderers.high:
if instance.customRenderers[i].editor == editor.TextDocumentEditor and instance.customRenderers[i].id.int64 == cb:
instance.customRenderers.removeSwap(i)
break
proc textEditorAddOverlay*(instance: ptr InstanceData; editor: TextEditor; selections: Selection; text: sink string; id: int64; scope: sink string; bias: Bias; renderId: int64; location: OverlayRenderLocation): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
editor.TextDocumentEditor.addOverlay(selections.toInternal, text, id.int, scope, bias.toInternal, renderId.int, location.toInternal)
proc textEditorClearOverlays*(instance: ptr InstanceData; editor: TextEditor; id: int64): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
editor.TextDocumentEditor.clearOverlays(id.int)
proc textEditorAllocateOverlayId*(instance: ptr InstanceData; editor: TextEditor): int64 =
if instance.host == nil:
return -1
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
let overlay = editor.TextDocumentEditor.displayMap.overlay
return overlay.allocateId().get(-1).int64
return -1
proc textEditorReleaseOverlayId*(instance: ptr InstanceData; editor: TextEditor; id: int64): void =
if instance.host == nil:
return
if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor:
editor.TextDocumentEditor.displayMap.overlay.releaseId(id.int)
proc typesNewSharedBuffer*(instance: ptr InstanceData, size: int64): SharedBufferResource =
return SharedBufferResource(buffer: SharedBuffer.new(size))
proc typesCloneRef*(instance: ptr InstanceData; self: var SharedBufferResource): SharedBufferResource =
return self
proc typesLen*(instance: ptr InstanceData; self: var SharedBufferResource): int64 =
if self.buffer.isNil:
return 0
return self.buffer.len
proc typesWriteString*(instance: ptr InstanceData; self: var SharedBufferResource; index: int64; data: sink string): void =
if self.buffer.isNil or index + data.len > self.buffer.len:
log lvlError, &"Buffer write out of bounds: {index}..<{index + data.len} notin 0..<{self.buffer.len}"
return
self.buffer.write(index, data)
proc typesWrite*(instance: ptr InstanceData; self: var SharedBufferResource; index: int64; data: sink seq[uint8]): void =
if self.buffer.isNil or index + data.len > self.buffer.len:
log lvlError, &"Buffer write out of bounds: {index}..<{index + data.len} notin 0..<{self.buffer.len}"
return
self.buffer.write(index, data)
proc typesReadInto*(instance: ptr InstanceData; self: var SharedBufferResource; index: int64; dst: uint32; len: int32): void =
if self.buffer.isNil or len <= 0 or index + len > self.buffer.len:
log lvlError, &"Buffer read out of bounds: {index}..<{index + len} notin 0..<{self.buffer.len}"
return
discard instance.funcs.mem[(dst.int + len.int - 1).WasmPtr] # crash if out of bounds. todo: replace this with bounds check
let wasmBuffer = instance.funcs.mem.getRawPtr(dst.WasmPtr)
if wasmBuffer != nil:
self.buffer.readInto(index, wasmBuffer.toOpenArray(0, len - 1))
proc typesRead*(instance: ptr InstanceData; self: var SharedBufferResource; index: int64; len: int32): seq[uint8] =
if self.buffer.isNil or len <= 0 or index + len > self.buffer.len:
return @[]
result = newSeq[uint8](len)
self.buffer.readInto(0, result)
proc typesSharedBufferOpen*(instance: ptr InstanceData; path: sink string): Option[SharedBufferResource] =
let buff = openGlobalBuffer(path)
if buff.isSome:
return SharedBufferResource(buffer: buff.get).some
proc typesSharedBufferMount*(instance: ptr InstanceData; buffer: sink SharedBufferResource; path: sink string; unique: bool): string =
mountGlobalBuffer(path, buffer.buffer, unique)
proc typesNewRope*(instance: ptr InstanceData, content: sink string): RopeResource =
return RopeResource(rope: createRope(content).slice().suffix(Point()))
proc typesClone*(instance: ptr InstanceData, self: var RopeResource): RopeResource =
return RopeResource(rope: self.rope.clone())
proc typesRopeMount*(instance: ptr InstanceData; rope: sink RopeResource; path: sink string; unique: bool): string =
return mountGlobalResource(path, rope.ensureMove, unique)
proc typesRopeOpen*(instance: ptr InstanceData; path: sink string): Option[RopeResource] =
return openGlobalResource(path, RopeResource)