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

WhatsApp 2.2136.10 - Desktop client for...
WhatsApp is the desktop client for WhatsApp Messenger, a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS. WhatsApp Messenger is available for... Read more
Thunderbird 91.1.1 - Email client from M...
As of July 2012, Thunderbird has transitioned to a new governance model, with new features being developed by the broader free software and open source community, and security fixes and improvements... Read more
Direct Mail 5.9.1 - Create and send grea...
Direct Mail is an easy-to-use, fully-featured email marketing app purpose-built for macOS. Create, send, and track great looking email campaigns that get results. Start your newsletter by selecting... Read more
LibreOffice 7.2.1.2 - Free, open-source...
LibreOffice is an office suite (word processor, spreadsheet, presentations, drawing tool) compatible with other major office suites. The Document Foundation is coordinating development and... Read more
Steam 2.0 - Multiplayer and communicatio...
Steam is a digital distribution, digital rights management, multiplayer and communications platform developed by Valve Corporation. It is used to distribute a large number of games and related media... Read more
Adobe Acrobat DC 21.007.20091 - Powerful...
Acrobat DC is available only as a part of Adobe Creative Cloud, and can only be installed and/or updated through Adobe's Creative Cloud app. Adobe Acrobat DC with Adobe Document Cloud services is... Read more
Carbon Copy Cloner 6.0.3 - Easy-to-use b...
Carbon Copy Cloner backups are better than ordinary backups. Suppose the unthinkable happens while you're under deadline to finish a project: your Mac is unresponsive and all you hear is an ominous,... Read more
Adobe Animate 21.0.9 - Animation authori...
Adobe Animate is available as part of Adobe Creative Cloud for as little as $20.99/month (or $9.99/month if you're a previous Flash Professional customer). Adobe Animate (was Flash CC) lets you share... Read more
Vivaldi 4.2.2406.44 - An advanced browse...
Vivaldi is a browser for our friends. We live in our browsers. Choose one that has the features you need, a style that fits and values you can stand by. From the look and feel, to how you interact... Read more
Adobe Acrobat Reader 2021.007.20091 - Vi...
Adobe Acrobat Reader allows users to view PDF documents. You may not know what a PDF file is, but you've probably come across one at some point. PDF files are used by companies and even the IRS to... Read more

Latest Forum Discussions

See All

PUBG New State crosses 40 million pre-re...
PUBG New State has received over 40 million pre-registrations on both Android and iOS, Krafton has recently announced. The futuristic, sci-fi PUBG Mobiletitle is all set to launch later this year, in October. [Read more] | Read more »
A Mere Husk of a Human Being – The Touch...
In this week’s episode of The TouchArcade Show I continue to be more or less out of my mind due to the exhaustion of having a newborn baby. Yes, I’ve been through all this before with our previous child, but somehow this is kicking my ass even worse... | Read more »
TouchArcade Game of the Week: ‘Night in...
I have said this probably dozens of times over the years, but there are tons and tons of cool video games on non-mobile platforms that people gush about all the time, and I always tell myself “I’ll definitely get around to playing that myself on [... | Read more »
SwitchArcade Round-Up: ‘Ni no Kuni II’,...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for September 17th, 2021. In today’s article, we finish our look at the new games of the week with the Friday releases. Some fairly big games in the list today, like Ni no Kuni II:... | Read more »
‘LEGO Star Wars Battles’ from TT Games a...
Last month, LEGO Star Wars Battles () was revealed for Apple Arcade. | Read more »
COD Mobile: The 5 best SMGs in the game
COD Mobile is often lauded for its vast array of weapons and elaborate customization. With every update, the guns get some kind of nerfs or buffs. Regardless of that, SMGs remain popular with players for close to mid-range combat. [Read more] | Read more »
SEGA Will Reveal a New Mobile RPG at Tok...
A few days ago, there was a bit of buzz around the listing of a new RPG under SEGA / Atlus for Tokyo Game Show 2021. Tokyo Game Show 2021 begins later this month and both SEGA and Atlus will have games and updates to showcase. SEGA will be revealing... | Read more »
‘Castlevania: Grimoire of Souls’ and ‘Te...
This week’s Apple Arcade roundup has updates to four amazing games on the service and the addition of two new games. The first new game is Castlevania: Grimoire of Souls () from Konami. | Read more »
‘Indies’ Lies’ is a New Roguelike Deck B...
For several years, as the popularity of MegaCrit’s roguelike deck-building game Slay the Spire grew amongst PC gamers, lots and lots of mobile gamers hoped that the game would one day arrive on their mobile devices, where it seemed like a natural... | Read more »
‘Steam Highwayman: Smog & Ambuscade’...
Cubus Games have released a number of interesting gamebooks on mobile for a number of years now, including titles such as Heavy Metal Thunder and The Frankenstein Wars. Now at the end of this month they’ll be adding another to their catalogue with a... | Read more »

Price Scanner via MacPrices.net

This is the final week for Apple’s 2021 Back...
Apple’s Back to School promotion for 2021 continues through September 27, 2021, making this the final full week to take advantage of these offers. As part of this promotion, Apple will include one... Read more
Verizon offers $100 discount on Apple’s new 8...
Verizon has Apple’s new 8.3-inch iPad mini and 9th-generation iPad on sale for $100 off MSRP with an Unlimited service plan. Discount is for 64GB and 256GB cellular-enabled models. The $100 sale... Read more
Apple’s new 9th generation iPad and 8.3-inch...
Amazon is offering preorder discounts on Apple’s new 9th generation iPad and 8.3″ iPad mini (64GB WiFi models) ranging up to $40 off MSRP. Delivery is expected starting September 24th: iPad: – 10″... Read more
Xfinity Mobile offers new Apple iPhone 13 mod...
Xfinity Mobile has Apple’s new iPhone 13 family of smartphones on sale and available for preorder for $300 off MSRP for customers opening a new line of service. No trade-in is required. Cost of the... Read more
Verizon offers free Apple iPhone 13 and iPhon...
Verizon is offering an $800 discount on Apple’s new iPhone 13 and $700 discount on the iPhone 13 mini for new and existing customers with a qualified trade-in. Price of the iPhone 13 will be spread... Read more
Apple Product Announcements, As Of Late, Have...
COMMENTARY: 09.17.21 – If you were left feeling a little, “meh” following Apple’s latest product launch, you’re not alone. On Tuesday — in a pre-recorded virtual event dubbed, “California Streaming... Read more
Verizon offers 25% discount on Apple MagSafe...
Verizon has Apple MagSafe Chargers on sale for 25% off MSRP from 9/16/21 to 9/30/21. Verizon service is not required to take advantage of these savings. With the discount, Verizon’s sale prices are... Read more
Verizon offers $1000 discount on new Apple iP...
Verizon is offering a $1000 discount on Apple’s new iPhone 13 Pro and iPhone 13 Pro Max for new and existing customers with a qualified trade-in. Price of the iPhone 13 Pro will be spread over 24 or... Read more
New at AT&T: Apple iPhone 13 and 13 mini...
We’ve already told you about AT&T’s $1000 discounts on the Apple iPhone 13 Pro and iPhone 13 Pro Max. AT&T now has Apple’s new iPhone 13 and iPhone 13 mini discounted to $700 off MSRP for new... Read more
‘Mac Potpourri’ Story On Apple And Folding Sm...
FEATURE: 09.16.21 – A certain writer has been seemingly thrust into the limelight thanks to an article published last month on MacPrices. The article — a commentary on how Apple must “‘flip’ the... Read more

Jobs Board

Geek Squad *Apple* Consultation Professiona...
**829606BR** **Job Title:** Geek Squad Apple Consultation Professional **Job Category:** Store Associates **Store Number or Department:** 001422-Tualatin-Store **Job Read more
Geek Squad Advanced Repair *Apple* Professi...
**831864BR** **Job Title:** Geek Squad Advanced Repair Apple Professional **Job Category:** Store Associates **Store Number or Department:** 000011-Northtown-Store Read more
Geek Squad *Apple* Consultation Professiona...
**831828BR** **Job Title:** Geek Squad Apple Consultation Professional **Job Category:** Store Associates **Store Number or Department:** 000028-Green Bay-Store Read more
Sr Infrastructure Engineer - *Apple* MacInt...
**Sr Infrastructure Engineer - Apple MacIntosh** **Description** At Bank of the West, our people are having a positive impact on the world. We're investing where we Read more
Senior Software Developer - *Apple* (iOS/tv...
**SUMMARY** Hulu's Apple team is seeking an experienced Senior Software Engineer with a passion for mobile applications to join our team in Seattle. Our highly Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.