Пример #1
0
    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()
Пример #2
0
def pre_appdata_use_startup(appdata_path):
    preload_dlls(unhandled_exc_handler)
    try:
        DOMAIN = NSString.alloc().initWithString_('com.apple.LaunchServices')
        KEYS = (NSString.alloc().initWithString_('LSArchitecturesForX86_64'), NSString.alloc().initWithString_('LSArchitecturesForX86_64v2'))
        APP = NSString.alloc().initWithString_('com.getdropbox.dropbox')
        UserDefaults = NSUserDefaults.standardUserDefaults()
        launchServices = UserDefaults.persistentDomainForName_(DOMAIN)
        if launchServices:
            for key in KEYS:
                apps = launchServices.objectForKey_(key)
                if apps and apps.get(APP):
                    apps.removeObjectForKey_(APP)
                    UserDefaults.setObject_forKey_(apps, key)
                    UserDefaults.setPersistentDomain_forName_(launchServices, DOMAIN)
                    UserDefaults.synchronize()
                    report_bad_assumption("User had 'Open using Rosetta' set.")

    except Exception:
        unhandled_exc_handler()

    if MAC_VERSION <= LEOPARD:
        try:
            psn = ProcessSerialNumber()
            Carbon.GetCurrentProcess(psn)
            TRACE('On Leopard or lower: PSN is %r', (psn.lowLongOfPSN, psn.highLongOfPSN))
        except Exception:
            unhandled_exc_handler()

    return arch.fixperms.check_and_fix_permissions(appdata_path)
Пример #3
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
        })
Пример #4
0
def input_box(title):
    box = NSAlert.alloc().init()
    box.addButtonWithTitle_(NSString.alloc().initWithString_("OK"))
    box.setMessageText_(NSString.alloc().initWithString_(title))
    textbox = NSTextField.alloc().initWithFrame_(NSMakeRect(0, 0, 200, 24));
    box.setAccessoryView_(textbox)
    box.runModal()
    return textbox.stringValue()
Пример #5
0
def volume_list(folders, delegate):
    volumes = NSMutableArray.alloc().init()
    volumes.addObject_(NSString.alloc().initWithString_(os.path.expanduser('~/Ubuntu One')))
    volumes.addObject_(NSString.alloc().initWithString_(os.path.expanduser('/Users/jose/Library/Application Support/ubuntuone')))
    
    for folder in folders:
        if (bool(folder['subscribed'])):
            volumes.addObject_(NSString.alloc().initWithString_(folder['path']))

    delegate.returnedVolumeList_(volumes)
Пример #6
0
def create_favitem(url=None, name=None):
    if name is None:
        # Make the display name the same as the URL by default
        name = url
    props = {
        NSString.stringWithString_('com.apple.LSSharedFileList.OverrideIcon.OSType'):
        NSString.stringWithString_(u'srvr')
    }
    props = NSDictionary.alloc().initWithDictionary_(props)
    return SFLListItem.alloc().initWithName_URL_properties_(
        name,
        NSURL.alloc().initWithString_(url), props)
Пример #7
0
def volume_list(folders, delegate):
    volumes = NSMutableArray.alloc().init()
    volumes.addObject_(NSString.alloc().initWithString_(
        os.path.expanduser('~/Ubuntu One')))
    volumes.addObject_(NSString.alloc().initWithString_(
        os.path.expanduser(
            '/Users/jose/Library/Application Support/ubuntuone')))

    for folder in folders:
        if (bool(folder['subscribed'])):
            volumes.addObject_(NSString.alloc().initWithString_(
                folder['path']))

    delegate.returnedVolumeList_(volumes)
Пример #8
0
	def add(self, label, uri, index=-1):
		if label in self.labels:
			return
		if index == -1 or index > len(self.items):
			index = len(self.items)
		elif index < -1:
			index = 0
		new_item = NSDictionary.alloc().initWithDictionary_(
			dict(
				Name=NSString.alloc().initWithString_(label), 
				URL=NSString.alloc().initWithString_(uri)
			)
		)
		self.items.insert(index, new_item)
		self.labels.append(label)
