Skip to content

Commit

Permalink
Run Black (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante authored Mar 24, 2023
1 parent 394fef9 commit 8ace809
Show file tree
Hide file tree
Showing 12 changed files with 138 additions and 77 deletions.
12 changes: 8 additions & 4 deletions FocusSublimeWindow.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,16 @@ class FocusSublimeWindowCommand(WindowCommand):
"""
Focuses the SublimeText window.
"""

def run(self, **args):
if NATIVE_FOCUS_WINDOW:
self.window.bring_to_front()

platform = sublime.platform()
if platform == 'linux':
os.system('sh -c "xdotool windowactivate $(xdotool search --class sublime | tail -1)"')
os.system(
'sh -c "xdotool windowactivate $(xdotool search --class sublime | tail -1)"'
)
elif platform == 'osx':
script = """
tell application "Sublime Text"
Expand All @@ -29,7 +32,8 @@ def run(self, **args):
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
subprocess.Popen(
'powershell -Command (New-Object -ComObject WScript.Shell).AppActivate({})'
.format(os.getppid()),
startupinfo=startupinfo
'powershell -Command (New-Object -ComObject WScript.Shell).AppActivate({})'.format(
os.getppid()
),
startupinfo=startupinfo,
)
34 changes: 26 additions & 8 deletions GhostText.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ def run(self):
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:
Expand All @@ -52,7 +53,10 @@ def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({"WebSocketPort": port, "ProtocolVersion": 1}).encode())
self.wfile.write(
json.dumps({"WebSocketPort": port, "ProtocolVersion": 1}).encode()
)


class HttpStatusServerThread(Thread):
def __init__(self, settings):
Expand All @@ -61,8 +65,12 @@ def __init__(self, settings):

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'))
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))

Expand All @@ -81,6 +89,7 @@ class ReplaceContentCommand(TextCommand):
"""
Replaces the views complete text content.
"""

def run(self, edit, **args):
self.view.replace(edit, sublime.Region(0, self.view.size()), args['text'])
text_length = len(args['text'])
Expand All @@ -102,7 +111,9 @@ def on_message(self, text):
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'])
current_view = window_helper.add_file(
request['title'] + '.' + syntax, request['text']
)
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)
Expand All @@ -128,10 +139,14 @@ def on_message(self, text):
class OnClose(AbstractOnClose):
def __init__(self, settings):
self._settings = settings
self._close_view_on_disconnect = bool(settings.get('close_view_on_disconnect', False))
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)
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:
Expand All @@ -140,14 +155,17 @@ def on_close(self):
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)
OnSelectionModifiedListener.unbind_view_by_web_socket_server_id(
self._web_socket_server
)
Utils.show_status('Connection closed')


class GhostTextGlobals():
class GhostTextGlobals:
"""
'Namespace' for global vars.
"""

http_status_server_thread = None


Expand Down
38 changes: 21 additions & 17 deletions GhostTextTools/OnSelectionModifiedListener.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,25 @@ class OnSelectionModifiedListener(EventListener):
"""
Handles content changes, each changes gets send with the given web socket server to the client.
"""

_bind_views = {}
_disabled = set()

def on_selection_modified(self, view):
vid = view.id()
if (
vid not in OnSelectionModifiedListener._bind_views
or vid in self._disabled
):
if vid not in OnSelectionModifiedListener._bind_views or vid in self._disabled:
return

changed_text = view.substr(sublime.Region(0, view.size()))
selections = OnSelectionModifiedListener._get_selections(view)
response = json.dumps({
'title': view.name(),
'text': changed_text,
'syntax': view.scope_name(0),
'selections': selections
})
response = json.dumps(
{
'title': view.name(),
'text': changed_text,
'syntax': view.scope_name(0),
'selections': selections,
}
)

OnSelectionModifiedListener._bind_views[view.id()].send_message(response)

Expand Down Expand Up @@ -87,7 +87,11 @@ def unbind_view_by_web_socket_server_id(web_socket_server):
"""
Unbinds a view specified by it's WebSocket server.
"""
view_id_to_unbind = OnSelectionModifiedListener.find_view_id_by_web_socket_server_id(web_socket_server)
view_id_to_unbind = (
OnSelectionModifiedListener.find_view_id_by_web_socket_server_id(
web_socket_server
)
)

if view_id_to_unbind is not None:
OnSelectionModifiedListener.unbind_view_by_id(view_id_to_unbind)
Expand All @@ -98,7 +102,10 @@ def find_view_id_by_web_socket_server_id(web_socket_server):
Searches a view by the given WebSocket server or returns None.
"""
for view_id in OnSelectionModifiedListener._bind_views:
if OnSelectionModifiedListener._bind_views[view_id].get_id() == web_socket_server.get_id():
if (
OnSelectionModifiedListener._bind_views[view_id].get_id()
== web_socket_server.get_id()
):
return view_id

return None
Expand All @@ -111,9 +118,6 @@ def _get_selections(view):
selections = []

for pos in view.sel():
selections.append({
'start': pos.begin(),
'end': pos.end()
})
selections.append({'start': pos.begin(), 'end': pos.end()})

return selections
return selections
14 changes: 10 additions & 4 deletions GhostTextTools/Utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import traceback


class Utils():
class Utils:
"""
Loose collection of GhostText related utils for working with the Sublime Text API.
"""
Expand All @@ -23,7 +23,11 @@ def show_error(e=None, hint='', message=''):
hint = ' - ' + hint

if e:
sublime.status_message('GhostText{}: {}, {}, {}'.format(hint, message, str(e), traceback.format_exc()))
sublime.status_message(
'GhostText{}: {}, {}, {}'.format(
hint, message, str(e), traceback.format_exc()
)
)
else:
sublime.status_message('GhostText{}: {}'.format(hint, message))

Expand Down Expand Up @@ -63,7 +67,9 @@ def close_view(view):
"""
window = view.window()
group_index, view_index = window.get_view_index(view)
window.run_command('close_by_index', {'group': group_index, 'index': view_index})
window.run_command(
'close_by_index', {'group': group_index, 'index': view_index}
)
if len(sublime.windows()) > 1 and len(window.views()) is 0:
window.run_command('close')

Expand Down Expand Up @@ -144,4 +150,4 @@ def get_syntax_by_host(host):

return host_to_syntax[host_fragment]

return settings.get('default_syntax')
return settings.get('default_syntax')
15 changes: 11 additions & 4 deletions GhostTextTools/WindowHelper.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ class WindowHelper(sublime.Window):
"""
Helper class for opening new files in the active sublime text window.
"""

def __init__(self):
self.window_id = sublime.active_window().id()
self._view_disconnected_prefix = Utils.get_view_prefix('disconnected')
Expand All @@ -17,7 +18,9 @@ def add_file(self, title, text):
Creates a new file and adds the given text content to it.
"""
view = self._find_disconnected_view(title)
view.set_name('{} {}'.format(self._view_connected_prefix, os.path.splitext(title)[0]))
view.set_name(
'{} {}'.format(self._view_connected_prefix, os.path.splitext(title)[0])
)
view.set_status('title', title)
view.run_command('replace_content', {'text': text})
view.set_scratch(True)
Expand All @@ -27,12 +30,16 @@ def add_file(self, title, text):
def _find_disconnected_view(self, title=None):
disconnected_views = []

if title is not None: # if title is set try to find the best match by exact title first
if (
title is not None
): # if title is set try to find the best match by exact title first
needle = '{} {}'.format(self._view_disconnected_prefix, title)
disconnected_views.extend(Utils.search_views_by_title(needle))

disconnected_views.extend(Utils.search_views_by_title(self._view_disconnected_prefix))
disconnected_views.extend(
Utils.search_views_by_title(self._view_disconnected_prefix)
)
if len(disconnected_views) > 0:
return disconnected_views[0]

return self.open_file(title)
return self.open_file(title)
2 changes: 1 addition & 1 deletion GhostTextTools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@

from .OnSelectionModifiedListener import OnSelectionModifiedListener
from .WindowHelper import WindowHelper
from .Utils import Utils
from .Utils import Utils
5 changes: 3 additions & 2 deletions WebSocket/AbstractHandler.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
class AbstractHandler():
class AbstractHandler:
"""
Abstract on whatever handler.
"""

def __init__(self):
self._web_socket_server = None

def set_web_socket_server(self, web_socket_server):
self._web_socket_server = web_socket_server
self._web_socket_server = web_socket_server
3 changes: 2 additions & 1 deletion WebSocket/AbstractOnClose.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ class AbstractOnClose(AbstractHandler):
"""
Abstract on connection close handler.
"""

def on_close(self):
raise NotImplementedError("error message")
raise NotImplementedError("error message")
3 changes: 2 additions & 1 deletion WebSocket/AbstractOnMessage.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ class AbstractOnMessage(AbstractHandler):
"""
Abstract on message handler.
"""

def on_message(self, text):
raise NotImplementedError("error message")
raise NotImplementedError("error message")
Loading

0 comments on commit 8ace809

Please sign in to comment.