-
Notifications
You must be signed in to change notification settings - Fork 2
/
sdmain.py
2035 lines (1774 loc) · 74.9 KB
/
sdmain.py
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 sublime
import sublime_plugin
import subprocess
import threading
import traceback
import os
import sys
import re
import signal
import uuid
from GoDebug.sdconst import DlvConst
from GoDebug.sdlogger import DlvLogger
from GoDebug.sdworker import DlvWorker
from GoDebug.sdview import DlvView
from GoDebug.sdobjecttype import *
dlv_project = {}
class DlvProject(object):
def __init__(self, window):
self.window = window
self.const = DlvConst(self.window)
self.logger = DlvLogger(self.window, self.const)
self.cursor = ''
self.cursor_position = 0
self.last_cursor_view = None
self.panel_layout = {}
self.panel_window = None
self.panel_view = None
self.input_view = None
self.command_history = []
self.command_history_pos = 0
self.next_in_progress = False
self.__session_proc = None
self.__session_send_signal = False
self.__server_proc = None
self.session_view = self.__initialize_view(self.const.SESSION_VIEW)
self.console_view = self.__initialize_view(self.const.CONSOLE_VIEW)
self.stacktrace_view = self.__initialize_view(self.const.STACKTRACE_VIEW)
self.goroutine_view = self.__initialize_view(self.const.GOROUTINE_VIEW)
self.variable_view = self.__initialize_view(self.const.VARIABLE_VIEW)
self.watch_view = self.__initialize_view(self.const.WATCH_VIEW)
self.bkpt_view = self.__initialize_view(self.const.BREAKPOINT_VIEW)
self.worker = DlvWorker(self, worker_callback)
def get_views(self):
return [self.session_view, self.variable_view, self.watch_view, self.stacktrace_view, self.bkpt_view, self.goroutine_view]
def get_new_view(self, name, view):
if name == self.const.SESSION_VIEW:
return DlvSessionView(self, view)
elif name == self.const.CONSOLE_VIEW:
return DlvConsoleView(self, view)
elif name == self.const.STACKTRACE_VIEW:
return DlvStacktraceView(self, view)
elif name == self.const.GOROUTINE_VIEW:
return DlvGoroutineView(self, view)
elif name == self.const.VARIABLE_VIEW:
return DlvVariableView(name, self, view)
elif name == self.const.WATCH_VIEW:
return DlvVariableView(name, self, view)
elif name == self.const.BREAKPOINT_VIEW:
return DlvBreakpointView(self, view)
return None
def __initialize_view(self, name):
view = None
for v in self.window.views():
if v.name() == self.const.get_view_setting(name, self.const.TITLE):
view = v
return self.get_new_view(name, view)
def reset_cursor(self):
self.cursor = ''
self.cursor_position = 0
self.next_in_progress = False
def panel_on_start(self):
self.panel_window = self.window
self.panel_layout = self.panel_window.get_layout()
self.panel_view = self.panel_window.active_view()
self.panel_window.set_layout(self.const.PANEL_LAYOUT)
def panel_on_stop(self):
self.panel_window.set_layout(self.panel_layout)
self.panel_window.focus_view(self.panel_view)
def check_input_view(self, view):
return self.input_view is not None and view.id() == self.input_view.id()
def set_input(self, edit, text):
self.input_view.erase(edit, sublime.Region(0, self.input_view.size()))
self.input_view.insert(edit, 0, text)
def show_input(self):
self.command_history_pos = len(self.command_history)
self.input_view = self.window.show_input_panel("Delve command", "", self.input_on_done, self.input_on_change, self.input_on_cancel)
def input_on_done(self, s):
if not self.is_running():
message = "Delve session not found, need to start debugging"
self.logger.debug(message)
set_status_message(message)
return
if s.strip() != "quit" and s.strip() != "exit" and s.strip() != "q":
self.command_history.append(s)
self.show_input()
self.run_input_cmd(s)
def input_on_cancel(self):
pass
def input_on_change(self, s):
pass
def run_input_cmd(self, cmd):
if isinstance(cmd, list):
for c in cmd:
self.run_input_cmd(c)
return
elif cmd.strip() == "":
return
message = "Input command: %s" % cmd
self.session_view.add_line(message)
self.logger.info(message)
try:
self.__session_proc.stdin.write(cmd + '\n')
self.__session_proc.stdin.flush()
except:
traceback.print_exc(file=(sys.stdout if self.logger.get_file() == self.const.STDOUT else open(self.logger.get_file(),"a")))
self.logger.error("Exception thrown, details in file: %s" % self.logger.get_file())
requests = []
requests.append({"cmd": self.const.STATE_COMMAND, "parms": None})
self.add_breakpoint_request(requests)
self.add_goroutine_request(requests)
self.worker.do_batch(requests)
def is_running(self):
return self.__session_proc is not None and self.__session_proc.poll() is None
def is_server_running(self):
return self.__server_proc is not None and self.__server_proc.poll() is None
def terminate_session(self, send_sigint=False):
if self.is_running():
try:
if send_sigint:
self.logger.debug('Send to session subprocess SIGINT signal')
self.__session_proc.send_signal(signal.SIGINT)
else:
self.logger.debug('Send to session subprocess SIGTERM signal')
self.__session_proc.send_signal(signal.SIGTERM)
except:
traceback.print_exc(file=(sys.stdout if self.logger.get_file() == self.const.STDOUT else open(self.logger.get_file(),"a")))
self.logger.error("Exception thrown (terminate_session), details in file: %s" % self.logger.get_file())
if self.is_server_running():
try:
if send_sigint:
self.logger.debug('Send to server subprocess SIGINT signal')
self.__server_proc.send_signal(signal.SIGINT)
else:
self.logger.debug('Send to server subprocess SIGTERM signal')
self.__server_proc.send_signal(signal.SIGTERM)
except:
traceback.print_exc(file=(sys.stdout if self.logger.get_file() == self.const.STDOUT else open(self.logger.get_file(),"a")))
self.logger.error("Exception thrown (terminate_session), details in file: %s" % self.logger.get_file())
def terminate_server(self):
if self.is_server_running():
try:
self.logger.debug('Send to server subprocess SIGINT signal')
self.__server_proc.send_signal(signal.SIGINT)
except:
traceback.print_exc(file=(sys.stdout if self.logger.get_file() == self.const.STDOUT else open(self.logger.get_file(),"a")))
self.logger.error("Exception thrown (terminate_server), details in file: %s" % self.logger.get_file())
self.logger.debug('Send to server subprocess SIGKILL signal')
self.__server_proc.kill()
self.logger.error("Delve server killed after timeout")
v = self.console_view
if v.is_open():
if v.is_close_at_stop():
v.close()
self.logger.debug("Closed console view")
else:
v.clear(True)
if self.console_view.is_open():
self.console_view.close()
def cleanup_session(self):
v = self.console_view
if v.is_open():
if v.is_close_at_stop():
v.close()
else:
v.clear(True)
for v in self.get_views():
if v.is_open():
if v.is_close_at_stop():
v.close()
else:
v.clear(True)
self.panel_on_stop()
self.logger.debug("Closed required debugging views")
if self.const.is_project_executable():
self.const.clear_project_executable()
self.logger.debug("Cleared project executable settings")
self.worker.stop()
self.logger.stop()
self.clear_position()
self.reset_cursor()
def __open_subprocess(self, cmd, cwd=None):
return subprocess.Popen(cmd, shell=False, cwd=cwd, universal_newlines=True,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def load_session_subprocess(self, cmd_session):
message = "Delve session started with command: %s" % " ".join(cmd_session)
self.logger.info(message)
self.session_view.add_line(message)
try:
self.__session_proc = self.__open_subprocess(cmd_session)
except:
traceback.print_exc(file=(sys.stdout if self.logger.get_file() == self.const.STDOUT else open(self.logger.get_file(),"a")))
self.logger.error("Exception thrown, details in file: %s" % self.logger.get_file())
self.logger.error(message)
set_status_message(message)
if self.is_local_mode():
self.terminate_server()
else:
self.cleanup_session()
return
self.reset_cursor()
t = threading.Thread(target=self.dlv_output, args=(self.__session_proc.stdout,))
t.start()
t = threading.Thread(target=self.dlv_output, args=(self.__session_proc.stderr,))
t.start()
def load_server_subprocess(self, cmd_server, cmd_session, cwd):
set_status_message("Starts Delve server, wait...")
message = "Delve server started with command: %s" % " ".join(cmd_server)
self.logger.info(message)
self.logger.debug("In directory: %s" % cwd)
self.console_view.add_line(message)
try:
self.__server_proc = self.__open_subprocess(cmd_server, cwd)
except:
traceback.print_exc(file=(sys.stdout if self.logger.get_file() == self.const.STDOUT else open(self.logger.get_file(),"a")))
message = "Exception thrown, details in file: %s" % self.logger.get_file()
self.logger.error(message)
set_status_message(message)
self.terminate_server()
self.cleanup_session()
return
t = threading.Thread(target=self.dlv_output, args=(self.__server_proc.stdout, cmd_session))
t.start()
t = threading.Thread(target=self.dlv_output, args=(self.__server_proc.stderr,))
t.start()
def dlv_output(self, pipe, cmd_session=None):
started_session = False
# reaesc = re.compile(r'\x1b[^m]*m')
reaesc = re.compile(r'\x1b\[[\d;]*m')
if self.__session_proc is not None and pipe == self.__session_proc.stdout:
sublime.set_timeout(self.show_input, 0)
self.logger.debug("Input field is ready")
sublime.set_timeout(self.bkpt_view.sync_breakpoints, 0)
sublime.set_timeout(set_status_message("Delve session started"), 0)
while True:
try:
line = pipe.readline()
if len(line) == 0:
if self.is_local_mode() and self.__server_proc is not None:
if pipe in [self.__server_proc.stdout, self.__server_proc.stderr]:
self.logger.error("Broken %s pipe of the Delve server" % \
("stdout" if pipe == self.__server_proc.stdout else "stderr"))
break
if self.__session_proc is not None and self.__session_proc.stdout is not None:
self.logger.error("Broken %s pipe of the Delve session" % \
("stdout" if pipe == self.__session_proc.stdout else "stderr"))
break
else:
line = reaesc.sub('', line)
line = line.replace("\\n", "\n").replace("\\\"", "\"").replace("\\t", "\t")
# line = line.replace('\n', '') #alternative of line above
if line.startswith("(dlv)"):
line = line.replace("(dlv)", "")
line = line.strip()
if len(line) == 0:
continue
if self.__session_proc is not None:
if pipe == self.__session_proc.stdout:
self.session_view.add_line(line)
self.logger.info("Session stdout: " + line)
elif pipe == self.__session_proc.stderr:
self.session_view.add_line(line)
self.logger.error("Session stderr: " + line)
if self.__server_proc is not None:
if pipe == self.__server_proc.stdout:
self.console_view.add_line(line)
self.logger.info("Server stdout: " + line)
if not started_session:
self.logger.debug("Delve server is working, try to start Delve Session")
lock = threading.RLock()
lock.acquire()
sublime.set_timeout(self.load_session_subprocess(cmd_session), 0)
started_session = True
lock.release()
elif pipe == self.__server_proc.stderr:
self.console_view.add_line(line)
self.logger.error("Server stderr: " + line)
except:
traceback.print_exc(file=(sys.stdout if self.logger.get_file() == self.const.STDOUT else open(self.logger.get_file(),"a")))
self.logger.error("Exception thrown, details in file: %s" % self.logger.get_file())
if self.__session_proc is not None and pipe == self.__session_proc.stdout:
message = "Delve session closed"
sublime.set_timeout(set_status_message(message), 0)
self.logger.info(message)
# sublime.set_timeout(self.terminate_server, 0)
if self.__server_proc is not None and pipe == self.__server_proc.stdout:
self.logger.info("Delve server closed")
sublime.set_timeout(self.terminate_session, 0)
if (not self.is_local_mode() and self.__session_proc is not None and pipe == self.__session_proc.stdout) or \
(self.is_local_mode() and self.__server_proc is not None and pipe == self.__server_proc.stdout):
sublime.set_timeout(self.cleanup_session, 0)
def clear_position(self):
if self.last_cursor_view is not None:
region = self.last_cursor_view.get_regions(self.const.DLV_REGION)
if region is None or len(region) == 0:
self.last_cursor_view = None
return
assert (len(region) == 1)
row, col = self.last_cursor_view.rowcol(region[0].a)
bkpt = self.bkpt_view.find_breakpoint(self.last_cursor_view.file_name(), row + 1)
if self.last_cursor_view is not None:
self.last_cursor_view.erase_regions(self.const.DLV_REGION)
if bkpt is not None:
bkpt._show(self.is_running(), self.last_cursor_view)
self.last_cursor_view = None
def update_position(self, view):
self.clear_position()
if self.is_running() and self.cursor == view.file_name() and self.cursor_position != 0:
bkpt = self.bkpt_view.find_breakpoint(self.cursor, self.cursor_position)
if bkpt is not None:
bkpt._hide(view)
view.add_regions(self.const.DLV_REGION, [view.line(view.text_point(self.cursor_position - 1, 0))], \
"entity.name.class", "bookmark", sublime.HIDDEN)
self.last_cursor_view = view
def add_breakpoint_request(self, requests):
assert (self.is_running())
requests.append({"cmd": self.const.BREAKPOINT_COMMAND, "parms": None})
def add_goroutine_request(self, requests):
assert (self.is_running())
requests.append({"cmd": self.const.GOROUTINE_COMMAND, "parms": None})
def add_watch_request(self, requests):
assert (self.is_running())
if self.watch_view.is_watches_exist():
goroutine_id = self.goroutine_view.get_selected_goroutine_id()
frame = self.stacktrace_view.get_selected_frame()
parms = {"watches": self.watch_view.get_watches_as_parm()}
if goroutine_id > 0:
parms['goroutine_id'] = goroutine_id
parms['frame'] = frame
requests.append({"cmd": self.const.WATCH_COMMAND, "parms": parms})
def add_variable_request(self, requests, parms):
assert (self.is_running())
requests.append({"cmd": self.const.VARIABLE_COMMAND, "parms": parms})
def is_local_mode(self):
return self.const.MODE in [self.const.DEBUG_MODE, self.const.TEST_MODE]
def is_next_enabled(self):
assert (self.is_running())
return not self.next_in_progress
def is_project_file_exists(window):
return window.project_file_name() is not None
def is_equal(first, second):
return first.id() == second.id()
def set_status_message(message):
sublime.status_message(message)
def normalize(file):
if file is None:
return None
return os.path.abspath(os.path.normcase(file))
def is_gosource(s):
if s is None:
return False
ext = os.path.splitext(os.path.basename(s))[1]
if ext is not None and ext == ".go":
return True
else:
return False
def is_plugin_enable():
window = sublime.active_window()
if is_project_file_exists(window) and 'settings' in window.project_data():
settings = window.project_data()['settings']
if 'delve_enable' in settings and settings['delve_enable']:
key = window.id()
if not key in dlv_project:
dlv_project[key] = DlvProject(window)
return True, dlv_project[key]
return False, None
def worker_callback(prj, responses):
const = prj.const
state = None
update_views = []
update_marker_views = False
update_position_view = None
bkpts_add = []
bkpts_del = []
commonResult = True
for response in responses:
cmd = response['cmd']
result = response['result']
error_code = None
error_message = None
if not result:
commonResult = False
if 'error_code' in response:
error_code = response['error_code']
error_message = response['error_message']
if cmd == const.CREATE_BREAKPOINT_COMMAND:
new_bkpt = DlvBreakpointType()
view = prj.bkpt_view
if result:
new_bkpt._update(response['response'])
find_bkpt = view.find_breakpoint(new_bkpt.file, new_bkpt.line)
if find_bkpt is not None:
find_bkpt._update(response['response'])
find_bkpt._reset_error_message()
else:
bkpts_add.append(new_bkpt)
else:
new_bkpt._update(response['parms'])
find_bkpt = view.find_breakpoint(new_bkpt.file, new_bkpt.line)
if find_bkpt is None:
bkpts_add.append(new_bkpt)
find_bkpt = new_bkpt
find_bkpt._set_error_message(error_message)
if view not in update_views:
update_views.append(view)
elif cmd == const.CLEAR_BREAKPOINT_COMMAND:
if result:
view = prj.bkpt_view
new_bkpt = DlvBreakpointType()
new_bkpt._update(response['response'])
bkpts_del.append(new_bkpt)
if view not in update_views:
update_views.append(view)
elif cmd == const.BREAKPOINT_COMMAND:
if result:
view = prj.bkpt_view
view.load_data(response['response'])
update_marker_views = True
if view not in update_views:
update_views.append(view)
elif cmd == const.GOROUTINE_COMMAND:
if result:
view = prj.goroutine_view
view.load_data(response['response'], response['current_goroutine_id'])
if view not in update_views:
update_views.append(view)
elif cmd == const.STACKTRACE_COMMAND:
if result:
view = prj.stacktrace_view
view.load_data(response['response'])
if view not in update_views:
update_views.append(view)
elif cmd == const.VARIABLE_COMMAND:
if result:
view = prj.variable_view
view.load_variable(response['response'])
if view not in update_views:
update_views.append(view)
elif cmd == const.WATCH_COMMAND:
if result:
view = prj.watch_view
view.load_watch(response['response'])
if view not in update_views:
update_views.append(view)
elif cmd == const.STATE_COMMAND:
if not result and error_code != -32803:
prj.terminate_session()
return
if not result and error_code == -32803:
prj.terminate_session(prj.is_local_mode())
return
if result and type(response['response']) is dict and 'State' in response['response']:
state = DlvStateType()
state._update(response['response'])
prj.next_in_progress = state.NextInProgress
thread = state._get_thread('currentThread')
if state.exited or thread.goroutineID == 0:
prj.logger.debug("Process exit with status: %d" % state.exitStatus)
prj.terminate_session()
return
if state is not None:
thread = state._get_thread('currentThread')
if thread is not None:
window = prj.window
view = window.find_open_file(thread.file)
if view is None:
window.focus_group(0)
update_position_view = window.open_file("%s:%d" % (thread.file, thread.line), sublime.ENCODED_POSITION)
prj.cursor = thread.file
prj.cursor_position = thread.line
prj.bkpt_view.upgrade_breakpoints(bkpts_add, bkpts_del)
for view in update_views:
view.update_view()
if update_marker_views:
prj.bkpt_view.update_markers()
if update_position_view is not None:
prj.update_position(update_position_view)
if not commonResult:
set_status_message("Errors occured, details in file: %s" % prj.logger.get_file())
class DlvBreakpointType(DlvObjectType):
def __init__(self, file=None, line=None, **kwargs):
super(DlvBreakpointType, self).__init__("Breakpoint", **kwargs)
self.__file = file
self.__line = line
self.__original_line = line
self.__showed = False
self.__show_running = False
self.__uuid = None
self.__error_message = None
def __getattr__(self, attr):
if attr == "file" and self.__file is not None:
return self.__file
if attr == "line" and self.__line is not None:
return self.__line
return super(DlvBreakpointType, self).__getattr__(attr)
@property
def _as_parm(self):
response = super(DlvBreakpointType, self)._as_parm
if self.__file is not None:
response[self._object_name]['file'] = self.__file
if self.__line is not None:
response[self._object_name]['line'] = self.__line
return response
@property
def _key(self):
if self.__original_line is None:
self.__original_line = self.line
return "dlv.bkpt%s" % self.__original_line
def _set_error_message(self, error_message=None):
self.__error_message = error_message if error_message is not None else '<not available>'
def _reset_error_message(self):
self.__error_message = None
def _is_error(self):
return (self.__error_message != None)
def _set_uuid(self, uuid):
self.__uuid = uuid
def _get_uuid(self):
return self.__uuid
def _update_line(self, line):
assert (self.__original_line is not None)
self.__line = line
def _show(self, running, view):
assert (view is not None)
if not self.__showed or running != self.__show_running:
icon_file = "Packages/GoDebug/%s" % ('bkpt_active.png' if running and not self._is_error() else 'bkpt_inactive.png')
assert (view.text_point(self.line - 1, 0) != 0)
view.add_regions(self._key, [view.line(view.text_point(self.line - 1, 0))], "keyword.dlv", icon_file, sublime.HIDDEN)
self.__showed = True
self.__show_running = running
def _hide(self, view):
assert (view is not None)
if self.__showed:
view.erase_regions(self._key)
self.__showed = False
self.__show_running = False
def _was_hided(self):
self.__showed = False
self.__show_running = False
def _is_loaded(self):
return hasattr(self, 'id')
def _format(self, running):
output = "\"%s:%d\"" % (os.path.basename(self.file), self.line)
if running:
if not self._is_error():
if self._is_loaded():
output += " %d" % self.id
else:
output += " \"%s\"" % self.__error_message
return output
class DlvStateType(DlvObjectType):
def __init__(self, **kwargs):
super(DlvStateType, self).__init__("State", **kwargs)
def _get_thread(self, name=None):
thread = DlvThreadType()
if name is None:
name = thread._object_name
value = self._kwargs.get(name, None)
if value is not None:
obj_value = {}
obj_value[thread._object_name] = value
thread._update(obj_value)
return thread
else:
return None
class DlvLocationType(DlvObjectType):
def __init__(self, **kwargs):
super(DlvLocationType, self).__init__("Location", **kwargs)
def _get_variables(self):
variables = []
for element in self.Locals:
var = DlvtVariableType()
var._update({"Variable": element})
variables.append(var)
for element in self.Arguments:
var = DlvtVariableType()
var._update({"Variable": element})
variables.append(var)
return variables
def _format(self):
return "%s \"%s:%d\"" % (os.path.basename(self.function['name']), os.path.basename(self.file), self.line)
class DlvThreadType(DlvObjectType):
def __init__(self, **kwargs):
super(DlvThreadType, self).__init__("Thread", **kwargs)
def _get_breakpoint(self, name=None):
breakpoint = DlvBreakpointType(self.file, self.line)
if name is None:
name = breakpoint._object_name
value = self._kwargs.get(name, None)
if value is not None:
obj_value = {}
obj_value[breakpoint._object_name] = value
breakpoint._update(obj_value)
return breakpoint
else:
return None
def _format(self):
return "%d\t%s" % (self.id, self.function['name'])
class DlvGoroutineType(DlvObjectType):
def __init__(self, **kwargs):
super(DlvGoroutineType, self).__init__("Goroutine", **kwargs)
@property
def _current_file(self):
return self.currentLoc['file']
@property
def _current_line(self):
return self.currentLoc['line']
def _format(self):
return "%s \"%s:%d\" %d" % (os.path.basename(self.currentLoc['function']['name']), os.path.basename(self.currentLoc['file']), self.currentLoc['line'], self.id)
class DlvSessionView(DlvView):
def __init__(self, prj, view):
super(DlvSessionView, self).__init__(prj.const.SESSION_VIEW, prj.window, prj.const, view, True)
self.__prj = prj
class DlvConsoleView(DlvView):
def __init__(self, prj, view):
super(DlvConsoleView, self).__init__(prj.const.CONSOLE_VIEW, prj.window, prj.const, view, True)
self.__prj = prj
class DlvBreakpointView(DlvView):
def __init__(self, prj, view):
super(DlvBreakpointView, self).__init__(prj.const.BREAKPOINT_VIEW, prj.window, prj.const, view)
self.__prj = prj
self.__breakpoints = []
if self.const.SAVE_BREAKPOINT:
data = self.const.load_breakpoints()
bkpts_add = []
for element in data:
bkpts_add.append(DlvBreakpointType(element['file'], element['line']))
self.upgrade_breakpoints(bkpts_add)
def open(self, reset=False):
super(DlvBreakpointView, self).open(reset)
if self.is_open():
self.set_syntax("Packages/GoDebug/GoDebug.tmLanguage")
if not self.__prj.is_running():
self.update_breakpoint_lines()
self.update_view()
def hide_view_breakpoints(self, view):
for bkpt in self.__breakpoints:
if bkpt.file == view.file_name():
bkpt._was_hided()
def select_breakpoint(self, view):
row, col = view.rowcol(view.sel()[0].a)
if len(self.__breakpoints) > 0:
bkpt = self.__breakpoints[row]
find_view = self.window.find_open_file(bkpt.file)
if find_view is None:
self.window.focus_group(0)
self.window.open_file("%s:%d" % (bkpt.file, bkpt.line), sublime.ENCODED_POSITION)
def upgrade_breakpoints(self, bkpts_add=[], bkpts_del=[]):
need_update = False
for bkpt in bkpts_add:
cur_bkpt = self.find_breakpoint(bkpt.file, bkpt.line)
assert (cur_bkpt is None)
cur_bkpt = bkpt
self.__breakpoints.append(cur_bkpt)
update_view = self.window.find_open_file(cur_bkpt.file)
if update_view is not None:
running = self.__prj.is_running()
if not running or running and not \
(self.__prj.cursor_position == cur_bkpt.line and self.__prj.cursor == cur_bkpt.file):
cur_bkpt._show(running, update_view)
need_update = True
for bkpt in bkpts_del:
cur_bkpt = self.find_breakpoint(bkpt.file, bkpt.line)
if cur_bkpt is None:
self.__prj.logger.debug("Breakpoint %s:%d not found, skip update" % (bkpt.file, bkpt.line))
continue
update_view = self.window.find_open_file(cur_bkpt.file)
if update_view is not None:
cur_bkpt._hide(update_view)
self.__breakpoints.remove(cur_bkpt)
need_update = True
return need_update
def __get_marker_views(self):
views = []
for bkpt in self.__breakpoints:
view = self.window.find_open_file(bkpt.file)
if view is None:
continue
if view not in views:
views.append(view)
return views
def update_markers(self, views=None):
if views is None:
views = self.__get_marker_views()
for view in views:
file = view.file_name()
assert (file is not None)
for bkpt in self.__breakpoints:
if bkpt.file == file:
running = self.__prj.is_running()
if not running or running and not \
(self.__prj.cursor_position == bkpt.line and self.__prj.cursor == bkpt.file):
bkpt._show(running, view)
def clear_markers(self):
for bkpt in self.__breakpoints:
view = self.window.find_open_file(bkpt.file)
if view is None:
continue
bkpt._hide(view)
def update_view(self):
super(DlvBreakpointView, self).update_view()
if not self.is_open():
return
self.__breakpoints.sort(key=lambda b: (b.file, b.line))
running = self.__prj.is_running()
for bkpt in self.__breakpoints:
self.add_line(bkpt._format(running))
def find_breakpoint_by_idx(self, idx):
if idx >= 0 and idx < len(self.__breakpoints):
return self.__breakpoints[idx]
return None
def find_breakpoint(self, file, line=None):
for bkpt in self.__breakpoints:
if bkpt.file == file and (line is None or line is not None and bkpt.line == line):
return bkpt
return None
def load_data(self, data):
bkpts_add = []
bkpts_del = []
bkpt_uuid = uuid.uuid4()
for element in data['Breakpoints']:
cur_bkpt = DlvBreakpointType()
cur_bkpt._update({"Breakpoint": element})
if cur_bkpt.id <= 0:
continue
else:
cur_bkpt._set_uuid(bkpt_uuid)
bkpt = self.find_breakpoint(cur_bkpt.file, cur_bkpt.line)
if bkpt is None:
bkpts_add.append(cur_bkpt)
else:
bkpt._update({"Breakpoint": element})
bkpt._set_uuid(bkpt_uuid)
for bkpt in self.__breakpoints:
if bkpt._get_uuid() != bkpt_uuid and not bkpt._is_error():
bkpts_del.append(bkpt)
self.upgrade_breakpoints(bkpts_add, bkpts_del)
def toggle_breakpoint(self, elements):
assert (len(elements) > 0)
requests = []
bkpts_add = []
bkpts_del = []
bkpts_error_del = []
for element in elements:
bkpt = self.find_breakpoint(element['file'], element['line'])
if bkpt is not None:
if self.__prj.is_running():
if not bkpt._is_error():
requests.append({"cmd": self.const.CLEAR_BREAKPOINT_COMMAND, "parms": {"bkpt_id": bkpt.id, "bkpt_name": bkpt.name}})
else:
bkpts_error_del.append(bkpt)
else:
bkpts_del.append(bkpt)
else:
value = element['value']
if not value.startswith('//') and not value.startswith('/*') and not value.endswith('*/'):
bkpt = DlvBreakpointType(element['file'], element['line'])
requests.append({"cmd": self.const.CREATE_BREAKPOINT_COMMAND, "parms": bkpt._as_parm})
bkpts_add.append(bkpt)
else:
self.__prj.logger.debug("Source line %s:%d is empty or commented, skip add breakpoint" % (element['file'], element['line']))
if self.__prj.is_running():
if len(requests) > 0:
self.__prj.worker.do_batch(requests)
if len(bkpts_error_del) > 0 and self.upgrade_breakpoints([], bkpts_error_del):
self.update_view()
else:
if self.upgrade_breakpoints(bkpts_add, bkpts_del):
self.update_view()
def sync_breakpoints(self):
requests = []
bkpts = []
for bkpt in self.__breakpoints:
requests.append({"cmd": self.const.CREATE_BREAKPOINT_COMMAND, "parms": bkpt._as_parm})
bkpts.append({"file": bkpt.file, "line": bkpt.line})
requests.append({"cmd": self.const.CONTINUE_COMMAND, "parms": None})
self.__prj.add_goroutine_request(requests)
if len(requests) > 0:
self.__prj.add_breakpoint_request(requests)
self.__prj.worker.do_batch(requests)
if self.const.SAVE_BREAKPOINT:
self.const.save_breakpoints(bkpts)
if self.const.SAVE_WATCH:
self.__prj.watch_view.save_watches()
def update_breakpoint_lines(self, view=None):
got_changes = False
for bkpt in self.__breakpoints:
cur_view = view
if view is None:
cur_view = self.window.find_open_file(bkpt.file)
if cur_view is None:
continue
else:
if bkpt.file != view.file_name():
continue
else:
cur_view = view
region = cur_view.get_regions(bkpt._key)
assert (len(region) == 1)
row, col = cur_view.rowcol(region[0].a)
row += 1
if bkpt.line != row:
bkpt._update_line(row)
got_changes = True
return got_changes
class DlvStacktraceView(DlvView):
def __init__(self, prj, view):
super(DlvStacktraceView, self).__init__(prj.const.STACKTRACE_VIEW, prj.window, prj.const, view)
self.__prj = prj
self.__reset()
def __reset(self):
self.__locations = []
self.__cursor_position = 0
def open(self, reset=False):
super(DlvStacktraceView, self).open(reset)
if self.is_open():
self.set_syntax("Packages/GoDebug/GoDebug.tmLanguage")
if reset:
self.__reset()
self.update_view()
def clear(self, reset=False):
if reset:
self.__reset()
super(DlvStacktraceView, self).clear(reset)
def get_selected_frame(self):
return self.__cursor_position
def select_location(self, view=None):
if len(self.__locations) == 0:
self.view.erase_regions("dlv.location_pos")
return
loc = None
if view is not None:
new_row, new_col = self.view.rowcol(view.sel()[0].a)
if new_row == self.__cursor_position or new_row >= len(self.__locations):
return
else:
self.view.erase_regions("dlv.location_pos")
self.__cursor_position = new_row
loc = self.__locations[new_row]
find_view = self.window.find_open_file(loc.file)
if find_view is None:
self.window.focus_group(0)
self.window.open_file("%s:%d" % (loc.file, loc.line), sublime.ENCODED_POSITION)
if loc is None:
loc = self.__locations[self.__cursor_position]
self.view.add_regions("dlv.location_pos", [self.view.line(self.view.text_point(self.__cursor_position, 0))], \
"entity.name.class", "bookmark" if self.__prj.goroutine_view.is_current_goroutine_selected() and \
self.__cursor_position == 0 else "dot", sublime.HIDDEN)
goroutine_id = self.__prj.goroutine_view.get_selected_goroutine_id()
assert (goroutine_id > 0)
requests = []
self.__prj.add_variable_request(requests, {"goroutine_id": goroutine_id, "frame": self.__cursor_position})
self.__prj.add_watch_request(requests)
self.__prj.worker.do_batch(requests)
def load_data(self, data):
self.__reset()
if not self.__prj.is_running():
return
for element in data['Locations']:
loc = DlvLocationType()
loc._update({"Location": element})
self.__locations.append(loc)
def update_view(self):
super(DlvStacktraceView, self).update_view()
if not self.is_open():
return
for loc in self.__locations:
self.add_line(loc._format(), '')
self.select_location()
class DlvGoroutineView(DlvView):
def __init__(self, prj, view):
super(DlvGoroutineView, self).__init__(prj.const.GOROUTINE_VIEW, prj.window, prj.const, view)
self.__prj = prj
self.__reset()
def __reset(self):
self.__goroutines = []
self.__cursor_position = 0