07 May 14
16:33

Here’s my .emacs file in all its unedited glory. May it be a light in your time of google searching or a darkness in your time of trying to understand how to configure emacs.

It’s also in a gist.

It’s a franken.emacs from lots of sources on the net. I’ve forgot them all, but almost none of this functionality originated with me and thus you should give your thanks to the anonymous internet. I wanted to document it for a while because it’s helpful when I switch to a new computer. It’s so messy that I put off documenting it. I’ve decided to share it anyways.
Features are

  • ctrl-x ctrl-o to switch between a .m, .mm, .c, .cpp file to corresponding .h file if it is nearby
  • ctrl-arrow to switch between multiple buffers/windows that you split horizontally or vertically (e.g. with ‘ctrl-x ctrl-3’
  • auto reverts when file changes on disk (e.g. when you git checkout) – note this can be a little dangerous, but I believe it doesn’t do this if you have local modifications
  • copy and paste works with os-x clipboard and vice-versa with your yank/copy/kill ring
  • other stuff

27 Apr 14
14:21

pop quiz: why are my parameters zero when I pass them in with non-zero values

This one had me stuck for a number of minutes. It’s not hard, but it got me. See if you can spot it: say you create a new class that is inited like so: @interface YoDogWhatsWrong @property (nonatomic) float aValue; @end @implementation YoDogWhatsWrong – (id)initWithAValue:(float)aFloat anotherValue:(float)someOtherValue { if ((self = [super init])) { self.aValue = […]

Debug the rest of this issue »

28 Dec 13
08:45

Android Dev Console Wallet Registration: Error 400

If you’re setting up IAP for the first time on your google dev console, you will probably need to setup google wallet for merchants. I ran into a silly bug where I fill out the form and always got a message that read: An error occurred {“type”:”PLATFORM_ERROR”, “payload”:”400″, “request_id”:”4EDF17245AA00.A803E4F.6DB2″} Emailed support a couple times, turns […]

Debug the rest of this issue »

25 Dec 13
21:27

Namespacing a framework in objective-c, @compatibility_alias, and #defines

Shakespeare said something about roses and names smelling nice, but if you’re Outkast you know that sometimes, roses really smell like poo. Additionally, if you’re a programmer, you sometimes need to get another set of better spelling roses to set the world right. Far-fetched metaphors aside, namespacing issues come up less than I would expect. For one, most people know better than to call their classes ‘Object’, and everyone has their own novel solutions to the problem – be it prefixing every class with their initials or a swear word. This week I came across a project that required two implementations of the same framework to be present in the same iOS app. The frameworks had the same, or very similar headers, but the implementations were quite different. The use case in question was for migrating data from one implementation of the framework to another. Objective-C doesn’t have the namespace keyword magic that would make this problem a little faster.

My thought process evolved like this:

  1. My first thought was to rename everything in the old framework by adding a new ‘OLD’ prefix. However, this is quite a lot of work, depending on the size of the framework, and it can be tricky to come up with the right sed command that does everything you wanted.
  2. My next thought was to use #defines for everything I wanted to namespace in the headers only. However, this poses some serious problems for class naming conventions, even if you only conditionally define it within the framework compilation unit. Consider a class called ‘MyClass’. You might have MyClassDelegate, eTargetTypeMyClass, and even other classes with the same prefix or suffix, like MyClassManager or ComplicatedMyClass. #defines might or might not expand in the way you want here – but you can see the risk: it’s easy to end up with half of the file containing ComplicatedOLDMyClass in one compilation unit and OLDComplicatedMyClass in the other.
  3. 3. I found out about @compatibility_alias, which solves the problems with #2 for classes (and nothing else). However, this actually solved most of my problems and was fairly compatible with doing non-class namespacing as mentioned in 2.
  4. @interface OLDMyClass
    ...
    @end
    
    @protocol OLDMyProtocol
    @end
    
    #ifdef COMPILING_MYCLASS
    @compatibility_alias MyClass OLDMyClass; // this tricks the MyClass.m file to use the OLDMyClass interface
    #define MyProtocol OLDMyProtocol
    #endif
    

Limitations of @compatibility_alias:

  1. You can only use it with a real class to an aliased class. You can use it before the real class is declared (but the compiler will emit a warning). If the alias class is already declared, it will cause an error.
  2. You can only use it once per compilation unit for a given alias (you can’t use it liberally like you can with forward declares).
  3. You cannot use it with protocols, typdefs, enums, or anything besides an objective-c class.
  4. All @class MyClass forward decl’s will need to either be swapped out for an #import “MyClass.h” or changing the forward decl to @class OLDMyClass and all occurrances in the header to OLDMyClass.

So how do you namespace the protocols, typedefs, and enums? You could rename everything in the .h and .m files, but it is a lot less work to just ‘#define originalprotocol OLDoriginalprotocol’ and declare OLDProtocol in the header.

You can then #ifdef the #defines and @compatibility_alias’s on the condition that you are compiling the framework itself. This trick is similar to exporting only certain symbols when building a library, and allows for the framework’s implementation (.m files) to be remain almost entirely unchanged (using the ‘originalclass’ form), and when compiling the app, the app only sees the OLD_originalclass form, and also the #defines won’t be able to accidentally expand strings that it happens to match.

I ended up using a sed command only to change the #import to #import.

I did the above for the older version of the framework, and left the newer one unchanged. This allows them to both be used simultaneously. There are other tricks you might be able to do like dynamic loading, but if you need classes from both at the same time, this is probably the way to go.

For reference, here’s a file that I used to test the edge cases. You can compile with ‘clang -framework Foundation compatibility_alias_test.m’, or see the errors caused by wrong usage with ‘clang -DWONT_COMPILE -framework Foundation compatibility_alias_test.m’ :

#include <Foundation/Foundation.h>
#include <stdio.h>

// 1.Only classes work with @compatibility_alias:
// 2. Protocols, typedef, enums and other things are out.
// 3. You might be able to use a #define with #undef for those
// 3.1. If that would interfere with the original namespace you are colliding with,
//      you might try conditionally defining it where it is needed, probably similar
//      to exporting only some symbols when building a lib (if just including headers it would be hidden)

#ifdef WONT_COMPILE
// forward declare of aliased name conflicts with alias
@class SpecificClass; // error: conflicting types for alias 'SpecificClass'
#endif

@protocol NonColiding_BeerHolder
@property (nonatomic, assign) int beers;
@end
#ifdef WONT_COMPILE
@compatibility_alias BeerHolder NonColiding_BeerHolder; // warning: cannot find interface declaration for 'NonColiding_BeerHolder'
// also, later: error: cannot find protocol declaration for 'BeerHolder'
#else
#define BeerHolder NonColiding_BeerHolder
#endif

@interface NonColiding_SpecificClass : NSObject <BeerHolder>
@property (nonatomic, assign) int beers;
@end

@implementation NonColiding_SpecificClass
- (id)initWithBeers:(int)beers
{
    if ((self = [super init])) {
        self.beers = beers;
    }
    return self;
}
@end

@compatibility_alias SpecificClass NonColiding_SpecificClass;

#ifdef WONT_COMPILE
// you also can't double up on compatibility_alias like you can with forward decls.
@compatibility_alias SpecificClass NonColiding_SpecificClass;
#endif

int main(int argc, const char* argv[])
{
    SpecificClass* bob = [[SpecificClass alloc] initWithBeers:5];
    NSObject<BeerHolder>* bh = bob;

    // sanity
    printf("yo dog i'm bob and i have %d beers.\n", bob.beers);
    printf("yo dog i'm a beer holder and i have %d beers.\n", bh.beers);
    [bob release];
}

25 Aug 13
00:11

Mac Dictionary Services API Tease

Basic lookup working

I am a big fan of Dictionary.app. It’s pretty handy for English, but what makes it really shine is that it has a zomg-amazing Japanese dict called Daijisen. What’s more, with 10.8 Apple threw in German, French, Spanish, and Chinese dictionaries as well. However, after getting used to the app, while still using it, I have decided that it sucks. I should clarify. The dictionary content that it has is great. But the app itself is lacking some features that would make it so much more useful. I want search history that goes beyond a single app launch, and an interface for seeing what words I looked up when. I want to be able to export this list so I can make flash cards. I also want to be able to search by words other than by a ‘starts-with’ scheme, such as ‘contains’ or ‘ends with’, like many online dictionaries have.

For a while I just assumed there was no easy way of using the content the mac dictionary app uses. Then I found out about the mac dictionary services API, which looks promising at a glance.

I created the basic lookup pretty quickly while on the BART commute to work and back. But it became apparent after some tinkering that the existing API (which has only two functions for word lookup) is entirely incomplete. You can look up a string, and get a definition back from the same dictionaries that Dictionary.app uses. However, you can’t specify which dictionary, or which entry within a dictionary (e.g. for a word that has multiple definitions). This means you only will the first entry of the first dictionary that gets hit. So I decided to spend a good part of today trying to see what could be done about this.

I came across one or two or three interesting posts that showed some private API off. Most of these were for simple CLI programs, or for building their own dictionary. And used private calls such as DCSRecordCopyData() and DCSCopyAvailableDictionaries(). DCSCopyAvailableDictionaries allowed me to access specific dictionaries, and used in conjunction with DCSGetTermRangeInString and DCSCopyRecordsForSearchString, I was able to generate a reasonable list of candidate DCSRecordRefs entries from a single input word. The only thing missing was the definitions for each DCSRecordRef.

I wanted to make this dictionary for my Japanese studies. In Japanese, there are tons of homonym and homophones depending on if you use write the word with kanji or not. I didn’t see a function from my googles that would show the word listing, but doing an NSLog(@”%@”, record) on an example search for ‘いる’ showed some info about the DCSRecord structure:

lldb output:
{key = いる, headword = いる【射る】, bodyID = 111081}
{key = いる, headword = いる【要る】, bodyID = 104584}
{key = いる, headword = いる【居る】, bodyID = 163639}

It looked like the ‘bodyID’ or ‘headword’ field of DCSRecordRef had the most specific information about the result. So I went into the framework and searched for symbols of functions that might do the trick:

cd /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/DictionaryServices.framework
nm -gU DictionaryServices|grep DCS
0000000000007b06 T _DCSActivateDictionaryPanel
000000000000914d T _DCSCopyActiveDictionaries
000000000000916f T _DCSCopyAvailableDictionaries
[...]
0000000000007e07 T _DCSRecordCopyData
0000000000007e1e T _DCSRecordCopyDataURL
0000000000007e63 T _DCSRecordGetAnchor
00000000000076ef T _DCSRecordGetAssociatedObj
0000000000007e4c T _DCSRecordGetDictionary
0000000000007ebd T _DCSRecordGetHeadword
0000000000007e91 T _DCSRecordGetRawHeadword
0000000000007f04 T _DCSRecordGetString
0000000000007e35 T _DCSRecordGetSubDictionary
0000000000007e7a T _DCSRecordGetTitle
0000000000009181 T _DCSRecordGetTypeID
00000000000076d9 T _DCSRecordSetAssociatedObj
0000000000007ea8 T _DCSRecordSetHeadword
000000000000878a T _DCSSearchSessionCreate
[...]

The second entry for 棺 should be ひつぎ

There were about a 100 or so symbols or so that Apple didn’t feel like sharing via docs. I tried a few combinations, but it looks like DCSRecordGetTitle or DCSRecordGetRawHeadword produced the best strings for use with DCSCopyTextDefinition. This solves the homonym problem for the most part. However, this did not work at all with heteronyms (words that are spelled the same, but pronounced differently), since the headword/display title would be the same. For example, for the input 棺 I need the definitions for both 棺 read as ‘kan’ and 棺 read as ‘hitsugi’, but this method would give me two definitions for ‘kan’ instead. Eventually I gave up. I hope someone else figures this out. I put the intermediate result up on github. Let me know if you make any progress.

On iOS it goes without saying that you should probably avoid using private APIs, since the main means of distribution is through apple. On the mac distributing an app yourself is still viable, and thus you can use private APIs to your heart’s content. However, because the non-documented but exported symbols do not provide function signatures, it’s pretty much just a tease unless you want to spend a lot of time to figure out what each method takes. After googling symbol names, it seems dictionary services are relatively unexplored. But I’m mostly interested in this for making my hobby dictionary that I can nerd out on and add lots of obscure features to while using the apple-provided dictionaries.