The New Carbon

After scratching an itch and developing my new cocoapod TotalObserver, I started to read more about ReactiveCocoa (again) and notice the similarities between what I was doing and RACSignal. This got me thinking about Reactive Programming and how that might fit into Cocoa going forward, when I realized an alignment that can’t be a coincidence. The more I consider it, the more it makes sense. Interest in hearing everyone’s thoughts.

Will today’s Cocoa today be the new Carbon after WWDC 2016? I think Carbon is a good analogy for a new transition Apple has in store for developers on their platforms.

Carbon was originally a partial rewrite of the classic Mac OS toolbox to turn it into an API layer that was portable to the new OS X platform. On OS X Carbon came to be a set of APIs, parallel to Cocoa, that was kept pace for a while but everyone knew wasn’t going to last forever. Over time, all developers eventually migrated to the other OS X API and its language, Cocoa & Objective-C.

Perhaps is Apple planning a similar transition now. However, instead of transitioning between platforms its between languages, Objective-C to Swift. Like Carbon was the API that spanned both OSes, Cocoa will stay for a time as the API that supports both languages, with some small amount of necessary cruft, but there will be a new API paradigm that’s exclusive to Swift.

The analogy is not perfect. In early days of OS X, Cocoa wasn’t new but rather was an evolution of NeXTStep. And anyone adapting an old Mac OS app to Carbon didn’t have a free ride, as it was certainly an API in flux with bugs and quirks on both the old and new platform. To stay relevant Mac OS developers were forced to undergo the transition to keep their customers moving to OS X. Instead the upcoming transition will begin with Cocoa as a solid, fully functional API and language, and after the new platform is unveiled, unmodified Cocoa apps should stay as relevant as before. This new transition will be more of a choice.

The transition form of Cocoa has been underway since Swift 1.0 with piecemeal adoption of the new language allowed, native Swift objects bridged to their Foundation counterparts, and significant amount syntax meant to adapt to Cocoa APIs. For those of us sticking with the old language, added “nullable” qualifiers and collection generics. And this is all before the new platform is unveiled. But all those features I note above have a certain familiar the whiff of compatibility

Its as if we’re in mid-90s and OS X isn’t on anyone’s radar yet but Apple is introducing developers to Carbon as new Mac OS toolbox paradigm for System 7.5. Imagine Apple quietly, confidently working towards NeXTStep as their new OS back then instead of fumbling with Copeland and Taligent.

What will the new platform be? I suspect its a top-to-bottom revamp of the Cocoa APIs on all their platforms, Swift-only, and inspired by Functional Reactive Programming and perhaps MVVM. The few clues to this are in what’s fallen by the wayside in Cocoa, or at least unchanged for years:

KVO and Cocoa Bindings on OS X

When bindings was left out of iOS, not too many OS X developers were complaining. Its hadn’t ever been a great success and I bet Apple was planning its replacement even back then. Apple probably barely entertained bringing it over, or I suspect not at all, even when everything else cool in OS X was seeing a rewrite into iOS if not a straight port. With the exception Objective-C properties getting automatic KVO support and some frameworks like AVFoundation exposing small amounts of functionality exclusively through observed properties, KVO has seen no fresh coats of paint, and no fanfare. WWDC has had no sessions “What’s new in KVO and Bindings”. Since this is withered so long in Cocoa, it likely to be central to the new paradigm. Its further evidence that something like KVO has been left out of Swift to date.

Target-Action & the Responder Chain

This mechanism for connecting control views to their controllers objects goes back to the beginning of NeXTStep, including dragging lines to make connections in Interface Builder. In iOS, controls can have multiple targets instead of just one, but otherwise nothing new. One might suggest that there’s no reason to change what works, and so there’s no evidence of upheaval. However, since blocks were introduced to Objective-C, several parts of the frameworks have adopted them and modernized their interfaces, but not controls and the responser chain. One can easily have imagined a new method like `addTargetBlock:forControlEvent:`, but between 2009 and now there’s been nothing like that. I suspect there’s old sections of the frameworks like this, as well as KVO, for which was thought: don’t bother adding blocks here, we’ll be replacing it completely soon enough.

