summaryrefslogtreecommitdiff
path: root/gui-wm/wayfire/tests/snap-zones.py
blob: 51d6f79d20b26df731c72b1b04f41bad206773f5 (plain)
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
#!/usr/bin/env python3
"""Exercise the display API in a private compositor, never the active desktop."""
import json, os, socket, struct, subprocess, tempfile, time
from PIL import Image
from pathlib import Path

stage=Path(os.environ.get('WCM_TEST_STAGE','/var/tmp/wayfire-snap-zones'))
runtime=Path(tempfile.mkdtemp(prefix='scope-toggle-test-'))
env=os.environ.copy()
for key in ['WAYLAND_DISPLAY','DISPLAY','WAYFIRE_SOCKET','_WAYFIRE_SOCKET','WAYFIRE_CONFIG_FILE','WAYFIRE_DEFAULT_CONFIG_BACKEND']:
    env.pop(key,None)
env.update(GIO_USE_VFS='local',GTK_USE_PORTAL='0',XDG_RUNTIME_DIR=str(runtime),WLR_BACKENDS='headless',WLR_HEADLESS_OUTPUTS='4',WLR_RENDERER='gles2',
    WLR_RENDER_DRM_DEVICE='/dev/dri/renderD128',WAYFIRE_PLUGIN_PATH=str(stage/'plugins'),WAYFIRE_PLUGIN_XML_PATH=str(stage/'metadata'))
config=runtime/'wayfire.ini'
config.write_text('''# Preserve this comment and unrelated settings.
[core]
plugins = ipc stipc ipc-rules output-control grid place move resize wm-actions wobbly follow-focus simple-tile cube vswitch
xwayland = false
stitch_enabled = true
stitch_outputs = HEADLESS-1 HEADLESS-2 HEADLESS-3
default_output = VIRTUAL-1
window_scope = physical
window_scope_rules = [{"app_id":"tile-wide*","scope":"virtual"},{"app_id":"scope-pinned","scope":"HEADLESS-3"}]
[simple-tile]
key_toggle = none
tile_by_default = none
float_on_top = false
inner_gap_size = 10
outer_horiz_gap_size = 5
outer_vert_gap_size = 5
[wm-actions]
toggle_always_on_top = <super> KEY_T
[cube]
rotate_left = <alt> <ctrl> KEY_LEFT
rotate_right = <alt> <ctrl> KEY_RIGHT
[autostart]
autostart_wf_shell = false
[grid]
toggle_scope = <super> KEY_ENTER
type = none
zone_gap = 20
[output:HEADLESS-1]
mode = 640x720@60
position = 0,0
[output:HEADLESS-2]
zone_gap = 20
mode = 640x720@60
position = 640,0
[output:HEADLESS-3]
mode = 640x720@60
position = 1280,0
[output:HEADLESS-4]
mode = 320x240@60
position = 1920,0
masked = true
''')
if os.environ.get('GRID_TEST_UPGRADE'):
    config.write_text(config.read_text().replace('output-control grid place', 'output-control '+str(stage/'libgrid-r19.so')+' place'))
if os.environ.get('SCOPE_TEST_ANIMATION'):
    config.write_text(config.read_text().replace('type = none', 'type = crossfade\nduration = 300ms circle'))

log=(runtime/'wayfire.log').open('w')
compositor_env=env.copy()
if os.environ.get('WCM_TEST_ASAN'):
    compositor_env.update(LD_PRELOAD=os.environ['WCM_TEST_ASAN'],ASAN_OPTIONS='detect_leaks=0:abort_on_error=1',UBSAN_OPTIONS='halt_on_error=1:print_stacktrace=1')
process=subprocess.Popen([os.environ.get('WCM_TEST_COMPOSITOR','/usr/bin/wayfire'),'-c',str(config)],env=compositor_env,stdout=log,stderr=log)
def wait(fn,timeout=10):
    deadline=time.monotonic()+timeout
    while time.monotonic()<deadline:
        if process.poll() is not None:raise RuntimeError(f'Compositor exited; {runtime}/wayfire.log')
        result=fn()
        if result:return result
        time.sleep(.05)
    raise TimeoutError(f'Condition timed out; {runtime}/wayfire.log')
