Tab Dumping with AppleScript and back to Python

Rock

Goal: Iterate through all my (OS X Safari) browser windows and make a list of titles and urls which is then placed in the clipboard ready to be pasted into an email or blog post.

This is an update to Tab Dumping in Safari. That still works well as the basis for extending any Cocoa-based application at runtime, but it relies on SIMBL, which while it is a great bit of code, essentially is abusing the InputManager interface. Some developers and users shun such hacks, and at least one Apple application checks for them at startup and warns you from using them.

I have been running the WebKit nightlies, which are like Safari, but with newer code and features (most importantly to me right now, a Firebug-like developer toolkit). WebKit warns at startup that if you’re running extensions (such as SIMBL plugins) it may make the application less stable. I was running both Saft and my own tab dumping plugin, and WebKit was crashing a lot. So I removed those and the crashes went away. I miss a handful of the Saft extensions (but not having to update it for every Safari point release), and I found I really miss my little tab-dumping tool.

I toyed with the idea of rewriting it as a service, which would then be available from the services menu, but couldn’t figure out how to access the application’s windows and tabs from the service. So I tried looking at Safari’s scriptable dictionary, using the AppleScript Script Editor. Long ago, John Gruber had written about the frustration with Safari’s tabs not being scriptable, but a glance at the scripting dictionary showed me this was no longer the case (and probably hasn’t been for years, I haven’t kept track).

I am a complete n00b at AppleScript. I find the attempt at English-like syntax just confuses (and irritates) me no end. But what I wanted looked achievable with it, so I armed myself with some examples from Google searches, and Apple’s intro pages and managed to get what I wanted working. It may not be the best possible solution (in fact I suspect the string concatenation may be one of the most pessimal methods), but it Works For Me™.

In Script Editor, paste in the following:

set url_list to ""
-- change WebKit to Safari if you are not running nightlies
tell application "WebKit"
  set window_list to windows
  repeat with w in window_list
    try
      set tab_list to tabs of w
      repeat with t in tab_list
        set url_list to url_list & name of t & "\n"
        set url_list to url_list & URL of t & "\n\n"
      end repeat
    on error
      -- not all windows have tabs
    end try
  end repeat
  set the clipboard to url_list
end tell

I had to use AppleScript Utility to add the script menu to my menu bar. From there it was easy to create script folders that are specific to both WebKit and Safari and save a copy of the script (with the appropriate substitution, see comment in script) into each folder. Now I can copy the title and URL of all my open tabs onto the clipboard easily again, without any InputManager hacks.

I had some recollection that is a way to do this from Python, so I looked and found Appscript. I was able to install this with a simple easy_install appscript and quickly ported most of the applescript to Python. The only stumbling block was that I couldn’t find a way to access the clipboard with appscript, and I didn’t want to have to pull in the PyObjC framework just to write to the clipboard. So I used subprocess to call the command-line pbcopy utility.

#!/usr/local/bin/python
from appscript import app
import subprocess
tab_summaries = []
for window in app('WebKit').windows.get():
    try:
        for tab in window.tabs.get():
            name = tab.name.get().encode('utf-8')
            url = tab.URL.get().encode('utf-8')
            tab_summaries.append('%s\n%s' % (name, url))
    except:
        # not all windows have tabs
        pass
clipboard = subprocess.Popen('pbcopy', stdin=subprocess.PIPE)
clipboard.stdin.write('\n\n'.join(tab_summaries))

The remaining hurdle was simply to put the Python script I’d written into the same Scripting folder as my AppleScript version. For me this was ~/Library/Scripts/Applications/WebKit/. When run from the scripts folder, your usual environment is not inherited, so the #! line must point to the version of Python you are using (and which has Appscript installed). You should also make the script executable. Adding .py or any other extension is not necessary.

Overall, while I found AppleScript to be very powerful, and not quite as painful as I remembered, I found the Python version (warts and all) to be easier to work with. Combined with the fact that the script folder will run non-Applescript scripts, this opens up new worlds for me. I have hesitated in the past to write a lot of SIMBL-based plugins, tempting though it may be, because they are hacks, and they run in every Cocoa-based application. But adding application-specific (or universal) scripts, in Python, is pure, unadulterated goodness.

Back to the Drawing Board

Well, I’ve been promising this off and on here in my intermittent blog, but I’ve had the code up on Google code hosting for some time now, my kids have tested out the latest version, I’ve fixed some bugs introduced when PyObjC switched from distutils to setuptools. It is still pretty raw, unpolished, unoptimized, but I’m ready to let the world see it and let me know what they think.

Current features of Drawing Board:

  • Freehand sketching: This is the main point of the software
  • Onion-skinning: See previous frame dimmed behind current frame
  • Create new frames: Either blank, or containing a copy of the current frame. Copied frames include the entire undo stack for the frame, so you can copy, and then undo a portion of the frame
  • Change colours and line sizes
  • Change the opacity of the window (this is a hack to allow you to trace images until I get image backgrounds implemented)
  • Scale and translate the frame
  • Remove current frame (not undo-able)
  • Export as SVG
  • Export frame as PNG or JPEG (PNG includes alpha for any area not drawn)

