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

X Lossless Decoder 20201123 - Encode, tr...
X Lossless Decoder(XLD) is a tool for Mac OS X that is able to decode/convert/play various 'lossless' audio files. The supported audio files can be split into some tracks with cue sheet when decoding... Read more
Blackmagic Disk Speed Test 3.3 - Measure...
Blackmagic Disk Speed Test is an easy to use tool to quickly measure and certify your disk performance for working with high quality video! Simply click the start button and Disk Speed Test will... Read more
FotoMagico 5.6.14 - Powerful slideshow c...
FotoMagico lets you create professional slideshows from your photos and music with just a few, simple mouse clicks. It sports a very clean and intuitive yet powerful user interface. High image... Read more
calibre 5.6.0 - Complete e-book library...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital librarian... Read more
VOX 3.3.18 - Music player that supports...
VOX just sounds better! The beauty is in its simplicity, yet behind the minimal exterior lies a powerful music player with a ton of features and support for all audio formats you should ever need.... Read more
Apple Safari 14.0.1 - Apple's Web b...
Apple Safari is Apple's web browser that comes bundled with the most recent macOS. Safari is faster and more energy efficient than other browsers, so sites are more responsive and your notebook... Read more
MenuMeters 2.1.1 - CPU, memory, disk, an...
MenuMeters is a set of CPU, memory, disk, and network monitoring tools for Mac OS X. Although there are numerous other programs which do the same thing, none had quite the feature set I was looking... Read more
iTubeDownloader 6.5.26 - Easily download...
iTubeDownloader is a powerful-yet-simple YouTube downloader for the masses. Because it contains a proprietary browser, you can browse YouTube like you normally would. When you see something you want... Read more
Duet 2.3.2.6 - Use your iPad as an exter...
Duet is the first app that allows you to use your iDevice as an extra display for your Mac using the Lightning or 30-pin cable. Note: This app requires a $9.99 iOS companion app. Version 2.3.2.6:... Read more
DaisyDisk 4.12.1 - $9.99
DaisyDisk allows you to visualize your disk usage and free up disk space by quickly finding and deleting big unused files. The program scans your disk and displays its content as a sector diagram... Read more

Latest Forum Discussions

See All