def ipc(method,data=None,fail=False):
    with socket.socket(socket.AF_UNIX) as s:
        s.settimeout(8);s.connect(env['WAYFIRE_SOCKET'])
        b=json.dumps({'method':method,'data':data or {}}).encode();s.sendall(struct.pack('<I',len(b))+b)
        def read(n):
            b=b''
            while len(b)<n:
                c=s.recv(n-len(b))
                if not c:raise RuntimeError('IPC disconnected')
                b+=c
            return b
        result=json.loads(read(struct.unpack('<I',read(4))[0]))
    if fail:assert result.get('error'),result
    else:assert not isinstance(result,dict) or not result.get('error'),result
    return result
def get():return ipc('displays/get')
def apply(options,fail=False):return ipc('displays/apply',{'revision':get()['revision'],'options':options},fail)
def revert(t):return ipc('displays/revert',{'token':t['token']})
def confirm(t,fail=False):return ipc('displays/confirm',{'token':t['token']},fail)
def names():return [d['name'] for d in get()['desktops']]

clients=[]
def spawn(app,mode='normal'):
    f=(runtime/(app+'.log')).open('w')
    p=subprocess.Popen([str(stage/'scope-client'),app,mode],env=env,stdin=subprocess.PIPE,stdout=f,stderr=f,text=True)
    clients.append((p,f))
    if mode=='bar':
        wait(lambda:any(v.get('app-id')=='scope-bar' and v.get('mapped') for v in ipc('window-rules/list-views')))
        return p,None
    v=wait(lambda:next((v for v in ipc('window-rules/list-views') if v.get('app-id')==app and v.get('mapped')),None))
    return p,v['id']
def info(vid):return next(v for v in ipc('window-rules/list-views') if v['id']==vid)
def geometry(vid):return info(vid)['geometry']
def command(p,cmd):p.stdin.write(cmd+'\n');p.stdin.flush()
def expect(vid,**wanted):
    try:return wait(lambda:all(geometry(vid)[k]==v for k,v in wanted.items()))
    except Exception:
        print('FAILED expected',wanted,'actual',info(vid),flush=True);raise

def focus(vid):ipc('window-rules/focus-view',{'id':vid})
def keys(*ks):
    for k in ks:ipc('stipc/feed_key',{'key':k,'state':True})
    for k in reversed(ks):ipc('stipc/feed_key',{'key':k,'state':False})
def layout(monitor,ws=0):return ipc('simple-tile/get-layout',{'wset-index':wset,'workspace':{'x':ws,'y':0},'monitor':monitor})['layout']
def contains(node,vid):
    return node.get('view-id')==vid or any(contains(c,vid) for c in node.get('vertical-split',[])+node.get('horizontal-split',[]))
def tiled(vid):return any(contains(layout(m),vid) for m in ['HEADLESS-1','HEADLESS-2','HEADLESS-3','VIRTUAL-1'])
def toggle(vid):
    was=tiled(vid);focus(vid);keys('KEY_LEFTMETA','KEY_ENTER');wait(lambda:tiled(vid)!=was)
def spawn_at(app,monitor):
    ipc('stipc/move_cursor',{'x':(monitor-1)*640+200,'y':200})
    return spawn(app)
def bounds(vid,x,y,w,h):
    g=geometry(vid);assert g['x']>=x and g['y']>=y and g['x']+g['width']<=x+w and g['y']+g['height']<=y+h,(vid,g,(x,y,w,h))
