Commits

Jonathan Eunice committed 61c5d0b

regularized unicode usage; modified paste() API

Comments (0)

Files changed (3)

     from richxerox import copy, paste, available
     from richxerox import dict_print # demo only
     
-    print available() # what's on the clipboard?
-    print paste()     # get it in the 'best' format
+    print available() # what kind of data is on the clipboard?
+    
+    print paste()     # get data in the default format ('text')
+    print paste(format='rtf')   # get RTF
+    print paste(format='html')  # get HTML
     
     dict_print(pasteall(), 'ALL CONTENTS')
     
     copy(text="this is good!", html="this is <strong>good</strong>!")
     dict_print(pasteall(), 'AFTER COPY')
+    
+    rtf = paste(')
 
 Background
 ==========
 
-Search as I might, I couldn't find a module that made ``copy`` and ``paste``
-operations on Mac OS X easy and straightforward. I like the `xerox
-<http://pypi.python.org/pypi/xerox>`_ module, but it only does plain
-text. What about browsers and word processors that export rich
-text with hyperlinks, styles, and so on? How do I get access to *that*?
+I searched long and hard but couldn't find a simple Python module that made
+``copy`` and ``paste`` operations on Mac OS X easy and straightforward. `xerox
+<http://pypi.python.org/pypi/xerox>`_ works well, but it only supports plain
+text. What about browsers and word processors that export rich text with
+hyperlinks, styles, and so on? How can you access *that* data?
 
 After banging my head against this a few times, I eventually found code samples
 I could adapt and make work without understanding the entirety of Apple's
 ``Foundation`` and ``AppKit``. This module is the result.
 
+It's still in flux as I improve my understanding of the underlying
+``NSPasteboard`` class and ``UTI`` descriptors, and of how my programs will use
+the APIs.
+
 Credits and References
 ======================
 
     'rtf':  'public.rtf',
     'text': 'public.utf8-plain-text'
 }
+uti2format =  dict((v,k) for k, v in format2uti.iteritems())
 
 # UTIs are Uniform Type Identfifiers (http://en.wikipedia.org/wiki/Uniform_Type_Identifier)
 # ...even if they sound a lot like urinary tract infections
     """
     return format2uti.get(fmt, fmt)
 
-def paste(formats=None):
-    """
-    Get data from the Mac pasteboard (aka clipboard). Prefers a list of
-    formats such as HTML and RTF, but takes plain text if that's what's available.
-    That order of perferred formats has a reasonable default, but can be 
-    specified on a per-call basis via the formats arg. If desired, raw UTIs
-    can be given on formats as well.
-    """
-    formats = formats or preferred_formats
-    pb = NSPasteboard.generalPasteboard()
-    for f in formats:
-        contents = pb.stringForType_(UTI(f))
-        if contents:
-            return unicode(contents)
-    return None
-
-def paste_format(fmt):
+def paste(format='text'):
     """
     Return data of the given format ('rtf', 'html', 'text', or an explict UTI) from
     the Mac pasteboard (aka clipboard), if any, otherwise None.
     """
     pb = NSPasteboard.generalPasteboard()
-    return pb.stringForType_(UTI(fmt)) or None
+    return unicode(pb.stringForType_(UTI(format))) or None
 
-
-def available(dyn=False):
+def available(neat=True, dyn=False):
     """
-    Return list of UTIs (data types) of data available on the pasteboard. By
-    default, excludes items whose type starts with 'dyn.', which is a dynamic
-    type lookup scheme for 'unregistered' type codes--beyond our current
-    scope of operations.
+    Return list of formats available on the pasteboard. By default, provides a
+    simple 'format' name ('rtf', 'html', or 'text') for preferred types, or UTIs
+    for other types. By default, excluses items whose type starts with 'dyn.',
+    which is a dynamic type lookup scheme for 'unregistered' type codes--beyond
+    our current scope of operations.
+    """
+    items = NSPasteboard.generalPasteboard().pasteboardItems()
+    if not items:
+        return []
+    types = items[0].types()
+    if not dyn:
+        types = [ t for t in types if not t.startswith('dyn.') ]
+    if neat:
+        return [ uti2format.get(u, u) for u in types ]
+    else:
+        return types
+    
+def pasteall(neat=True, dyn=False):
+    """
+    Return a dict of all available data types, matched to the associated
+    content. Good for curiosity, if not as useful in practice. Arguments
+    are as those for available().
     """
     pb = NSPasteboard.generalPasteboard()
-    if dyn:
-        return pb.pasteboardItems()[0].types()
-    else:
-        return [ t for t in pb.pasteboardItems()[0].types() if not t.startswith('dyn.') ] 
-
-def pasteall(dyn=False):
-    """
-    Return a dict of all available data types, matched to the associated
-    content. Good for curiosity, if not as useful in practice.
-    """
-    pb = NSPasteboard.generalPasteboard()
-    return { t: pb.stringForType_(t) for t in available(dyn) }
+    return { unicode(t): unicode(pb.stringForType_(UTI(t))) for t in available(neat, dyn) }
 
 def copy(**kwargs):
     """
     """
     pb = NSPasteboard.generalPasteboard()
     pb.clearContents()
-    
-def uutf(v):
-    """
-    Coerce a value to unicode(), then get its utf8 encoding. 
-    """
-    return unicode(v).encode('utf-8')
+
 
 def dict_print(d, heading=None, wrap=False, **kwargs):
     """
     if heading:
         print heading
     for key, value in d.iteritems():
-        item_text = "{}: {}".format(uutf(key), uutf(value))
+        item_text = "{}: {}".format(key, value)
         if wrap:
             print '\n'.join(textwrap.wrap(item_text, **kwargs))
         else:
     print available()
     print paste()
     dict_print(pasteall(), 'ALL CONTENTS')
+    
+    clear()
+    dict_print(pasteall(), 'AFTER CLEAR')
+    
     copy(text="this is good!", html="this is <strong>good</strong>!")
     dict_print(pasteall(), 'AFTER COPY')
     
 
 setup(
     name='richxerox',
-    version='0.06',
+    version='0.07',
     author='Jonathan Eunice',
     author_email='jonathan.eunice@gmail.com',
     description='copy/paste for Mac OS X for rich text (HTML/RTF) rather than plain text',