def awakeFromNib(self):
        self.outputView.setShouldCloseWithWindow_(True)
        self.outputView.registerForDraggedTypes_(NSArray.arrayWithObject_(NSFilenamesPboardType))
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "webviewFinishedLoading:", WebViewProgressFinishedNotification, self.outputView)
        if self.inputText:
            self.inputText.registerForDraggedTypes_(NSArray.arrayWithObject_(NSFilenamesPboardType))
            self.inputText.setOwner(self)
            NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "textDidChange:", NSTextDidChangeNotification, self.inputText)

        self.messageQueue = []
Beispiel #2
0
    async def scanForPeripherals_(self, scan_options) -> List[CBPeripheral]:
        """
        Scan for peripheral devices
        scan_options = { service_uuids, timeout }
        """
        service_uuids = []
        if "service_uuids" in scan_options:
            service_uuids_str = scan_options["service_uuids"]
            service_uuids = NSArray.alloc().initWithArray_(
                list(map(string2uuid, service_uuids_str)))

        timeout = None
        if "timeout" in scan_options:
            timeout = scan_options["timeout"]

        self.central_manager.scanForPeripheralsWithServices_options_(
            service_uuids, None)

        if timeout is None or type(timeout) not in (int, float):
            return

        await asyncio.sleep(timeout)
        self.central_manager.stopScan()

        return []
 def tableView_writeRows_toPasteboard_(self, table, rows, pboard):
     index = rows[0]
     pboard.declareTypes_owner_(NSArray.arrayWithObject_("dragged-row"),
                                self)
     pboard.setString_forType_(NSString.stringWithString_(str(index)),
                               "dragged-row")
     return True
    async def scanForPeripherals_(self, scan_options) -> List[CBPeripheral]:
        """
        Scan for peripheral devices
        scan_options = { service_uuids, timeout }
        """
        # remove old
        self.devices = {}
        service_uuids = []
        if "service_uuids" in scan_options:
            service_uuids_str = scan_options["service_uuids"]
            service_uuids = NSArray.alloc().initWithArray_(
                list(map(string2uuid, service_uuids_str)))

        timeout = 0
        if "timeout" in scan_options:
            timeout = float(scan_options["timeout"])

        self.central_manager.scanForPeripheralsWithServices_options_(
            service_uuids, None)

        if timeout > 0:
            await asyncio.sleep(timeout)

        self.central_manager.stopScan()
        while self.central_manager.isScanning():
            await asyncio.sleep(0.1)

        return []
Beispiel #5
0
 def copy_(self, sender):
     if self.delegate is None:
         return
     pb = NSPasteboard.generalPasteboard()
     copy_text = format_identity_to_string(self.delegate.sessionController.remotePartyObject, check_contact=True, format='full')
     pb.declareTypes_owner_(NSArray.arrayWithObject_(NSStringPboardType), self)
     pb.setString_forType_(copy_text, NSStringPboardType)
    async def retrieveConnected_(self, scan_options) -> List[CBPeripheral]:
        self.devices = {}
        service_uuids = []
        if "service_uuids" in scan_options:
            service_uuids_str = scan_options["service_uuids"]
            service_uuids = NSArray.alloc().initWithArray_(
                list(map(string2uuid, service_uuids_str)))

        peripherals = self.central_manager.retrieveConnectedPeripheralsWithServices_(
            service_uuids)

        # Add all those peripherals:
        for peripheral in peripherals:
            uuid_string = peripheral.identifier().UUIDString()

            if uuid_string in self.devices:
                device = self.devices[uuid_string]
            else:
                address = uuid_string
                name = peripheral.name() or None
                details = peripheral
                device = BLEDeviceCoreBluetooth(address, name, details)
                self.devices[uuid_string] = device

            logger.debug("Connected device {}: {}".format(
                uuid_string, device.name))

        return []
