Database error: [Table 'gotow_ben.blog_categories' doesn't exist]
SELECT * FROM blog_categories WHERE 1=1


Warning: Invalid argument supplied for foreach() in /usr/www/users/gotow/gotow.net/blog/wp-blog-header.php on line 235

Database error: [Unknown column 'user_level' in 'where clause']
SELECT * FROM blog_users WHERE user_level > 0


Warning: Invalid argument supplied for foreach() in /usr/www/users/gotow/gotow.net/blog/wp-blog-header.php on line 298

Database error: [Table 'gotow_ben.blog_categories' doesn't exist]
SELECT DISTINCT ID, category_id, cat_name, category_nicename, category_description, category_parent FROM blog_categories, blog_post2cat, blog_posts WHERE category_id = cat_ID AND post_id = ID AND post_id IN (82,79,76,73,71,69,64,60,43,40,38,33,31,28,18,16,14,13,12,11,10,8,9,7,6,5,4,3,1,2)


Warning: Invalid argument supplied for foreach() in /usr/www/users/gotow/gotow.net/blog/wp-blog-header.php on line 478

Warning: Cannot modify header information - headers already sent by (output started at /usr/www/users/gotow/gotow.net/blog/wp-includes/wp-db.php:80) in /usr/www/users/gotow/gotow.net/blog/wp-atom.php on line 8
Gotow.net - Blog Just another WordPress weblog 2012-04-25T07:22:39Z Copyright 2012 WordPress Automatically generating Objective-C .h files from .m files http://www.gotow.net/creative/wordpress?p=82 2012-04-25T07:22:39Z 2012-04-25T07:14:04Z

Database error: [Table 'gotow_ben.blog_categories' doesn't exist]
SELECT category_id, cat_name, category_nicename, category_description, category_parent FROM blog_categories, blog_post2cat WHERE blog_post2cat.category_id = cat_ID AND blog_post2cat.post_id = 82


Warning: Invalid argument supplied for foreach() in /usr/www/users/gotow/gotow.net/blog/wp-includes/template-functions-category.php on line 114
Last weekend I participated in Hack Nashville and built a social pixel-art app called 46px. It was a fun project, but our team of four programmers hacking things together over the course of two days made quite a mess. We rushed to finish the app and one of the first things to go was .h/.m file consistency. Now I need to update most of the project’s .h files to remove warnings. In the past, this has amounted to: Copying the functions, body and all, from the .m file to the .h file. Removing everything in the brackets, adding a semicolon. Repeat for hundreds of functions. That workflow pretty much sucks. It’s not what I want to spend my day doing. I set about to do it a better way and discovered that it isn’t too hard to automate this mess with Automator and BBEdit’s GREP functionality. Cut to the chase, download the Workflow: Copy Function Headers.workflow Here’s the breakdown of Grep functions to perform the above: [objc] // remove all of the lines that are not pragma marks or method declarations 1. Find: ^(?!#pragma)((?!([-+]+[^;{]*)r).)*$r Replace With: <nothing> // Add a semicolon to the end of each method declaration 2. Find: ^([-+]+[^;{-+]*)r Replace With: 1;r // Remove any stray close brackets 3. Find: } Replace With: <nothing> // Identify pragma marks and add a leading and trailing carriage return 4. Find: (#pragma.*) Replace With: r1r // Find places where two or more lines of pragma marks in a row caused a series of three carriage returns in a row. 5. Find: rrr Replace With: r [/objc] I realize this is a hack—hell, that series of grep commands does and then _undoes_ some carriage returns. But at the end of the day, it works pretty well, and you get something like this: [objc] #pragma mark - #pragma mark UITableView Data Source Functions - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; - (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath; - (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)indexPath; #pragma mark - #pragma mark IBActions - (IBAction)helpIconTapped:(id)sender; - (IBAction)questionCountSliderChanged:(NumberRangeView*)slider; - (IBAction)operandRangeSliderChanged:(NumberRangeView*)slider; - (IBAction)timerSliderChanged:(NumberRangeView*)slider; [/objc] To use this Automator Workflow, double click to install it and then go to System Preferences > Keyboard and add a Keyboard Shortcut to Xcode. Tie a hotkey of your choice to the menu item “Copy Function Headers". The new workflow? Select the body of a .m file. Press the hotkey you assigned the action to. Paste into .h file. Enjoy! I hope this saves you as much time as it’s saved me. Download Copy Function Headers.workflow Last weekend I participated in Hack Nashville and built a social pixel-art app called 46px. It was a fun project, but our team of four programmers hacking things together over the course of two days made quite a mess. We rushed to finish the app and one of the first things to go was .h/.m file consistency.

Now I need to update most of the project’s .h files to remove warnings. In the past, this has amounted to:

  1. Copying the functions, body and all, from the .m file to the .h file.
  2. Removing everything in the brackets, adding a semicolon.
  3. Repeat for hundreds of functions.

That workflow pretty much sucks. It’s not what I want to spend my day doing. I set about to do it a better way and discovered that it isn’t too hard to automate this mess with Automator and BBEdit’s GREP functionality.

Cut to the chase, download the Workflow:
Copy Function Headers.workflow

Here’s the breakdown of Grep functions to perform the above:
[objc]
// remove all of the lines that are not pragma marks or method declarations
1. Find: ^(?!#pragma)((?!([-+]+[^;{]*)r).)*$r
Replace With: <nothing>

// Add a semicolon to the end of each method declaration
2. Find: ^([-+]+[^;{-+]*)r
Replace With: 1;r

// Remove any stray close brackets
3. Find: }
Replace With: <nothing>

// Identify pragma marks and add a leading and trailing carriage return
4. Find: (#pragma.*)
Replace With: r1r

// Find places where two or more lines of pragma marks in a row caused a series of three carriage returns in a row.
5. Find: rrr
Replace With: r
[/objc]

I realize this is a hack—hell, that series of grep commands does and then _undoes_ some carriage returns. But at the end of the day, it works pretty well, and you get something like this:

[objc]
#pragma mark -
#pragma mark UITableView Data Source Functions

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath;
- (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)indexPath;

#pragma mark -
#pragma mark IBActions

- (IBAction)helpIconTapped:(id)sender;
- (IBAction)questionCountSliderChanged:(NumberRangeView*)slider;
- (IBAction)operandRangeSliderChanged:(NumberRangeView*)slider;
- (IBAction)timerSliderChanged:(NumberRangeView*)slider;
[/objc]

To use this Automator Workflow, double click to install it and then go to System Preferences > Keyboard and add a Keyboard Shortcut to Xcode. Tie a hotkey of your choice to the menu item “Copy Function Headers".

The new workflow?

  1. Select the body of a .m file.
  2. Press the hotkey you assigned the action to.
  3. Paste into .h file.

Enjoy! I hope this saves you as much time as it’s saved me.

Download Copy Function Headers.workflow

]]>
PNG compression in Android… (You have got to be kidding) http://www.gotow.net/creative/wordpress?p=79 2010-01-08T06:23:23Z 2010-01-08T06:20:33Z

Database error: [Table 'gotow_ben.blog_categories' doesn't exist]
SELECT category_id, cat_name, category_nicename, category_description, category_parent FROM blog_categories, blog_post2cat WHERE blog_post2cat.category_id = cat_ID AND blog_post2cat.post_id = 79


Warning: Invalid argument supplied for foreach() in /usr/www/users/gotow/gotow.net/blog/wp-includes/template-functions-category.php on line 114
Over the last few weeks, I’ve been learning the Android SDK in an effort to bring Layers to Android devices. It’s going pretty well, but every once and a while I run into a truly WTF moment. Tonight I was importing some images from the iPhone version of Layers when I noticed that Android seems to visibly reduce the quality of PNG files at compile time. In images with fine gradients, smooth color transitions, or very light shadows you tend to get banding. It almost looks like the image were being converted to a GIF file. I figured it’d be easy to fix. Go into Eclipse, right click on everything, look in menus… repeat… profit! Unfortunately, it seems there’s no way to turn off compression for specific file or choose a non-lossy compression method. However, I found this gem of a solution in the Android Widget Design Guidelines: “To reduce banding when exporting a widget, apply the following Photoshop Add Noise setting to your graphic.” Um… what now? It turns out, you can get around the compression algorithm by adding a small amount of pixel noise to your images. It’s mostly invisible, and it prevents the compression from producing obvious bands. It’s an instant fix, but I almost laughed out loud. Seriously? This is the documented solution? *sigh*. Over the last few weeks, I’ve been learning the Android SDK in an effort to bring Layers to Android devices. It’s going pretty well, but every once and a while I run into a truly WTF moment.

Tonight I was importing some images from the iPhone version of Layers when I noticed that Android seems to visibly reduce the quality of PNG files at compile time. In images with fine gradients, smooth color transitions, or very light shadows you tend to get banding. It almost looks like the image were being converted to a GIF file.

I figured it’d be easy to fix. Go into Eclipse, right click on everything, look in menus… repeat… profit! Unfortunately, it seems there’s no way to turn off compression for specific file or choose a non-lossy compression method. However, I found this gem of a solution in the Android Widget Design Guidelines:

“To reduce banding when exporting a widget, apply the following Photoshop Add Noise setting to your graphic.”

Um… what now?

It turns out, you can get around the compression algorithm by adding a small amount of pixel noise to your images. It’s mostly invisible, and it prevents the compression from producing obvious bands.

It’s an instant fix, but I almost laughed out loud. Seriously? This is the documented solution? *sigh*.

]]>
iPhone Development Tutorial http://www.gotow.net/creative/wordpress?p=76 2009-10-16T20:39:15Z 2009-10-16T20:35:54Z

Database error: [Table 'gotow_ben.blog_categories' doesn't exist]
SELECT category_id, cat_name, category_nicename, category_description, category_parent FROM blog_categories, blog_post2cat WHERE blog_post2cat.category_id = cat_ID AND blog_post2cat.post_id = 76


Warning: Invalid argument supplied for foreach() in /usr/www/users/gotow/gotow.net/blog/wp-includes/template-functions-category.php on line 114
I gave a presentation within the Engineering school on Friday that gave a brief look at the iPhone platform and Objective-C. The end of the presentation was a quick tutorial in Interface Builder and XCode. You can download the presentation and the tutorial project here: iPhone Development Tutorial iPhoneDevelopmentTutorial.zip If you have any questions, feel free to email me at bengotow@gmail.com or post a comment. Also, be sure to check out layersforiphone.com. I gave a presentation within the Engineering school on Friday that gave a brief look at the iPhone platform and Objective-C. The end of the presentation was a quick tutorial in Interface Builder and XCode. You can download the presentation and the tutorial project here:
iPhone Development Tutorial

iPhoneDevelopmentTutorial.zip

If you have any questions, feel free to email me at bengotow@gmail.com or post a comment. Also, be sure to check out layersforiphone.com.

]]>
Layers featured in Macworld Article on iPhone Piracy! http://www.gotow.net/creative/wordpress?p=73 2009-10-16T20:24:39Z 2009-10-16T20:24:10Z

Database error: [Table 'gotow_ben.blog_categories' doesn't exist]
SELECT category_id, cat_name, category_nicename, category_description, category_parent FROM blog_categories, blog_post2cat WHERE blog_post2cat.category_id = cat_ID AND blog_post2cat.post_id = 73


Warning: Invalid argument supplied for foreach() in /usr/www/users/gotow/gotow.net/blog/wp-includes/template-functions-category.php on line 114
The piracy statistics I posted earlier this month have gathered some attention, and Nick Spence at Macworld.co.uk is running an article about the price of piracy for independent software developers. Check it out! iPhone App piracy: Small time developers feel the pinch UPDATE: The article was pushed to Macworld.com as well! The piracy statistics I posted earlier this month have gathered some attention, and Nick Spence at Macworld.co.uk is running an article about the price of piracy for independent software developers. Check it out!

iPhone App piracy: Small time developers feel the pinch

UPDATE: The article was pushed to Macworld.com as well!

]]>
App Store Piracy: Worse than you think. http://www.gotow.net/creative/wordpress?p=71 2009-08-15T05:16:26Z 2009-08-15T05:16:26Z

