コード例 #1
0
def text(textString, pt):
    # Draw a text on position "x", "y".
    NSString.stringWithString_(textString).drawAtPoint_withAttributes_(
        NSMakePoint(pt[0], pt[1]), {
            NSFontAttributeName: currentFont,
            NSForegroundColorAttributeName: currentFillColor
        })
コード例 #2
0
ファイル: DebugWindow.py プロジェクト: uditha-atukorala/blink
    def handle_notification(self, notification):
        handler = getattr(self, '_NH_%s' % notification.name, Null)
        handler(notification)

        if notification.name in ('SIPEngineSIPTrace', 'SIPEngineLog', 'MSRPLibraryLog', 'MSRPTransportTrace'):
            return

        # notifications text view
        if self.notificationsCheckBox.state() == NSOnState:
            attribs = notification.data.__dict__.copy()

            # remove some data that would be too big to log
            if notification.name == "MSRPTransportTrace":
                if len(attribs["data"]) > 30:
                    attribs["data"] = "<%i bytes>"%len(attribs["data"])
            elif notification.name in ("FileTransferStreamGotChunk", "ScreenSharingStreamGotData"):
                attribs["content"] = "..."
                if attribs.has_key("data"):
                    attribs["data"] = "..."

            attribs = ", ".join("%s=%s" % (k, v) for k, v in attribs.iteritems())
            ts = notification.datetime
            ts = ts.replace(microsecond=0) if type(ts) == datetime else ""

            self.notificationsBytes += len(notification.name) + len(str(notification.sender)) + len(attribs) + len(str(ts))
            self.notifications_unfiltered.append((NSString.stringWithString_(notification.name),
                                            NSString.stringWithString_(str(notification.sender)),
                                            NSString.stringWithString_(attribs),
                                            NSString.stringWithString_(str(ts))))
            self.renderNotifications()
コード例 #3
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)
コード例 #4
0
ファイル: __init__.py プロジェクト: Dangeranger/pymacadmin
def DSQuery(dstype, objectname, attribute=None):
    """DirectoryServices query.

  Args:
    dstype: The type of objects to query. user, group.
    objectname: the object to query.
    attribute: the optional attribute to query.
  Returns:
    If an attribute is specified, the value of the attribute. Otherwise, the
    entire plist.
  Raises:
    DSException: Cannot query DirectoryServices.
  """
    ds_path = "/%ss/%s" % (dstype.capitalize(), objectname)
    cmd = [_DSCL, "-plist", ".", "-read", ds_path]
    if attribute:
        cmd.append(attribute)
    (stdout, stderr, returncode) = RunProcess(cmd)
    if returncode:
        raise DSException("Cannot query %s for %s: %s" % (ds_path, attribute, stderr))
    plist = NSString.stringWithString_(stdout).propertyList()
    if attribute:
        value = None
        if "dsAttrTypeStandard:%s" % attribute in plist:
            value = plist["dsAttrTypeStandard:%s" % attribute]
        elif attribute in plist:
            value = plist[attribute]
        try:
            # We're copying to a new list to convert from NSCFArray
            return value[:]
        except TypeError:
            # ... unless we can't
            return value
    else:
        return plist
コード例 #5
0
ファイル: Canvas.py プロジェクト: tomihasa/pygui
 def show_text(self, text):
     x, y = self._ns_path.currentPoint()
     font = self._font
     ns_font = font._ns_font
     ns_color = self._textcolor._ns_color
     ns_string = NSString.stringWithString_(text)
     ns_attrs = {
         NSFontAttributeName: ns_font,
         NSForegroundColorAttributeName: ns_color,
     }
     #		print "Canvas.show_text:", repr(text) ###
     #		print "family:", ns_font.familyName() ###
     #		print "size:", ns_font.pointSize() ###
     #		print "ascender:", ns_font.ascender() ###
     #		print "descender:", ns_font.descender() ###
     #		print "capHeight:", ns_font.capHeight() ###
     #		print "leading:", ns_font.leading() ###
     #		print "matrix:", ns_font.matrix() ###
     #		print "defaultLineHeightForFont:", ns_font.defaultLineHeightForFont() ###
     h = ns_font.defaultLineHeightForFont()
     d = -ns_font.descender()
     dy = h - d
     if ns_font.familyName() == "Courier New":
         dy += ns_font.pointSize() * 0.229167
     ns_point = NSPoint(x, y - h)
     #print "drawing at:", ns_point ###
     ns_string.drawAtPoint_withAttributes_(ns_point, ns_attrs)
     dx = ns_font.widthOfString_(ns_string)
     #self._ns_path.relativeMoveToPoint_(NSPoint(x + dx, y))
     self._ns_path.relativeMoveToPoint_((dx, 0))
コード例 #6
0
ファイル: password_generator.py プロジェクト: chilcote/pylab
def load_dictionaries(context_ref, language_list):
    # The function is a bit picky about making sure we pass a clean NSArray with NSStrings
    langs = NSMutableArray.array()
    for x in language_list:
        langs.addObject_(NSString.stringWithString_(x))
    # The True argument is for whether the language string objects are already retained
    SFPWAContextLoadDictionaries(context_ref, langs, True)
コード例 #7
0
def DSSearch(path, key, value, node='.'):
    cmd = [_DSCL, node, '-search', path, key, value]
    (stdout, stderr, returncode) = gmacpyutil.RunProcess(cmd)
    if returncode:
        raise DSException('Cannot search %s for %s:%s. %s' %
                          (path, key, value, stderr))
    return NSString.stringWithString_(stdout)
コード例 #8
0
    def requiredThickness(self):
        lineCount = len(self.lineIndices())
        digits = int(math.log10(lineCount) + 1)

        sampleString = NSString.stringWithString_("8" * digits)
        stringSize = sampleString.sizeWithAttributes_(self.textAttributes())
        return math.ceil(max([self.DEFAULT_THICKNESS, stringSize.width + self.RULER_MARGIN * 2]))
コード例 #9
0
 def _GetSystemProfile(self, sp_type):
   # pylint: disable=global-statement
   if sp_type not in self._cache:
     logging.debug('%s not cached', sp_type)
     sp_xml = self._GetSystemProfilerOutput(sp_type)
     self._cache[sp_type] = NSString.stringWithString_(sp_xml).propertyList()
   return self._cache[sp_type]
コード例 #10
0
ファイル: systemconfig.py プロジェクト: AaronBurchfield/imagr
 def _GetSystemProfile(self, sp_type):
   # pylint: disable=global-statement
   if sp_type not in self._cache:
     logging.debug('%s not cached', sp_type)
     sp_xml = self._GetSystemProfilerOutput(sp_type)
     self._cache[sp_type] = NSString.stringWithString_(sp_xml).propertyList()
   return self._cache[sp_type]
