当前位置: 首页>>代码示例>>Python>>正文


Python AppKit.NSPasteboard类代码示例

本文整理汇总了Python中AppKit.NSPasteboard的典型用法代码示例。如果您正苦于以下问题:Python NSPasteboard类的具体用法?Python NSPasteboard怎么用?Python NSPasteboard使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了NSPasteboard类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: macpaste

def macpaste():
    from AppKit import NSPasteboard
    pb = NSPasteboard.generalPasteboard()
    lastitems = [None]

    def paste():
        items = pb.pasteboardItems()
        if lastitems[0] == items:
            return False # if the clipboard did not change, return False, more performance
        else:
            lastitems[0] = items
            
        links = set()
        for item in items:
            types = set(item.types())
            if "public.html" in types:
                links.update(extracthtml(item.dataForType_("public.html").bytes().tobytes()))
            if "public.url" in types:
                links.add(item.stringForType_("public.url"))
            if "public.rtf" in types:
                # find HYPERLINK, used especially by safari and adium
                links.update(re.findall(r'HYPERLINK "(.*?)"', item.stringForType_("public.rtf")))
            for t in types:
                m = re.match("public.(.*?)-plain-text", t)
                if m:
                    try:
                        encoding = m.group(1)
                        f = encoding.find("-external")
                        if f > 0:
                            encoding = encoding[:f]
                        data = item.dataForType_(t).bytes().tobytes().decode(encoding)
                    except LookupError:
                        continue
                    if data:
                        links |= hoster.collect_links(data)
                    break # do not parse multiple encodings
        return links
    return paste
开发者ID:Werniman,项目名称:client,代码行数:38,代码来源:clipboard_monitor.py

示例2: get_paste_img_file

def get_paste_img_file():
    pb = NSPasteboard.generalPasteboard()
    data_type = pb.types()
    # if img file
    print data_type
    now = int(time.time() * 1000)  # used for filename
    if NSPasteboardTypePNG in data_type:
        # png
        data = pb.dataForType_(NSPasteboardTypePNG)
        filename = "%s.png" % now
        filepath = "/tmp/%s" % filename
        ret = data.writeToFile_atomically_(filepath, False)
        if ret:
            return filepath
    elif NSPasteboardTypeTIFF in data_type:
        # tiff
        data = pb.dataForType_(NSPasteboardTypeTIFF)
        filename = "%s.tiff" % now
        filepath = "/tmp/%s" % filename
        ret = data.writeToFile_atomically_(filepath, False)
        if ret:
            return filepath
    elif NSPasteboardTypeString in data_type:
        # string todo, recognise url of png & jpg
        pass
开发者ID:jay61439476,项目名称:markdown-img-upload,代码行数:25,代码来源:clipboard.py

示例3: __init__

 def __init__(self, **kwds):
     self._ns_app = Globals.ns_application
     self._ns_app.pygui_app = self
     self._ns_pasteboard = NSPasteboard.generalPasteboard()
     self._ns_key_window = None
     GApplication.__init__(self, **kwds)
     self.ns_init_application_name()
开发者ID:karlmatthew,项目名称:pygtk-craigslist,代码行数:7,代码来源:Application.py

示例4: readAICBFromPasteboard

def readAICBFromPasteboard():
    """
    get the AICB data from the NSPasteboard
    """
    from AppKit import NSPasteboard
    pb = NSPasteboard.generalPasteboard()
    types = [
        "CorePasteboardFlavorType 0x41494342",
        "com.adobe.encapsulated-postscript"
    ]
    data = None
    for typ in types:
        data = pb.dataForType_(typ)
        if data is not None:
            break
    if not data:
        return None
    data = data.bytes()
    try:
        if isinstance(data, memoryview):
            data = data.tobytes()
    except NameError:
        pass
    data = str(data)
    return data
开发者ID:LettError,项目名称:aicbTools,代码行数:25,代码来源:aicbTools.py

示例5: copy

def copy(data, uti='public.utf8-plain-text', private=True):
    """Put ``data`` on pasteboard with type ``uti``.

    If ``private`` is ``True`` (the default), the data are
    marked as "concealed", so clipboard managers will ignore
    them.

    Args:
        data (object): Data to put on pasteboard
        uti (str, optional): UTI for data
        private (bool, optional): Whether to hide the data from
            clipboard managers
    """
    pbdata = {uti: data}
    if private:
        pbdata[UTI_PRIVATE] = 'whateva'

    pboard = NSPasteboard.generalPasteboard()
    pboard.clearContents()

    for uti, data in pbdata.items():
        if isinstance(uti, unicode):
            uti = uti.encode('utf-8')

        pboard.setData_forType_(nsdata(data), uti)
开发者ID:TravisCarden,项目名称:dotfiles,代码行数:25,代码来源:pasteboard.py

示例6: _to_clipboard

