Example #1
0
            def _pyobjc_notify(message, title=None, subtitle=None, appIcon=None, contentImage=None, open_URL=None, delay=0, sound=False):

                swizzle(objc.lookUpClass('NSBundle'),
                        b'bundleIdentifier',
                        swizzled_bundleIdentifier)
                notification = NSUserNotification.alloc().init()
                notification.setInformativeText_(message)
                if title:
                    notification.setTitle_(title)
                if subtitle:
                    notification.setSubtitle_(subtitle)
                if appIcon:
                    url = NSURL.alloc().initWithString_(appIcon)
                    image = NSImage.alloc().initWithContentsOfURL_(url)
                    notification.set_identityImage_(image)
                if contentImage:
                    url = NSURL.alloc().initWithString_(contentImage)
                    image = NSImage.alloc().initWithContentsOfURL_(url)
                    notification.setContentImage_(image)

                if sound:
                    notification.setSoundName_(
                        "NSUserNotificationDefaultSoundName")
                notification.setDeliveryDate_(
                    NSDate.dateWithTimeInterval_sinceDate_(delay, NSDate.date()))
                NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(
                    notification)
Example #2
0
            def _pyobjc_notify(message,
                               title=None,
                               subtitle=None,
                               appIcon=None,
                               contentImage=None,
                               open_URL=None,
                               delay=0,
                               sound=False):

                swizzle(objc.lookUpClass('NSBundle'), b'bundleIdentifier',
                        swizzled_bundleIdentifier)
                notification = NSUserNotification.alloc().init()
                notification.setInformativeText_(message)
                if title:
                    notification.setTitle_(title)
                if subtitle:
                    notification.setSubtitle_(subtitle)
                if appIcon:
                    url = NSURL.alloc().initWithString_(appIcon)
                    image = NSImage.alloc().initWithContentsOfURL_(url)
                    notification.set_identityImage_(image)
                if contentImage:
                    url = NSURL.alloc().initWithString_(contentImage)
                    image = NSImage.alloc().initWithContentsOfURL_(url)
                    notification.setContentImage_(image)

                if sound:
                    notification.setSoundName_(
                        "NSUserNotificationDefaultSoundName")
                notification.setDeliveryDate_(
                    NSDate.dateWithTimeInterval_sinceDate_(
                        delay, NSDate.date()))
                NSUserNotificationCenter.defaultUserNotificationCenter(
                ).scheduleNotification_(notification)
Example #3
0
 def alertShowHelp_(self, alert):
     TRACE('Help button clicked on boot error dialog')
     help_link = alert.helpAnchor()
     if help_link is not None:
         url = NSURL.alloc().initWithString_(help_link)
         NSWorkspace.sharedWorkspace().openURL_(url)
     return YES
Example #4
0
def _set_urls(array):
    urls = []
    if array is not None:
        for url in array:
            urls.append(NSURL.alloc().initWithString(url))

    general_pasteboard().URLs = urls
Example #5
0
def set_url(url: str):
    """
    Copy the given URL to the pasteboard.

    :param url: The string to copy as an URL.
    """

    check(url, "url", [str, None])

    general_pasteboard().URL = NSURL.alloc().initWithString(url)
Example #6
0
def create_favitem(url=None, name=None):
    if name is None:
        # Make the display name the same as the URL by default
        name = url
    props = {
        NSString.stringWithString_('com.apple.LSSharedFileList.OverrideIcon.OSType'):
        NSString.stringWithString_(u'srvr')
    }
    props = NSDictionary.alloc().initWithDictionary_(props)
    return SFLListItem.alloc().initWithName_URL_properties_(
        name,
        NSURL.alloc().initWithString_(url), props)
Example #7
0
def set_url(url: Union[str, List[str]]):
    """
    Copies the given URL to the pasteboard.

    :param url: A string or a list of strings.
    """

    check(url, "url", [str, None])

    if isinstance(url, list):
        _set_urls(url)
    else:
        general_pasteboard().URL = NSURL.alloc().initWithString(url)
Example #8
0
def set_urls(array: List[str]):
    """
    Copy the given URLs to the pasteboard.

    :param array: A list of strings to copy as URLs.
    """

    check(array, "array", [list, None])

    urls = []
    if array is not None:
        for url in array:
            urls.append(NSURL.alloc().initWithString(url))

    general_pasteboard().URLs = urls
