@@ -0,0 +1,311 @@
package stambhadriver
import (
"context"
"errors"
"image"
"image/color"
"math"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/macos/autoinstall/ocr"
"github.com/Nwflower/reims-go/internal/macos/autoinstall/vision"
"github.com/Nwflower/reims-go/internal/qmp"
"github.com/Nwflower/reims-go/internal/thumb"
)
// The login window handles its power menu even when it ignores the SMC
// power-button shortcut. Read the native menu before selecting an action.
func requestLoginWindowShutdown ( ctx context . Context , conn * qmp . Conn ) ( bool , error ) {
tmp , err := os . MkdirTemp ( "" , "reims-arm-shutdown-" )
if err != nil {
return false , err
}
defer os . RemoveAll ( tmp )
pp , err := filepath . Abs ( filepath . Join ( tmp , "screen.ppm" ) )
if err != nil {
return false , err
}
readFrame := func ( ) ( image . Image , error ) {
format , err := qmp . ScreendumpDisplay ( conn , pp , "gfx" , 0 )
if err != nil {
return nil , err
}
return thumb . Load ( pp , format )
}
frame , err := readFrame ( )
if err != nil {
// Older runtimes and guests still in their boot console use the
// existing power-button path.
return false , nil
}
icon , scale , found := findLoginPowerIcon ( frame )
if ! found {
return false , nil
}
engine , err := ocr . NewWinOCREngine ( "" )
if err != nil {
return false , nil
}
defer engine . Close ( )
bounds := frame . Bounds ( )
// A power-shaped status item alone can also belong to an ordinary desktop app.
clockRegion := image . Rect ( bounds . Dx ( ) / 4 , bounds . Dy ( ) / 18 , bounds . Dx ( ) * 3 / 4 , bounds . Dy ( ) / 3 ) . Add ( bounds . Min )
clock := thumb . Scale ( vision . Crop ( frame , clockRegion ) , 512 )
probe , cancel := context . WithTimeout ( ctx , 2 * time . Second )
reading , err := engine . Recognize ( probe , clock )
cancel ( )
if ctx . Err ( ) != nil {
return false , ctx . Err ( )
}
if err != nil || ! hasLoginClock ( reading . Lines , clock . Bounds ( ) ) {
return false , nil
}
mice , err := qmp . QueryMice ( conn )
if err != nil {
return true , err
}
if ! qmp . HasCurrentAbsoluteMouse ( mice ) {
return true , errors . New ( "the macOS login window needs an absolute pointer to use its power menu" )
}
iconArea := image . Rect ( icon . X - 7 * scale , icon . Y - 7 * scale , icon . X + 8 * scale , icon . Y + 8 * scale )
crop := image . Rect ( bounds . Max . X - 165 * scale , bounds . Min . Y , bounds . Max . X , bounds . Min . Y + 125 * scale ) . Intersect ( bounds )
before := scalePowerMenu ( frame , crop )
menuCtx , cancel := context . WithTimeout ( ctx , 7 * time . Second )
defer cancel ( )
opened := false
for menuCtx . Err ( ) == nil {
menu := scalePowerMenu ( frame , crop )
// The user may already have opened the power menu. In that case
// select the verified entry without toggling the menu closed first.
if ! opened || menuAppeared ( before , menu ) {
result , ocrErr := engine . Recognize ( menuCtx , menu )
if ocrErr != nil {
break
}
if entry , ok := shutdownMenuEntry ( result . Lines ) ; ok {
point := crop . Min . Add ( entry . Div ( 3 ) )
if point . Y <= icon . Y + 20 * scale || point . Y >= icon . Y + 100 * scale ||
point . X < icon . X - 95 * scale || point . X > icon . X + 28 * scale {
break
}
// The guest can unlock, resize or dismiss its menu while OCR runs.
current , err := readFrame ( )
if err != nil {
return true , err
}
menuArea := image . Rect ( crop . Min . X , icon . Y + 10 * scale , crop . Max . X , crop . Max . Y )
target := image . Rect ( point . X - 20 * scale , point . Y - 6 * scale , point . X + 20 * scale , point . Y + 6 * scale )
if ! samePowerMenuArea ( frame , current , menuArea ) || ! samePowerMenuArea ( frame , current , target ) ||
! samePowerMenuArea ( frame , current , clockRegion ) {
break
}
return true , clickGuestPowerMenu ( menuCtx , conn , point , bounds )
}
}
if ! opened {
current , err := readFrame ( )
if err != nil {
return false , err
}
if ! samePowerMenuArea ( frame , current , iconArea ) || ! samePowerMenuArea ( frame , current , clockRegion ) ||
! samePowerMenuArea ( frame , current , crop ) {
break
}
if err := clickGuestPowerMenu ( menuCtx , conn , icon , bounds ) ; err != nil {
return true , err
}
opened = true
}
if waitShutdownInput ( menuCtx , 400 * time . Millisecond ) != nil {
break
}
frame , err = readFrame ( )
if err != nil {
return true , err
}
if frame . Bounds ( ) != bounds {
break
}
}
if err := ctx . Err ( ) ; err != nil {
return true , err
}
return true , errors . New ( "could not identify the macOS Shut Down option. Open the power menu in the virtual machine to shut down" )
}
func clickGuestPowerMenu ( ctx context . Context , conn * qmp . Conn , p image . Point , bounds image . Rectangle ) error {
if err := ctx . Err ( ) ; err != nil {
return err
}
p = p . Sub ( bounds . Min )
if err := qmp . MouseButtonAt ( conn , p . X , p . Y , bounds . Dx ( ) , bounds . Dy ( ) , "left" , true ) ; err != nil {
_ = qmp . MouseButton ( conn , "left" , false )
return err
}
err := waitShutdownInput ( ctx , 120 * time . Millisecond )
return errors . Join ( err , qmp . MouseButton ( conn , "left" , false ) )
}
func waitShutdownInput ( ctx context . Context , delay time . Duration ) error {
timer := time . NewTimer ( delay )
defer timer . Stop ( )
select {
case <- ctx . Done ( ) :
return ctx . Err ( )
case <- timer . C :
return nil
}
}
// Intensity mask for the power symbol: a vertical stroke above a broken ring.
// Compare contrast, so the same mask works on light and dark backgrounds.
var powerIconMask = [ ... ] string {
"......#......" ,
"......#......" ,
".+#...#...#+." ,
".#....#....#." ,
"++....#....++" ,
"#.....#.....#" ,
"#...........#" ,
"#...........#" ,
"++.........++" ,
".#.........#." ,
".+#.......#+." ,
"..+#+...+#+.." ,
"....+###+...." ,
}
func findLoginPowerIcon ( frame image . Image ) ( image . Point , int , bool ) {
b := frame . Bounds ( )
best , point , scale := 0.89 , image . Point { } , 0
if b . Dx ( ) < 640 || b . Dy ( ) < 400 {
return point , scale , false
}
for step := 1 ; step <= 2 ; step ++ {
for y := 4 * step ; y <= 18 * step ; y ++ {
for x := b . Max . X - 96 * step ; x < b . Max . X - 19 * step ; x ++ {
candidate := image . Pt ( x , y )
score := powerIconScore ( frame , candidate , step )
if score > best {
best , point , scale = score , candidate . Add ( image . Pt ( 6 * step , 6 * step ) ) , step
}
}
}
}
return point , scale , scale != 0
}
func powerIconScore ( frame image . Image , top image . Point , step int ) float64 {
var n , sum , sum2 , ink , ink2 , dot float64
for y , row := range powerIconMask {
for x , token := range row {
var weight float64
if token == '#' {
weight = 1
} else if token == '+' {
weight = .5
}
c := color . GrayModel . Convert ( frame . At ( top . X + x * step , top . Y + y * step ) ) . ( color . Gray )
val := float64 ( c . Y )
n ++
sum , sum2 = sum + val , sum2 + val * val
ink , ink2 = ink + weight , ink2 + weight * weight
dot += weight * val
}
}
variance := sum2 - sum * sum / n
if variance < 10000 {
return 0
}
return math . Abs ( dot - sum * ink / n ) / math . Sqrt ( variance * ( ink2 - ink * ink / n ) )
}
func scalePowerMenu ( frame image . Image , crop image . Rectangle ) * image . RGBA {
result := image . NewRGBA ( image . Rect ( 0 , 0 , crop . Dx ( ) * 3 , crop . Dy ( ) * 3 ) )
for y := range result . Bounds ( ) . Dy ( ) {
for x := range result . Bounds ( ) . Dx ( ) {
result . Set ( x , y , frame . At ( crop . Min . X + x / 3 , crop . Min . Y + y / 3 ) )
}
}
return result
}
func menuAppeared ( before , after * image . RGBA ) bool {
// Ignore the status bar highlight around the power button. An open menu
// changes a substantial region below it, including its background.
changed := 0
for y := 90 ; y < after . Bounds ( ) . Dy ( ) ; y += 6 {
for x := 0 ; x < after . Bounds ( ) . Dx ( ) ; x += 6 {
a , b := before . RGBAAt ( x , y ) , after . RGBAAt ( x , y )
if absColorDelta ( a . R , b . R ) + absColorDelta ( a . G , b . G ) + absColorDelta ( a . B , b . B ) > 65 {
changed ++
}
}
}
return changed > 250
}
func absColorDelta ( a , b uint8 ) int {
return max ( int ( a ) , int ( b ) ) - min ( int ( a ) , int ( b ) )
}
var loginClock = regexp . MustCompile ( "^(?:[01]?[0-9]|2[0-3])[:: ][0-5][0-9](?:AM|PM)?$" )
func hasLoginClock ( lines [ ] ocr . Line , bounds image . Rectangle ) bool {
for _ , line := range lines {
r := line . Rect
centerX := ( r . Min . X + r . Max . X ) / 2
if r . Empty ( ) || ! r . In ( bounds ) || r . Dy ( ) < bounds . Dy ( ) / 6 ||
centerX < bounds . Min . X + bounds . Dx ( ) * 2 / 5 || centerX > bounds . Min . X + bounds . Dx ( ) * 3 / 5 {
continue
}
text := strings . ToUpper ( strings . Join ( strings . Fields ( line . Text ) , "" ) )
if loginClock . MatchString ( text ) {
return true
}
}
return false
}
// Allow minor antialiasing changes while the pointer moves, but require the
// scene or popover that authorized the click to still be present.
func samePowerMenuArea ( a , b image . Image , area image . Rectangle ) bool {
if a . Bounds ( ) != b . Bounds ( ) || area . Empty ( ) || ! area . In ( a . Bounds ( ) ) {
return false
}
changed , samples := 0 , 0
for y := area . Min . Y ; y < area . Max . Y ; y += 2 {
for x := area . Min . X ; x < area . Max . X ; x += 2 {
ac := color . RGBAModel . Convert ( a . At ( x , y ) ) . ( color . RGBA )
bc := color . RGBAModel . Convert ( b . At ( x , y ) ) . ( color . RGBA )
if absColorDelta ( ac . R , bc . R ) + absColorDelta ( ac . G , bc . G ) + absColorDelta ( ac . B , bc . B ) > 45 {
changed ++
}
samples ++
}
}
return changed * 100 <= samples
}
func shutdownMenuEntry ( lines [ ] ocr . Line ) ( image . Point , bool ) {
normal := func ( s string ) string { return strings . ToLower ( strings . Join ( strings . Fields ( s ) , "" ) ) }
for i := 1 ; i + 1 < len ( lines ) ; i ++ {
a , b , c := lines [ i - 1 ] , lines [ i ] , lines [ i + 1 ]
switch [ 3 ] string { normal ( a . Text ) , normal ( b . Text ) , normal ( c . Text ) } {
case [ 3 ] string { "restart" , "shutdown" , "sleep" } , [ 3 ] string { "restart" , "shutdown" , "sieep" } ,
[ 3 ] string { "重新启动" , "关机" , "睡眠" } , [ 3 ] string { "重新啟動" , "關機" , "睡眠" } :
if ! a . Rect . Empty ( ) && ! b . Rect . Empty ( ) && ! c . Rect . Empty ( ) &&
math . Abs ( float64 ( a . Rect . Min . X - b . Rect . Min . X ) ) <= 30 && math . Abs ( float64 ( c . Rect . Min . X - b . Rect . Min . X ) ) <= 30 &&
b . Rect . Min . Y - a . Rect . Min . Y >= 35 && b . Rect . Min . Y - a . Rect . Min . Y <= 160 && c . Rect . Min . Y - b . Rect . Min . Y >= 35 && c . Rect . Min . Y - b . Rect . Min . Y <= 160 {
return b . Rect . Min . Add ( b . Rect . Max ) . Div ( 2 ) , true
}
}
}
return image . Point { } , false
}