コード例 #11
0
    def drawHashMarksAndLabelsInRect_(self, rect):
        bounds = self.bounds()
        view = self.clientView()

        rulerBackgroundColor = self.rulerBackgroundColor()
        if rulerBackgroundColor is not None:
            rulerBackgroundColor.set()
            NSRectFill(bounds)

        if not isinstance(view, NSTextView):
            return

        layoutManager = view.layoutManager()
        container = view.textContainer()
        text = view.string()
        nullRange = NSMakeRange(NSNotFound, 0)
        yinset = view.textContainerInset().height
        visibleRect = self.scrollView().contentView().bounds()
        textAttributes = self.textAttributes()

        lines = self.lineIndices()

        glyphRange = layoutManager.glyphRangeForBoundingRect_inTextContainer_(visibleRect, container)
        _range = layoutManager.characterRangeForGlyphRange_actualGlyphRange_(glyphRange, None)[0]
        _range.length += 1

        count = len(lines)
        index = 0

        lineNumber = self.lineNumberForCharacterIndex_inText_(_range.location, text)

        for line in range(lineNumber, count):
            index = lines[line]
            if NSLocationInRange(index, _range):
                rects, rectCount = layoutManager.rectArrayForCharacterRange_withinSelectedCharacterRange_inTextContainer_rectCount_(
                    NSMakeRange(index, 0),
                    nullRange,
                    container,
                    None
                )
                if rectCount > 0:
                    ypos = yinset + NSMinY(rects[0]) - NSMinY(visibleRect)
                    labelText = NSString.stringWithString_("%s" % (line + 1))
                    stringSize = labelText.sizeWithAttributes_(textAttributes)

                    x = NSWidth(bounds) - stringSize.width - self.RULER_MARGIN
                    y = ypos + (NSHeight(rects[0]) - stringSize.height) / 2.0
                    w = NSWidth(bounds) - self.RULER_MARGIN * 2.0
                    h = NSHeight(rects[0])

                    labelText.drawInRect_withAttributes_(NSMakeRect(x, y, w, h), textAttributes)

            if index > NSMaxRange(_range):
                break

        path = NSBezierPath.bezierPath()
        path.moveToPoint_((bounds.origin.x + bounds.size.width, bounds.origin.y))
        path.lineToPoint_((bounds.origin.x + bounds.size.width, bounds.origin.y + bounds.size.height))
        NSColor.grayColor().set()
        path.stroke()
コード例 #12
0
def DSQuery(dstype, objectname, attribute):
  """DirectoryServices query.

  Args:
	dstype: The type of objects to query. user, group.
	objectname: the object to query.
	attribute: the attribute to query.
  Returns:
	the value of the attribute. If single-valued array, return single value.
  Raises:
	DSException: Cannot query DirectoryServices.
  """
  ds_path = '/%ss/%s' % (dstype.capitalize(), objectname)
  cmd = [_DSCL, '-plist', '.', '-read', ds_path, attribute]
  task = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  (stdout, stderr) = task.communicate()
  if task.returncode:
	raise DSException('Cannot query %s for %s: %s' % (ds_path,
													  attribute,
													  stderr))
  plist = NSString.stringWithString_(stdout).propertyList()
  if 'dsAttrTypeStandard:%s' % attribute in plist:
	value = plist['dsAttrTypeStandard:%s' % attribute]
	if len(value) == 1:
	  return value[0]
	else:
	  return value
  else:
	return None
コード例 #13
0
ファイル: message_view.py プロジェクト: ziz/tinymail
 def _update_view_with_string(self, str_data):
     ns_str = NSString.stringWithString_(str_data.decode('latin-1'))
     data = ns_str.dataUsingEncoding_(NSISOLatin1StringEncoding)
     url = NSURL.URLWithString_('about:blank')
     frame = self.web_view.mainFrame()
     frame.loadData_MIMEType_textEncodingName_baseURL_(data, 'text/plain',
                                                       'latin-1', url)
コード例 #14
0
ファイル: Canvas.py プロジェクト: skykooler/Lightningbeam
    def show_text(self, text):
        x, y = self._ns_path.currentPoint()
        font = self._font
        ns_font = font._ns_font
        ns_color = self._textcolor._ns_color
        ns_string = NSString.stringWithString_(text)
        ns_attrs = {
            NSFontAttributeName: ns_font,
            NSForegroundColorAttributeName: ns_color,
        }
#		print "Canvas.show_text:", repr(text) ###
#		print "family:", ns_font.familyName() ###
#		print "size:", ns_font.pointSize() ###
#		print "ascender:", ns_font.ascender() ###
#		print "descender:", ns_font.descender() ###
#		print "capHeight:", ns_font.capHeight() ###
#		print "leading:", ns_font.leading() ###
#		print "matrix:", ns_font.matrix() ###
#		print "defaultLineHeightForFont:", ns_font.defaultLineHeightForFont() ###
        h = ns_font.defaultLineHeightForFont()
        d = -ns_font.descender()
        dy = h - d
        if ns_font.familyName() == "Courier New":
            dy += ns_font.pointSize() * 0.229167
        ns_point = NSPoint(x, y - dy)
        #print "drawing at:", ns_point ###
        ns_string.drawAtPoint_withAttributes_(ns_point, ns_attrs)
        dx = ns_font.widthOfString_(ns_string)
        #self._ns_path.relativeMoveToPoint_(NSPoint(x + dx, y))
        self._ns_path.relativeMoveToPoint_((dx, 0))
コード例 #15
0
def load_dictionaries(context_ref, language_list):
    # The function is a bit picky about making sure we pass a clean NSArray with NSStrings
    langs = NSMutableArray.array()
    for x in language_list:
        langs.addObject_(NSString.stringWithString_(x))
    # The True argument is for whether the language string objects are already retained
    SFPWAContextLoadDictionaries(context_ref, langs, True)
コード例 #16
0
 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
コード例 #17
0
 def setLabel_(self, label):
     if type(label) == NSString:
         self.label = label
     else:
         self.label = NSString.stringWithString_(label)
     frame = self.frame()
     frame.size.width = self.idealWidth()
     self.setFrame_(frame)
コード例 #18
0
 def setLabel_(self, label):
     if type(label) == NSString:
         self.label = label
     else:
         self.label = NSString.stringWithString_(label)
     frame = self.frame()
     frame.size.width = self.idealWidth()
     self.setFrame_(frame)
