Example #1
0
def notify(
    title: str,
    subtitle: str,
    info_text: str,
    delay: int = 0,
    sound: bool = False,
    user_info: Dict[str, str] = None,
) -> None:
    """ Python method to show a desktop notification on Mountain Lion. Where:
        title: Title of notification
        subtitle: Subtitle of notification
        info_text: Informative text of notification
        delay: Delay (in seconds) before showing the notification
        sound: Play the default notification sound
        userInfo: a dictionary that can be used to handle clicks in your
                  app's applicationDidFinishLaunching:aNotification method
    """
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(title)
    notification.setSubtitle_(subtitle)
    notification.setInformativeText_(info_text)
    user_info = user_info or {}
    user_info = NSMutableDictionary.alloc().init().setDictionary_(user_info)
    notification.setUserInfo_(user_info)
    if sound:
        notification.setSoundName_("NSUserNotificationDefaultSoundName")
    center = NSUserNotificationCenter.defaultUserNotificationCenter()
    if center is not None:
        center.deliverNotification_(notification)
Example #2
0
def notification(title, subtitle, message, data=None, sound=True):
    """Send a notification to Notification Center (OS X 10.8+). If running on a version of macOS that does not
    support notifications, a ``RuntimeError`` will be raised. Apple says,

        "The userInfo content must be of reasonable serialized size (less than 1k) or an exception will be thrown."

    So don't do that!

    :param title: text in a larger font.
    :param subtitle: text in a smaller font below the `title`.
    :param message: text representing the body of the notification below the `subtitle`.
    :param data: will be passed to the application's "notification center" (see :func:`rumps.notifications`) when this
                 notification is clicked.
    :param sound: whether the notification should make a noise when it arrives.
    """
    if not _NOTIFICATIONS:
        raise RuntimeError('OS X 10.8+ is required to send notifications')
    if data is not None and not isinstance(data, Mapping):
        raise TypeError('notification data must be a mapping')
    _require_string_or_none(title, subtitle, message)
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(title)
    notification.setSubtitle_(subtitle)
    notification.setInformativeText_(message)
    infoDict = NSMutableDictionary.alloc().init()
    infoDict.setDictionary_({} if data is None else data)
    notification.setUserInfo_(infoDict)
    if sound:
        notification.setSoundName_("NSUserNotificationDefaultSoundName")
    notification.setDeliveryDate_(NSDate.dateWithTimeInterval_sinceDate_(0, NSDate.date()))
    notification_center = _default_user_notification_center()
    notification_center.scheduleNotification_(notification)
Example #3
0
    def export(self, canvasname, file, format='pdf', force=False, is_checksum=False):
        """
        Exports one canvas named {@code canvasname}
        """

        format = format.lower()

        chksum = None
        if os.path.isfile(file) and not force:
            existing_chksum = checksum(file) if format != 'pdf' \
                                             else checksum_pdf(file)
            new_chksum = self.compute_canvas_checksum(canvasname)

            if existing_chksum == new_chksum and existing_chksum != None:
                logging.debug('No exporting - canvas %s not changed' % 
                              canvasname)
                return False
            else:
                chksum = new_chksum

        elif format == 'pdf':
            chksum = self.compute_canvas_checksum(canvasname)

        win = self.og.windows.first()

        canvas = [c for c in self.doc.canvases() if c.name() == canvasname]
        if len(canvas) == 1:
            canvas = canvas[0]
        else:
            logging.warn('Canvas %s does not exist in %s' % 
                         (canvasname, self.schemafile))
            return False

        self.og.set(win.canvas, to=canvas)

        export_format = OmniGraffleSchema.EXPORT_FORMATS[format]
        if (export_format == None):
            self.doc.save(in_=file)
        else:
            self.doc.save(as_=export_format, in_=file)

        if not is_checksum and self.options.verbose:
            print "%s" % file

        logging.debug("Exported `%s' into `%s' as %s" % (canvasname, file, format))

        if format == 'pdf':
            # save the checksum
            url = NSURL.fileURLWithPath_(file)
            pdfdoc = PDFKit.PDFDocument.alloc().initWithURL_(url)
            attrs = NSMutableDictionary.alloc().initWithDictionary_(pdfdoc.documentAttributes())

            attrs[PDFKit.PDFDocumentSubjectAttribute] = \
                '%s%s' % (OmniGraffleSchema.PDF_CHECKSUM_ATTRIBUTE, chksum)

            pdfdoc.setDocumentAttributes_(attrs)
            pdfdoc.writeToFile_(file)

        return True
Example #4
0
 def SetPathValue(self, path, value):
   """Sets the path value for a given path."""
   base = os.path.basename(path)
   if not base:
     raise SysconfigError('Updating %s not permitted.' % path)
   tree = os.path.dirname(path)
   settings = SCPreferencesPathGetValue(self.session, tree)
   if not settings:
     settings = NSMutableDictionary.alloc().init()
   settings[base] = value
   SCPreferencesPathSetValue(self.session, tree, settings)
Example #5
0
 def SetPathValue(self, path, value):
     """Sets the path value for a given path."""
     base = os.path.basename(path)
     if not base:
         raise SysconfigError('Updating %s not permitted.' % path)
     tree = os.path.dirname(path)
     settings = SCPreferencesPathGetValue(self.session, tree)
     if not settings:
         settings = NSMutableDictionary.alloc().init()
     settings[base] = value
     SCPreferencesPathSetValue(self.session, tree, settings)
Example #6
0
 def _ns_update_attributed_title(self):
     if self._color:
         ns_button = self._ns_view
         ns_attrs = NSMutableDictionary.alloc().init()
         ns_attrs[NSFontAttributeName] = ns_button.font()
         ns_attrs[NSForegroundColorAttributeName] = self._color._ns_color
         ns_parstyle = NSMutableParagraphStyle.alloc().init()
         ns_parstyle.setAlignment_(ns_button.alignment())
         ns_attrs[NSParagraphStyleAttributeName] = ns_parstyle
         ns_attstr = NSAttributedString.alloc().initWithString_attributes_(
             ns_button.title(), ns_attrs)
         ns_button.setAttributedTitle_(ns_attstr)
Example #7
0
def modify_ncprefs_plist(key, value, item_index):
    # make an immutuble copy of the 'apps' array in ncprefs
    new_apps_array = NSMutableArray.alloc().initWithArray_(pl)
    # make a mutable copy of the target dict within the array
    new_dict = NSMutableDictionary.alloc().initWithDictionary_copyItems_(
        new_apps_array[item_index], True)
    # set the value
    new_dict[key] = value
    # replace the mutible dict within the mutable array
    new_apps_array.replaceObjectAtIndex_withObject_(item_index, new_dict)
    # replace the array in the ncprefs plist
    CFPreferencesSetAppValue("apps", new_apps_array, NCPREFS_PLIST)
 def _ns_update_attributed_title(self):
     if self._color:
         ns_button = self._ns_view
         ns_attrs = NSMutableDictionary.alloc().init()
         ns_attrs[NSFontAttributeName] = ns_button.font()
         ns_attrs[NSForegroundColorAttributeName] = self._color._ns_color
         ns_parstyle = NSMutableParagraphStyle.alloc().init()
         ns_parstyle.setAlignment_(ns_button.alignment())
         ns_attrs[NSParagraphStyleAttributeName] = ns_parstyle
         ns_attstr = NSAttributedString.alloc().initWithString_attributes_(
             ns_button.title(), ns_attrs)
         ns_button.setAttributedTitle_(ns_attstr)
Example #9
0
def SetPlistKey(plist, key, value):
  """Sets the value for a given key in a plist.

  Args:
    plist: plist to operate on
    key: key to change
    value: value to set
  Returns:
    boolean: success
  Raises:
    MissingImportsError: if NSMutableDictionary is missing
  """
  if NSMutableDictionary:
    mach_info = NSMutableDictionary.dictionaryWithContentsOfFile_(plist)
    if not mach_info:
      mach_info = NSMutableDictionary.alloc().init()
    mach_info[key] = value
    return mach_info.writeToFile_atomically_(plist, True)
  else:
    raise MissingImportsError('NSMutableDictionary not imported successfully.')
Example #10
0
def SetPlistKey(plist, key, value):
  """Sets the value for a given key in a plist.

  Args:
    plist: plist to operate on
    key: key to change
    value: value to set
  Returns:
    boolean: success
  Raises:
    MissingImportsError: if NSMutableDictionary is missing
  """
  if NSMutableDictionary:
    mach_info = NSMutableDictionary.dictionaryWithContentsOfFile_(plist)
    if not mach_info:
      mach_info = NSMutableDictionary.alloc().init()
    mach_info[key] = value
    return mach_info.writeToFile_atomically_(plist, True)
  else:
    raise MissingImportsError('NSMutableDictionary not imported successfully.')
Example #11
0
def main():

    if len(sys.argv) != 4:
        print("Usage: {} in.pdf out.pdf \"creator string\"".format(__file__))
        sys.exit(1)

    in_PDF = os.path.expanduser(sys.argv[1])
    out_PDF = os.path.expanduser(sys.argv[2])
    creator_str = sys.argv[3]

    fn = os.path.expanduser(in_PDF)
    url = NSURL.fileURLWithPath_(fn)
    pdfdoc = PDFDocument.alloc().initWithURL_(url)

    attrs = (NSMutableDictionary.alloc()
             .initWithDictionary_(pdfdoc.documentAttributes()))
    attrs[PDFDocumentCreatorAttribute] = creator_str

    pdfdoc.setDocumentAttributes_(attrs)
    pdfdoc.writeToFile_(out_PDF)
Example #12
0
    def AxisMapperMain(self, sender=None):
        try:
            # clear macro window log:
            Glyphs.clearLog()

            # update settings to the latest user input:
            if not self.SavePreferences():
                print("Note: 'Axis Mapper' could not write preferences.")

            thisFont = Glyphs.font  # frontmost font
            if thisFont is None:
                Message(
                    title="No Font Open",
                    message=
                    "The script requires a font. Open a font and run the script again.",
                    OKButton=None)
            else:
                print("Axis Mapper Report for %s" % thisFont.familyName)
                if thisFont.filepath:
                    print(thisFont.filepath)
                else:
                    print("āš ļø The font file has not been saved yet.")
                print()

                minValue = float(
                    Glyphs.defaults["com.mekkablue.AxisMapper.minValue"])
                maxValue = float(
                    Glyphs.defaults["com.mekkablue.AxisMapper.maxValue"])
                mappingRecipe = Glyphs.defaults[
                    "com.mekkablue.AxisMapper.mappingRecipe"]
                axisTag = Glyphs.defaults[
                    "com.mekkablue.AxisMapper.axisPicker"]

                print("šŸ”  Building Mapping for: %s" % axisTag)

                axisMapping = NSMutableDictionary.alloc().init()

                # axis extremes must be there:
                nativeLow, nativeHigh = extremeMasterValuesNative(
                    thisFont, axisTag=axisTag)
                for masterExtreme in (nativeLow, nativeHigh):
                    axisMapping.addObject_forKey_(masterExtreme, masterExtreme)
                print("āœ… Added axis extremes to mapping: %iā†’%i, %iā†’%i" %
                      (nativeLow, nativeLow, nativeHigh, nativeHigh))

                # process line
                for line in mappingRecipe.splitlines():
                    if "#" in line:
                        line = line[:line.find("#")]
                    if "->" in line:
                        line = line.strip()
                        userValue, targetValue = [
                            float(v.strip()) for v in line.split("->")
                        ]
                        userCoeff = coefficient(userValue, minValue, maxValue)
                        targetCoeff = coefficient(targetValue, minValue,
                                                  maxValue)
                        nativeUserValue = valueForCoefficient(
                            userCoeff, nativeLow, nativeHigh)
                        nativeTargetValue = valueForCoefficient(
                            targetCoeff, nativeLow, nativeHigh)
                        axisMapping.addObject_forKey_(nativeTargetValue,
                                                      nativeUserValue)
                        print("āœ… Translating %iā†’%i to %iā†’%i" %
                              (userValue, targetValue, nativeUserValue,
                               nativeTargetValue))

                parameterName = "Axis Mappings"
                mappings = Font.customParameters[parameterName]
                if not mappings:
                    print("šŸ™Œ Adding new %s parameter" % parameterName)
                    mappings = NSMutableDictionary.alloc(
                    ).initWithObject_forKey_(axisMapping, "wght")
                    mappings.addObject_forKey_(axisMapping, axisTag)
                else:
                    print("šŸ§© Inserting %s mapping into existing %s parameter" %
                          (axisTag, parameterName))
                    mappings.setObject_forKey_(axisMapping, axisTag)
                thisFont.customParameters[parameterName] = mappings

            # Final report:
            Glyphs.showNotification(
                "ā€˜%sā€™ mapping for %s" % (axisTag, thisFont.familyName),
                "Inserted ā€˜%sā€™ mapping with %i entries. Details in Macro Window"
                % (axisTag, len(axisMapping.allKeys())),
            )
            print("\nDone.")

        except Exception as e:
            # brings macro window to front and reports error:
            Glyphs.showMacroWindow()
            print("Axis Mapper Error: %s" % e)
            import traceback
            print(traceback.format_exc())
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
__doc__ = """
Inserts (or resets) a default Axis Mappings parameter for all style values currently present in the font. Ignores style values outside the designspace bounds defined by the masters.
"""

from Foundation import NSMutableDictionary
from axisMethods import *

if Glyphs.versionNumber < 3.0:
    Message(title="Glyphs Version Error",
            message="This script requires Glyphs 3.0 or later.",
            OKButton=None)
    # return

mappings = NSMutableDictionary.alloc().init()
font = Glyphs.font
for axis in font.axes:
    axisTag = axis.axisTag
    minAxisPos, maxAxisPos = extremeMasterValuesNative(font, axisTag=axisTag)

    # add axis extremes:
    axisMapping = NSMutableDictionary.alloc().init()
    for masterExtreme in nativeMasterExtremes:
        axisMapping.addObject_forKey_(masterExtreme, masterExtreme)

    # add style positions
    for style in font.instances:
        styleValue = styleValueForAxisTag(style, axisTag)
        if minAxisPos < styleValue < maxAxisPos:
            axisMapping.addObject_forKey_(styleValue, styleValue)
Example #14
0
def export_one(schema, filename, canvasname, format='pdf', force=False):
    def _checksum(filepath):
        assert os.path.isfile(filepath), '%s is not a file' % filepath

        c = hashlib.md5()
        with open(filepath, 'rb') as f:
            for chunk in iter(lambda: f.read(128), ''):
                c.update(chunk)

        return c.hexdigest()

    def _checksum_pdf(filepath):
        assert os.path.isfile(filepath), '%s is not a file' % filepath

        url = NSURL.fileURLWithPath_(filepath)
        pdfdoc = PDFKit.PDFDocument.alloc().initWithURL_(url)

        assert pdfdoc != None

        chsum = None
        attrs = pdfdoc.documentAttributes()
        if PDFKit.PDFDocumentSubjectAttribute in attrs:
            chksum = pdfdoc.documentAttributes()[
                PDFKit.PDFDocumentSubjectAttribute]
        else:
            return None

        if not chksum.startswith(OmniGraffleSchema.PDF_CHECKSUM_ATTRIBUTE):
            return None
        else:
            return chksum[len(OmniGraffleSchema.PDF_CHECKSUM_ATTRIBUTE):]

    def _compute_canvas_checksum(canvasname):
        tmpfile = tempfile.mkstemp(suffix='.png')[1]
        os.unlink(tmpfile)

        export_one(schema, tmpfile, canvasname, 'png')

        try:
            chksum = _checksum(tmpfile)
            return chksum
        finally:
            os.unlink(tmpfile)

    # checksum
    chksum = None
    if os.path.isfile(filename) and not force:
        existing_chksum = _checksum(filename) if format != 'pdf' \
                                              else _checksum_pdf(filename)

        new_chksum = _compute_canvas_checksum(canvasname)

        if existing_chksum == new_chksum and existing_chksum != None:
            logging.debug(
                'Not exporting `%s` into `%s` as `%s` - canvas has not been changed'
                % (canvasname, filename, format))
            return False
        else:
            chksum = new_chksum

    elif format == 'pdf':
        chksum = _compute_canvas_checksum(canvasname)

    try:
        schema.export(canvasname, filename, format=format)
    except RuntimeError as e:
        print >> sys.stderr, e.message
        return False

    # update checksum
    if format == 'pdf':
        # save the checksum
        url = NSURL.fileURLWithPath_(filename)
        pdfdoc = PDFKit.PDFDocument.alloc().initWithURL_(url)
        attrs = NSMutableDictionary.alloc().initWithDictionary_(
            pdfdoc.documentAttributes())

        attrs[PDFKit.PDFDocumentSubjectAttribute] = \
            '%s%s' % (OmniGraffleSchema.PDF_CHECKSUM_ATTRIBUTE, chksum)

        pdfdoc.setDocumentAttributes_(attrs)
        pdfdoc.writeToFile_(filename)

    return True
def export_one(schema, filename, canvasname, format='pdf', force=False):
    def _checksum(filepath):
        assert os.path.isfile(filepath), '%s is not a file' % filepath

        c = hashlib.md5()
        with open(filepath, 'rb') as f:
            for chunk in iter(lambda: f.read(128), ''):
                c.update(chunk)

        return c.hexdigest()

    def _checksum_pdf(filepath):
        assert os.path.isfile(filepath), '%s is not a file' % filepath

        url = NSURL.fileURLWithPath_(filepath)
        pdfdoc = PDFKit.PDFDocument.alloc().initWithURL_(url)

        assert pdfdoc != None

        chsum = None
        attrs = pdfdoc.documentAttributes()
        if PDFKit.PDFDocumentSubjectAttribute in attrs:
            chksum = pdfdoc.documentAttributes()[PDFKit.PDFDocumentSubjectAttribute]
        else:
            return None

        if not chksum.startswith(OmniGraffleSchema.PDF_CHECKSUM_ATTRIBUTE):
            return None
        else:
            return chksum[len(OmniGraffleSchema.PDF_CHECKSUM_ATTRIBUTE):]

    def _compute_canvas_checksum(canvasname):
        tmpfile = tempfile.mkstemp(suffix='.png')[1]
        os.unlink(tmpfile)

        export_one(schema, tmpfile, canvasname, 'png')

        try:
            chksum = _checksum(tmpfile)
            return chksum
        finally:
            os.unlink(tmpfile)

    # checksum
    chksum = None
    if os.path.isfile(filename) and not force:
        existing_chksum = _checksum(filename) if format != 'pdf' \
            else _checksum_pdf(filename)

        new_chksum = _compute_canvas_checksum(canvasname)

        if existing_chksum == new_chksum and existing_chksum != None:
            logging.debug(
                'Not exporting `%s` into `%s` as `%s` - canvas has not been changed' % (canvasname, filename, format))
            return False
        else:
            chksum = new_chksum

    elif format == 'pdf':
        chksum = _compute_canvas_checksum(canvasname)

    try:
        schema.export(canvasname, filename, format=format)
    except RuntimeError as e:
        print >> sys.stderr, e.message
        return False

    # update checksum
    if format == 'pdf':
        # save the checksum
        url = NSURL.fileURLWithPath_(filename)
        pdfdoc = PDFKit.PDFDocument.alloc().initWithURL_(url)
        attrs = NSMutableDictionary.alloc().initWithDictionary_(pdfdoc.documentAttributes())

        attrs[PDFKit.PDFDocumentSubjectAttribute] = \
            '%s%s' % (OmniGraffleSchema.PDF_CHECKSUM_ATTRIBUTE, chksum)

        pdfdoc.setDocumentAttributes_(attrs)
        pdfdoc.writeToFile_(filename)

    return True
    def export(self, canvasname, filename, format='pdf', force=False):
        """
        Exports one canvas named {@code canvasname}
        """

        # canvas name
        if not canvasname or len(canvasname) == 0:
            raise Exception('canvasname is missing')
        logging.debug('Exporting canvas: %s ' % canvasname)

        # format
        if not format or len(format) == 0:
            format = 'pdf'
        else:
            format = format.lower()
        if format not in OmniGraffleSchema.EXPORT_FORMATS:
            raise Exception('Unknown format: %s' % format)
        logging.debug('Exporting into format: %s ' % format)

        filename = os.path.abspath(filename)

        # suffix
        if filename[filename.rfind('.')+1:].lower() != format:
            filename = '%s.%s' % (filename, format)
        logging.debug('Exporting into: %s ' % filename)

        # checksum
        chksum = None
        if os.path.isfile(filename) and not force:
            existing_chksum = checksum(filename) if format != 'pdf' \
                                             else checksum_pdf(filename)
            new_chksum = self.compute_canvas_checksum(canvasname)

            if existing_chksum == new_chksum and existing_chksum != None:
                logging.debug('No exporting - canvas %s not changed' %
                              canvasname)
                return False
            else:
                chksum = new_chksum

        elif format == 'pdf':
            chksum = self.compute_canvas_checksum(canvasname)

        if self._export_internal(canvasname, filename, format):
            if self.verbose:
                print "%s" % filename
        else:
            print >> sys.stderr, 'Failed to export canvas: %s to %s' % \
                                       (canvasname, filename)

        # update checksum
        if format == 'pdf':
            # save the checksum
            url = NSURL.fileURLWithPath_(filename)
            pdfdoc = PDFKit.PDFDocument.alloc().initWithURL_(url)
            attrs = NSMutableDictionary.alloc().initWithDictionary_(
                        pdfdoc.documentAttributes())

            attrs[PDFKit.PDFDocumentSubjectAttribute] = \
                '%s%s' % (OmniGraffleSchema.PDF_CHECKSUM_ATTRIBUTE, chksum)

            pdfdoc.setDocumentAttributes_(attrs)
            pdfdoc.writeToFile_(filename)

        return True
	def __init__(self):
		self.id              = "com.apple.sidebarlists"
		self.favoriteservers = NSMutableDictionary.alloc().initWithDictionary_copyItems_(CoreFoundation.CFPreferencesCopyAppValue("favoriteservers", self.id), True)
		self.items           = NSMutableArray.alloc().initWithArray_(self.favoriteservers["CustomListItems"] if self.favoriteservers.get("CustomListItems") else list())
		self.labels          = [item["Name"] for item in self.items]
