Vincent Gable’s Blog

February 18, 2009

Competing Software Engineering Approaches

Filed under: Cocoa,Programming,Quotes,UNIX | , , , , ,
― Vincent Gable on February 18, 2009

Tim Bray,

…Palm’s approach is
radically different from both Android’s and Apple’s. Since they’re all here
at more or less the same time, running the
same Web browser on roughly
equivalent hardware, this represents an unprecedented experiment in
competitive software-engineering approaches.

Language Framework Notes
Apple Objective-C Cocoa Old-school object-oriented language compiled to the metal; general-purpose UI
framework with roots reaching back to NeXT.
Android Java Android Java language, custom VM, built-from-scratch UI
framework aimed at small-form-factor devices, fairly abstraction-free, based
on “Actions” and “Intents”.
web OS JavaScript “Mojo” All Web technology all the time. Innovative and visually-impressive
“card”-based UI.

(I think it’s interesting to see Windows Mobile on the list:

Windows Mobile C/C++ Windows CE/.NET Micro Philosophically tries to bring Windows to the phone. When I did WinCE development it felt like doing C++ for a Windows OS from the past.

)

I see way too many other factors to attribute success/failure of the devices to the language. So I wouldn’t call this an experiment.

But it is interesting how much development for each platform diverges at a fundamental level!

