<commit_before># -*- coding: utf-8 -*-

"""Python module to control Android phones via `ADB`_ from Stb-tester scripts.

Copyright © 2017 Stb-tester.com Ltd.
License: LGPL v2.1 or (at your option) any later version (see
https://github.com/stb-tester/stb-tester/blob/master/LICENSE for details).

Usage::

    from stbt.android import AdbDevice
    adb = AdbDevice()
    adb.tap(x=100, y=50)

For feedback (video from the Android device-under-test) you can use:

* Stb-tester's standard HDMI video-capture if the device-under-test is an
  Android set-top box.
* HDMI video-capture from a tablet or phone with an MHL adapter.
* A camera pointed at the phone's screen with an `Stb-tester CAMERA`_ device.
* Screenshots captured over USB via ADB.

For more details on the benefits and trade-offs of each method, see
<https://stb-tester.com/blog/2017/02/21/testing-video-playback-on-mobile-devices>.

Note that you can instead use Stb-tester features such as image-matching
in your existing Selenium/WebDriver/Appium tests. See
<https://stb-tester.com/blog/2016/09/20/add-visual-verification-to-your-selenium-tests-with-stb-tester>.

.. _ADB: https://developer.android.com/studio/command-line/adb.html
.. _Stb-tester CAMERA: https://stb-tester.com/videos/the-stb-tester-camera-for-tvs-and-mobile-devices

"""

from __future__ import division

import ConfigParser
import logging
import re
import subprocess
import sys
import time
from collections import namedtuple

import cv2
import numpy
from enum import Enum

import stbt


class CoordinateSystem(Enum):
    # pylint:disable=pointless-string-statement

    """How to translate coordinates from the video-frames processed by your
    test script, to the coordinates expected by ADB for tap & swipe events.

    When you tell ADB to send a tap or swipe event you must give it x & y
    coordinates. The coordinate system matches the orientation of the device.
    We'll call these the physical coordinates. For example my phone's display
    is Full HD (1080 pixels x 1920 pixels):

    ===================  ======  ======  ======================================
    Logical orientation  x       y       (0, 0) is
    ===================  ======  ======  ======================================
    Portrait             0-1080  0-1920  top-left
    Landscape            0-1920  0-1080  top-left (i.e. the top-right corner if
                                         the phone is physically in portrait)
    ===================  ======  ======  ======================================

    Note that an app can force the device to think it's in portrait orientation
    even if you're physically holding the device in landscape orientation. We
    call this the "logical orientation". Similarly, an app can force the device
    into logical landscape orientation even if you have switched off auto-rotate
    in the device's settings menu.

    However the video-frames that you analyse in your test scripts may not
    match the physical resolution of the device. For example if you're using a
    camera pointed at the device's screen, the resolution of your screenshots
    (even after geometric correction by the `Stb-tester CAMERA`_) will be the
    resolution of the camera, not of the device under test.

    You can give `AdbDevice.tap` and `AdbDevice.swipe` the coordinates from
    your video-frame (for example, you can pass in ``stbt.match(...).region``)
    and this setting will ensure that the coordinates are converted to
    physical coordinates in the appropriate way before passing them on to ADB.
    """

    """Frames are captured via ADB screenshot.

    Frames will be in the same orientation & resolution as the physical device.
    """
    ADB_NATIVE = 0

    """Frames are captured via ADB screenshot and then scaled to 720p.

    Frames will be in the same orientation as the physical device, but scaled.
    """
    ADB_720P = 1

    """
    Frames are captured via HDMI (using an MHL cable) at 720p.

    Frames will always be in landscape orientation. If the device is in
    portrait orientation, you'll get black bars to the left & right. If the
    device is in landscape orientation, the frame will match what you see on
    the device (assuming the device's physical aspect ratio matches the aspect
    ratio of HDMI).
    """
    HDMI_720P = 2

    """Frames are captured from an `Stb-tester CAMERA`_ pointing at the
    device's screen.

    The camera & device must both be physically in landscape orientation.

    Frames will always be in landscape orientation; if the device is in logical
    portrait orientation the image will be rotated 90° anti-clockwise.
    """
    CAMERA_720P = 3