def toggle_scope(vid, keyboard=False):
    was=info(vid)['window-scope']
    if keyboard:
        focus(vid);keys('KEY_LEFTMETA','KEY_ENTER')
    else:ipc('grid/toggle_scope',{'view-id':vid})
    wait(lambda:(info(vid)['window-scope']=='virtual') != (was=='virtual'))
    time.sleep(.4 if os.environ.get('SCOPE_TEST_ANIMATION') else .1)

def same_geometry(vid, before):
    expect(vid,**before)

def rect(x,y,w,h):return dict(x=x,y=y,width=w,height=h)
def slot_rect(area,slot):
    x,y,w,h=(area[k] for k in ('x','y','width','height'))
    if slot%3==1:w=int(w/2)
    elif slot%3==0:x+=int(w/2);w=int(w/2)
    if slot>=7:h=int(h/2)
    elif slot<=3:y+=int(h/2);h=int(h/2)
    return rect(x,y,w,h)
def move(x,y):ipc('stipc/move_cursor',{'x':x,'y':y});time.sleep(.04)
def button(mode):ipc('stipc/feed_button',{'combo':'S-BTN_LEFT','mode':mode})
def prepare(vid,monitor=1):
    ipc('window-rules/set-window-scope',{'id':vid,'scope':'physical'})
    ipc('grid/restore',{'view-id':vid})
    g=rect((monitor-1)*640+140,180,300,180)
    ipc('window-rules/configure-view',{'id':vid,'geometry':g})
    expect(vid,**g);time.sleep(.4 if os.environ.get("SCOPE_TEST_ANIMATION") else .05);focus(vid)
def begin(vid,offset=150):
    g=geometry(vid);move(g['x']+offset,g['y']+60);button('press')
    move(g['x']+offset+30,g['y']+60)
def preview(expected):
    def found():
        return any(v.get('mapped') and v.get('type')!='toplevel' and v.get('app-id')!='scope-bar' and v.get('geometry')==expected for v in ipc('window-rules/list-views'))
    try:wait(found,3)
    except Exception:
        print('PREVIEW expected',expected,'views',ipc('window-rules/list-views'),flush=True);raise

def end(vid,expected):
    button('release');expect(vid,**expected);time.sleep(.25)
import random

def zones(**kw):return ipc('grid/snap-zones',kw)
def hit(g,x,y):return g['x']<=x<g['x']+g['width'] and g['y']<=y<g['y']+g['height']
def expected(area,x,y,e,q):
    l=x-area['x']<=e;r=area['x']+area['width']-x<=e
    t=y-area['y']<e;b=area['y']+area['height']-y<e
    fl=x-area['x']<=q;fr=area['x']+area['width']-x<=q
    ft=y-area['y']<q;fb=area['y']+area['height']-y<q
    if l and ft or fl and t:return 'tl'
    if r and ft or fr and t:return 'tr'
    if r and fb or fr and b:return 'br'
    if l and fb or fl and b:return 'bl'
    return 'r' if r else 'l' if l else 'c' if t else 'b' if b else ''
def check_partition(state):
    rng=random.Random(392)
    for m in state['monitors']:
        a=m['workarea'];g=m['geometry'];e=state['edge'];q=state['corner']
        xs={int(g['x']),int(g['x']+g['width']-1)};ys={int(g['y']),int(g['y']+g['height']-1)}
        for d in [0,e,q]:
            for delta in [-1,0,1]:
                xs.update([int(a['x']+d+delta),int(a['x']+a['width']-d+delta)])
                ys.update([int(a['y']+d+delta),int(a['y']+a['height']-d+delta)])
        points=[(x,y) for x in xs for y in ys if hit(g,x,y)]
        points +=[(rng.randrange(int(g['x']),int(g['x']+g['width'])),rng.randrange(int(g['y']),int(g['y']+g['height']))) for _ in range(600)]
        for x,y in points:
            found=[r['slot'] for r in m['regions'] if hit(r['geometry'],x,y)]
            wanted=expected(a,x,y,e,q)
            assert found==([wanted] if wanted else []),(m['name'],x,y,found,wanted,state)

