Exemple #1
1
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
Exemple #2
0
def getClipboardData(projDir="."):
    """获取剪贴板的内容。
    
    Keyword Arguments:
        projectDir {str} -- 项目路径。当剪贴板数据是图片时,会将图片保存到此路径中。 (default: {"."})
    
    Returns:
        string, string -- 第一返回值是剪贴板数据的类型。第二返回值是剪贴板的数据,若类型为图片则返回值为路径。
    """
    t = getClipboardDataType()
    if OS_CUR == OS_WINDOWS:
        if t == TYPE_STRING:
            wcb.OpenClipboard()
            data = wcb.GetClipboardData(wcb.CF_TEXT)
            wcb.CloseClipboard()
            # print(data)
            data = str(data, 'gbk')
            data = data.replace('\r', '')
        elif t == TYPE_PNG:
            # import win32ui

            # wcb.OpenClipboard()
            # data = wcb.GetClipboardData(wcb.CF_BITMAP) # 这是个句柄,不知道怎么用
            # wcb.CloseClipboard()

            # dc = win32ui.CreateDCFromHandle(data)

            # bmp = win32ui.CreateBitmapFromHandle(data)
            # # print(dir(bmp))
            # bmp.SaveBitmapFile(dc, '123.png')

            from PIL import ImageGrab
            img = ImageGrab.grabclipboard()
            data = '%s/%s' % (projDir, 'data.png')
            img.save(data, 'png')

        else:
            exit(2)

    elif OS_CUR == OS_MAC:
        if t == TYPE_STRING:
            pb = NSPasteboard.generalPasteboard()
            data = pb.dataForType_(NSPasteboardTypeString)
            data = str(data, 'utf-8')

        elif t == TYPE_PNG:
            pb = NSPasteboard.generalPasteboard()
            img = pb.dataForType_(NSPasteboardTypePNG)
            data = '%s/%s' % (projDir, 'data.png')
            img.writeToFile_atomically_(data, False)  # 将剪切板数据保存为文件

        else:
            exit(2)

    return t, data
Exemple #3
0
def get_pasteboard_img():
    """
    Get image from pasteboard/clipboard and save to file 
    DEPRECATED: FOR THE REASON IT ONLY GENERATES TIFF IMAGE FROM CLIPBOARD
    WHICH MAKES TO BE NEEDED ONE MORE FUNCTION TO CONVERT IMAGE TO PNG
    """
    pb = NSPasteboard.generalPasteboard()  # Get data object from clipboard
    data_type = pb.types()  # Get type of the data

    # Recognize data type for furher processing
    if NSPasteboardTypePNG in data_type:  # PNG:
        # Get data content by data type
        data = pb.dataForType_(NSPasteboardTypePNG)
        filename = '%d.png' % int(time.time() * 1000)
    elif NSPasteboardTypeTIFF in data_type:  # TIFF: most probablly it's tiff
        data = pb.dataForType_(NSPasteboardTypeTIFF)
        filename = '%d.tiff' % int(time.time() * 1000)
    elif NSPasteboardTypeString in data_type:  # Text: if it's already a filepath then just return it
        data = str(pb.dataForType_(NSPasteboardTypeString))
        return data if os.path.exists(data) else None
    else:
        return None

    # Write data to a local file
    filepath = '/tmp/%s' % filename
    success = data.writeToFile_atomically_(filepath, False)

    return filepath if success else None