Пример #9
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)
Пример #10
0
 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)
Пример #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 _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]
Пример #13
0
    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))
Пример #14
0
    def executeFileAtPath_encoding_(self, path, encoding):
        """Execute file at path in an empty namespace. Update the engine
        user_ns with the resulting locals."""

        lines, err = NSString.stringWithContentsOfFile_encoding_error_(
            path, encoding, None)
        self.engine.execute(lines)
Пример #15
0
def get_public_files(public_files, path, delegate):
    for public_file in public_files:
        if public_file['path'] == path:
            delegate.returnedPublicLink_(NSString.alloc().initWithString_(
                public_file['public_url']))
            return None
    delegate.returnedPublicLink_(None)
Пример #16
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]))
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
Пример #18
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)
Пример #19
0
 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))
Пример #20
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)
Пример #21
0
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
Пример #22
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
Пример #23
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]
Пример #24
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)
Пример #25
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)
Пример #26
0
 def executeFileAtPath_encoding_(self, path, encoding):
     """Execute file at path in an empty namespace. Update the engine
     user_ns with the resulting locals."""
     
     lines,err = NSString.stringWithContentsOfFile_encoding_error_(
         path,
         encoding,
         None)
     self.engine.execute(lines)
Пример #27
0
def _value_to_nsobject(value, nstype):
    '''Convert a string with a type specifier to a native Objective-C NSObject (serializable).'''
    return {
        'string': lambda v: NSString.stringWithUTF8String_(v),
        'int': lambda v: NSNumber.numberWithInt_(v),
        'float': lambda v: NSNumber.numberWithFloat_(v),
        'bool': lambda v: True if v == 'true' else False,
        'data': lambda v: NSMutableData.dataWithLength_(len(value)).initWithBase64EncodedString_options_(value)
    }[nstype](value)
Пример #28
0
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"]
Пример #29
0
def _valueToNSObject(value, nstype):
    '''Convert a string with a type specifier to a native Objective-C NSObject (serializable).'''
    return {
        'string': lambda v: NSString.stringWithUTF8String_(v),
        'int': lambda v: NSNumber.numberWithInt_(v),
        'float': lambda v: NSNumber.numberWithFloat_(v),
        'bool': lambda v: True if v == 'true' else False,
        'data': lambda v: NSData.initWithBytes_length_(v, len(v))
    }[nstype](value)
Пример #30
0
def _valueToNSObject(value, nstype):
    '''Convert a string with a type specifier to a native Objective-C NSObject (serializable).'''
    return {
        'string': lambda v: NSString.stringWithUTF8String_(v),
        'int': lambda v: NSNumber.numberWithInt_(v),
        'float': lambda v: NSNumber.numberWithFloat_(v),
        'bool': lambda v: True if v == 'true' else False,
        'data': lambda v: NSData.initWithBytes_length_(v, len(v))
    }[nstype](value)
Пример #31
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)
Пример #32
0
def _value_to_nsobject(value, nstype):
    '''Convert a string with a type specifier to a native Objective-C NSObject (serializable).'''
    return {
        'string': lambda v: NSString.stringWithUTF8String_(v),
        'int': lambda v: NSNumber.numberWithInt_(v),
        'float': lambda v: NSNumber.numberWithFloat_(v),
        'bool': lambda v: True if v == 'true' else False,
        'data': lambda v: NSMutableData.dataWithLength_(len(value)).initWithBase64EncodedString_options_(value)
    }[nstype](value)
Пример #33
0
	def _fetchLists(self):
		"""A private convenience function that uses BeautifulSoup (for parsing) and NSString (for authentication) 
		to make combing the HTML code from the main page of lists a bit easier."""
		page = NSString.stringWithContentsOfURL_(NSURL.URLWithString_("http://%s.tadalist.com/lists" % (self.username)))
		soup = BeautifulSoup(page)
		rawLists = soup.findAll('li')
		lists = []
		for rawList in rawLists:
			lists.append( TadaList(rawList.a['href'], rawList.a.contents[0], self) )
		return lists	
