TweetFollow Us on Twitter

Aug 01 Application Development

Volume Number: 17 (2001)
Issue Number: 08
Column Tag: Application Development

DropScript

by Wilfredo Sanchez

Or How to Build a Way Easy Yet Spiffy App

Quick, I Need A Demo

Last year at Apple's Worldwide Developers Conference I was giving a talk on BSD in Mac OS X. Basically, I was standing in front of a (full) room of Macintosh developer explaining why Unix is good for Mac OS.

There has been a fair amount of debate over the value of keeping the BSD command line (Terminal.app) and the BSD toolset in the base operating system. The majority of Mac OS users will not need to interact with the command line, and therefore the Terminal will not be of great use to them. (There is also the argument that the very presence of the command line option in the system will give developers an undesireable crutch; that users might end up having to use the command line.)

I actually agree that Terminal.app is not a necessity in the base system, though I'm glad it's there for my own convenience. (It is a necessity in the developer toolset.) I also agree that requiring users to deal with the decidedly arcane Unix interface would be a grave mistake. However, even with no way to get to an interactive command line, the presence of the BSD toolset in the standard installation of Mac OS is of great value to developers and therefore to users. My argument is simple: the BSD commands provide another valuable API to developers; they enable software authors to do great things will less effort.

In order to make my case that the BSD toolset is important, it helps to have a good demo for the talk, in true WWDC fashion. Certainly I can't let the QuickTime folks get all of the applause. BSD provides many small programs (often called commands, as they tend to be invoked by users on an interactive command line), each of which performs some specialize function. A command called cp, for example, can copy a file; another, mv, can rename a file. An application author can write programs that invoke BSD commands to do certain task. These commands can be shell scripts which in turn may invoke several other commands in sequence. I figured that an application that did this would be a good demo.

I had heard of an application for NeXTStep (can't remember the name; I've never seen it), which would let you graphically create a shell script by chaining commands together. That sounded hard to write in a week... I've seen people use MacPerl, which lets you create droplets, applications onto which you can drop a file and have a perl script process the file for you. Now wouldn't it be cool if you could take any BSD command and turn it into a drop application? That didn't sound so hard, so I started thinking about it.

Designing A Surprisingly Simple Application

What I needed was an program that could turn a command line tool into an application. Many command-like tools operate on files. You invoke the program by name and give it file names as arguments. For those of you not familiar with the command line, the basic usage is fairly simple. Say I have a program called gzip, which will compress a file. I want to compress the file Big File, so I type the following into the terminal:

gzip "Big File" 

and I end up with a smaller file called Big File.gz (the .gz file name extension denotes a gzip-compressed file). Now I want to be able to do the same thing in Finder by dragging a file onto an icon rather than using the command line.

My droplet-generating program therefore needs to create a new application which invokes the desired command (typically a shell script)1 for me, with my file as an argument. I started by writing a droplet application which I would use as a template, thinking that the droplet generator would copy the template application and replace the command it invokes with another. I wanted to avoid the need to compile a new binary, since many users will not have the developer tools installed; while it's probably OK to say only developers can create droplets, I'd rather not require the developer tools if I don't need to.

Writing the primordial droplet

My plan was to create an application which would contain a shell script in it. Whenever the application is asked to open a file, it will invoke the script with the file's path as an argument. The generator would therefore only need to copy the original app and replace the script with a new one.

I decided to write the application using Cocoa. Mostly, this is because Cocoa is the only application toolkit I'm proficient at (I don't write many apps), but the reason Cocoa is the only toolkit I know is that Cocoa is an excellent toolkit. Cocoa does an excellent job of minimizing the amount of work I need to do. For example, when a user drops a file onto an application with Finder, what happens is that Finder launches the application and sends it an AppleEvent telling it to open the file. Any decent Mac OS application which opens files has a File menu with an Open menu item which also opens a file. Cocoa automatically provides menu items for quitting, hiding the app, hiding the other apps, as well as the Edit functionality of copy and paste.