コード例 #19
0
ファイル: ds.py プロジェクト: AaronBurchfield/imagr
def DSSearch(path, key, value, node='.'):
  cmd = [_DSCL, node, '-search', path, key, value]
  (stdout, stderr, returncode) = gmacpyutil.RunProcess(cmd)
  if returncode:
    raise DSException('Cannot search %s for %s:%s. %s' % (path,
                                                          key,
                                                          value,
                                                          stderr))
  return NSString.stringWithString_(stdout)
コード例 #20
0
ファイル: XPlist.py プロジェクト: piaoapiao/XPlist
def init_with_url(url):
	contents = urlopen(url).read()
	start = contents.find("<?xml ")
	plist = NSString.stringWithString_(contents[start:]).propertyList()
	
	if not isinstance(plist, NSDictionary):
		raise Exception("Invalid URL contents.", url, contents)
	
	return plist["meta"], plist["data"]
コード例 #21
0
    def requiredThickness(self):
        lineCount = len(self.lineIndices())
        digits = int(math.log10(lineCount) + 1)

        sampleString = NSString.stringWithString_("8" * digits)
        stringSize = sampleString.sizeWithAttributes_(self.textAttributes())
        return math.ceil(
            max([
                self.DEFAULT_THICKNESS,
                stringSize.width + self.RULER_MARGIN * 2
            ]))
コード例 #22
0
ファイル: make_icons.py プロジェクト: 11liju/macvim
 def drawTextAtSize(self, text, s):
   if s != 16:
     docerator.TextRenderer.drawTextAtSize(self, text, s)
     return
   text = NSString.stringWithString_(text.lower()[0:3])  # at most 3 chars
   attribs = self.attribsAtSize(s)
   if len(text) <= 2:
     attribs[NSKernAttributeName] = 0  # we have some space
   else:
     attribs[NSKernAttributeName] = -1  # we need all the room we can get
   text.drawInRect_withAttributes_( ((1, 2), (15, 11)), attribs)
コード例 #23
0
def getOutline(page, label):
	# Create Destination
	myPage = myPDF.pageAtIndex_(page)
	pageSize = myPage.boundsForBox_(Quartz.kCGPDFMediaBox)
	x = 0
	y = Quartz.CGRectGetMaxY(pageSize)
	pagePoint = Quartz.CGPointMake(x,y)
	myDestination = Quartz.PDFDestination.alloc().initWithPage_atPoint_(myPage, pagePoint)
	myLabel = NSString.stringWithString_(label)
	myOutline = Quartz.PDFOutline.alloc().init()
	myOutline.setLabel_(myLabel)
	myOutline.setDestination_(myDestination)
	return myOutline
コード例 #24
0
 def drawTextAtSize(self, text, s):
     if s != 16:
         docerator.TextRenderer.drawTextAtSize(self, text, s)
         return
     text = NSString.stringWithString_(
         text.lower()[0:3])  # at most 3 chars
     attribs = self.attribsAtSize(s)
     if len(text) <= 2:
         attribs[NSKernAttributeName] = 0  # we have some space
     else:
         attribs[
             NSKernAttributeName] = -1  # we need all the room we can get
     text.drawInRect_withAttributes_(((1, 2), (15, 11)), attribs)
コード例 #25
0
def getOutline(page, label):
	# Create Destination
	myPage = myPDF.pageAtIndex_(page)
	pageSize = myPage.boundsForBox_(Quartz.kCGPDFMediaBox)
	x = 0
	y = Quartz.CGRectGetMaxY(pageSize)
	pagePoint = Quartz.CGPointMake(x,y)
	myDestination = Quartz.PDFDestination.alloc().initWithPage_atPoint_(myPage, pagePoint)
	myLabel = NSString.stringWithString_(label)
	myOutline = Quartz.PDFOutline.alloc().init()
	myOutline.setLabel_(myLabel)
	myOutline.setDestination_(myDestination)
	return myOutline
コード例 #26
0
ファイル: finder.py プロジェクト: bizonix/DropBoxLibrarySRC
 def _send_message(self, event_type, *arguments):
     if not self._port:
         self._connect_port()
     message_type = bytearray([event_type])
     message_args = [ NSString.stringWithString_(arg).dataUsingEncoding_(NSUTF16StringEncoding) for arg in arguments ]
     components = [message_type] + message_args
     try:
         message = NSPortMessage.alloc().initWithSendPort_receivePort_components_(self._port, None, components)
         if not message.sendBeforeDate_(NSDate.dateWithTimeIntervalSinceNow_(self.EVENT_TIMEOUT)):
             raise Exception('Failed to send the port message.')
     except Exception:
         TRACE('Mach port became invalid.')
         self._port = None
         raise
コード例 #27
0
    def makeDragImage(self):
        if self.delegate is None:
            return

        image = NSImage.alloc().initWithSize_(self.frame().size)
        image.lockFocus()

        frame = self.frame()
        frame.origin = NSZeroPoint
        rect = NSInsetRect(frame, 1.5, 1.5)

        if self.conferencing and not self.draggedOut:
            NSColor.selectedControlColor().colorWithAlphaComponent_(0.7).set()
        else:
            NSColor.whiteColor().colorWithAlphaComponent_(0.7).set()
        path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(rect, 5.0, 5.0)
        path.fill()

        if self.selected:
            path.setLineWidth_(3)
            NSColor.grayColor().set()
        else:
            path.setLineWidth_(1)
            NSColor.grayColor().set()
        path.stroke()

        NSColor.blackColor().set()
        point = NSMakePoint(8, NSMaxY(frame)-20)
        uri = format_identity_to_string(self.delegate.sessionController.remotePartyObject, check_contact=False, format='compact')
        NSString.stringWithString_(uri).drawAtPoint_withAttributes_(point,
              NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.boldSystemFontOfSize_(12), NSFontAttributeName))
        point = NSMakePoint(8, 6)
        if self.conferencing:
            NSString.stringWithString_(NSLocalizedString("Drop outside to remove from conference", "Audio session label")).drawAtPoint_withAttributes_(point,
                  NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.systemFontOfSize_(10), NSFontAttributeName))
        else:
            audio_sessions = [sess.hasStreamOfType("audio") for sess in NSApp.delegate().contactsWindowController.sessionControllersManager.sessionControllers]
            if self.delegate.transferEnabled:
                text = NSLocalizedString("Drop this over a session or contact", "Audio session label") if len(audio_sessions) > 1 else NSLocalizedString("Drop this over a contact to transfer", "Audio session label")
            else:
                text = NSLocalizedString("Drop this over a session to conference", "Audio session label")
            NSString.stringWithString_(text).drawAtPoint_withAttributes_(point,
                  NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.systemFontOfSize_(10), NSFontAttributeName))

        icon = NSImage.imageNamed_("NSEveryone")
        rect = frame
        s = icon.size()
        p = NSMakePoint(NSWidth(rect) - s.width - 8, rect.size.height - s.height - 8)
        r = NSMakeRect(0, 0, s.width, s.height)
        icon.drawAtPoint_fromRect_operation_fraction_(p, r, NSCompositeSourceOver, 0.5)

        image.unlockFocus()
        return image