Database error: [Table 'gotow_ben.blog_categories' doesn't exist]
SELECT category_id, cat_name, category_nicename, category_description, category_parent FROM blog_categories, blog_post2cat WHERE blog_post2cat.category_id = cat_ID AND blog_post2cat.post_id = 71


Warning: Invalid argument supplied for foreach() in /usr/www/users/gotow/gotow.net/blog/wp-includes/template-functions-category.php on line 114
Two weeks ago, a minor update to Layers hit the App Store. The update included several important bug fixes and a few features, but one of the most major changes was the addition of a piracy tracking system. Each time the app is used on a jailbroken device, it phones home with a few (anonymized) metrics so that I can track the spread of pirated copies. Software on the Layers server gathers the data and prints out some cool statistics. Technically cool, that is. Not really “cool” at all. I’ve sold around 1,500 copies of Layers this week and in the same 7 day period, more than 1,780 copies have been pirated. It’s flattering, to some extent; people obviously enjoy the app. However, it’s also evidence to a much larger problem that I feel Apple continues to overlook. The DRM used in iPhone apps hasn’t been changed in ages, and an app on a jailbroken device can be automatically cracked using another iPhone app in a matter of seconds. No command line tools. No hand-editing files. You double click the app’s icon and it cracks it. Done. For “expensive” apps like Layers, piracy is an especially significant problem. The latest version of Layers runs about 22,000 lines of code, and my community and target market are small. Everyone needs to chip in so I can recoup the cost of development and rationalize extra time spent improving the app. The App Store’s layout and “Top 100″ formatting encourage 99¢ apps with limited utility, so it’s difficult to market a $4.99 drawing app to begin with. (I’ve been lucky enough to be a Staff Favorite on the App Store) Piracy rates above 100% really don’t help. So what do you do? I feel it’s absolutely necessary to weed out the pirates. I wouldn’t mind providing illegitimate users with a time-limited or feature-limited version of the app. The problem is, current methods of screening for pirated copies are binary-dependent and patchable. In about a week, Layers will start displaying notices to pirates asking them to upgrade their “demo” copies of the app to a full version or “buy me a beer.” I hope that a few people will appreciate the app enough after using the pirated copy to consider paying. Even a 5% pirated-to-paid conversion rate would be an extra 15 sales a day. In the future, I’d like to see Apple implement a secure model for confirming that users are licensed to use an app. A secure receipts model is built in to the In-App Purchase system, and I don’t see why it wouldn’t work for the app as a whole. The app would establish a secure connection to an iTunes server, exchange product identifiers and account details, and verify that a product had in fact been purchased. I don’t think Apple will implement anything in the near future, because it would require admitting that piracy was, in fact, an issue. We can dream, though. A few other developers I’ve talked to have suggested creating a repository of device identifiers that have been nabbed during phone-home routines. It seems like a good idea, but I understand there’s some hesitation to start calling people pirates left and right. Apps would need to pre-emptively contact the repository, and a simple change to the UNIX hosts file could break the system. So for now, It looks like I’ll be dreaming of an extra 1,700 sales a week. Two weeks ago, a minor update to Layers hit the App Store. The update included several important bug fixes and a few features, but one of the most major changes was the addition of a piracy tracking system. Each time the app is used on a jailbroken device, it phones home with a few (anonymized) metrics so that I can track the spread of pirated copies. Software on the Layers server gathers the data and prints out some cool statistics.

Technically cool, that is. Not really “cool” at all. I’ve sold around 1,500 copies of Layers this week and in the same 7 day period, more than 1,780 copies have been pirated. It’s flattering, to some extent; people obviously enjoy the app. However, it’s also evidence to a much larger problem that I feel Apple continues to overlook. The DRM used in iPhone apps hasn’t been changed in ages, and an app on a jailbroken device can be automatically cracked using another iPhone app in a matter of seconds. No command line tools. No hand-editing files. You double click the app’s icon and it cracks it. Done.

For “expensive” apps like Layers, piracy is an especially significant problem. The latest version of Layers runs about 22,000 lines of code, and my community and target market are small. Everyone needs to chip in so I can recoup the cost of development and rationalize extra time spent improving the app. The App Store’s layout and “Top 100″ formatting encourage 99¢ apps with limited utility, so it’s difficult to market a $4.99 drawing app to begin with. (I’ve been lucky enough to be a Staff Favorite on the App Store) Piracy rates above 100% really don’t help.

So what do you do? I feel it’s absolutely necessary to weed out the pirates. I wouldn’t mind providing illegitimate users with a time-limited or feature-limited version of the app. The problem is, current methods of screening for pirated copies are binary-dependent and patchable. In about a week, Layers will start displaying notices to pirates asking them to upgrade their “demo” copies of the app to a full version or “buy me a beer.” I hope that a few people will appreciate the app enough after using the pirated copy to consider paying. Even a 5% pirated-to-paid conversion rate would be an extra 15 sales a day.

In the future, I’d like to see Apple implement a secure model for confirming that users are licensed to use an app. A secure receipts model is built in to the In-App Purchase system, and I don’t see why it wouldn’t work for the app as a whole. The app would establish a secure connection to an iTunes server, exchange product identifiers and account details, and verify that a product had in fact been purchased. I don’t think Apple will implement anything in the near future, because it would require admitting that piracy was, in fact, an issue. We can dream, though.

A few other developers I’ve talked to have suggested creating a repository of device identifiers that have been nabbed during phone-home routines. It seems like a good idea, but I understand there’s some hesitation to start calling people pirates left and right. Apps would need to pre-emptively contact the repository, and a simple change to the UNIX hosts file could break the system.

So for now, It looks like I’ll be dreaming of an extra 1,700 sales a week.

]]>
4 1/2 stars! But you can’t compete with sex… http://www.gotow.net/creative/wordpress?p=69 2009-08-04T18:13:39Z 2009-08-04T18:13:39Z