Beispiel #7
0
    def browseFile_(self, sender):
        panel = NSOpenPanel.openPanel()
        panel.setTitle_(NSLocalizedString("Select a Picture", "Label"))

        if panel.runModalForTypes_(NSArray.arrayWithObjects_("png", "tiff", "jpeg", "jpg", "tif")) == NSOKButton:
            path = unicode(panel.filename())
            self.cropAndAddImage(path)
    def awakeFromNib(self):
        self.outputView.setShouldCloseWithWindow_(True)
        self.outputView.registerForDraggedTypes_(
            NSArray.arrayWithObject_(NSFilenamesPboardType))
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            self, "webviewFinishedLoading:",
            WebViewProgressFinishedNotification, self.outputView)
        if self.inputText:
            self.inputText.registerForDraggedTypes_(
                NSArray.arrayWithObject_(NSFilenamesPboardType))
            self.inputText.setOwner(self)
            NSNotificationCenter.defaultCenter(
            ).addObserver_selector_name_object_(self, "textDidChange:",
                                                NSTextDidChangeNotification,
                                                self.inputText)

        self.messageQueue = []
Beispiel #9
0
    def browseFile_(self, sender):
        panel = NSOpenPanel.openPanel()
        panel.setTitle_(NSLocalizedString("Select a Picture", "Label"))

        if panel.runModalForTypes_(
                NSArray.arrayWithObjects_("png", "tiff", "jpeg", "jpg",
                                          "tif")) == NSOKButton:
            path = str(panel.filename())
            self.cropAndAddImage(path)
 def awakeFromNib(self):
     NotificationCenter().add_observer(self, name="BlinkGroupsHaveChanged")
     self.addressTable.tableColumnWithIdentifier_(
         "0").dataCell().setPlaceholderString_(
             NSLocalizedString("Click to add a new address",
                               "Text placeholder"))
     self.addressTable.setDraggingSourceOperationMask_forLocal_(
         NSDragOperationGeneric, True)
     self.addressTable.registerForDraggedTypes_(
         NSArray.arrayWithObject_("dragged-row"))
 def copy_(self, sender):
     if self.delegate is None:
         return
     pb = NSPasteboard.generalPasteboard()
     copy_text = format_identity_to_string(
         self.delegate.sessionController.remoteIdentity,
         check_contact=True,
         format='full')
     pb.declareTypes_owner_(NSArray.arrayWithObject_(NSStringPboardType),
                            self)
     pb.setString_forType_(copy_text, NSStringPboardType)
    def start_scan(self, scan_options):
        # remove old
        self.devices = {}
        service_uuids = []
        if "service_uuids" in scan_options:
            service_uuids_str = scan_options["service_uuids"]
            service_uuids = NSArray.alloc().initWithArray_(
                list(map(string2uuid, service_uuids_str)))

        self.central_manager.scanForPeripheralsWithServices_options_(
            service_uuids, None)
 def copy_img(self, image_data, mime='image/png', clear_first=True):
     image = NSImage.alloc().initWithData_(image_data)
     array = NSArray.arrayWithObject_(image)
     pb = NSPasteboard.generalPasteboard()
     if clear_first:
         pb.clearContents()
     # end def
     if mime in self.FORMAT_CONVERTER:
         pb.declareTypes_owner_([self._f(mime)], None)
     # end def
     success = pb.writeObjects_(array)
     return success  # todo: throw
Beispiel #14
0
def purify(obj):
    # This code ensures that certain data types are very definitely the ObjC versions
    d = dir(obj)
    if '__reversed__' in d:
        # list / NSArray
        return NSArray.alloc().initWithArray_(obj)
    elif 'items' in d:
        # dictionary / NSDictionary
        return NSDictionary.alloc().initWithDictionary_(obj)
    elif 'strip' in d:
        # string / NSString
        return NSString.alloc().initWithString_(obj)
    # Unhandled
    return obj
    def init_sdl_window(self):
        if self.sdl_window:
            return
        if self.window is not None:
            return
        if self.streamController.stream is None:
            return
        if self.streamController.stream.video_windows is None:
            return
        if self.streamController.stream.video_windows.remote is None:
            return

        self.sdl_window = self.streamController.stream.video_windows.remote

        self.initial_size = self.streamController.stream.video_windows.remote.size
        self.aspect_ratio = float(self.initial_size[0]) / self.initial_size[1]
        self.sessionController.log_debug('Remote aspect ratio is %.2f' % self.aspect_ratio)

        self.initial_aspect_ratio = self.aspect_ratio

        found = False
        for ratio in self.valid_aspect_ratios:
            if ratio is None:
                continue
            diff = ratio - self.aspect_ratio
            if diff < 0:
                diff = diff * -1
            if self.aspect_ratio > 0.95 * ratio and self.aspect_ratio < 1.05 * ratio:
                found = True
                break

        if not found:
            self.valid_aspect_ratios.append(self.aspect_ratio)

        self.window = NSWindow(cobject=self.sdl_window.native_handle)
        self.window.setTitle_(self.title)
        self.window.setDelegate_(self)
        self.sessionController.log_debug('Init %s in %s' % (self.window, self))
        self.dif_y = self.window.frame().size.height - self.streamController.stream.video_windows.remote.size[1]
        #self.toogleAlwaysOnTop()
        self.updateTrackingAreas()

        frame = self.window.frame()
        self.sessionController.log_info('Remote video stream at %0.fx%0.f resolution' % (frame.size.width, frame.size.height-self.dif_y))
        frame.size.width = 640
        frame.size.height = frame.size.width / self.aspect_ratio
        frame.size.height += self.dif_y
        self.window.setFrame_display_(frame, True)
        self.window.center()
        self.window.registerForDraggedTypes_(NSArray.arrayWithObject_(NSFilenamesPboardType))