コード例 #28
0
    def start(self):
        '''Start the connection'''
        if not self.destination_path:
            self.log('No output file specified.')
            self.done = True
            return
        url = NSURL.URLWithString_(self.url)
        request = (
            NSMutableURLRequest.requestWithURL_cachePolicy_timeoutInterval_(
                url, NSURLRequestReloadIgnoringLocalCacheData,
                self.connection_timeout))
        if self.post_data:
            request.setHTTPMethod_('POST')
            data_unicode = unicode(self.post_data)
            data = NSData.dataWithBytes_length_(
                NSString.stringWithString_(data_unicode).UTF8String(),
                len(data_unicode.encode('utf-8')))
            request.setHTTPBody_(data)

        if self.additional_headers:
            for header, value in self.additional_headers.items():
                request.setValue_forHTTPHeaderField_(value, header)
        # does the file already exist? See if we can resume a partial download
        if os.path.isfile(self.destination_path):
            stored_data = self.get_stored_headers()
            if (self.can_resume and 'expected-length' in stored_data and
                ('last-modified' in stored_data or 'etag' in stored_data)):
                # we have a partial file and we're allowed to resume
                self.resume = True
                local_filesize = os.path.getsize(self.destination_path)
                byte_range = 'bytes=%s-' % local_filesize
                request.setValue_forHTTPHeaderField_(byte_range, 'Range')
        if self.download_only_if_changed and not self.resume:
            stored_data = self.cache_data or self.get_stored_headers()
            if 'last-modified' in stored_data:
                request.setValue_forHTTPHeaderField_(
                    stored_data['last-modified'], 'if-modified-since')
            if 'etag' in stored_data:
                request.setValue_forHTTPHeaderField_(stored_data['etag'],
                                                     'if-none-match')

        self.connection = NSURLConnection.alloc().initWithRequest_delegate_(
            request, self)
コード例 #29
0
ファイル: helpers.py プロジェクト: LcTrKiD/nudge
def get_serial():
    '''Get system serial number'''
    # Credit to Michael Lynn
    IOKit_bundle = NSBundle.bundleWithIdentifier_('com.apple.framework.IOKit')

    functions = [
        ("IOServiceGetMatchingService", b"II@"),
        ("IOServiceMatching", b"@*"),
        ("IORegistryEntryCreateCFProperty", b"@I@@I"),
    ]

    objc.loadBundleFunctions(IOKit_bundle, globals(), functions)
    # pylint: disable=undefined-variable
    serial = IORegistryEntryCreateCFProperty(
        IOServiceGetMatchingService(
            0, IOServiceMatching("IOPlatformExpertDevice".encode("utf-8"))),
        NSString.stringWithString_("IOPlatformSerialNumber"), None, 0)
    # pylint: enable=undefined-variable
    return serial
コード例 #30
0
ファイル: gurl.py プロジェクト: bruienne/imagr
    def start(self):
        '''Start the connection'''
        if not self.destination_path:
            self.log('No output file specified.')
            self.done = True
            return
        url = NSURL.URLWithString_(self.url)
        request = (
            NSMutableURLRequest.requestWithURL_cachePolicy_timeoutInterval_(
                url, NSURLRequestReloadIgnoringLocalCacheData,
                self.connection_timeout))
        if self.post_data:
            request.setHTTPMethod_('POST')
            data_unicode = unicode(self.post_data)
            data = NSData.dataWithBytes_length_(NSString.stringWithString_(data_unicode).UTF8String(), len(data_unicode.encode('utf-8')))
            request.setHTTPBody_(data)

        if self.additional_headers:
            for header, value in self.additional_headers.items():
                request.setValue_forHTTPHeaderField_(value, header)
        # does the file already exist? See if we can resume a partial download
        if os.path.isfile(self.destination_path):
            stored_data = self.get_stored_headers()
            if (self.can_resume and 'expected-length' in stored_data and
                    ('last-modified' in stored_data or 'etag' in stored_data)):
                # we have a partial file and we're allowed to resume
                self.resume = True
                local_filesize = os.path.getsize(self.destination_path)
                byte_range = 'bytes=%s-' % local_filesize
                request.setValue_forHTTPHeaderField_(byte_range, 'Range')
        if self.download_only_if_changed and not self.resume:
            stored_data = self.cache_data or self.get_stored_headers()
            if 'last-modified' in stored_data:
                request.setValue_forHTTPHeaderField_(
                    stored_data['last-modified'], 'if-modified-since')
            if 'etag' in stored_data:
                request.setValue_forHTTPHeaderField_(
                    stored_data['etag'], 'if-none-match')

        self.connection = NSURLConnection.alloc().initWithRequest_delegate_(
            request, self)
コード例 #31
0
ファイル: purl.py プロジェクト: bochoven/munkireport-php
    def start(self):
        """Start the connection."""
        url = NSURL.URLWithString_(self.url)
        request = NSMutableURLRequest.requestWithURL_cachePolicy_timeoutInterval_(
            url, NSURLRequestReloadIgnoringLocalCacheData,
            self.connection_timeout)
        if self.additional_headers:
            for header, value in self.additional_headers.items():
                request.setValue_forHTTPHeaderField_(value, header)
        request.setHTTPMethod_(self.method)

        if self.method == "POST":
            body_unicode = unicode(self.body)
            body_data = NSData.dataWithBytes_length_(
                NSString.stringWithString_(body_unicode).UTF8String(),
                len(body_unicode.encode("utf-8")),
            )
            request.setHTTPBody_(body_data)

        self.connection = NSURLConnection.alloc().initWithRequest_delegate_(
            request, self)