Example #9
0
def apply_cifilter_with_name(filter_name, orientation, in_path, out_path, dry_run=False):
    
    print "-- in: ", in_path
    print "-- out:", out_path
    
    assert in_path
    assert out_path
    
    assert filter_name in ["CIPhotoEffectTonal", "CIPhotoEffectMono", "CIPhotoEffectInstant", "CIPhotoEffectTransfer",
                           "CIPhotoEffectProcess", "CIPhotoEffectChrome", "CIPhotoEffectNoir", "CIPhotoEffectFade",
                           "CIPhotoEffect3DDramatic", "CIPhotoEffect3DVivid", "CIPhotoEffect3DDramaticCool", "CIPhotoEffect3DNoir"]
                     
    url = NSURL.alloc().initFileURLWithPath_(in_path)
    ci_image = CIImage.imageWithContentsOfURL_(url)
    assert ci_image
    
    in_creation_timestamp = os.path.getmtime(in_path)
    print time.ctime(in_creation_timestamp)
    
    if orientation != None and orientation != 1:
        print "-- orientation:", orientation
        ci_image = ci_image.imageByApplyingOrientation_(orientation)
        
    ci_filter = CIFilter.filterWithName_(filter_name)
    assert ci_filter
    
    ci_filter.setValue_forKey_(ci_image, "inputImage")
    ci_filter.setDefaults()
    
    ci_image_result = ci_filter.outputImage()
    assert ci_image_result
    
    bitmap_rep = NSBitmapImageRep.alloc().initWithCIImage_(ci_image_result)
    assert bitmap_rep
    
    properties = { "NSImageCompressionFactor" : 0.9 }
    data = bitmap_rep.representationUsingType_properties_(3, properties) # 3 for JPEG
    
    if dry_run:
        print "-- dryrun, don't write", out_path
        return
    
    assert data.writeToFile_atomically_(out_path, True)
    
    os.utime(out_path, (time.time(), in_creation_timestamp))
Example #10
0
 def _check_for_access(self):
     '''Check for accessibility permission'''
     # Because unsigned bundle will fail to call
     # AXIsProcessTrustedWithOptions with a segment falt, we're
     # not currently stepping into this function.
     return
     self.log('Begin checking for accessibility')
     core_services = objc.loadBundle(
         'CoreServices',
         globals(),
         bundle_identifier='com.apple.ApplicationServices'
     )
     objc.loadBundleFunctions(
         core_services,
         globals(),
         [('AXIsProcessTrustedWithOptions', b'Z@')]
     )
     objc.loadBundleFunctions(
         core_services,
         globals(),
         [('kAXTrustedCheckOptionPrompt', b'@')]
     )
     self.log('Bundle com.apple.ApplicationServices loaded')
     try:
         if not AXIsProcessTrustedWithOptions(  # noqa
             {kAXTrustedCheckOptionPrompt: False}  # noqa
         ):
             self.log('Requesting access, Opening syspref window')
             NSWorkspace.sharedWorkspace().openURL_(
                 NSURL.alloc().initWithString_(
                     'x-apple.systempreferences:'
                     'com.apple.preference.security'
                     '?Privacy_Accessibility'
                 )
             )
     except:
         # Unsigned bundle will fail to call AXIsProcessTrustedWithOptions
         self.log((
             'Error detecting accessibility permission status, '
             'KeyCounter might not work'
         ))
     self.log('Access already granted')
Example #11
0
 def _check_for_access(self):
     '''Check for accessibility permission'''
     # Because unsigned bundle will fail to call
     # AXIsProcessTrustedWithOptions with a segment falt, we're
     # not currently stepping into this function.
     return
     self.log('Begin checking for accessibility')
     core_services = objc.loadBundle(
         'CoreServices',
         globals(),
         bundle_identifier='com.apple.ApplicationServices'
     )
     objc.loadBundleFunctions(
         core_services,
         globals(),
         [('AXIsProcessTrustedWithOptions', b'Z@')]
     )
     objc.loadBundleFunctions(
         core_services,
         globals(),
         [('kAXTrustedCheckOptionPrompt', b'@')]
     )
     self.log('Bundle com.apple.ApplicationServices loaded')
     try:
         if not AXIsProcessTrustedWithOptions(  # noqa
             {kAXTrustedCheckOptionPrompt: False}  # noqa
         ):
             self.log('Requesting access, Opening syspref window')
             NSWorkspace.sharedWorkspace().openURL_(
                 NSURL.alloc().initWithString_(
                     'x-apple.systempreferences:'
                     'com.apple.preference.security'
                     '?Privacy_Accessibility'
                 )
             )
     except:
         # Unsigned bundle will fail to call AXIsProcessTrustedWithOptions
         self.log((
             'Error detecting accessibility permission status, '
             'KeyCounter might not work'
         ))
     self.log('Access already granted')