Historically most operating systems —
UNIX, OS/2, Linux, Windows, Solaris, Mac (Classic and OS X) — were predominantly, written in C/C++. While each platform has it’s own frameworks, they all have strong support for C++ development. (Although Mac OS X has is slowly dropping support for it’s C/C++ “Carbon” API, and Windows wants to be moving to C# .NET)

It’s really cool to see mobile platforms doing something radically different from each other. There are good arguments for each approach — may the best one win.

October 5, 2008

Restarting Your Mac OS X Cocoa Application

Filed under: Bug Bite,Cocoa,MacOSX,Objective-C,Programming,UNIX | , ,
― Vincent Gable on October 5, 2008

Restarting your own application is a tricky thing to do, because you can’t tell yourself to start up when you aren’t running. Here is one solution, use NSTask to run a very short script that you can embed right in your Objective-C code:
kill -9 YourPID
open PathToYourApp

Something to be aware of, kill -9 will immediately terminate your application, without going through the usual applicationWillTerminate: business that happens when an application quits more gracefully.

- (void) restartOurselves
{
   //$N = argv[N]
   NSString *killArg1AndOpenArg2Script = @"kill -9 $1 \n open \"$2\"";
   
   //NSTask needs its arguments to be strings
   NSString *ourPID = [NSString stringWithFormat:@"%d",
                  [[NSProcessInfo processInfo] processIdentifier]];
   
   //this will be the path to the .app bundle,
   //not the executable inside it; exactly what `open` wants
   NSString * pathToUs = [[NSBundle mainBundle] bundlePath];
   
   NSArray *shArgs = [NSArray arrayWithObjects:@"-c", // -c tells sh to execute the next argument, passing it the remaining arguments.
                killArg1AndOpenArg2Script,
                @"", //$0 path to script (ignored)
                ourPID, //$1 in restartScript
                pathToUs, //$2 in the restartScript
                nil];
   NSTask *restartTask = [NSTask launchedTaskWithLaunchPath:@"/bin/sh" arguments:shArgs];
   [restartTask waitUntilExit]; //wait for killArg1AndOpenArg2Script to finish
   NSLog(@"*** ERROR: %@ should have been terminated, but we are still running", pathToUs);
   assert(!"We should not be running!");
}

WARNING: don’t make the same mistake that I did and test restartOurselves without some kind of guard to keep your application from restarting forever. It is very difficult to kill such a beast, because whenever it starts up it takes keyboard focus away from what you are doing…. well I’m sure you get the idea.

- (BOOL) weHaveRunBefore {
   NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
   BOOL weHaveRunBefore = [prefs boolForKey:@"weHaveRunBefore"];
   [prefs setBool:YESs forKey:@"weHaveRunBefore"];
   [prefs synchronize];
   return weHaveRunBefore;
}

August 22, 2008

Is an Application Running?

Filed under: Cocoa,MacOSX,Objective-C,Programming,Sample Code,UNIX | ,
― Vincent Gable on August 22, 2008

UPDATED 2009-01-13 to correctly detect background applications.

Pass in the bundle-identfier of an application, and this will tell you if it’s currently running or not:
- (BOOL) ThereIsARunningApplicationWithBundleID:(NSString*)bundleID; {
   ProcessSerialNumber PSN = {kNoProcess};
   while(GetNextProcess(&PSN) == noErr) {
      CFDictionaryRef info = ProcessInformationCopyDictionary(&PSN,kProcessDictionaryIncludeAllInformationMask);
      if(info) {
         NSString *theirBundleID = (NSString*)CFDictionaryGetValue(info, kIOBundleIdentifierKey);
         BOOL bundleIDMatches = [bundleID isEqualTo:(NSString*)theirBundleID];
         CFRelease(info);
         if(bundleIDMatches)
            return YES;
      }
   }
   return NO;
}

(It’s a good idea to test if an application is running before sending it an AppleEvent, because that will launch it.)

Interestingly, none of the the Process Manager APIs can see into another user’s process-space; but ps can; at least on OS X 10.5 and 10.4.

August 17, 2008

launchctl Gotcha

Filed under: Bug Bite,MacOSX,Programming,UNIX | , ,
― Vincent Gable on August 17, 2008

On Mac OS X 10.5, the launchd you talk to as non-root user is not the same launchd you talk to when root. So
$ launchctl list
$ sudo launchctl list
print out different lists, and the unprivileged `launchctl list` contains processes that the root-`launchctl list` does not know about. So running a launctl command as root may cause it to fail.

I have never seen another UNIX-ish tool that would fail when run as root, but succeed otherwise.

July 7, 2008

Programatically Excluding Things from Time Machine Backups

Filed under: Cocoa,MacOSX,Objective-C,Programming,UNIX | , ,
― Vincent Gable on July 7, 2008

To exclude files/folders from a Time Machine backup, you can use the C-function CSBackupSetItemExcluded().

As far as I know there isn’t an official way to do this from the command-line or a shell script. As near as I can tell, the safest way to it without using compiled C-code is:

sudo defaults write /Library/Preferences/com.apple.TimeMachine \
SkipPaths -array-add "PATH-ONE" "PATH-TWO"

where "PATH-ONE" "PATH-TWO" are of course paths to items you want to exclude.

Credit to Ellis Jordan Bojar for this solution. (original article) Using defaults instead of tinkering with .plist files directly is really the way to go!

May 4, 2008

Getting Mac OS X Version Information

Filed under: MacOSX,Objective-C,Programming,Sample Code,UNIX | , ,
― Vincent Gable on May 4, 2008

Cocoa

For a human-readable string, use [[NSProcessInfo processInfo] operatingSystemVersionString]. It looks like “Version 10.5 (Build 9A581)”, but that format might change in the future. NSProcessInfo.h explicitly warns against using it for parsing. It will always be human-readable though.

For machine-friendly numbers, use the Gestalt function, with one of the selectors:
gestaltSystemVersionMajor (in 10.4.17 this would be the decimal value 10)
gestaltSystemVersionMinor (in 10.4.17 this would be the decimal value 4)
gestaltSystemVersionBugFix (in 10.4.17 this would be the decimal value 17)
Do not use gestaltSystemVersion unless your code needs to run on OS X 10.2 or earlier. It’s a legacy function that can’t report minor/bugfix versions > 9; meaning it can’t distinguish between 10.4.9 and 10.4.11. The CocoaDev wiki has example code that works in 10.0 if you need to go that route.

Here’s a simpler example of using Gestalt:

- (BOOL) usingLeopard {
  long minorVersion, majorVersion;
  Gestalt(gestaltSystemVersionMajor, &majorVersion);
  Gestalt(gestaltSystemVersionMinor, &minorVersion);
  return majorVersion == 10 && minorVersion == 5;
}

Scripts

For scripts and command-line work, there is the sw_vers command.
$ sw_vers
ProductName: Mac OS X
ProductVersion: 10.5
BuildVersion: 9A581
$ sw_vers -productName
Mac OS X
$ sw_vers -productVersion
10.5
$ sw_vers -buildVersion
9A581

Java

Check the value of:

System.getProperty("os.name");
System.getProperty("os.version");

Fallback

Finally, if you must, you can parse /System/Library/CoreServices/SystemVersion.plist — but I don’t like the idea of doing that. There’s a chance that the file could have been corrupted or maliciously altered. It seems safer, and less complicated, to directly ask the operating system it’s version.

Minimum OS Requirements

To enforce a minimum OS requirement for your application, you can set the LSMinimumSystemVersion key in the Info.plist file. Big Nerd Ranch has a more robust, user-friendly, but complicated solution for older legacy systems.

March 18, 2008

Finding your laptop’s location with a shell command

Filed under: MacOSX,Programming,Sample Code,Tips,UNIX | ,
― Vincent Gable on March 18, 2008

Every wireless access point has a MAC address — a 48 bit number that uniquely identifies it. By checking the MAC address of the wireless access point your computer is connected to, you can figure out if it is being used at home, in your office, etc.

You can read this value from the shell with the command:
arp `ipconfig getoption en1 router`
Here’s how it works. The command ipconfig getoption en1 router gets the IP address of the router for the interface en1, which is the name of the Airport interface. If you want to get the router connected to the ethernet port use en0. The output of the command looks like:
128.62.96.1

arp prints information about the IP address, including the MAC address. arp is a little tricky in that it needs to take the address as an argument, you can’t pipe the output from ipconfig into it — that’s why ipconfig getoption en1 router is surrounded in “. Output from arp 128.62.96.1 looks like:
cisco-128-62-96-1.public.utexas.edu (128.62.96.1) at 0:12:44:f:5f:0 on en1 [ethernet]

The MAC address is in there, but you may need to use a regular expression to get at it. Here is an example of a perl script which prints just the MAC address of the wireless access point, or an error message.

if (qx{arp `ipconfig getoption en1 router`} =~ /([0-9A-Fa-f]{1,2}:[0-9A-Fa-f]{1,2}:[0-9A-Fa-f]{1,2}:[0-9A-Fa-f]{1,2}:[0-9A-Fa-f]{1,2}:[0-9A-Fa-f]{1,2})/){
   print "$1\n";
} else {
   print "Error; wireless internet is most likely unavailable\n";
}

This is essentially how IMLocation determines location.

In summary: Using the shell commands: arp `ipconfig getoption en1 router`, and the regular expression ([0-9A-Fa-f]{1,2}:[0-9A-Fa-f]{1,2}:[0-9A-Fa-f]{1,2}:[0-9A-Fa-f]{1,2}:[0-9A-Fa-f]{1,2}:[0-9A-Fa-f]{1,2}) on it’s output, you can get the MAC-address of the wireless access point your computer is using. This gives you the computer’s location in about a 150 foot radius.

EDITED TO ADD: Another way to get this information is to use the private tool: /System/Library/PrivateFrameworks/Apple80211.framework/Resources/airport
-s gives a list of surrounding networks; -I gives information about the current network.
Try /System/Library/PrivateFrameworks/Apple80211.framework/Resources/airport --help for more information.

You can even get the MAC address of all visible base-stations this way. Unfortunately, any system update could change the Apple80211.framework enough to break your code.

March 13, 2008

Useful Mac OS X Text-Editing Shortcuts

Filed under: MacOSX,Tips,UNIX,Usability | , , ,
― Vincent Gable on March 13, 2008

Here is a handful of lesser-known Mac OS X keyboard shortcuts that I’ve found to be very useful for working with text. They work in all standard text-fields, which means they work in most programs. Sadly, they don’t work in Microsoft products, and a few other apps that use non-standard text fields.

option = you will see the mouse cursor into a + , and you can now select columns of text! Unfortunately it only seems to work in editable text-fields, which is a great shame.

ctrl + d = forward delete, even if you don’t have it on your MacBook’s keyboard.

ctrl + a = Go to the beginning of the line the insertion-point is on.

ctrl + e = Go to the beginning end of the line line the insertion-point is on.

ctrl + k = “kill the current line”, deletes everything from the right of the insertion point to the next newline. This is very useful in Terminal, because you can delete the tail of a long command

command + delete = “Delete To Beginning Of Line”. Just like ctrl+k, but backwards, not forwards. (It even puts the killed text on the yank-pasteboard — don’t worry if that makes no sense, it’s an emacs-ism I don’t find useful.)

And yes, that’s ctrl, not command, because these are shortcuts inherited from the old UNIX text-editor emacs. There are more emacs “key bindings” that are available, but I have never found them useful. This long list of Mac OS X keyboard shortcuts includes them.

command + ctrl + d = look up the word under the mouse in the dictionary. I can’t believe that other operating systems haven’t done this for decades, it’s that useful.

It is unfortunate when programs use text-fields that do not support commands the operating system should give to every application. It’s always a mistake. Fundamentally, not supporting ctrl+a (go to beginning) is no different then not supporting command+c (copy).

If you find these commands useful, please teach them, and let developers know it’s a problem when you can’t use them. That will improve computing for everyone.

March 5, 2008

Calling the Command Line from Cocoa

Filed under: Cocoa,MacOSX,Objective-C,Programming,Tips,UNIX | , , , ,
― Vincent Gable on March 5, 2008

The best way to call a shell-command from Coca is by using an NSTask. Here are the three resources on using an NSTask that I found the most helpful:
CocoDev’s write up
A few quick exaples
NSTask Class Refrence

And here is some sample code to do it for you. You are free to use this code however you please, but attribution is always appreciated. The two principle functions are:

+ (NSString*) executeShellCommandSynchronously:(NSString*)command executes the command “command” with sh, wait until it finishes, and return whatever it printed to stdout and stderr as an NSString.
CAUTION: may deadlock under some circumstances if the output gets so big it fills the pipe. See http://dev.notoptimal.net/search/label/NSTask for an overview of the problem, and a solution. I have not experienced the problem myself, so I can’t comment.

executeShellCommandAsynchronously: will have sh execute command in the background, without blocking anything.

For quick hacks, the POSIX int system(const char* command) function, might be a good one-line solution. It synchronously evaluates command with sh.

Enjoy!

EDITED 2009-11-29: this code probably won’t have the same $PATH you would get if you used Terminal. See this question on stackoverflow for more details. A solution that seems to work is to do,

    [task setLaunchPath:@"/bin/bash"];
    NSArray	*args = [NSArray arrayWithObjects:@"-l",
    				 @"-c",
    				 commandlineHere,
    				 nil];
    [task setArguments: args];

This launches bash (not in sh compatibility mode), and -l (lowercase L) tells it to “act as if it had been invoked as a login shell”. I haven’t tested this on systems where bash isn’t the default shell. There are lots of ways $PATH could be set, and I haven’t tested them all. But you are almost certainly going to be OK if everything you refer to is in /usr/bin:/bin:/usr/sbin:/sbin.

February 28, 2008

Useful MacOSX Terminal Commands

Filed under: MacOSX,Tips,UNIX | , ,
― Vincent Gable on February 28, 2008

Here are some OS X specific terminal commands that I have found useful, and you might not be aware of. Running man command in the Terminal will give you more information about command as it is on your system.

open
open file will open file the same way it would have been opened if you double-clicked it in the Finder. You can also specify what program to use to open the file.

pbcopy, pbpaste
Bridges the clipboard and the command line; you can pipe the clipboard into stdout, or pipe stdout into the clipboard.

ps -axww
Lists every process running on the system, and gives the full-path to them, and their PSN. I almost never use any other arguments to ps.

osascript
Execute an AppleScript. osascript -e “code-goes-here”, will execute the AppleScript inside the “”. This is a great way to get AppleScript functionality in a good scripting language.

ditto
Can do the work of cp or zip, but it does the right thing on OS X, and won’t throw away Mac-specific bits.
ditto -ckX --rsrc --keepParent path_to_a_bundledFile.bundle bundledFile.bundle.zip will compress path_to_a_bundledFile.bundle, and keep all the Mac-bits intact.

hdiutil
Create and manipulate disk-images; you can even use it to burn a disk-image to CD/DVD.
Inside a perl-script I do:
hdiutil create -ov -fs HFS+ -format UDBZ -volname \”IMLocation v$version (beta)\” -srcfolder $IMLBuildDir ~/Projects/Website/imlocation/IMLocation.dmg

To make the disk-image for IMLocation out of the contents of the directory $IMLBuildDir.

screencapture
Lets you take a screenshot. Unfortunately not very well documented.
screencapture -x /tmp/screen.png
Will silently take a screenshot, and save it to /tmp/screen.png.
I think this could be great for bug-reporting.

system_profiler
Reports system hardware and software configuration; with no arguments it reports everything. Obviously great for bug reports and research.

sw_vers
Prints version information about the Mac OS X.
$ sw_vers
ProductName: Mac OS X
ProductVersion: 10.5
BuildVersion: 9A581
$ sw_vers -productName
Mac OS X
$ sw_vers -productVersion
10.5
$ sw_vers -buildVersion
9A581

systemsetup
Configuration tool for certain machine settings in System Preferences.

defaults
Read and write application preferences. You can use it to discover and activate hidden settings, like Safari’s Debug menu. defaults read > all_defaults.txt will give you a grep-able text-file with every default on your system. It’s also a useful tool for automated testing, since you can twiddle configurations.

class-dump (3rd party tool)
Makes .h files from a binary. Great for reverse-engineering.

In addition to standard UNIX commands, Mac OS X includes many powerful command-line tools. This article only scratches the surface, and ignores many tools like podcast that are probably very useful, but aren’t part of my workflow.

Older Posts »

Powered by WordPress