Snippet: code to convert RGB to HSV and back again

I sketched this code together needing a quick way to convert from RGB to HSV and back again, then realized I didn’t need it. So I’m putting it here in the theory that this may be useful someday…

/*	RGBToHSV
 *
 *		Conver to HSV
 */

static void RGBToHSV(float r, float g, float b, float *h, float *s, float *v)
{
	float max = r;
	if (max < g) max = g;
	if (max < b) max = b;
	float min = r;
	if (min > g) min = g;
	if (min > b) min = b;
	
	/*
	 *	Calculate h
	 */
	
	*h = 0;
	if (max == min) h = 0;
	else if (max == r) {
		*h = 60 * (g - b)/(max - min);
		if (*h < 0) *h += 360;
		if (*h >= 360) *h -= 360;
	} else if (max == g) {
		*h = 60 * (b - r) / (max - min) + 120;
	} else if (max == b) {
		*h = 60 * (r - g) / (max - min) + 240;
	}

	if (max == 0) *s = 0;
	else *s = 1 - (min / max);

	*v = max;
}

/*	HSVToRGB
 *
 *		Convert to RGB
 */

static void HSVToRGB(float h, float s, float v, float *r, float *g, float *b)
{
	if (h < 0) h = 0;
	if (h > 359) h = 359;
	if (s < 0) s = 0;
	if (s > 1) s = 100;
	if (v < 0) v = 0;
	if (v > 1) v = 100;

	float tmp = h/60.0;
	int hi = floor(tmp);
	float f = tmp - hi;
	float p = v * (1 - s);
	float q = v * (1 - f * s);
	float t = v * (1 - (1 - f) * s);
	
	switch (hi) {
		case 0:
			*r = v;
			*g = t;
			*b = p;
			break;
		case 1:
			*r = q;
			*g = v;
			*b = p;
			break;
		case 2:
			*r = p;
			*g = v;
			*b = t;
			break;
		case 3:
			*r = p;
			*g = q;
			*b = v;
			break;
		case 4:
			*r = t;
			*g = p;
			*b = v;
			break;
		case 5:
			*r = v;
			*g = p;
			*b = q;
			break;
	}
}

Basic Lessons: Object Oriented Programming with Objects

The really stupid thing, by the way, about most code that I review is how few people know about object oriented development. Yes, yes, yes; they say they know all about object oriented development–but when you then review their code (say, in an iOS application with a table) do they practice proper encapsulation? Nooooooooooo…

All too often I see something like this:

MyTableViewCell.h

@interface MyTableViewCell: UITableViewCell
@property (strong) IBOutlet UILabel *leftLabel;
@property (strong) IBOutlet UILabel *rightLabel;
@end

MyTableViewController.m

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyTableViewCell *c = (MyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"MyTableViewCell" forIndexPath:indexPath];

    c.leftLabel.text = [NSString stringWithFormat:@"Left %d",indexPath.row];
    c.rightLabel.text = @"Right Label";

    return c;
}

The text in red above: no, no, no, no, no.

Haven’t you even heard of encapsulation? No? Well, that’s probably because (a) most developers have no idea what they’re doing beyond copying someone else’s models, and (b) they’ve been taught some bad habits by other developers who also have no idea what they’re doing.

Of course this isn’t helped by Apple, whose own UITableViewCell by default exposes the fields contained within.


What is object encapsulation?

The idea of object encapsulation is central to the idea of object oriented programming. Essentially it refers to the idea of creating “objects”–chunks of data associated with functions designed to work on that data.

To understand how useful this is we need to dive into a pre-OOP language, such as C.

Back in the “bad old days” of C, you had functions, and you had structures. And that was it:

struct MyRecord
{
    int a;
    int b;
};

int AddFields(struct MyRecord x)
{
    return x.a + x.b;
}

While this sort of procedural programming has it’s place–and languages such as C are extremely good at embedded development or in Kernel programming (where execution efficiency is important), it falls short with developing user interfaces, simply because with user interfaces we manipulate things like buttons and text fields and table view cells.

In fact, it turns out that object-oriented programming is tied to user interface development, by abstracting the idea of user interface elements into a new concept of an “object” as a self-contained unit that combines the idea of a structure or record with the idea of functions or procedures that operate on that record.

In C++, we can express this idea as a class:

class MyRecord
{
	int a;
	int b;

	int AddFields();
};


int MyRecord::AddFields()
{
	return a + b;
}

Notice that this expresses the same idea as our C snippet above, which adds the contents of the two fields in MyRecord. Except now, AddFields is associated with a record. This means if we have a record and we want the sum of the fields, instead of writing

