import pyscreenshot

from discogui import imglog
from discogui.mouse import PyMouse
from discogui.screenrect import ScreenRect


def getbbox(img, outside=False):
    """
    Get bounding box.
    PIL getbbox() is not symmetrical on left/right.

    outside=0 -> box contains edges
    outside=1 -> box does not contain edges

    :param img: PIL image
    :param outside: bool
    :rtype: ScreenRect
    """
    bbox = img.getbbox()
    if bbox:
        bbox = ScreenRect(bbox)
        if outside:
            bbox.left -= 1
            bbox.top -= 1
        else:
            bbox.right += 1
            bbox.bottom += 1
        return bbox


def autocrop(img, outside=False):
    box = getbbox(img, outside=outside)
    if box:
        img = img.crop(box)
    return img


class EmptyScreenException(Exception):
    pass


def focus_wnd():
    """
    move mouse over window to get focus
    """
    rct_wnd = getbbox(grab())
    if not rct_wnd:
        raise EmptyScreenException("Empty screen!")

    imglog.set_crop_rect(rct_wnd)

    # init window focus
    mouse = PyMouse()
    mouse.move(*rct_wnd.topleft)

    img_orig = grab()
    imglog.img_log(img_orig, "img_orig")
    return img_orig


def grab():
    return pyscreenshot.grab(childprocess=True)


@@ -203,17 +203,18 @@
 tbbox() 
-i
+wa
 s not sy
@@ -237,16 +237,48 @@
 t/right.
+%0A    It is OK in latest version.
 %0A%0A    ou
@@ -523,32 +523,71 @@
 outside:%0A       
+     bbox = bbox.add_border()%0A        #
      bbox.left -
@@ -589,32 +589,34 @@
 eft -= 1%0A       
+ #
      bbox.top -=
@@ -625,16 +625,18 @@
 %0A       
+ #
  else:%0A 
@@ -633,32 +633,34 @@
  # else:%0A       
+ #
      bbox.right 
@@ -663,32 +663,34 @@
 ght += 1%0A       
+ #
      bbox.bottom

fix getbbox