-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathindex.nim
1583 lines (1305 loc) · 55.5 KB
/
index.nim
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 / [async, jsffi, strutils, sequtils, sugar, dom, strformat, os, jsconsole]
import results
import lib, types, lang, paths, index_config, config, trace_metadata
import rr_gdb
import program_search
import ../common/ct_logging
# We have two main modes: server and desktop.
# By default we compile in desktop.
# In server mode we don't have electron, so we immitate or disable some of the code
# a lot of the logic is in index_config.nim/lib.nim and related
when defined(server):
var electronDebug: js = undefined
let app: ElectronApp = ElectronApp()
let globalShortcut: js = undefined
else:
var electronDebug = require("electron-debug")
let app = cast[ElectronApp](electron.app)
let globalShortcut = electron.globalShortcut
let Menu = electron.Menu
data.start = now()
var close = false
proc showOpenDialog(dialog: JsObject, browserWindow: JsObject, options: JsObject): Future[JsObject] {.importjs: "#.showOpenDialog(#,#)".}
proc loadExistingRecord(traceId: int) {.async.}
proc prepareForLoadingTrace(traceId: int, pid: int) {.async.}
proc isCtInstalled: bool
proc onClose(e: js) =
if data.config.test:
discard
elif not close:
# TODO refactor to use just `client.send`
mainWindow.webContents.send "CODETRACER::close", js{}
close = true
# proc call(dialog: JsObject, browserWindow: JsObject, options: JsObject): Future[JsObject] {.importjs: "#.showOpenDialog(#,#)".}
# <traceId>
# --port <port>
# --frontend-socket-port <frontend-socket-port>
# --frontend-socket-parameters <frontend-socket-parameters>
# --backend-socket-port <backend-socket-port>
# --caller-pid <callerPid>
# # eventually if needed --backend-socket-host <backend-socket-host>
proc parseArgs =
data.startOptions.screen = true
data.startOptions.loading = false
data.startOptions.record = false
if electronProcess.env.hasKey(cstring"CODETRACER_TRACE_ID"):
data.startOptions.traceID = electronProcess.env[cstring"CODETRACER_TRACE_ID"].parseJSInt
data.startOptions.inTest = electronProcess.env[cstring"CODETRACER_TEST"] == cstring"1"
callerProcessPid = electronProcess.env[cstring"CODETRACER_CALLER_PID"].parseJsInt
return
else:
discard
data.startOptions.folder = electronprocess.cwd()
if electronProcess.env.hasKey(cstring"CODETRACER_TEST_STRATEGY"):
data.startOptions.rawTestStrategy = electronProcess.env[cstring"CODETRACER_TEST_STRATEGY"]
infoPrint "RAW TEST STRATEGY:", data.startOptions.rawTestStrategy
let argsExceptNoSandbox = electronProcess.argv.filterIt(it != cstring"--no-sandbox")
# TODO electron or just node? server code compatibility
if argsExceptNoSandbox.len > 2:
var args = argsExceptNoSandbox[2 .. ^1]
var i = 0
while i < args.len:
let arg = args[i]
if arg == cstring"--bypass":
data.startOptions.screen = false
data.startOptions.loading = true
elif arg == cstring"--test":
data.startOptions.screen = false
data.startOptions.inTest = true
elif arg == cstring"--no-record":
data.startOptions.record = false
elif arg == cstring"edit":
data.startOptions.edit = true
data.startOptions.name = argsExceptNoSandbox[i + 3]
let file = fs.lstatSync(data.startOptions.name)
var folder = cstring""
if data.startOptions.name[0] == '/':
if cast[bool](file.isFile()):
folder = nodePath.dirname(data.startOptions.name) & cstring"/"
else:
folder = data.startOptions.name
data.startOptions.name = cstring""
if folder[folder.len - 1] != '/':
folder = folder & cstring"/"
else:
folder = electronprocess.cwd() & cstring"/"
data.startOptions.folder = folder
break
elif arg == cstring"--shell-ui":
data.startOptions.shellUi = true
data.startOptions.folder = electronprocess.cwd()
data.startOptions.traceID = -1
break
elif arg == cstring"--port":
if i + 1 < args.len:
data.startOptions.port = args[i + 1].parseJsInt
i += 2
continue
else:
errorPrint "expected --port <port>"
break
elif arg == cstring"--frontend-socket-port":
if i + 1 < args.len:
data.startOptions.frontendSocket.port = args[i + 1].parseJsInt
i += 2
continue
else:
errorPrint "expected --frontend-socket-port <frontend-socket-port>"
break
elif arg == cstring"--frontend-socket-parameters":
if i + 1 < args.len:
data.startOptions.frontendSocket.parameters = args[i + 1]
i += 2
continue
else:
errorPrint "expected --frontend-socket-parameters <frontend-socket-parameters>"
break
elif arg == cstring"--backend-socket-port":
if i + 1 < args.len:
data.startOptions.backendSocket.port = args[i + 1].parseJsInt
i += 2
continue
else:
errorPrint "expected --backend-socket-port <backend-socket-port>"
break
# elif arg == cstring"--backend-socket-parameters":
# if i + 1 < args.len:
# data.startOptions.backendSocket.parameters = args[i + 1]
# i += 2
# continue
# else:
# errorPrint "expected --backend-socket-parameters <backend-socket-parameters>"
# break
elif arg == cstring"--caller-pid":
if i + 1 < args.len:
callerProcessPid = args[i + 1].parseJsInt
i += 2
continue
else:
errorPrint "expected --caller-pid <caller-pid>"
break
elif not arg.isNaN:
data.startOptions.screen = false
data.startOptions.loading = true
data.startOptions.record = false
data.startOptions.traceID = arg.parseJSInt
data.startOptions.folder = electronprocess.cwd()
else:
discard
i += 1
else:
data.startOptions.traceID = -1
data.startOptions.welcomeScreen = true
data.startOptions.folder = electronprocess.cwd()
# "traceId=1", "test", "no-sandbox"
proc selectFileOrFolder(options: JsObject): Future[cstring] {.async.} =
let selection = await electron.dialog.showOpenDialog(mainWindow, options)
let filePaths = cast[seq[cstring]](selection.filePaths)
if filePaths.len > 0:
return filePaths[0]
else:
return cstring""
proc selectFiles(dialogTitle: cstring): Future[seq[cstring]] {.async.} =
let selection = await electron.dialog.showOpenDialog(
mainWindow,
js{
properties: @[j"openFile", j"multiSelections"],
title: dialogTitle,
buttonLabel: cstring"Select"})
if not selection.cancelled.to(bool):
return cast[seq[cstring]](selection.filePaths)
# tried to return a folder *with* a trailing slash, if it finds one
proc selectDir(dialogTitle: cstring, defaultPath: cstring = cstring""): Future[cstring] {.async.} =
let selection = await electron.dialog.showOpenDialog(
mainWindow,
js{
properties: @[cstring"openDirectory", cstring"showHiddenFiles"],
title: dialogTitle,
buttonLabel: cstring"Select",
defaultPath: defaultPath
}
)
let filePaths = cast[seq[cstring]](selection.filePaths)
if filePaths.len > 0:
var resultDir = filePaths[0]
if not ($resultDir).endsWith("/"):
resultDir.add(cstring"/")
return resultDir
else:
return cstring""
proc duration*(name: string) =
infoPrint fmt"index: TIME for {name}: {now() - data.start}ms"
# If codetracer has a 'broken' installation, only then do we attempt to install it
proc createMainWindow: js =
when not defined(server):
# TODO load from config
let iconPath = linksPath & "/resources/Icon.iconset/icon_256x256.png"
let win = jsnew electron.BrowserWindow(
js{
"title": j"CodeTracer",
"icon": iconPath,
"width": 1900,
"height": 1400,
"minWidth": 1050,
"minHeight": 600,
"webPreferences": js{
"nodeIntegration": true,
"contextIsolation": false,
"spellcheck": false
},
"frame": false,
"transparent": true,
})
win.on("maximize", proc() =
win.webContents.executeJavaScript("document.body.style.backgroundColor = 'black';"))
win.on("unmaximize", proc() =
win.webContents.executeJavaScript("document.body.style.backgroundColor = 'transparent';"))
win.maximize()
let url = "file://" & $codetracerExeDir & "/index.html"
win.loadURL(cstring(url))
win.on("close", onClose)
# TODO: eventually add a shortcut and ipc message that lets us
# open the dev tools directly from the interface, as in browsers
let inDevEnv = nodeProcess.env[cstring"CODETRACER_OPEN_DEV_TOOLS"] == cstring"1"
if inDevEnv:
electronDebug.devTools(win)
duration("opening the browser window from index")
return win
else:
# we make a test-only placeholder instance of it
let win = FrontendIPC(webContents: FrontendIPCSender())
return win.toJs
proc createInstallSubwindow(): js =
let win = jsnew electron.BrowserWindow(
js{
"width": 700,
"height": 422,
"resizable": false,
"parent": mainWindow,
"modal": true,
"webPreferences": js{
"nodeIntegration": true,
"contextIsolation": false,
"spellcheck": false
},
"frame": false,
"transparent": false,
})
let url = "file://" & $codetracerExeDir & "/subwindow.html"
debugPrint "Attempting to load: ", url
win.loadURL(cstring(url))
let inDevEnv = nodeProcess.env[cstring"CODETRACER_OPEN_DEV_TOOLS"] == cstring"1"
if inDevEnv:
electronDebug.devTools(win)
win.toJs
type
DebuggerInfo = object of JsObject
path: cstring
exe: seq[cstring]
#lang: Lang
proc onUpdateTable(sender: js, response: UpdateTableArgs) {.async.} =
discard debugger.updateTable(response)
proc onTracepointDelete(sender: js, response: TracepointId) {.async.} =
discard debugger.tracepointDelete(response)
proc onTracepointToggle(sender: js, response: TracepointId) {.async.} =
discard debugger.tracepointToggle(response)
proc onLoadCallstack(sender: js, response: LoadCallstackArg) {.async.} =
# debug "load ", id=response.codeID
try:
var callstack = await debugger.loadCallstack(response)
var id = j($response.codeID & " " & $response.withArgs)
# debug "ready ", id=id
mainWindow.webContents.send "CODETRACER::load-callstack-received", js{argId: id, value: callstack}
except:
errorPrint "loadCallstack: ", getCurrentExceptionMsg()
var id = j($response.codeID & " " & $response.withArgs)
let callstack: seq[Call] = @[]
mainWindow.webContents.send "CODETRACER::load-callstack-received", js{argId: id, value: callstack}
# TODO location?
proc onLoadCallArgs(sender: js, response: CalltraceLoadArgs) {.async.} =
discard debugger.loadCallArgs(response)
proc onCollapseCalls(sender: js, response: CollapseCallsArgs) =
discard debugger.collapseCalls(response)
proc onExpandCalls(sender: js, response: CollapseCallsArgs) =
discard debugger.expandCalls(response)
proc updateExpand(path: cstring, line: int, expansionFirstLine: int, update: MacroExpansionLevelUpdate) {.async.} =
warnPrint "update expansion disabled for now: needs a more stabilized version"
# let res = await debugger.updateExpansionLevel(path, line, update)
# mainWindow.webContents.send "CODETRACER::open-location", res
# case update.kind:
# of MacroUpdateCollapse:
# mainWindow.webContents.send "CODETRACER::collapse-expansion", js{path: path, line: line, expansionFirstLine: expansionFirstLine, update: update}
# of MacroUpdateCollapseAll:
# mainWindow.webContents.send "CODETRACER::collapse-all-expansion", js{path: path, line: line, expansionFirstLine: expansionFirstLine, update: update}
# else:
# discard
when not defined(server):
proc viewerMenu(location: types.Location, times: int): js =
# advanced menu is for cases where we want to filter the shape of the variable
var submenus: seq[JsObject] = @[]
submenus.add(js{
label: cstring"Expand macro invocation at this line",
click: proc(menuItem: js, win: js) {.async.} =
await updateExpand(location.path, location.line, location.expansionFirstLine, MacroExpansionLevelUpdate(kind: MacroUpdateExpand, times: times))
})
submenus.add(js{
label: cstring"Expand all macro invocations at this line",
click: proc(menuItem: js, win: js) {.async.} =
await updateExpand(location.path, location.line, location.expansionFirstLine, MacroExpansionLevelUpdate(kind: MacroUpdateExpandAll))
})
submenus.add(js{
label: cstring"Collapse macro invocation at this line",
click: proc(menuItem: js, win: js) {.async.} =
await updateExpand(location.path, location.line, location.expansionFirstLine, MacroExpansionLevelUpdate(kind: MacroUpdateCollapse, times: times))
})
submenus.add(js{
label: cstring"Collapse all macro invocation at this line",
click: proc(menuItem: js, win: js) {.async.} =
await updateExpand(location.path, location.line, location.expansionFirstLine, MacroExpansionLevelUpdate(kind: MacroUpdateCollapseAll))
})
#@[
# js{
# label: j"Jump to def",
# click: proc(menuItem, win: js) = mainWindow.webContents.send "CODETRACER::jump-def", location
# },
# js{
# label: j"Advanced trace",
# click: (proc(menuItem, win: js) =
# discard com.poolFindShape(expression, depth, path, line))
# },
# js{
# label: j"Advanced history",
# click: (proc(menuItem, win: js) =
# discard com.poolFindShape(expression, depth, path, line))
# },
# js{
# label: j"Trace",
# click: (proc(menuItem, win: js) =
# let tracepoints = @[Tracepoint(
# mode: TracExpandable,
# path: location.path,
# line: location.line,
# expression: location.expression,
# shape: NIL_TYPE,
# recipe: @[],
# query: nil)]
# mainWindow.webContents.send "CODETRACER::context-start-trace", tracepoints
# discard debugger.trace(TraceSession(tracepoints: tracepoints), -1))
# }
# js{
# label: j"History",
# click: (proc(menuItem, win: js) =
# discard com.poolFastHistory(js{expression: expression, depth: depth, path: path, line: line, codeID: codeID, functionID: functionID, callID: callID, optimized: false}))
# },
# js{
# label: j"Optimized history",
# click: (proc(menuItem, win: js) =
# discard com.poolFastHistory(js{expression: expression, depth: depth, path: path, line: line, codeID: codeID, functionID: functionID, callID: callID, optimized: true}))
# },
# js{
# label: j"Semantic History",
# click: (proc(menuItem, win: js) =
# discard loadSemanticHistory(expression, path, line))}
# ]
# if running:
# submenus.add(js{
# label: j"Load history",
# click: proc(menuItem: js, win: js) =
# mainWindow.webContents.send "CODETRACER::context-start-history", js{inState: false, expression: location.expression}
# discard debugger.loadHistory(location.expression, location)
# })
var menu = Menu.buildFromTemplate(cast[js](submenus))
return menu
# proc valueMenu(children: seq[cstring], event: Stop, expression: cstring): js =
# var elements: seq[js] = @[]
# for child in children:
# if child == j"Trace":
# elements.add(js{
# label: child,
# click: proc(menuItem: js, win: js) =
# let tracepoints = @[Tracepoint(
# mode: TracExpandable,
# name: event.name,
# line: event.line,
# expression: expression,
# shape: NIL_TYPE,
# recipe: @[],
# query: nil,
# lang: # TODO)]
# mainWindow.webContents.send "CODETRACER::context-start-trace", tracepoints
# discard debugger.trace(TraceSession(tracepoints: tracepoints), -1)
# })
# elif child == j"Load history":
# elements.add(js{
# label: child,
# click: proc(menuItem: js, win: js) =
# mainWindow.webContents.send "CODETRACER::context-start-history", js{inState: true, expression: expression}
# # TODO discard readHistory(event, expression)
# })
# Menu.buildFromTemplate(cast[js](elements)).toJs
type
FileFilter = ref object
name*: cstring
extensions*: seq[cstring]
when not defined(server):
proc debugSend*(self: js, f: js, id: cstring, data: js) =
var values = loadValues(data, id)
if ct_logging.LOG_LEVEL <= CtLogLevel.Debug:
console.log data
f.call(self, cast[cstring](id), data)
# IPC HANDLERS
proc onAsmLoad(sender: js, response: FunctionLocation) {.async.} =
let res = await data.nativeLoadInstructions(response)
mainWindow.webContents.send "CODETRACER::asm-load-received", js{argId: cstring(fmt"{response.path}:{response.name}:{response.key}"), value: res.instructions}
proc onTabLoad(sender: js, response: jsobject(location=types.Location, name=cstring, editorView=EditorView, lang=Lang)) {.async.} =
case response.lang:
of LangC, LangCpp, LangRust, LangNim, LangGo, LangRubyDb:
if response.editorView in {ViewSource, ViewTargetSource, ViewCalltrace}:
discard mainWindow.openTab(response.location, response.lang, response.editorView)
else:
discard
of LangAsm:
if response.editorView == ViewInstructions:
let res = await data.nativeLoadInstructions(FunctionLocation(path: response.location.path, name: response.location.functionName, key: response.location.key))
mainWindow.webContents.send "CODETRACER::tab-load-received", js{argId: response.name, value: res}
else:
discard mainWindow.openTab(response.location, response.lang, response.editorView)
proc onLoadLowLevelTab(sender: js, response: jsobject(pathOrName=cstring, lang=Lang, view=EditorView)) {.async.} =
case response.lang:
of LangC, LangCpp, LangRust, LangGo:
case response.view:
of ViewTargetSource:
warnPrint fmt"low level view source not supported for {response.lang}"
of ViewInstructions:
let res = await data.nativeLoadInstructions(FunctionLocation(name: response.pathOrName))
mainWindow.webContents.send "CODETRACER::low-level-tab-received", js{argId: response.pathOrName & j" " & j($response.view), value: res}
else:
warnPrint fmt"low level view {response.view} not supported for {response.lang}"
of LangNim:
case response.view:
of ViewTargetSource, ViewInstructions:
let res = await data.nimLoadLowLevel(response.pathOrName, response.view)
mainWindow.webContents.send "CODETRACER::low-level-tab-received", js{argId: response.pathOrName & j" " & j($response.view), value: res}
else:
warnPrint fmt"low level view {response.view} not supported for {response.lang}"
else:
warnPrint fmt"low level view not supported for {response.lang}"
# TODO: when fixing the nim c level support
# proc onLoadLowLevelLocations(sender: js, response: jsobject(path=cstring, line=int, lang=Lang, view=EditorView)) {.async.} =
# case response.lang:
# of LangNim:
# let res = await data.nimLoadLowLevelLocations(response.path, response.line, response.view)
# mainWindow.webContents.send "CODETRACER::load-low-level-locations-received", js{argId: response.path & j" " & j($response.line) & j" " & j($response.view), value: res}
# else:
# discard
proc onViewerMenu(sender: js, response: jsobject(coords=MenuLocation, location=types.Location, times=int)) {.async.} =
when not defined(server):
let menu = viewerMenu(response.location, response.times)
menu.popup(mainWindow, js{x: response.coords.x, y: response.coords.y, async: true})
else:
warnPrint "not applicable, should work in frontend for browser version"
proc onUpdateExpansion(sender: js, response: jsobject(path=cstring, line=int, update=MacroExpansionLevelUpdate)) {.async.} =
await updateExpand(response.path, response.line, -1, response.update) # TODO expansionFirstLine ?
proc onLoadTokens(sender: js, response: jsobject(path=cstring, lang=Lang)) {.async.} =
errorPrint "onLoadTokens not working anymore"
proc onSaveConfig(sender: js, response: jsobject(name=cstring, layout=cstring)) {.async.} =
# await persistConfig(mainWindow, response.name, response.layout)
warnprint "FOR NOW: persisting config disabled"
proc onEventJump(sender: js, response: ProgramEvent) {.async.} =
await debugger.eventJump(response)
proc onLoadTerminal(sender: js, response: js) {.async.} =
discard debugger.loadTerminal(EmptyArg())
# proc onCallstackJump(sender: js, response: CallstackJump) {.async.} =
# calls the n-th function in the callstack, 0 is current
# await debugger.callstackJump(response)
proc onCalltraceJump(sender: js, response: types.Location) {.async.} =
await debugger.calltraceJump(response)
proc onTraceJump(sender: js, response: ProgramEvent) {.async.} =
await debugger.traceJump(response)
proc onHistoryJump(sender: js, response: types.Location) {.async.} =
await debugger.historyJump(response)
# proc onDebugCT(sender: js, response: cstring) {.async.} =
# let output = await debugger.debugCT(response)
# mainWindow.webContents.send "CODETRACER::debug-output", output
# not supported in db-backend for now
# proc onDebugGdb(sender: js, response: DebugGdbArg) {.async.} =
# there is a debug-output event, we ignore this one here for now
# let output = await debugger.debugGdb(response)
# discard output
# TODO also function name/id-based
proc onAddBreak(sender: js, response: SourceLocation) {.async.} =
let id = await debugger.addBreak(response)
mainWindow.webContents.send "CODETRACER::add-break-response",
BreakpointInfo(path: response.path, line: response.line, id: id)
proc onDeleteBreak(sender: js, response: SourceLocation) {.async.} =
discard debugger.deleteBreak(response)
# proc onAddBreakC(sender: js, response: jsobject(path=cstring, line=int)) {.async.} =
# let id = await debugger.addBreakC(response.path, response.line)
# mainWindow.webContents.send "CODETRACER::add-break-c-response",
# BreakpointInfo(path: response.path, line: response.line, id: id)
proc onDeleteBreakC(sender: js, response: SourceLocation) {.async.} =
discard debugger.deleteBreak(response)
proc onEnable(sender: js, response: SourceLocation) {.async.} =
discard debugger.enable(response)
proc onDisable(sender: js, response: SourceLocation) {.async.} =
discard debugger.disable(response)
# proc onLoadCallstackDirectChildrenBefore(sender: js, response: jsobject(codeID=int64, before=int64)) {.async.} =
# var calls = await debugger.loadCallstackDirectChildrenBefore(response.codeID, response.before)
# mainWindow.webContents.send "CODETRACER::load-callstack-direct-children-before-received", js{argId: j($response.codeID & " " & $response.before), value: calls}
proc onSearchCalltrace(sender: js, response: cstring) {.async.} =
var calls = await debugger.calltraceSearch(CallSearchArg(value: response))
mainWindow.webContents.send "CODETRACER::search-calltrace-received", js{argId: response, value: calls}
# TODO
# proc onUpdatedCalltraceArgs(sender: js, response: js) {.async.} =
# for element in response.args:
# let codeID = cast[int64](element.codeID)
# let args = cast[CalltraceArgs](element.args)
# graphEngine.args[codeID] = args
# mainWindow.webContents.send "CODETRACER::updated-calltrace-args", response
proc onResetOperation(sender: js, response: jsobject(full=bool, taskId=TaskId, resetLastLocation=bool)) {.async.} =
await debugger.resetOperation(ResetOperationArg(full: response.full, resetLastLocation: response.resetLastLocation), response.taskId)
proc onExitError(sender: js, response: cstring) {.async.} =
# we call this on fatal errors
errorPrint fmt"exit: {response}"
if true: # workaround for unreachable statement and async
quit(1)
# proc onInlineCallJump(sender: js, response: types.Location) {.async.} =
# discard debugger.inlineCallJump(response)
# proc onUpdateTelemetryLog(sender: js, response: jsobject(logs=seq[TelemetryEvent])) {.async.} =
# # we save the log in the file
# if TELEMETRY_ENABLED:
# var text = j""
# for log in response.logs:
# text = text & toYaml(log)
# index_config.fs.appendFile(j"telemetry.log", text, proc = discard)
# else:
# await fsWriteFile(j"telemetry.log", j"")
proc onUpdateWatches(sender: js, response: jsobject(watchExpressions=seq[cstring])) {.async, exportc.} =
discard debugger.updateWatches(response.watchExpressions)
proc onRunTracepoints(sender: js, response: RunTracepointsArg) {.async.} =
await debugger.runTracepoints(response)
var files: seq[(cstring, cstring)] = @[]
proc saveAsFile(name: cstring, raw: cstring) {.async.} =
electron.dialog.showSaveDialog(js{
title: j"save as", defaultPath: name, buttonLabel: j"save"
}, proc (file: cstring) {.async.} =
if file.len > 0:
discard fsWriteFile(file, raw)
var files = JsAssoc[cstring, cstring]{}
files[name] = file
mainWindow.webContents.send "CODETRACER::saved-as", files)
proc onSaveFile(sender: js, response: jsobject(name=cstring, raw=cstring, saveAs=bool)) {.async.} =
# debug "file register", name=response.name
# files.add((response.name, response.raw, response.saveFile))
# debugPrint response.name, " ", response.saveAs
if response.saveAs:
await saveAsFile(response.name, response.raw)
else:
await fsWriteFile(response.name, response.raw)
proc onSaveUntitled(sender: js, response: jsobject(name=cstring, raw=cstring, saveAs=bool)) {.async.} =
await saveAsFile(response.name, response.raw)
proc onUpdate(sender: js, response: jsobject(build=bool, currentPath=cstring)) {.async.} =
for file in files:
# debug "save file", name=file[0]
if not data.tabs.hasKey(file[0]):
data.tabs[file[0]] = ServerTab(path: file[0], lang: LangNim, fileWatched: true)
data.tabs[file[0]].ignoreNext = 2
await fsWriteFile(file[0], file[1])
files = @[]
# not supported yet
# if response.build:
# await initUpdate(data.trace, response.currentPath)
# @FileError, JsonError, ElectronError
# simple examples
# {.pragma: asyncError, raises: [IOError].}
# proc onUpdatedReader(sender: js, response: cstring) {.async.} =
# data.reader = Json.parse(await fsReadFile(response)).to(SimpleReader)
# mainWindow.webContents.send j"CODETRACER::updated-reader", data.reader
proc onSaveNew(sender: js, response: SaveFile) {.async, raises: [].} =
data.save.files.add(response)
await cast[Future[void]](0)
# await data.saveSave()
proc onSaveClose(sender: js, index: int) {.async.} =
if not data.config.test:
data.save.files.delete(index)
await data.saveSave()
proc onLoadHistory(sender: js, response: LoadHistoryArg) {.async.} =
# TODO: fix in core/use new dsl
await debugger.loadHistory(response)
proc onLoadFlow(sender: js, response: FlowQuery) {.async.} =
await debugger.loadFlow(response.location, response.taskId)
proc onSetupTraceSession(sender: js, response: RunTracepointsArg) {.async.} =
discard
proc onLoadFlowShape(sender: js, response: types.Location) {.async.} =
# await debugger.loadFlowShape(response)
warnPrint "TODO: fix in core/use new dsl: loadFlowShape not working now, also not sure about flow shape reform"
var startedFuture: proc: void
var startedReceived = false
proc onStarted(sender: js, response: js) {.async.} =
if not startedFuture.isNil:
startedReceived = true
startedFuture()
proc onOpenTab(sender: js, response: js) {.async.} =
let options = js{
properties: @[j"openFile"],
title: cstring"Select File",
buttonLabel: cstring"Select"}
let file = await selectFileOrFolder(options)
if file != "":
if file.slice(-4) == j".nim":
mainWindow.webContents.send "CODETRACER::opened-tab", js{path: file, lang: LangNim}
else:
mainWindow.webContents.send "CODETRACER::opened-tab", js{path: file, lang: LangUnknown}
proc onReloadFile(sender: js, response: jsobject(path=cstring)) {.async.} =
let lang = if response.path.slice(-4) == j".nim": LangNim else: LangUnknown
data.tabs[response.path].waitsPrompt = false
discard data.open(mainWindow, types.Location(highLevelPath: response.path, isExpanded: false), ViewSource, "tab-reloaded", false, data.exe, lang, -1)
proc onNoReloadFile(sender: js, response: jsobject(path=cstring)) {.async.} =
data.tabs[response.path].waitsPrompt = false
proc onCloseApp(sender: js, response: js) {.async.} =
for (name, file) in files:
await fsWriteFile(name, file)
mainWindow.close()
proc onRunToEntry(sender: js, response: js) {.async.} =
discard debugger.runToEntry(EmptyArg())
proc onRestart(sender: js, response: js) {.async.} =
quit(RESTART_EXIT_CODE)
proc onSearch(sender: js, response: SearchQuery) {.async.} = discard
# # debugPrint "search ", response
# if data.pluginCommands.hasKey(response.value):
# if data.pluginClient.isNil:
# # debugPrint cstring"plugin client is nil"
# return
# if data.pluginClient.running:
# await data.pluginClient.cancelOrWait()
# data.pluginClient.running = true
# data.pluginClient.cancelled = false
# # debugPrint response.command
# await (data.pluginCommands[response.value]).search(response, data.pluginClient)
# data.pluginClient.running = false
# if not data.pluginClient.cancelOrWaitFunction.isNil:
# data.pluginClient.cancelOrWaitFunction()
# else:
# errorPrint "not found ", response.value
# proc onRunTo(sender: js, response: jsobject(path=cstring, line=int, reverse=bool)) {.async.} =
# discard debugger.runTo(response.path, response.line, response.reverse)
# proc onRunToCall(sender: js, re)
# TODO pass argId?
proc onSearchProgram(sender: js, query: cstring) {.async.} =
debugPrint "search program ", query
when not defined(server):
discard doProgramSearch($query, debugSend, mainWindow)
# discard debugger.searchProgram(query)
proc onLoadStepLines(sender: js, response: LoadStepLinesArg) {.async.} =
discard debugger.loadStepLines(response)
proc onUploadTraceFile(sender: js, response: UploadTraceArg) {.async.} =
let res = await readProcessOutput(
codetracerExe.cstring,
@[
j"upload",
j"--trace-folder=" & response.trace.outputFolder
]
)
proc onDownloadTraceFile(sender: js, response: jsobject(downloadId=seq[cstring])) {.async.} =
let res = await readProcessOutput(
codetracerExe.cstring,
@[j"download"].concat(response.downloadId)
)
if res.isOk:
await prepareForLoadingTrace(parseInt($res.v.trim()), nodeProcess.pid.to(int))
await loadExistingRecord(parseInt($res.v.trim()))
proc onSendBugReportAndLogs(sender: js, response: BugReportArg) {.async.} =
let process = await runProcess(
codetracerExe.cstring,
@[j"report-bug",
j"--title=" & response.title,
j"--description=" & response.description,
j($callerProcessPid),
j"--confirm-send=0"]
)
# debugPrint process
proc onStep(sender: js, response: JsObject) {.async.} =
await debugger.step(cast[StepArg](response), cast[TaskId](response.taskId))
proc onDeleteAllBreakpoints(sender: js, response: js) {.async.} =
await debugger.deleteAllBreakpoints(EmptyArg())
proc onSourceLineJump(sender: js, response: SourceLineJumpTarget) {.async.} =
await debugger.sourceLineJump(response)
proc onSourceCallJump(sender: js, response: SourceCallJumpTarget) {.async.} =
await debugger.sourceCallJump(response)
proc onLocalStepJump(sender: js, response: LocalStepJump) {.async.} =
await debugger.localStepJump(response)
# TODO: somehow share with codetracer_shell.nim ?
proc scriptSessionLogPath(sessionId: int): cstring =
cstring(codetracerTmpPath / fmt"session-{sessionId}-script.log")
let pty: JsObject = jsundefined # = cast[Pty](jsundefined) # TODO or remove completely require(cstring"node-pty"))
var afterId = 0
var sessionId = -1
var shellXtermProgress = -1
const CT_DEBUG_INSTANCE_PATH_BASE*: cstring = cstring"/tmp/codetracer/ct_instance_"
proc newDebugInstancePipe(pid: int): Future[JsObject] {.async.} =
var future = newPromise() do (resolve: proc(response: JsObject)):
var connections: seq[JsObject] = @[nil.toJs]
let path = CT_DEBUG_INSTANCE_PATH_BASE & cstring($pid)
connections[0] = net.createServer(proc(server: JsObject) =
infoPrint "index: connected instance server for ", path
# connections[0].pipe(connections[0])
# js{path: path, encoding: cstring"utf8"},
resolve(server))
connections[0].on(cstring"error") do (error: js):
errorPrint "index: socket instance server error: ", error
resolve(nil.toJs)
connections[0].listen(path)
return await future
# startSocket(debugger, CT_DEBUG_INSTANCE_PATH_BASE & cstring($pid)) # & cstring"_" & cstring($callerProcessPid))
proc sendOutputJumpIPC(instance: DebugInstance, outputLine: int) {.async.} =
debugPrint "send output jump ipc ", cast[int](instance.process.pid), " ", outputLine
instance.pipe.write(cstring($outputLine & "\n"))
proc onShowInDebugInstance(sender: js, response: jsobject(traceId=int, outputLine=int)) {.async.} =
if not data.debugInstances.hasKey(response.traceId):
var process = child_process.spawn(
codetracerExe,
@[cstring"run", cstring($response.traceId)])
var pipe = await newDebugInstancePipe(process.pid)
data.debugInstances[response.traceId] = DebugInstance(process: process, pipe: pipe)
await wait(5_000)
if response.outputLine != -1:
await sendOutputJumpIPC(data.debugInstances[response.traceId], response.outputLine)
proc onOpenTrace(sender: js, traceId: int) {.async.} =
# codetracer run <traceId>
var process = child_process.spawn(
codetracerExe,
@[cstring"run", cstring($traceId)])
# proc onUpdatedEventsContent(sender: js, response: cstring) {.async.} =
# try:
# mainWindow.webContents.send "CODETRACER::updated-events-content", response
# except:
# errorPrint "error for `onUpdatedEventsContent` ", getCurrentExceptionMsg()
proc onLoadParsedExprs(sender: js, response: LoadParsedExprsArg) {.async.} =
let value = await debugger.loadParsedExprs(response)
mainWindow.webContents.send "CODETRACER::load-parsed-exprs-received", js{"argId": j($response.path & ":" & $response.line), "value": value}
proc onLoadLocals(sender: js, response: LoadLocalsArg) {.async.} =
# debug "load locals"
var locals = await debugger.loadLocals(response)
mainWindow.webContents.send "CODETRACER::load-locals-received", js{"argId": j($response.rrTicks), "value": locals}
proc onEvaluateExpression(sender: js, response: EvaluateExpressionArg) {.async.} =
var value = await debugger.evaluateExpression(response)
mainWindow.webContents.send "CODETRACER::evaluate-expression-received", js{"argId": j($response.rrTicks & ":" & $response.expression), "value": value}
proc onEventLoad(sender: js, response: js) {.async.} =
discard debugger.eventLoad(EmptyArg())
proc onExpandValue(sender: js, response: ExpandValueTarget) {.async.} =
var value = await debugger.expandValue(response)
mainWindow.webContents.send "CODETRACER::expand-value-received", js{"argId": j($response.rrTicks & " " & $response.subPath), "value": value}
# proc onExpandValues(sender: js, response: jsobject(expressions=seq[cstring], depth=int, stateCompleteMoveIndex=int)) {.async.} =
# var values = await debugger.expandValues(response.expressions, response.depth)
# mainWindow.webContents.send(
# "CODETRACER::expand-values-received",
# js{
# "argId": j($response.stateCompleteMoveIndex & " " & $response.expressions),
# "value": values})
proc onMinimizeWindow(sender: js, response: JsObject) {.async.} =
mainWindow.minimize()
proc onRestoreWindow(sender: js, response: JsObject) {.async.} =
mainWindow.restore()
proc onMaximizeWindow(sender: js, response: JsObject) {.async.} =
mainWindow.maximize()
proc onCloseWindow(sender: js, response: JsObject) {.async.} =
mainWindow.close()
when not defined(server):
app.on("window-all-closed") do ():
if electronProcess.platform != "darwin":
app.quit(0)
# app.on("activate") do ():
# if mainWindow == nil:
# mainWindow = createMainWindow()
# mainWindow.setMenuBarVisibility(false)
# mainWindow.setMenu(jsNull)
proc started*: Future[void] =
var future = newPromise() do (resolve: (proc: void)):
if startedFuture.isNil:
startedFuture = resolve
mainWindow.webContents.send "CODETRACER::started", js{}
discard windowSetTimeout(proc =
if not startedReceived:
discard started(), 100)
return future
proc loadExistingRecord(traceId: int) {.async.} =
debugPrint "[info]: load existing record with ID: ", $traceId
let trace = await app.findTraceWithCodetracer(traceId)
data.trace = trace
data.pluginClient.trace = trace
if data.trace.compileCommand.len == 0:
data.trace.compileCommand = data.config.defaultBuild
debugPrint "index: start ct start_core " & $traceId & " " & $callerProcessPid
var process = child_process.spawn(
codetracerExe.cstring,
# TODO: don't hardcode those, use Victor's fields and parseArgs first
@[cstring"start_core", cstring($traceId), cstring($callerProcessPid)])
debugPrint "index: start and setup core ipc"
await startAndSetupCoreIPC(debugger)
if not data.trace.isNil:
debugPrint "index: init debugger"
discard initDebugger(mainWindow, data.trace, data.config, Helpers())
debugPrint "index: init frontend"
mainWindow.webContents.send(
"CODETRACER::init",
js{
home: paths.home.cstring,
config: data.config,
layout: data.layout,
helpers: data.helpers,