MyRecord a;
int sum = AddFields(a);

we write

MyRecord a;
int sum = a.AddFields();

That is, we apply the message against the object.

Now we haven’t really done anything new yet. In fact, if you were to write in C++ the method ‘AddFields()’ from our C example, it would still work with our C++ declaration of MyRecord.

But C++ gives us a new tool: a way of marking fields “private”–that is, only accessible from the methods that are associated with the class.

Thus:

class MyRecord
{
	private:
		int a;
		int b;

	public:
		int AddFields();
};

We’ve hidden a and b from view. Now the only way you can change a and b or get their values is through methods which are then made public with MyRecord.

Encapsulation is the process of creating self-contained objects: objects which provide a clear interface for manipulating the object, but which hide the details as to how the object does it’s work.

Now there was no need to actually use the new features of C++ to provide this sort of data hiding. In C, we can take advantage of the fact that things declared within a single C file stay within that file: we could declare a pointer to a structure in our header file, but hide the details by declaring them in the C file that contains the implementation. C++ makes this easier for us by giving us better tools to manipulate access to the contents of the object.


Why is encapsulation important?

Simply put, encapsulation allows us to separate the “what” from the “how”; separate what we want an object to do from how the object actually does the work.

This becomes important for two reasons.

First, it means that we have an object which has a clearly defined “purpose.” For example we can define an object which represents a button on the screen: a rectangular region the user can tap on or click with their mouse, which then responds to that tap by visually changing appearance and by firing an event which represents the response to that tap or button press.

And second, tied to the first, we can isolate all of the code which handles the button’s behavior within the button itself. A user of the button doesn’t need to know the details of how a button works to put one on the screen, nor does the user need to know how a button receives click or tap events, or how it processes those events. A user doesn’t even need to know the details of how a button draws itself: they don’t need to know how the button handles details such as switching text alignment for languages which read right to left instead of left to right.

And because the details are isolated away, it means those details can change: instead of firing an event on the down click of the mouse the event can be fired when the mouse click is released. The button’s appearance can change–or even be changeable depending on the skin the user selects. The button can even be handled as a spectrum of button-like objects. None of this matter to the user of that button: drop one on the screen, set the text, and wire up the event for the response, and you’re done.


How we can change our object above to respect proper encapsulation

This idea of encapsulation is one that we can–and should follow in our own code. That way if we later have to change the details of how we implement a thing, it doesn’t require us to hunt through all of our code and change the details everywhere else. Change the object, not all the callers manipulating the object.

So, for our UITableViewCell example above, the change is simple. First, hide the details how our table view cell is implemented:

MyTableViewCell.h

@interface MyTableViewCell: UITableViewCell
- (void)setLeftText:(NSString *)left rightText:(NSString *)right;
@end

MyTableViewCell.m

@implementation MyTableViewCell
@property (strong) IBOutlet UILabel *leftLabel;
@property (strong) IBOutlet UILabel *rightLabel;

- (void)setLeftText:(NSString *)left rightText:(NSString *)right
{
    self.leftLabel.text = left;
    self.rightLabel.text = right;
}
@end

And in our caller code:

MyTableViewController.m

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyTableViewCell *c = (MyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"MyTableViewCell" forIndexPath:indexPath];

    c.leftLabel.text = [NSString stringWithFormat:@"Left %d",indexPath.row];
    c.rightLabel.text = @"Right Label";
    [c setLeftText:[NSString stringWithFormat:@"Left %d",indexPath.row]
         rightText:@"Right Label"];
 

    return c;
}

The original offending code was wrong because it confused the “how” to do something (setting the internal structure of the table cell) with the “what”: set the left and right text.

And notice that now we’ve hidden the details inside the table view. So later, if for some reason we change our implementation of the UITableViewCell:

MyTableViewCell.m

@implementation MyTableViewCell
@property (copy) NSString *leftLabel;
@property (copy) NSString UILabel *rightLabel;

- (void)setLeftText:(NSString *)left rightText:(NSString *)right
{
    self.leftLabel = left;
    self.rightLabel = right;
	[self setNeedsDisplay];
}

