forked from sublimescala/sublime-ensime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ensime.py
2001 lines (1716 loc) · 72.9 KB
/
ensime.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
from sublime import *
from sublime_plugin import *
import os, threading, thread, socket, getpass, signal, glob
import subprocess, tempfile, datetime, time, json, zipfile
import functools, inspect, traceback, random, re, sys
from functools import partial as bind
from string import strip
from types import *
import env, diff, dotensime, dotsession, rpc
import sexp
from sexp import key, sym
from constants import *
from paths import *
from rpc import *
from sbt import *
class EnsimeCommon(object):
def __init__(self, owner):
self.owner = owner
if type(owner) == Window:
self._env = env.for_window(owner)
self._recalc_session_id()
self.w = owner
elif type(owner) == View:
# todo. find out why owner.window() is sometimes None
w = owner.window() or sublime.active_window()
self._env = env.for_window(w)
self._recalc_session_id()
self.w = w
self.v = owner
else:
raise Exception("unsupported owner of type: " + str(type(owner)))
@property
def env(self):
if not self._env:
self._env = env.for_window(self.w)
self._recalc_session_id()
return self._env
def _recalc_session_id(self):
self.session_id = self._env.session_id if self._env else None
@property
def rpc(self):
return self.env.rpc
def status_message(self, msg):
sublime.set_timeout(bind(sublime.status_message, msg), 0)
def error_message(self, msg):
sublime.set_timeout(bind(sublime.error_message, msg), 0)
def log(self, data):
sublime.set_timeout(bind(self.log_on_ui_thread, "ui", data), 0)
def log_client(self, data):
sublime.set_timeout(bind(self.log_on_ui_thread, "client", data), 0)
def log_server(self, data):
sublime.set_timeout(bind(self.log_on_ui_thread, "server", data), 0)
def log_on_ui_thread(self, flavor, data):
if flavor in self.env.settings.get("log_to_console", {}):
print data.strip()
if flavor in self.env.settings.get("log_to_file", {}):
try:
if not os.path.exists(self.env.log_root):
os.mkdir(self.env.log_root)
file_name = self.env.log_root + os.sep + flavor + ".log"
with open(file_name, "a") as f: f.write("[" + str(datetime.datetime.now()) + "]: " + data.strip() + "\n")
except:
exc_type, exc_value, exc_tb = sys.exc_info()
detailed_info = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
print detailed_info
def is_valid(self):
return self.env and self.env.valid
def is_running(self):
return self.is_valid() and self.env.running
def _filename_from_wannabe(self, wannabe):
if type(wannabe) == type(None):
v = self.v if hasattr(self, "v") else self.w.active_view()
return self._filename_from_wannabe(v) if v != None else None
if type(wannabe) == sublime.View:
return wannabe.file_name()
return wannabe
def in_project(self, wannabe = None):
filename = self._filename_from_wannabe(wannabe)
extension_ok = filename and (filename.endswith("scala") or filename.endswith("java"))
subpath_ok = self.env and is_subpath(self.env.project_root, filename)
return extension_ok and subpath_ok
def project_relative_path(self, wannabe):
filename = self._filename_from_wannabe(wannabe)
if not self.in_project(filename): return None
return relative_path(self.env.project_root, filename)
def _invoke_view_colorer(self, method, *args):
view = args[0]
args = args[1:]
if view == "default": view = self.v
if view != None:
colorer = Colorer(view)
getattr(colorer, method)(*args)
def _invoke_all_colorers(self, method, *args):
for i in range(0, self.w.num_groups()):
if self.w.views_in_group(i):
v = self.w.active_view_in_group(i)
colorer = Colorer(v)
getattr(colorer, method)(*args)
def colorize(self, view = "default"): self._invoke_view_colorer("colorize", view)
def colorize_all(self): self._invoke_all_colorers("colorize")
def uncolorize(self, view = "default"): self._invoke_view_colorer("uncolorize", view)
def uncolorize_all(self): self._invoke_all_colorers("uncolorize")
def redraw_highlights(self, view = "default"): self._invoke_view_colorer("redraw_highlights", view)
def redraw_all_highlights(self): self._invoke_all_colorers("redraw_highlights")
def redraw_status(self, view = "default"): self._invoke_view_colorer("redraw_status", view)
def redraw_breakpoints(self, view = "default"): self._invoke_view_colorer("redraw_breakpoints", view)
def redraw_all_breakpoints(self): self._invoke_all_colorers("redraw_breakpoints")
def redraw_debug_focus(self, view = "default"): self._invoke_view_colorer("redraw_debug_focus", view)
def redraw_all_debug_focuses(self): self._invoke_all_colorers("redraw_debug_focus")
def redraw_stack_focus(self, view = "default"): self._invoke_view_colorer("redraw_stack_focus", view)
def redraw_all_stack_focuses(self): self._invoke_all_colorers("redraw_stack_focus")
class EnsimeWindowCommand(EnsimeCommon, WindowCommand):
def __init__(self, window):
super(EnsimeWindowCommand, self).__init__(window)
self.window = window
class EnsimeTextCommand(EnsimeCommon, TextCommand):
def __init__(self, view):
super(EnsimeTextCommand, self).__init__(view)
self.view = view
class EnsimeEventListener(EnsimeCommon):
pass
class EnsimeEventListenerProxy(EventListener):
def __init__(self):
def is_ensime_event_listener(member):
return inspect.isclass(member) and member != EnsimeEventListener and issubclass(member, EnsimeEventListener)
self.listeners = map(lambda info: info[1], inspect.getmembers(sys.modules[__name__], is_ensime_event_listener))
def _invoke(self, view, handler_name, *args):
for listener in self.listeners:
instance = listener(view)
try: handler = getattr(instance, handler_name)
except: handler = None
if handler: return handler(*args)
def on_new(self, view):
return self._invoke(view, "on_new")
def on_clone(self, view):
return self._invoke(view, "on_clone")
def on_load(self, view):
return self._invoke(view, "on_load")
def on_close(self, view):
return self._invoke(view, "on_close")
def on_pre_save(self, view):
return self._invoke(view, "on_pre_save")
def on_post_save(self, view):
return self._invoke(view, "on_post_save")
def on_modified(self, view):
return self._invoke(view, "on_modified")
def on_selection_modified(self, view):
return self._invoke(view, "on_selection_modified")
def on_activated(self, view):
return self._invoke(view, "on_activated")
def on_deactivated(self, view):
return self._invoke(view, "on_deactivated")
def on_query_context(self, view, key, operator, operand, match_all):
return self._invoke(view, "on_query_context", key, operator, operand, match_all)
def on_query_completions(self, view, prefix, locations):
return self._invoke(view, "on_query_completions", prefix, locations)
class EnsimeSloppyMouseCommand(EnsimeTextCommand):
def run(self, edit):
raise Exception("abstract method: EnsimeSloppyMouseCommand.run")
class EnsimePreciseMouseCommand(EnsimeTextCommand):
def run(self, target):
raise Exception("abstract method: EnsimePreciseMouseCommand.run")
def is_applicable(self):
return self.is_running() and self.in_project()
def _run_underlying(self, args):
system_command = args["command"] if "command" in args else None
if system_command:
system_args = dict({"event": args["event"]}.items() + args["args"].items())
self.v.run_command(system_command, system_args)
# note the underscore in "run_"
def run_(self, args):
if self.is_applicable():
self.old_sel = [(r.a, r.b) for r in self.v.sel()]
# unfortunately, running an additive drag_select is our only way of getting the coordinates of the click
# I didn't find a way to convert args["event"]["x"] and args["event"]["y"] to text coordinates
# there are relevant APIs, but they refuse to yield correct results
self.v.run_command("drag_select", {"event": args["event"], "additive": True})
self.new_sel = [(r.a, r.b) for r in self.v.sel()]
self.diff = list((set(self.old_sel) - set(self.new_sel)) | (set(self.new_sel) - set(self.old_sel)))
if len(self.diff) == 0:
if len(self.new_sel) == 1:
self.run(self.new_sel[0][0])
else:
# this is a tough one
# here's how we possibly could arrive here
# we have a multi selection, and then ctrl+click on one the active cursors
# there's no way we can guess the exact point of click, so we bail
pass
elif len(self.diff) == 1:
sel = self.v.sel()
sel.clear()
sel.add(Region(self.diff[0][0], self.diff[0][1]))
self.run(self.diff[0][0])
else:
# this shouldn't happen
self.log("len(diff) > 1: command = " + str(type(self)) + ", old_sel = " + str(self.old_sel) + ", new_sel = " + str(self.new_sel))
else:
self._run_underlying(args)
class ValidOnly:
def is_enabled(self):
return self.is_valid()
class ProjectDoesntExist:
def is_enabled(self):
return not dotensime.exists(self.w)
class ProjectExists:
def is_enabled(self):
return dotensime.exists(self.w)
class NotRunningOnly:
def is_enabled(self):
return not self.is_running()
class RunningOnly:
def is_enabled(self):
return self.is_running()
class RunningProjectFileOnly:
def is_enabled(self):
return self.is_running() and self.in_project()
class ProjectFileOnly:
def is_enabled(self):
return self.in_project()
class NotDebuggingOnly:
def is_enabled(self):
return self.is_running() and not self.env.profile
class DebuggingOnly:
def is_enabled(self):
return self.is_running() and self.env.profile
class FocusedOnly:
def is_enabled(self):
return self.is_running() and self.env.focus
class EnsimeToolView(EnsimeCommon):
def __init__(self, env):
super(EnsimeToolView, self).__init__(env.w)
def can_show(self):
raise Exception("abstract method: EnsimeToolView.can_show(self)")
@property
def name(self):
raise Exception("abstract method: EnsimeToolView.name(self)")
def render(self):
raise Exception("abstract method: EnsimeToolView.render(self)")
def setup_events(self, v):
v.settings().set("result_file_regex", "([:.a-z_A-Z0-9\\\\/-]+[.](?:scala|java)):([0-9]+)")
v.settings().set("result_line_regex", "")
v.settings().set("result_base_dir", self.env.project_root)
other_view = self.w.new_file()
self.w.focus_view(other_view)
self.w.run_command("close_file")
self.w.focus_view(v)
def handle_event(self, event, target):
pass
@property
def v(self):
wannabes = filter(lambda v: v.name() == self.name, self.w.views())
return wannabes[0] if wannabes else None
def _mk_v(self):
v = self.w.new_file()
v.set_scratch(True)
v.set_name(self.name)
self.setup_events(v)
return v
def _update_v(self, content):
if self.v != None:
v = self.v
edit = v.begin_edit()
v.replace(edit, Region(0, v.size()), content)
v.end_edit(edit)
v.sel().clear()
v.sel().add(Region(0, 0))
def clear(self):
self._update_v("")
# TODO: ideally, rendering should only happen when a tool view is visible
def refresh(self):
if self.v != None:
content = self.render() or ""
self._update_v(content)
def show(self):
if self.v == None:
self._mk_v()
self.refresh()
self.w.focus_view(self.v)
############################## LOW-LEVEL: CLIENT & SERVER ##############################
class ClientListener:
def on_client_async_data(self, data):
pass
class ClientSocket(EnsimeCommon):
def __init__(self, owner, port, timeout, handlers):
super(ClientSocket, self).__init__(owner)
self.port = port
self.timeout = timeout
self.connected = False
self.handlers = handlers
self._lock = threading.RLock()
self._connect_lock = threading.RLock()
self._receiver = None
self.socket = None
def notify_async_data(self, data):
for handler in self.handlers:
if handler:
handler.on_client_async_data(data)
def receive_loop(self):
while self.connected:
try:
msglen = self.socket.recv(6)
if msglen:
msglen = int(msglen, 16)
# self.log_client("RECV: incoming message of " + str(msglen) + " bytes")
buf = ""
while len(buf) < msglen:
chunk = self.socket.recv(msglen - len(buf))
if chunk:
# self.log_client("RECV: received a chunk of " + str(len(chunk)) + " bytes")
buf += chunk
else:
raise Exception("fatal error: recv returned None")
self.log_client("RECV: " + buf)
try:
s = buf.decode('utf-8')
form = sexp.read(s)
self.notify_async_data(form)
except:
self.log_client("failed to parse incoming message")
raise
else:
raise Exception("fatal error: recv returned None")
except Exception:
self.log_client("***** ERROR *****")
self.log_client(traceback.format_exc())
self.connected = False
self.status_message("Ensime server has disconnected")
# todo. do we need to check session_ids somewhere else as well?
if self.env.session_id == self.session_id:
self.env.controller.shutdown()
def start_receiving(self):
t = threading.Thread(name = "ensime-client-" + str(self.w.id()) + "-" + str(self.port), target = self.receive_loop)
t.setDaemon(True)
t.start()
self._receiver = t
def connect(self):
self._connect_lock.acquire()
try:
s = socket.socket()
s.settimeout(self.timeout)
s.connect(("127.0.0.1", self.port))
s.settimeout(None)
self.socket = s
self.connected = True
self.start_receiving()
return s
except socket.error as e:
self.connected = False
self.log_client("Cannot connect to Ensime server: " + str(e.args))
self.status_message("Cannot connect to Ensime server")
self.env.controller.shutdown()
finally:
self._connect_lock.release()
def send(self, request):
try:
if not self.connected:
self.connect()
self.socket.send(request)
except:
self.connected = False
def close(self):
self._connect_lock.acquire()
try:
if self.socket:
self.socket.close()
finally:
self.connected = False
self._connect_lock.release()
class Client(ClientListener, EnsimeCommon):
def __init__(self, owner, port_file, timeout):
super(Client, self).__init__(owner)
with open(port_file) as f: self.port = int(f.read())
self.timeout = timeout
self.init_counters()
methods = filter(lambda m: m[0].startswith("message_"), inspect.getmembers(self, predicate=inspect.ismethod))
self.log_client("reflectively found " + str(len(methods)) + " message handlers: " + str(methods))
self.handlers = dict((":" + m[0][len("message_"):].replace("_", "-"), (m[1], None, None)) for m in methods)
def startup(self):
self.log_client("Starting Ensime client (plugin version is " + (self.env.settings.get("plugin_version") or "unknown") + ")")
self.log_client("Launching Ensime client socket at port " + str(self.port))
self.socket = ClientSocket(self.owner, self.port, self.timeout, [self, self.env.controller])
return self.socket.connect()
def shutdown(self):
if self.socket.connected: self.rpc.shutdown_server()
self.socket.close()
self.socket = None
def async_req(self, to_send, on_complete = None, call_back_into_ui_thread = None):
if on_complete is not None and call_back_into_ui_thread is None:
raise Exception("must specify a threading policy when providing a non-empty callback")
if not self.socket:
raise Exception("socket is either not yet initialized or is already destroyed")
msg_id = self.next_message_id()
self.handlers[msg_id] = (on_complete, call_back_into_ui_thread, time.time())
msg_str = sexp.to_string([key(":swank-rpc"), to_send, msg_id])
msg_str = "%06x" % len(msg_str) + msg_str
self.feedback(msg_str)
self.log_client("SEND ASYNC REQ: " + msg_str)
self.socket.send(msg_str.encode('utf-8'))
def sync_req(self, to_send, timeout=0):
msg_id = self.next_message_id()
event = threading.Event()
self.handlers[msg_id] = (event, None, time.time())
msg_str = sexp.to_string([key(":swank-rpc"), to_send, msg_id])
msg_str = "%06x" % len(msg_str) + msg_str
self.feedback(msg_str)
self.log_client("SEND SYNC REQ: " + msg_str)
self.socket.send(msg_str)
max_wait = timeout or self.timeout
event.wait(max_wait)
if hasattr(event, "payload"):
return event.payload
else:
self.log_client("sync_req #" + str(msg_id) +
" has timed out (didn't get a response after " +
str(max_wait) + " seconds)")
return None
def on_client_async_data(self, data):
self.log_client("SEND ASYNC RESP: " + str(data))
self.feedback(str(data))
self.handle_message(data)
# examples of responses can be seen here:
# http://docs.sublimescala.org
def handle_message(self, data):
# (:return (:ok (:pid nil :server-implementation (:name "ENSIMEserver") :machine nil :features nil :version "0.0.1")) 1)
# (:background-message "Initializing Analyzer. Please wait...")
# (:compiler-ready t)
# (:typecheck-result (:lang :scala :is-full t :notes nil))
msg_type = str(data[0])
handler = self.handlers.get(msg_type)
if handler:
handler, _, _ = handler
msg_id = data[-1] if msg_type == ":return" else None
data = data[1:-1] if msg_type == ":return" else data[1:]
payload = None
if len(data) == 1: payload = data[0]
if len(data) > 1: payload = data
return handler(msg_id, payload)
else:
self.log_client("unexpected message type: " + msg_type)
def message_return(self, msg_id, payload):
handler, call_back_into_ui_thread, req_time = self.handlers.get(msg_id)
if handler: del self.handlers[msg_id]
def invoke_subscribed_handler(success, payload = None):
if callable(handler):
# only do async callbacks if the result is a success
# however note that we need to ping sync callbacks in any case
# in order to prevent freezes upon erroneous responses
if call_back_into_ui_thread and success:
sublime.set_timeout(bind(handler, payload), 0)
else:
handler(payload)
else:
handler.payload = payload
handler.set()
resp_time = time.time()
self.log_client("request #" + str(msg_id) + " took " + str(resp_time - req_time) + " seconds")
reply_type = str(payload[0])
# (:return (:ok (:project-name nil :source-roots ("D:\\Dropbox\\Scratchpad\\Scala"))) 2)
if reply_type == ":ok":
payload = payload[1]
if handler:
invoke_subscribed_handler(success = True, payload = payload)
else:
self.log_client("warning: no handler registered for message #" + str(msg_id) + " with payload " + str(payload))
# (:return (:abort 210 "Error occurred in Analyzer. Check the server log.") 3)
elif reply_type == ":abort":
detail = payload[2]
if msg_id <= 1: # initialize project
self.error_message(self.prettify_error_detail(detail))
self.status_message("Ensime startup has failed")
self.env.controller.shutdown()
else:
invoke_subscribed_handler(success = False)
self.status_message(detail)
# (:return (:error NNN "SSS") 4)
elif reply_type == ":error":
detail = payload[2]
invoke_subscribed_handler(success = False)
self.error_message(self.prettify_error_detail(detail))
else:
invoke_subscribed_handler(success = False)
self.log_client("unexpected reply type: " + reply_type)
def call_back_into_ui_thread(vanilla):
def wrapped(self, msg_id, payload):
sublime.set_timeout(bind(vanilla, self, msg_id, payload), 0)
return wrapped
@call_back_into_ui_thread
def message_compiler_ready(self, msg_id, payload):
self.env.compiler_ready = True
filename = self.env.plugin_root + os.sep + "Encouragements.txt"
lines = [line.strip() for line in open(filename)]
msg = lines[random.randint(0, len(lines) - 1)]
self.status_message(msg + " This could be the start of a beautiful program, " + getpass.getuser().capitalize() + ".")
self.colorize_all()
v = self.w.active_view()
if self.in_project(v): v.run_command("save")
@call_back_into_ui_thread
def message_indexer_ready(self, msg_id, payload):
pass
@call_back_into_ui_thread
def message_full_typecheck_finished(self, msg_id, payload):
pass
@call_back_into_ui_thread
def message_background_message(self, msg_id, payload):
# (:background-message 105 "Initializing Analyzer. Please wait...")
self.status_message(payload[1])
def _update_note_ui(self):
self.redraw_all_highlights()
v = self.w.active_view()
if v != None:
self.env.notee = v
self.env.notes.refresh()
@call_back_into_ui_thread
def message_java_notes(self, msg_id, payload):
self.env._notes.append(rpc.Note.parse_list(payload))
self._update_note_ui()
@call_back_into_ui_thread
def message_scala_notes(self, msg_id, payload):
self.env._notes.append(rpc.Note.parse_list(payload))
self._update_note_ui()
@call_back_into_ui_thread
def message_clear_all_java_notes(self, msg_id, _):
self.env._notes.filter(lambda n: not n.file_name.endswith(".java"))
self._update_note_ui()
@call_back_into_ui_thread
def message_clear_all_scala_notes(self, msg_id, _):
self.env._notes.filter(lambda n: not n.file_name.endswith(".scala"))
self._update_note_ui()
@call_back_into_ui_thread
def message_debug_event(self, msg_id, payload):
debug_event = rpc.DebugEvent.parse(payload)
if debug_event: self.env.debugger.handle(debug_event)
def init_counters(self):
self._counter = 0
self._counterLock = threading.RLock()
def next_message_id(self):
self._counterLock.acquire()
try:
self._counter += 1
return self._counter
finally:
self._counterLock.release()
def prettify_error_detail(self, detail):
detail = "Ensime server has encountered a fatal error: " + detail
if detail.endswith(". Check the server log."):
detail = detail[0:-len(". Check the server log.")]
if not detail.endswith("."): detail += "."
detail += "\n\nCheck the server log at " + self.env.log_root + os.sep + "server.log" + "."
return detail
def feedback(self, msg):
msg = msg.replace("\r\n", "\n").replace("\r", "\n") + "\n"
self.log_client(msg)
class ServerListener:
def on_server_data(self, data):
pass
class ServerProcess(EnsimeCommon):
def __init__(self, owner, command, listeners):
super(ServerProcess, self).__init__(owner)
self.killed = False
self.listeners = listeners or []
env = os.environ.copy()
args = self.env.ensime_args or "-Xms256M -Xmx1512M -XX:PermSize=128m -Xss1M -Dfile.encoding=UTF-8"
if not "-Densime.explode.on.disconnect" in args: args += " -Densime.explode.on.disconnect=1"
env["ENSIME_JVM_ARGS"] = str(args) # unicode not supported here
if os.name =="nt":
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow |= 1 # SW_SHOWNORMAL
creationflags = 0x8000000 # CREATE_NO_WINDOW
self.proc = subprocess.Popen(
command,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
startupinfo = startupinfo,
creationflags = creationflags,
env = env,
cwd = self.env.server_path)
else:
self.proc = subprocess.Popen(
command,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
env = env,
cwd = self.env.server_path)
self.log_server("started ensime server with pid " + str(self.proc.pid))
if self.proc.stdout:
thread.start_new_thread(self.read_stdout, ())
if self.proc.stderr:
thread.start_new_thread(self.read_stderr, ())
def kill(self):
if not self.killed:
self.killed = True
self.proc.kill()
self.listeners = []
def poll(self):
return self.proc.poll() == None
def read_stdout(self):
while True:
data = os.read(self.proc.stdout.fileno(), 2**15)
if data != "":
for listener in self.listeners:
if listener:
listener.on_server_data(data)
else:
self.proc.stdout.close()
break
def read_stderr(self):
while True:
data = os.read(self.proc.stderr.fileno(), 2**15)
if data != "":
for listener in self.listeners:
if listener:
listener.on_server_data(data)
else:
self.proc.stderr.close()
break
class Server(ServerListener, EnsimeCommon):
def __init__(self, owner, port_file):
super(Server, self).__init__(owner)
self.port_file = port_file
def startup(self):
ensime_command = self.get_ensime_command()
if self.get_ensime_command() and self.verify_ensime_version():
self.log_server("Starting Ensime server (plugin version is " + (self.env.settings.get("plugin_version") or "unknown") + ")")
self.log_server("Launching Ensime server process with command = " + str(ensime_command) + " and args = " + str(self.env.ensime_args))
self.proc = ServerProcess(self.owner, ensime_command, [self, self.env.controller])
return True
def get_ensime_command(self):
if not os.path.exists(self.env.ensime_executable):
message = "Ensime server executable \"" + self.env.ensime_executable + "\" does not exist."
message += "\n\n"
message += "If you haven't yet installed Ensime server, download it from http://download.sublimescala.org, "
message += "and unpack it into the \"server\" subfolder of the SublimeEnsime plugin home, which is usually located at " + sublime.packages_path() + os.sep + "Ensime. "
message += "Your installation is correct if inside the \"server\" subfolder there are folders named \"bin\" and \"lib\"."
message += "\n\n"
message += "If you have already installed Ensime server, check your Ensime.sublime-settings (accessible via Preferences > Package Settings > Ensime) "
message += "and make sure that the \"ensime_server_path\" entry points to a valid location relative to " + sublime.packages_path() + " "
message += "(currently it points to the path shown above)."
self.error_message(message)
return
return [self.env.ensime_executable, self.port_file]
def verify_ensime_version(self):
self.log_server("Verifying Ensime server version")
ensime_jar_dir = self.env.server_path + os.sep + "lib"
ensime_jars = filter(os.path.isfile, glob.glob(ensime_jar_dir + os.sep + "ensime*.jar"))
if len(ensime_jars) != 1:
self.log_server("Error: no ensime*.jar files found in " + ensime_jar_dir)
self.log_server("Warning: skipping the version check, proceeding with starting up the server")
return True
ensime_jar = None
try:
ensime_jar = zipfile.ZipFile(ensime_jars[0], "r")
manifest = ensime_jar.open("META-INF/MANIFEST.MF", "r").readlines()
def parse_line(line):
try:
m = re.match(r"^(.*?):(.*)$", line)
return (m.group(1).strip(), m.group(2).strip())
except:
self.log_server("Problems parsing line: " + line)
manifest = dict(parse_line(line) for line in manifest if line.strip())
def parse_version(s):
try:
m = re.match(r"^(\d+)\.(\d+)(?:.(\d+)(?:.(\d+))?)?$", s)
return map(lambda s: int(s), filter(lambda s: s, m.groups()))
except:
self.log_server("Problems parsing version: " + s)
aversion = parse_version(manifest["Implementation-Version"])
rversion = parse_version(self.env.settings.get("min_ensime_server_version"))
self.log_server("Required version: " + str(rversion) + ", actual version: " + str(aversion))
if aversion < rversion:
message = "Ensime server version is " + manifest["Implementation-Version"] + ", "
message += "required version is at least " + str(self.env.settings.get("min_ensime_server_version")) + "."
message += "\n\n"
message += "To update your Ensime server, download a suitable version from http://download.sublimescala.org, "
message += "and unpack it into the \"server\" subfolder of the SublimeEnsime plugin home, which is usually located at " + sublime.packages_path() + os.sep + "Ensime. "
message += "Your installation is correct if inside the \"server\" subfolder there are folders named \"bin\" and \"lib\"."
self.error_message(message)
return
return True
except:
exc_type, exc_value, exc_tb = sys.exc_info()
detailed_info = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
self.log_server("Error verifying Ensime server version:" + detailed_info)
self.log_server("Warning: skipping the version check, proceeding with starting up the server")
return True
finally:
if ensime_jar: ensime_jar.close()
def on_server_data(self, data):
str_data = str(data).replace("\r\n", "\n").replace("\r", "\n")
self.log_server(str_data)
def shutdown(self):
self.proc.kill()
self.proc = None
class Controller(EnsimeCommon, ClientListener, ServerListener):
def __init__(self, env):
super(Controller, self).__init__(env.w)
self.client = None
self.server = None
def startup(self):
try:
if not self.env.running:
if self.env.settings.get("connect_to_external_server", False):
self.port_file = self.env.settings.get("external_server_port_file")
if not self.port_file:
message = "\"connect_to_external_server\" in your Ensime.sublime-settings is set to true, "
message += "however \"external_server_port_file\" is not specified. "
message += "Set it to a meaningful value and restart Ensime."
sublime.set_timeout(bind(sublime.error_message, message), 0)
raise Exception("external_server_port_file not specified")
if not os.path.exists(self.port_file):
message = "\"connect_to_external_server\" in your Ensime.sublime-settings is set to true, "
message += ("however \"external_server_port_file\" is set to a non-existent file \"" + self.port_file + "\" . ")
message += "Check the configuration and restart Ensime."
sublime.set_timeout(bind(sublime.error_message, message), 0)
raise Exception("external_server_port_file not specified")
self.server = None
self.env.running = True
sublime.set_timeout(self.ignition, 0)
else:
_, port_file = tempfile.mkstemp("_ensime_port")
self.port_file = port_file
self.server = Server(self.owner, port_file)
self.server.startup() # delay handshake until the port number has been written
except:
self.env.running = False
raise
def on_server_data(self, data):
if not self.env.running and re.search("Wrote port", data):
self.env.running = True
sublime.set_timeout(self.ignition, 0)
def ignition(self):
timeout = self.env.settings.get("timeout_sync_roundtrip", 3)
self.client = Client(self.owner, self.port_file, timeout)
self.client.startup()
self.status_message("Initializing Ensime server... ")
def init_project(subproject_name):
conf = self.env.project_config + [key(":active-subproject"), subproject_name]
self.rpc.init_project(conf)
dotensime.select_subproject(self.env.project_config, self.owner, init_project)
def shutdown(self):
try:
if self.env.running:
try:
self.env.debugger.shutdown()
except:
self.log("Error shutting down ensime debugger:")
self.log(traceback.format_exc())
try:
self.env._notes.clear()
sublime.set_timeout(self.uncolorize_all, 0)
sublime.set_timeout(self.env.notes.clear, 0)
except:
self.log("Error shutting down ensime UI:")
self.log(traceback.format_exc())
try:
if self.client:
self.client.shutdown()
except:
self.log_client("Error shutting down ensime client:")
self.log(traceback.format_exc())
try:
if self.server:
self.server.shutdown()
except:
self.log_server("Error shutting down ensime server:")
self.log(traceback.format_exc())
finally:
self.port_file = None
self.env.running = False
self.env.compiler_ready = False
self.client = None
self.server = None
############################## ENSIME <-> SUBLIME ADAPTER ##############################
class Daemon(EnsimeEventListener):
def on_load(self):
# print "on_load"
if self.is_running() and self.in_project():
self.rpc.typecheck_file(self.v.file_name())
def on_post_save(self):
# print "on_post_save"
if self.is_running() and self.in_project():
self.rpc.typecheck_file(self.v.file_name())
if same_paths(self.v.file_name(), self.env.session_file):
self.env.load_session()
self.redraw_all_breakpoints()
def on_activated(self):
# print "on_activated"
self.colorize()
if self.in_project():
self.env.notee = self.v
self.env.notes.refresh()
def on_selection_modified(self):
# print "on_selection_modified"
self.redraw_status()
def on_modified(self):
# print "on_modified"
rs = self.v.get_regions(ENSIME_BREAKPOINT_REGION)
if rs:
irrelevant_breakpoints = filter(
lambda b: not same_paths(b.file_name, self.v.file_name()),
self.env.breakpoints)
def new_breakpoint_position(r):
lines = self.v.lines(r)
if lines:
(linum, _) = self.v.rowcol(lines[0].begin())
return dotsession.Breakpoint(self.v.file_name(), linum + 1)
relevant_breakpoints = filter(lambda b: b, map(new_breakpoint_position, rs))
self.env.breakpoints = irrelevant_breakpoints + relevant_breakpoints
self.env.save_session()
self.redraw_breakpoints()
class Colorer(EnsimeCommon):
def colorize(self):
self.uncolorize()
self.redraw_highlights()
self.redraw_status()
self.redraw_breakpoints()
self.redraw_debug_focus()
self.redraw_stack_focus()
def uncolorize(self):
self.v.erase_regions(ENSIME_ERROR_OUTLINE_REGION)
self.v.erase_regions(ENSIME_ERROR_UNDERLINE_REGION)
# don't erase breakpoints, they should be permanent regardless of whether ensime is running or not
# self.v.erase_regions(ENSIME_BREAKPOINT_REGION)
self.v.erase_regions(ENSIME_DEBUGFOCUS_REGION)
self.v.erase_regions(ENSIME_STACKFOCUS_REGION)
self.redraw_status()
def redraw_highlights(self):
self.v.erase_regions(ENSIME_ERROR_OUTLINE_REGION)
self.v.erase_regions(ENSIME_ERROR_UNDERLINE_REGION)
if self.env:
relevant_notes = self.env._notes.for_file(self.v.file_name())
# Underline specific error range
underlines = [sublime.Region(note.start, note.end) for note in relevant_notes]
if self.env.settings.get("error_highlight") and self.env.settings.get("error_underline"):
self.v.add_regions(
ENSIME_ERROR_UNDERLINE_REGION,
underlines + self.v.get_regions(ENSIME_ERROR_UNDERLINE_REGION),
self.env.settings.get("error_scope"),
sublime.DRAW_EMPTY_AS_OVERWRITE)
# Outline entire errored line
errors = [self.v.full_line(note.start) for note in relevant_notes]
if self.env.settings.get("error_highlight"):
self.v.add_regions(
ENSIME_ERROR_OUTLINE_REGION,
errors + self.v.get_regions(ENSIME_ERROR_OUTLINE_REGION),
self.env.settings.get("error_scope"),
self.env.settings.get("error_icon"),
sublime.DRAW_OUTLINED)
# we might need to add/remove/refresh the error message in the status bar
self.redraw_status()
# breakpoints and debug focus should always have priority over red squiggles
self.redraw_breakpoints()
self.redraw_debug_focus()
self.redraw_stack_focus()
def redraw_status(self, custom_status = None):
if custom_status:
self._update_statusbar(custom_status)