Database error: [Table 'gotow_ben.blog_categories' doesn't exist]
SELECT category_id, cat_name, category_nicename, category_description, category_parent FROM blog_categories, blog_post2cat WHERE blog_post2cat.category_id = cat_ID AND blog_post2cat.post_id = 69


Warning: Invalid argument supplied for foreach() in /usr/www/users/gotow/gotow.net/blog/wp-includes/template-functions-category.php on line 114
Layers finally dropped off the list of top paid entertainment apps on the App Store this week. It’s not all that surprising - for such an expensive app, I was happy to see it on there at all! I think this screenshot pretty much sums up my feelings, though. Of the top 100 entertainment apps, 13 of them are some variant of “hot babe” apps. Looks like you just can’t compete with sex. I’ve heard rumors that Apple is working on a new way of presenting apps that will showcase the more complex apps, and it couldn’t be coming soon enough. Looking at the top 100 lists just makes me lose faith in humanity. It seems like I should be writing hot babe slideshows and fart apps, but I just can’t bring myself to do it… Layers finally dropped off the list of top paid entertainment apps on the App Store this week. It’s not all that surprising - for such an expensive app, I was happy to see it on there at all! I think this screenshot pretty much sums up my feelings, though. Of the top 100 entertainment apps, 13 of them are some variant of “hot babe” apps. Looks like you just can’t compete with sex.

Layers - Not hot babes!

I’ve heard rumors that Apple is working on a new way of presenting apps that will showcase the more complex apps, and it couldn’t be coming soon enough. Looking at the top 100 lists just makes me lose faith in humanity. It seems like I should be writing hot babe slideshows and fart apps, but I just can’t bring myself to do it…

]]>
EXIF Orientation Flags and the iPhone Camera http://www.gotow.net/creative/wordpress?p=64 2009-07-26T03:54:12Z 2009-07-26T03:50:15Z

