/usr/lib/python3/dist-packages/pyvirtualdisplay/smartdisplay.py is in python3-pyvirtualdisplay 0.2.1-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | from pyvirtualdisplay.display import Display
from PIL import Image
from PIL import ImageChops
import logging
import pyscreenshot
import time
log = logging.getLogger(__name__)
# class DisplayError(Exception):
# pass
class DisplayTimeoutError(Exception):
pass
class SmartDisplay(Display):
pyscreenshot_backend = None
pyscreenshot_childprocess = True
def autocrop(self, im):
'''Crop borders off an image.
:param im: Source image.
:param bgcolor: Background color, using either a color tuple or a color name (1.1.4 only).
:return: An image without borders, or None if there's no actual content in the image.
'''
if im.mode != "RGB":
im = im.convert("RGB")
bg = Image.new("RGB", im.size, self.bgcolor)
diff = ImageChops.difference(im, bg)
bbox = diff.getbbox()
if bbox:
return im.crop(bbox)
return None # no contents
def grab(self, autocrop=True):
try:
# first try newer pyscreenshot version
img = pyscreenshot.grab(
childprocess=self.pyscreenshot_childprocess,
backend=self.pyscreenshot_backend,
)
except TypeError:
# try older pyscreenshot version
img = pyscreenshot.grab()
if autocrop:
img = self.autocrop(img)
return img
def waitgrab(self, timeout=60, autocrop=True, cb_imgcheck=None):
'''start process and create screenshot.
Repeat screenshot until it is not empty and
cb_imgcheck callback function returns True
for current screenshot.
:param autocrop: True -> crop screenshot
:param timeout: int
:param cb_imgcheck: None or callback for testing img,
True = accept img,
False = reject img
'''
t = 0
sleep_time = 0.3 # for fast windows
repeat_time = 1
while 1:
log.debug('sleeping %s secs' % str(sleep_time))
time.sleep(sleep_time)
t += sleep_time
img = self.grab(autocrop=autocrop)
if img:
if not cb_imgcheck:
break
if cb_imgcheck(img):
break
sleep_time = repeat_time
repeat_time += 1 # progressive
if t > timeout:
msg = 'Timeout! elapsed time:%s timeout:%s ' % (t, timeout)
raise DisplayTimeoutError(msg)
break
log.debug('screenshot is empty, next try..')
assert img
# if not img:
# log.debug('screenshot is empty!')
return img
|