Esempio n. 1
0
 def __init__(self):
     if alsaaudio:
         self.mixer = alsaaudio.Mixer(control='PCM')
     elif osax:
         self.mixer = osax.OSAX()
     else:
         print "Unable to control volume"
Esempio n. 2
0
 def applicationDidFinishLaunching_(self, sender):
     for m in [appscriptsupport, osaxfinder, dictionaryexporter]:
         m.init()
     self.standardAdditions = osax.OSAX()
     aemreceive.installeventhandler(
         handle_get, 'coregetd',
         ('----', 'ref', aemreceive.kae.typeObjectSpecifier))
Esempio n. 3
0
 def test_6(self):
     sa = osax.OSAX(
         'Standardadditions',
         aemapp=aem.Application("/System/Library/CoreServices/Finder.app/"))
     self.assertEqual(65, sa.ASCII_number('A'))
     self.assertEqual(
         mactypes.Alias("/System/Library/CoreServices/Finder.app/"),
         sa.path_to(None))
Esempio n. 4
0
 def test_5(self):
     pid = int(
         commands.getoutput("top -l1 | grep Finder | awk '{ print $1 }'"))
     sa = osax.OSAX('Standardadditions', pid=pid)
     self.assertEqual(
         mactypes.Alias("/System/Library/CoreServices/Finder.app/"),
         sa.path_to(None))
     self.assertEqual(65, sa.ASCII_number('A'))
Esempio n. 5
0
 def test_4(self):
     sa = osax.OSAX('Standardadditions', id='com.apple.finder')
     sa.activate()
     self.assertEqual({
         osax.k.button_returned: '',
         osax.k.gave_up: True
     }, sa.display_dialog('test', giving_up_after=1))
     self.assertEqual(
         mactypes.Alias("/System/Library/CoreServices/Finder.app/"),
         sa.path_to(None))
Esempio n. 6
0
 def __init__(self):
   self.loop = None
   self.logs = []
   self.recent = ''
   self.last = ''
   self.stdin = None
   self.waiting = set()
   self.volume_handler = osax.OSAX()
   self.process = None
   self.last_event_time = time.time()
Esempio n. 7
0
    def __init__(self):
        print "Volume started."

        if alsaaudio:
            self.mixer = alsaaudio.Mixer(control='PCM')
        elif osax:
            self.mixer = osax.OSAX()
        else:
            print "Unable to control volume"

        # JSONCommandService handles all of the low-level TCP connection stuff.
        super(Volume, self).__init__()
Esempio n. 8
0
 def test_5(self):
     pid = int(
         commands.getoutput("top -l1 | grep Finder | awk '{ print $1 }'"))
     sa = osax.OSAX('Standardadditions', pid=pid)
     self.assertEqual(
         mactypes.Alias("/System/Library/CoreServices/Finder.app/"),
         sa.path_to(None))
     sa.activate()
     self.assertEqual({
         osax.k.button_returned: '',
         osax.k.gave_up: True
     }, sa.display_dialog('test', giving_up_after=1))
Esempio n. 9
0
    def test_1(self):
        sa = osax.OSAX('Standardadditions')

        self.assertEqual(65, sa.ASCII_number('A'))

        self.assertEqual(mactypes.Alias("/Applications/"),
                         sa.path_to(osax.k.applications_folder))

        self.assertEqual(
            mactypes.Alias("/Library/Scripts/"),
            sa.path_to(osax.k.scripts_folder, from_=osax.k.local_domain))

        self.assertRaises(AttributeError, getattr, sa, 'non_existent_command')
Esempio n. 10
0
 def test_5(self):
     p = subprocess.Popen("top -l1 | grep Finder | awk '{ print $1 }'",
                          shell=True,
                          stdout=subprocess.PIPE)
     p.wait()
     pid = int(p.stdout.read())
     sa = osax.OSAX('Standardadditions', pid=pid)
     self.assertEqual(
         mactypes.Alias("/System/Library/CoreServices/Finder.app/"),
         sa.path_to(None))
     sa.activate()
     self.assertEqual({
         osax.k.button_returned: '',
         osax.k.gave_up: True
     }, sa.display_dialog('test', giving_up_after=1))
