forked from Floobits/floobits-sublime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfloobits.py
1054 lines (847 loc) · 36.5 KB
/
floobits.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
# coding: utf-8
try:
unicode()
except NameError:
unicode = str
import sys
import os
import re
import hashlib
import imp
import json
import uuid
import binascii
import subprocess
import traceback
import webbrowser
import threading
from collections import defaultdict
import sublime_plugin
import sublime
PY2 = sys.version_info < (3, 0)
if PY2 and sublime.platform() == 'windows':
sublime.error_message('Sorry, but the Windows version of Sublime Text 2 lacks Python’s select module, so the Floobits plugin won’t work. Please upgrade to Sublime Text 3. :(')
elif sublime.platform() == 'osx':
try:
p = subprocess.Popen(['/usr/bin/sw_vers', '-productVersion'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
result = p.communicate()
if float(result[0][:4]) < 10.7:
sublime.error_message('Sorry, but the Floobits plugin doesn\'t. Please upgrade your operating system if you want to use this plugin. :(')
except Exception as e:
print(e)
try:
import ssl
assert ssl
except ImportError:
ssl = False
if ssl is False and sublime.platform() == 'linux':
plugin_path = os.path.dirname(os.path.realpath(__file__))
if plugin_path in ('.', ''):
plugin_path = os.getcwd()
_ssl = None
ssl_versions = ['0.9.8', '1.0.0', '10', '1.0.1']
ssl_path = os.path.join(plugin_path, 'lib', 'linux')
lib_path = os.path.join(plugin_path, 'lib', 'linux-%s' % sublime.arch())
if not PY2:
ssl_path += '-py3'
lib_path += '-py3'
so_path = os.path.join(plugin_path, 'lib', 'custom')
try:
filename, path, desc = imp.find_module('_ssl', [so_path])
if filename:
_ssl = imp.load_module('_ssl', filename, path, desc)
except ImportError as e:
print('Failed loading custom _ssl module %s: %s' % (so_path, unicode(e)))
for version in ssl_versions:
if _ssl:
break
so_path = os.path.join(lib_path, 'libssl-%s' % version)
try:
filename, path, desc = imp.find_module('_ssl', [so_path])
if filename is None:
print('Module not found at %s' % so_path)
continue
_ssl = imp.load_module('_ssl', filename, path, desc)
break
except ImportError as e:
print('Failed loading _ssl module %s: %s' % (so_path, unicode(e)))
if _ssl:
print('Hooray! %s is a winner!' % so_path)
filename, path, desc = imp.find_module('ssl', [ssl_path])
if filename is None:
print('Couldn\'t find ssl module at %s' % ssl_path)
else:
try:
ssl = imp.load_module('ssl', filename, path, desc)
except ImportError as e:
print('Failed loading ssl module at: %s' % unicode(e))
else:
print('Couldn\'t find an _ssl shared lib that\'s compatible with your version of linux. Sorry :(')
try:
import urllib
urllib = imp.reload(urllib)
from urllib import request
request = imp.reload(request)
Request = request.Request
urlopen = request.urlopen
HTTPError = urllib.error.HTTPError
URLError = urllib.error.URLError
assert Request and urlopen and HTTPError and URLError
except ImportError:
import urllib2
urllib2 = imp.reload(urllib2)
Request = urllib2.Request
urlopen = urllib2.urlopen
HTTPError = urllib2.HTTPError
URLError = urllib2.URLError
try:
from .floo import version
from .floo import sublime_utils as sutils
from .floo.listener import Listener
from .floo.sublime_connection import SublimeConnection
from .floo.common import api, ignore, reactor, msg, shared as G, utils
from .floo.common.handlers.account import CreateAccountHandler
from .floo.common.handlers.credentials import RequestCredentialsHandler
assert HTTPError and api and G and ignore and msg and utils
except (ImportError, ValueError):
from floo import version
from floo import sublime_utils as sutils
from floo.listener import Listener
from floo.common import api, ignore, reactor, msg, shared as G, utils
from floo.common.handlers.account import CreateAccountHandler
from floo.common.handlers.credentials import RequestCredentialsHandler
from floo.sublime_connection import SublimeConnection
assert Listener and version
reactor = reactor.reactor
on_room_info_waterfall = utils.Waterfall()
ignore_modified_timeout = None
def update_recent_workspaces(workspace):
d = utils.get_persistent_data()
recent_workspaces = d.get('recent_workspaces', [])
recent_workspaces.insert(0, workspace)
recent_workspaces = recent_workspaces[:100]
seen = set()
new = []
for r in recent_workspaces:
string = json.dumps(r)
if string not in seen:
new.append(r)
seen.add(string)
d['recent_workspaces'] = new
utils.update_persistent_data(d)
def add_workspace_to_persistent_json(owner, name, url, path):
d = utils.get_persistent_data()
workspaces = d['workspaces']
if owner not in workspaces:
workspaces[owner] = {}
workspaces[owner][name] = {'url': url, 'path': path}
utils.update_persistent_data(d)
def get_legacy_projects():
a = ['msgs.floobits.log', 'persistent.json']
owners = os.listdir(G.COLAB_DIR)
floorc_json = defaultdict(defaultdict)
for owner in owners:
if len(owner) > 0 and owner[0] == '.':
continue
if owner in a:
continue
workspaces_path = os.path.join(G.COLAB_DIR, owner)
try:
workspaces = os.listdir(workspaces_path)
except OSError:
continue
for workspace in workspaces:
workspace_path = os.path.join(workspaces_path, workspace)
workspace_path = os.path.realpath(workspace_path)
try:
fd = open(os.path.join(workspace_path, '.floo'), 'r')
url = json.loads(fd.read())['url']
fd.close()
except Exception:
url = utils.to_workspace_url({
'port': 3448, 'secure': True, 'host': 'floobits.com', 'owner': owner, 'workspace': workspace
})
floorc_json[owner][workspace] = {
'path': workspace_path,
'url': url
}
return floorc_json
def migrate_symlinks():
data = {}
old_path = os.path.join(G.COLAB_DIR, 'persistent.json')
if not os.path.exists(old_path):
return
old_data = utils.get_persistent_data(old_path)
data['workspaces'] = get_legacy_projects()
data['recent_workspaces'] = old_data.get('recent_workspaces')
utils.update_persistent_data(data)
try:
os.unlink(old_path)
os.unlink(os.path.join(G.COLAB_DIR, 'msgs.floobits.log'))
except Exception:
pass
print('migrated')
def ssl_error_msg(action):
sublime.error_message('Your version of Sublime Text can\'t ' + action + ' because it has a broken SSL module. '
'This is a known issue on Linux builds of Sublime Text. '
'See this issue: https://github.com/SublimeText/Issues/issues/177')
def get_active_window(cb):
win = sublime.active_window()
if not win:
return utils.set_timeout(get_active_window, 50, cb)
cb(win)
def create_or_link_account():
agent = None
account = sublime.ok_cancel_dialog('You need a Floobits account!\n\n'
'Click "Open browser" if you have one or click "cancel" and we\'ll make it for you.',
'Open browser')
if account:
token = binascii.b2a_hex(uuid.uuid4().bytes).decode('utf-8')
agent = RequestCredentialsHandler(token)
elif not utils.get_persistent_data().get('disable_account_creation'):
agent = CreateAccountHandler()
if not agent:
sublime.error_message('A configuration error occured earlier. Please go to floobits.com and sign up to use this plugin.\n\nWe\'re really sorry. This should never happen.')
return
try:
reactor.connect(agent, G.DEFAULT_HOST, G.DEFAULT_PORT, True)
except Exception as e:
print(e)
tb = traceback.format_exc()
print(tb)
def global_tick():
reactor.tick()
utils.set_timeout(global_tick, G.TICK_TIME)
def disconnect_dialog():
if G.AGENT and G.JOINED_WORKSPACE:
disconnect = sublime.ok_cancel_dialog('You can only be in one workspace at a time.', 'Leave %s/%s' % (G.AGENT.owner, G.AGENT.workspace))
if disconnect:
msg.debug('Stopping agent.')
reactor.stop()
G.AGENT = None
return disconnect
return True
def on_room_info_msg():
who = 'Your friends'
anon_perms = G.AGENT.workspace_info.get('anon_perms')
if 'get_buf' in anon_perms:
who = 'Anyone'
_msg = 'You are sharing:\n\n%s\n\n%s can join your workspace at:\n\n%s' % (G.PROJECT_PATH, who, G.AGENT.workspace_url)
# Workaround for horrible Sublime Text bug
utils.set_timeout(sublime.message_dialog, 0, _msg)
def get_or_create_chat(cb=None):
if G.DEBUG:
msg.LOG_LEVEL = msg.LOG_LEVELS['DEBUG']
def return_view():
G.CHAT_VIEW_PATH = G.CHAT_VIEW.file_name()
G.CHAT_VIEW.set_read_only(True)
if cb:
return cb(G.CHAT_VIEW)
def open_view():
if not G.CHAT_VIEW:
p = os.path.join(G.BASE_DIR, 'msgs.floobits.log')
G.CHAT_VIEW = G.WORKSPACE_WINDOW.open_file(p)
utils.set_timeout(return_view, 0)
# Can't call open_file outside main thread
if G.LOG_TO_CONSOLE:
if cb:
return cb(None)
else:
utils.set_timeout(open_view, 0)
class FloobitsBaseCommand(sublime_plugin.WindowCommand):
def is_visible(self):
return bool(self.is_enabled())
def is_enabled(self):
return bool(G.AGENT and G.AGENT.is_ready())
class FloobitsOpenSettingsCommand(sublime_plugin.WindowCommand):
def run(self):
window = sublime.active_window()
if window:
window.open_file(G.FLOORC_PATH)
class FloobitsShareDirCommand(FloobitsBaseCommand):
def is_enabled(self):
return not super(FloobitsShareDirCommand, self).is_enabled()
def run(self, dir_to_share=None, paths=None, current_file=False, api_args=None):
global on_room_info_waterfall
self.api_args = api_args
utils.reload_settings()
if not (G.USERNAME and G.SECRET):
return create_or_link_account()
if paths:
if len(paths) != 1:
return sublime.error_message('Only one folder at a time, please. :(')
return self.on_input(paths[0])
if dir_to_share is None:
dir_to_share = os.path.expanduser(os.path.join('~', 'share_me'))
on_room_info_waterfall = utils.Waterfall()
self.window.show_input_panel('Directory to share:', dir_to_share, self.on_input, None, None)
def on_input(self, dir_to_share):
file_to_share = None
dir_to_share = os.path.expanduser(dir_to_share)
dir_to_share = os.path.realpath(utils.unfuck_path(dir_to_share))
workspace_name = os.path.basename(dir_to_share)
workspace_url = None
print(G.COLAB_DIR, G.USERNAME, workspace_name)
def find_workspace(workspace_url):
if ssl is False:
# No ssl module (broken Sublime Text). Just behave as if the workspace exists.
return True
try:
api.get_workspace_by_url(workspace_url)
except HTTPError:
try:
result = utils.parse_url(workspace_url)
d = utils.get_persistent_data()
del d['workspaces'][result['owner']][result['name']]
utils.update_persistent_data(d)
except Exception as e:
msg.debug(unicode(e))
return False
except URLError:
# Timeout or something bad. Just assume the workspace exists
return True
on_room_info_waterfall.add(ignore.create_flooignore, dir_to_share)
on_room_info_waterfall.add(lambda: G.AGENT.upload(dir_to_share, on_room_info_msg))
return True
if os.path.isfile(dir_to_share):
file_to_share = dir_to_share
dir_to_share = os.path.dirname(dir_to_share)
else:
try:
utils.mkdir(dir_to_share)
except Exception:
return sublime.error_message('The directory %s doesn\'t exist and I can\'t make it.' % dir_to_share)
floo_file = os.path.join(dir_to_share, '.floo')
info = {}
try:
floo_info = open(floo_file, 'r').read()
info = json.loads(floo_info)
except (IOError, OSError):
pass
except Exception:
print('Couldn\'t read the floo_info file: %s' % floo_file)
workspace_url = info.get('url')
try:
result = utils.parse_url(workspace_url)
except Exception:
workspace_url = None
if workspace_url and find_workspace(workspace_url):
add_workspace_to_persistent_json(result['owner'], result['workspace'], workspace_url, dir_to_share)
return self.window.run_command('floobits_join_workspace', {
'workspace_url': workspace_url,
'agent_conn_kwargs': {'get_bufs': False}})
for owner, workspaces in utils.get_persistent_data()['workspaces'].items():
for name, workspace in workspaces.items():
if workspace['path'] == dir_to_share:
workspace_url = workspace['url']
if find_workspace(workspace_url):
return self.window.run_command('floobits_join_workspace', {
'workspace_url': workspace_url,
'agent_conn_kwargs': {'get_bufs': False}})
# make & join workspace
on_room_info_waterfall.add(ignore.create_flooignore, dir_to_share)
on_room_info_waterfall.add(lambda: G.AGENT.upload(file_to_share or dir_to_share, on_room_info_msg))
def on_done(owner):
self.window.run_command('floobits_create_workspace', {
'workspace_name': workspace_name,
'dir_to_share': dir_to_share,
'api_args': self.api_args,
'owner': owner[0],
})
if ssl is False:
return on_done([G.USERNAME])
orgs = api.get_orgs_can_admin()
orgs = json.loads(orgs.read().decode('utf-8'))
if len(orgs) == 0:
return on_done([G.USERNAME])
orgs = [[org['name'], 'Create workspace under %s' % org['name']] for org in orgs]
orgs.insert(0, [G.USERNAME, 'Create workspace under %s' % G.USERNAME])
self.window.show_quick_panel(orgs, lambda index: index < 0 or on_done(orgs[index]))
class FloobitsCreateWorkspaceCommand(sublime_plugin.WindowCommand):
def is_visible(self):
return False
def is_enabled(self):
return True
# TODO: throw workspace_name in api_args
def run(self, workspace_name=None, dir_to_share=None, prompt='Workspace name:', api_args=None, owner=None):
if not disconnect_dialog():
return
if ssl is False:
return ssl_error_msg('create workspaces')
self.owner = owner or G.USERNAME
self.dir_to_share = dir_to_share
self.workspace_name = workspace_name
self.api_args = api_args or {}
if workspace_name and dir_to_share and prompt == 'Workspace name:':
return self.on_input(workspace_name, dir_to_share)
self.window.show_input_panel(prompt, workspace_name, self.on_input, None, None)
def on_input(self, workspace_name, dir_to_share=None):
if dir_to_share:
self.dir_to_share = dir_to_share
if workspace_name == '':
return self.run(dir_to_share=self.dir_to_share)
try:
self.api_args['name'] = workspace_name
self.api_args['owner'] = self.owner
msg.debug(str(self.api_args))
api.create_workspace(self.api_args)
workspace_url = 'https://%s/%s/%s' % (G.DEFAULT_HOST, self.owner, workspace_name)
print('Created workspace %s' % workspace_url)
except HTTPError as e:
err_body = e.read()
msg.error('Unable to create workspace: %s %s' % (unicode(e), err_body))
if e.code not in [400, 402, 409]:
return sublime.error_message('Unable to create workspace: %s %s' % (unicode(e), err_body))
kwargs = {
'dir_to_share': self.dir_to_share,
'workspace_name': workspace_name,
'api_args': self.api_args,
'owner': self.owner,
}
if e.code == 400:
kwargs['workspace_name'] = re.sub('[^A-Za-z0-9_\-\.]', '-', workspace_name)
kwargs['prompt'] = 'Invalid name. Workspace names must match the regex [A-Za-z0-9_\-\.]. Choose another name:'
elif e.code == 402:
try:
err_body = json.loads(err_body)
err_body = err_body['detail']
except Exception:
pass
return sublime.error_message('%s' % err_body)
else:
kwargs['prompt'] = 'Workspace %s/%s already exists. Choose another name:' % (self.owner, workspace_name)
return self.window.run_command('floobits_create_workspace', kwargs)
except Exception as e:
msg.error('Unable to create workspace: %s' % unicode(e))
return sublime.error_message('Unable to create workspace: %s' % unicode(e))
add_workspace_to_persistent_json(self.owner, workspace_name, workspace_url, self.dir_to_share)
self.window.run_command('floobits_join_workspace', {
'workspace_url': workspace_url,
'agent_conn_kwargs': {
'get_bufs': False
}
})
class FloobitsPromptJoinWorkspaceCommand(sublime_plugin.WindowCommand):
def run(self, workspace='https://floobits.com/'):
self.window.show_input_panel('Workspace URL:', workspace, self.on_input, None, None)
def on_input(self, workspace_url):
if disconnect_dialog():
self.window.run_command('floobits_join_workspace', {
'workspace_url': workspace_url,
})
class FloobitsJoinWorkspaceCommand(sublime_plugin.WindowCommand):
def run(self, workspace_url, agent_conn_kwargs=None):
agent_conn_kwargs = agent_conn_kwargs or {}
def get_workspace_window():
workspace_window = None
for w in sublime.windows():
for f in w.folders():
if utils.unfuck_path(f) == utils.unfuck_path(G.PROJECT_PATH):
workspace_window = w
break
return workspace_window
def set_workspace_window(cb):
workspace_window = get_workspace_window()
if workspace_window is None:
return utils.set_timeout(set_workspace_window, 50, cb)
G.WORKSPACE_WINDOW = workspace_window
cb()
def truncate_chat_view(chat_view, cb):
if chat_view:
chat_view.set_read_only(False)
chat_view.run_command('floo_view_replace_region', {'r': [0, chat_view.size()], 'data': ''})
chat_view.set_read_only(True)
cb()
def create_chat_view(cb):
with open(os.path.join(G.BASE_DIR, 'msgs.floobits.log'), 'a') as msgs_fd:
msgs_fd.write('')
get_or_create_chat(lambda chat_view: truncate_chat_view(chat_view, cb))
def open_workspace_window2(cb):
if sublime.platform() == 'linux':
subl = open('/proc/self/cmdline').read().split(chr(0))[0]
elif sublime.platform() == 'osx':
# TODO: totally explodes if you install ST2 somewhere else
settings = sublime.load_settings('Floobits.sublime-settings')
subl = settings.get('sublime_executable', '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl')
if not os.path.exists(subl):
return sublime.error_message('Can\'t find your Sublime Text executable at %s. Please add "sublime_executable /path/to/subl" to your ~/.floorc and restart Sublime Text' % subl)
elif sublime.platform() == 'windows':
subl = sys.executable
else:
raise Exception('WHAT PLATFORM ARE WE ON?!?!?')
command = [subl]
if get_workspace_window() is None:
command.append('--new-window')
command.append('--add')
command.append(G.PROJECT_PATH)
# Maybe no msg view yet :(
print('command:', command)
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
poll_result = p.poll()
print('poll:', poll_result)
set_workspace_window(lambda: create_chat_view(cb))
def open_workspace_window3(cb):
G.WORKSPACE_WINDOW = get_workspace_window()
if not G.WORKSPACE_WINDOW:
G.WORKSPACE_WINDOW = sublime.active_window()
msg.debug('Setting project data. Path: %s' % G.PROJECT_PATH)
G.WORKSPACE_WINDOW.set_project_data({'folders': [{'path': G.PROJECT_PATH}]})
create_chat_view(cb)
def open_workspace_window(cb):
if PY2:
open_workspace_window2(cb)
else:
open_workspace_window3(cb)
def run_agent(owner, workspace, host, port, secure):
global on_room_info_waterfall
if G.AGENT:
msg.debug('Stopping agent.')
reactor.stop()
G.AGENT = None
on_room_info_waterfall.add(update_recent_workspaces, {'url': workspace_url})
try:
conn = SublimeConnection(owner, workspace, agent_conn_kwargs.get("get_bufs", True))
reactor.connect(conn, host, port, secure)
conn.once('room_info', on_room_info_waterfall.call)
on_room_info_waterfall = utils.Waterfall()
except Exception as e:
print(e)
tb = traceback.format_exc()
print(tb)
def make_dir(d):
d = os.path.realpath(os.path.expanduser(d))
if not os.path.isdir(d):
make_dir = sublime.ok_cancel_dialog('%s is not a directory. Create it?' % d)
if not make_dir:
return self.window.show_input_panel('%s is not a directory. Enter an existing path:' % d, d, None, None, None)
try:
utils.mkdir(d)
except Exception as e:
return sublime.error_message('Could not create directory %s: %s' % (d, str(e)))
G.PROJECT_PATH = d
add_workspace_to_persistent_json(result['owner'], result['workspace'], workspace_url, d)
open_workspace_window(lambda: run_agent(**result))
try:
result = utils.parse_url(workspace_url)
except Exception as e:
return sublime.error_message(str(e))
utils.reload_settings()
if not (G.USERNAME and G.SECRET):
return create_or_link_account()
d = utils.get_persistent_data()
try:
G.PROJECT_PATH = d['workspaces'][result['owner']][result['workspace']]['path']
except Exception as e:
G.PROJECT_PATH = ''
print('Project path is %s' % G.PROJECT_PATH)
if not os.path.isdir(G.PROJECT_PATH):
default_dir = os.path.realpath(os.path.join(G.COLAB_DIR, result['owner'], result['workspace']))
return self.window.show_input_panel('Save workspace in directory:', default_dir, make_dir, None, None)
open_workspace_window(lambda: run_agent(**result))
class FloobitsPinocchioCommand(sublime_plugin.WindowCommand):
def is_visible(self):
return self.is_enabled()
def is_enabled(self):
return G.AUTO_GENERATED_ACCOUNT
def run(self):
floorc = utils.load_floorc()
username = floorc.get('USERNAME')
secret = floorc.get('SECRET')
print(username, secret)
if not (username and secret):
return sublime.error_message('You don\'t seem to have a Floobits account of any sort')
webbrowser.open('https://%s/%s/pinocchio/%s/' % (G.DEFAULT_HOST, username, secret))
class FloobitsLeaveWorkspaceCommand(FloobitsBaseCommand):
def run(self):
if G.AGENT:
reactor.stop()
G.AGENT = None
# TODO: Mention the name of the thing we left
sublime.error_message('You have left the workspace.')
else:
sublime.error_message('You are not joined to any workspace.')
class FloobitsPromptMsgCommand(FloobitsBaseCommand):
def run(self, msg=''):
print(('msg', msg))
self.window.show_input_panel('msg:', msg, self.on_input, None, None)
def on_input(self, msg):
self.window.run_command('floobits_msg', {'msg': msg})
class FloobitsMsgCommand(FloobitsBaseCommand):
def run(self, msg):
if not msg:
return
if G.AGENT:
G.AGENT.send_msg(msg)
def description(self):
return 'Send a message to the floobits workspace you are in (join a workspace first)'
class FloobitsClearHighlightsCommand(FloobitsBaseCommand):
def run(self):
G.AGENT.clear_highlights(self.window.active_view())
class FloobitsSummonCommand(FloobitsBaseCommand):
# TODO: ghost this option if user doesn't have permissions
def run(self):
G.AGENT.summon(self.window.active_view())
class FloobitsJoinRecentWorkspaceCommand(sublime_plugin.WindowCommand):
def _get_recent_workspaces(self):
self.recent_workspaces = utils.get_persistent_data()['recent_workspaces']
try:
recent_workspaces = [x.get('url') for x in self.recent_workspaces if x.get('url') is not None]
except Exception:
pass
return recent_workspaces
def run(self, *args):
workspaces = self._get_recent_workspaces()
self.window.show_quick_panel(workspaces, self.on_done)
def on_done(self, item):
if item == -1:
return
workspace = self.recent_workspaces[item]
if disconnect_dialog():
self.window.run_command('floobits_join_workspace', {'workspace_url': workspace['url']})
def is_enabled(self):
return bool(len(self._get_recent_workspaces()) > 0)
class FloobitsOpenMessageViewCommand(FloobitsBaseCommand):
def run(self, *args):
def print_msg(chat_view):
msg.log('Opened message view')
if not G.AGENT:
msg.log('Not joined to a workspace.')
get_or_create_chat(print_msg)
def description(self):
return 'Open the floobits messages view.'
class FloobitsAddToWorkspaceCommand(FloobitsBaseCommand):
def run(self, paths, current_file=False):
if not self.is_enabled():
return
if paths is None and current_file:
paths = [self.window.active_view().file_name()]
for path in paths:
G.AGENT.upload(path)
def description(self):
return 'Add file or directory to currently-joined Floobits workspace.'
class FloobitsDeleteFromWorkspaceCommand(FloobitsBaseCommand):
def run(self, paths, current_file=False):
if not self.is_enabled():
return
confirm = bool(sublime.ok_cancel_dialog('This will delete your local copy as well. Are you sure you want do do this?', 'Delete'))
if not confirm:
return
if paths is None and current_file:
paths = [self.window.active_view().file_name()]
for path in paths:
G.AGENT.delete_buf(path)
def description(self):
return 'Add file or directory to currently-joined Floobits workspace.'
class FloobitsCreateHangoutCommand(FloobitsBaseCommand):
def run(self):
owner = G.AGENT.owner
workspace = G.AGENT.workspace
webbrowser.open('https://plus.google.com/hangouts/_?gid=770015849706&gd=%s/%s' % (owner, workspace))
def is_enabled(self):
return bool(super(FloobitsCreateHangoutCommand, self).is_enabled() and G.AGENT.owner and G.AGENT.workspace)
class FloobitsPromptHangoutCommand(FloobitsBaseCommand):
def run(self, hangout_url):
confirm = bool(sublime.ok_cancel_dialog('This workspace is being edited in a Google+ Hangout? Do you want to join the hangout?'))
if not confirm:
return
webbrowser.open(hangout_url)
def is_visible(self):
return False
def is_enabled(self):
return bool(super(FloobitsPromptHangoutCommand, self).is_enabled() and G.AGENT.owner and G.AGENT.workspace)
class FloobitsOpenWebEditorCommand(FloobitsBaseCommand):
def run(self):
try:
agent = G.AGENT
url = utils.to_workspace_url({
'port': agent.proto.port,
'secure': agent.proto.secure,
'owner': agent.owner,
'workspace': agent.workspace,
'host': agent.proto.host,
})
webbrowser.open(url)
except Exception as e:
sublime.error_message('Unable to open workspace in web editor: %s' % unicode(e))
class FloobitsHelpCommand(FloobitsBaseCommand):
def run(self):
webbrowser.open('https://floobits.com/help/plugins/#sublime-usage', new=2, autoraise=True)
def is_visible(self):
return True
def is_enabled(self):
return True
class FloobitsEnableStalkerModeCommand(FloobitsBaseCommand):
def run(self):
G.STALKER_MODE = True
# TODO: go to most recent highlight
def is_enabled(self):
return bool(super(FloobitsEnableStalkerModeCommand, self).is_enabled() and not G.STALKER_MODE)
class FloobitsDisableStalkerModeCommand(FloobitsBaseCommand):
def run(self):
G.STALKER_MODE = False
G.SPLIT_MODE = False
def is_enabled(self):
return bool(super(FloobitsDisableStalkerModeCommand, self).is_enabled() and G.STALKER_MODE)
class FloobitsOpenWorkspaceSettingsCommand(FloobitsBaseCommand):
def run(self):
url = G.AGENT.workspace_url + '/settings'
webbrowser.open(url, new=2, autoraise=True)
def is_enabled(self):
return bool(super(FloobitsOpenWorkspaceSettingsCommand, self).is_enabled() and G.PERMS and 'kick' in G.PERMS)
class RequestPermissionCommand(FloobitsBaseCommand):
def run(self, perms, *args, **kwargs):
G.AGENT.send({
'name': 'request_perms',
'perms': perms
})
def is_enabled(self):
if not super(RequestPermissionCommand, self).is_enabled():
return False
if 'patch' in G.PERMS:
return False
return True
class FloobitsFollowSplit(FloobitsBaseCommand):
def run(self):
G.SPLIT_MODE = True
G.STALKER_MODE = True
if self.window.num_groups() == 1:
self.window.set_layout({
"cols": [0.0, 1.0],
"rows": [0.0, 0.5, 1.0],
"cells": [[0, 0, 1, 1], [0, 1, 1, 2]]
})
class FloobitsNotACommand(sublime_plugin.WindowCommand):
def run(self, *args, **kwargs):
pass
def is_visible(self):
return True
def is_enabled(self):
return False
def description(self):
return
# The new ST3 plugin API sucks
class FlooViewSetMsg(sublime_plugin.TextCommand):
def run(self, edit, data, *args, **kwargs):
size = self.view.size()
self.view.set_read_only(False)
self.view.insert(edit, size, data)
self.view.set_read_only(True)
# TODO: this scrolling is lame and centers text :/
self.view.show(size)
def is_visible(self):
return False
def is_enabled(self):
return True
def description(self):
return
def unignore_modified_events():
G.IGNORE_MODIFIED_EVENTS = False
def transform_selections(selections, start, new_offset):
new_sels = []
for sel in selections:
a = sel.a
b = sel.b
if sel.a > start:
a += new_offset
if sel.b > start:
b += new_offset
new_sels.append(sublime.Region(a, b))
return new_sels
# The new ST3 plugin API sucks
class FlooViewReplaceRegion(sublime_plugin.TextCommand):
def run(self, edit, *args, **kwargs):
selections = [x for x in self.view.sel()] # deep copy
selections = self._run(edit, selections, *args, **kwargs)
self.view.sel().clear()
for sel in selections:
self.view.sel().add(sel)
def _run(self, edit, selections, r, data, view=None):
global ignore_modified_timeout
if not getattr(self, 'view', None):
return selections
G.IGNORE_MODIFIED_EVENTS = True
utils.cancel_timeout(ignore_modified_timeout)
ignore_modified_timeout = utils.set_timeout(unignore_modified_events, 2)
start = max(int(r[0]), 0)
stop = min(int(r[1]), self.view.size())
region = sublime.Region(start, stop)
if stop - start > 10000:
self.view.replace(edit, region, data)
G.VIEW_TO_HASH[self.view.buffer_id()] = hashlib.md5(sutils.get_text(self.view).encode('utf-8')).hexdigest()
return transform_selections(selections, start, stop - start)
existing = self.view.substr(region)
i = 0
data_len = len(data)
existing_len = len(existing)
length = min(data_len, existing_len)
while (i < length):
if existing[i] != data[i]:
break
i += 1
j = 0
while j < (length - i):
if existing[existing_len - j - 1] != data[data_len - j - 1]:
break
j += 1
region = sublime.Region(start + i, stop - j)
replace_str = data[i:data_len - j]
self.view.replace(edit, region, replace_str)
G.VIEW_TO_HASH[self.view.buffer_id()] = hashlib.md5(sutils.get_text(self.view).encode('utf-8')).hexdigest()
new_offset = len(replace_str) - ((stop - j) - (start + i))
return transform_selections(selections, start + i, new_offset)
def is_visible(self):
return False
def is_enabled(self):
return True
def description(self):
return
# The new ST3 plugin API sucks
class FlooViewReplaceRegions(FlooViewReplaceRegion):
def run(self, edit, commands):
is_read_only = self.view.is_read_only()
self.view.set_read_only(False)
selections = [x for x in self.view.sel()] # deep copy
for command in commands:
selections = self._run(edit, selections, **command)
self.view.set_read_only(is_read_only)
self.view.sel().clear()
for sel in selections: