Archive for the 'Ship-It Saturday' Category

Ship-It Saturday: PRHEmptySingleton repository

Saturday, September 4th, 2010

The singleton-done-right example from my article on the subject is now in a Mercurial repository on Bitbucket. The repository includes not only the class (which I’ve put in the public domain), but also a test suite for some of the test cases listed in the post.

There are some adventurous testing techniques at work here.

First, since we don’t want multiple test runs to use the same singleton instance, the test cases actually run in subprocesses. Each test method is prefaced with this code:

if (!isInSubprocess) {
    [self runTestInSubprocess:_cmd];

That method calls fork.

In the child process, the test case sets isInSubprocess to YES, then tells itself to perform that selector; this gets execution back to the test method, which checks the variable again, finds that it’s true this time, and continues on with the test.

The parent process calls waitpid and checks the result; if the child failed, the parent propagates the failure. If the child crashed (got a signal), the parent raises the same signal; if the child simply exited abnormally, then the parent exits with the same status.

Second, there’s test case #6:

  • If [super init] returns a different object, alloc/init won’t break.

That one is hard to test, because PRHEmptySingleton’s superclass is NSObject, and -[NSObject init] doesn’t return a different object. (Not in any version of Foundation I’ve ever encountered, anyway.)

So, the first step is to create an intermediate class that does return a different object. But that doesn’t help as long as PRHEmptySingleton is still a direct subclass of NSObject.

The simple solution would be to just change PRHEmptySingleton’s superclass, but that reduces the purity of the testing: A test should be able to work without modifying the code under test, and any changes to the code under test should be permanent changes that aren’t only to enable the test; you should be able to explain the changes as if the test case did not exist.

So what I did was to import everything in my prefix header, even more than I usually do, and then import my intermediate class’s header, and then use the preprocessor to ensure that any direct subclasses of NSObject declared elsewhere are declared as subclasses of the intermediate class. Thus, the prefix header causes PRHEmptySingleton to be a subclass of the intermediate class with no changes to PRHEmptySingleton’s header. It’s a bit of a hack, and doing this sort of thing could potentially cause problems in a larger program or test suite, but in this context, it works.

With that, five of the six test cases in the original post are now covered (I’m not sure how to cover #3 without changing PRHEmptySingleton.[hm]), and the code is under version control, so you can subscribe to and track changes.

Please use singletons responsibly.

Portable centimetric measuring tape

Saturday, August 14th, 2010

This is a roll-up measuring tape that tucks neatly into my wallet, mostly so that I can compare sizes of products in the store without having to buy them or go find a ruler.

File: Centimetric_Ruler-portable.pdf

A US Letter page containing the ruler (20 cm long) and a specification for the cardboard handle you glue the ruler to.


Photo of the portable centimetric measuring tape, rolled up, sitting on a table.

Photo of the portable centimetric measuring tape, with 6 cm unrolled, sitting on a table.

In case you’re wondering about the pattern of the mm markings, I borrowed it from this New Zealand ruler that Dave posted about.

If I were to assemble this again, I would glue the “tape” to the other end of the handle, so that I can unroll the tape from left to right using my right hand. If you’re left-handed, you might prefer to assemble yours the same way I did assemble mine.

Centimetric ruler/measuring tape

Saturday, July 3rd, 2010

One mistake a lot of people make when trying to learn the metric system is trying to memorize and use conversion factors. Do you think people in other countries measure everything in inches and then convert to centimeters?

No, they have measuring tapes and rulers in centimeters or millimeters. Such rulers are easy to come by here in the US, but the measuring tapes are not.

So, in order to solve that problem and make it easier for fellow Americans to measure lengths in metric units, I present my Centimetric Ruler. It totals 2.5 meters, and looks like this:

Tick marks every 1 mm, with numbers over centimeter marks.

Despite the name, I use it as a measuring tape, coiled up and held in that shape (when not in use) by a small rubber band.

The page is US Letter (because that’s the paper I have), and you’ll need to cut out the pieces and tape them together. I recommend cutting through the tick marks so that there is no gap between them and the bottom of the “tape”.

Note that every 25th centimeter appears twice in the printout. This is to give you one centimeter in which to lay each segment over the previous/next one.

There’s nothing I can do for you for measuring mass (but scales that measure in grams are easy to come by; you can buy a digital one at Target for $20), but volume is easy, and demonstrates the elegance of the metric system pretty well:

  1. A liter is equal to the volume of a cube that is 1 decimeter (= ¹⁄₁₀ meter = 10 cm) to a side. That volume is 1 dm × 1 dm × 1 dm, or 1 dm³—one cubic decimeter.
  2. ¹⁄₁₀ of a decimeter is one centimeter (¹⁄₁₀₀ of a meter).
  3. Imagine, or construct, a cube one decimeter to a side. Starting from one corner, make a cut in each edge, one-tenth of the way from the corner. This will produce a cube that is one centimeter to a side—one cubic centimeter.
  4. Note that this cube is ¹⁄₁₀ of the larger cube in each dimension, which means its volume is (¹⁄₁₀ × ¹⁄₁₀ × ¹⁄₁₀) = ¹⁄₁₀₀₀ of the volume of the larger cube.
  5. The volume of the larger cube being one liter, the volume of the smaller cube is ¹⁄₁₀₀₀ of that. ¹⁄₁₀₀₀ of a liter. One milliliter.
  6. QED: One cubic centimeter (1 cc) = one milliliter (1 ml).

Knowing how volume and length relate to each other in metric, you can use the measuring tape (most easily on cuboid objects) to measure volume as well.

Capture Cursor

Saturday, March 13th, 2010

Most people don’t know how to get the cursor that’s currently on the screen—a useful ability, especially if you’re writing screenshot or screen-recording software. I’ve written an app that demonstrates the technique, or at least tries to.

It’s a bit flaky. The API it uses, IOFramebuffer, doesn’t tell me how many frames there are or what format they’re in, so the app assumes ARGB in native byte-order and doesn’t worry about frames. This gives wrong results more of the time than I like.

I’ve filed a request for a higher-level API, which would make the task much easier and the app much shorter.

I’ve posted a build in the repository’s downloads area, in case you’d like to see it in action. If you want to build it yourself, you’ll need to download SGHotKeysLib and put the source where the Capture Cursor Xcode project expects it to be.

UPDATE 2010-08-28: I’ve pushed a change, [9cbec7dd5169], that deletes the IOFramebuffer-based category method and uses Snow Leopard’s new, far more reliable [NSCursor currentSystemCursor] instead. I suggest you do the same.

Easy main-thread performing category

Saturday, February 13th, 2010

Anyone who’s ever had to perform a message on the main thread knows how ugly the code can be:

[obj performSelectorOnMainThread:@selector(receiveAnswer:)
                      withObject:[NSNumber numberWithUnsignedInteger:42]

I’ve written a category that changes the above code to something much simpler:

[[obj performOnMainThread_PRH] receiveAnswer:42];

Notice that not only is the code much easier to read and to write, but you no longer need to box and unbox primitive values.

You can get the code, under a BSD license, from the higher-order main-thread perform repository.

Back when I originally mentioned my creation of the category on Twitter, Dave Dribin replied that he had already written one of his own. His is part of his DDFoundation framework, and requires DDInvocationGrabber (a fork of Jonathan Wight‘s CInvocationGrabber), also part of that framework.

My category requires nothing but Cocoa and is not part of a larger framework. That said, it’s interesting to read in his code how the functionality of the Invocation Grabber makes his implementation nothing but a thin wrapper around it. (Also, his version lets you say waitUntilDone:YES.)

Nearest Neighbor Image Unit

Saturday, February 6th, 2010

I originally wrote this as an application using NSImage (with NSImageInterpolationNone), but decided to rewrite it as an Image Unit. So, here it is.

Ship-It Saturday: Shorten URLs service

Saturday, January 30th, 2010

When posting links on Twitter, your Twitter client will automatically shorten the URLs to make them fit.

There are many, many general shorteners, including TinyURL, Notlong, Metamark, and One of the complaints about these is that they hide the true destination of the link: From the URL alone, you don’t know whether you’re going to be educated, RickRolled, or worse. (TinyURL and both offer a way to preview the link, but that’s not as easy as just looking at the URL.)

To help with this, several non-shortening-related websites have added their own shorteners that use their own domains, particularly for use on their official Twitter accounts or with a built-in post-to-Twitter feature.

The problem is that it’s not always easy to tell what the shortened link will be. Flickr is among the most difficult: Their regular links use decimal numbers, but their shortened links use base-58, which is not a trivial conversion to perform in any programming environment I know how to use. (Not so easy as, say, decimal to octal.) It’s certainly doable, but would require extensive tests to verify that your base-58 numbers match Flickr’s. There’s sample code, but it’s in PHP, so if you’re writing in anything else, that means porting it, which means (again) extensive tests.

So, rather than write my own shortener, it’s much easier to just use Flickr’s: curl the canonical long URL, then scrape the short one out of the body. (Yay for <link rev="canonical">!) I wrote a service to do this.

For Ship-It Saturday, I retooled it. No longer is it just a Flickr shortening service: It now handles YouTube, Amazon, and a few other sites as well. A single service invocation shortens all links to websites that have their own shorteners.

So, here you go: The Shorten URLs service.

finder, a command-line tool

Sunday, January 24th, 2010

Today’s Ship-It Saturday is a command-line interface to the Finder.

The two most useful commands are:

  • finder reveal file, which will select the file in a Finder window, and
  • finder update (or updated) file, which will tell the Finder that the file has been updated.

The latter command probably is not too useful anymore, but the command-line tool should work on no less than 10.4, and could probably be recompiled for even older versions of Mac OS X, so you may still have a use for it.

Pointers tutorial 1.3

Saturday, January 16th, 2010

At long last, a new version of Everything you need to know about pointers.

The most significant changes are long-overdue corrections regarding declarations of const pointers and the difference between arrays and pointers. You can—and, if you learned how to work with pointers from this tutorial, should—read all of the changes in the delta between 1.2 and 1.3.

Ship-It Saturday: IconGrabber 2.0.1

Sunday, January 3rd, 2010

The last time I released a version of IconGrabber was only a week after Valve released Half-Life 2—way back in 2004. That game wasn’t even on my radar then, since I couldn’t run it on my PowerPC-based Mac!

Just over five years later, I’ve played all of the Half-Life 2 games and love them, and IconGrabber returns with some bug fixes and support for the new bigger icon sizes introduced in Tiger and Leopard. Version 2.0.1 is available from the IconGrabber home page.

Ship-It Saturday: Translate Text

Sunday, December 27th, 2009

Real artists ship.

Steve Jobs

With the idea that an application that’s 95% finished and in active use is better than an application waiting for 100% in the seclusion of my hard drive, Ship-It Saturday is where I dust off a program that I have 95% finished, call it done, and just ship it already. I hope to make this a regular feature, although I have no idea how frequently I’ll do it.

Today’s winner is Translate Text, an app I wrote to make handling Adium feedback emails easier. Just select some text, then choose the service corresponding to the language it’s in (or the auto-detect-language-and-then-translate service). A window will open with the original, a couple of language pop-up menus, and the translation.

Screenshot of myself invoking the French-to-English service through a contextual menu.

More information, both screenshots, and the downloads at the Translate Text web page.