Esempio n. 11
0
File: Basic.py Progetto: imclab/asw
 def __getattr__(self, name):
     """
     Routes attribute requests through app dictionary by default, then System Events dictionary, then Standard Additions
     Name collisions are not resolved, use internal objects explicity to resolve them
     """
     verbose = False
     try:
         return App_Dictionary_Only.__getattr__(self, name)
     except AttributeError:
         try:
             if not self.system_events:
                 self.system_events = appscript.app(
                     'System Events').processes[self.app_name]
             g = getattr(self.system_events, name)
             if g:
                 if self.auto_activate:
                     self.activate(
                     )  # GUI scripting requires app to be activated
                 verbose and print(
                     "Returning self.system_events.{0}".format(name))
                 return g
         except AttributeError:
             if not self.standard_additions:
                 self.standard_additions = osax.OSAX(
                     name=self.app_name
                 )  # launches an osax, very slow, egro we make it dynamic ... and last
             try:
                 g = getattr(self.standard_additions, name)
                 if g:
                     if self.auto_activate:
                         self.activate()
                     verbose and print(
                         "Returning self.standard_additions.{0}".format(
                             name))
                     return g
             except AttributeError:
                 raise AttributeError("Unknown attribute!")
Esempio n. 12
0
 def __init__(self):
     self.sa = osax.OSAX()
     self.original_volume = list(
         self.sa.get_volume_settings().iteritems())[2][1]
Esempio n. 13
0
File: Basic.py Progetto: imclab/asw
class AppleScriptWrapper(App_SystEvents_StndAdditions):
    def __init__(self, name):
        App_SystEvents_StndAdditions.__init__(self, name)
        self._wait = 0.25

    def get_list_of_documents(self):
        return self.application.documents[:]

    def file_is_open(self, title):
        return title in [f.name() for f in self.get_list_of_documents()]