Beispiel #16
0
    def discovered_devices(self) -> List[BLEDevice]:
        found = []
        peripherals = self._manager.central_manager.retrievePeripheralsWithIdentifiers_(
            NSArray(self._identifiers.keys()),
        )

        for peripheral in peripherals:
            address = peripheral.identifier().UUIDString()
            name = peripheral.name() or "Unknown"
            details = peripheral
            rssi = self._manager.devices[address].rssi

            advertisementData = self._identifiers[peripheral.identifier()]
            manufacturer_binary_data = advertisementData.get(
                "kCBAdvDataManufacturerData"
            )
            manufacturer_data = {}
            if manufacturer_binary_data:
                manufacturer_id = int.from_bytes(
                    manufacturer_binary_data[0:2], byteorder="little"
                )
                manufacturer_value = bytes(manufacturer_binary_data[2:])
                manufacturer_data = {manufacturer_id: manufacturer_value}

            uuids = [
                cb_uuid_to_str(u)
                for u in advertisementData.get("kCBAdvDataServiceUUIDs", [])
            ]

            service_data = {}
            adv_service_data = advertisementData.get("kCBAdvDataServiceData", [])
            for u in adv_service_data:
                service_data[cb_uuid_to_str(u)] = bytes(adv_service_data[u])

            found.append(
                BLEDevice(
                    address,
                    name,
                    details,
                    rssi=rssi,
                    uuids=uuids,
                    manufacturer_data=manufacturer_data,
                    service_data=service_data,
                    delegate=self._manager.central_manager.delegate(),
                )
            )

        return found
 def buttonClicked_(self, sender):
     if sender.tag() == 20: # ch icon
         panel = NSOpenPanel.openPanel()
         panel.setTitle_(NSLocalizedString("Select Contact Icon", "Window title"))
         if panel.runModalForTypes_(NSArray.arrayWithObjects_("tiff", "png", "jpeg", "jpg")) == NSFileHandlingPanelOKButton:
             path = panel.filename()
             image = NSImage.alloc().initWithContentsOfFile_(path)
             self.photoImage.setImage_(image)
     elif sender.tag() == 21: # clear icon
         self.photoImage.setImage_(self.defaultPhotoImage)
     elif sender.tag() == 10:
         self.startDeallocTimer()
         NSApp.stopModalWithCode_(NSOKButton)
     else:
         self.startDeallocTimer()
         NSApp.stopModalWithCode_(NSCancelButton)
Beispiel #18
0
    def mouseDragged_(self, event):
        if self.delegate is None:
            return
        pos = event.locationInWindow()
        if abs(self.dragPos.x - pos.x) > 3 or abs(self.dragPos.y - pos.y) > 3:
            image = self.makeDragImage()

            pos.x -= image.size().width/2
            pos.y -= image.size().height/2
            pboard = NSPasteboard.pasteboardWithName_(NSDragPboard)
            pboard.declareTypes_owner_(NSArray.arrayWithObject_("x-blink-audio-session"), self)
            uri = format_identity_to_string(self.delegate.sessionController.remotePartyObject, check_contact=False, format='compact')
            pboard.setString_forType_(uri, "x-blink-audio-session")
            self.window().dragImage_at_offset_event_pasteboard_source_slideBack_(image,
                    pos, NSZeroPoint, event, pboard, self, False)
            self.draggedOut = False
 def buttonClicked_(self, sender):
     if sender.tag() == 20: # ch icon
         panel = NSOpenPanel.openPanel()
         panel.setTitle_(NSLocalizedString("Select Contact Icon", "Window title"))
         if panel.runModalForTypes_(NSArray.arrayWithObjects_("tiff", "png", "jpeg", "jpg")) == NSFileHandlingPanelOKButton:
             path = panel.filename()
             image = NSImage.alloc().initWithContentsOfFile_(path)
             self.photoImage.setImage_(image)
     elif sender.tag() == 21: # clear icon
         self.photoImage.setImage_(self.defaultPhotoImage)
     elif sender.tag() == 10:
         self.startDeallocTimer()
         NSApp.stopModalWithCode_(NSOKButton)
     else:
         self.startDeallocTimer()
         NSApp.stopModalWithCode_(NSCancelButton)
    def mouseDragged_(self, event):
        if self.delegate is None:
            return
        pos = event.locationInWindow()
        if abs(self.dragPos.x - pos.x) > 3 or abs(self.dragPos.y - pos.y) > 3:
            image = self.makeDragImage()

            pos.x -= image.size().width / 2
            pos.y -= image.size().height / 2
            pboard = NSPasteboard.pasteboardWithName_(NSDragPboard)
            pboard.declareTypes_owner_(
                NSArray.arrayWithObject_("x-blink-audio-session"), self)
            uri = format_identity_to_string(
                self.delegate.sessionController.remoteIdentity,
                check_contact=False,
                format='compact')
            pboard.setString_forType_(uri, "x-blink-audio-session")
            self.window(
            ).dragImage_at_offset_event_pasteboard_source_slideBack_(
                image, pos, NSZeroPoint, event, pboard, self, False)
            self.draggedOut = False
Beispiel #21
0
    async def start_scan(self, scan_options) -> None:
        # remove old
        self.devices = {}
        service_uuids = None
        if "service_uuids" in scan_options:
            service_uuids_str = scan_options["service_uuids"]
            service_uuids = NSArray.alloc().initWithArray_(
                list(map(CBUUID.UUIDWithString_, service_uuids_str)))

        self.central_manager.scanForPeripheralsWithServices_options_(
            service_uuids, None)

        # The `isScanning` property was added in macOS 10.13, so before that
        # just waiting some will have to do.
        if objc.macos_available(10, 13):
            event = asyncio.Event()
            self._did_start_scanning_event = event
            if not self.central_manager.isScanning():
                await event.wait()
        else:
            await asyncio.sleep(0.1)
def reorderUnicodes(thisGlyph):
    defaultUnicode = Glyphs.glyphInfoForName(thisGlyph.name).unicode
    oldUnicodes = thisGlyph.unicodes
    if oldUnicodes:
        oldUnicodes = list(oldUnicodes)
        if len(oldUnicodes) > 1:
            if defaultUnicode:
                orderedUnicodes = []
                try:
                    i = oldUnicodes.index(defaultUnicode)
                    try:
                        orderedUnicodes.append(oldUnicodes.pop(
                            i))  # add the default as the first one
                        orderedUnicodes.extend(oldUnicodes)  # add the rest
                        if orderedUnicodes != oldUnicodes:
                            print("---> %s: %s" %
                                  (thisGlyph.name, ", ".join(orderedUnicodes)))
                            unicodeSet = NSArray.alloc().initWithArray_(
                                orderedUnicodes)
                            thisGlyph.setUnicodesArray_(unicodeSet)
                    except Exception as e:
                        print(e)
                        print()
                        import traceback
                        print(traceback.format_exc())
                except:
                    print(
                        "- %s: No default (%s) among unicodes (%s); left unchanged."
                        % (thisGlyph.name, defaultUnicode,
                           ", ".join(oldUnicodes)))
            else:
                print(
                    "- %s: No unicode defined in Glyph Info; left unchanged (%s)"
                    % (thisGlyph.name,
                       ", ".join(oldUnicodes) if oldUnicodes else "-"))
        else:
            print("- %s: Only one unicode set (%s); left unchanged." %
                  (thisGlyph.name, oldUnicodes[0]))
    else:
        print("- %s: No unicodes set, nothing to reorder." % (thisGlyph.name))
Beispiel #23
0
    async def scanForPeripherals_(self, scan_options) -> List[CBPeripheral]:
        """
        Scan for peripheral devices
        scan_options = { service_uuids, timeout }
        """
        # remove old
        self.devices = {}
        service_uuids = []
        if "service_uuids" in scan_options:
            service_uuids_str = scan_options["service_uuids"]
            service_uuids = NSArray.alloc().initWithArray_(
                list(map(string2uuid, service_uuids_str))
            )

        timeout = 0
        if "timeout" in scan_options:
            timeout = float(scan_options["timeout"])

        self.central_manager.scanForPeripheralsWithServices_options_(
            service_uuids, None
        )

        if timeout > 0:
            await asyncio.sleep(timeout)

        self.central_manager.stopScan()

        # Wait a while to allow central manager to stop scanning.
        # The `isScanning` attribute is added in macOS 10.13, so before that
        # just waiting some will have to do. In 10.13+ I have never seen
        # bleak enter the while-loop, so this fix is most probably safe.
        if _IS_PRE_10_13:
            await asyncio.sleep(0.1)
        else:
            while self.central_manager.isScanning():
                await asyncio.sleep(0.1)

        return []
from common import getRootElement, findWebArea, elementToString, \
  getAttributeValue, getParameterizedAttributeValue, \
  findElemWithDOMIdentifier
from Foundation import NSDictionary, NSArray

root = findElemWithDOMIdentifier(getRootElement(name="Safari"), "image_1")
print(elementToString(root))
startMarker = getAttributeValue(root, "AXStartTextMarker")
endMarker = getAttributeValue(root, "AXEndTextMarker")
markers = NSArray.alloc().initWithObjects_(startMarker, endMarker)
r = getParameterizedAttributeValue(root,
                                   "AXTextMarkerRangeForUnorderedTextMarkers",
                                   markers)


def strFromRange(r):
    return getParameterizedAttributeValue(root, "AXStringForTextMarkerRange",
                                          r)


print(len(strFromRange(r)))