I start by creating a new Cocoa Application project in Project Builder. In the resources group of the project, I add an new empty file called "script" which will contain my shell script. We'll start with a simple script:

#!/bin/sh
gzip -9 "$@"

This script will compress files with gzip using the maximum compression level.

Most Cocoa applications instantiate a controller object. This object reacts to user actions and drives the application. Very often the controller is "owned" by the main user interface; I'll do that for this app, but more on that later. First, I'll consider what the controller needs to do.

For this app, I already know that it needs to be able to open a file, so I'll define a method called open:. open: is what is called an action; actions are methods which are called by other objects in the AppKit to trigger some activity in the application. AppKit interface elements can be set up to invoke an action on another object, called its target. For example, pressing a button or sliding a slider will cause the button or slider to send an action to its target. Action methods always take one argument: the id of the object which sent the action message to the target. The interface for our controller object (which I'll call a DropController) follows:

#import <Foundation/NSObject.h>

@class NSString;

@interface DropController : NSObject

/* Instance variables */
{}

/* Actions */
- (IBAction) open: (id) aSender;

@end

Next, I open up the MainMenu.nib file in the project, which opens in Interface Builder. I then import the header DropController.h (click on the Classes tab, and use the Classes->Read Files... menu item), and instantiate that object (Classes->Instantiate) in the nib file. When the application is launched, the MenMenu.nib interface (which is the main application interface) is loaded automatically. It will in turn instantiate the DropController object. I want the File->Open menu item to invoke the open: action method, so I simply connect the menu item to the controller and set the target method to open:. (You'll be wanting to go through an Interface Builder tutorial if I've lost you; If you want to take my word for it, this is very easy.) And because I won't be needing them, I can delete all of the menu items other than the Apple menu and the File->Open item.

If you are new to Interface Builder, that was the hard part. The rest is a breeze from here.

I need to locate the path to the shell script (or command) I've put into the application (it'll be in the Resources folder within the app), so I'm going to keep that information in an instance variable of the controller. I therefore edit DropController.h to add an instance variable:

/* Instance variables */
{
@private
  NSString* myScriptFileName; //we'll keep the path to the script
}

Side note: I make a habit of always marking my instance variables as private, as allowing other objects to access them directly is almost always a mistake. Subclasses cannot directly modify a private instance variable, instead, they must use the provided API, a core tenet of data encapsulation.

We can begin writing the implementation of the controller (DropController.m) now:

#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
#import "DropController.h"

@implementation DropController

/* Inits */

- (id) init
{
  if ((self = [super init]))
    {
      myScriptFileName =
        [[[NSBundle mainBundle] pathForResource:@"script" ofType:nil] retain];
    }
  return self;
}

- (void) dealloc
{
  [myScriptFileName release];

  [super dealloc];
}

/* Actions */

@end

