<commit_before>""" Abstracts the capturing and interfacing of applications """
import os
import re
import time
import pyperclip
import platform
import subprocess

from .RegionMatching import Region
from .Settings import Debug
from .PlatformManagerWindows import PlatformManagerWindows
from .Exceptions import FindFailed

if platform.system() == "Windows":
    PlatformManager = PlatformManagerWindows() # No other input managers built yet
else:
    # Avoid throwing an error if it's just being imported for documentation purposes
    if not os.environ.get('READTHEDOCS') == 'True':
        raise NotImplementedError("Lackey is currently only compatible with Windows.")

# Python 3 compatibility
try:
    basestring
except NameError:
    basestring = str

class App(object):
    """ Allows apps to be selected by title, PID, or by starting an
    application directly. Can address individual windows tied to an
    app.

    For more information, see `Sikuli's App documentation<http://sikulix-2014.readthedocs.io/en/latest/appclass.html#App>`_.
    """
    def __init__(self, identifier=None):
        self._pid = None
        self._search = identifier
        self._title = ""
        self._exec = ""
        self._params = ""
        self._process = None
        self._devnull = None
        self._defaultScanRate = 0.1
        self.proc = None

        # Replace class methods with instance methods
        self.focus = self._focus_instance
        self.close = self._close_instance
        self.open = self._open_instance

        # Process `identifier`
        if isinstance(identifier, int):
            # `identifier` is a PID
            Debug.log(3, "Creating App by PID ({})".format(identifier))
            self._pid = identifier
        elif isinstance(identifier, basestring):
            # `identifier` is either part of a window title
            # or a command line to execute. If it starts with a "+",
            # launch it immediately. Otherwise, store it until open() is called.
            Debug.log(3, "Creating App by string ({})".format(identifier))
            launchNow = False
            if identifier.startswith("+"):
                # Should launch immediately - strip the `+` sign and continue
                launchNow = True
                identifier = identifier[1:]
            # Check if `identifier` is an executable commmand
            # Possible formats:
            # Case 1: notepad.exe C:\sample.txt
            # Case 2: "C:\Program Files\someprogram.exe" -flag

            # Extract hypothetical executable name
            if identifier.startswith('"'):
                executable = identifier[1:].split('"')[0]
                params = identifier[len(executable)+2:].split(" ") if len(identifier) > len(executable) + 2 else []
            else:
                executable = identifier.split(" ")[0]
                params = identifier[len(executable)+1:].split(" ") if len(identifier) > len(executable) + 1 else []

            # Check if hypothetical executable exists
            if self._which(executable) is not None:
                # Found the referenced executable
                self._exec = executable
                self._params = params
                # If the command was keyed to execute immediately, do so.
                if launchNow:
                    self.open()
            else:
                # No executable found - treat as a title instead. Try to capture window.
                self._title = identifier
                self.open
        else:
            self._pid = -1 # Unrecognized identifier, setting to empty app

        self._pid = self.getPID() # Confirm PID is an active process (sets to -1 otherwise)

    def _which(self, program):
        """ Private method to check if an executable exists

        Shamelessly stolen from http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python
        """
        def is_exe(fpath):
            return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

        fpath, fname = os.path.split(program)
        if fpath:
            if is_exe(program):
                return program
        else:
            for path in os.environ["PATH"].split(os.pathsep):
                path = path.strip('"')
                exe_file = os.path.join(path, program)
                if is_exe(exe_file):
                    return exe_file
        return None<commit_msg>Fix App init if selected by title<commit_after>""" Abstracts the capturing and interfacing of applications """
import os
import re
import time
import pyperclip
import platform
import subprocess

from .RegionMatching import Region
from .Settings import Debug
from .PlatformManagerWindows import PlatformManagerWindows
from .Exceptions import FindFailed

if platform.system() == "Windows":
    PlatformManager = PlatformManagerWindows() # No other input managers built yet
else:
    # Avoid throwing an error if it's just being imported for documentation purposes
    if not os.environ.get('READTHEDOCS') == 'True':
        raise NotImplementedError("Lackey is currently only compatible with Windows.")

# Python 3 compatibility
try:
    basestring
except NameError:
    basestring = str

class App(object):
    """ Allows apps to be selected by title, PID, or by starting an
    application directly. Can address individual windows tied to an
    app.

    For more information, see `Sikuli's App documentation<http://sikulix-2014.readthedocs.io/en/latest/appclass.html#App>`_.
    """
    def __init__(self, identifier=None):
        self._pid = None
        self._search = identifier
        self._title = ""
        self._exec = ""
        self._params = ""
        self._process = None
        self._devnull = None
        self._defaultScanRate = 0.1
        self.proc = None

        # Replace class methods with instance methods
        self.focus = self._focus_instance
        self.close = self._close_instance
        self.open = self._open_instance

        # Process `identifier`
        if isinstance(identifier, int):
            # `identifier` is a PID
            Debug.log(3, "Creating App by PID ({})".format(identifier))
            self._pid = identifier
        elif isinstance(identifier, basestring):
            # `identifier` is either part of a window title
            # or a command line to execute. If it starts with a "+",
            # launch it immediately. Otherwise, store it until open() is called.
            Debug.log(3, "Creating App by string ({})".format(identifier))
            launchNow = False
            if identifier.startswith("+"):
                # Should launch immediately - strip the `+` sign and continue
                launchNow = True
                identifier = identifier[1:]
            # Check if `identifier` is an executable commmand
            # Possible formats:
            # Case 1: notepad.exe C:\sample.txt
            # Case 2: "C:\Program Files\someprogram.exe" -flag

            # Extract hypothetical executable name
            if identifier.startswith('"'):
                executable = identifier[1:].split('"')[0]
                params = identifier[len(executable)+2:].split(" ") if len(identifier) > len(executable) + 2 else []
            else:
                executable = identifier.split(" ")[0]
                params = identifier[len(executable)+1:].split(" ") if len(identifier) > len(executable) + 1 else []

            # Check if hypothetical executable exists
            if self._which(executable) is not None:
                # Found the referenced executable
                self._exec = executable
                self._params = params
                # If the command was keyed to execute immediately, do so.
                if launchNow:
                    self.open()
            else:
                # No executable found - treat as a title instead. Try to capture window.
                self._title = identifier
                self.open()
        else:
            self._pid = -1 # Unrecognized identifier, setting to empty app

        self._pid = self.getPID() # Confirm PID is an active process (sets to -1 otherwise)

    def _which(self, program):
        """ Private method to check if an executable exists

        Shamelessly stolen from http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python
        """
        def is_exe(fpath):
            return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

        fpath, fname = os.path.split(program)
        if fpath:
            if is_exe(program):
                return program
        else:
            for path in os.environ["PATH"].split(os.pathsep):
                path = path.strip('"')
                exe_file = os.path.join(path, program)
                if is_exe(exe_file):
                    return exe_file
        return None
{'fraction_non_alphanumeric': 0.08940697148030784, 'fraction_numerical': 0.0061113626075147125, 'mean_word_length': 2.0673377299548767, 'pattern_counts': {'":': 2, '<': 5, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '173885', 'n_tokens_mistral': 2348, 'n_tokens_neox': 2195, 'n_words': 749}