MVC

This is the encompassing paradigm under the application-level frameworks, again, going back to the beginning of NeXTStep. Since the beginning, window controllers and now view controllers have been a easy place for a large portion of an app’s code to accumulate. Cocoa Bindings and scriptability on OS X were good incentives to architect an application differently and put more logic to the modal layer, but it’s been a struggle for developers to do so. So many iOS apps I see consist mainly of the App Delegate, a slew of UIViewControllers, plus the thinnest of “model objects” to make use of Core Data. The Massive View Controller problem is a constant topic. I don’t see Apple sitting by and letting developers constantly fall into this trap; their developers are too idealistic, in my experience, to continue with the current problematic paradigm this long without a plan in place to address it.

It looks to me like there’s little debate that Reactive Programming, specifically Functional Reactive which ReactiveCocoa is modelled after, leads to simpler and more robust code. It’s a new system of adding observers to objects and events, binding views to models and goes hand-in-hand with MVVM as a new spin on MVC. It hits all the bases, aligning perfectly with the cruftiest pieces of Cocoa that Apple has most neglected. Reactive and FRP specifically was hitting the radar of the early adopters several years ago, perhaps the right time period for Apple to have been starting down the path of replacing Cocoa. And no coincidence, Swift is a big step in the Functional direction from Objective-C. Map and flatmap are standard, and some of us are even learning what the work “monad” means!

I think the writing is on the wall. Apple has had what seems like a moratorium on enhancing some fundamental parts of Cocoa with conveniences for blocks and updated support for Swift, and it seems likely they’ve all been on the chopping block. Old and busted to be replaced by new hotness. And the timing is right, Swift has done a major revision and filled in most of its missing pieces needed for current Cocoa development, everything is set for its next version to leave Cocoa behind. Cocoa as it is today will probably linger for a long time, like Carbon did, but when it goes, Objective-C will surely go with it.

Who’s to say the new paradigm will be named, perhaps Cocoa 2? I think personally that the “Cocoa” name, which was picked for its affinity with “Java”, needs replacing and that what’s to come will probably be given a name that has affinity with “Swift” instead.

P.S. I’d like to see a band named “Target-Action & the Responder Chain”


Automator workflows for creating folders in Finder’s list view

Save these workflows as Services to allow a right-click within a Finder list view window/tab to create folder at any point in the hierarchy.

There are 2 workflows: New Folder Within is shown when the selection is a folder for creating a new folder within it, New Folder Here is shown for any kind of selection and creates a new folder as its peer.

Both are restricted to be shown when front-most Finder window/tab is in list view and when there’s only a single item is selected. The first of those restrictions is because the workflows aren’t terribly useful when in any other view, the normal New Folder is just as good. The second restriction is because if the selection include items at different levels of the visible hierarchy then it’s not clear where to create the folder; its easier just to avoid this possibility and only show the option when its a single selection.

I hope this is useful for someone. If anyone makes any improvements, please write about them in the comments below and share with the rest of the class.

To install, either open them in Automator and save as Services, or manually copy them into ~/Library/Services.

Download from here.


Throwback Xcode Theme

Having a need for an Xcode theme using a narrow font, I made this one. It’s gotten admiration and funny looks by friends & colleagues, so thought I’d make it public.

xcode throwback theme

I had used the 80-column Apple 2 font as a lark every now and again, and always found it to be pretty much the narrowest font on my system. Soon after using a MacBook Air as my main development Mac, I started using it sometime as a text editor font. That turned into using it Xcode, but never found it to fit well with the color schemes, as whenever I saw that font back in the day it was on my Apple //e with one of those green-screen monitors. So eventually I took an existing green-on-black scheme (converted from some TextMate theme I think, I haven’t been able to find the actual source yet) and further customized its colours to get this theme. It largely the same shade of green with a few subtle variations, largely for comments and string literals.

It uses the PR Number 3 font by Kreative Korporation hosted at  www.kreativekorp.com/software/fonts/apple2.shtml. (Kreative Korporation is an outlet of Rebecca G. Bettencourt, kudos to her for producing and freely distributing those fonts).