Database error: [Table 'gotow_ben.blog_categories' doesn't exist]
SELECT category_id, cat_name, category_nicename, category_description, category_parent FROM blog_categories, blog_post2cat WHERE blog_post2cat.category_id = cat_ID AND blog_post2cat.post_id = 64


Warning: Invalid argument supplied for foreach() in /usr/www/users/gotow/gotow.net/blog/wp-includes/template-functions-category.php on line 114
Alright, I have a rant. Bear with me… Layers just came out this past Monday, and it has this great feature that allows you to add a layer to a drawing from your iPhone’s photo library. Simple enough - right? Apple provides the UIImagePicker API, we call a couple functions and get an image back. For most purposes, that would work great! Write some code, test, commit, done. The problem is, the picker interface allows the user to adjust the scale/positioning of the image, and the cropped image is always returned at 320x320px (or less). 320px is really quite pathetic, and it means the images are smaller than the 512x512px drawing canvas in Layers. I could scale up each photo when it’s added to the drawing, but that’d be pretty lame. The UIImagePicker API provides an editInfo dictionary containing the original image and the cropping rect information, so I decided to grab the original and re-perform the adjustments. Using the cropRect provided by the API, I could just re-crop the large, original image to 512x512… right? Unfortunately, no. Photos taken with the iPhone’s camera use the industry-standard EXIF orientation flag to store rotation information. That means that the image data is always saved upright, and it’s the client application’s job to realize it should be rotated 90º, 180º or 270º because the user was holding the camera upside down or sideways. Technically, this is great. The problem is, the editInfo dictionary contains (1) the original image and (2) the crop rect, defined in the coordinate space of the image after the EXIF orientation flag is taken into account. You can’t just jump in and crop the original image, because one has had transformations applied and the other hasn’t. So there are two options: - Option 1: Rotate the original image you’re given based on the EXIF data, and then crop it using the cropRect. This is slow because you have to rotate the entire image and then you end up throwing most of it away. For extremely large images (which can be added into your photo library via Mail attachments), it fails entirely. - Option 2: Adjust the cropping rect and undo the transformations that have been applied to it based on the EXIF data. This is better, but it requires writing some nasty CGRect transformations and lots of boxes drawn on paper. I decided to go with option 2. I wrote a nice big switch statement to undo the transformations for each of the eight possible EXIF values. But then I discovered something else: Somebody was lazy. The iPhone’s Photos application only understands EXIF orientations 1, 3, 6, and 8. These correspond to the common orientations: UIImageOrientationUp, UIImageOrientationDown, UIImageOrientationLeft, and UIImageOrientationRight. Photos with the other four orientations (the “mirrored” ones) appear unrotated in the photo browser. (See screenshot at right. Numbers on the images correspond to their EXIF orientation values). I want the user to get what they expect to get when they add a photo - even if it isn’t what they want. If the image is sideways while they’re cropping it, it should still be sideways when they press OK. I promptly deleted code for the other orientations so as to handle them as badly as the photo browser. Cool. moving on… The image picker allows the user to zoom in on the image of their choosing and pan around it, but the pan functionality is broken. You can pan beyond the edge of the image along the vertical axis, so that image is only partially visible within the gray cropping rectangle. This can lead to some strange results. A cropRect of (0,0,320,200) for an image of size (512,512), for example, indicates that a black gap is present at the top of the crop region. After playing around with this for a while, I was able to figure out how to differentiate between the cropRect values and properly draw the image to appear exactly as it did in the preview. Fixing this problem took almost 5 hours - and it really shouldn’t have. Here’s the code that takes the original image and cropRect and re-performs the adjustments to yield a 512x512 cropped image that matches exactly what the user saw when they clicked “Choose” in the picker: [objc] - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo { if ([picker sourceType] == UIImagePickerControllerSourceTypeCamera){ // save the image to the photo library UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil); } [self dismissModalViewControllerAnimated:YES]; NSDictionary * assets = [NSDictionary dictionaryWithObjectsAndKeys:img, @"smallCroppedImage", editInfo, @"editInfo", nil]; [self performSelector:@selector(imagePickerControllerDidFinishThreaded:) withObject:assets afterDelay:0.05]; } - (void)imagePickerControllerDidFinishThreaded:(NSDictionary*)assets { NSDictionary * editInfo = [assets objectForKey: @"editInfo"]; CGRect editCropRect = [[editInfo valueForKey:UIImagePickerControllerCropRect] CGRectValue]; // 1. Determine original image orientation and size UIImage * originalImage = [editInfo valueForKey: UIImagePickerControllerOriginalImage]; UIImageOrientation originalOrientation = originalImage.imageOrientation; CGSize originalSize = originalImage.size; CGSize desiredSize = CGSizeMake(512,512); // 2. Modify crop rect to reflect image orientation CGFloat oldY = editCropRect.origin.y; CGFloat oldOriginalW = originalSize.width; CGFloat tmp; switch (originalOrientation) { case UIImageOrientationUp: //EXIF 1 break; case UIImageOrientationDown: //EXIF 3 // X flipped horizontally // Y flipped vertically editCropRect.origin.x = originalSize.width - (editCropRect.size.width + editCropRect.origin.x); editCropRect.origin.y = originalSize.height - (editCropRect.size.height + editCropRect.origin.y); break; case UIImageOrientationLeft: //EXIF 6 // fix info for original image. originalSize.width = originalSize.height; originalSize.height = oldOriginalW; // fix crop rect tmp = editCropRect.size.height; editCropRect.size.height = editCropRect.size.width; editCropRect.size.width = tmp; // rotation to the left editCropRect.origin.y = originalSize.height - (editCropRect.origin.x + editCropRect.size.height); editCropRect.origin.x = oldY; break; case UIImageOrientationRight: //EXIF 8 // fix info for original image. originalSize.width = originalSize.height; originalSize.height = oldOriginalW; // fix crop rect tmp = editCropRect.size.height; editCropRect.size.height = editCropRect.size.width; editCropRect.size.width = tmp; // rotate to the right editCropRect.origin.y = editCropRect.origin.x; editCropRect.origin.x = originalSize.height - oldY; break; default: break; } // 2.5. make the damn thing square if it’s ALMOST square if (fabs((editCropRect.size.height - editCropRect.size.width) / fminf(originalSize.height, originalSize.width)) < 0.0295){ editCropRect.size.width = fminf(editCropRect.size.width, editCropRect.size.height); editCropRect.size.height = editCropRect.size.width; } // 3. Crop image using crop rect UIGraphicsBeginImageContext(desiredSize); CGContextRef context = UIGraphicsGetCurrentContext(); CGImageRef image = CGImageCreateWithImageInRect([originalImage CGImage], editCropRect); CGRect imageRect = CGRectMake(0.0f, 0.0f, desiredSize.width, desiredSize.height); // Image width < Image height. Just center vertically if (editCropRect.size.width / editCropRect.size.height < 1){ imageRect.origin.x = (desiredSize.width - editCropRect.size.width * desiredSize.height/editCropRect.size.height)/2; imageRect.size.width -= imageRect.origin.x * 2; // Image width > Image height } else if (editCropRect.size.width / editCropRect.size.height > 1){ float extraHeight = desiredSize.height - editCropRect.size.height * (desiredSize.width / editCropRect.size.width); // If the crop rect’s origin is at the top of the screen, some of it might be clear (IE, the user may // have dragged “too far” and have some white space at the top of the preview box if (editCropRect.origin.y == 0) { imageRect.size.height -= extraHeight; if (roundf(editCropRect.size.height) == roundf(originalSize.height)) imageRect.origin.y = extraHeight / 2; else imageRect.origin.y = 0; // User dragged “too far” down, and white space is visible at the bottom of preview box } else if (fabs(editCropRect.origin.y - (originalSize.height - roundf(editCropRect.size.height))) Alright, I have a rant. Bear with me…

Layers just came out this past Monday, and it has this great feature that allows you to add a layer to a drawing from your iPhone’s photo library. Simple enough - right? Apple provides the UIImagePicker API, we call a couple functions and get an image back.

For most purposes, that would work great! Write some code, test, commit, done. The problem is, the picker interface allows the user to adjust the scale/positioning of the image, and the cropped image is always returned at 320x320px (or less). 320px is really quite pathetic, and it means the images are smaller than the 512x512px drawing canvas in Layers. I could scale up each photo when it’s added to the drawing, but that’d be pretty lame.

The UIImagePicker API provides an editInfo dictionary containing the original image and the cropping rect information, so I decided to grab the original and re-perform the adjustments. Using the cropRect provided by the API, I could just re-crop the large, original image to 512x512… right?

Unfortunately, no. Photos taken with the iPhone’s camera use the industry-standard EXIF orientation flag to store rotation information. That means that the image data is always saved upright, and it’s the client application’s job to realize it should be rotated 90º, 180º or 270º because the user was holding the camera upside down or sideways.

Technically, this is great. The problem is, the editInfo dictionary contains (1) the original image and (2) the crop rect, defined in the coordinate space of the image after the EXIF orientation flag is taken into account. You can’t just jump in and crop the original image, because one has had transformations applied and the other hasn’t. So there are two options:

- Option 1: Rotate the original image you’re given based on the EXIF data, and then crop it using the cropRect. This is slow because you have to rotate the entire image and then you end up throwing most of it away. For extremely large images (which can be added into your photo library via Mail attachments), it fails entirely.
- Option 2: Adjust the cropping rect and undo the transformations that have been applied to it based on the EXIF data. This is better, but it requires writing some nasty CGRect transformations and lots of boxes drawn on paper.

I decided to go with option 2. I wrote a nice big switch statement to undo the transformations for each of the eight possible EXIF values. But then I discovered something else:

iPhone Photos App with Different EXIF Orientation FlagsSomebody was lazy. The iPhone’s Photos application only understands EXIF orientations 1, 3, 6, and 8. These correspond to the common orientations: UIImageOrientationUp, UIImageOrientationDown, UIImageOrientationLeft, and UIImageOrientationRight. Photos with the other four orientations (the “mirrored” ones) appear unrotated in the photo browser. (See screenshot at right. Numbers on the images correspond to their EXIF orientation values).

I want the user to get what they expect to get when they add a photo - even if it isn’t what they want. If the image is sideways while they’re cropping it, it should still be sideways when they press OK. I promptly deleted code for the other orientations so as to handle them as badly as the photo browser. Cool. moving on…

iPhone Photos App - Weird Vertical Pan BehaviorThe image picker allows the user to zoom in on the image of their choosing and pan around it, but the pan functionality is broken. You can pan beyond the edge of the image along the vertical axis, so that image is only partially visible within the gray cropping rectangle. This can lead to some strange results. A cropRect of (0,0,320,200) for an image of size (512,512), for example, indicates that a black gap is present at the top of the crop region. After playing around with this for a while, I was able to figure out how to differentiate between the cropRect values and properly draw the image to appear exactly as it did in the preview.

Fixing this problem took almost 5 hours - and it really shouldn’t have. Here’s the code that takes the original image and cropRect and re-performs the adjustments to yield a 512x512 cropped image that matches exactly what the user saw when they clicked “Choose” in the picker:

[objc]
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo
{
if ([picker sourceType] == UIImagePickerControllerSourceTypeCamera){
// save the image to the photo library
UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil);
}

[self dismissModalViewControllerAnimated:YES];

NSDictionary * assets = [NSDictionary dictionaryWithObjectsAndKeys:img, @"smallCroppedImage", editInfo, @"editInfo", nil];
[self performSelector:@selector(imagePickerControllerDidFinishThreaded:) withObject:assets afterDelay:0.05];
}

- (void)imagePickerControllerDidFinishThreaded:(NSDictionary*)assets
{
NSDictionary * editInfo = [assets objectForKey: @"editInfo"];
CGRect editCropRect = [[editInfo valueForKey:UIImagePickerControllerCropRect] CGRectValue];

// 1. Determine original image orientation and size
UIImage * originalImage = [editInfo valueForKey: UIImagePickerControllerOriginalImage];
UIImageOrientation originalOrientation = originalImage.imageOrientation;
CGSize originalSize = originalImage.size;
CGSize desiredSize = CGSizeMake(512,512);

// 2. Modify crop rect to reflect image orientation
CGFloat oldY = editCropRect.origin.y;
CGFloat oldOriginalW = originalSize.width;
CGFloat tmp;

switch (originalOrientation) {
case UIImageOrientationUp: //EXIF 1
break;

case UIImageOrientationDown: //EXIF 3
// X flipped horizontally
// Y flipped vertically
editCropRect.origin.x = originalSize.width - (editCropRect.size.width + editCropRect.origin.x);
editCropRect.origin.y = originalSize.height - (editCropRect.size.height + editCropRect.origin.y);
break;

case UIImageOrientationLeft: //EXIF 6
// fix info for original image.
originalSize.width = originalSize.height;
originalSize.height = oldOriginalW;

// fix crop rect
tmp = editCropRect.size.height;
editCropRect.size.height = editCropRect.size.width;
editCropRect.size.width = tmp;

// rotation to the left
editCropRect.origin.y = originalSize.height - (editCropRect.origin.x + editCropRect.size.height);
editCropRect.origin.x = oldY;
break;

case UIImageOrientationRight: //EXIF 8
// fix info for original image.
originalSize.width = originalSize.height;
originalSize.height = oldOriginalW;

// fix crop rect
tmp = editCropRect.size.height;
editCropRect.size.height = editCropRect.size.width;
editCropRect.size.width = tmp;

// rotate to the right
editCropRect.origin.y = editCropRect.origin.x;
editCropRect.origin.x = originalSize.height - oldY;
break;

default:
break;
}

// 2.5. make the damn thing square if it’s ALMOST square
if (fabs((editCropRect.size.height - editCropRect.size.width) / fminf(originalSize.height, originalSize.width)) < 0.0295){
editCropRect.size.width = fminf(editCropRect.size.width, editCropRect.size.height);
editCropRect.size.height = editCropRect.size.width;
}

// 3. Crop image using crop rect
UIGraphicsBeginImageContext(desiredSize);
CGContextRef context = UIGraphicsGetCurrentContext();
CGImageRef image = CGImageCreateWithImageInRect([originalImage CGImage], editCropRect);
CGRect imageRect = CGRectMake(0.0f, 0.0f, desiredSize.width, desiredSize.height);

// Image width < Image height. Just center vertically
if (editCropRect.size.width / editCropRect.size.height < 1){
imageRect.origin.x = (desiredSize.width - editCropRect.size.width * desiredSize.height/editCropRect.size.height)/2;
imageRect.size.width -= imageRect.origin.x * 2;

// Image width > Image height
} else if (editCropRect.size.width / editCropRect.size.height > 1){
float extraHeight = desiredSize.height - editCropRect.size.height * (desiredSize.width / editCropRect.size.width);

// If the crop rect’s origin is at the top of the screen, some of it might be clear (IE, the user may
// have dragged “too far” and have some white space at the top of the preview box
if (editCropRect.origin.y == 0) {
imageRect.size.height -= extraHeight;
if (roundf(editCropRect.size.height) == roundf(originalSize.height))
imageRect.origin.y = extraHeight / 2;
else
imageRect.origin.y = 0;

// User dragged “too far” down, and white space is visible at the bottom of preview box
} else if (fabs(editCropRect.origin.y - (originalSize.height - roundf(editCropRect.size.height))) <= 1.1) {
imageRect.origin.y = extraHeight;
imageRect.size.height -= extraHeight;

}else {
imageRect.origin.y = (desiredSize.height - editCropRect.size.height * desiredSize.width/editCropRect.size.width)/2;
imageRect.size.height -= imageRect.origin.y * 2;
}
}

CGContextClearRect(context, CGRectMake(0,0,desiredSize.width,desiredSize.height));
CGContextDrawImage(context, imageRect, image);
UIImage* croppedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRelease(image);

// 4. Perform image rotation
UIImage * finalImage = [self rotateImage: croppedImage byOrientationFlag: originalOrientation];

// DO SOMETHING WITH finalImage!
}

#pragma mark Convenience Functions for Image Picking

- (UIImage*)rotateImage:(UIImage*)img byOrientationFlag:(UIImageOrientation)orient
{
CGImageRef imgRef = img.CGImage;
CGFloat width = CGImageGetWidth(imgRef);
CGFloat height = CGImageGetHeight(imgRef);
CGAffineTransform transform = CGAffineTransformIdentity;
CGRect bounds = CGRectMake(0, 0, width, height);
CGSize imageSize = bounds.size;
CGFloat boundHeight;

switch(orient) {

case UIImageOrientationUp: //EXIF = 1
transform = CGAffineTransformIdentity;
break;

case UIImageOrientationDown: //EXIF = 3
transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
transform = CGAffineTransformRotate(transform, M_PI);
break;

case UIImageOrientationLeft: //EXIF = 6
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
transform = CGAffineTransformScale(transform, -1.0, 1.0);
transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
break;

case UIImageOrientationRight: //EXIF = 8
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
break;

default:
// image is not auto-rotated by the photo picker, so whatever the user
// sees is what they expect to get. No modification necessary
transform = CGAffineTransformIdentity;
break;

}

UIGraphicsBeginImageContext(bounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();

if ((orient == UIImageOrientationDown) || (orient == UIImageOrientationRight) || (orient == UIImageOrientationUp)){
// flip the coordinate space upside down
CGContextScaleCTM(context, 1, -1);
CGContextTranslateCTM(context, 0, -height);
}

CGContextConcatCTM(context, transform);
CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return imageCopy;
}
[/objc]

I hope that it saves you time - please leave a comment below if you find it useful! Also - I’ve attached a ZIP file with eight images that can be used to debug problems with EXIF orientation handling. Each image has a different EXIF orientation flag value, and a giant number in the center of the image lets you know what it is. On the Mac desktop, all eight will appear to be vertical because QuickLook properly adjusts them based on their EXIF values. Other apps, like Fireworks, will open them sideways, upside-down, backwards, etc… Enjoy!

Download EXIF Orientation Sample Images (44MB)

]]>
Mac OS X Stack Overflow Status Item! http://www.gotow.net/creative/wordpress?p=60 2009-07-06T04:09:07Z 2009-07-06T04:08:01Z

Database error: [Table 'gotow_ben.blog_categories' doesn't exist]
SELECT category_id, cat_name, category_nicename, category_description, category_parent FROM blog_categories, blog_post2cat WHERE blog_post2cat.category_id = cat_ID AND blog_post2cat.post_id = 60


Warning: Invalid argument supplied for foreach() in /usr/www/users/gotow/gotow.net/blog/wp-includes/template-functions-category.php on line 114
I’ve become a huge fan of Stack Overflow over the last few weeks. The community there is helpful and fast and there are quite a few questions about Cocoa and Objective-C! It’s gotten to the point where I visit SO whenever my code is compiling - so I thought it was time to take matters into my own hands and make things easier to follow. I’ve made a Stack Overflow status item for Mac OS X (also a “menu bar item” or a “system icon") that shows your reputation and lists questions on the front page containing your interesting tags: It’s pretty primitive at this point - you can click a question to view it, or click the tiny arrow to go to your user page. It updates every 90 seconds using the RSS and ATOM feeds from the site, so the most active questions are always available at a glance. It’s compatible with Mac OS X 10.5 and 10.6 - so download it and give it a shot! I know there are a lot of things that could be added - so leave a comment and let me know what you think. Download the Stack Overflow Status Item for Mac OS X (0.5 MB) I’ve become a huge fan of Stack Overflow over the last few weeks. The community there is helpful and fast and there are quite a few questions about Cocoa and Objective-C! It’s gotten to the point where I visit SO whenever my code is compiling - so I thought it was time to take matters into my own hands and make things easier to follow.

I’ve made a Stack Overflow status item for Mac OS X (also a “menu bar item” or a “system icon") that shows your reputation and lists questions on the front page containing your interesting tags:

SO Status Item in Action

It’s pretty primitive at this point - you can click a question to view it, or click the tiny arrow to go to your user page. It updates every 90 seconds using the RSS and ATOM feeds from the site, so the most active questions are always available at a glance. It’s compatible with Mac OS X 10.5 and 10.6 - so download it and give it a shot! I know there are a lot of things that could be added - so leave a comment and let me know what you think.

Download the Stack Overflow Status Item for Mac OS X (0.5 MB)

]]>
PackBits algorithm in Objective-C http://www.gotow.net/creative/wordpress?p=43 2009-07-26T04:09:52Z 2009-05-25T05:09:18Z

Database error: [Table 'gotow_ben.blog_categories' doesn't exist]
SELECT category_id, cat_name, category_nicename, category_description, category_parent FROM blog_categories, blog_post2cat WHERE blog_post2cat.category_id = cat_ID AND blog_post2cat.post_id = 43


Warning: Invalid argument supplied for foreach() in /usr/www/users/gotow/gotow.net/blog/wp-includes/template-functions-category.php on line 114
The PackBits algorithm is one of the TIFF data compression methods, and it’s also used for pixel data in Photoshop PSD and TGA files. It was originally developed for MacPaint, and although it’s still widely used, there isn’t a whole lot of information online about it. I spent some time this weekend writing a category to extend the NSData class and support the packBits algorithm, and I think I’ve finally got it. PackBits is really dirt simple. If you have a string of hex values like 00 00 00 FF FF FF FF, it replaces series of  3 or more identical bytes with a count, and then the repeated byte. The input above would be 03 00 04 FF. A prefix is also attached to series of different bytes so the decoder knows how many bytes to pass through before looking for another header byte. The full documentation of PackBits can be found on Wikipedia. My implementation is a modified version of the one available here: http://michael.dipperstein.com/rle/index.html (source link at very bottom of page). That implementation is a modification of the official PackBits algorithm that allows slightly larger runs of data to be encoded in a single header + byte pair. I was interested in the original implementation only (since data written from any customized encoder could not be opened by a standard decoder) so I changed it back to the standard algorithm. The primary function provided in the PackBitsAdditions category below is: [objc] - (NSData*)packedBitsForRange:(NSRange)range skip:(int)skip[/objc] This function returns the packBits representation of the data in “range", advancing “skip” bytes with each read. For instance, to read and encode every byte in “range", you would provide skip = 1. To read and encode only every 4th byte, you would pass skip = 4. This may seem like an odd implementation, but it’s very handy when you need to encode the channels of an RGBA image separately (as in PSD format). The other function in the category is packedBitsDescription. It describes the packed bits and the process that would be followed to decode them. This function could be easily extended to actually decode the data. If you find this code useful, please leave a comment! I debugged this for quite a while, and I’d be happy to help if you run into any issues with my implementation! NSDataPackBitsAdditions.h [objc] @interface NSData (PackBitsAdditions) - (NSString*)packedBitsDescription; - (NSData*)packedBitsForRange:(NSRange)range skip:(int)skip; @end [/objc] NSDataPackBitsAdditions.m [objc] @implementation NSData (PackBitsAdditions) - (NSString*)packedBitsDescription { NSMutableString * description = [NSMutableString string]; char * row = (char*)[self bytes]; int pbOffset = 0; int pbResultBytes = 0; while (pbOffset < [self length]){ int headerByte = (int)row[pbOffset]; if (headerByte < 0){ int repeatTimes = 1-headerByte; UInt8 repeatByte = (UInt8)row[pbOffset+1]; [description appendFormat: @"Printing %u %d times. ", repeatByte, repeatTimes]; pbResultBytes += repeatTimes; pbOffset += 2; } else if (headerByte >= 0){ [description appendFormat: @"Printing %d literal bytes. ", headerByte + 1]; pbResultBytes += headerByte + 1; pbOffset += 2 + headerByte; } } [description appendFormat: @"Total: %d bytes decoded.", pbResultBytes]; return description; } - (NSData*)packedBitsForRange:(NSRange)range skip:(int)skip { char * bytesIn = [self bytes]; int bytesLength = range.location + range.length; int bytesOffset = range.location; NSMutableData * dataOut = [NSMutableData data]; BOOL currIsEOF = NO; unsigned char currChar; /* current character */ unsigned char charBuf[MAX_READ]; /* buffer of already read characters */ int count; /* number of characters in a run */ /* prime the read loop */ currChar = bytesIn[bytesOffset]; bytesOffset = bytesOffset + skip; count = 0; /* read input until there’s nothing left */ while (!currIsEOF) { charBuf[count] = (unsigned char)currChar; count++; if (count >= MIN_RUN){ int i; /* check for run charBuf[count - 1] .. charBuf[count - MIN_RUN]*/ for (i = 2; i <= MIN_RUN; i++){ if (currChar != charBuf[count - i]){ /* no run */ i = 0; break; } } if (i != 0){ /* we have a run write out buffer before run*/ int nextChar; if (count > MIN_RUN){ /* block size - 1 followed by contents */ UInt8 a = count - MIN_RUN - 1; [dataOut appendBytes:&a length:sizeof(UInt8)]; [dataOut appendBytes:&charBuf length:sizeof(unsigned char) * (count - MIN_RUN)]; } /* determine run length (MIN_RUN so far) */ count = MIN_RUN; while (true){ if (bytesOffset < bytesLength){ nextChar = bytesIn[bytesOffset]; bytesOffset += skip; } else { currIsEOF = YES; nextChar = EOF; } if (nextChar != currChar) break; count++; if (count == MAX_RUN){ /* run is at max length */ break; } } /* write out encoded run length and run symbol */ UInt8 a = ((int)(1 - (int)(count))); [dataOut appendBytes:&a length:sizeof(UInt8)]; [dataOut appendBytes:&currChar length:sizeof(UInt8)]; if ((!currIsEOF) && (count != MAX_RUN)){ /* make run breaker start of next buffer */ charBuf[0] = nextChar; count = 1; } else { /* file or max run ends in a run */ count = 0; } } } if (count == MAX_READ){ int i; /* write out buffer */ UInt8 a = MAX_COPY - 1; [dataOut appendBytes:&a length:sizeof(UInt8)]; [dataOut appendBytes:&charBuf[0] length:sizeof(unsigned char) * MAX_COPY]; /* start a new buffer */ count = MAX_READ - MAX_COPY; /* copy excess to front of buffer */ for (i = 0; i < count; i++) charBuf[i] = charBuf[MAX_COPY + i]; } if (bytesOffset < bytesLength) currChar = bytesIn[bytesOffset]; else currIsEOF = YES; bytesOffset += skip; } /* write out last buffer */ if (0 != count){ if (count <= MAX_COPY){ /* write out entire copy buffer */ UInt8 a = count - 1; [dataOut appendBytes:&a length:sizeof(UInt8)]; [dataOut appendBytes:&charBuf length:sizeof(unsigned char) * count]; } else { /* we read more than the maximum for a single copy buffer */ UInt8 a = MAX_COPY - 1; [dataOut appendBytes:&a length:sizeof(UInt8)]; [dataOut appendBytes:&charBuf length:sizeof(unsigned char) * MAX_COPY]; /* write out remainder */ count -= MAX_COPY; a = count - 1; [dataOut appendBytes:&a length:sizeof(UInt8)]; [dataOut appendBytes:&charBuf[MAX_COPY] length:sizeof(unsigned char) * count]; } } return dataOut; } @end [/objc] The PackBits algorithm is one of the TIFF data compression methods, and it’s also used for pixel data in Photoshop PSD and TGA files. It was originally developed for MacPaint, and although it’s still widely used, there isn’t a whole lot of information online about it. I spent some time this weekend writing a category to extend the NSData class and support the packBits algorithm, and I think I’ve finally got it.

PackBits is really dirt simple. If you have a string of hex values like 00 00 00 FF FF FF FF, it replaces series of  3 or more identical bytes with a count, and then the repeated byte. The input above would be 03 00 04 FF. A prefix is also attached to series of different bytes so the decoder knows how many bytes to pass through before looking for another header byte.

The full documentation of PackBits can be found on Wikipedia. My implementation is a modified version of the one available here: http://michael.dipperstein.com/rle/index.html (source link at very bottom of page). That implementation is a modification of the official PackBits algorithm that allows slightly larger runs of data to be encoded in a single header + byte pair. I was interested in the original implementation only (since data written from any customized encoder could not be opened by a standard decoder) so I changed it back to the standard algorithm.

The primary function provided in the PackBitsAdditions category below is:

[objc] - (NSData*)packedBitsForRange:(NSRange)range skip:(int)skip[/objc]

This function returns the packBits representation of the data in “range", advancing “skip” bytes with each read. For instance, to read and encode every byte in “range", you would provide skip = 1. To read and encode only every 4th byte, you would pass skip = 4. This may seem like an odd implementation, but it’s very handy when you need to encode the channels of an RGBA image separately (as in PSD format).

The other function in the category is packedBitsDescription. It describes the packed bits and the process that would be followed to decode them. This function could be easily extended to actually decode the data.

If you find this code useful, please leave a comment! I debugged this for quite a while, and I’d be happy to help if you run into any issues with my implementation!

NSDataPackBitsAdditions.h

[objc]

@interface NSData (PackBitsAdditions)

- (NSString*)packedBitsDescription;
- (NSData*)packedBitsForRange:(NSRange)range skip:(int)skip;

@end
[/objc]

NSDataPackBitsAdditions.m

[objc]
@implementation NSData (PackBitsAdditions)

- (NSString*)packedBitsDescription
{
NSMutableString * description = [NSMutableString string];
char * row = (char*)[self bytes];
int pbOffset = 0;
int pbResultBytes = 0;

while (pbOffset < [self length]){
int headerByte = (int)row[pbOffset];
if (headerByte < 0){
int repeatTimes = 1-headerByte;
UInt8 repeatByte = (UInt8)row[pbOffset+1];
[description appendFormat: @"Printing %u %d times. ", repeatByte, repeatTimes];

pbResultBytes += repeatTimes;
pbOffset += 2;
} else if (headerByte >= 0){
[description appendFormat: @"Printing %d literal bytes. ", headerByte + 1];
pbResultBytes += headerByte + 1;
pbOffset += 2 + headerByte;
}
}

[description appendFormat: @"Total: %d bytes decoded.", pbResultBytes];
return description;
}

- (NSData*)packedBitsForRange:(NSRange)range skip:(int)skip
{
char * bytesIn = [self bytes];
int bytesLength = range.location + range.length;
int bytesOffset = range.location;
NSMutableData * dataOut = [NSMutableData data];

BOOL currIsEOF = NO;
unsigned char currChar; /* current character */
unsigned char charBuf[MAX_READ]; /* buffer of already read characters */
int count; /* number of characters in a run */

/* prime the read loop */
currChar = bytesIn[bytesOffset];
bytesOffset = bytesOffset + skip;
count = 0;

/* read input until there’s nothing left */
while (!currIsEOF)
{
charBuf[count] = (unsigned char)currChar;
count++;

if (count >= MIN_RUN){
int i;

/* check for run charBuf[count - 1] .. charBuf[count - MIN_RUN]*/
for (i = 2; i <= MIN_RUN; i++){
if (currChar != charBuf[count - i]){
/* no run */
i = 0;
break;
}
}

if (i != 0){
/* we have a run write out buffer before run*/
int nextChar;

if (count > MIN_RUN){
/* block size - 1 followed by contents */
UInt8 a = count - MIN_RUN - 1;
[dataOut appendBytes:&a length:sizeof(UInt8)];
[dataOut appendBytes:&charBuf length:sizeof(unsigned char) * (count - MIN_RUN)];
}

/* determine run length (MIN_RUN so far) */
count = MIN_RUN;
while (true){
if (bytesOffset < bytesLength){
nextChar = bytesIn[bytesOffset];
bytesOffset += skip;
} else {
currIsEOF = YES;
nextChar = EOF;
}
if (nextChar != currChar) break;

count++;
if (count == MAX_RUN){
/* run is at max length */
break;
}
}

/* write out encoded run length and run symbol */
UInt8 a = ((int)(1 - (int)(count)));
[dataOut appendBytes:&a length:sizeof(UInt8)];
[dataOut appendBytes:&currChar length:sizeof(UInt8)];

if ((!currIsEOF) && (count != MAX_RUN)){
/* make run breaker start of next buffer */
charBuf[0] = nextChar;
count = 1;
} else {
/* file or max run ends in a run */
count = 0;
}
}
}

if (count == MAX_READ){
int i;

/* write out buffer */
UInt8 a = MAX_COPY - 1;
[dataOut appendBytes:&a length:sizeof(UInt8)];
[dataOut appendBytes:&charBuf[0] length:sizeof(unsigned char) * MAX_COPY];

/* start a new buffer */
count = MAX_READ - MAX_COPY;

/* copy excess to front of buffer */
for (i = 0; i < count; i++)
charBuf[i] = charBuf[MAX_COPY + i];
}

if (bytesOffset < bytesLength)
currChar = bytesIn[bytesOffset];
else
currIsEOF = YES;
bytesOffset += skip;
}

/* write out last buffer */
if (0 != count){
if (count <= MAX_COPY){
/* write out entire copy buffer */
UInt8 a = count - 1;
[dataOut appendBytes:&a length:sizeof(UInt8)];
[dataOut appendBytes:&charBuf length:sizeof(unsigned char) * count];
}
else
{
/* we read more than the maximum for a single copy buffer */
UInt8 a = MAX_COPY - 1;
[dataOut appendBytes:&a length:sizeof(UInt8)];
[dataOut appendBytes:&charBuf length:sizeof(unsigned char) * MAX_COPY];

/* write out remainder */
count -= MAX_COPY;
a = count - 1;
[dataOut appendBytes:&a length:sizeof(UInt8)];
[dataOut appendBytes:&charBuf[MAX_COPY] length:sizeof(unsigned char) * count];
}
}

return dataOut;
}

@end
[/objc]

]]>
Custom compiler flags in XCode http://www.gotow.net/creative/wordpress?p=40 2009-04-01T03:40:37Z 2009-04-01T03:39:55Z

Database error: [Table 'gotow_ben.blog_categories' doesn't exist]
SELECT category_id, cat_name, category_nicename, category_description, category_parent FROM blog_categories, blog_post2cat WHERE blog_post2cat.category_id = cat_ID AND blog_post2cat.post_id = 40


Warning: Invalid argument supplied for foreach() in /usr/www/users/gotow/gotow.net/blog/wp-includes/template-functions-category.php on line 114
So I’ve been messing with compiler flags in XCode for the last hour or so, and it turns out I was totally misunderstanding things. If you get info on a project or target in XCode, there’s a “User-Defined” section at the bottom that allows you to create your own flags for use at compile time. However, these flags are not actually passed into GCC! (Mistake 1!) I assumed that adding a key-value pair to the list would pass the flag straight through to GCC, but it appears that they are for use in build scripts, etc… To pass a custom flag through to GCC so that you can use it in #ifdef and #if macros at compile time, you have to add a User-Defined Setting called “OTHER_CFLAGS". For my project, I set the value to “-DIS_PHOTO_CHAT=1″. At compile time, the exact text is passed as an argument to GCC. You can set different values in different targets - and I was able to conditionally include some code in a header file using #if (IS_PHOTO_CHAT==1)… It seems like you can use XCode’s built-in flags like ${TARGET_NAME} and ${PRODUCT_NAME} to insert variables into the value of OTHER_CFLAGS, but if your target name has spaces, I think you’re at a loss. I tried to set -DTARGET_NAME=${TARGET_NAME} for about an hour, but the target name had a space and I can’t get GCC to accept the value (tried quotes… no luck…) I’m no command-line-compiler-whiz, so I’m sure there’s a trick, but Google hasn’t turned anything up. I’m still surprised OTHER_CFLAGS wasn’t preset to “” in the target build settings. There’s an empty field for “Other Code Signing Flags” (which seems less useful!) Oh well… Guess XCode is in permanent beta anyway? So I’ve been messing with compiler flags in XCode for the last hour or so, and it turns out I was totally misunderstanding things. If you get info on a project or target in XCode, there’s a “User-Defined” section at the bottom that allows you to create your own flags for use at compile time. However, these flags are not actually passed into GCC! (Mistake 1!) I assumed that adding a key-value pair to the list would pass the flag straight through to GCC, but it appears that they are for use in build scripts, etc…

To pass a custom flag through to GCC so that you can use it in #ifdef and #if macros at compile time, you have to add a User-Defined Setting called “OTHER_CFLAGS". For my project, I set the value to “-DIS_PHOTO_CHAT=1″. At compile time, the exact text is passed as an argument to GCC. You can set different values in different targets - and I was able to conditionally include some code in a header file using #if (IS_PHOTO_CHAT==1)…

It seems like you can use XCode’s built-in flags like ${TARGET_NAME} and ${PRODUCT_NAME} to insert variables into the value of OTHER_CFLAGS, but if your target name has spaces, I think you’re at a loss. I tried to set -DTARGET_NAME=${TARGET_NAME} for about an hour, but the target name had a space and I can’t get GCC to accept the value (tried quotes… no luck…) I’m no command-line-compiler-whiz, so I’m sure there’s a trick, but Google hasn’t turned anything up.

I’m still surprised OTHER_CFLAGS wasn’t preset to “” in the target build settings. There’s an empty field for “Other Code Signing Flags” (which seems less useful!) Oh well… Guess XCode is in permanent beta anyway?

]]>