def _to_clipboard(s):
    'Mac only'
    from AppKit import NSPasteboard, NSArray
    pb = NSPasteboard.generalPasteboard()
    pb.clearContents()
    a = NSArray.arrayWithObject_(s)
    pb.writeObjects_(a)
开发者ID:nishio,项目名称:idea-generation,代码行数:7,代码来源:workbench.py

示例7: _toPasteBoard

 def _toPasteBoard(self, text):
     pb = NSPasteboard.generalPasteboard()
     pb.clearContents()
     pb.declareTypes_owner_([
         NSPasteboardTypeString,
     ], None)
     pb.setString_forType_(text,  NSPasteboardTypeString)
开发者ID:LettError,项目名称:glyphBrowser,代码行数:7,代码来源:browser.py

示例8: get_paste_img_file

def get_paste_img_file():
    ''' get a img file from clipboard;
    the return object is a `tempfile.NamedTemporaryFile`
    you can use the name field to access the file path.
    the tmp file will be delete as soon as possible(when gc happened or close explicitly)
    you can not just return a path, must hold the reference'''

    pb = NSPasteboard.generalPasteboard()
    data_type = pb.types()
    # if img file
    print data_type
    # always generate png format img
    png_file = tempfile.NamedTemporaryFile(suffix="png")

    supported_image_format = (NSPasteboardTypePNG, NSPasteboardTypeTIFF)
    if NSPasteboardTypeString in data_type:
        # make this be first, because plain text may be TIFF format?
        # string todo, recognise url of png & jpg
        pass
    elif any(filter(lambda f: f in data_type, supported_image_format)):
        # do not care which format it is, we convert it to png finally
        # system screen shotcut is png, QQ is tiff
        tmp_clipboard_img_file = tempfile.NamedTemporaryFile()
        print tmp_clipboard_img_file.name
        data = pb.dataForType_(NSPasteboardTypePNG)
        ret = data.writeToFile_atomically_(tmp_clipboard_img_file.name, False)
        if not ret: return

        # convert it to png file
        os.system('sips -s format png %s --out %s' % (tmp_clipboard_img_file.name, png_file.name))

        # close the file explicitly
        tmp_clipboard_img_file.close()
        return png_file
开发者ID:wolflee,项目名称:markdown-img-upload,代码行数:34,代码来源:clipboard.py

示例9: uploadNewScreenshots

def uploadNewScreenshots():
	# Get a list of filenames in the watch directory
	files = os.listdir(WATCH_PATH)
	
	lastUploadedFile = None
	screenshots = []
	
	# See if there are any screenshots to upload
	# Make sure we haven't already uploaded it
	for filename in files:
		if MAC_SCREENSHOT_REGEX.match(filename) and not macgrab.isUploaded(filename):
			screenshots.append(filename)
		
		# Proceed if there was a new screen shot
		if len(screenshots) > 0:
			logging.info("Found screenshots to upload: %s" % screenshots)
			
			for screenshot in screenshots:
			
				# Attempt to upload the image
				status, resp = macgrab.upload(os.path.join(WATCH_PATH, screenshot))
	
				# If it worked, tell us the URL, else tell us what went wrong.
				if status != True:
					print "There was an error while trying to upload the screenshot: %s" % resp
					continue
	
				# print to std out for simple copy/paste
				print "Screenshot uploaded successfully! URL is %s" % resp['original_image']
	
				# returns url
				lastUploadedFile = [resp['original_image']]
	
				# Add the screenshot to the list of already uploaded shots
				macgrab.addUploaded(screenshot)
	
				# If we're told to, delete the screenshot afterwards
				try:
					delshot = CONFIG.getboolean('general', 'post_delete')
				except NoOptionError:
					delshot = False
				
				if delshot:
					os.remove(os.path.join(WATCH_PATH, screenshot))
	
			# Steps to take after a file has been uploaded
			if lastUploadedFile != None:
				
				# verbose notification
				macgrab.say("uploaded screen shot")
			
				# Now copy the URL to the clipboard
				pb = NSPasteboard.generalPasteboard()
				pb.clearContents()
				pb.writeObjects_(lastUploadedFile)
				
				# clear last uploaded file var
				lastUploadedFile = None;
开发者ID:stevenleeg,项目名称:Macgrab,代码行数:58,代码来源:watcher.py

示例10: get_paste_img_file