#    def close(self):
#        print self.current_document()
#        self.application.close(self.current_document())

    def close_without_saving(self):
        self.application.close(self.current_document(), saving=self.k('no'))

    def save(self):
        self.application.save(self.current_document())

    def save_as(self, path):
        self.application.save(self.current_document(), in_=path)

    def save_as_pdf(self, path=None):
        """
        Automates the print as pdf function in print dialog box, takes current document and saves it as its name + 'pdf'
        Saves it first for new documents when path is not specified
        """
        if not path:
            path = self.current_document().path()
            if not path:
                self.save()
                path = self.current_document().path()
            path, name = os.path.split(path)
            name, ext = os.path.splitext(name)
            path = path + name + ext
        try:
            self.application.save(self.current_document(), in_=path, as_='pdf')
        except:
            self.application.save(self.current_document(), in_=path + '.pdf')

    def save_gui(self, path, confirm=True):
        """ 
        Saves current document using gui scripting, if confirm is false then lets user check and hit return 
        
        """
        self.command_down('s')
        path = self.resolve_name_collision(path)
        self.navigate_using_goto(path, confirm=confirm)

    def navigate_using_goto(self, path, confirm=False):
        self.command_down('G')
        self.keystroke(path)
        self.keystroke_return()
        if confirm:
            self.keystroke_return()

    def wait(self, times_longer=1):
        time.sleep(self._wait * times_longer)

    def menu_item_present(self, menu, item):
        """ Returns menu item object if exists, false if not, can be used to see if present """
        ref = self.menu_bars[1].menu_bar_items[menu].menus[menu].menu_items[
            item]
        try:
            ref = ref()
        except:
            ref = False
        return ref

    def submenu_item_present(self, menu, submenu, item):
        ref = self.menu_bars[1].menu_bar_items[menu].menus[menu].menu_items[
            submenu].menus[submenu].menu_items[item]
        try:
            ref = ref()
        except:
            ref = False
        return ref

    def menu_item_enabled(self, menu, item):
        ref = self.menu_item_present(menu, item)
        if not ref: return False
        return ref.enabled()

    def submenu_item_enabled(self, menu, submenu, item):
        ref = self.submenu_item_present(menu, submenu, item)
        if not ref:
            raise Exception(
                "Passed invalid menu and item to menu_item_enabled")
        return ref.enabled()

    def click_menu_item(self, menu, item):
        ref = self.menu_item_present(menu, item)
        if ref:
            self.wait()
            ref.click()
            self.wait()

    def click_submenu_item(self, menu, submenu, item):
        ref = self.submenu_item_present(menu, submenu, item)
        if ref:
            self.wait()
            ref.click()
            self.wait()

    def toggle_menu_item(self, menu, item):
        ref = self.menu_item_present(menu, item)
        if ref:
            self.wait()
            ref.click()
            self.wait()

    def toggle_submenu_item(self, menu, submenu, item):
        ref = self.submenu_item_present(menu, submenu, item)
        if ref:
            self.wait()
            ref.click()
            self.wait()

    def menu_item_checked(self, menu, item):
        return self.menu_item_present(menu, item).selected()

    def keystroke_convenience(self, key, times=1, **keysdown):
        """ convenience method for all keystrokes with **keysdown passed as named options """
        self.wait()
        options = self.convert_options_to_list(keysdown)
        for i in range(0, times):
            if options:
                self.keystroke(key, using=options)
            else:
                self.keystroke(key)
        self.wait()

    def check_menu_item(self, menu, item, boolean):
        self.menu_item_present(menu, item).selected.set(boolean)

    def keystroke_return(self):
        self.keystroke_convenience('\r')

    def command_down(self, char):
        """ convenenience method for keystroke with command down """
        self.keystroke_convenience(char, command_down=True)

    def paste(self):
        self.command_down('v')

    def option_down(self, char):
        self.keystroke_convenience(char, option_down=True)

    def command_option_down(self, char):
        """ convenenience method for keystroke with command down """
        self.keystroke_convenience(char, command_down=True, option_down=True)

    def keystroke_idiom(self, idiom, **keysdown):
        options = self.convert_options_to_list(keysdown)
        possible_idioms = {
            'escape': 53,
            'down arrow': 125,
            'up arrow': 126,
            'left arrow': 123,
            'right arrow': 124
        }
        try:
            this_idiom = possible_idioms[idiom.lower()]
        except:
            return  # no error
        self.wait()
        if options:
            self.key_code(this_idiom, using=options)
        else:
            self.key_code(this_idiom)

    def display_alert_convenience(self,
                                  prompt,
                                  message,
                                  as_="warning",
                                  **kwargs):
        possible_alert_kinds = {'warning': self.k('warning')}
        self.display_alert(prompt,
                           message=message,
                           as_=possible_alert_kinds[as_])

    def display_dialog_convenience(self,
                                   prompt,
                                   default_answer=None,
                                   buttons=['Cancel', 'OK'],
                                   default_button=0,
                                   timeout=10000,
                                   cancel_button_name="Cancel",
                                   **kwargs):
        """ returns text if default_answer or the text of the button if not, throws exception if Cancel is pushed """
        def pushed_cancel_button(_response):
            if _response is None: return True
            return buttons.index(_response[self.k(
                'button_returned')]) == 0 and buttons[0] == cancel_button_name

        if not default_button:
            default_button = len(buttons)
        if default_answer is None:
            response = self.display_dialog(prompt,
                                           buttons=buttons,
                                           default_button=default_button,
                                           timeout=timeout,
                                           **kwargs)
            if pushed_cancel_button(response):
                raise User_Canceled
            return response[self.k('button_returned')]
        else:
            response = self.display_dialog(prompt,
                                           default_answer=default_answer,
                                           buttons=buttons,
                                           default_button=default_button,
                                           timeout=timeout,
                                           **kwargs)
            if pushed_cancel_button(response):
                raise User_Canceled
            return response[self.k('text_returned')]

    def get_int_input(self,
                      prompt,
                      default_answer="1",
                      buttons=['Cancel', 'OK'],
                      default_button=2,
                      minimum=0,
                      maximum=10000):
        num = minimum - 1
        while not (minimum <= num <= maximum):
            reply = self.get_input(prompt,
                                   default_answer=default_answer,
                                   buttons=buttons,
                                   default_button=default_button)
            try:
                num = int(reply)
            except:
                num = minimum - 1
        return num

    def get_input_loop(self):
        """ forget what this was for exactly """
        raise NotImplemented

    def get_input_loop_i(self):
        raise NotImplemented

    def choose_from_list_convenience(self,
                                     prompt,
                                     llist,
                                     timeout=10000,
                                     **kwargs):
        """ returns string or list of string of item chosen in llist, raises UserCanceled if Cancel is pressed """
        response = self.choose_from_list(llist,
                                         with_prompt=prompt,
                                         timeout=timeout,
                                         **kwargs)
        if response is None:
            raise Exception("Got strange return from choose_from_list")
        if response is False:
            raise User_Canceled
        if len(response) == 1:
            return response[0]
        else:
            return response

    def choose_file_convenience(self, prompt, file_types, **kwargs):
        """ will take list of dot notated file types """
        if not isinstance(file_types, list): file_types = [file_types]
        file_types = [f.lstrip('.') for f in file_types]
        return self.choose_file(with_prompt=prompt,
                                of_type=file_types,
                                **kwargs)

    def tell_app_to_do(self, app, do, *args, **kwargs):
        """
        Depreciated, should use module-level method instead
        """
        f = getattr(appscript.app(app), do)
        f(*args, **kwargs)

    def ensure_gui_scripting_activated(self, app_name="This application"):
        """
        Interact with user in a way that ensures GUI scripting is possible
        """
        def enabled():
            return app("System Events").UI_elements_enabled()

        if not enabled:
            from .SystemPreferences import SystemPreferences
            sys = SystemPreferences()
            sys.activate()
            sys.universal_acess_panel()
            sys.get_input(
                "{0} utilizes the built-in Graphic User Interface Scripting ararchitecture of Mac OS X which is currently disabled\n\nYou can activate GUI Scripting by selecting the checkbox \"Enable access for assistive devices\" in the Universal Access preference pane, which will be visible once you click OK."
                .format(app_name),
                buttons=["OK"])
            sys.activate()
            with self.context_no_activate():
                self.display_alert_convenience(
                    "Click OK when you have enabled access for assistive devices in the Universal Access preference pane",
                    "")
        enabled = app("System Events").UI_elements_enabled()
        if not enabled:
            self.display_alert_convenience(
                "you haven't enabled access for assistive devices.",
                "{} is quitting now.".format(app_name))
            raise GUIScriptingNotEnabled

    def start_timer(self):
        self._start_time = time.time()

    def stop_timer(self):
        self._start_time = 0

    def elapsed_time_since_start(self):
        """ returns in minutes the period of time taken """
        if not self._start_time: return 0
        return (time.time() - self._start_time) / 60

    def do_shell_script_convenience(self,
                                    command,
                                    authenticate=False,
                                    async=False,
                                    **kwargs):
        """ authenticate and asyncs are possible """
        if authenticate:
            sa = osax.OSAX()  # new instance needed
            sa.activate()
            result = sa.do_shell_script(command,
                                        administrator_privileges=True,
                                        **kwargs)
            self.activate()
            return result
        else:
            import subprocess
            p = suprocess.Popen(command,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                **kwargs)
            if not async:
                return p.communicate()
            else:
                return p