Exemple #4
0
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
Exemple #5
0
def get_paste_img_file(filepath):
    """
    将剪切板数据保存到本地文件并返回文件路径
    """
    pb = NSPasteboard.generalPasteboard()  # 获取当前系统剪切板数据
    data_type = pb.types()  # 获取剪切板数据的格式类型

    # 根据剪切板数据类型进行处理
    if NSPasteboardTypePNG in data_type:          # PNG处理
        data = pb.dataForType_(NSPasteboardTypePNG)
        # print('png: '+str(type(data)))
        # filename = 'HELLO_PNG.png'
        # filepath = 'tmp/%s' % filename            # 保存文件的路径
        ret = data.writeToFile_atomically_(filepath, False)    # 将剪切板数据保存为文件
        if ret:   # 判断文件写入是否成功
            return data
    elif NSPasteboardTypeTIFF in data_type:         #TIFF处理: 一般剪切板里都是这种
        # tiff
        data = pb.dataForType_(NSPasteboardTypeTIFF)
        # print('tiff: '+str(type(data)))
        filename = 'HELLO_TIFF.tiff'
        filepath = '/tmp/%s' % filename
        ret = data.writeToFile_atomically_(filepath, False)
        if ret:
            return data
    elif NSPasteboardTypeString in data_type:
        # string todo, recognise url of png & jpg
        pass
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
Exemple #7
0
def run(options):
    elapsed_time = 0
    monitor_time = int(options["monitor_time"])
    output_file = options["output_file"]

    previous = ""

    while elapsed_time <= monitor_time:
        try:
            pasteboard = NSPasteboard.generalPasteboard()
            pasteboard_string = pasteboard.stringForType_(NSStringPboardType)

            if pasteboard_string != previous:
                if output_file:
                    with open(output_file, "a+") as out:
                        out.write(pasteboard_string + "\n")
                else:
                    st = datetime.fromtimestamp(time()).strftime("%H:%M:%S")
                    print "[clipboard] " + st + " - '%s'" % str(
                        pasteboard_string).encode("utf-8")

            previous = pasteboard_string

            sleep(1)
            elapsed_time += 1
        except Exception as ex:
            print str(ex)

    if output_file:
        print "Clipboard written to: " + output_file
Exemple #8
0
def _to_clipboard(s):
    'Mac only'
    from AppKit import NSPasteboard, NSArray
    pb = NSPasteboard.generalPasteboard()
    pb.clearContents()
    a = NSArray.arrayWithObject_(s)
    pb.writeObjects_(a)
def main():
    import time
    from xpra.platform import program_context
    with program_context("OSX Clipboard Change Test"):
        log.enable_debug()

        #init UI watcher with gobject (required by pasteboard monitoring code)
        from xpra.gtk_common.gtk_util import import_gtk
        gtk = import_gtk()
        get_UI_watcher(glib.timeout_add, glib.source_remove)

        def noop(*_args):
            pass
        log.info("testing pasteboard")
        pasteboard = NSPasteboard.generalPasteboard()
        proxy = OSXClipboardProxy("CLIPBOARD", pasteboard, noop, noop)
        log.info("current change count=%s", proxy.change_count)
        clipboard = gtk.Clipboard(selection="CLIPBOARD")
        log.info("changing clipboard %s contents", clipboard)
        clipboard.set_text("HELLO WORLD %s" % time.time())
        proxy.update_change_count()
        log.info("new change count=%s", proxy.change_count)
        log.info("any update to your clipboard should get logged (^C to exit)")
        cc = proxy.change_count
        while True:
            v = proxy.change_count
            if v!=cc:
                log.info("success! the clipboard change has been detected, new change count=%s", v)
            else:
                log.info(".")
            time.sleep(1)
        if v==cc:
            log.info("no clipboard change detected")
Exemple #10
0
def get_pasteboard_file_path():
    """获取剪贴板的文件路径"""

    # 获取系统剪贴板对象
    pasteboard = NSPasteboard.generalPasteboard()
    # 剪贴板里的数据类型
    data_type = pasteboard.types()

    # 如果是直接复制的文件
    if NSFilenamesPboardType in data_type:
        # 获取到这个文件的路径和类型
        file_path = pasteboard.propertyListForType_(NSFilenamesPboardType)[0]
        return file_path

    now = int(time.time())

    # 剪贴板是png,tiff文件,生成文件返回文件路径
    for file_type, pastedboard_file_type in TYPE_MAP.items():
        if pastedboard_file_type not in data_type:
            continue
        filename = '{}.{}'.format(now, file_type)
        file_path = '/tmp/%s' % filename

        data = pasteboard.dataForType_(pastedboard_file_type)
        ret = data.writeToFile_atomically_(file_path, False)
        if not ret:
            raise WriteFileError(file_type)
        return file_path
Exemple #11
0
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
Exemple #12
0
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, *args, **kwargs):
     self.pasteboard = NSPasteboard.generalPasteboard()
     if self.pasteboard is None:
         raise Exception("cannot load Pasteboard, maybe not running from a GUI session?")
     kwargs["clipboard.local"] = "CLIPBOARD"
     kwargs["clipboards.local"] = ["CLIPBOARD"]
     ClipboardTimeoutHelper.__init__(self, *args, **kwargs)
Exemple #14
0
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 _toPasteBoard(self, text):
     pb = NSPasteboard.generalPasteboard()
     pb.clearContents()
     pb.declareTypes_owner_([
         NSPasteboardTypeString,
     ], None)
     pb.setString_forType_(text,  NSPasteboardTypeString)