Пример #34
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)
Пример #35
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
            ]))
Пример #36
0
	def _fetchItems(self, force=True):
		"""Private method that fetches attributes off of the list's page, parses the HTML (with BeautifulSoup),
		and then creates TadaItems.  This is called automatically when a user requests the 'items' of a TadaList."""
		page = NSString.stringWithContentsOfURL_(NSURL.URLWithString_(self._url()))
		soup = BeautifulSoup(page)
		lis = soup.findAll('li')
		items = []
		for li in lis: 
			items.append(TadaItem(li.form.contents[-1].strip(), li['id'][5:], self))
		self.items = items
		return self.items
Пример #37
0
def _normalize_darwin_path(filename, canonicalise=False):

    if canonicalise:
        filename = os.path.realpath(filename)
    filename = os.path.normpath(filename)

    decoded = filename.decode("utf-8", "quodlibet-osx-path-decode")

    try:
        return NSString.fileSystemRepresentation(decoded)
    except ValueError:
        return filename
Пример #38
0
    def __normalize_path_batch(self, paths):
        pool = NSAutoreleasePool.alloc().init()
        try:
            results = []
            for path in paths:
                assert isinstance(path, unicode)
                s = NSString.alloc().initWithString_(path).autorelease()
                ret = s.fileSystemRepresentation()
                results.append(ret.decode('UTF-8'))

            return results
        finally:
            del pool
Пример #39
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
Пример #40
0
    def _decodeData(self, url, data, error):
        if error:
            logger.error("Cannot read url '%s'" % url)
            logger.error("Error '%s'" % error)
            return

        data = NSString.alloc().initWithData_encoding_(data, NSUTF8StringEncoding)
        try:
            extensionData = json.loads(data)
            return extensionData.get('extensions', [])
        except json.JSONDecodeError as e:
            logger.error("Cannot decode extension data at '%s'" % url)
            logger.error("Error '%s'" % e)
Пример #41
0
def set_user_interface_language(code):
    if platform == 'mac':
        from Foundation import NSAutoreleasePool, NSString, NSUserDefaults
        arp = NSAutoreleasePool.alloc().init()
        s = NSString.alloc().initWithString_(APPLE_LANGUAGES)
        defaults = NSUserDefaults.standardUserDefaults()
        if code == '':
            TRACE('Setting language defaults to system language.')
            defaults.removeObjectForKey_(s)
        else:
            TRACE('Updating language defaults to %r.', code)
            defaults.setObject_forKey_([code], s)
        defaults.synchronize()
Пример #42
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)
Пример #43
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
Пример #44
0
    def _fetchLists(self):
        """A private convenience function that uses BeautifulSoup (for parsing) and NSString (for authentication) 
		to make combing the HTML code from the main page of lists a bit easier."""
        page = NSString.stringWithContentsOfURL_(
            NSURL.URLWithString_("http://%s.tadalist.com/lists" %
                                 (self.username)))
        soup = BeautifulSoup(page)
        rawLists = soup.findAll('li')
        lists = []
        for rawList in rawLists:
            lists.append(
                TadaList(rawList.a['href'], rawList.a.contents[0], self))
        return lists
Пример #45
0
    def _fetchItems(self, force=True):
        """Private method that fetches attributes off of the list's page, parses the HTML (with BeautifulSoup),
		and then creates TadaItems.  This is called automatically when a user requests the 'items' of a TadaList."""
        page = NSString.stringWithContentsOfURL_(
            NSURL.URLWithString_(self._url()))
        soup = BeautifulSoup(page)
        lis = soup.findAll('li')
        items = []
        for li in lis:
            items.append(
                TadaItem(li.form.contents[-1].strip(), li['id'][5:], self))
        self.items = items
        return self.items