Esempio n. 14
0
# -*- coding: utf-8 -*-
import numpy as np
import cv2
import osax

hand_cascade = cv2.CascadeClassifier('Hand.Cascade.1.xml')

cap = cv2.VideoCapture(0)
font = cv2.FONT_HERSHEY_SIMPLEX
xvals=[]
yvals=[]
currentx = -1
currenty = -1

sa = osax.OSAX()
sa.set_volume(0)
settings = sa.get_volume_settings()
keys = list(settings.keys())
currentvol = settings[keys[2]]
waiting = 0
volume_increment = 7/100.

while 1:
    waiting += 1
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    hands = hand_cascade.detectMultiScale(gray, 1.3, 5)

    if len(hands) > 0:
        for (x,y,w,h) in hands:
            cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
Esempio n. 15
0
import time
import osax
import lightblue

wtf = osax.OSAX()


def set_low(LOW_VOL=1):  # lowest = 0
    wtf.set_volume(LOW_VOL)


def set_high(HIGH_VOL=4):  # highest = 8
    wtf.set_volume(HIGH_VOL)


def get_device_names(timeout=5):
    return [
        name
        for (address, name, number) in lightblue.finddevices(length=timeout)
    ]


def device_exists(name=u"Nexus S"):
    return name in get_device_names()


def main(poll_time=1):
    action_map = {True: set_low, False: set_high}
    # we don't know what the initial level is
    # so set on first iteration
    current_state = "NOT_TRUE_AND_NOT_FALSE"
Esempio n. 16
0
 def test_4(self):
     sa = osax.OSAX('Standardadditions', id='com.apple.finder')
     self.assertEqual(65, sa.ASCII_number('A'))
     self.assertEqual(
         mactypes.Alias("/System/Library/CoreServices/Finder.app/"),
         sa.path_to(None))