summaryrefslogtreecommitdiff
path: root/gui-apps/wcm/tests/cube-hyperspace-ui.py
blob: de39f9333e8927c88de67bbc38e91a7d46ffaa4b (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
244
245
246
247
248
249
250
251
252
253
254
255
#!/usr/bin/env python3
"""Toggle Cube's overview through WCM on a private session and config."""
import configparser
import json
import os
from pathlib import Path
import socket
import struct
import subprocess
import tempfile
import time
import gi
gi.require_version('Atspi', '2.0')
from gi.repository import Atspi

assert os.geteuid()!=0
stage=Path(os.environ.get('CUBE_HYPERSPACE_STAGE','/var/tmp/wayfire-cube-hyperspace-prototype-20261010'))
root=Path(tempfile.mkdtemp(prefix='wcm-cube-backdrop-'))
env=os.environ.copy()
for key in ('WAYLAND_DISPLAY','DISPLAY','WAYFIRE_SOCKET','_WAYFIRE_SOCKET','WAYFIRE_CONFIG_FILE',
            'WAYFIRE_DEFAULT_CONFIG_BACKEND','NO_AT_BRIDGE'):
    env.pop(key,None)
env.update(XDG_RUNTIME_DIR=str(root),XDG_CONFIG_HOME=str(root/'config'),XDG_DATA_HOME=str(root/'data'),
           XDG_CACHE_HOME=str(root/'cache'),XDG_STATE_HOME=str(root/'state'),WLR_BACKENDS='headless',
           WLR_HEADLESS_OUTPUTS='3',WLR_RENDERER='gles2',WLR_RENDER_DRM_DEVICE='/dev/dri/renderD128',
           WAYFIRE_PLUGIN_PATH=str(stage/'plugins'),WAYFIRE_PLUGIN_XML_PATH=str(stage/'metadata'),
           GTK_USE_PORTAL='0',GIO_USE_VFS='local',GTK_MODULES='atk-bridge',
           XDG_DATA_DIRS='/usr/local/share:/usr/share')
config=root/'wayfire.ini'
config.write_text(f'''# Keep unrelated preferences.
[core]
plugins = ipc stipc ipc-rules {stage}/plugins/libcube.so place grid
xwayland = false
vwidth = 4
vheight = 3
stitch_enabled = true
stitch_outputs = HEADLESS-1 HEADLESS-2 HEADLESS-3
[cube]
activate = <ctrl> <alt> BTN_LEFT
dim = 0.25
[grid]
toggle_scope = <super> KEY_ENTER
[output:HEADLESS-1]
mode = 1400x1000@60
position = 0,0
[output:HEADLESS-2]
mode = 1400x1000@60
position = 1400,0
[output:HEADLESS-3]
mode = 1400x1000@60
position = 2800,0
''')
original=config.read_text()
shell=root/'shell.ini';shell.write_text('')
compositor=subprocess.Popen([str(stage/'wayfire'),'-c',str(config)],env=env,
    stdout=(root/'wayfire.log').open('w'),stderr=subprocess.STDOUT)
ui=None

def wait(fn,timeout=15):
    until=time.monotonic()+timeout
    while time.monotonic()<until:
        assert compositor.poll() is None,f'Compositor exited; {root}'
        if ui is not None:assert ui.poll() is None,f'WCM exited; {root}'
        value=fn()
        if value:return value
        time.sleep(.05)
    raise TimeoutError(str(root))

def ipc(method,data=None):
    with socket.socket(socket.AF_UNIX) as stream:
        stream.settimeout(5);stream.connect(env['WAYFIRE_SOCKET'])
        assert struct.unpack('3i',stream.getsockopt(socket.SOL_SOCKET,socket.SO_PEERCRED,12))[:2]==(compositor.pid,os.geteuid())
        payload=json.dumps({'method':method,'data':data or {}}).encode()
        stream.sendall(struct.pack('<I',len(payload))+payload)
        def read(n):
            value=b''
            while len(value)<n:
                block=stream.recv(n-len(value));assert block;value+=block
            return value
        result=json.loads(read(struct.unpack('<I',read(4))[0]))
        assert not isinstance(result,dict) or not result.get('error'),result
        return result

def nodes():
    stack=[Atspi.get_desktop(0)]
    while stack:
        node=stack.pop()
        if node is None:continue
        yield node
        stack.extend(node.get_child_at_index(i) for i in range(node.get_child_count()))

def find(name,role):
    return next((n for n in nodes() if n.get_name()==name and n.get_role()==role),None)

def showing(node):
    return node is not None and node.get_state_set().contains(Atspi.StateType.SHOWING)

def overview_check(name='Show all workspace rows'):
    # Generic WCM options place a separate label beside an unnamed checkbox.
    label=find(name,Atspi.Role.LABEL)
    if label is None:return None
    container=label.get_parent()
    for _ in range(4):
        stack=[container];checks=[]
        while stack:
            node=stack.pop()
            if node.get_role()==Atspi.Role.CHECK_BOX:checks.append(node)
            stack.extend(node.get_child_at_index(i) for i in range(node.get_child_count()))
        if len(checks)==1:return checks[0]
        container=container.get_parent()
    return None

def value():
    parsed=configparser.ConfigParser(interpolation=None,strict=False)
    parsed.read(config)
    return parsed

try:
    env['WAYFIRE_SOCKET']=str(wait(lambda:next(root.glob('wayfire-*.socket'),None)))
    env['WAYLAND_DISPLAY']=ipc('stipc/get_display')['wayland']
    ui=subprocess.Popen(['/usr/bin/wcm','--config',str(config),'--shell-config',str(shell),'--plugin=cube'],
        env=env,stdout=(root/'wcm.log').open('w'),stderr=subprocess.STDOUT)
    wait(lambda:find('Warp tunnel',Atspi.Role.PAGE_TAB))
    time.sleep(.3)
    assert config.read_text()==original,'Opening Cube settings wrote the config'
    def control(label_name,role):
        label=find(label_name,Atspi.Role.LABEL)
        if label is None:return None
        parent=label.get_parent()
        for _ in range(4):
            stack=[parent];found=[]
            while stack:
                node=stack.pop()
                if node.get_role()==role:found.append(node)
                stack.extend(node.get_child_at_index(i) for i in range(node.get_child_count()))
            if len(found)==1:return found[0]
            parent=parent.get_parent()
        return None
    def tab(name):
        item=wait(lambda:find(name,Atspi.Role.PAGE_TAB))
        assert item.get_parent().get_selection_iface().select_child(item.get_index_in_parent())
    def choose(label,item):
        combo=wait(lambda:control(label,Atspi.Role.COMBO_BOX))
        wait(lambda:showing(combo))
        assert combo.get_action_iface().do_action(0)
        choice=wait(lambda:next((n for n in nodes() if n.get_name()==item and n.get_role()==Atspi.Role.MENU_ITEM and showing(n)),None))
        assert choice.get_action_iface().do_action(0)
    tab('General')
    choose('Background mode','Warp tunnel')
    wait(lambda:ipc('wayfire/get-config-option',{'option':'cube/background_mode'})['value']=='warp')
    assert value()['cube']['background_mode']=='warp'
    tab('General')
    choose('Background mode','None')
    wait(lambda:ipc('wayfire/get-config-option',{'option':'cube/background_mode'})['value']=='none')
    assert value()['cube']['background_mode']=='none'
    tab('General')
    choose('Background mode','Warp tunnel')
    wait(lambda:ipc('wayfire/get-config-option',{'option':'cube/background_mode'})['value']=='warp')
    print('PASS WCM None mode saves and switches back to Warp',flush=True)
    tab('General')
    backdrop=wait(lambda:control('Backdrop image opacity',Atspi.Role.SPIN_BUTTON))
    backdrop.get_component_iface().scroll_to(Atspi.ScrollType.ANYWHERE)
    if not showing(backdrop):backdrop.get_component_iface().grab_focus()
    wait(lambda:showing(backdrop))
    assert backdrop.get_value_iface().get_current_value()==1
    for opacity in (0,.5,1):
        assert backdrop.get_value_iface().set_current_value(opacity)
        wait(lambda:float(ipc('wayfire/get-config-option',{'option':'cube/backdrop_image_opacity'})['value'])==opacity)
        assert float(value()['cube']['backdrop_image_opacity'])==opacity
    subprocess.run(['grim','-o','VIRTUAL-1',str(root/'backdrop-control.png')],env=env,check=True)
    print('PASS WCM backdrop opacity control defaults to 100%, hides at 0%, blends at 50%, and restores at 100%',flush=True)
    tab('Warp tunnel')
    animate=wait(lambda:overview_check('Animate at rest'))
    wait(lambda:showing(animate))
    assert animate.get_state_set().contains(Atspi.StateType.CHECKED),'Idle animation does not default to enabled'
    for enabled in (False,True):
        assert animate.get_action_iface().do_action(0)
        wait(lambda:ipc('wayfire/get-config-option',{'option':'cube/warp_animate_at_rest'})['value']==str(enabled).lower())
        assert value().getboolean('cube','warp_animate_at_rest')==enabled
    print('PASS WCM Animate at rest is enabled by default, updates live and saves both toggle states',flush=True)
    expected=['Travel speed','Star density','Streak length','Star glow','Tunnel brightness','Tunnel twist','Tunnel rings','Tunnel colour','Tunnel quality','Tunnel frame rate']
    for label in expected:assert find(label,Atspi.Role.LABEL),label
    speed=wait(lambda:control('Travel speed',Atspi.Role.SPIN_BUTTON))
    wait(lambda:showing(speed))
    for setting in (1.25,0,.8):
        assert speed.get_value_iface().set_current_value(setting)
        wait(lambda:float(ipc('wayfire/get-config-option',{'option':'cube/warp_speed'})['value'])==setting)
        assert float(value()['cube']['warp_speed'])==setting
    choose('Tunnel quality','Detailed')
    wait(lambda:ipc('wayfire/get-config-option',{'option':'cube/warp_quality'})['value']=='2')
    subprocess.run(['grim','-o','VIRTUAL-1',str(root/'warp-controls.png')],env=env,check=True)
    choose('Tunnel quality','Balanced')
    wait(lambda:ipc('wayfire/get-config-option',{'option':'cube/warp_quality'})['value']=='1')
    assert value()['core']['plugins'].split()==['ipc','stipc','ipc-rules',str(stage/'plugins/libcube.so'),'place','grid']
    assert float(value()['cube']['dim'])==.25
    assert value()['grid']['toggle_scope']=='<super> KEY_ENTER'
    print('PASS WCM Warp mode, ten controls, live speed and quality, preserving unrelated preferences',flush=True)
    tab('General')
    choose('Background mode','Hyperspace')
    wait(lambda:ipc('wayfire/get-config-option',{'option':'cube/background_mode'})['value']=='hyperspace')
    assert value()['cube']['background_mode']=='hyperspace'
    tab('Hyperspace')
    labels=['Animate hyperspace at rest','Hyperspace speed','Cloud density','Cloud turbulence',
        'Light ribbons','Destination glow','Hyperspace brightness','Jump surge','Passing stars',
        'Coloured stars','Distant stars','Distant star drift','Space dust','Cloud variation','Pulsar strength','Journey seed','Hyperspace colour','Hyperspace quality','Hyperspace frame rate']
    for label in labels:assert find(label,Atspi.Role.LABEL),label
    idle=wait(lambda:overview_check('Animate hyperspace at rest'))
    assert idle.get_state_set().contains(Atspi.StateType.CHECKED)
    for enabled in (False,True):
        assert idle.get_action_iface().do_action(0)
        wait(lambda:ipc('wayfire/get-config-option',{'option':'cube/hyperspace_animate_at_rest'})['value']==str(enabled).lower())
        assert value().getboolean('cube','hyperspace_animate_at_rest')==enabled
    for label,key,settings in [('Hyperspace speed','hyperspace_speed',(1.25,0,.65)),
        ('Cloud density','hyperspace_cloud_density',(1.4,.85)),
        ('Distant star drift','hyperspace_distant_drift',(0,.1)),
        ('Space dust','hyperspace_dust_density',(0,1.7,.9)),
        ('Cloud variation','hyperspace_cloud_variation',(0,1.6,1.15)),
        ('Pulsar strength','hyperspace_pulsars',(0,1.3,.65)),
        ('Journey seed','hyperspace_seed',(31415,0))]:
        tab('Hyperspace')
        spin=wait(lambda:control(label,Atspi.Role.SPIN_BUTTON))
        spin.get_component_iface().scroll_to(Atspi.ScrollType.ANYWHERE)
        if not showing(spin):spin.get_component_iface().grab_focus()
        for setting in settings:
            assert spin.get_value_iface().set_current_value(setting)
            wait(lambda:float(ipc('wayfire/get-config-option',{'option':'cube/'+key})['value'])==setting)
            assert float(value()['cube'][key])==setting
    tab('Hyperspace')
    quality=wait(lambda:control('Hyperspace quality',Atspi.Role.COMBO_BOX))
    quality.get_component_iface().scroll_to(Atspi.ScrollType.ANYWHERE)
    if not showing(quality):quality.get_component_iface().grab_focus()
    if not showing(quality):
        for bar in nodes():
            if bar.get_role()==Atspi.Role.SCROLL_BAR and showing(bar) and bar.get_state_set().contains(Atspi.StateType.VERTICAL):
                val=bar.get_value_iface()
                val.set_current_value(val.get_maximum_value())
        time.sleep(.15)
    choose('Hyperspace quality','Detailed')
    wait(lambda:ipc('wayfire/get-config-option',{'option':'cube/hyperspace_quality'})['value']=='2')
    choose('Hyperspace quality','Balanced')
    wait(lambda:ipc('wayfire/get-config-option',{'option':'cube/hyperspace_quality'})['value']=='1')
    assert ipc('wayfire/get-config-option',{'option':'cube/hyperspace_coloured_stars'})['default']=='0.120000'
    assert ipc('wayfire/get-config-option',{'option':'cube/warp_coloured_stars'})['default']=='0.120000'
    subprocess.run(['grim','-o','VIRTUAL-1',str(root/'hyperspace-controls.png')],env=env,check=True)
    assert float(value()['cube']['warp_speed'])==.8
    assert value()['grid']['toggle_scope']=='<super> KEY_ENTER'
    print('PASS WCM Hyperspace mode, all nineteen controls, live speed/density/drift/quality, idle toggle and saved settings',flush=True)
    print('ALL HYPERSPACE WCM CHECKS PASSED',flush=True)

finally:
    try:(root/'accessibility.txt').write_text('\n'.join(str(n.get_role())+' '+n.get_name() for n in nodes()))
    except Exception:pass
    if ui is not None and ui.poll() is None:ui.terminate();ui.wait(timeout=5)
    compositor.terminate();compositor.wait(timeout=10)
    print('Artifacts:',root,flush=True)