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

40 restore connection #58

Open
wants to merge 29 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
481059f
Implemented INSTALL_PREFIX env variable
KES777 May 14, 2015
b05c91a
Bring window under ST3
KES777 Sep 19, 2015
5223ac7
Revert "Implemented INSTALL_PREFIX env variable"
KES777 Sep 19, 2015
9e93aa8
IMPLEMENTED: method to remove empty folders
KES777 Sep 21, 2015
dce40ff
Cleanup variable names
KES777 Sep 21, 2015
44796d5
IMPLEMENTED: WORKDIR
KES777 Sep 21, 2015
bf9bdbc
Remove empty folders recursively
KES777 Sep 21, 2015
249f28a
Create full directory tree structure on local host as on remote
KES777 Sep 21, 2015
b9ca5cd
Reformatting code for readability
KES777 Sep 21, 2015
bbcc0df
Revert "Implemented INSTALL_PREFIX env variable"
KES777 Sep 21, 2015
1bce1db
Revert "Implemented INSTALL_PREFIX env variable"
KES777 Sep 21, 2015
6fac4bb
FIX wrong url
KES777 Sep 21, 2015
768b893
FIXED: plugin_loaded() is invoked for both Sublime 2 & 3
KES777 Sep 21, 2015
d2c4976
Merge branch 'feature/48_fix_install_url'
KES777 Sep 21, 2015
a284c1e
Merge branch 'feature/43_not_bringing_sublime_text_3'
KES777 Sep 21, 2015
ed6acdd
Merge branch 'feature/45_does_not_open_new_tab_for_already_opened_file'
KES777 Sep 21, 2015
38873bc
TYPO FIX
KES777 Sep 21, 2015
0c9737f
Merge branch 'feature/45_does_not_open_new_tab_for_already_opened_file'
KES777 Sep 21, 2015
37c1b61
Move removeEmptyFolders out of class
KES777 Sep 21, 2015
e30bf9a
Merge branch 'feature/45_does_not_open_new_tab_for_already_opened_fil…
KES777 Sep 21, 2015
8b3bead
Put code to bring sublime to front on its own function
KES777 Sep 21, 2015
32a3983
Cleanup working directory when plugin is unloaded/reloaded
KES777 Sep 21, 2015
1793730
Restore remote editing
KES777 Sep 21, 2015
e35797f
Store work_dir to the view
KES777 Sep 21, 2015
4b87ea5
Remove WORKDIR tree for the view
KES777 Sep 21, 2015
314d6c4
import global variable into function
KES777 Sep 21, 2015
8311450
Point current session to file where old view buffer belongs to
KES777 Sep 21, 2015
65183c1
Send local modifications to remote
KES777 Sep 21, 2015
a3dd742
Code reformatting
KES777 Sep 21, 2015
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
136 changes: 106 additions & 30 deletions rsub.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import os
import tempfile
import socket

from threading import Thread
try:
import socketserver
Expand All @@ -20,21 +21,59 @@

SESSIONS = {}
server = None
WINDOW_HANDLE = 'sublime_text.Sublime_text'
WORKDIR = None


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

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


# http://www.jacobtomlinson.co.uk/2014/02/16/python-script-recursively-remove-empty-folders-directories/
def removeEmptyFolders( path, removeRoot=True ):
'Function to remove empty folders'
if not os.path.isdir(path):
return

# remove empty subfolders
files = os.listdir(path)
if len(files):
for f in files:
fullpath = os.path.join(path, f)
if os.path.isdir(fullpath):
removeEmptyFolders(fullpath)

# if folder empty, delete it
files = os.listdir(path)
if len(files) == 0 and removeRoot:
print( "Removing empty folder:", path )
os.rmdir(path)



class Session:
def __init__(self, socket):
self.env = {}
self.file = b""
self.file_size = 0
self.in_file = False
self.env = {}
self.file = b""
self.file_size = 0
self.in_file = False
self.parse_done = False
self.socket = socket
self.temp_path = None
self.socket = socket
self.temp_file = None