コード例 #32
0
    def copy_text(self, text, clear_first=True):
        if not text:
            raise ValueError('no input')
        # end if
        if isinstance(text, str):
            text = {'text/plain': text}
        # end if
        if not isinstance(text, dict):
            raise ValueError('wrong')
        # end if

        pb = NSPasteboard.generalPasteboard()
        if clear_first:
            pb.clearContents()
        # end def
        pb.declareTypes_owner_([self._f(fmt) for fmt in text.keys()], None)

        for fmt, value in text.items():
            new_str = NSString.stringWithString_(value).nsstring()
            new_data = new_str.dataUsingEncoding_(NSUTF8StringEncoding)
            pb.setData_forType_(new_data, self._f(fmt))
コード例 #33
0
ファイル: __init__.py プロジェクト: rapaul/puppetrepo
def DSQueryLDAPv3(dstype, node, objectname, attribute=None):
    """LDAPv3 DirectoryServices query.

  Args:
    dstype: The type of objects to query. user, group.
    node:  The node to query.
    objectname: the object to query.
    attribute: the optional attribute to query.
  Returns:
    If an attribute is specified, the value of the attribute. Otherwise, the
    entire plist.
  Raises:
    DSException: Cannot query DirectoryServices.
  """
    ds_path = '/%ss/%s' % (dstype.capitalize(), objectname)
    cmd = [_DSCL, '-plist', node, '-read', ds_path]
    if attribute:
        cmd.append(attribute)
    (stdout, stderr, returncode) = RunProcess(cmd)
    if returncode:
        raise DSException('Cannot query %s for %s: %s' %
                          (ds_path, attribute, stderr))
    plist = NSString.stringWithString_(stdout).propertyList()
    if attribute:
        value = None
        if 'dsAttrTypeStandard:%s' % attribute in plist:
            value = plist['dsAttrTypeStandard:%s' % attribute]
        elif attribute in plist:
            value = plist[attribute]
        try:
            # We're copying to a new list to convert from NSCFArray
            return value[:]
        except TypeError:
            # ... unless we can't
            return value
    else:
        return plist
コード例 #34
0
ファイル: mschtml.py プロジェクト: 50kaliber/munki
def unquote(a_string):
    '''Replacement for urllib.unquote that handles Unicode strings'''
    return str(NSString.stringWithString_(
                   a_string).stringByReplacingPercentEscapesUsingEncoding_(
                       NSUTF8StringEncoding))
コード例 #35
0
    def makeDragImage(self):
        if self.delegate is None:
            return

        image = NSImage.alloc().initWithSize_(self.frame().size)
        image.lockFocus()

        frame = self.frame()
        frame.origin = NSZeroPoint
        rect = NSInsetRect(frame, 1.5, 1.5)

        if self.conferencing and not self.draggedOut:
            NSColor.selectedControlColor().colorWithAlphaComponent_(0.7).set()
        else:
            NSColor.whiteColor().colorWithAlphaComponent_(0.7).set()
        path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(
            rect, 5.0, 5.0)
        path.fill()

        if self.selected:
            path.setLineWidth_(3)
            NSColor.grayColor().set()
        else:
            path.setLineWidth_(1)
            NSColor.grayColor().set()
        path.stroke()

        NSColor.blackColor().set()
        point = NSMakePoint(8, NSMaxY(frame) - 20)
        uri = format_identity_to_string(
            self.delegate.sessionController.remoteIdentity,
            check_contact=False,
            format='compact')
        NSString.stringWithString_(uri).drawAtPoint_withAttributes_(
            point,
            NSDictionary.dictionaryWithObjectsAndKeys_(
                NSFont.boldSystemFontOfSize_(12), NSFontAttributeName))
        point = NSMakePoint(8, 6)
        if self.conferencing:
            NSString.stringWithString_(
                NSLocalizedString(
                    "Drop outside to remove from conference",
                    "Audio status label")).drawAtPoint_withAttributes_(
                        point,
                        NSDictionary.dictionaryWithObjectsAndKeys_(
                            NSFont.systemFontOfSize_(10), NSFontAttributeName))
        else:
            audio_sessions = [
                sess.hasStreamOfType("audio")
                for sess in NSApp.delegate().contactsWindowController.
                sessionControllersManager.sessionControllers
            ]
            if self.delegate.transferEnabled:
                text = NSLocalizedString(
                    "Drop this over a session or contact", "Audio status label"
                ) if len(audio_sessions) > 1 else NSLocalizedString(
                    "Drop this over a contact to transfer",
                    "Audio status label")
            else:
                text = NSLocalizedString(
                    "Drop this over a session to conference",
                    "Audio status label")
            NSString.stringWithString_(text).drawAtPoint_withAttributes_(
                point,
                NSDictionary.dictionaryWithObjectsAndKeys_(
                    NSFont.systemFontOfSize_(10), NSFontAttributeName))

        icon = NSImage.imageNamed_("NSEveryone")
        rect = frame
        s = icon.size()
        p = NSMakePoint(
            NSWidth(rect) - s.width - 8, rect.size.height - s.height - 8)
        r = NSMakeRect(0, 0, s.width, s.height)
        icon.drawAtPoint_fromRect_operation_fraction_(p, r,
                                                      NSCompositeSourceOver,
                                                      0.5)

        image.unlockFocus()
        return image
コード例 #36
0
    def drawHashMarksAndLabelsInRect_(self, rect):
        bounds = self.bounds()
        view = self.clientView()

        rulerBackgroundColor = self.rulerBackgroundColor()
        if rulerBackgroundColor is not None:
            rulerBackgroundColor.set()
            NSRectFill(bounds)

        if not isinstance(view, NSTextView):
            return

        layoutManager = view.layoutManager()
        container = view.textContainer()
        text = view.string()
        nullRange = NSMakeRange(NSNotFound, 0)
        yinset = view.textContainerInset().height
        visibleRect = self.scrollView().contentView().bounds()
        textAttributes = self.textAttributes()

        lines = self.lineIndices()

        glyphRange = layoutManager.glyphRangeForBoundingRect_inTextContainer_(
            visibleRect, container)
        _range = layoutManager.characterRangeForGlyphRange_actualGlyphRange_(
            glyphRange, None)[0]
        _range.length += 1

        count = len(lines)
        index = 0

        lineNumber = self.lineNumberForCharacterIndex_inText_(
            _range.location, text)

        for line in range(lineNumber, count):
            index = lines[line]
            if NSLocationInRange(index, _range):
                rects, rectCount = layoutManager.rectArrayForCharacterRange_withinSelectedCharacterRange_inTextContainer_rectCount_(
                    NSMakeRange(index, 0), nullRange, container, None)
                if rectCount > 0:
                    ypos = yinset + NSMinY(rects[0]) - NSMinY(visibleRect)
                    labelText = NSString.stringWithString_("%s" % (line + 1))
                    stringSize = labelText.sizeWithAttributes_(textAttributes)

                    x = NSWidth(bounds) - stringSize.width - self.RULER_MARGIN
                    y = ypos + (NSHeight(rects[0]) - stringSize.height) / 2.0
                    w = NSWidth(bounds) - self.RULER_MARGIN * 2.0
                    h = NSHeight(rects[0])

                    labelText.drawInRect_withAttributes_(
                        NSMakeRect(x, y, w, h), textAttributes)

            if index > NSMaxRange(_range):
                break

        path = NSBezierPath.bezierPath()
        path.moveToPoint_(
            (bounds.origin.x + bounds.size.width, bounds.origin.y))
        path.lineToPoint_((bounds.origin.x + bounds.size.width,
                           bounds.origin.y + bounds.size.height))
        NSColor.grayColor().set()
        path.stroke()
