This repository has been archived by the owner on Feb 21, 2018. It is now read-only.
/
mac.py
236 lines (201 loc) · 7.75 KB
/
mac.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
#! /usr/bin/env python
# -*- coding: UTF-8 -*-
import os, os.path
import time
import hashlib
from Quartz import *
from LaunchServices import * # kUTType constants
from AppKit import NSEvent, NSRunningApplication, NSApplicationActivateIgnoringOtherApps
from errors import WindowException, NotImplementedException
from point import Point
from constants import *
class Image:
data = None
BYTES_PER_PIXEL = 4
BITS_PER_COMPONENT = 8
COLOR_SPACE = CGColorSpaceCreateDeviceRGB()
def __init__(self, src):
self.imageRef = src
self.width = CGImageGetWidth(self.imageRef)
self.height = CGImageGetHeight(self.imageRef)
bytesPerRow = self.BYTES_PER_PIXEL * self.width
size = bytesPerRow * self.height
rawData = Foundation.NSMutableData.dataWithLength_(size)
context = CGBitmapContextCreate(rawData, self.width, self.height, self.BITS_PER_COMPONENT, bytesPerRow, self.COLOR_SPACE, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big)
CGContextDrawImage(context, CGRectMake(0, 0, self.width, self.height), self.imageRef)
self.data = rawData
def isEqual(self, image):
return self.hash() == image.hash()
def hash(self):
hashSrc = ''
for y in range(self.height):
for x in range(self.width):
p = Point(x, y)
hashSrc += str(self.getPixel(p))
return hashlib.md5(hashSrc).hexdigest()
def getPixel(self, point):
byteIndex = long(self.BYTES_PER_PIXEL * (self.width * point.y + point.x))
r = ord(self.data[byteIndex])
g = ord(self.data[byteIndex + 1])
b = ord(self.data[byteIndex + 2])
#a = ord(self.data[byteIndex + 3])
return r * 256 * 256 + g * 256 + b
class Mouse:
@staticmethod
def press(point):
event = CGEventCreateMouseEvent(None, kCGEventLeftMouseDown, point.asTuple(), 0)
CGEventPost(kCGHIDEventTap, event)
@staticmethod
def release(point):
event = CGEventCreateMouseEvent(None, kCGEventLeftMouseUp, point.asTuple(), 0)
CGEventPost(kCGHIDEventTap, event)
@staticmethod
def move(point):
move = CGEventCreateMouseEvent(None, kCGEventMouseMoved, point.asTuple(), 0)
CGEventPost(kCGHIDEventTap, move)
@staticmethod
def position():
loc = NSEvent.mouseLocation()
return Point(loc.x, CGDisplayPixelsHigh(0) - loc.y)
class Keyboard:
@staticmethod
def keydown(keycode):
event = CGEventCreateKeyboardEvent(None, CG_KEY_CODES[str(keycode)], True)
CGEventPost(kCGHIDEventTap, event)
@staticmethod
def keyup(keycode):
event = CGEventCreateKeyboardEvent(None, CG_KEY_CODES[str(keycode)], False)
CGEventPost(kCGHIDEventTap, event)
@staticmethod
def press(keycode):
Keyboard.keydown(keycode)
time.sleep(0.05)
Keyboard.keyup(keycode)
class PlatformSpecificApi:
snapshot = None
def initGameWindow(self):
windowList = CGWindowListCopyWindowInfo(kCGWindowListOptionAll, kCGNullWindowID)
self.window = None
for window in windowList:
if kCGWindowName in window and GAME_TITLE in window[kCGWindowName]:
self.window = window
break
if self.window:
if 'Firefox' in self.window[kCGWindowOwnerName]:
raise WindowException('Firefox not supported. Use Google Chrome')
self.windowId = window[kCGWindowNumber]
else:
raise WindowException('Can not find game window')
self.hashes = {}
for filename in os.listdir('grabbed-images'):
if filename.endswith('.png'):
asset = self.loadIcon(os.path.join('grabbed-images', filename))
if asset:
h = asset.hash()
self.hashes[h] = asset
print '[d] Hashes: ', len(self.hashes)
def loadIcon(self, filename):
imgDataProvider = CGDataProviderCreateWithCFData(NSData.dataWithContentsOfFile_(filename))
imageRef = CGImageCreateWithPNGDataProvider(imgDataProvider, None, True, kCGRenderingIntentDefault)
if imageRef:
return Image(imageRef)
else:
return None
def cropCGImage(self, image, cropRect):
bitsPerComponent = CGImageGetBitsPerComponent(image)
bytesPerRow = CGImageGetBytesPerRow(image) / CGImageGetWidth(image) * cropRect.size.width
context = CGBitmapContextCreate(None, cropRect.size.width, cropRect.size.height, bitsPerComponent, bytesPerRow, CGColorSpaceCreateDeviceRGB(), CGImageGetBitmapInfo(image))
CGContextDrawImage(context, ((-cropRect.origin.x, -cropRect.origin.y), cropRect.size), image)
return CGBitmapContextCreateImage(context)
def getImageAtPoint(self, point, checkHashes = False, size = Point(32, 32)):#, useSnapshot = True):
# point = point + self.getOffset() + Point(1, 2)
point = point + self.getLocalOffset() + Point(1, 2)
rect = CGRectMake(point.x, point.y, size.x - 1, size.y)
# imageRef = CGWindowListCreateImageFromArray(rect, [self.windowId], kCGWindowImageBoundsIgnoreFraming)
imageRef = CGImageCreateWithImageInRect(self.snapshot, rect)
# imageRef = self.cropCGImage(self.snapshot, rect)
image = Image(imageRef)
if checkHashes:
h = image.hash()
if not h in self.hashes:
print '[i] Grabbed new asset'
self.hashes[h] = image
self.saveImage(image.imageRef, os.path.join('grabbed-images', str(h) + '.png'))
return image
def getVerticalWindowOffset(self):
MAX_OFFSET = 300 # Возможный отступ
bounds = self.window[kCGWindowBounds]
searchRect = CGRectMake(bounds['X'] + bounds['Width'] / 2 - 1, bounds['Y'] + GAME_SIZE.y, 3, MAX_OFFSET)
searchRectImage = CGWindowListCreateImageFromArray(searchRect, [self.windowId], kCGWindowImageBoundsIgnoreFraming)
searchRectImage = Image(searchRectImage)
for y in range(0, MAX_OFFSET):
if searchRectImage.getPixel(Point(0, y)) == 0x000 and searchRectImage.getPixel(Point(1, y)) == 0x000 and searchRectImage.getPixel(Point(2, y)) == 0x000:
return y - 2 # Не ясно пока, почему нужна поправка, но пусть будет
return 0
def getLocalOffset(self):
return Point(self.window[kCGWindowBounds]['Width'] / 2 - GAME_SIZE.x / 2, self.verticalWindowOffset)
def getOffset(self):
bounds = self.window[kCGWindowBounds]
localOffset = self.getLocalOffset()
return Point(bounds['X'] + localOffset.x, bounds['Y'] + localOffset.y)
def activateWindow(self):
app = NSRunningApplication.runningApplicationWithProcessIdentifier_(self.window[kCGWindowOwnerPID])
app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)
def click(self, point):
oldPosition = Mouse.position()
point = point + self.getOffset()
time.sleep(0.05)
self.activateWindow()
time.sleep(0.05)
Mouse.press(point)
Mouse.release(point)
time.sleep(0.001)
Mouse.move(oldPosition)
def drag(self, pointA, pointB):
pointA = pointA + self.getOffset()
pointB = pointB + self.getOffset()
oldPosition = Mouse.position()
time.sleep(0.05)
self.activateWindow()
time.sleep(0.05)
Mouse.press(pointA)
time.sleep(0.05)
Mouse.move(pointB)
time.sleep(0.25)
Mouse.release(pointB)
time.sleep(0.3)
Mouse.move(oldPosition)
def sendkey(self, key):
self.activateWindow()
time.sleep(0.05)
Keyboard.press(key)
def testPixel(self, point, colorCode):
# point = point + self.getOffset()
# rect = CGRectMake(point.x, point.y, 1, 1)
# imageRef = CGWindowListCreateImageFromArray(rect, [self.windowId], kCGWindowImageBoundsIgnoreFraming)
# image = Image(imageRef)
point = point + self.getLocalOffset()
image = Image(self.snapshot)
return colorCode == image.getPixel(point)
# return colorCode == image.getPixel(Point(0, 0))
# Additional test methods
def getWindowScreenshot(self):
windowImage = CGWindowListCreateImageFromArray(CGRectNull, [self.windowId], kCGWindowImageBoundsIgnoreFraming)
return windowImage
def saveImage(self, image, filename):
url = NSURL.fileURLWithPath_(filename)
imageDestination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, None)
CGImageDestinationAddImage(imageDestination, image, None)
CGImageDestinationFinalize(imageDestination)
CG_KEY_CODES = {
'shift': 56,
'1': 18,
'2': 19,
'3': 20,
'4': 21,
'5': 23,
'6': 22,
'7': 26,
'8': 28,
'tilda': 50
}