-
Notifications
You must be signed in to change notification settings - Fork 2
/
i3ipc_dynamic_tiling.py
executable file
·1251 lines (1061 loc) · 40.4 KB
/
i3ipc_dynamic_tiling.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
#!/usr/bin/env python3
"""Dynamic tiling for the I3 and SWAY window managers.
A Python IPC implementation of dynamic tiling for the I3 and SWAY window
managers, trying to mimic the tiling behavior of the excellent DWM and XMONAD
window managers, while utilizing the strengths of I3 and SWAY. """
import argparse
import copy
import logging
import os
import signal
import sys
import i3ipc
from i3ipc import Event
###############################################################################
# Logging #
###############################################################################
# Create the logger.
# logging.basicConfig(
# format='%(asctime)s %(levelname)s: %(message)s',
# level=log_level_numeric)
logging.basicConfig(
format='%(asctime)s %(levelname)s: %(message)s',
level=0)
###############################################################################
# Global variables #
###############################################################################
DATA = {
'initialized': False,
'opacity': {
'focused': 1.0,
'inactive': 1.0
},
'variant': None,
'hide_bar': False,
'workspace_ignore': []
}
I3DT_LAYOUT = dict()
FOCUS = {'previous': None, 'current': None}
###############################################################################
# Helper functions #
###############################################################################
def execute_commands(ipc, commands, preamble='Executing:'):
"""Execute a chain of commands."""
if commands:
if preamble:
logging.debug(preamble)
if isinstance(commands, list):
parsed_commands = [x for x in commands if x]
commands = parsed_commands
reply = ipc.command('; '.join(commands))
for ind, cmd in enumerate(commands):
logging.debug('+ %s => %s', cmd, reply[ind].ipc_data)
if not reply[ind].success:
logging.error(reply[ind].error)
else:
reply = ipc.command(commands)
logging.debug('+ %s => %s', commands, reply[0].ipc_data)
if not reply[0].success:
logging.error(reply[0].error)
return []
def get_workspace_info(ipc, workspace=None):
"""Collect the state of the window manager."""
if not workspace:
tree = ipc.get_tree()
focused = tree.find_focused()
workspace = focused.workspace()
# Initialize the dictionary.
info = {
'mode': 'manual',
'name': workspace.name,
'layout': workspace.layout,
'children': [],
'tiled': [],
'descendants': [],
'id': workspace.id,
'focused': None,
'fullscreen': False,
'unmanaged': [],
'glbl': {
'mark': 'I3DT_GLBL_{}'.format(workspace.name),
'id': None,
'orientation': 'horizontal',
'layout': 'splith'
},
'main': {
'mark': 'I3DT_MAIN_{}'.format(workspace.name),
'fullscreen': 0,
'id': None,
'focus': None,
'layout': 'splitv',
'children': []
},
'scnd': {
'mark': 'I3DT_SCND_{}'.format(workspace.name),
'fullscreen': 0,
'id': None,
'focus': None,
'layout': 'splitv',
'children': [],
},
}
# Collect workspace information.
if workspace.name not in DATA['workspace_ignore']:
info['mode'] = 'tiled'
info['descendants'] = workspace.descendants()
for con in workspace.leaves():
info['children'].append(con.id)
if not con.floating or not con.floating.endswith('on'):
info['tiled'].append(con.id)
for con in info['descendants']:
marks = con.marks
if con.focused:
info['focused'] = con.id
info['fullscreen'] = con.fullscreen_mode
if info['glbl']['mark'] in marks:
info['glbl']['id'] = con.id
info['glbl']['orientation'] = con.orientation
info['glbl']['layout'] = con.layout
for name in ['main', 'scnd']:
if info[name]['mark'] in marks:
info[name]['id'] = con.id
if con.focus:
info[name]['focus'] = con.focus[0]
info[name]['fullscreen'] = con.fullscreen_mode
info[name]['layout'] = con.layout
info[name]['children'] = list(d.id for d in con.leaves())
# Find unmanaged windows.
info['unmanaged'] = copy.deepcopy(info['tiled'])
for cid in info['main']['children']:
info['unmanaged'].remove(cid)
for cid in info['scnd']['children']:
info['unmanaged'].remove(cid)
return info
def rename_secondary_container(info):
"""Rename the secondary container to the main container."""
command = []
command.append('[con_id={}] unmark {}'
.format(info['scnd']['id'], info['scnd']['mark']))
command.append('[con_id={}] mark {}'
.format(info['scnd']['id'], info['main']['mark']))
return command
def restore_container_layout(key, info):
"""Restore the saved container layout."""
if not info[key]['id']:
return []
if info['name'] not in I3DT_LAYOUT:
I3DT_LAYOUT[info['name']] = {'main': 'splitv', 'scnd': 'splitv'}
commands = []
if info[key]['layout'] != I3DT_LAYOUT[info['name']][key]:
if I3DT_LAYOUT[info['name']][key] == 'stacked':
commands.append('[con_id={}] layout {}'
.format(info[key]['children'][0], 'stacking'))
else:
commands.append('[con_id={}] layout {}'
.format(info[key]['children'][0],
I3DT_LAYOUT[info['name']][key]))
if DATA['variant'] == 'sway':
if I3DT_LAYOUT[info['name']][key] in ['splith', 'splitv']:
for cid in info[key]['children']:
if cid == info['focused']:
commands.append('[con_id={}] opacity {}'
.format(cid,
DATA['opacity']['focused']))
else:
commands.append('[con_id={}] opacity {}'
.format(cid,
DATA['opacity']['inactive']))
else:
for cid in info[key]['children']:
commands.append('[con_id={}] opacity {}'
.format(cid, DATA['opacity']['focused']))
return commands
def save_container_layout(key, info):
"""Save the container layout."""
if info['name'] not in I3DT_LAYOUT:
I3DT_LAYOUT[info['name']] = {'main': 'splitv', 'scnd': 'splitv'}
if info[key]['id']:
I3DT_LAYOUT[info['name']][key] = info[key]['layout']
def find_parent_id(con_id, info):
"""Find the parent container id."""
parent = None
containers = (con for con in info['descendants'] if not con.name)
for con in containers:
for dsc in con.descendants():
if dsc.id == con_id:
parent = con.id
break
return parent
def create_container(ipc, name, con_id=None):
"""Create a split container for the specified container id.
Parameters
----------
ipc : i3ipc.Connection
An i3ipc connection
name : str
The name of the target split container
con_id : int, optional
The container id that should be contained (default is the
focused container id)
"""
logging.debug('Create container: %s', name)
# Get workspace information.
info = get_workspace_info(ipc)
# Exit if container already exists.
if info[name]['id']:
raise ValueError('Container already exist!')
# Get the window that should be contained and make sure it is
# focused.
command = []
focused = info['focused']
if not con_id:
con_id = focused
else:
command.append('[con_id={}] focus'.format(con_id))
# Remove any marks that may exist.
command.append('[con_id={}] unmark'.format(con_id))
# Move the window outside any other container.
other = 'main' if name == 'scnd' else 'scnd'
if con_id in info[other]['children']:
if info['glbl']['id']:
command.append('move to mark {}; splitv'
.format(info['glbl']['mark']))
else:
if other == 'main':
move = 'right'
if info['layout'] in ['splitv', 'stacked']:
move = 'down'
# Move the to the edge of the container.
index = 0
for cid in info['main']['children']:
if info['focused'] == cid:
break
index += 1
layout = info['main']['layout']
if (layout in ['splith', 'tabbed'] and move == 'right') or \
(layout in ['splitv', 'stacked'] and move == 'down'):
command.extend(['move {}'.format(move)]
* (len(info['main']['children']) - index))
else:
move = 'left'
if info['layout'] in ['splitv', 'stacked']:
move = 'up'
# Move the to the edge of the container.
index = 0
for cid in info['scnd']['children']:
if info['focused'] == cid:
break
index += 1
layout = info['main']['layout']
if (layout in ['splith', 'tabbed'] and move == 'left') \
or (layout in ['splitv', 'stacked'] and move == 'up'):
command.extend(['move {}'.format(move)] * (index + 1))
# Move outside the split container.
command.append('move {}'.format(move))
if info['layout'] in ['splitv', 'stacked']:
command.append('splith')
command.append('resize set height 50 ppt')
else:
command.append('splitv')
command.append('resize set width 50 ppt')
else:
command.append('[con_id={}] splitv'.format(con_id))
command = execute_commands(ipc, command, '')
# Find and mark the newly created split container.
info = get_workspace_info(ipc)
parent = find_parent_id(con_id, info)
command.append('[con_id={}] mark {}'
.format(parent, info[name]['mark']))
# Make sure that the newly created container is in the global split
# container.
if info['glbl']['id']:
command.append('[con_id={}] move to mark {}'
.format(parent, info['glbl']['mark']))
if name == 'main' and info['scnd']['id']:
command.append('[con_id={}] swap container with con_id {}'
.format(parent, info['scnd']['id']))
command = execute_commands(ipc, command, '')
def find_parent_container_key(info, con_id=None):
"""Find parent the container key.
Parameters
----------
info : dict
The state of the window manager
con_id : int, optional
A container id (default focused)
"""
key = None
if not con_id:
con_id = info['focused']
if info['main']['id'] and con_id in info['main']['children']:
key = 'main'
elif info['scnd']['id'] and con_id in info['scnd']['children']:
key = 'scnd'
return key
def find_parent_container(info):
"""Find parent the container.
Parameters
----------
info : dict
The state of the window manager
"""
parent = None
children = []
if info['focused'] in info['main']['children']:
parent = info['main']['id']
layout = info['main']['layout']
children = info['main']['children']
elif info['focused'] in info['scnd']['children']:
parent = info['scnd']['id']
layout = info['scnd']['layout']
children = info['scnd']['children']
else:
parent = info['id']
layout = info['layout']
children = info['tiled']
return parent, layout, children
def find_container_index(info, con_ids=None):
"""Find the container index in a list.
Parameters
----------
info : dict
The state of the window manager
con_ids : list, optional
A list of container id's
"""
if not con_ids:
con_ids = info['tiled']
ind = 0
for cid in con_ids:
if cid == info['focused']:
break
ind += 1
return ind
def get_movement(layout, direction):
"""Convert next/prev to an i3/sway movement.
Parameters
----------
layout : str
The layout of the container
direction : str
The movement next/prev to convert
"""
if direction == 'next':
if layout in ['splith', 'tabbed']:
movement = 'right'
else:
movement = 'down'
elif direction == 'prev':
if layout in ['splith', 'tabbed']:
movement = 'left'
else:
movement = 'up'
return movement
def i3ipc_focus_next_prev(ipc, info, key, is_monocle, direction):
"""Focus the next or previous window with wrapping."""
command = []
children = info['tiled']
if key and is_monocle:
children = info[key]['children']
index = find_container_index(info, children)
length = len(children)
if length > 1:
if direction == 'next':
command.append('[con_id={}] focus'
.format(children[(index + 1) % length]))
elif direction == 'prev':
command.append('[con_id={}] focus'
.format(children[(index - 1) % length]))
elif is_monocle:
command.extend(i3ipc_monocle_disable_commands(key, info))
execute_commands(ipc, command, '')
def i3ipc_focus_other(ipc, info, key, is_monocle):
"""Focus the window in the other container."""
command = []
if info['scnd']['id']:
if is_monocle:
command.extend(i3ipc_monocle_disable_commands(key, info))
other = 'main' if key == 'scnd' else 'scnd'
command.append('[con_id={}] focus'.format(info[other]['focus']))
else:
logging.warning('Window::Focus::Other::No other container')
execute_commands(ipc, command, '')
def i3ipc_focus_toggle(ipc, info, key, is_monocle):
"""Focus the previously focused window."""
command = []
if is_monocle and \
(not key or FOCUS['previous'] not in info[key]['children']):
command.extend(i3ipc_monocle_disable_commands(key, info))
if FOCUS['previous']:
command.append('[con_id={}] focus'.format(FOCUS['previous']))
else:
logging.warning('Window::Focus::Toggle::No previous window')
execute_commands(ipc, command, '')
def i3ipc_focus(ipc, event):
"""Different window focus events.
Parameters
----------
ipc : i3ipc.Connection
An i3ipc connection
event : i3ipc.BindingEvent
An i3ipc binding event
"""
action = event.binding.command.split(" ")[-1]
logging.info('Window::Focus::%s', action.title())
info = get_workspace_info(ipc)
key = find_parent_container_key(info)
is_monocle = i3ipc_monocle_enabled(key, info)
if action in ['next', 'prev']:
i3ipc_focus_next_prev(ipc, info, key, is_monocle, action)
elif action == 'other':
i3ipc_focus_other(ipc, info, key, is_monocle)
elif action == 'toggle':
i3ipc_focus_toggle(ipc, info, key, is_monocle)
def i3ipc_move_next_prev(ipc, info, direction):
"""Move the focused window forward or backward."""
# Find the position of the focused window in the list of all windows
# and only perform the movement if it keeps the window within the
# container.
_, layout, children = find_parent_container(info)
command = []
if children:
movement = get_movement(layout, direction)
if direction == 'next':
if info['focused'] != children[-1]:
command.append('move {}'.format(movement))
elif direction == 'prev':
if info['focused'] != children[0]:
command.append('move {}'.format(movement))
execute_commands(ipc, command, '')
def i3ipc_move_other(ipc, info):
"""Move the focused window to the other container."""
# Find the parent container of the window and then move the window to the
# other container. Make sure that the main container does not become empty.
command = []
if info['focused'] in info['main']['children']:
if len(info['main']['children']) == 1:
if info['scnd']['id']:
command.append('[con_id={}] focus'
.format(info['scnd']['children'][0]))
command.append('swap container with con_id {}'
.format(info['focused']))
elif info['scnd']['id']:
command.append('[con_id={}] move to mark {}'
.format(info['focused'], info['scnd']['mark']))
command.append('[con_id={}] focus; focus child'
.format(info['main']['id']))
else:
create_container(ipc, 'scnd')
else:
command.append('[con_id={}] move to mark {}'
.format(info['focused'], info['main']['mark']))
command.append('[con_id={}] focus; focus child'
.format(info['scnd']['id']))
execute_commands(ipc, command, '')
def i3ipc_move_swap(ipc, info):
"""Swap the focused window with other container."""
command = []
if info['scnd']['id']:
if info['focused'] in info['scnd']['children']:
command.append('[con_id={}] focus'
.format(info['main']['focus']))
command.append('swap container with con_id {}'
.format(info['scnd']['focus']))
command.append('[con_id={}] focus'
.format(info['scnd']['focus']))
execute_commands(ipc, command, '')
def i3ipc_move(ipc, event):
"""Different window movements.
Parameters
----------
ipc : i3ipc.Connection
An i3ipc connection
event : i3ipc.BindingEvent
An i3ipc binding event
"""
action = event.binding.command.split(" ")[-1]
logging.info('Window::Move::%s', action.title())
info = get_workspace_info(ipc)
if action in ['next', 'prev']:
i3ipc_move_next_prev(ipc, info, action)
elif action == 'other':
i3ipc_move_other(ipc, info)
elif action == 'swap':
i3ipc_move_swap(ipc, info)
def i3ipc_tabbed_disable(ipc, info):
"""Disable tabbed mode."""
if info['layout'] == 'tabbed' or info['glbl']['layout'] == 'tabbed':
if DATA['hide_bar']:
os.system("polybar-msg cmd show 1>/dev/null")
command = []
if info['scnd']['id']:
command.append('[con_id={}] layout toggle split'
.format(info['scnd']['id']))
for k in ['main', 'scnd']:
command.extend(restore_container_layout(k, info))
execute_commands(ipc, command, '')
def i3ipc_tabbed_enable(ipc, info):
"""Enable tabbed mode."""
if info['mode'] == 'tiled':
if DATA['hide_bar']:
os.system("polybar-msg cmd hide 1>/dev/null")
command = []
for k in ['main', 'scnd']:
if info[k]['id']:
save_container_layout(k, info)
command.append('[con_id={}] layout tabbed'
.format(info[k]['children'][0]))
if info['scnd']['id']:
command.append('[con_id={}] layout tabbed'
.format(info['scnd']['id']))
execute_commands(ipc, command, '')
# Find the newly created split container and mark it.
if DATA['variant'] != 'sway':
info = get_workspace_info(ipc)
if not info['glbl']['id']:
glbl = info['descendants'][0].id
execute_commands(ipc, '[con_id={}] mark {}'
.format(glbl, info['glbl']['mark']), '')
def i3ipc_tabbed_toggle(ipc):
"""Toggle the tabbed mode on or off.
Parameters
----------
ipc : i3ipc.Connection
An i3ipc connection
"""
logging.info('Workspace::Tabbed')
info = get_workspace_info(ipc)
if info['mode'] == 'manual':
return
if info['mode'] == 'monocle':
i3ipc_monocle_toggle(ipc)
return
if info['layout'] == 'tabbed' or info['glbl']['layout'] == 'tabbed':
i3ipc_tabbed_disable(ipc, info)
elif info['mode'] == 'tiled':
i3ipc_tabbed_enable(ipc, info)
def i3ipc_monocle_disable_commands(key, info):
"""Generate a list of ipc commands to disable the monocle mode.
Parameters
----------
key : str
The name of the split container of the focused window
info : dict
The current workspace information dictionary
Returns
-------
list
List of commands to run
"""
commands = []
if not key and info['fullscreen']:
commands.append('fullscreen disable')
elif info[key]['id'] and info[key]['fullscreen']:
commands.extend(restore_container_layout(key, info))
commands.append('[con_id={}] fullscreen toggle'
.format(info[key]['id']))
return commands
def i3ipc_monocle_enable_commands(key, info):
"""Generate a list of ipc commands to enable the monocle mode.
Parameters
----------
key : str
The name of the split container of the focused window
info : dict
The current workspace information dictionary
Returns
-------
list
List of commands to run
"""
commands = []
if not key and not info['fullscreen']:
commands.append('fullscreen enable')
elif key and info[key]['id'] and not info[key]['fullscreen']:
save_container_layout(key, info)
if info[key]['layout'] != 'tabbed' \
and (len(info[key]['children']) > 1):
commands.append('layout tabbed')
if DATA['variant'] == 'sway':
for cid in info[key]['children']:
commands.append('[con_id={}] opacity {}'
.format(cid, DATA['opacity']['focused']))
commands.append('[con_id={}] fullscreen toggle'
.format(info[key]['id']))
if DATA['variant'] != 'sway':
commands.append('focus child')
return commands
def i3ipc_monocle_toggle_commands(key, info):
"""Generate a list of ipc commands to toggle the monocle mode.
Parameters
----------
key : str
The name of the split container of the focused window
info : dict
The current workspace information dictionary
Returns
-------
list
List of commands to run
"""
commands = []
if i3ipc_monocle_enabled(key, info):
commands = i3ipc_monocle_disable_commands(key, info)
else:
commands = i3ipc_monocle_enable_commands(key, info)
return commands
def i3ipc_monocle_enabled(key, info):
"""Check if monocle mode is enabled.
Parameters
----------
key : str
The name of the split container of the focused window
info : dict
The current workspace information dictionary
Returns
-------
bool
True if monocle mode is enabled, False otherwise.
"""
enabled = False
if not key and info['fullscreen']:
enabled = True
elif key and info[key]['id'] and info[key]['fullscreen']:
enabled = True
return enabled
def i3ipc_monocle_toggle(ipc):
"""Toggle the monocle mode on or off.
Parameters
----------
ipc : i3ipc.Connection
An i3ipc connection
"""
logging.info('Workspace::Monocle')
info = get_workspace_info(ipc)
key = find_parent_container_key(info)
commands = i3ipc_monocle_toggle_commands(key, info)
execute_commands(ipc, commands, '')
def i3ipc_mirror(ipc):
"""Mirror the secondary container.
This function handles the moving the secondary container from one side the
main container to the other.
Parameters
----------
ipc : i3ipc.Connection
An i3ipc connection
"""
logging.info('Workspace::Mirror')
info = get_workspace_info(ipc)
if info['scnd']['id'] and info['mode'] == 'tiled':
execute_commands(ipc, '[con_id={}] swap container with con_id {}'
.format(info['main']['id'], info['scnd']['id']))
def i3ipc_reflect(ipc):
"""Reflect the secondary container.
This function handles the moving the secondary container between a
horizontal and vertical position relative to the main container.
Parameters
----------
ipc : i3ipc.Connection
An i3ipc connection
"""
logging.info('Workspace::Reflect')
info = get_workspace_info(ipc)
command = []
if info['scnd']['id'] and info['mode'] == 'tiled':
# Toggle split on the second container to create a workspace global
# split container.
command.append('[con_id={}] layout toggle split'
.format(info['scnd']['id']))
# Sway does not create a global split container as i3 does.
if DATA['variant'] != 'sway' and not info['glbl']['id']:
command = execute_commands(ipc, command)
info = get_workspace_info(ipc)
command.append('[con_id={}] mark {}'
.format(info['descendants'][0].id,
info['glbl']['mark']))
# Update the layout of the containers.
command = execute_commands(ipc, command)
info = get_workspace_info(ipc)
orientation = 'horizontal'
if DATA['variant'] == 'sway' and info['layout'] == 'splitv':
orientation = 'vertical'
else:
orientation = info['glbl']['orientation']
for k in ['main', 'scnd']:
layout = info[k]['layout']
if (layout == 'splitv' and orientation == 'vertical') \
or (layout == 'splith' and orientation == 'horizontal'):
command.append('[con_id={}] layout toggle split'
.format(info[k]['children'][0]))
execute_commands(ipc, command, '')
def i3ipc_kill(ipc):
"""Close the focused window.
This function handles the special case of closing a window when there is a
single window in the main contianer when there still is a secondary
container.
Parameters
----------
ipc : i3ipc.Connection
An i3ipc connection
"""
# pylint: disable=unused-argument
logging.info('Window::Close')
info = get_workspace_info(ipc)
if info['mode'] == 'manual':
return
command = []
if info['focused'] in info['main']['children'] \
and (len(info['main']['children']) == 1) \
and info['scnd']['id']:
command.append('[con_id={}] swap container with con_id {}'
.format(info['focused'], info['scnd']['children'][0]))
execute_commands(ipc, command)
def on_window_close(ipc, event):
"""React on window close event.
Parameters
----------
ipc : i3ipc.Connection
An i3ipc connection
event : i3ipc.WindowEvent
An i3ipc window event
"""
logging.info('Window::Close')
floating = event.container.floating
if floating and floating.endswith('on'):
return
info = get_workspace_info(ipc)
if info['mode'] == 'manual':
return
command = []
if not info['main']['id'] and info['scnd']['id']:
if len(info['scnd']['children']) == 1:
command.extend(rename_secondary_container(info))
else:
con_id = info['scnd']['children'][0]
create_container(ipc, 'main', con_id)
command.append('[con_id={}] focus'.format(con_id))
execute_commands(ipc, command)
def on_workspace_focus(ipc, event):
"""React on workspace focus event.
Parameters
----------
ipc : i3ipc.Connection
An i3ipc connection
event : i3ipc.WorkspaceEvent
An i3ipc workspace event
"""
logging.info('Workspace::Focus::%s', event.current.name)
info = get_workspace_info(ipc, event.current)
command = []
if info['mode'] != 'manual':
if info['glbl']['layout'] == 'tabbed' or info['mode'] == 'monocle':
if DATA['hide_bar']:
os.system("polybar-msg cmd hide 1>/dev/null")
else:
if DATA['hide_bar']:
os.system("polybar-msg cmd show 1>/dev/null")
if info['name'] not in I3DT_LAYOUT:
I3DT_LAYOUT[info['name']] = {'main': 'splitv', 'scnd': 'splitv'}
if info['unmanaged']:
if info['main']['id']:
if not info['scnd']['id']:
create_container(ipc, 'scnd', info['unmanaged'][0])
elif len(info['unmanaged']) > 1:
unmanaged = info['unmanaged']
create_container(ipc, 'main', unmanaged[0])
create_container(ipc, 'scnd', unmanaged[1])
info = get_workspace_info(ipc)
if info['scnd']['id']:
for i in info['unmanaged']:
command.append('[con_id={}] move to mark {}'
.format(i, info['scnd']['mark']))
else:
if DATA['hide_bar']:
os.system("polybar-msg cmd show 1>/dev/null")
execute_commands(ipc, command)
def on_window_new(ipc, event):
"""React on window new event.
Parameters
----------
ipc : i3ipc.Connection
An i3ipc connection
event : i3ipc.WindowEvent
An i3ipc window event
"""
logging.info('Window::New')
info = get_workspace_info(ipc)
window = event.container
is_bar = window.name and window.name.startswith('polybar')
is_floating = window.floating and window.floating.endswith('on')
if info['mode'] == 'manual' or is_bar \
or is_floating or len(info['tiled']) < 2:
return
if not info['main']['id']:
create_container(ipc, 'main', info['tiled'][0])
create_container(ipc, 'scnd', info['tiled'][1])
elif not info['scnd']['id']:
create_container(ipc, 'scnd')
else:
if info['focused'] in info['main']['children']:
commands = []
commands.append('[con_id={}] move to mark {}'
.format(info['focused'], info['scnd']['mark']))
commands.append('[con_id={}] focus'
.format(info['focused']))
execute_commands(ipc, commands, '')
def on_window_focus(ipc, event):
"""React on window focus event.
Parameters
----------
ipc : i3ipc.Connection
An i3ipc connection
event : i3ipc.WindowEvent
An i3ipc window event
"""
logging.info('Window::Focus')
FOCUS['previous'] = FOCUS['current']
FOCUS['current'] = event.container.id
command = []
if DATA['variant'] == 'sway' and FOCUS['previous']:
info = get_workspace_info(ipc)
prev_key = find_parent_container_key(info, FOCUS['previous'])
if prev_key:
logging.info('Window::Opacity')
curr_key = find_parent_container_key(info)
if curr_key != prev_key \
or info[curr_key]['layout'] in ['splith', 'splitv']:
command.append('[con_id={}] opacity {}'
.format(FOCUS['previous'],
DATA['opacity']['inactive']))
command.append('[con_id={}] opacity {}'
.format(FOCUS['current'], DATA['opacity']['focused']))
execute_commands(ipc, command, '')
def on_window_floating(ipc, event):
"""React on window floating toggle event.
Parameters
----------
ipc : i3ipc.Connection
An i3ipc connection
event : i3ipc.WindowEvent
An i3ipc window event
"""
logging.info('Window::Floating')
info = get_workspace_info(ipc)
if info['mode'] == 'manual':
return
command = []
if event.container.floating == 'user_off':
if info['scnd']['id']:
command.append('move to mark {}'