Street Kart Racing will hold a Virtual S...
Street Kart Racing has teamed up with SKUSA to launch the Virtual Supernats, “Virtual Las Vegas” following the real-world event being cancelled due to Covid. The live in-game event starts on November 29th and will last for six days. During this... | Read more »
Puppoz is a cutesy balloon popping game...
Puppoz is a new, cutesy action game from developer Superstar Games that sees a bunch of canines darting about different levels popping balloons. It's a free game that you can download now for both iOS and Android devices. [Read more] | Read more »
Lara Croft returns in Tomb Raider Reload...
Square Enix has unveiled the next entry in the Tomb Raider series, this time headed for mobile platforms sometime in 2021. [Read more] | Read more »
Genshin Impact - Fallen Star Challenge G...
| Read more »
New update for The Battle of Polytopia p...
The Battle of Polytopia released on PC back in August of this year with iOS and Android versions being dated too far behind. But now developer Midjiwan AB has released the Moonrise update to put it on the same level as its PC counterpart, bringing... | Read more »
Transport City: Truck Tycoon is a logist...
Transport City: Truck Tycoon is a brand new simulation game from developer Cupgum that's available now for iOS and Android. As you can probably guess from the name of the game it'll see you working on building a supply chain and logistics setup... | Read more »
Bridge Constructor: The Walking Dead is...
Headup Games' team up with their popular bridge-building franchise and AMC's zombie TV is now available for iOS and Android. Bridge Constructor: The Walking Dead is the latest game in the series and the second to make use of another IP after... | Read more »
Genshin Impact - How to Beat Tartaglia (...
In the 1.1 update to Genshin Impact, the final chapter to the story arc in Liyue reaches its climax with a fight against Tartaglia (AKA Childe), one of the Fatui Harbingers. We won't go into detail as to why this is or the circumstances of the... | Read more »
Genshin Impact - Unreconciled Stars Even...
Genshin Impact's 1.1 update has brought a ton of new content to the game, and one of these things is a brand new event: Unreconciled Stars. This event kicked off yesterday and is running through the end of the month. There are sweet rewards and... | Read more »
The next expansion for Gwent, “Way of th...
CD Projekt Red has announced Way of the Witcher, the next free expansion for its card game, Gwent: The Witcher Card Game. You won’t have long to wait either, as it’s coming to the game on 8th December. [Read more] | Read more »

Price Scanner via MacPrices.net

Shop at Apple’s online store on Cyber Monday,...
Apple’s Cyber Monday 2020 event is now live and runs through Monday night. Receive a free $150 Apple Store gift card with the purchase of select Macs and $50-$100 with various iPads. Get a $50 Apple... Read more
B&H launches Cyber Monday 2020 sale: Take...
Apple’s new 2020 13″ MacBook Airs with M1 Apple Silicon CPUs are now on sale at B&H Photo for $100-$110 off MSRP, starting at $999, as part of their Cyber Monday 2020 sales event. Free expedited... Read more
B&H launches Cyber Monday Apple iPad Air...
B&H Photo has new 2020 10.9″ Apple iPad Airs in stock and on sale today for up to $50 off MSRP as part of their Cyber Monday 2020 sale. Many configurations are in stock today, and expedited... Read more
B&H Cyber Monday 2020 sale: $400 off Appl...
B&H Photo has 16″ MacBook Pros on sale today for $300-$400 off Apple’s MSRP, starting at $2099, as part of their Cyber Monday 2020 sale. Expedited shipping is free to many addresses in the US.... Read more
Cyber Monday clearance Apple sale: 2020 13″ 1...
Apple reseller B&H Photo has clearance 2020 13″ 1.4GHz Intel-based MacBook Pros on sale today for $1099, $200 off Apple’s original MSRP, as part of their Cyber Monday 2020 sale. Expedited... Read more
Best Black Friday/Cyber Monday Deal: New 13″...
Apple’s new 2020 13″ MacBook Pros with M1 Apple Silicon CPUs are on sale at B&H Photo for $100 off MSRP, starting at $1199, as part of their Black Friday/Cyber Monday 2020 sales event. Free... Read more
The cheapest no-contract Apple iPhones availa...
Looking for the cheapest new Apple iPhone this Black Friday/Cyber Monday 2020 shopping weekend? Several of Apple’s wireless carriers are offering free iPhones if you sign up for new service spread... Read more
Looking for a 13″ 2GHz Intel-based MacBook Pr...
Apple has a full line of Certified Refurbished 2020 13″ 2.0GHz 4-Core Touch Bar MacBook Pros, with 10th generation Intel processors, available starting at $1529 and up to $300 off MSRP. Apple’s one-... Read more
Black Friday at Amazon: 512GB & 1TB 11″ i...
Amazon has 2020 11″ WiFi iPad Pros in 512GB and 1TB configurations on sale for $150 off Apple’s MSRP as part of their Black Friday 2020 sale. These are the same iPad Pros sold by Apple in its retail... Read more
Black Friday Sale: Apple Watch Series 3 avail...
Amazon has Apple Watch Series 3 GPS models on sale for $80 off MSRP, starting at only $119.99, as part of their Black Friday 2020 sale. Their prices are the lowest available for these models from any... Read more

Jobs Board

Branch Relationship Banker I - *Apple* Ave...
Description Apple Ave Branch - Muskegon, MI - The Relationship Banker is a Financial Concierge for our walk in customers. You are responsible for building customer Read more
Solutions Partner Marketing Specialist, *App...
Solutions Partner Marketing Specialist, Apple Tempe, AZ, US Requisition Number:79115 As aSolutions Partner Marketing Specialistfor Apple at Insight, you will be Read more
Senior Data Engineer - *Apple* - Theorem, L...
Job Summary Apple is seeking an experienced, detail-minded data engineeringconsultant to join our worldwide business development and strategy team. If you are Read more
Cub Foods - *Apple* Valley - Now Hiring Par...
Cub Foods - Apple Valley - Now Hiring Part Time! United States of America, Minnesota, Apple Valley Retail Post Date Nov 18, 2020 Requisition # 124800 Sign Up for Read more
*Apple* Test Engineer - Vectrus (United Stat...
Overview The Apple Test Engineer (TE) works as part of a team to perform the integration, packaging, testing, and trobleshooting of applications/changes delivered to Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.