Files
dxdesigner-part-replacement/tools/accept_acrylic_ui.py
T

152 lines
9.2 KiB
Python

"""Capture the real task-center UI above an owned, changing backdrop (Windows).
Uses only temporary sample projects and an isolated task store. Never starts CAD.
Run: python tools/accept_acrylic_ui.py --output build/acrylic-acceptance
"""
import argparse
import ctypes
from ctypes import wintypes
import json
import logging
import os
from pathlib import Path
import sys
import tempfile
import time
os.environ.pop('QT_QPA_PLATFORM',None)
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'src'))
from PySide6.QtCore import Qt,QRectF
from PySide6.QtGui import QColor,QFont,QPainter,QLinearGradient,QPen
from PySide6.QtWidgets import QApplication,QWidget,QToolTip
from PIL import ImageGrab,ImageChops,ImageStat
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
from dx_productivity.trial_task_center.target_plan import ComponentTarget,TargetPlanRow
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output',type=Path,default=Path('build/acrylic-acceptance'))
args=parser.parse_args();out=args.output.resolve();out.mkdir(parents=True,exist_ok=True)
app=QApplication([]);app.setFont(QFont('Microsoft YaHei UI',9))
def settle(seconds=.2):
deadline=time.monotonic()+seconds
while time.monotonic()<deadline:
app.processEvents();time.sleep(.01)
class Background(QWidget):
phase=0
def paintEvent(self,event):
p=QPainter(self);g=QLinearGradient(0,0,self.width(),self.height())
g.setColorAt(0,QColor('#386eae')if self.phase==0 else QColor('#c17c51'))
g.setColorAt(.5,QColor('#a5bfbb'));g.setColorAt(1,QColor('#cfa4ad')if self.phase==0 else QColor('#5b87b4'))
p.fillRect(self.rect(),g);p.setPen(QPen(QColor(255,255,255,190),2))
for x in range(0,self.width(),22):p.drawLine(x,0,x,self.height())
p.setPen(QColor('#2e4a6b'));p.setFont(QFont('Segoe UI',32,QFont.Weight.Bold))
for y in range(100,self.height(),150):p.drawText(20,y,'OWNED LIVE BACKDROP / '+str(self.phase+1))
background=Background(None,Qt.WindowType.FramelessWindowHint|Qt.WindowType.Tool|Qt.WindowType.WindowStaysOnTopHint)
screen=app.primaryScreen();area=screen.availableGeometry()
width=min(1280,area.width()-80);height=min(880,area.height()-80)
x=area.x()+(area.width()-width)//2;y=area.y()+(area.height()-height)//2
background.setGeometry(x-18,y-40,width+36,height+60);background.show()
user=ctypes.WinDLL('user32',use_last_error=True)
class Point(ctypes.Structure):_fields_=[('x',ctypes.c_long),('y',ctypes.c_long)]
user.WindowFromPoint.argtypes=[Point];user.WindowFromPoint.restype=wintypes.HWND
user.GetWindowThreadProcessId.argtypes=[wintypes.HWND,ctypes.POINTER(wintypes.DWORD)]
captures={};report={'cad_started':False,'sample_data_only':True,'ownership_checked':True,'os_build':sys.getwindowsversion().build}
with tempfile.TemporaryDirectory(prefix='sample-',dir=out,ignore_cleanup_errors=True)as temp:
root=Path(temp);projects=root/'projects'
for name in ('Audio_D2128','Audio_T605A'):
project=projects/name/(name+'.prj');project.parent.mkdir(parents=True)
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
store=TaskStore(root/'tasks.db')
service=TaskCenterService(store,configure_logging(root/'data'))
tasks=service.create_project_tasks(projects)
service.add_rule(tasks[0].task_id,'4100-CA0000-T7','4100-CA0000-T0')
project=store.list_projects(tasks[0].task_id)[0].path
rows=tuple(TargetPlanRow(ComponentTarget(project,'MAIN','1','sample-'+str(i),ref,'4100-CA0000-T7','100nF / 50V'),i==0,'4100-CA0000-T0')for i,ref in enumerate(('RV05','RV11','C103','C104','C105','C106')))
store.record_target_inventory(tasks[0].task_id,tuple(row.target for row in rows))
service.replace_target_plan(tasks[0].task_id,rows)
window=TrialTaskCenterWindow(service,close_plan_confirmer=lambda:'discard')
window.setWindowFlag(Qt.WindowType.WindowStaysOnTopHint,True)
window.setGeometry(x,y,width,height);window.show();window.raise_();window.activateWindow()
window.open_task(tasks[0].task_id)
deadline=time.monotonic()+10
while time.monotonic()<deadline:
settle(.1)
if not window._workers and not window._context_query.busy and not window._task_query.busy and not window._feedback_query.busy:break
window.mapping_tabs.setCurrentIndex(1);settle(1)
assert window.property('acrylicEnabled'),'Native Acrylic not available under current system policy'
report['native_enabled']=True
def capture(name):
settle(.7)
QToolTip.hideText();settle(.12)
geo=window.geometry();scale=screen.devicePixelRatio()
box=tuple(round(v*scale)for v in [geo.x(),geo.y(),geo.right()+1,geo.bottom()+1])
def owns_rectangle():
for cy in range(box[1]+3,box[3]-3,30):
for cx in range(box[0]+3,box[2]-3,30):
pid=wintypes.DWORD();user.GetWindowThreadProcessId(user.WindowFromPoint(Point(cx,cy)),ctypes.byref(pid))
if pid.value!=os.getpid():return False
return True
for attempt in range(4):
if owns_rectangle():break
window.raise_();settle(.5)
else:raise AssertionError('Capture occluded by a foreign window; no image saved')
image=ImageGrab.grab(bbox=box,all_screens=True).convert('RGB');image.save(out/(name+'.png'));captures[name]=image
return geo
geometry=capture('native-app-backdrop-a')
background.phase=1;background.update();capture('native-app-backdrop-b')
scale=screen.devicePixelRatio()
def relative_rect(widget):
pt=widget.mapTo(window,widget.rect().topLeft());r=widget.rect()
return [round(v*scale)for v in [pt.x(),pt.y(),pt.x()+r.width(),pt.y()+r.height()]]
sidebar=relative_rect(window.task_list.list)
sidebar=[sidebar[0]+8,sidebar[1]+round(190*scale),sidebar[2]-8,sidebar[3]-12]
table=relative_rect(window.plan_panel.table.viewport())
table=[table[0]+12,max(table[1]+8,table[3]-round(45*scale)),table[2]-20,table[3]-8]
header=relative_rect(window.project_summary.path)
execution=relative_rect(window.run_panel.execution_status)
execution=[(execution[0]+execution[2])//2,execution[1],execution[2]-12,execution[3]]
assert sidebar[3]>sidebar[1] and table[3]>table[1]
a=captures['native-app-backdrop-a'];b=captures['native-app-backdrop-b']
mean=lambda image:sum(ImageStat.Stat(image).mean)/3
difference=ImageChops.difference(a,b)
report['sidebar_backdrop_difference']=mean(difference.crop(sidebar))
report['opaque_table_backdrop_difference']=mean(difference.crop(table))
report['right_header_backdrop_difference']=mean(difference.crop(header))
report['right_execution_backdrop_difference']=mean(difference.crop(execution))
assert report['sidebar_backdrop_difference']>2,report
assert report['right_header_backdrop_difference']>2,report
assert report['right_execution_backdrop_difference']>2,report
assert report['opaque_table_backdrop_difference']<1.5,report
window.plan_panel.find_text.setText('RV');window.plan_panel.find()
report['visible_search_feedback']=window.plan_panel.find_result.isVisible()
assert '2 / 6'in window.plan_panel.find_result.text()
capture('native-app-search')
window.plan_panel.find_text.setText('NO-MATCH');window.plan_panel.find()
report['empty_search_feedback']=window.plan_panel.table.empty_hint.isVisible()
assert report['empty_search_feedback']
capture('native-app-empty-search')
window.plan_panel.clear_find();window.plan_panel.table.clearSelection()
window.reduced_transparency_button.setChecked(True);capture('native-app-solid')
assert not window.property('acrylicEnabled')
solid=captures['native-app-solid']
report['solid_sidebar_mean']=ImageStat.Stat(solid.crop(sidebar)).mean
assert min(report['solid_sidebar_mean'])>200,report
report['solid_fallback']=True
window.reduced_transparency_button.setChecked(False);settle(.3)
window.resize(980,700);capture('native-app-compact')
report['compact_size']=[window.width(),window.height()]
report['compact_table_height']=window.plan_panel.table.viewport().height()
assert report['compact_size']==[980,700]
assert report['compact_table_height']>=100
window.project_options_button.setChecked(True);settle(.2)
report['options_exposed']=window.run_panel.copy_value_check.isVisible()
window.plan_panel.discard_all();window.close();settle(.3);store.close();logging.shutdown()
background.close();app.processEvents()
(out/'acceptance.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print(json.dumps(report,ensure_ascii=True))
if __name__=='__main__':main()