# nextMarker = startMarker
# index = 0
# while True:
#   nextMarker = getParameterizedAttributeValue(root, "AXNextTextMarkerForTextMarker", nextMarker)
#   leftWord = strFromRange(getParameterizedAttributeValue(root, "AXLeftWordTextMarkerRangeForTextMarker", nextMarker))
#   rightWord = strFromRange(getParameterizedAttributeValue(root, "AXRightWordTextMarkerRangeForTextMarker", nextMarker))
#   print("%d [%s] [%s] " % (index, leftWord, rightWord))
#   index += 1
#   if not nextMarker or nextMarker == endMarker:
    def testFunctions(self):
        v = CTParagraphStyleGetTypeID()
        self.assertIsInstance(v, (int, long))
        self.assertResultHasType(CTParagraphStyleGetValueForSpecifier,
                                 objc._C_BOOL)

        # Test below is not needed due to manaul wrapper:
        #self.assertResultIsCFRetained(CTParagraphStyleCreate)
        style = CTParagraphStyleCreate(None, 0)
        self.assertIsInstance(style, CTParagraphStyleRef)

        self.assertResultIsCFRetained(CTParagraphStyleCreateCopy)
        v = CTParagraphStyleCreateCopy(style)
        self.assertIsInstance(v, CTParagraphStyleRef)

        ok, v = CTParagraphStyleGetTabStops(style)
        self.assertTrue(ok)
        self.assertIsInstance(v, CFArrayRef)
        self.assertTrue(len(v))
        self.assertIsInstance(v[0], CTTextTabRef)

        ok, v = CTParagraphStyleGetValueForSpecifier(
            style, kCTParagraphStyleSpecifierAlignment, sizeof_CTTextAlignment,
            None)
        self.assertTrue(ok)
        self.assertIsInstance(v, bytes)
        self.assertEqual(len(v), sizeof_CTTextAlignment)

        ok, v = CTParagraphStyleGetValueForSpecifier(
            style, kCTParagraphStyleSpecifierFirstLineHeadIndent,
            sizeof_CGFloat, None)
        self.assertTrue(ok)
        self.assertIsInstance(v, bytes)
        self.assertEqual(len(v), sizeof_CGFloat)

        ok, v = CTParagraphStyleGetValueForSpecifier(
            style, kCTParagraphStyleSpecifierLineBreakMode,
            sizeof_CTLineBreakMode, None)
        self.assertTrue(ok)
        self.assertIsInstance(v, bytes)
        self.assertEqual(len(v), sizeof_CTLineBreakMode)

        ok, v = CTParagraphStyleGetValueForSpecifier(
            style, kCTParagraphStyleSpecifierBaseWritingDirection,
            sizeof_CTWritingDirection, None)
        self.assertTrue(ok)
        self.assertIsInstance(v, bytes)
        self.assertEqual(len(v), sizeof_CTWritingDirection)

        # And now the hard part: create a CTParagraphStyle with custom options
        if sys.maxint > 2**32:
            float_pack = "d"
        else:
            float_pack = "f"
        options = [
            CTParagraphStyleSetting(
                spec=kCTParagraphStyleSpecifierBaseWritingDirection,
                valueSize=sizeof_CTWritingDirection,
                value=chr(kCTParagraphStyleSpecifierTailIndent).encode(
                    'latin1')),
            CTParagraphStyleSetting(
                spec=kCTParagraphStyleSpecifierFirstLineHeadIndent,
                valueSize=sizeof_CGFloat,
                value=struct.pack(float_pack, 10.5)),
            CTParagraphStyleSetting(
                spec=kCTParagraphStyleSpecifierTabStops,
                valueSize=sizeof_id,
                value=NSArray.arrayWithArray_([
                    CTTextTabCreate(kCTLeftTextAlignment, 40.0, None),
                    CTTextTabCreate(kCTLeftTextAlignment, 80.0, None),
                ])),
        ]
        options.append(
            CTParagraphStyleSetting(
                spec=kCTParagraphStyleSpecifierBaseWritingDirection,
                valueSize=sizeof_CTWritingDirection,
                value=chr(kCTWritingDirectionRightToLeft)), )
        style = CTParagraphStyleCreate(options, len(options))
        self.assertIsInstance(style, CTParagraphStyleRef)

        ok, v = CTParagraphStyleGetTabStops(style)
        self.assertTrue(ok)
        self.assertIsInstance(v, CFArrayRef)
        self.assertEqual(len(v), 2)

        ok, v = CTParagraphStyleGetValueForSpecifier(
            style, kCTParagraphStyleSpecifierBaseWritingDirection,
            sizeof_CTWritingDirection, None)
        self.assertTrue(ok)
        self.assertIsInstance(v, str)
        self.assertEqual(v, chr(kCTWritingDirectionRightToLeft))

        ok, v = CTParagraphStyleGetValueForSpecifier(
            style, kCTParagraphStyleSpecifierFirstLineHeadIndent,
            sizeof_CGFloat, None)
        self.assertTrue(ok)
        self.assertIsInstance(v, str)
        self.assertEqual(v, struct.pack(float_pack, 10.5))
Beispiel #26
0
def update_user_account(user_data):
    """
    Updates the user account. When being executed on a booted volume, updates
    via the Open Directory API. When being executed on a targeted volume,
    updates via the user account Property List.
    """

    name = user_data["name"]

    if is_booted_volume():
        node = get_od_node()

        if not node:
            print "Unable to look up OpenDirectory node, aborting..."
            exit(1)

        record, error = node.recordWithRecordType_name_attributes_error_(
            kODRecordTypeUsers, name, None, None)

        if error:
            print error
            exit(1)

        for attribute, value in user_data.items():

            # jpegphoto and ShadowHashData are data blobs, not strings, so a
            # little conversion is required
            if attribute == "jpegphoto" or attribute == "ShadowHashData":
                data = NSData.dataWithBytes_length_(value, len(value))
                value = NSArray.alloc().initWithObjects_(data)

            success, error = record.setValue_forAttribute_error_(
                value, attribute, None)

            if error:
                print error
                exit(1)

            # we don't want to spew out the data blobs to stdout, so we just
            # replace it with something simple. this is purely for formatting
            # reasons
            if attribute == "jpegphoto" or attribute == "ShadowHashData":
                value = "DATA"

            print "User account '" + name + "' updated attribute " + \
                attribute + ": " + str(value)
    else:  # Property List logic
        path = get_target() + get_user_plist_path() + name + ".plist"
        dictionary = plistlib.readPlist(path)

        for attribute, value in user_data.items():

            # jpegphoto and ShadowHashData are data blobs, not strings, so a
            # little conversion is required
            if attribute == "jpegphoto" or attribute == "ShadowHashData":
                value = plistlib.Data(value)

            dictionary[attribute] = [value]

            # we don't want to spew out the data blobs to stdout, so we just
            # replace it with something simple. this is purely for formatting
            # reasons
            if attribute == "jpegphoto" or attribute == "ShadowHashData":
                value = "DATA"

            print "User account '" + name + "' updated attribute " + \
                attribute + ": " + str(value)

        plistlib.writePlist(dictionary, path)
 def awakeFromNib(self):
     self.participantsTable.registerForDraggedTypes_(NSArray.arrayWithObjects_("x-blink-sip-uri"))
 def awakeFromNib(self):
     self.registerForDraggedTypes_(
         NSArray.arrayWithObjects_("x-blink-audio-session",
                                   "x-blink-sip-uri",
                                   NSFilenamesPboardType))