def parse_input(self, input_line):
if (input_line.strip() == b"open" or self.parse_done is True):
Expand Down Expand Up @@ -71,43 +110,75 @@ def close(self):
self.socket.send(b"\n")
self.socket.shutdown(socket.SHUT_RDWR)
self.socket.close()
os.unlink(self.temp_path)
os.rmdir(self.temp_dir)
os.unlink(self.temp_file)
try:
removeEmptyFolders( self.env['work_dir'], True )
except OSError as e:
sublime.error_message( 'Can not clean WORKDIR: %s' % e )


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")
temp_file = open(self.temp_file, "rb")
new_file = temp_file.read()
temp_file.close()
self.socket.send(b"data: " + str(len(new_file)).encode("utf8") + b"\n")
self.socket.send(new_file)
self.socket.send(b"\n")

def on_done(self):
global WORKDIR, SESSIONS
# Create a secure temporary directory, both for privacy and to allow
# multiple files with the same basename to be edited at once without
# overwriting each other.

self.env['host'] = self.env['display-name'].split(':')[0]

v_list = sublime.active_window().views();
for v in v_list:
env = v.settings().get( 'rsub' )
if (
bool( env )
and not v.id() in SESSIONS
and self.env['host'] == env['host']
and self.env['real-path'] == env['real-path']
):
self.env['work_dir'] = env['work_dir']
SESSIONS[ v.id() ] = self
self.temp_file = v.file_name()
self.send_save()
sublime.active_window().focus_view( v )
bring_to_front()
return


self.env['work_dir'] = WORKDIR
self.temp_dir = WORKDIR +"/" +self.env['host'] +os.path.dirname( self.env['real-path'] )

try:
self.temp_dir = tempfile.mkdtemp(prefix='rsub-')
if not os.path.exists( self.temp_dir ) :
os.makedirs( self.temp_dir )
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]))
self.temp_file = os.path.join(
self.temp_dir,
os.path.basename( self.env['display-name'].split(':')[-1] )
)
try:
temp_file = open(self.temp_path, "wb+")
temp_file = open( self.temp_file, "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.
if os.path.exists(self.temp_path):
os.remove(self.temp_path)
if os.path.exists( self.temp_file ):
os.remove( self.temp_file )
try:
os.rmdir(self.temp_dir)
except OSError:
pass
removeEmptyFolders( self.temp_dir )
except OSError as e:
sublime.error_message( 'Can not clean WORKDIR: %s' % e )

sublime.error_message('Failed to write to temp file! Error: %s' % str(e))

Expand All @@ -116,7 +187,7 @@ def on_done(self):
sublime.run_command("new_window")

# Open it within sublime
view = sublime.active_window().open_file(self.temp_path)
view = sublime.active_window().open_file( self.temp_file )

# Add the file metadata to the view's settings
# This is mostly useful to obtain the path of this file on the server
Expand All @@ -126,16 +197,7 @@ def on_done(self):
SESSIONS[view.id()] = self

# Bring sublime to front
if(sublime.platform() == 'osx'):
if(SBApplication):
subl_window = SBApplication.applicationWithBundleIdentifier_("com.sublimetext.2")
subl_window.activate()
else:
os.system("/usr/bin/osascript -e '%s'" %
'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)
bring_to_front()


class ConnectionHandler(socketserver.BaseRequestHandler):
Expand Down Expand Up @@ -185,8 +247,14 @@ def on_close(self, view):
say('Closed ' + sess.env['display-name'])


def plugin_unloaded():
global WORKDIR

removeEmptyFolders( WORKDIR )


def plugin_loaded():
global SESSIONS, server
global SESSIONS, WINDOW_HANDLE, WORKDIR, server

# Load settings
settings = sublime.load_settings("rsub.sublime-settings")
Expand All @@ -198,6 +266,14 @@ def plugin_loaded():
Thread(target=start_server, args=[]).start()
say('Server running on ' + host + ':' + str(port) + '...')

try:
WORKDIR = tempfile.mkdtemp(prefix='rsub-')
except OSError as e:
sublime.error_message('Failed to create rsub temporary working directory! Error: %s' % e)
return


# call the plugin_loaded() function if running in sublime text 2
if (int(sublime.version())< 3000):
WINDOW_HANDLE = 'sublime_text.sublime-text-2'
plugin_loaded()