Being a pixel-font, its noticeably not as crisp on retina screens as other fonts, and I’ve chosen a font size that’s quite small for maximum code density, so this theme is definitely an acquired taste. I hope you like it, or at least get a kick out of it. If anyone has any improvements, please add a comment below.

Download the dvtcolortheme file from here, and the font from here.


More On Software Patents (pun intended)

I originally wrote this as a response to this macrumors article where I say Apple’s 2 software patents, for which the judge ruled in their favour against HTC, are lame.

It’s because all software patents are lame [or.. moronic]. The decision on these 2 patents doesn’t cover any part of the core of what makes the iPhone what it is, and like most similar patents, there’s surely prior art in the past decades of the patent-less software industry but nothing that can be proven.

It used to be that a patent was on a physical invention and you submitted its technical design (or even a working unit, was it?) and the mechanics of how it worked was what you had protection for. Also the design was put into the public record so that the invention didn’t die with the inventor, which was apparently common beforehand when everything was trade secrets. This was the problem that the patent system was meant to solve.

A patent on, say, an automatic car window, applied to the design of the mechanism inside the door that makes it work. Some competitor could invent a different mechanism that worked the same way to the user. If patents on physical invention worked like a software patents then they wouldn’t need to submit the mechanism, only the idea and vague outline of its workings (with the lifter unit represented by a square in a diagram, connected to crude drawings of the door, switch and window) such that anyone inventing a new mechanism would be in violation of the patent.

The mechanics and technical design of software, what mirrors the patentable design of physical inventions, is by definition the source code. But because the patent office employs lawyers and not coders, all they have the expertise to analyse are high-level requirements specifications and behavior (diagrams with boxes and lines described by paragraphs of useless legalese).

Software patented should follow the intent of the patent system. It should be a kind of open source process, the code is submitted and visible to competitors, but they can’t use in the marketplace until after however-many years. To be in violation the patent you’d have to had copied that source code, reimplementing it would almost invariably be a new invention. (Don’t believe that? Look at a coding competitions and see how different people’s solutions are.)

A software patent should assist competitors in copying the software exact behaviour! And with source code made open, they can ensure they’re using different algorithms. (Most commenters on that macrumors forum talk about algorithms where they don’t even know what the word means, like that of Apple’s multitouch. Under their concept, all similarly-performing sorting algorithms would be the same because the produced the exact same behaviour to the user)

[I may be totally wrong, IANAL and all I know about patents are vague recollections from a long time ago, probably from a schoolhouse rock PSA]


Cocoa terse backtrace using NSRegularExpression

I recently wanted to improve some logging code to print out the callers to some methods (I’m tracking down errant retains / releases). [NSThread callStackSymbols] is excellent and easy, but I found that simply logging a chunk of the call stack was too verbose. I wanted to include callers from just my app and also parse it to include just the method names, ie. to turn this output from callStackSymbols:

0   MyApp                               0x0005da3a -[UnsavedPhoto retain] + 136,
1   CoreFoundation                      0x02b75fac CFRetain + 92,
2   CoreFoundation                      0x02b7ea52 __CFBasicHashAddValue + 98,
3   CoreFoundation                      0x02b86219 CFDictionarySetValue + 105,
4   CoreFoundation                      0x02c620d5 -[__NSCFDictionary setObject:forKey:] + 117,
5   MyApp                               0x000d631e -[OrderedDictionary setObject:forKey:] + 165,
6   MyApp                               0x0005c668 -[PhotoSaver addPhoto:] + 224,
...

into just this: "-[OrderedDictionary removeObjectForKey:] < -[PhotoSaver discardPhoto:]".

I made a method in NSString category (um, because it generates a string), which I call like this:

logthis = [NSString appBacktraceOfDepth:2 fromStackSymbols:[NSThread callStackSymbols]];

Here it is, fairly concise. Note that it does something reasonable if pre-iOS4 and NSRegularExpression is not present (namely just returns a chunk of the line from the top stack frame), fires an assertion if the regular expression fails (because it shouldn’t), and restarts without the restriction of matching only app calls if there are none in the stack before main.