Beispiel #29
0
 def awakeFromNib(self):
     self.registerForDraggedTypes_(NSArray.arrayWithObjects_("x-blink-audio-session", "x-blink-sip-uri", NSFilenamesPboardType))
 def awakeFromNib(self):
     self.participantsTable.registerForDraggedTypes_(NSArray.arrayWithObjects_("x-blink-sip-uri"))
Beispiel #31
0
 def doCBad_(self, aTimer):
     NSArray([1])[5]
 def tableView_writeRows_toPasteboard_(self, table, rows, pboard):
     index = rows[0]
     pboard.declareTypes_owner_(NSArray.arrayWithObject_("dragged-row"), self)
     pboard.setString_forType_(NSString.stringWithString_(str(index)), "dragged-row")
     return True
 def awakeFromNib(self):
     NotificationCenter().add_observer(self, name="BlinkGroupsHaveChanged")
     self.addressTable.tableColumnWithIdentifier_("0").dataCell().setPlaceholderString_(NSLocalizedString("Click to add a new address", "Text placeholder"))
     self.addressTable.setDraggingSourceOperationMask_forLocal_(NSDragOperationGeneric, True)
     self.addressTable.registerForDraggedTypes_(NSArray.arrayWithObject_("dragged-row"))
Beispiel #34
0
def getRange(m1, m2):
    markers = NSArray.alloc().initWithObjects_(m1, m2)
    return getParameterizedAttributeValue(
        root, "AXTextMarkerRangeForUnorderedTextMarkers", markers)
Beispiel #35
0
    except Exception as e:
        print("Error for path index %s, node index %i:\n%s" % (pi, ni, e))
        import traceback
        print(traceback.format_exc())
        return False


# determine current layer:
currentFont = Glyphs.font
currentLayer = currentFont.selectedLayers[0]
currentGlyph = currentLayer.parent

# find compatible layers in the same glyph:
layerIDs = []
for subrunArray in currentGlyph.layerGroups_masters_error_(
        NSArray(currentFont.instances), NSArray(currentFont.masters), None):
    subrun = tuple(subrunArray)
    if currentLayer.layerId in subrun:
        for ID in subrun:
            if ID != currentLayer.layerId:
                layerIDs.append(ID)

# if there are any compatible layers...
if not layerIDs:
    Message(
        title="Dekink Error",
        message=
        "Could not find any other layers in this glyph for this interpolation.",
        OKButton=None)
else:
    if not currentGlyph.mastersCompatible:
Beispiel #36
0
	for match in matches:
		if match["MatchType"] == "Match":
			count += 1
		elif match["MatchType"] == "MatchAny":
			count += len(match["Matches"])
		else:
			raise Exception("Invalid MatchType.")
	
	return count


# ---------------------------------------------------------------------------

if __name__ == "__main__":
	
	XPROTECTS = NSArray.arrayWithContentsOfFile_(os.path.join(sys.path[0], "XPlist.plist"))
	
	if not XPROTECTS:
		raise Exception("Invalid URLs property list file.")
	
	for xprotect in XPROTECTS:
		
		# print target
		print xprotect["name"]
		
		# print source
		# init meta and data
		if xprotect.has_key("url"):
			print xprotect["url"]
			meta, data = init_with_url(xprotect["url"])
		
