FRAppliance 101

From AwkwardTV
Revision as of 14:17, 31 March 2007 by EricIII (talk | contribs) (New page: This is the first in a likely series of tutorials on writing Apple TV Finder.app plugins. The basic setup of Xcode and the development environment will be described, and a simple "Hello W...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This is the first in a likely series of tutorials on writing Apple TV Finder.app plugins. The basic setup of Xcode and the development environment will be described, and a simple "Hello World" plugin will be created.

Prerequisites

  • Mac OS X 10.4
  • Xcode 2.4.1
  • BackRow.framework and iPhotoAccess.framework from the Apple TV (see below)
  • BackRow headers (either class-dumped yourself, or a starter set from ATVFiles 0.1.0 is located at: http://ericiii.net/sa/appletv/FRApplianceTutorial/BackRow.zip). This tutorial assumes you're using the starter set (see note at end for details.)
  • Knowledge of object-oriented programming, especially in Objective-C and Cocoa.
  • Familiarity with Xcode and the shell is assumed.

Note: These instructions are written for a PowerPC Macintosh. Some steps, especially regarding build architecture settings, may not be necessary on an Intel Mac but are still recommended.

Preparing the Environment

  1. Install Xcode and especially the Mac OS X 10.4 Universal (10.4u) SDK.
  2. Copy the BackRow.framework and iPhotoAccess.framework from /System/Library/PrivateFrameworks on the Apple TV to some place on your computer. I recommend placing these in the same folder your project folder will be created.

Creating the Plugin

Now the fun stuff starts, actually creating the plugin.

Making the Project

Launch Xcode, and create a new Cocoa Bundle project (File > New Project...). Name it "HelloWorld".

At this point, you have an empty project with no code. You now need to specify the frameworks to link to.

Adding Frameworks

In the Frameworks and Libraries group, drag BackRow.framework and iPhotoAccess.framework to the Linked Frameworks group. In the dialog that pops up, make sure "Copy items into destination group's folder" is unchecked and choose a Reference Type of "Default". In "Add to Targets," the HelloWorld target should be checked. Click "Add".

In order for the workaround for the plug-in whitelist to work, you must also link to the ExceptionHandling framework. To do this, right click on Linked Frameworks and choose Add > Existing Frameworks..., and choose "ExceptionHandling.framework" in /System/Library/ExceptionHandling.framework. Click "Add".

At this point, you should have four frameworks listed underneath "Linked Frameworks:" ExceptionHandling.framework, BackRow.framework, iPhotoAccess.framework, and Cocoa.framework.

Headers

One last step, you must add the BackRow headers to the project.

Add the headers by dragging them to the folder containing the header files to just underneath the "HelloWorld" item at the top of the Groups & Files list. You'll see a marker indicating where they'll be added. In the dialog, check "Copy items into destination group's folder" and "Recursively create groups for any added folders."

Creating the Plugin

Open InfoPlist.strings (for English) and add the following lines:

 CFBundleName = "Hello, World!";

The CFBundleName is the label that will be given in the main menu.

The Main Appliance Class

Now you finally write some code! Right click on the Classes group and choose Add > New File..., under Cocoa add an Objective-C class and give it a name of "HelloWorldAppliance". Check "Also create HelloWorldAppliance.h", make sure you're adding to project HelloWorldTest, and the HelloWorld target is checked. Click on "Finish".

Open HelloWorldAppliance.h and change it so that your HelloWorldAppliance class inherits from BRAppliance. Change "NSObject" in the line beginning with "@interface" to read "BRAppliance".

You also need to add the following lines to the header, just underneath the existing "#import" line:

 #import <BRAppliance.h>
 #import <BRAlertController.h>
 

Open HelloWorldAppliance.m now, and in order to bypass the plugin whitelist, you must put the following code in the HelloWorldAppliance implementation. Add this line before the @implementation line:

 static IMP gOrigLoadAppliancePtr = (IMP)0;
 

And put this code before the @end line:

// Override to allow FrontRow to load custom appliance plugins
+ (NSString *) className {
    // this function creates an NSString from the contents of the
    // struct objc_class, which means using this will not call this
    // function recursively, and it'll also return the *real* class
    // name.
    NSString * className = NSStringFromClass( self );
	
    if ( gOrigLoadAppliancePtr == 0 ) {
      // get original function address
      // one implementation is raw C code, which may be more reliable
      // (can't be overridden by the target class)
      /*
      Class c = objc_getClass( "BRApplianceManager" );
      Method m = class_getInstanceMethod( c, @selector( _loadApplianceInfoAtPath: ) );
      if ( m != NULL )
      gOrigLoadAppliancePtr = (_loadApplianceInfoAtPath_fn) m->method_imp;
      */
      gOrigLoadAppliancePtr = [BRApplianceManager instanceMethodForSelector:
          @selector( _loadApplianceInfoAtPath: )];
    }
	
    @try {
        [NSException raise: NSGenericException format: @"backtracing"];
    } @catch(NSException * e) {
        [e _addExceptionHandlerStackTrace];
        NSArray * trace = [[[e userInfo] objectForKey: @"NSStackTraceKey"]
                           componentsSeparatedByString: @"  "];
        if ( [trace count] > 2 ) {
            void * test = (void *) gOrigLoadAppliancePtr;
            NSString * callerStr = [trace objectAtIndex:1];
			      unsigned int caller;
            [[NSScanner scannerWithString: callerStr] scanHexInt:&caller];
			
            // an arbitrary number -- function is a little over a
            // kilobyte in size, but the className call is near the
            // beginning anyway
            if ( ((void *)caller > test) && ((void *)caller < test + 1000) ) {
                NSLog(@"+[%@ className] called for whitelist check, so I'm lying, m'kay?",
                             className );
                className = @"RUICalibrationAppliance";
            }
        }
    }
	
    return ( className );
}

When the menu item is selected, the -applianceControllerWithScene: method is called on your BRAppliance subclass. This method needs to return a controller for your display. (Note: I'll write more on how the displays actually work in the future, but it's essentially a stack of controllers that are pushed to go deeper in the hierarchy and popped to go back.)

The following implementation uses the BRAlertController class to display a simple "Hello, World" message when the item is selected.

- (id)applianceControllerWithScene:(id)scene {
	BRAlertController *alert = [BRAlertController alertOfType:0
               titled:@"Hello, World!"
               primaryText:@"Hello from my first Apple TV plugin!"
               secondaryText:nil
               withScene:scene];
	return alert;
}

Building the Plugin

This isn't very hard, but you have to set some settings first.

Build Settings

Before you can properly build, you must adjust some build settings to build for the Apple TV environment.

Under the "Targets" group on the left side of the Xcode project window, right click on the "HelloWorld" target and choose "Get Info."

On the "Properties" tab, change Identifier to something unique, such as "org.awkwardtv.HelloWorldAppliance". Change the Creator to "fnrw", and set Principal Class to "HelloWorldAppliance" (this must match the BRAppliance subclass for your plugin).

On the "Build" tab, set configuration to "All Configurations" and then set the build settings as follows:

In the "Architectures" collection, double click on the Architectures setting and make sure only Intel is checked. This is a value of "i386".

In "Build Locations," make sure the SDK Path is set to "/Developer/SDKs/MacOSX10.4u.sdk" (it should be by default).

In "Linking," make sure ZeroLink is unchecked.

In "Packaging," set the Wrapper Extension to "frappliance."

In "Language" (underneath "GNU C/C++ Compiler 4.0"), make sure "Enable Objective-C Exceptions" is checked.

Building

At this point, you can just click Build to build the plugin. The compiled version will appear in build/Debug/HelloWorldTest.frappliance in your project folder. The whitelist workaround causes some warnings when building, but those can be ignored.

Running the Plugin

To run it, just copy the built version to /System/Library/CoreServices/Finder.app/Contents/PlugIns on the Apple TV. I really recommend at least creating a symlink to the frappliance in the frontrow home directory, if not directly mounting the project from your development system, but both are beyond the scope of the tutorial.

After it's in place on the Apple TV, you need to restart Finder (either with killall Finder if you have killall installed, otherwise use ps awx|grep Finder to get the PID and then kill PID.)

Now when you choose the "Hello, World!" menu item on the Apple TV, you should see the message!

Congratulations!

If you've successfully made it this far, you've created your first plugin!

A completed xcode project can be found at http://ericiii.net/sa/appletv/FRApplianceTutorial/HelloWorld.zip. This is set up for the two frameworks are in the same folder as the HelloWorld project folder.

A Note about the BackRow Headers

The headers generated from class-dump are available here: http://ericiii.net/sa/appletv/BackRowHeaders.zip. These cannot be used as-is in Xcode, and require some minor modifications to clean them up. The starter set mentioned above contains cleaned up versions of a small number of the headers.