Exemple #16
0
 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()
Exemple #17
0
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)
Exemple #18
0
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)
Exemple #19
0
def init_pasteboard():
    global _initialised
    if _initialised:
        return
    _initialised = True
    try:
        from AppKit import NSPasteboard  #@UnresolvedImport
        pasteboard = NSPasteboard.generalPasteboard()
        if pasteboard is None:
            log.warn(
                "Warning: cannot load Pasteboard, maybe not running from a GUI session?"
            )
            return

        def get_change_count():
            return pasteboard.changeCount()

        #test it (may throw an exception?):
        v = get_change_count()
        if v is None:
            log.warn(
                "Warning: NSPasteboard.changeCount did not return a value")
            return
        log(
            "NSPasteboard.changeCount() access success, current value=%s, setting up timer to watch for changes",
            v)
        #good, use it:
        setup_watcher(get_change_count)
    except:
        log.error("Error: initializing NSPasteboard", exc_info=True)
 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()
Exemple #21
0
 def _toPasteBoard(self, text):
     pb = NSPasteboard.generalPasteboard()
     pb.clearContents()
     pb.declareTypes_owner_([
         NSPasteboardTypeString,
     ], None)
     pb.setString_forType_(text,  NSPasteboardTypeString)
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
Exemple #23
0
    def save_clipboard_data(image_name):
        """
        save clipboard data to local umage
        """
        pb = NSPasteboard.generalPasteboard()
        data_type = pb.types()

        if NSPasteboardTypePNG in data_type:
            data = pb.dataForType_(NSPasteboardTypePNG)
            image_path_uncompress = os.path.join('/tmp', 'temp_' + image_name)
            ret = data.writeToFile_atomically_(image_path_uncompress, False)

            image_path_compress = os.path.join('/tmp', image_name)
            # compress image
            if self.is_compress:
                compress_image(image_path_uncompress, image_path_compress,
                               TINIFY_KEY)
            else:
                image_path_compress = image_path_uncompress

            # if save right return image_path_compress
            if ret:
                return image_path_compress
        elif NSFilenamesPboardType in data_type:
            # file in machine
            return pb.propertyListForType_(NSFilenamesPboardType)[0]
Exemple #24
0
def _to_clipboard(s):
    'Mac only'
    from AppKit import NSPasteboard, NSArray
    pb = NSPasteboard.generalPasteboard()
    pb.clearContents()
    a = NSArray.arrayWithObject_(s)
    pb.writeObjects_(a)
Exemple #25
0
def get_img_file_from_mac_clipboard():
    """
    在MacOS系统中,读取剪切板图片并保存为文件,返回文件路径
    若剪切板无图片,返回None
    """
    pb = NSPasteboard.generalPasteboard()
    data_type = pb.types()

    time_stamp = int(time.time() * 1000)

    if NSPasteboardTypePNG in data_type:
        # png 格式
        data = pb.dataForType_(NSPasteboardTypePNG)
        filepath = "/tmp/%s.png" % time_stamp
        ret = data.writeToFile_atomically_(filepath, False)
        if ret:
            return filepath
    elif NSPasteboardTypeTIFF in data_type:
        # tiff 格式
        data = pb.dataForType_(NSPasteboardTypeTIFF)
        filepath = "/tmp/%s.tiff" % time_stamp
        ret = data.writeToFile_atomically_(filepath, False)
        if ret:
            return filepath
    elif NSPasteboardTypeString in data_type:
        # string todo, recognise url of png
        pass
    return None
Exemple #26
0
def get_pasteboard_file_path():
    """
    获取剪贴板的文件路径
    """

    # 获取系统剪贴板对象
    pasteboard = NSPasteboard.generalPasteboard()
    # 剪贴板里的数据类型
    data_type = pasteboard.types()

    # 如果是直接复制的文件
    if NSFilenamesPboardType in data_type:
        # 获取到这个文件的路径和类型
        file_path = pasteboard.propertyListForType_(NSFilenamesPboardType)[0]
        return file_path, False

    # 剪贴板是png,tiff文件,生成文件返回文件路径
    for file_type, pastedboard_file_type in TYPE_MAP.items():
        if pastedboard_file_type not in data_type:
            continue

        file_path = image_path(file_type)
        data = pasteboard.dataForType_(pastedboard_file_type)
        ret = data.writeToFile_atomically_(file_path, False)
        if not ret:
            notify('从剪贴板写入文件失败')
            return '', True

        return file_path, True

    return '', False