Example #12
0
    def setSecurityScopedBookmark(self, path):

        #=======================================================================
        #  Security Scoped Bookmark
        #=======================================================================
        try:
            dirURL = NSURL.alloc().initFileURLWithPath_(path)
                
            myData = dirURL.bookmarkDataWithOptions_includingResourceValuesForKeys_relativeToURL_error_(NSURLBookmarkCreationWithSecurityScope,
                                                                                                            None,
                                                                                                            None,
                                                                                                            None) 
            theBytes = myData[0].bytes().tobytes()
                
            self.bookmarks.append(theBytes)
        
        except Exception, e:
        
            print "Unable to create security-scoped-bookmarks"
            print str(e)
            print "------------------------------------------"
Example #13
0
# Some notes about using this script:
# - Configure the application path and bundle id below
# - This script needs to be run as the user you need to set the checkmark for
# - The setting will not take effect until they log out and log back in at least once

import os.path
from Foundation import NSHomeDirectory, CFPreferencesCopyMultiple, CFPreferencesSetMultiple, kCFPreferencesAnyUser, kCFPreferencesCurrentHost, NSMutableDictionary, NSURL, NSURLBookmarkCreationMinimalBookmark, NSMutableArray

# --- CHANGE THESE SETTINGS ---
lowres_app_path = u'/Applications/TextEdit.app'
lowres_app_id = u'com.apple.TextEdit'
# -----------------------------

# create the bookmark data
app_url = NSURL.alloc().initFileURLWithPath_(lowres_app_path)
bookmark, error = app_url.bookmarkDataWithOptions_includingResourceValuesForKeys_relativeToURL_error_(
    NSURLBookmarkCreationMinimalBookmark, [], None, None)

# check if the file exists already
ls_prefs = os.path.join(
    NSHomeDirectory(),
    u'Library/Preferences/com.apple.LaunchServices/com.apple.LaunchServices')
ls_prefs_plist = ls_prefs + u'.plist'

if os.path.isfile(ls_prefs_plist):
    # read it in
    current_prefs = CFPreferencesCopyMultiple(None, ls_prefs,
                                              kCFPreferencesAnyUser,
                                              kCFPreferencesCurrentHost)
else:
 def setContentFile_(self, path):
     self.finishedLoading = False
     request = NSURLRequest.alloc().initWithURL_(
         NSURL.alloc().initFileURLWithPath_(path))
     self.outputView.mainFrame().loadRequest_(request)
     assert self.outputView.preferences().isJavaScriptEnabled()
 def setContentFile_(self, path):
     self.finishedLoading = False
     request = NSURLRequest.alloc().initWithURL_(NSURL.alloc().initFileURLWithPath_(path))
     self.outputView.mainFrame().loadRequest_(request)
     assert self.outputView.preferences().isJavaScriptEnabled()
Example #16
0
    def speakToFile(self, mp3Path, speechGenerator, progressCallback,
                    labelCallback, checkStopFunction):
        '''
        Writes the speech output given by the speech generator as an MP3 file
        that will be saved to mp3Path.
        
        The speech generator should generate tuples of the following:
        ('speech', 'label')
        
        The progressCallback should be a function that takes an int from 0-100,
        100 being when it is done.
        
        The checkStopFunction returns a boolean value saying whether we need to
        stop creation, False being don't stop, and True being stop.
        '''

        self._tts.stopSpeaking()

        try:
            os.remove(temp_path('tmp.aiff'))
        except OSError:
            pass
        aiffPath = unicode(temp_path('tmp.aiff'))

        # Create a single string that will be sent to the TTS
        myString = ''
        labelCallback('Preparing speech...')
        for speech in speechGenerator:
            myString += speech[0] + '. '
            myString = myString.replace('..', '.')
            if checkStopFunction():
                break

        if not checkStopFunction() and len(myString) > 0:

            progressCallback(30)
            labelCallback('Speaking into AIFF...')

            # Create my URL object
            url = NSURL.alloc()
            url.initFileURLWithPath_(aiffPath)

            # Speak string into TTS
            success = self._tts.startSpeakingString_toURL_(myString, url)

            while self._tts.isSpeaking() and not checkStopFunction():
                progressCallback(30)
                time.sleep(0.05)

            progressCallback(60)

            # Convert to MP3
            if not checkStopFunction():

                labelCallback('Converting to MP3...')
                lameExe = '"' + program_path('src/lame_mac') + '"'

                lameCommand = lameExe + ' -h "' + aiffPath + '" "' + mp3Path + '"'
                ps = subprocess.Popen(lameCommand,
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE,
                                      shell=True)

                while ps.poll() == None:
                    if checkStopFunction():
                        ps.terminate()
                        break
                    out = ps.stderr.readline()
                    if re.search(r'\([0-9]+%\)', out) != None:
                        percent = int(
                            float(
                                re.search(r'\([0-9]+%\)', out).group(0)[1:-2])
                            * 0.3)
                        progressCallback(69 + percent)

            progressCallback(100)