Example #18
0
import plistlib
import CoreFoundation
from Foundation import NSDate, NSMutableArray, NSMutableDictionary

# read the current ManagedPlugInPolicies
policy = CoreFoundation.CFPreferencesCopyAppValue("ManagedPlugInPolicies",
                                                  "com.apple.Safari")

if policy:
    # policy is an immutable dict, so we have to make a mutable copy
    my_policy = NSMutableDictionary.alloc().initWithDictionary_copyItems_(
        policy, True)
else:
    # create an empty dict
    my_policy = {}

if 'com.oracle.java.JavaAppletPlugin' in my_policy:
    # make a mutable copy of the dict
    current_dict = my_policy['com.oracle.java.JavaAppletPlugin']
    my_policy['com.oracle.java.JavaAppletPlugin'] = NSMutableDictionary.alloc(
    ).initWithDictionary_copyItems_(current_dict, True)
else:
    # create an empty dict
    my_policy['com.oracle.java.JavaAppletPlugin'] = {}

if 'PlugInHostnamePolicies' in my_policy['com.oracle.java.JavaAppletPlugin']:
    # make a mutable copy of the array
    current_array = my_policy['com.oracle.java.JavaAppletPlugin'][
        'PlugInHostnamePolicies']
    my_policy['com.oracle.java.JavaAppletPlugin'][
        'PlugInHostnamePolicies'] = NSMutableArray.alloc().initWithArray_(