-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
GhostText.py
195 lines (155 loc) · 6.45 KB
/
GhostText.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
__author__ = 'Guido Krömer'
__license__ = 'MIT'
__version__ = '0.2'
__email__ = 'mail 64 cacodaemon 46 de'
import sublime
import http.server
import socketserver
from sublime import Window
from sublime_plugin import TextCommand
from sublime_plugin import EventListener
from threading import Thread
import json
from time import sleep
from .WebSocket.WebSocketServer import WebSocketServer
from .WebSocket.AbstractOnClose import AbstractOnClose
from .WebSocket.AbstractOnMessage import AbstractOnMessage
from .GhostTextTools.OnSelectionModifiedListener import OnSelectionModifiedListener
from .GhostTextTools.WindowHelper import WindowHelper
from .GhostTextTools.Utils import Utils
class WebSocketServerThread(Thread):
def __init__(self, settings):
super().__init__()
self._server = WebSocketServer('localhost', 0)
self._server.on_message(OnConnect(settings))
self._server.on_close(OnClose(settings))
def run(self):
self._server.start()
def get_server(self):
return self._server
class OnRequest(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
if len(sublime.windows()) == 0 or self.new_window_on_connect:
sublime.run_command('new_window')
if len(self.window_command_on_connect) > 0:
sublime.active_window().run_command(self.window_command_on_connect)
web_socket_server_thread = WebSocketServerThread(self._settings)
web_socket_server_thread.start()
while not web_socket_server_thread.get_server().get_running():
sleep(0.1)
port = web_socket_server_thread.get_server().get_port()
Utils.show_status('Connection opened')
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(
json.dumps({"WebSocketPort": port, "ProtocolVersion": 1}).encode()
)
class HttpStatusServerThread(Thread):
def __init__(self, settings):
super().__init__()
server_port = int(settings.get('server_port', 4001))
handler = OnRequest
handler._settings = settings
handler.new_window_on_connect = bool(
settings.get('new_window_on_connect', False)
)
handler.window_command_on_connect = str(
settings.get('window_command_on_connect', 'focus_sublime_window')
)
self._server = socketserver.TCPServer(("", server_port), OnRequest)
Utils.show_status('Ready on port ' + str(server_port))
def run(self):
try:
self._server.serve_forever()
except OSError as e:
Utils.show_error(e, 'HttpStatusServerThread')
raise e
def stop(self):
self._server.shutdown()
class ReplaceContentCommand(TextCommand):
"""
Replaces the views complete text content.
"""
def run(self, edit, **args):
# Temporarily disable conversion of tabs to spaces before
# pasting text, so that the selections stay valid
old_setting = self.view.settings().get('translate_tabs_to_spaces')
try:
self.view.settings().set('translate_tabs_to_spaces', False)
self.view.replace(edit, sublime.Region(0, self.view.size()), args['text'])
finally:
self.view.settings().set('translate_tabs_to_spaces', old_setting)
text_length = len(args['text'])
self.view.sel().clear()
if 'selections' in args and len(args['selections']) > 0:
selection = args['selections'][0]
self.view.sel().add(sublime.Region(selection['start'], selection['end']))
else:
self.view.sel().add(sublime.Region(text_length, text_length))
class OnConnect(AbstractOnMessage):
def __init__(self, settings):
self._settings = settings
def on_message(self, text):
try:
request = json.loads(text)
window_helper = WindowHelper()
syntax = Utils.get_syntax_by_host(request['url'])
current_view = window_helper.add_file(
request['title'] + '.' + syntax, request['text'], request.get('selections')
)
OnSelectionModifiedListener.bind_view(current_view, self._web_socket_server)
self._web_socket_server.on_message(OnMessage(self._settings, current_view))
current_view.window().focus_view(current_view)
except ValueError as e:
Utils.show_error(e, 'Invalid JSON')
class OnMessage(AbstractOnMessage):
def __init__(self, settings, current_view):
self._current_view = current_view
self._settings = settings
def on_message(self, text):
try:
request = json.loads(text)
with OnSelectionModifiedListener.disabled(self._current_view):
self._current_view.run_command('replace_content', request)
self._current_view.window().focus_view(self._current_view)
except ValueError as e:
Utils.show_error(e, 'Invalid JSON')
class OnClose(AbstractOnClose):
def __init__(self, settings):
self._settings = settings
self._close_view_on_disconnect = bool(
settings.get('close_view_on_disconnect', False)
)
def on_close(self):
view_id = OnSelectionModifiedListener.find_view_id_by_web_socket_server_id(
self._web_socket_server
)
if view_id is not None:
view = Utils.find_view_by_id(view_id)
if view is not None:
Utils.mark_view_as(view, 'disconnected')
if self._close_view_on_disconnect:
Utils.close_view_by_id(view_id)
OnSelectionModifiedListener.unbind_view_by_web_socket_server_id(
self._web_socket_server
)
Utils.show_status('Connection closed')
class GhostTextGlobals:
"""
'Namespace' for global vars.
"""
http_status_server_thread = None
def plugin_loaded():
print('GhostText is starting now…')
settings = sublime.load_settings('GhostText.sublime-settings')
GhostTextGlobals.http_status_server_thread = HttpStatusServerThread(settings)
GhostTextGlobals.http_status_server_thread.start()
Utils.replace_connected_with_disconnected_prefix()
def plugin_unloaded():
print('GhostText is stopping now…')
print(GhostTextGlobals.http_status_server_thread)
if GhostTextGlobals.http_status_server_thread is None:
return
GhostTextGlobals.http_status_server_thread.stop()
OnSelectionModifiedListener.unbind_all_views()