I mostly decided to blog this because I didn’t initially spot any good examples of using NSRegularExpression to extract capture groups. The answer was to use firstMatchInString:options:range: to get a NSTextCheckingResult and then replacementStringForResult:inString:offset:template:.

@interface NSString (backtraceOfDepth_fromStackSymbols)
+ (NSString *)appBacktraceOfDepth:(int)depth fromStackSymbols:(NSArray *)frames;
+ (NSString *)backtraceOfDepth:(int)depth fromStackSymbols:(NSArray *)frames;
+ (NSString *)backtraceOfDepth:(int)depth fromStackSymbols:(NSArray *)frames matching:(NSString *)from;
@end
@implementation NSString (backtraceOfDepth_fromStackSymbols)
+ (NSString *)appBacktraceOfDepth:(int)depth fromStackSymbols:(NSArray *)frames { return [self backtraceOfDepth:depth fromStackSymbols:frames matching:[[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleNameKey]]; }
+ (NSString *)backtraceOfDepth:(int)depth fromStackSymbols:(NSArray *)frames { return [self backtraceOfDepth:depth fromStackSymbols:frames matching:nil]; }
+ (NSString *)backtraceOfDepth:(int)depth fromStackSymbols:(NSArray *)frames matching:(NSString *)from {
  NSRegularExpression *regex = nil;
  if (!NSClassFromString(@"NSRegularExpression") || !(regex = [NSRegularExpression regularExpressionWithPattern:@"[0-9]+ +(.+[^ ]) +0x[0-9a-f]+ (.+) \\+ [0-9a-f]+" options:0 error:nil]))
    return [[frames objectAtIndex:1] substringFromIndex:51]; // no regex, be lame and rely on column counts
  for (int goodframes=0, framenum=1; goodframes < depth && framenum < [frames count]; ++framenum) {
    NSString *frame = [frames objectAtIndex:framenum];
    NSTextCheckingResult *match = [regex firstMatchInString:frame options:0 range:NSMakeRange(0, [frame length])];
    if (!match)
      NSAssert1(NO, @"unparsed stack frame: %@", frame);
    if (from && ![from isEqualToString:[regex replacementStringForResult:match inString:frame offset:0 template:@"$1"]])
      continue;
    ++goodframes;
    NSString *caller = [regex replacementStringForResult:match inString:frame offset:0 template:@"$2"];
    if (from && goodframes == 1 && [caller isEqualToString:@"main"])
      return [self backtraceOfDepth:depth fromStackSymbols:frames matching:nil]; // no useful calls from us, take ones from anyone instead
    result = !result ? caller : [result stringByAppendingFormat:@" < %@", caller];
  }
  return result ? result : @"?";
}
@end

My thoughts about the GPL

A thought on GPL that didn’t fit in a tweet. GPL developers are idealists and have noble intent and I’m saddened to see people I respect tarnish their efforts when they bad-mouth the GPL.

For commercial software developers, code that people want to contribute to the GPL is unusable to them, but then again so is the source code to MS Word and Photoshop, where’s the vitriol against that set of source code. To use one set of source you sign your over to the FSF’s concept to community, to use the other you accept a job at MS or Adobe and sign your work over to them.

From the outside of both groups, their an unusable set of source I don’t see a big difference between the two. Oh, except that I can inspect and study GPL code and, use the resulting products freely, contribute missing functionality if I so desire, all benefits. To complain that you can look but not touch seems petty to me. Maybe I’m missing the point.


Found my TTPhotoView bug

TTPhotoView bug ExampleThis is a tip for anyone hacking TTPhotoViewController, and specifically TTPhotoView. If you’re finding swiping only rotating between three photos, and if there’s a mix of landscape and portrait then it gets a redraw bug that looks like this:

then you’ve probably disabled updateLayer (perhaps because it wasn’t working for photos with orientations other than Up) but didn’t replace it with [self setNeedsDisplay]. You’re welcome.
Also, for anyone else trying to untie TTPhotoView from TTURLCache and instead work with images you can’t load asynchronously: don’t. Instead make it work with fake URLs, force-feeding the cache as you go. Hey ALAssetLibrary, thanks for being async in all the wrong places.