Пример #46
0
 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
Пример #47
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
Пример #48
0
def _normalize_darwin_path(filename, canonicalise=False):

    filename = path2fsn(filename)

    if canonicalise:
        filename = os.path.realpath(filename)
    filename = os.path.normpath(filename)

    data = fsn2bytes(filename, "utf-8")
    decoded = data.decode("utf-8", "quodlibet-osx-path-decode")

    try:
        return bytes2fsn(NSString.fileSystemRepresentation(decoded), "utf-8")
    except ValueError:
        return filename
Пример #49
0
def _mac_get_system_languages():
    assert platform == 'mac'
    from Foundation import NSAutoreleasePool, NSString, NSUserDefaults
    arp = NSAutoreleasePool.alloc().init()
    s = NSString.alloc().initWithString_(APPLE_LANGUAGES)
    try:
        from pymac.helpers.core import get_preference
        langs = list(get_preference('com.apple.systempreferences', APPLE_LANGUAGES))
        TRACE('_mac_get_system_languages real: %r', langs)
        return langs
    except Exception:
        unhandled_exc_handler()

    langs = NSUserDefaults.standardUserDefaults().get(s)
    TRACE('_mac_get_system_languages from user: %r', langs)
    return langs
Пример #50
0
def _normalize_darwin_path(filename, canonicalise=False):

    filename = path2fsn(filename)

    if canonicalise:
        filename = os.path.realpath(filename)
    filename = os.path.normpath(filename)

    data = fsn2bytes(filename, "utf-8")
    decoded = data.decode("utf-8", "quodlibet-osx-path-decode")

    try:
        return bytes2fsn(
            NSString.fileSystemRepresentation(decoded), "utf-8")
    except ValueError:
        return filename
Пример #51
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
Пример #52
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)
Пример #53
0
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
Пример #54
0
    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)
Пример #55
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))
Пример #56
0
    def _checkURLCallback(self, url, data, error):
        self._valid = True
        self._validation_report = ""

        if error:
            self._valid = False
            self._validation_report = "Cannot load url '%s'" % url
            logger.error(self._validation_report)
            self.showMessage("Invalid URL", self._validation_report)
            return

        data = NSString.alloc().initWithData_encoding_(data,
                                                       NSUTF8StringEncoding)
        try:
            _data = json.loads(data)
            extensionData = _data['extensions']
        except Exception as e:
            self._valid = False
            self._validation_report = "Cannot validate url '%s'" % url
            logger.error(self._validation_report)
            logger.error(e)
            self.showMessage("Invalid URL", self._validation_report)
            return

        if url in self._existingURLs:
            self._valid = False
            self._validation_report = "URL already existing"
            self.showMessage("Invalid URL", self._validation_report)
            return

        if not self._valid:
            self.showMessage(
                "Not a valid extension json URL.",
                "The url '%s' is not a valid. \n\n%s" %
                (self.w.url.get(), self._validation_report))

        # everything’s valid, proceed with the add
        if self._callback:
            self._callback(self)
Пример #57
0
def imshow_image(title, image):
    from PIL import Image
    from io import BytesIO
    from pyto import QuickLookHelper
    import base64
    import threading
    
    image = Image.fromarray(image)
    buffered = BytesIO()
    
    try:
        image.save(buffered, format="JPEG")
    except OSError:
        return
    
    img_str = base64.b64encode(buffered.getvalue())
    img_str = NSString.alloc().initWithUTF8String(img_str)
   
    try:
        QuickLookHelper.previewFile(img_str, script=threading.current_thread().script_path, removePrevious=True)
    except AttributeError:
        QuickLookHelper.previewFile(img_str, script=None, removePrevious=True)
Пример #58
0
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
def io_key_string_value(keyname):
    """Converts NSData/CFData return value to an NSString"""
    raw_value = io_key(keyname)
    return NSString.alloc().initWithData_encoding_(
        raw_value, NSUTF8StringEncoding).rstrip('\0')