def get_paste_img_file():
    """ get a img file from clipboard;
    the return object is a `tempfile.NamedTemporaryFile`
    you can use the name field to access the file path.
    the tmp file will be delete as soon as possible(when gc happened or close explicitly)
    you can not just return a path, must hold the reference"""

    pb = NSPasteboard.generalPasteboard()
    data_type = pb.types()

    supported_image_format = (NSPasteboardTypePNG, NSPasteboardTypeTIFF)
    if NSFilenamesPboardType in data_type:
        # file in clipboard
        img_path = pb.propertyListForType_(NSFilenamesPboardType)[0]
        img_type = imghdr.what(img_path)

        if not img_type:
            # not image file
            return NONE_IMG

        if img_type not in ("png", "jpeg", "gif"):
            # now only support png & jpg & gif
            return NONE_IMG

        is_gif = img_type == "gif"
        _file = tempfile.NamedTemporaryFile(suffix=img_type)
        tmp_clipboard_img_file = tempfile.NamedTemporaryFile()
        shutil.copy(img_path, tmp_clipboard_img_file.name)
        if not is_gif:
            _convert_to_png(tmp_clipboard_img_file.name, _file.name)
        else:
            shutil.copy(tmp_clipboard_img_file.name, _file.name)
        tmp_clipboard_img_file.close()
        return _file, False, "gif" if is_gif else "png"

    if NSPasteboardTypeString in data_type:
        # make this be first, because plain text may be TIFF format?
        # string todo, recognise url of png & jpg
        pass

    if any(filter(lambda f: f in data_type, supported_image_format)):
        # do not care which format it is, we convert it to png finally
        # system screen shotcut is png, QQ is tiff
        tmp_clipboard_img_file = tempfile.NamedTemporaryFile()
        print tmp_clipboard_img_file.name
        png_file = tempfile.NamedTemporaryFile(suffix="png")
        for fmt in supported_image_format:
            data = pb.dataForType_(fmt)
            if data:
                break
        ret = data.writeToFile_atomically_(tmp_clipboard_img_file.name, False)
        if not ret:
            return NONE_IMG

        _convert_to_png(tmp_clipboard_img_file.name, png_file.name)
        # close the file explicitly
        tmp_clipboard_img_file.close()
        return png_file, True, "png"
开发者ID:tiann,项目名称:markdown-img-upload,代码行数:58,代码来源:clipboard.py

示例11: sendToClipBoard

def sendToClipBoard(string):
	if removeAnsiCodes == True:
		r= re.compile("\033\[[0-9;]+m") 
		string = r.sub("", string)

	from AppKit import NSPasteboard,NSObject,NSStringPboardType
	pasteboard = NSPasteboard.generalPasteboard()
	emptyOwner = NSObject.alloc().init()
	pasteboard.declareTypes_owner_([NSStringPboardType], emptyOwner)
	pasteboard.setString_forType_(string, NSStringPboardType)
开发者ID:mondopiccolo,项目名称:iterm2clip,代码行数:10,代码来源:iterm2clip.py

示例12: to_clipboard

def to_clipboard(value):
	if sys.platform.startswith('darwin'):
		from AppKit import NSPasteboard
		pb = NSPasteboard.generalPasteboard()
		pb.clearContents()
		pb.writeObjects_([value])
	elif sys.platform.startswith('win32'):
		import win32clipboard
		win32clipboard.OpenClipboard()
		win32clipboard.SetClipboardText(value)
		win32clipboard.CloseClipboard()
开发者ID:cwaldren,项目名称:boo,代码行数:11,代码来源:boom.py

示例13: get_AppKit_Pasteboard_changeCount

def get_AppKit_Pasteboard_changeCount():
    """ PyObjC AppKit implementation to access Pasteboard's changeCount """
    from AppKit import NSPasteboard      #@UnresolvedImport
    pasteboard = NSPasteboard.generalPasteboard()
    if pasteboard is None:
        log.warn("cannot load Pasteboard, maybe not running from a GUI session?")
        return None

    def get_change_count():
        return pasteboard.changeCount()
    return get_change_count
开发者ID:svn2github,项目名称:Xpra,代码行数:11,代码来源:osx_clipboard.py

示例14: copyToClipboard

def copyToClipboard():
    try:
        word = b64decode(alfred.argv(2))
        pb = NSPasteboard.generalPasteboard()
        pb.clearContents()
        a = NSArray.arrayWithObject_(word)
        pb.writeObjects_(a)
        alfred.exit('已拷贝地址到剪切板')
    except Exception, e:
        alfred.log(e)
        alfred.exit('出错啦')
开发者ID:davidwangsg,项目名称:alfred-workflows,代码行数:11,代码来源:action.py

示例15: setClipboard

def setClipboard( myText ):
	"""
	Sets the contents of the clipboard to myText.
	Returns True if successful, False if unsuccessful.
	"""
	try:
		myClipboard = NSPasteboard.generalPasteboard()
		myClipboard.declareTypes_owner_( [NSStringPboardType], None )
		myClipboard.setString_forType_( myText, NSStringPboardType )
		return True
	except Exception as e:
		return False
开发者ID:eliheuer,项目名称:glyphs-scripts,代码行数:12,代码来源:Copy+Glyph+Name+List.py


注:本文中的AppKit.NSPasteboard类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。