Beispiel #37
0
def init_with_files(fmeta, fdata):
	meta = NSDictionary.dictionaryWithContentsOfFile_(fmeta)
	data = NSArray.arrayWithContentsOfFile_(fdata)
	
	return meta, data
    def testFunctions(self):
        v = CTParagraphStyleGetTypeID()
        self.assertIsInstance(v, (int, long))
        self.assertResultHasType(CTParagraphStyleGetValueForSpecifier, objc._C_BOOL)

        # Test below is not needed due to manaul wrapper:
        #self.assertResultIsCFRetained(CTParagraphStyleCreate)
        style = CTParagraphStyleCreate(None, 0)
        self.assertIsInstance(style, CTParagraphStyleRef);

        self.assertResultIsCFRetained(CTParagraphStyleCreateCopy)
        v = CTParagraphStyleCreateCopy(style)
        self.assertIsInstance(v, CTParagraphStyleRef);

        ok, v = CTParagraphStyleGetTabStops(style)
        self.assertTrue(ok)
        self.assertIsInstance(v, NSArray)
        self.assertTrue(len(v))
        self.assertIsInstance(v[0], CTTextTabRef)

        ok, v = CTParagraphStyleGetValueForSpecifier(style,
                kCTParagraphStyleSpecifierAlignment, sizeof_CTTextAlignment, None)
        self.assertTrue(ok)
        self.assertIsInstance(v, bytes)
        self.assertEqual(len(v), sizeof_CTTextAlignment)

        ok, v = CTParagraphStyleGetValueForSpecifier(style,
                kCTParagraphStyleSpecifierFirstLineHeadIndent, sizeof_CGFloat, None)
        self.assertTrue(ok)
        self.assertIsInstance(v, bytes)
        self.assertEqual(len(v), sizeof_CGFloat)

        ok, v = CTParagraphStyleGetValueForSpecifier(style,
                kCTParagraphStyleSpecifierLineBreakMode, sizeof_CTLineBreakMode, None)
        self.assertTrue(ok)
        self.assertIsInstance(v, bytes)
        self.assertEqual(len(v), sizeof_CTLineBreakMode)

        ok, v = CTParagraphStyleGetValueForSpecifier(style,
                kCTParagraphStyleSpecifierBaseWritingDirection, sizeof_CTWritingDirection, None)
        self.assertTrue(ok)
        self.assertIsInstance(v, bytes)
        self.assertEqual(len(v), sizeof_CTWritingDirection)

        # And now the hard part: create a CTParagraphStyle with custom options
        if sys.maxsize > 2**32:
            float_pack = "d"
        else:
            float_pack = "f"
        options = [
                CTParagraphStyleSetting(
                    spec=kCTParagraphStyleSpecifierBaseWritingDirection,
                    valueSize=sizeof_CTWritingDirection,
                    value=chr(kCTParagraphStyleSpecifierTailIndent).encode('latin1')),
                CTParagraphStyleSetting(
                    spec=kCTParagraphStyleSpecifierFirstLineHeadIndent,
                    valueSize=sizeof_CGFloat,
                    value=struct.pack(float_pack, 10.5)),
                CTParagraphStyleSetting(
                    spec=kCTParagraphStyleSpecifierTabStops,
                    valueSize=sizeof_id,
                    value=NSArray.arrayWithArray_([
                        CTTextTabCreate(kCTLeftTextAlignment, 40.0, None),
                        CTTextTabCreate(kCTLeftTextAlignment, 80.0, None),
                    ])),
        ]
        options.append(
                CTParagraphStyleSetting(
                    spec=kCTParagraphStyleSpecifierBaseWritingDirection,
                    valueSize=sizeof_CTWritingDirection,
                    value=chr(kCTWritingDirectionRightToLeft).encode('latin1')),
        )
        style = CTParagraphStyleCreate(options, len(options))
        self.assertIsInstance(style, CTParagraphStyleRef);

        ok, v = CTParagraphStyleGetTabStops(style)
        self.assertTrue(ok)
        self.assertIsInstance(v, NSArray)
        self.assertEqual(len(v), 2)

        ok, v = CTParagraphStyleGetValueForSpecifier(style,
                kCTParagraphStyleSpecifierBaseWritingDirection, sizeof_CTWritingDirection, None)
        self.assertTrue(ok)
        self.assertIsInstance(v, bytes)
        self.assertEqual(v, chr(kCTWritingDirectionRightToLeft).encode('latin1'))

        ok, v = CTParagraphStyleGetValueForSpecifier(style,
                kCTParagraphStyleSpecifierFirstLineHeadIndent, sizeof_CGFloat, None)
        self.assertTrue(ok)
        self.assertIsInstance(v, bytes)
        self.assertEqual(v, struct.pack(float_pack, 10.5))