class AdbDevice(object):
    """Control an Android device using `ADB`_.

    Default values for each parameter can be specified in your "stbt.conf"
    config file under the "[android]" section.

    :param string adb_server:
        The ADB server (that is, the PC connected to the Android device).
        Defaults to localhost.
    :param string adb_device:
        Serial number of the Android device connected to ADB server PC (you can
        get this by running ``adb devices -l``). If not specified, there must be
        only one Android device connected. If ``tcpip=True`` this must be the
        Android device's IP address.
    :param string adb_binary:
        The path to the ADB client executable. Defaults to "adb".
    :param bool tcpip:
        The ADB server communicates with the Android device via TCP/IP, not
        USB. This requires that you have enabled TCP/IP ADB access on the
        device. Defaults to False.
    :param CoordinateSystem coordinate_system:
        How to convert the coordinates you give to `AdbDevice.tap` and
        `AdbDevice.swipe` into the coordinates required by ADB. See
        `CoordinateSystem` for details. Defaults to ``CAMERA_720P`` on the
        `Stb-tester CAMERA`_, or ``ADB_NATIVE`` elsewhere.
    """

    def __init__(self, adb_server=None, adb_device=None, adb_binary=None,
                 tcpip=False, coordinate_system=None, _config=None):

        if _config is None:
            _config = stbt._stbt.config._config_init()  # pylint:disable=protected-access

        self.adb_server = adb_server or _get_config(_config, "android",
                                                    "adb_server", None)
        self._adb_device = adb_device or _get_config(_config, "android",
                                                     "adb_device", None)
        self.adb_binary = adb_binary or _get_config(_config, "android",
                                                    "adb_binary", "adb")
        if tcpip is None:
            try:
                tcpip = _config.getboolean("android", "tcpip")
            except ConfigParser.Error:
                tcpip = False
        self.tcpip = tcpip

        if coordinate_system is None:
            name = _get_config("android", "coordinate_system", "ADB_NATIVE")
            if name not in CoordinateSystem.__members__:  # pylint:disable=no-member
                raise ValueError(
                    "Invalid value '%s' for android.coordinate_system in "
                    "config file. Valid values are %s."
                    % (name, ", ".join("'%s'" % k for k in
                                       CoordinateSystem.__members__)))  # pylint:disable=no-member
            coordinate_system = CoordinateSystem[name]
        self.coordinate_system = coordinate_system

    @property
    def adb_device(self):
        if self.tcpip and self._adb_device and ":" not in self._adb_device:
            return self._adb_device + ":5555"
        else:
            return self._adb_device

    def adb(self, command, timeout_secs=5 * 60, capture_output=False, **kwargs):
        """Run any ADB command.

        ``command`` and ``kwargs`` are the same as `subprocess.check_output`,
        except that ``shell``, ``stdout`` and ``stderr`` are not allowed.

        Raises `AdbError` if the command fails.<commit_msg>AdbDevice: Try to connect when constructed (if using TCP/IP)<commit_after># -*- coding: utf-8 -*-

"""Python module to control Android phones via `ADB`_ from Stb-tester scripts.