コード例 #37
0
ファイル: gen_archive.py プロジェクト: benoit-pierre/pyobjc
 def __getstate__(self):
     return {'a': self.a, 'b': self.b, NSString.stringWithString_('c'): self.c}
コード例 #38
0
 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
コード例 #39
0
ファイル: pymaIdentity.py プロジェクト: Jaharmi/pymaIdentity
</function>
<function name='CSGetLocalIdentityAuthority'>
<retval type='^{__CSIdentityAuthority=}'/>
</function>
<function name='CSGetManagedIdentityAuthority'>
<retval type='^{__CSIdentityAuthority=}'/>
</function>
</signatures>
""", globals(), '/System/Library/Frameworks/CoreServices.framework/Frameworks/OSServices.framework')

username,groupname = ("root", "wheel")

print "Getting pseudo central authority ..."
defaultAuthority = CSGetLocalIdentityAuthority()
print "Looking for user:"******"Search succeeded:", result
users_found = CSIdentityQueryCopyResults(userQuery)
print "Number of users found:", len(users_found)
print users_found
print "Looking for group:", groupname
groupQuery = CSIdentityQueryCreateForName(NULL, NSString.stringWithString_(groupname), kCSIdentityQueryStringEquals, kCSIdentityClassGroup, defaultAuthority)
result = CSIdentityQueryExecute(groupQuery, kCSIdentityQueryIncludeHiddenIdentities, NULL)
print "Search succeeded:", result
groups_found = CSIdentityQueryCopyResults(groupQuery)[:]
print "Number of groups found:", len(groups_found)
print groups_found
print 'Checking group membership for "%s" in "%s"' % (username, groupname)
result = CSIdentityIsMemberOfGroup(users_found[0], groups_found[0])
print "Is member of group:", result
コード例 #40
0
 def drawText(self, text, textPosition, fontColor=NSColor.whiteColor()):
     try:
         string = NSString.stringWithString_(text)
         string.drawAtPoint_color_alignment_(textPosition, fontColor, 4)
     except:
         print traceback.format_exc()
コード例 #41
0
	def dataRepresentationOfType_(self, aType):
		if len(self.text) > 0:
			return NSString.stringWithString_(self.text).dataUsingEncoding_(NSUTF8StringEncoding)
		else:
			NSdata.data()
コード例 #42
0
	def drawText( self, text, textPosition, fontColor=NSColor.blackColor() ):
		try:
			string = NSString.stringWithString_(text)
			string.drawAtPoint_color_alignment_(textPosition, fontColor, 4)
		except:
			print traceback.format_exc()
コード例 #43
0
 def setText_(self, text):
     self.text = NSString.stringWithString_(text)
     self.setNeedsDisplay_(True)
コード例 #44
0
ファイル: gen_archive.py プロジェクト: ivanmolera/Raspberry
 def __getstate__(self):
     return {
         'a': self.a,
         'b': self.b,
         NSString.stringWithString_('c'): self.c
     }
コード例 #45
0
ファイル: gen_archive.py プロジェクト: danchr/pyobjc-git
 def __getstate__(self):
     return {
         "a": self.a,
         "b": self.b,
         NSString.stringWithString_("c"): self.c
     }
コード例 #46
0
def io_key(keyname):
    return IORegistryEntryCreateCFProperty(
        IOServiceGetMatchingService(
            0, IOServiceMatching("IOPlatformExpertDevice".encode("utf-8"))),
        NSString.stringWithString_(keyname), None, 0)
コード例 #47
0
    def testFunctions(self):
        self.assertIsInstance(CFNetwork.CFHTTPAuthenticationGetTypeID(), int)

        msg = CFNetwork.CFHTTPMessageCreateResponse(
            None, 401, "Authenticate", CFNetwork.kCFHTTPVersion1_0)
        self.assertIsInstance(msg, CFNetwork.CFHTTPMessageRef)
        CFNetwork.CFHTTPMessageSetHeaderFieldValue(
            msg,
            NSString.stringWithString_("WWW-Authenticate"),
            NSString.stringWithString_('Basic realm="WallyWorld"'),
        )

        self.assertResultIsCFRetained(
            CFNetwork.CFHTTPAuthenticationCreateFromResponse)
        ref = CFNetwork.CFHTTPAuthenticationCreateFromResponse(None, msg)
        self.assertIsInstance(ref, CFNetwork.CFHTTPAuthenticationRef)

        self.assertResultIsBOOL(CFNetwork.CFHTTPAuthenticationIsValid)
        self.assertArgIsOut(CFNetwork.CFHTTPAuthenticationIsValid, 1)
        v, err = CFNetwork.CFHTTPAuthenticationIsValid(ref, None)
        self.assertIsInstance(v, bool)
        if v:
            self.assertTrue(err is None)
        else:
            self.assertIsInstance(err, CFNetwork.CFStreamError)

        self.assertResultIsBOOL(CFNetwork.CFHTTPAuthenticationAppliesToRequest)
        v = CFNetwork.CFHTTPAuthenticationAppliesToRequest(ref, msg)
        self.assertIsInstance(v, bool)

        self.assertResultIsBOOL(
            CFNetwork.CFHTTPAuthenticationRequiresOrderedRequests)
        v = CFNetwork.CFHTTPAuthenticationRequiresOrderedRequests(ref)
        self.assertIsInstance(v, bool)

        url = CFNetwork.CFURLCreateWithString(None, "http://www.python.org/",
                                              None)
        req = CFNetwork.CFHTTPMessageCreateRequest(None, "GET", url, "1.0")

        self.assertResultIsBOOL(CFNetwork.CFHTTPMessageApplyCredentials)
        self.assertArgIsOut(CFNetwork.CFHTTPMessageApplyCredentials, 4)
        v, err = CFNetwork.CFHTTPMessageApplyCredentials(
            req, ref, "ronald", "secret", None)
        if v is True:
            self.assertEqual(err, None)

        else:
            self.assertIsInstance(err, CFNetwork.CFStreamError)

        self.assertResultIsBOOL(
            CFNetwork.CFHTTPMessageApplyCredentialDictionary)
        self.assertArgIsOut(CFNetwork.CFHTTPMessageApplyCredentialDictionary,
                            3)
        v, err = CFNetwork.CFHTTPMessageApplyCredentialDictionary(
            req,
            ref,
            {
                CFNetwork.kCFHTTPAuthenticationUsername: "******",
                CFNetwork.kCFHTTPAuthenticationPassword: "******",
            },
            None,
        )
        if v is True:
            self.assertEqual(err, None)
        else:
            self.assertIsInstance(err, CFNetwork.CFStreamError)

        self.assertResultIsCFRetained(CFNetwork.CFHTTPAuthenticationCopyRealm)
        self.assertResultHasType(CFNetwork.CFHTTPAuthenticationCopyRealm,
                                 b"^{__CFString=}")
        v = CFNetwork.CFHTTPAuthenticationCopyRealm(ref)
        self.assertTrue(v is None or isinstance(v, str))

        self.assertResultIsCFRetained(
            CFNetwork.CFHTTPAuthenticationCopyDomains)
        self.assertResultHasType(CFNetwork.CFHTTPAuthenticationCopyDomains,
                                 b"^{__CFArray=}")
        v = CFNetwork.CFHTTPAuthenticationCopyDomains(ref)
        self.assertTrue(v is None or isinstance(v, CFNetwork.CFArrayRef))

        self.assertResultIsCFRetained(CFNetwork.CFHTTPAuthenticationCopyMethod)
        self.assertResultHasType(CFNetwork.CFHTTPAuthenticationCopyMethod,
                                 b"^{__CFString=}")
        v = CFNetwork.CFHTTPAuthenticationCopyMethod(ref)
        self.assertTrue(v is None or isinstance(v, str))

        self.assertResultIsBOOL(
            CFNetwork.CFHTTPAuthenticationRequiresUserNameAndPassword)
        v = CFNetwork.CFHTTPAuthenticationRequiresUserNameAndPassword(ref)
        self.assertIsInstance(v, bool)

        self.assertResultIsBOOL(
            CFNetwork.CFHTTPAuthenticationRequiresAccountDomain)
        v = CFNetwork.CFHTTPAuthenticationRequiresAccountDomain(ref)
        self.assertIsInstance(v, bool)
コード例 #48
0
def set_clipboard(value):
    OS_CLIPBOARD.declareTypes_owner_([NSStringPboardType], None)
    OS_CLIPBOARD.setData_forType_(
        NSString.stringWithString_(value).nsstring().dataUsingEncoding_(
            NSUTF8StringEncoding), NSStringPboardType)
コード例 #49
0
ファイル: mschtml.py プロジェクト: ygini/munki
def unquote(a_string):
    '''Replacement for urllib.unquote that handles Unicode strings'''
    return str(
        NSString.stringWithString_(a_string).
        stringByReplacingPercentEscapesUsingEncoding_(NSUTF8StringEncoding))
コード例 #50
0
 def setText_(self, text):
     self.text = NSString.stringWithString_(text)
     self.setNeedsDisplay_(True)
コード例 #51
0
    def testFunctions(self):
        self.assertIsInstance(CFHTTPAuthenticationGetTypeID(), (int, long))

        msg = CFHTTPMessageCreateResponse(None, 401, "Authenticate", kCFHTTPVersion1_0)
        self.assertIsInstance(msg, CFHTTPMessageRef)
        CFHTTPMessageSetHeaderFieldValue(msg, NSString.stringWithString_('WWW-Authenticate'), NSString.stringWithString_('Basic realm="WallyWorld"'))

        self.assertResultIsCFRetained(CFHTTPAuthenticationCreateFromResponse)
        ref = CFHTTPAuthenticationCreateFromResponse(None, msg)
        self.assertIsInstance(ref, CFHTTPAuthenticationRef)

        self.assertResultIsBOOL(CFHTTPAuthenticationIsValid)
        self.assertArgIsOut(CFHTTPAuthenticationIsValid, 1)
        v, err = CFHTTPAuthenticationIsValid(ref, None)
        self.assertIsInstance(v, bool)
        if v:
            self.assertTrue(err is None)
        else:
            self.assertIsInstance(err, CFStreamError)

        self.assertResultIsBOOL(CFHTTPAuthenticationAppliesToRequest)
        v = CFHTTPAuthenticationAppliesToRequest(ref, msg)
        self.assertIsInstance(v, bool)

        self.assertResultIsBOOL(CFHTTPAuthenticationRequiresOrderedRequests)
        v = CFHTTPAuthenticationRequiresOrderedRequests(ref)
        self.assertIsInstance(v, bool)

        url = CFURLCreateWithString(None, "http://www.python.org/", None)
        req = CFHTTPMessageCreateRequest(None, "GET", url, "1.0")

        self.assertResultIsBOOL(CFHTTPMessageApplyCredentials)
        self.assertArgIsOut(CFHTTPMessageApplyCredentials, 4)
        v, err = CFHTTPMessageApplyCredentials(req, ref, "ronald", "secret", None)
        if v is True:
            self.assertEqual(err, None)

        else:
            self.assertIsInstance(err, CFStreamError)

        self.assertResultIsBOOL(CFHTTPMessageApplyCredentialDictionary)
        self.assertArgIsOut(CFHTTPMessageApplyCredentialDictionary, 3)
        v, err = CFHTTPMessageApplyCredentialDictionary(req, ref, {
                kCFHTTPAuthenticationUsername: '******',
                kCFHTTPAuthenticationPassword: '******',
            }, None)
        if v is True:
            self.assertEqual(err, None)
        else:
            self.assertIsInstance(err, CFStreamError)

        self.assertResultIsCFRetained(CFHTTPAuthenticationCopyRealm)
        self.assertResultHasType(CFHTTPAuthenticationCopyRealm, b'@')
        v = CFHTTPAuthenticationCopyRealm(ref)
        self.assertTrue(v is None or isinstance(v, unicode))

        self.assertResultIsCFRetained(CFHTTPAuthenticationCopyDomains)
        self.assertResultHasType(CFHTTPAuthenticationCopyDomains, b'^{__CFArray=}')
        v = CFHTTPAuthenticationCopyDomains(ref)
        self.assertTrue(v is None or isinstance(v, CFArrayRef))

        self.assertResultIsCFRetained(CFHTTPAuthenticationCopyMethod)
        self.assertResultHasType(CFHTTPAuthenticationCopyMethod, b'@')
        v = CFHTTPAuthenticationCopyMethod(ref)
        self.assertTrue(v is None or isinstance(v, unicode))

        self.assertResultIsBOOL(CFHTTPAuthenticationRequiresUserNameAndPassword)
        v = CFHTTPAuthenticationRequiresUserNameAndPassword(ref)
        self.assertIsInstance(v, bool)

        self.assertResultIsBOOL(CFHTTPAuthenticationRequiresAccountDomain)
        v = CFHTTPAuthenticationRequiresAccountDomain(ref)
        self.assertIsInstance(v, bool)
コード例 #52
0
    def drawNodeDistanceText(self, layer):
        if layer is None:
            return
        try:
            try:
                selection = layer.selection
            except:
                selection = layer.selection()
            if len(selection) == 2:
                x1, y1 = selection[0].x, selection[0].y
                x2, y2 = selection[1].x, selection[1].y
                t = 0.5  # MIDLLE
                xAverage = x1 + (x2 - x1) * t
                yAverage = y1 + (y2 - y1) * t
                dist = math.hypot(x2 - x1, y2 - y1)

                # Angle
                #======
                # print x2 >= x1 or y2 >= y1
                switch = (x1, y1) >= (x2, y2)

                if switch == True and self.angleAbsolute == False:
                    dx, dy = x1 - x2, y1 - y2
                    #print "switch"
                else:
                    dx, dy = x2 - x1, y2 - y1
                rads = math.atan2(dy, dx)
                degs = math.degrees(rads)

                if self.angleAbsolute == True:
                    degs = degs % 180  # Not using 360 here. same angles will have the same number, no matter the path direction of this segment
                if self.angleAbsolute == False:
                    degs = abs(degs) % 90

                scale = self.getScale()
                string = NSString.stringWithString_(
                    u"%s\n%s°" % (round(dist, 1), round(degs, 1)))
                attributes = NSString.drawTextAttributes_(NSColor.whiteColor())
                textSize = string.sizeWithAttributes_(attributes)

                # Badge
                #======
                badgeWidth = textSize.width + 8
                badgeHeight = textSize.height + 4
                badgeRadius = 5

                unitVector = UnitVectorFromTo(NSPoint(x1, y1), NSPoint(x2, y2))

                badgeOffsetX = -unitVector.y * (badgeWidth / 2 + 4)
                badgeOffsetY = unitVector.x * (badgeHeight / 2 + 4)

                cpX, cpY = math.floor(xAverage), math.floor(yAverage)

                glyphEditView = self.controller.graphicView()
                try:
                    selection = glyphEditView.selectedLayerRange()
                except:
                    selection = glyphEditView.textStorage().selectedRange()
                origin = glyphEditView.cachedPositionAtIndex_(
                    selection.location)
                cpX = cpX * scale + origin[0]
                cpY = cpY * scale + origin[1]

                self.drawCoveringBadge(cpX - badgeWidth / 2 - badgeOffsetX,
                                       cpY - badgeHeight / 2 - badgeOffsetY,
                                       badgeWidth, badgeHeight, badgeRadius)
                self.drawText(string, (cpX - badgeOffsetX, cpY - badgeOffsetY))

        except:
            print traceback.format_exc()
            pass
コード例 #53
0
def text(textString, pt):
	# Draw a text on position "x", "y".
	NSString.stringWithString_(textString).drawAtPoint_withAttributes_(NSMakePoint(pt[0], pt[1]), {NSFontAttributeName: currentFont, NSForegroundColorAttributeName:currentFillColor})
コード例 #54
0
    def __init__(self, eventTypes, pathMode, pathString, whitelist, blacklist, ignoreSysFiles, ignoreDirEvents, proxy):
        """
            Set-up Monitor thread.
            
            After initialising the superclass and some instance variables
            try to create an FSEventStream. Throw an exeption if this fails.
            
            :Parameters:
                eventTypes : 
                    A list of the event types to be monitored.          
                    
                pathMode : 
                    The mode of directory monitoring: flat, recursive or following.

                pathString : string
                    A string representing a path to be monitored.
                  
                whitelist : list<string>
                    A list of files and extensions of interest.
                    
                blacklist : list<string>
                    A list of subdirectories to be excluded.

                ignoreSysFiles :
                    If true platform dependent sys files should be ignored.
                    
                monitorId :
                    Unique id for the monitor included in callbacks.
                    
                proxy :
                    A proxy to be informed of events
                    
        """
        AbstractPlatformMonitor.__init__(self, eventTypes, pathMode, pathString, whitelist, blacklist, ignoreSysFiles, ignoreDirEvents, proxy)
        self.log = logging.getLogger("fsserver."+__name__)
        
        #: an FSEvents.FSEventStream StreamRef object reference.
        self.streamRef = None
        #: FSEvents.CFRunLoop object reference.
        self.runLoopRef = None
        self.clientInfo = str(uuid.uuid1())
        #
        # Without using the mutable array, ie using the Python list directly, 
        # the code works but throws up a couple of horrible warnings:
        # "Oject of class OC_PythonArray autoreleased with no pool in place 
        #     - just leaking"
        # With the array there are still warnings about the strings whether 
        # Python native strings are used or NSStrings.
        #
        # All of these warnings are eliminated by using a pool for the lifetime 
        # of the NSMutableArray.
        #
        pool = NSAutoreleasePool.alloc().init()
        pathsToMonitor = NSMutableArray.alloc().init()
        ms = NSString.stringWithString_(self.pathsToMonitor)
        pathsToMonitor.insertObject_atIndex_(ms, 0)

        self.directory = fsDirectory.Directory(pathString=self.pathsToMonitor, 
                                            whitelist=self.whitelist,
                                            pathMode=self.pathMode)

        self.streamRef = FSEvents.FSEventStreamCreate(FSEvents.kCFAllocatorDefault,
                                self.callback,
                                self.clientInfo,
                                pathsToMonitor,
                                FSEvents.kFSEventStreamEventIdSinceNow,
                                1,
                                FSEvents.kFSEventStreamCreateFlagWatchRoot)
 
        #
        # Release the pool now that the NSMutableArray has been used.
        #
        del pool
             
        if self.streamRef == None:
            raise Exception('Failed to create FSEvent Stream')
            
        self.log.info('Monitor set-up on %s', str(self.pathsToMonitor))
        self.log.info('Monitoring %s events', str(self.eTypes))