There is basic file handling, which may be useful as example code for learning Cocoa programming using Python. I’m still working at adding drawing tools besides freehand drawing, and I have ideas for a lot of other things, but the main idea is to keep the program from getting in your way–to keep as close to possible as sketching with a pencil on paper, but to make the process of creating simple animations easier.

Two features that are pretty close, and are important to the goal of the project, are export as Flash and export as Quicktime. Those will be coming sooner, rather than later.

The project page is at http://livingcode.org/project/drawingboard and you can find links there to the binary download, the source repository, and the bug/feature tracker. I’ve also set up Google groups for the Living Code projects: http://groups.google.com/group/livingcode-users and http://groups.google.com/group/livingcode-developer for ongoing discussions.

A few people have seen me demo this program at the Vancouver Python Workshop and at Bar Camp Vancouver and expressed an interest, so I hope it can be of use, both in learning to program OS X with Python, and for creating animations. Please let me know what you find useful and what could be improved!

PyObjC at VanPyZ

On Tuesday, October 3rd, at 7 pm, the Vancouver Python and Zope user’s group (VanPyZ) will be hosting two speakers. Paul Prescod will be discussing full-stack web frameworks in Python, and I will be presenting OS X programming in Python. This will probably not be a repeat of my presentation at the Vancouver Python Workshop (PDF slides, for anyone who is interested) but using Drawing Board and the InputManager hack to show how you can use PyObjC to build new applications in Python quickly and extend existing Cocoa applications easily. My focus these days is on how to take control of your computer and make it work for you, rather than the other way around.

The VanPyZ meeting will be at the Uniserve office, where Paul and I now work, Suite 1550, 1055 West Hastings Street, in Vancouver, BC. Mark Mayo took time out from his new baby (congratulations, Mark!) to create an Upcoming event for it. We’ll be going out for drinks afterwards, so come hang out with the Vancouver pythoneers.

Mac OS X Software Favorites Part One: Basics

Yesterday was my last day at my job for the past five years, and with it I left my Macbook Pro (it was a nice tool, but they own it). Coincidentally, I’m now setting up my new Macbook. Since I know several other people who are setting up new Macs, I thought I’d give my thoughts on some of the best software available. Since that’s a big topic, I’m going to break it up into several posts, starting with the basics: Application Launcher, Text Editor, Web Browser, Newsreader

Macbook vs. Macbook Pro

Before diving into the software, just a note on the hardware. I’m going with a black Macbook for several reasons. First, it looks really cool, and I can’t deny that appeals to me. Second, it is somewhat smaller and lighter than the smallest Macbook Pros, and since I carry my laptop to and from work every day by foot or bicycle, that matters (I’m getting two power bricks so I can leave one in each location to save even more weight). Third, the wifi reception is much better. Encasing an antenna in plastic appears to work better than encasing it in aluminum, go figure. Macbook Pros are more powerful, but only a bit, and mainly for heavy-duty 3D, which isn’t really my thing. We’ll see how much this matters in practice. White vs. Black Macbook: the white ones are rumored to stain really easily, plus did I mention that the black ones look really freaking cool? The Macbook is cheaper than the Macbook Pro, but that’s not a big factor in why I’m choosing it (since once again, work will own it, just a different work–more on that later). The Macbook also gets better battery life, is slightly less crotch-scaldingly hot, and so far I’m liking the keyboard a lot.

Application Launcher: Quicksilver

I used to use TigerLaunch (free, open source), and still do on other Macs in the family, but once you’ve tried Quicksilver (free, beta) there’s no going back. I’m still working on becoming a Quicksilver power user, but just the app-launching and file-searching facility is worth using this tool for. TigerLaunch is great for its simplicity, and Quicksilver is great for making you wonder how you ever got along without it. I’ve heard wonderful things about PathFinder ($34.95USD) and keep meaning to try it, but haven’t gotten to it yet. First I need to learn how to write Quicksilver plugins in Python…

Editor: TextMate

I used to use Pico on Unix and BBEdit Lite on Mac OS 7, back in the day. I couldn’t stand either vi or emacs. I wanted a T-shirt that read, “I’d rather die than use vi.” Then I worked at a company where the only editor you could count on being installed was vi and I began to get its keystrokes etched into the memory of my fingers. I’m not even that good at it, but sometimes vi can be so damn fast. Of course, I don’t use classic vi, but a nice modern Vim (free, open source). I’ve tried to switch back to Mac editors a few times: TextWrangler (free, the OS X incarnation of BBEdit Lite), SubEthaEdit ($35USD, great for collaborative editing), Smultron (free, open source). These are all great editors, but each one lacked something that kept me from switching over completely. I had been hearing about TextMate (€39EUR) for some time, but had trouble getting excited over a commercial editor when there were so many free ones to choose from. I finally gave it a serious try and I’m hooked. It still isn’t as easy to search as vi is, but the way it can be expanded on with plugins and the general fit and feel are great.

