Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Some code-style improvements #38

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 27 additions & 29 deletions rsub.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import sublime, sys
import sublime
import sublime_plugin
import os
import tempfile
import socket
import sys
import tempfile
from threading import Thread
try:
import socketserver
Expand All @@ -23,10 +24,11 @@


def say(msg):
print ('[rsub] ' + msg)
print('[rsub] ' + msg)


class Session:

def __init__(self, socket):
self.env = {}
self.file = b""
Expand All @@ -37,18 +39,18 @@ def __init__(self, socket):
self.temp_path = None

def parse_input(self, input_line):
if (input_line.strip() == b"open" or self.parse_done is True):
if input_line.strip() == b"open" or self.parse_done:
return

if(self.in_file is False):
if not self.in_file:
input_line = input_line.decode("utf8").strip()
if (input_line == ""):
return
if (input_line == "."):
self.parse_file(b".\n")
return
k, v = input_line.split(":", 1)
if (k == "data"):
if k == "data":
self.file_size = int(v)
if len(self.env) > 1:
self.in_file = True
Expand All @@ -58,7 +60,7 @@ def parse_input(self, input_line):
self.parse_file(input_line)

def parse_file(self, line):
if(len(self.file) >= self.file_size and line == b".\n"):
if len(self.file) >= self.file_size and line == b".\n":
self.in_file = False
self.parse_done = True
sublime.set_timeout(self.on_done, 0)
Expand All @@ -77,9 +79,8 @@ def close(self):
def send_save(self):
self.socket.send(b"save\n")
self.socket.send(b"token: " + self.env['token'].encode("utf8") + b"\n")
temp_file = open(self.temp_path, "rb")
new_file = temp_file.read()
temp_file.close()
with open(self.temp_path, 'rb') as f:
new_file = f.read()
self.socket.send(b"data: " + str(len(new_file)).encode("utf8") + b"\n")
self.socket.send(new_file)
self.socket.send(b"\n")
Expand All @@ -93,11 +94,12 @@ def on_done(self):
except OSError as e:
sublime.error_message('Failed to create rsub temporary directory! Error: %s' % e)
return
self.temp_path = os.path.join(self.temp_dir, os.path.basename(self.env['display-name'].split(':')[-1]))

filename = os.path.basename(self.env['display-name'].split(':')[-1])
self.temp_path = os.path.join(self.temp_dir, filename)
try:
temp_file = open(self.temp_path, "wb+")
temp_file.write(self.file[:self.file_size])
temp_file.flush()
temp_file.close()
except IOError as e:
# Remove the file if it exists.
Expand All @@ -119,36 +121,34 @@ def on_done(self):

# Add the file metadata to the view's settings
# This is mostly useful to obtain the path of this file on the server
view.settings().set('rsub',self.env)
view.settings().set('rsub', self.env)

# Add the session to the global list
SESSIONS[view.id()] = self

# Bring sublime to front
if(sublime.platform() == 'osx'):
if(SBApplication):
if sublime.platform() == 'osx':
if SBApplication:
subl_window = SBApplication.applicationWithBundleIdentifier_("com.sublimetext.2")
subl_window.activate()
else:
os.system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Sublime Text" to true' ''')
elif(sublime.platform() == 'linux'):
os.system('/usr/bin/osascript -e '
'\'tell app "Finder" to set frontmost of process "Sublime Text" to true\'')
elif sublime.platform() == 'linux':
import subprocess
subprocess.call("wmctrl -xa 'sublime_text.sublime-text-2'", shell=True)



class ConnectionHandler(socketserver.BaseRequestHandler):

def handle(self):
say('New connection from ' + str(self.client_address))

session = Session(self.request)
self.request.send(b"Sublime Text 2 (rsub plugin)\n")

socket_fd = self.request.makefile("rb")
while True:
line = socket_fd.readline()
if(len(line) == 0):
break
socket_fd = self.request.makefile('rb')
for line in iter(socket_fd.readline, b''):
session.parse_input(line)

say('Connection close.')
Expand All @@ -171,14 +171,15 @@ def unload_handler():


class RSubEventListener(sublime_plugin.EventListener):

def on_post_save(self, view):
if (view.id() in SESSIONS):
if view.id() in SESSIONS:
sess = SESSIONS[view.id()]
sess.send_save()
say('Saved ' + sess.env['display-name'])

def on_close(self, view):
if(view.id() in SESSIONS):
if view.id() in SESSIONS:
sess = SESSIONS.pop(view.id())
sess.close()
say('Closed ' + sess.env['display-name'])
Expand All @@ -198,9 +199,6 @@ def plugin_loaded():
say('Server running on ' + host + ':' + str(port) + '...')



# call the plugin_loaded() function if running in sublime text 2
if (int(sublime.version())<3000):
if int(sublime.version()) < 3000:
plugin_loaded()