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
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
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()
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
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)
def _to_clipboard(s): 'Mac only' from AppKit import NSPasteboard, NSArray pb = NSPasteboard.generalPasteboard() pb.clearContents() a = NSArray.arrayWithObject_(s) pb.writeObjects_(a)
def _toPasteBoard(self, text): pb = NSPasteboard.generalPasteboard() pb.clearContents() pb.declareTypes_owner_([ NSPasteboardTypeString, ], None) pb.setString_forType_(text, NSPasteboardTypeString)
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
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;
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"
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)
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()
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
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('出错啦')
def get_text_from_clipboard(self): try: pb = NSPasteboard.generalPasteboard() if not pb: return '' clipboard_string = pb.stringForType_(NSStringPboardType) if clipboard_string is None: return '' return clipboard_string except Exception: unhandled_exc_handler() return ''
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
def _macosx(self, text): # # taken from: http://stackoverflow.com/a/3555675 # from AppKit import NSPasteboard, NSArray pb = NSPasteboard.generalPasteboard() pb.clearContents() a = NSArray.arrayWithObject_(text) pb.writeObjects_(a) def clearit(): pb.clearContents() return clearit
def _copy_to_clipboard(arg): arg = str(globals().get(arg) or arg) if sys.platform == 'darwin': pb = NSPasteboard.generalPasteboard() pb.clearContents() a = NSArray.arrayWithObject_(arg) pb.writeObjects_(a) elif sys.platform.startswith('linux'): p = Popen(['xsel', '-pi'], stdin=PIPE) p.communicate(input=arg) print 'Copied to clipboard!'
def share_path(path, access_token): api_client = client.DropboxClient(access_token) try: url = api_client.share(path)['url'] pb = NSPasteboard.generalPasteboard() pb.clearContents() a = NSArray.arrayWithObject_(url) pb.writeObjects_(a) print 'Link copied to clipboard' except rest.ErrorResponse, e: print e.user_error_msg or str(e)
def copy_result(self, sender): from string import strip from AppKit import NSPasteboard, NSArray s = u"" results = self.w.font_list.getSelection() for i in results: s += self.w.font_list.get()[i]["Font"] + "\n\n" s += self.w.font_list.get()[i]["Result"] + "\n\n\n" pb = NSPasteboard.generalPasteboard() pb.clearContents() a = NSArray.arrayWithObject_(s.strip("\n")) pb.writeObjects_(a)
def copy(self): if 'indows' in platform.system(): try: import clipboard clipboard.copy(self.data) return clipboard.paste() except: import win32clipboard as w import win32con w.OpenClipboard() w.EmptyClipboard() w.SetClipboardData(w.CF_TEXT, self.data) return w.GetClipboardData(win32con.CF_TEXT) elif 'inux' in platform.system(): try: import clipboard clipboard.copy(self.data) return clipboard.paste() except: try: check_01 = os.system('which xsel') if check_01 != '': from subprocess import Popen, PIPE p = Popen(['xsel','-pi'], stdin=PIPE) p.communicate(input='data') return os.popen('xsel').read() else: return "\tplease install xsel (apt-get xsel) or clipboard (pypi)\n\tOn Windows you must install pywin32 (pypi) or clipboard (pypi)\n" except: if self.check_call('xsel') == 0: from subprocess import Popen, PIPE p = Popen(['xsel','-pi'], stdin=PIPE) p.communicate(input='data') return os.popen('xsel').read() else: return "\tplease install xsel (apt-get xsel) or clipboard (pypi)\n\tOn Windows you must install pywin32 (pypi) or clipboard (pypi)\n" elif 'arwin' in platform.system(): os.system("echo '%s' | pbcopy" % self.data) from AppKit import NSPasteboard from LaunchServices import * pb = NSPasteboard.generalPasteboard() text = pb.stringForType_(kUTTypeUTF8PlainText) return text else: print "\t you not in Windows, Linux or Mac, this support for windows/linux/mac yet"
def get_clipboard_html(): """returns html in clipboard, if any""" if 'darwin' in sys.platform: if NSPasteboard is None: raise Exception('AppKit not found, first run `pip install pyobjc`') pb = NSPasteboard.generalPasteboard() return pb.stringForType_('public.html') elif 'linux' in sys.platform: if Gtk is None: raise Exception('Could not import GTK, is it installed on this system?') cb = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) html_target = Gdk.Atom.intern('text/html', False) targets = cb.wait_for_targets()[1] if html_target not in targets: return None return cb.wait_for_contents(html_target).get_data() else: raise Exception('Platform "{}" is not supported'.format(sys.platform))
def run(): iCal = app(id='com.apple.iCal') iCal.activate() app(id='com.apple.systemevents').keystroke('c', using=k.command_down) eventString = NSPasteboard.generalPasteboard().readObjectsForClasses_options_( [NSString], {})[0] calendar_names = iCal.calendars[its.writable == True].name.get() sa = OSAX(id='com.apple.iCal', terms=standardadditions) calendar_name = sa.choose_from_list(calendar_names, with_title='Duplicate', with_prompt="Copy event to calendar:", default_items=[calendar_names[0]], OK_button_name="Duplicate", multiple_selections_allowed=False, empty_selection_allowed=False) if not calendar_name: sys.exit(0) calendar_name = calendar_name[0] p = {} p[k.summary], dates, other = eventString.split('\n', 2) date, start, end = re.match(r'scheduled (.+) from (.+) to (.+)', dates).groups() p[k.start_date] = parse_date_time(date, start) p[k.end_date] = parse_date_time(date, end) if other.startswith('Location: '): location, p[k.description] = other.split('\n', 1) p[k.location] = location.split(': ', 1)[1] else: p[k.description] = other event = iCal.calendars[calendar_name].make(new=k.event, with_properties=p) event.make(new=k.sound_alarm, with_properties={ k.trigger_interval: -10, k.sound_name: 'Basso'})
def _copy_to_clipboard(arg): import sys if sys.platform == 'darwin': from AppKit import NSPasteboard, NSArray elif sys.platform.startswith('linux'): from subprocess import Popen, PIPE else: raise ImportError("Clip magic only works on osx or linux!") arg = str(globals().get(arg) or arg) if sys.platform == 'darwin': pb = NSPasteboard.generalPasteboard() pb.clearContents() a = NSArray.arrayWithObject_(arg) pb.writeObjects_(a) elif sys.platform.startswith('linux'): p = Popen(['xsel', '-pi'], stdin=PIPE) p.communicate(input=arg) print('Copied to clipboard!')
def write_text(text, paste=False): '''send text formatted exactly as written to active window. will use pbpaste clipboard to paste the text instead of typing it.''' logging.debug("text = %s paste = %s" % (text, paste)) if text: # get current clipboard contents pb = NSPasteboard.generalPasteboard() classes = NSArray.arrayWithObject_(objc.lookUpClass('NSString')) options = NSDictionary.dictionary() items = NSArray(pb.readObjectsForClasses_options_(classes, options)) # copy our text to clipboard a = NSArray.arrayWithObject_(text) pb.clearContents() pb.writeObjects_(a) # paste key_press('v', 'super') pause(500) # return original text to clipboard pb.clearContents() pb.writeObjects_(items)
def to_clipboard(value): from AppKit import NSPasteboard pb = NSPasteboard.generalPasteboard() pb.clearContents() pb.writeObjects_([value])
# Copyright (C) 2012, 2013 Antoine Martin <*****@*****.**> # Xpra is released under the terms of the GNU GPL v2, or, at your option, any # later version. See the file COPYING for details. import gobject from xpra.clipboard.gdk_clipboard import GDKClipboardProtocolHelper from xpra.clipboard.clipboard_base import ClipboardProxy, TEXT_TARGETS, debug, log def update_clipboard_change_count(): return 0 change_callbacks = [] change_count = 0 try: from AppKit import NSPasteboard #@UnresolvedImport pasteboard = NSPasteboard.generalPasteboard() if pasteboard is None: log.warn("cannot load Pasteboard, maybe not running from a GUI session?") else: def update_clipboard_change_count(): global change_count change_count = pasteboard.changeCount() return change_count def timer_clipboard_check(): global change_count c = change_count change_count = pasteboard.changeCount() debug("timer_clipboard_check() was %s, now %s", c, change_count) if c!=change_count: for x in change_callbacks: try:
def __init__(self): self.pasteboard = NSPasteboard.generalPasteboard() self.current_count = -1
def sendToClipBoard(string): pasteboard = NSPasteboard.generalPasteboard() emptyOwner = NSObject.alloc().init() pasteboard.declareTypes_owner_([NSStringPboardType], emptyOwner) pasteboard.setString_forType_(string, NSStringPboardType)
def copy_to_clipboard(text): NSPasteboard.generalPasteboard().clearContents() NSPasteboard.generalPasteboard().setString_forType_(text, NSPasteboardTypeString)