The init method initializes the instance variables, in this case setting myScriptFileName to the path to the script and retaining the string (marking it so that it isn't deallocated until we are done with it). When the controller is discarded (the app quits), the dealloc method releases the string (expresses the controller's sudden disinterest in the string's safety). Andrew Stone discussed the use and power of NSBundle in his article "Dynamic Bundles and Runtime Loading in OS X" several issues back.

And then I tell the controller how to open a file by implementing the open: action:

/* Actions */

- (void) runScriptWithFiles: (NSArray* ) aFileList
{
  [NSTask launchedTaskWithLaunchPath: myScriptFileName
                           arguments: aFileList];
}

- (IBAction) open: (id) aSender
{
  NSOpenPanel* anOpenPanel = [NSOpenPanel openPanel];

  if ([anOpenPanel runModalForTypes:nil] == NSOKButton)
    {
      [self runScriptWithFiles: [anOpenPanel filenames]];
    }
}

The open: method creates an open panel and runs it modally, then runs the script on the selected files. I put the actual code to run the script in its own method because I'll be needing it again later.

At this point, I have an application which I can launch, then bring up the File->Open menu, and have it run a script on a file (or a few files) for me. But I still need to handle AppleEvents from the Finder or other sources. AppKit makes this easy. The AppKit application object (which I am using already, though I've not had to know it yet) handles AppleEvents for me. All I need it to ask it to tell me when it gets an open message.

First, I go back to the MainMenu.nib in Interface Builder. We need to mark the controller object as the delegate of the application object. A delegate is an object to which another object sends specific methods when something interesting happens. In Interface Builder, we connect the File's Owner object (which, for MainMenu.nib is the application object) to the controller object as the delegate.

If the application's delegate implements the method application:openFile:, the application will automatically call that method whenever the application is asked to open a file, such as with an AppleEvent. (This and other delegate methods are documented in the NSApplication docs.) All I have to do, then, is implement the method:

/* Application delegate */

- (BOOL) application: (NSApplication*) anApplication
    openFile: (NSString*) aFileName
{
  [self runScriptWithFiles: [NSArray arrayWithObject: aFileName]];

  return YES;
}

Now dropping files onto the droplet's icon works! With that, I've finished up the prototype droplet, which can compress files.

Writing the droplet generator

The droplet generator should itself be an application, so that I do not need access to the terminal. In fact, I'd like to be able to write a shell script in Text Edit, and then drop that file onto my droplet generator. That is, the droplet generator itself should be a droplet. Well... huh... I just wrote one of those. All this droplet needs to do different is that instead of compressing a file, it needs to copy the prototype app and replace the shell script inside. Well... huh... I can do that with a shell script a lot more easily that in C (even Objective-C) code. So it seems all I have to do here is replace the gzip script with a script that copies the application (itself!) and puts the new script in the right place. The droplet generator iteself becomes the prototype droplet. (Being lazy, like most programmers, this was an exciting revelation.) A simple script to do this might look like this:

#!/bin/sh -e

ScriptFileName=$1; shift

DropScript="$(echo $0 | sed ‘s|\.app/.*$|\.app|')"
Destination=$(dirname "${ScriptFileName}")
DropperName="Drop"$(basename "${ScriptFileName}" | sed ‘s/\..*$//')
NewDropper="${Destination}/${DropperName}.app"

mkdir "${NewDropper}"
pax -rw . "${NewDropper}"
chmod u+w "${NewDropper}/Contents/Resources/script"
cp -f "${ScriptFileName}" "${NewDropper}/Contents/Resources/script"
chmod 555 "${NewDropper}/Contents/Resources/script"

For more information

The complete source code to DropScript is available via the Darwin CVS server at Apple, in the DropScript CVS module. You can download a pre-built executable from my home page at MIT at
http://www.mit.edu/people/wsanchez/software/.

These are a few features in DropScript which were omitted from this article for simplicity, such as:

  • The primordial shell script is actually more complicated, as it does some rudimentary error checking.
  • In order to emulate the behavior of StuffIt Expander, which is probably the most familiar drop application for Mac OS users, I added a little code to have the droplets quit after processing a file if they weren't otherwise already running.
  • There is now a mechanism by which you can specify the file types that your new droplet accepts within the shell script.
  • There is an about box and a useless preferences panel.

Some commands don't take file names as arguments and most command have some special options you might want to use. The most flexible way to create droplets would therefore be to write a shell (or perl/python/etc) script that takes file name arguments and invkoes the right command(s) with the right option(s), and use that script as the command in your droplet.


Wilfredo SÁnchez wsanchez@mit.edu is an engineering manager at KnowNow, Inc., www.knownow.com, and knows just enough about Cocoa programming to hurt himself and possibly others.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »

Price Scanner via MacPrices.net

New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more
Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more

Jobs Board

DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
IT Systems Engineer ( *Apple* Platforms) - S...
IT Systems Engineer ( Apple Platforms) at SpaceX Hawthorne, CA SpaceX was founded under the belief that a future where humanity is out exploring the stars is Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.