Exemple #27
0
def info():
    global verbosity  # todo STAHP THAT!

    verbosity += 1

    for n in [
            NSGeneralPboard, NSDragPboard, NSFindPboard, NSFontPboard,
            NSRulerPboard
    ]:
        pb = NSPasteboard.pasteboardWithName_(n)
        log(pb.name())

        items = pb.pasteboardItems()
        if len(items):
            log('Found items:')
            for i in items:
                log(i)
                log(i.types())
                log(i.dataForType_(NSPasteboardTypeString))
        else:
            log('Pasteboard empty')

        log('')

    verbosity -= 1
Exemple #28
0
def image():
    log('Scrubbing non-image data from pasteboard')
    pb = NSPasteboard.generalPasteboard()
    items = pb.pasteboardItems()

    if len(items):
        log('Found items:')
        for i in items:
            log(i)
            log(i.types())

        #TODO: multi-item pasteboards?
        olditem = pb.pasteboardItems()[0]
        newitem = NSPasteboardItem.alloc().init()

        for t in olditem.types():
            if t in image_types:
                newitem.setData_forType_(olditem.dataForType_(t), t)

        pb.clearContents()
        pb.writeObjects_([newitem])

        log('New clipboard state:')
        log(pb.pasteboardItems())
        log(pb.types())
    else:
        log('Pasteboard empty')
Exemple #29
0
def copy_ip(item):
    """Copies IP to clipboard"""
    from AppKit import NSPasteboard, NSArray

    pb = NSPasteboard.generalPasteboard()
    pb.clearContents()
    a = NSArray.arrayWithObject_(item)
    pb.writeObjects_(a)
Exemple #30
0
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

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

        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

    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

        _convert_to_png(tmp_clipboard_img_file.name, png_file.name)
        # close the file explicitly
        tmp_clipboard_img_file.close()
        return png_file
Exemple #31
0
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"
Exemple #33
0
def c_types(args):
    for item in NSPasteboard.generalPasteboard().pasteboardItems():
        ts = item.types()
        for t in ts:
            if args.type:
                print("{}\tconforms to {}: {}".format(
                    t, args.type, UTTypeConformsTo(t, args.type)))
            else:
                print(t)
Exemple #34
0
def c_filter(args):
    pb = NSPasteboard.generalPasteboard()
    conforming_data = data_conforming_to_type(pb, args.type)
    if conforming_data:
        print("{} conforms to {}, replacing clipboard contents".format(
            conforming_data[0], args.type))
        pb.clearContents()
        pb.setData_forType_(conforming_data[1], conforming_data[0])
    else:
        exit(errno.ENODATA)
Exemple #35
0
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)
Exemple #36
0
def test_getClipboardFiles():
    import pdb
    pdb.set_trace()
    import AppKit
    pb = NSPasteboard.generalPasteboard()
    if pb.availableTypeFromArray_([AppKit.NSFilenamesPboardType]):
        files = pb.propertyListForType_(AppKit.NSFilenamesPboardType)
        return [unicode(filename) for filename in files]
    else:
        return []
Exemple #37
0
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()
Exemple #38
0
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 get_paste_img_file():

    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)
        return img_path
Exemple #40
0
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()
Exemple #41
0
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('出错啦')
Exemple #42
0
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 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
Exemple #44
0
	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 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
Exemple #46
0
 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 ''
Exemple #47
0
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)
Exemple #50
0
	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"
Exemple #51
0
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'})
Exemple #53
0
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!')
Exemple #54
0
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)
Exemple #55
0
def copy_to_clipboard(text):
	NSPasteboard.generalPasteboard().clearContents()
	NSPasteboard.generalPasteboard().setString_forType_(text, NSPasteboardTypeString)
Exemple #56
0
 def __init__(self):
     self.pasteboard = NSPasteboard.generalPasteboard()
     self.current_count = -1
Exemple #57
0
# 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:
Exemple #58
0
def to_clipboard(value):
	from AppKit import NSPasteboard
	pb = NSPasteboard.generalPasteboard()
	pb.clearContents()
	pb.writeObjects_([value])
def sendToClipBoard(string):
    pasteboard = NSPasteboard.generalPasteboard()
    emptyOwner = NSObject.alloc().init()
    pasteboard.declareTypes_owner_([NSStringPboardType], emptyOwner)
    pasteboard.setString_forType_(string, NSStringPboardType)