Browser: Safari + Saft

Safari is shaping up to be a great browser, fast and powerful. There are a few details that are missing, but nearly all of them are satisfied with the Saft ($12USD) extension, which provides great ad filtering, improves the way windows and tabs are handled, and gives shortcuts for accessing search sites from the address bar, among many other features. Safari itself takes two kinds of plugins, Netscape-style plugins and WebKit plugins. Unfortunately, these are only triggered when their target mime types are loaded, so they can’t readily be used to extend the way the application itself works. So all of the Safari extensions that I’m aware of are implemented as InputManagers (see my post on TabDump for more on InputManagers). My TabDump extension is the other extension that I find indispensable, which is why I wrote it, but more important than TabDump itself is the example it gives for writing your own extensions to Safari or any other (Cocoa) application. That’s what I love about OS X, you can get into it and take control of your own machine, make it your own. You can do that with Linux, of course, but the high-level of Cocoa applications make a huge difference. Back to browsers, I also recommend the Flip4Mac plugin, to allow your browser to play Windows Media files directly. Finally, I also keep Firefox (free, open-source) around for its advanced features. It’s not my main browser, but it has features that show where the browser (and all applications) will be going in the future. I may have to do a separate post just about the cool features coming in Firefox 2 (currently in beta) and Firefox 3. Other good browsers to keep around for testing are Camino (the Firefox engine with a Cocoa UI) and Opera (free). For more Safari plugins and extensions than you could ever use, check the listings at Pimp My Safari.

Newsreader: NetNewsWire

I realize that Safari now supports RSS feeds in some fashion, but it really isn’t a newsreader. I’m not crazy about trying to put every possible application into the browser. If you have to work betwwen Windows, OS X, and Linux, or some combination thereof, then things like GMail and Bloglines can be a godsend, otherwise you’re probably better off with a dedicated desktop app. NetNewsWire ($29.95USD) is a desktop app that is so good, it was the most popular newsreader (by far) for a long time, even though it only ran on OS X. Since being acquired by NewsGator, it’s still as good, but now synchronizes your feeds with the NewsGator site, so you get the best of both worlds: a top-notch desktop app, and a webapp that stays sychronized with it. I have a feeling that in the near future, nearly all applications will work this way. And if you can’t afford the price, they still offer NetNewsWire Lite for free (and I happily used it for a couple of years before upgrading).

Mail: Mail.app

Apple gives you a decent email program with OS X, nothing too fancy. It keeps getting better (mostly) with each new release. There has been some complaints about Mail.app in OS 10.4 changing to a proprietary format (which they did in order to integrate with Spotlight) and I’ll have more to say about that in a future post. I have tried using Gmail (when I was mostly using Windows at work) and Thunderbird (free, open-source), and coming back to Mail.app is like a breath of fresh air. For nearly everything I do, Mail.app is better. It’s far from perfect, and sites like HawkWings specialize in plugins and extensions for Mail.app, but it sure works for me. I do wonder why email programs are still so hard to get right. Since email is basically the oldest use of the internet (and networks generally), and the original “killer app,” if we don’t know how to do email yet, what hope do we have for anything that’s actually complicated? Of course, perhaps because they have been around for so long, choice of email programs tends to be very personal, so all I can say is, Mail.app works for me. I also recommend the AttachmentScannerPlugin by James Eagan, who also provides a tutorial on writing plugins for Mail.app which is generally applicable to extending Cocoa programs and using their undocumented private APIs. Also, he uses Python and PyObjC to write the plugin, which makes me happy.

Regular reader(s) were probably wondering how I was going to get that plug for Python and PyObjC in there, eh?

Bar Camp Tomorrow

Tomorrow, from 6PM to Saturday at 6PM will be the Bar Camp Vancouver. I’ll be heading over there with my neighbor, former co-worker, and original member of Pluto, John Ounpuu, currently of Sutori fame. I’m planning on ducking out to sleep at home rather than camping there, but I’m sure it will be a great time. If there is time I may reprise my presentation on Python, OS X, and Kids from the Vancouver Python Workshop. If time is short I may still be able to demo Drawing Board. If time is really short I’ll still try to squeeze in a demo of the new hack I figured out last night (see next post). I’m also hoping to find some time to hack on turtle graphics for OS X, since I’m so close to having a working port of the standard library turtle graphics in PyObjC. But the main thing I’m excited about is meeting folks, it’s going to be a great crowd.

Vancouver is such a great place. There’s the standard stuff: Great weather, beautiful beaches, forests and mountains. Then there is all the rest: lots of interesting geeks of various stripes, cool places to work, small conferences to attend. I’ve had so much more fun at the Vancouver Python Workshop and Northern Voices than at big anonymous events like JavaOne and OOPSLA. There’s just no contest. And BarCamp is all about being a small, intimate event–that appears to be its whole entire purpose. I can hardly wait.

« Previous entries Next Page » Next Page »

google

google

asus