- (void)drawRect:(CGRect)r
{
    CGRect textRect = CGRectMake(10, 0, 146, 44);
    {
        NSString* textContent = self.leftLabel;
        UIFont* textFont = [UIFont fontWithName: @"HelveticaNeue-Light" size: UIFont.labelFontSize];
        [UIColor.blackColor setFill];
        [textContent drawInRect: CGRectOffset(textRect, 0, (CGRectGetHeight(textRect) - [textContent sizeWithFont: textFont constrainedToSize: textRect.size lineBreakMode: UILineBreakModeWordWrap].height) / 2) withFont: textFont lineBreakMode: UILineBreakModeWordWrap alignment: UITextAlignmentLeft];
    }

    CGRect text2Rect = CGRectMake(164, 0, 146, 44);
    {
        NSString* textContent = self.rightLabel;
        UIFont* text2Font = [UIFont fontWithName: @"HelveticaNeue-Light" size: UIFont.labelFontSize];
        [UIColor.blueColor setFill];
        [textContent drawInRect: CGRectOffset(text2Rect, 0, (CGRectGetHeight(text2Rect) - [textContent sizeWithFont: text2Font constrainedToSize: text2Rect.size lineBreakMode: UILineBreakModeWordWrap].height) / 2) withFont: text2Font lineBreakMode: UILineBreakModeWordWrap alignment: UITextAlignmentRight];
    }
}
@end

Notice that we don’t have to change a single thing in MyTableViewController.m, simply because it never knew how the table view drew itself; it only knew how to ask.

Objective C declaration shortcuts

With a recent update (okay, not quite so recent update) to Objective C, the following lexical shortcuts appear to have been added:

Create a dictionary using @{…}

The @{ … } shortcut has been added to create a new NSDictionary with a list of keys and values. The format appears to be:

@{ key : value , ... }

So, to create a new dictionary with three keys:

NSDictionary *d = @{ @"a": @"First",
                     @"b": @"Second",
                     @"c": @"Third" };

This creates a dictionary with three keys: @”a”, @”b” and @”c”, with the values @”First”, @”Second” and @”Third”, respectively.

Create an array using @[ … ]

The @[ … ] shortcut creates a new NSArray with a list of values. The format appears to be:

@[ value, value, ... }

So, to create a new array with three items:

NSArray *a = @[ @"a", @"b", @"c" ];

This creates an array with three items, @”a”, @”b” and @”c”.

Create an NSNumber wrapper around a numeric constant using @(…)

The @(…) appears to take a scalar and wrap it in an NSNumber object. Thus:

NSNumber *n = @( 5 );

creates a new NSNumber with the value 5.


You can combine each of these together in any way you wish. For example:

NSDictionary *d = @{ @(1): @[ @"A" ],
                     @(2): @[ @"Another", @"Thing" ],
                     @(3): @[ @"Tom", @"Dick", @"Harry" ] };

Far more convenient than the old way.


I’ve seen the first two documented elsewhere, but I don’t think I’ve seen the third one (boxing an NSNumber) mentioned anywhere, and I don’t quite remember where I saw it. Probably in the compiler release notes.

Also note that these can be used in-line with code and not just with constant objects. So, for example, you can use the NSNumber boxing mechanism to box an integer return value from a function:

NSNumber *count = @( [array count] );

This has been a public service announcement.

Dear WordPress

Thanks (NOT!!!) for letting me know of all the messages in the queue waiting for approval–including comments that I made months ago.

(Shakes head)

There are days when I want to build my own blogging system, just so I can bypass all this weirdness.

My love/hate relationship with Design Patterns.

I have a love/hate relationship with Design Patterns, which is actually captured in the first two sentences of the Wikipedia article I just linked to.

I love them because they provide a general reusable solution–a rule of thumb, so to speak–on how to solve some fairly common problems.

For example, if you are developing a user interface application, then the Model-View-Controller pattern or the Model-View-Presenter pattern is definitely a lifesaver in helping you design a well-organized application.

(The difference between the two have to do with the ability of view components having direct access to the model data: MVC allows the connection as a rule of thumb, while MVP denies it. For most applications–such as simple iOS applications which access remote data from a database and present the results on a screen–strictly separating views from the model object makes a tremendous amount of sense. However, there are certain types of applications where the user interaction of the view with the data is so involved, you need to allow the view insight into the model data directly. Usually this is reserved for complex editing applications, like a text editor or a CAD system, where the logic for handling key or mouse events makes more sense to contain in a text editor view or a CAD drawing view than allow the raw events to percolate to an already over-loaded controller module.)

And having a good working knowledge of various design patterns helps you have a standard bag of tricks to apply to problems you may see in the field: singletons, proxies and modules are excellent ways to handle organization of conceptual functions. Flyweights are helpful when creating a complex page of preferences in a dialog. Object pools help with reducing the overhead of allocation. And so forth.


I hate them, though.

And I hate them for the very simple reason that to an inexperienced developer equipped with a hammer, the entire world becomes full of nails.

