- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLayout.py
More file actions
Latest commit
508 lines (417 loc) · 15.6 KB
/
Copy pathLayout.py
File metadata and controls
508 lines (417 loc) · 15.6 KB
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
importos
importjson
importsublime
importsublime_plugin
PLUGIN_NAME='Layout'
PLUGIN_PATH=os.path.join(sublime.packages_path(), PLUGIN_NAME)
LAYOUTS_PATH=os.path.join(PLUGIN_PATH, 'layouts')
X_MIN, Y_MIN, X_MAX, Y_MAX= (0, 1, 2, 3)
defplugin_loaded():
ifnotos.path.isdir(LAYOUTS_PATH):
os.makedirs(LAYOUTS_PATH)
defSettings():
returnsublime.load_settings('%s.sublime-settings'%PLUGIN_NAME)
classPaneCommand(sublime_plugin.WindowCommand):
@property
deflayout(self):
returnself.window.get_layout()
@property
defcells(self):
returnself.window.get_layout()['cells']
@property
defcurrent_group(self):
returnself.window.active_group()
@classmethod
defget_layout_path(cls, filename):
returnos.path.join(LAYOUTS_PATH, filename+'.layout')
deffixed_set_layout(self, layout):
# A bug was introduced in Sublime Text 3, sometime before 3053,
# in that it changes the active group to 0 when the layout is changed.
group=min(self.current_group, self.window.num_groups() -1)
self.window.set_layout(layout)
self.fixed_focus_group(group)
deffixed_focus_group(self, group):
# I have no idea why this is work instead of
# `self.window.focus_group(group)`
sublime.set_timeout(lambda : self.window.focus_group(group), 0)
sublime.set_timeout(lambda : self.window.focus_group(group), 0)
deflayout_to_json(self):
layout=self.layout
layout['views_in_group'] = []
layout['active_group'] =self.current_group
defview_to_jsonable(view):
returndict(
file_name=view.file_name(),
name=view.name(),
is_read_only=view.is_read_only(),
is_scratch=view.is_scratch()
)
foriinrange(len(layout['cells'])):
views=self.window.views_in_group(i)
views= [view_to_jsonable(view) forviewinviews]
layout['views_in_group'].append(views)
returnjson.dumps(layout, indent=2)
defload_layout_from_json(self, layout):
layout=json.loads(layout)
self.fixed_set_layout(layout)
defdict_to_view(view_dict, group, index):
view=self.window.open_file(view_dict['file_name'])
view.set_scratch(view_dict['is_scratch'])
view.set_name(view_dict['name'])
view.set_read_only(view_dict['is_read_only'])
self.window.set_view_index(view, group, index)
returnview
forgroupinrange(len(layout['cells'])):
views=layout['views_in_group'][group]
views= [dict_to_view(views[i], group, i) foriinrange(len(views))]
self.fixed_focus_group(0)
defget_adjacent_cells(self, group):
cells=self.cells
adjacent_cells= {
'left': [],
'right': [],
'up': [],
'down': [],
}
c=cells.pop(group)
x1, y1, x2, y2=c[X_MIN], c[Y_MIN], c[X_MAX], c[Y_MAX]
foracincells:
direction=None
ax1, ay1, ax2, ay2=ac[X_MIN], ac[Y_MIN], ac[X_MAX], ac[Y_MAX]
if (ax1<=x1<ax2) or (ax1<x2<=ax2):
ify1==ay2:
direction='up'
elify2==ay1:
direction='down'
if (ay1<=y1<ay2) or (ay1<y2<=ay2):
ifx1==ax2:
direction='left'
elifx2==ax1:
direction='right'
ifdirection:
adjacent_cells[direction].append(ac)
returnadjacent_cells
deflayout_to_value_cells(self, layout):
value_cells= []
rows=layout['rows']
cols=layout['cols']
forx1, y1, x2, y2inlayout['cells']:
value_cells.append([cols[x1], rows[y1], cols[x2], rows[y2]])
returnvalue_cells
defvalue_cells_to_layout(self, value_cells):
rows=set()
cols=set()
forc1, r1, c2, r2invalue_cells:
cols.add(c1)
rows.add(r1)
cols.add(c2)
rows.add(r2)
cols=list(cols)
rows=list(rows)
cols.sort()
rows.sort()
max_x=0
cells= []
forc1, r1, c2, r2invalue_cells:
x1, y1, x2, y2=cols.index(c1), rows.index(r1), cols.index(c2), rows.index(r2)
cells.append([x1, y1, x2, y2])
ifmax_x<x2:
max_x=x2
# cells arrange by y1 first then x1
cells.sort(key=lambdac: c[Y_MIN] * (max_x+1) +c[X_MIN])
layout= {'cols': cols, 'rows': rows, 'cells': cells}
returnlayout
defresize_pane(self, group, direction, step):
MIN_GAP=0.15
layout=self.layout
rows=layout['rows']
cols=layout['cols']
cells=layout['cells']
x1, y1, x2, y2=cells[group]
max_x, max_y=len(cols) -1, len(rows) -1
# resize by adjust ruler
ifdirection=='left':
# if is border
ifx1==0andx2==max_x:
return
# littler x
lx=0ifx1-1<0elsex1-1
ifx1>0andcols[x1] -cols[lx] >MIN_GAP:
cols[x1] -=step
ifx1==0andcols[x2] -cols[x1] >MIN_GAP:
cols[x2] -=step
elifdirection=='right':
ifx2==max_xandx1==0:
return
# greater x
gx=1ifx2+1>max_xelsex2+1
ifx2<max_xandcols[gx] -cols[x2] >MIN_GAP:
cols[x2] +=step
ifx2==max_xandcols[x2] -cols[x1] >MIN_GAP:
cols[x1] +=step
elifdirection=='up':
ify1==0andy2==max_y:
return
ly=0ify1-1<0elsey1-1
ify1>0androws[y1] -rows[ly] >MIN_GAP:
rows[y1] -=step
ify1==0androws[y2] -rows[y1] >MIN_GAP:
rows[y2] -=step
elifdirection=='down':
ify2==max_yandy1==0:
return
gy=1ify2+1>max_yelsey2+1
ify2<max_yandrows[gy] -rows[y2] >MIN_GAP:
rows[y2] +=step
ify2==max_yandrows[y2] -rows[y1] >MIN_GAP:
rows[y1] +=step
else:
return
layout= {'rows': rows, 'cols': cols, 'cells': cells}
self.fixed_set_layout(layout)
defsplit_pane(self, group, pattern, scale):
rows=self.layout['rows']
cols=self.layout['cols']
coord_cells=self.layout['cells']
try:
# (x1, y1) is top left point, (x2, y2) is bottom right point
x1, y1, x2, y2=coord_cells.pop(group)
c1, r1, c2, r2=cols[x1], rows[y1], cols[x2], rows[y2]
except:
return
value_cells=self.layout_to_value_cells({
'rows': rows,
'cols': cols,
'cells': coord_cells
})
# vertical
ifpattern=='v':
c= (c2-c1) *scale+c1
old_cell= [c1, r1, c, r2]
new_cell= [c, r1, c2, r2]
# horizontal
elifpattern=='h':
r= (r2-r1) *scale+r1
old_cell= [c1, r1, c2, r]
new_cell= [c1, r, c2, r2]
else:
return
value_cells.append(old_cell)
value_cells.append(new_cell)
layout=self.value_cells_to_layout(value_cells)
self.fixed_set_layout(layout)
defdestroy_pane(self, group):
layout=self.layout
cells=layout['cells']
try:
x1, y1, x2, y2=cells.pop(group)
except:
return
adjacent_cells=self.get_adjacent_cells(group)
adjacent_cells['left'].sort(key=lambdac: c[Y_MIN])
adjacent_cells['right'].sort(key=lambdac: c[Y_MIN])
adjacent_cells['up'].sort(key=lambdac: c[X_MIN])
adjacent_cells['down'].sort(key=lambdac: c[X_MIN])
extend_direction=None
fordir, csinadjacent_cells.items():
ifnotcs:
continue
if ((y1==cs[0][Y_MIN] andy2==cs[-1][Y_MAX]) or
(x1==cs[0][X_MIN] andx2==cs[-1][X_MAX])):
extend_direction=dir
ifextend_direction:
pair= {
'left': (X_MAX, x2),
'right': (X_MIN, x1),
'up': (Y_MAX, y2),
'down': (Y_MIN, y1),
}[extend_direction]
else:
return
forextend_cellinadjacent_cells[extend_direction]:
try:
i=cells.index(extend_cell)
except:
continue
cells[i][pair[0]] =pair[1]
layout['cells'] =cells
# remove extra rulers of column or row and reset cells
value_cells=self.layout_to_value_cells(layout)
layout=self.value_cells_to_layout(value_cells)
# kill all views in pane
ifSettings().get('auto_close_view'):
self.window.run_command('close')
self.fixed_set_layout(layout)
defget_closest_group(self, direction):
adjacent_cells=self.get_adjacent_cells(self.current_group)
try:
group=self.cells.index(adjacent_cells[direction][0])
except:
group=-1
returngroup
defmove_to_pane(self, direction):
group=self.get_closest_group(direction)
ifgroup==-1:
return
self.fixed_focus_group(group)
defcarry_file_to_pane(self, direction):
group=self.get_closest_group(direction)
view=self.window.active_view()
ifnot (viewandgroup>=0):
return
self.window.set_view_index(view, group, 0)
self.fixed_focus_group(group)
defclone_file_to_pane(self, direction):
view=self.window.active_view()
self.window.run_command("clone_file")
self.carry_file_to_pane(direction)
self.window.focus_view(view)
defget_options(self, command):
command=command.lower()
if'v'incommand:
pattern='v'
elif'h'incommand:
pattern='h'
else:
raiseException(': Invalid command string'%PLUGIN_NAME)
i=command.find(pattern)
group=int(command[:i] orself.current_group)
scale=int(command[i+1:] or50) /100
returngroup, pattern, scale
classRecordable(object):
defdo_run(self, *args, **kwargs):
raiseNotImplemented
@classmethod
defadd_history(cls, item):
iflen(cls.history) >cls.max_history_num:
cls.history.pop(0)
cls.history.append(item)
@classmethod
defadd_redo_history(cls, item):
iflen(cls.redo_history) >cls.max_history_num:
cls.redo_history.pop(0)
cls.redo_history.append(item)
@classmethod
defnext_record(cls):
item=cls.history.pop()
returnitem
@classmethod
defprev_record(cls):
item=cls.redo_history.pop()
returnitem
@classmethod
defclear_history(cls):
cls.history= []
cls.redo_history= []
classMoveableCommand(PaneCommand, Recordable):
# history of move between panes
history= []
redo_history= []
max_history_num=Settings().get('max_move_history') or100
defrun(self, *args, **kwargs):
self.add_history(self.current_group)
self.do_run(*args, **kwargs)
classRevocableCommand(PaneCommand, Recordable):
# history of move between panes
history= []
redo_history= []
max_history_num=Settings().get('max_layout_history') or10
defrun(self, *args, **kwargs):
self.add_history(self.layout_to_json())
# Clear move history every time
MoveableCommand.clear_history()
self.do_run(*args, **kwargs)
classMoveToPaneCommand(MoveableCommand):
defdo_run(self, direction):
self.move_to_pane(direction)
classCycleBetweenPanesCommand(MoveableCommand):
defdo_run(self):
num_groups=self.window.num_groups()
next_group=self.current_group+1
ifnext_group>num_groups-1:
next_group=0
self.fixed_focus_group(next_group)
classReverseCycleBetweenPanesCommand(MoveableCommand):
defdo_run(self):
num_groups=self.window.num_groups()
prev_group=self.current_group-1
ifprev_group<0:
prev_group=num_groups-1
self.fixed_focus_group(prev_group)
classSplitPaneCommand(RevocableCommand):
defdo_run(self, commands):
forcommandincommands:
group, pattern, scale=self.get_options(command)
self.split_pane(group, pattern, scale)
classCombineAllPanesCommand(RevocableCommand):
defdo_run(self):
self.fixed_set_layout({
'rows': [0, 1],
'cols': [0, 1],
'cells': [[0, 0, 1, 1]]
})
classDestroyCurrentPaneCommand(RevocableCommand):
defdo_run(self):
self.destroy_pane(self.current_group)
classCloneFileToPaneCommand(RevocableCommand):
defdo_run(self, direction):
self.clone_file_to_pane(direction)
classCarryFileToPaneCommand(RevocableCommand):
defdo_run(self, direction):
self.carry_file_to_pane(direction)
classResizePaneCommand(PaneCommand):
defrun(self, direction, step=1):
self.resize_pane(self.current_group, direction, step/100)
classLoadLayoutFromCommand(PaneCommand):
defload_layout_from_file(self, filename):
layout=open(self.get_layout_path(filename), 'r').read()
self.load_layout_from_json(layout)
defrun(self, filename=None):
iffilename:
self.load_layout_from_file(filename)
else:
view=self.window.show_input_panel(
caption='Load from Layout File',
initial_text='',
on_done=self.load_layout_from_file,
on_change=None,
on_cancel=None
)
sublime.status_message('Load Layout named `%s`'%filename)
classSaveLayoutAsCommand(PaneCommand):
defsave_layout_to_file(self, filename):
layout=self.layout_to_json()
withopen(self.get_layout_path(filename), 'w') asfp:
fp.write(layout)
defrun(self, filename=None):
iffilename:
self.save_layout_to_file(filename)
else:
view=self.window.show_input_panel(
caption='Save as Layout File',
initial_text='',
on_done=self.save_layout_to_file,
on_change=None,
on_cancel=None
)
sublime.status_message('Saved Current Layout as `%s`'%filename)
classUndoMoveToPaneCommand(PaneCommand):
defrun(self):
MoveableCommand.add_redo_history(self.current_group)
group=MoveableCommand.next_record()
self.fixed_focus_group(group)
classRedoMoveToPaneCommand(PaneCommand):
defrun(self):
MoveableCommand.add_history(self.current_group)
group=MoveableCommand.prev_record()
self.fixed_focus_group(group)
classUndoLayoutPaneCommand(PaneCommand):
defrun(self):
RevocableCommand.add_redo_history(self.layout_to_json())
layout=RevocableCommand.next_record()
self.load_layout_from_json(layout)
classRedoLayoutPaneCommand(PaneCommand):
defrun(self):
RevocableCommand.add_history(self.layout_to_json())
layout=RevocableCommand.prev_record()
self.load_layout_from_json(layout)