Copyright © 2017 Stb-tester.com Ltd.
License: LGPL v2.1 or (at your option) any later version (see
https://github.com/stb-tester/stb-tester/blob/master/LICENSE for details).

Usage::

    from stbt.android import AdbDevice
    adb = AdbDevice()
    adb.tap(x=100, y=50)

For feedback (video from the Android device-under-test) you can use:

* Stb-tester's standard HDMI video-capture if the device-under-test is an
  Android set-top box.
* HDMI video-capture from a tablet or phone with an MHL adapter.
* A camera pointed at the phone's screen with an `Stb-tester CAMERA`_ device.
* Screenshots captured over USB via ADB.

For more details on the benefits and trade-offs of each method, see
<https://stb-tester.com/blog/2017/02/21/testing-video-playback-on-mobile-devices>.

Note that you can instead use Stb-tester features such as image-matching
in your existing Selenium/WebDriver/Appium tests. See
<https://stb-tester.com/blog/2016/09/20/add-visual-verification-to-your-selenium-tests-with-stb-tester>.

.. _ADB: https://developer.android.com/studio/command-line/adb.html
.. _Stb-tester CAMERA: https://stb-tester.com/videos/the-stb-tester-camera-for-tvs-and-mobile-devices

"""

from __future__ import division

import ConfigParser
import logging
import re
import subprocess
import sys
import time
from collections import namedtuple

import cv2
import numpy
from enum import Enum

import stbt


class CoordinateSystem(Enum):
    # pylint:disable=pointless-string-statement

    """How to translate coordinates from the video-frames processed by your
    test script, to the coordinates expected by ADB for tap & swipe events.

    When you tell ADB to send a tap or swipe event you must give it x & y
    coordinates. The coordinate system matches the orientation of the device.
    We'll call these the physical coordinates. For example my phone's display
    is Full HD (1080 pixels x 1920 pixels):

    ===================  ======  ======  ======================================
    Logical orientation  x       y       (0, 0) is
    ===================  ======  ======  ======================================
    Portrait             0-1080  0-1920  top-left
    Landscape            0-1920  0-1080  top-left (i.e. the top-right corner if
                                         the phone is physically in portrait)
    ===================  ======  ======  ======================================

    Note that an app can force the device to think it's in portrait orientation
    even if you're physically holding the device in landscape orientation. We
    call this the "logical orientation". Similarly, an app can force the device
    into logical landscape orientation even if you have switched off auto-rotate
    in the device's settings menu.

    However the video-frames that you analyse in your test scripts may not
    match the physical resolution of the device. For example if you're using a
    camera pointed at the device's screen, the resolution of your screenshots
    (even after geometric correction by the `Stb-tester CAMERA`_) will be the
    resolution of the camera, not of the device under test.

    You can give `AdbDevice.tap` and `AdbDevice.swipe` the coordinates from
    your video-frame (for example, you can pass in ``stbt.match(...).region``)
    and this setting will ensure that the coordinates are converted to
    physical coordinates in the appropriate way before passing them on to ADB.
    """

    """Frames are captured via ADB screenshot.

    Frames will be in the same orientation & resolution as the physical device.
    """
    ADB_NATIVE = 0

    """Frames are captured via ADB screenshot and then scaled to 720p.

    Frames will be in the same orientation as the physical device, but scaled.
    """
    ADB_720P = 1

    """
    Frames are captured via HDMI (using an MHL cable) at 720p.

    Frames will always be in landscape orientation. If the device is in
    portrait orientation, you'll get black bars to the left & right. If the
    device is in landscape orientation, the frame will match what you see on
    the device (assuming the device's physical aspect ratio matches the aspect
    ratio of HDMI).
    """
    HDMI_720P = 2

    """Frames are captured from an `Stb-tester CAMERA`_ pointing at the
    device's screen.

    The camera & device must both be physically in landscape orientation.

    Frames will always be in landscape orientation; if the device is in logical
    portrait orientation the image will be rotated 90° anti-clockwise.
    """
    CAMERA_720P = 3


class AdbDevice(object):
    """Control an Android device using `ADB`_.

    Default values for each parameter can be specified in your "stbt.conf"
    config file under the "[android]" section.

    :param string adb_server:
        The ADB server (that is, the PC connected to the Android device).
        Defaults to localhost.
    :param string adb_device:
        Serial number of the Android device connected to ADB server PC (you can
        get this by running ``adb devices -l``). If not specified, there must be
        only one Android device connected. If ``tcpip=True`` this must be the
        Android device's IP address.
    :param string adb_binary:
        The path to the ADB client executable. Defaults to "adb".
    :param bool tcpip:
        The ADB server communicates with the Android device via TCP/IP, not
        USB. This requires that you have enabled TCP/IP ADB access on the
        device. Defaults to False.
    :param CoordinateSystem coordinate_system:
        How to convert the coordinates you give to `AdbDevice.tap` and
        `AdbDevice.swipe` into the coordinates required by ADB. See
        `CoordinateSystem` for details. Defaults to ``CAMERA_720P`` on the
        `Stb-tester CAMERA`_, or ``ADB_NATIVE`` elsewhere.
    """

    def __init__(self, adb_server=None, adb_device=None, adb_binary=None,
                 tcpip=False, coordinate_system=None, _config=None):

        if _config is None:
            _config = stbt._stbt.config._config_init()  # pylint:disable=protected-access

        self.adb_server = adb_server or _get_config(_config, "android",
                                                    "adb_server", None)
        self._adb_device = adb_device or _get_config(_config, "android",
                                                     "adb_device", None)
        self.adb_binary = adb_binary or _get_config(_config, "android",
                                                    "adb_binary", "adb")
        if tcpip is None:
            try:
                tcpip = _config.getboolean("android", "tcpip")
            except ConfigParser.Error:
                tcpip = False
        self.tcpip = tcpip

        if coordinate_system is None:
            name = _get_config("android", "coordinate_system", "ADB_NATIVE")
            if name not in CoordinateSystem.__members__:  # pylint:disable=no-member
                raise ValueError(
                    "Invalid value '%s' for android.coordinate_system in "
                    "config file. Valid values are %s."
                    % (name, ", ".join("'%s'" % k for k in
                                       CoordinateSystem.__members__)))  # pylint:disable=no-member
            coordinate_system = CoordinateSystem[name]
        self.coordinate_system = coordinate_system

        if self.tcpip:
            self._connect(timeout_secs=60)

    @property
    def adb_device(self):
        if self.tcpip and self._adb_device and ":" not in self._adb_device:
            return self._adb_device + ":5555"
        else:
            return self._adb_device

    def adb(self, command, timeout_secs=5 * 60, capture_output=False, **kwargs):
        """Run any ADB command.

        ``command`` and ``kwargs`` are the same as `subprocess.check_output`,
        except that ``shell``, ``stdout`` and ``stderr`` are not allowed.

        Raises `AdbError` if the command fails.
{'fraction_non_alphanumeric': 0.098636926889715, 'fraction_numerical': 0.01127633209417596, 'mean_word_length': 2.6750910746812386, 'pattern_counts': {'":': 4, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 10, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 18, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '298340', 'n_tokens_mistral': 4638, 'n_tokens_neox': 4274, 'n_words': 1746}