def shot(name):
    p=runtime/(name+'.png');subprocess.run(['grim',str(p)],env=env,check=True);return Image.open(p).convert('RGB')
try:
    env['WAYFIRE_SOCKET']=str(wait(lambda:next(runtime.glob('wayfire-*.socket'),None)))
    env['WAYLAND_DISPLAY']=next(p.name for p in runtime.glob('wayland-*') if not p.name.endswith('.lock'))
    print('Runtime:',runtime,flush=True);wait(lambda:names()==['VIRTUAL-1'])
    bar,_=spawn('zone-bar','bar');time.sleep(1.3)
    for edge,corner in [(10,50),(0,0),(35,90),(90,15),(600,800)]:
        ipc('wayfire/set-config-options',{'move/snap_threshold':edge,'move/quarter_snap_threshold':corner})
        for scope in ['physical','virtual']:check_partition(zones(scope=scope))
    print('PASS exact trigger partitions including threshold boundaries, corner priority, gaps, panels, VIRTUAL',flush=True)
    ipc('wayfire/set-config-options',{'move/snap_threshold':10,'move/quarter_snap_threshold':50})
    base=shot('hidden');state=zones(visible=True,owner='test');time.sleep(.1);shown=shot('shown')
    for m in state['monitors']:
        for r in m['regions']:
            g=r['geometry'];x=int(g['x']+g['width']/2);y=int(g['y']+g['height']/2)
            assert base.getpixel((x,y))!=shown.getpixel((x,y)),(m['name'],r)
        g=m['geometry'];p=(int(g['x']+g['width']/2),int(g['y']+g['height']/2));assert base.getpixel(p)==shown.getpixel(p)
    assert zones()['visible'];ipc('grid/snap-zones',{'visible':True,'owner':'another'},fail=True)
    assert zones(visible=False,owner='another')['visible'];assert not zones(visible=False,owner='test')['visible']
    time.sleep(.1);hidden=shot('hidden-again');assert hidden.size==base.size and hidden.tobytes()==base.tobytes()
    print('PASS overlay visible on every member, clean removal, owner isolation',flush=True)
    zones(visible=True,owner='test');time.sleep(2.8);assert not zones()['visible']
    assert shot('expired').tobytes()==base.tobytes()
    print('PASS compositor removes abandoned overlay automatically',flush=True)
    # Overlay must not intercept dragging or change the existing preview/drop.
    a,aid=spawn_at('zone-drag',2);prepare(aid,2);zones(visible=True,owner='test')
    begin(aid);move(642,1);expected_rect=rect(660,44,300,328);preview(expected_rect);end(aid,expected_rect)
    zones(visible=False,owner='test');print('PASS overlay is input-transparent to physical corner drag',flush=True)
    # Compare the advertised regions with real pointer previews on each member.
    for m in [1,2,3]:
        prepare(aid,m);begin(aid);move((m-1)*640+638,718)
        target=rect((m-1)*640+320,372,300,328);preview(target);end(aid,target)
    print('PASS advertised monitor targets agree with actual corner drops',flush=True)
    a.terminate();a.wait(timeout=3);bar.terminate();bar.wait(timeout=3)
    t=apply({'core/stitch_enabled':'false','core/default_output':'HEADLESS-1','output:HEADLESS-2/position':'640,100'});confirm(t);time.sleep(1.2)
    state=zones();check_partition(state);assert any(m['geometry']['y']==100 for m in state['monitors'])
    print('PASS independent output offsets',flush=True)
    for data in [{'scope':'wrong'},{'visible':'true','owner':'x'},{'visible':True},{'visible':True,'owner':''}]:ipc('grid/snap-zones',data,fail=True)
    print('PASS malformed requests rejected without changing configuration',flush=True)
    print('ALL PASS',flush=True)
finally:
    for p,f in clients:
        if p.poll() is None:p.terminate()
        p.wait(timeout=3);f.close()
    process.terminate();process.wait(timeout=5);log.close()