Design patterns are, as defined in Wikipedia, “general reusable solutions to commonly occurring problems.”

And there are three problems with that.

First, it requires some degree of understanding of the solution and how to apply it. If you don’t understand the ‘chain of responsibility’ pattern, for example, then you can really shoot yourself in the foot if you implement it poorly–as I’ve seen done on a number of occasions, with events in a custom event chain that just “disappeared”.

Second, it requires some degree of understanding what the problem was the solution is attempting to solve. One developer I had a conversation with a long time ago insisted on using a decorator pattern to allow a view to both have presentation and editing functionality, when either a flyweight or simple inheritance could have solved the problem far more gracefully.

And third, many developers labor under the presumption that these are the only solutions–that there are no other solutions out there. The whole world becomes full of nothing but nails, and by God if my hammer doesn’t work the problem is not solvable by us “mere mortals.”


To me, design patterns are just solutions to common problems. There are other potential solutions to other problems not quite as common: for example, I once wrote a networking stack for a small microprocessor by creating a state machine: a large switch statement where each ‘case’ ended by changing the variable controlling the state machine to the next ‘case’ that was to be executed.

Emulating multi-threading was achieved by having each network connection hold its own state–and on exit of each case, a pointer pointed to the next active network object and picked up with whatever state that network object was in.

(I’ve successfully used state machines to solve a number of esoteric problems, including building my own LISP interpreter, and my own virtual machine interpreter. And state machines are built by YACC for building a parser; they’re far more flexible than recursive-descent parsers.)

And there are many solutions I’ve come across which solve common problems related to multi-threading that I’ve yet to see written down as an “approved” Design Pattern, such as the solution I provide here, to solve the problem of anonymous inner blocks which may be deallocated by a user action prior to the completion of an asynchronous task.


Principally I hate design patterns for the same reason I hate orthodoxy: it’s just an excuse to stop thinking now that all of the approved answers have been derived for us.

iOS Notifications

Working through iOS notifications, and found an excellent article here:

Apple Push Notification Services in iOS 6 Tutorial: Part 1/2

Apple Push Notification Services in iOS 6 Tutorial: Part 2/2

Note that the steps for setting up a certificate have not changed, and worked like a charm for me.


Followup: when attempting to load the certificates into Amazon’s SNS service through the console, I ran into the dreaded “There was a transient failure registering the app with Amazon SNS.”

*sigh*

The trick is hinted at here: Amazon SNS with Apple APN

The trick is that you load the aps_development.cer file (or the APN certificate for release; I haven’t done that so not clear what it’s called) into Keychain by double-clicking on the file.

Then you select both the private key that was used to generate the certificate, and the APN certificate you just added to Keychain, and export both as a .p12 file.

Convert into a .pem file via

openssl pkcs12 -in InCert.p12 -out OutCert.pem -nodes -clcerts

This OutCert.pem can then be used as the single .pem file that Amazon asks for in the SNS console.


I hate when I run into weirdness like this.

Things to remember: resize icon script for iOS

On iOS there seems to be about a billion different icon sizes, depending on if you’re on iOS 7 or iOS 6, on iPhone or iPad, or for search icons or whatever.

This is a script which I created to help automatically resize all the icons that are used.

if [ $# -gt 0 ]; then
    sips $1 -Z 29 --out icon-29.png
    sips $1 -Z 58 --out icon-29@2x.png
    sips $1 -Z 40 --out icon-40.png
    sips $1 -Z 80 --out icon-40@2x.png
    sips $1 -Z 50 --out icon-50.png
    sips $1 -Z 100 --out icon-50@2x.png
    sips $1 -Z 57 --out icon-57.png
    sips $1 -Z 114 --out icon-57@2x.png
    sips $1 -Z 60 --out icon-60.png
    sips $1 -Z 120 --out icon-60@2x.png
    sips $1 -Z 72 --out icon-72.png
    sips $1 -Z 144 --out icon-72@2x.png
    sips $1 -Z 76 --out icon-76.png
    sips $1 -Z 152 --out icon-76@2x.png
    echo "Done."
else
    echo "You must provide the name of an image file to process."
fi

To use, in the terminal execute this script with the name of the .png file to be resized, and this will generate all the different icon sizes used.

Where am I?

We’re moving across country, and my folks bought me a Spot satellite tracking device. (Actually it’s for flying–I’m a newly minted IFR-rated pilot–so this allows folks to know where I am in an emergency. But as we drive across country it serves the secondary purpose of checking in with our current location.)

So after January 14th check in here to find out where we are as we drive across the country.

1 2 3 4 35