Sunday, June 21, 2009
Reverse-engineering stringed instruments
I once made a stringed synthesiser, when I was at college. The basic principle is that of an electric guitar running in reverse. A metal string is stretched between two bridges, and sits inside a horseshoe magnet. Now rather than plucking the string and letting the magnetic pickup detect the vibrations, we pass an alternating current through the string and use the magnetic field to cause the string to vibrate. Mount the whole shooting match on a soundbox roughly the shape of an appalachian dulcimer, so it makes a decent amount of noise. And there you go!
Well, there bits of you go, anyway. While you can drive the string at any frequency you like, it'll be really quiet on any note which isn't a natural harmonic - it's being forced at one frequency, and trying to vibrate at a bunch of other frequencies, so can't really resonate. Assuming that the materials of the string aren't up for grabs, it's the length and tension which choose the fundamental frequency. What you currently have is capable of playing bugle tunes. Put a few different bugles together and you can play chromatic scales, so putting a few different strings together increases the likelihood that our synthesiser has the ability to play some notes in the tune we want.
In fact, it's still going to have a fairly nasty volume characteristic, because most of the noise doesn't come from the string, it comes from the soundbox. In that regard, violins and pipe organs have quite a lot in common. But they differ in that pipe organs have one soundbox per note - the pipe itself - and violins have a single box. So it'd better be possible to get it to resonate at a whole bunch of interesting frequencies, which is one of the reasons for making them (and acoustic guitars) the shapes that they are. Now what the real acoustic characteristics of a fiddle body are, I'm not entirely sure. But what I do know is that a violin is surprisingly small - the "concert pitch" A pipe in an organ is a little under 40cm and the lowest note a violin usually has (a ninth lower) will therefore be almost a metre long. Even though an enclosed box like a violin needs to be half the length of an organ pipe playing the same note, it will still naturally accentuate the higher frequencies that the strings have on offer because it isn't big enough to do much else. And it's that which gives the instruments their sound. My synth's soundbox was cuboid-ish, so had two characteristic "loud" notes and their harmonics. The z-axis wouldn't have resonated much as the box was on a table which absorbed the momentum.
The remaining interesting point is that the violin is forced to extract the sound from a rubbish part of the string. The bridge is both responsible for translating the motion of the string into the wood and for stopping the string from moving. The string moves most somewhere out toward the middle (it's mainly vibrating at its natural wavelength, which is twice the length of the string) and not at all near the ends. That's why pickups on electric guitars sound "warmer" further away form the bridge. There they pick up more of the lower harmonics, but the nearest pickup (and the bridge) get proportionally more of the higher harmonics.
Tuesday, June 16, 2009
Beer improves perception of security
So, the attendee beer bash at WWDC. There is beer. There is also the regulatory framework of the state of California, which mandates that minors under 21 years of age may not be supplied with beer. There are also student scholarship places to the WWDC, and no theoretical minimum attendee age. There are also loads of people in the vague area of Yerba Buena Gardens who are not attending the WWDC. But only attendees may visit the bash, and only attendees over 21 may drink beer.
I went to the registration desk at Moscone West on the day before Phil Schiller's keynote, and identified myself as Graham Lee. "Hi, my name's Graham Lee" I said to the lady behind the desk. It turns out that's not sufficient. While I did indeed give the name of someone who was indeed registered to attend the conference, there's no reason for the lady to believe the identification I gave her. She wants to be able to authenticate my claim, and chooses to rely on a trusted third party to do so. That third party is the British government (insert your own jokes here), and she is happy to accept my passport as confirmation of my identity.
Now I am given my attendee badge, a token which demonstrates that I have authenticated as Graham Lee, an attendee at WWDC. When I move around the conference centre to get to the sessions and the labs, the security staff merely need to look for the presence of this token. They don't need to go through the business of checking my passport again, because the fact that I have my token satisfies them that I have previously had my identity authenticated to the required level.
The access token would be sufficient to get me in to the attendee beer bash, as it proves that I have authenticated as an attendee. But it does not demonstrate that I am authorised to drink beer. So on the day of the bash I go back to the registration desk and show a different lady my passport again, which indicates that I am over 21 and can therefore be given the authority to drink beer at the bash. I am given the subtle green wristband pictures, which again acts as a token; this time not an identification token but an authorisation token. The bar staff do not care which of the 5200 attendees I am. In fact they do not care about my identity at all, because they know that the security staff have already verified my attendee status at the entrance to the event - therefore they don't need to see my attendee pass. They only care about whether I'm in the group of people permitted to drink beer, and the wristband shows that I am in that group. It shows that I have demonstrated the credentials needed to gain that particular authority.So, there we have it. A quick beer of an evening with a few thousand colleagues can indeed turn into a fun discussion of the distinction between authentication and authorisation, and how these two tasks can be carried out independently.
Saturday, June 13, 2009
WWDC wind-down
The event itself was great fun, as ever. Meeting loads of new people (a big thank-you to the #paddyinvasion for my dishonourary membership) as well as plenty of old friends is always enjoyable - especially when everyone's so excited about what they're working on, what they've discovered and what they're up to the next day. It's an infectious enthusiasm.
Interestingly the sessions and labs content has more of a dual impact. On the one hand it's great to see how new things work, how I could use them, and to realise that I get what they do. The best feeling is taking some new information and being able to make use of it or see how it can be used. That's another reason why talking to everyone else is great - they all have their own perspectives on what they've seen and we can share those views, learning things from each other that we didn't get from the sessions. If you were wondering what the animated discussions and gesticulations were in the 4th Street Starbucks at 7am every morning, now you know.
On the other hand, it makes me realise that OS X is such a huge platform that there are parts I understand very well, and parts that I don't really know at all. My own code spreads a wide path over a timeline between January 1, 1970 and September 2009 (not a typo). For instance, it wasn't until about 2003 that I knew enough NetInfo to be able to write a program to use it (you may wonder why I didn't just use DirectoryServices - well even in 2003 the program was for NeXTSTEP 3 which didn't supply that API). I still have a level of knowledge of Mach APIs far below "grok", and have never known even the smallest thing about HIToolbox.
There are various options for dealing with that. The most time-intensive is to take time to study - I've got a huge collection of papers on the Mach design and implementation, and occasionally find time to pop one off the stack. The least is to ignore the problem - as I have done with HIToolbox, because it offers nothing I can't do with Cocoa. In-between are other strategies such as vicariously channeling the knowledge of Amit Singh or Mark Dalrymple and Aaron Hillegass. I expect that fully understanding Mac OS X is beyond the mental scope of any individual - but it's certainly fun to try :-).
Wednesday, June 10, 2009
Unit testing Cocoa projects in Xcode
Unlike Bill, whose reference to unit testing in Xcode 3.0 is linked at the title, when I started writing unit tests for my Cocoa projects I had no experience of testing in any other environment (well, OK, I'd used OCUnit on GNUstep, but I decline to consider that as a separate environment). However, what I've seen of unit testing in Cocoa still makes me think I must be missing something.
The first thing is that when people such as Kent Beck talk about test-driven development, they mention "red-green-refactor". Well, where's my huge red bar? Actually, I sometimes write good code so I'd like to see my huge green bar too, but Xcode 3.1 doesn't have one of those either. You have to grub through the build results window to see what happened.Sometimes, a test is just so badly broken that rather than just failing, it crashes the test runner. This is a bit unfortunate, because it can be very hard to work out what test broke the harness. That's especially true if the issue is some surprising concurrency bug and one test breaks a different test, or if the test manages to destroy the assumptions made in -teardown and crashes the harness after it's run. Now Chris Hanson has posted a workaround to get the debugger working with a unit test bundle target, but wouldn't it be nice if that "just worked", in the same way that breaking into the debugger from Build and Run "just works" in an app target?
Wednesday, June 03, 2009
Follow-up-and-slightly-over on safety/security
So Dennis Fisher argues that "very few users will switch to a Mac or from a Mac because of security"…"But if Snow Leopard turns out to be a major security upgrade over the current versions, that's an important step for Apple and its customers." I'm not sure I agree there. As far as I can see, the fundamental place where Fisher and I start to disagree is on what value security marketing has.
I infer from the article that Fisher takes security marketing to be a zero-sum game between the competitors: every time Apple wins, Microsoft necessarily loses: Microsoft have "out-secured" Apple and it's up to Apple to "out-secure" them back. I believe that many consumers consider security as a "hygiene factor"; invisible most of the time, but unacceptable when it becomes an issue. That would make it hard to market a secure OS, but impossible to sell an insecure one. An important distinction, let me explain. People will not consider security as a factor in any product which seems secure enough, but will not touch any product which does not seem secure enough. Therefore a loss for any one company pulls its rep down with respect to the competitors, but there isn't really any such thing as a security marketing "win".
Where does that leave Apple? Well, a "major security upgrade" could go in one of two directions. Either it means moving from 0 concern over Mac security to a smaller value of 0 concern; or it could lead people to think that there were some security holes in Leopard that Apple decided not to tell us about and patched up in Snow Leopard. It seems to me that there is, at best, no value in marketing based on the security posture of the OS (though security features are, admittedly, different), however there certainly is value in improving the security posture to avoid the negative market perception of vulnerabilities. There is also value in responding openly and quickly to security issues to stem the rep bleeding any problem would cause.
Knowing Apple, though, they'll find the other way; the way of making security posture a winnable marketing game and winning that game.
Fisher's article states that the real question "is whether Snow Leopard will be more secure than the current version of OS X" - whereas for the moment the real question is whether Snow Leopard will continue to be secure enough.
Friday, May 29, 2009
chord graphics
When I'm trying to think of chords in music I always end up with a mental image of a piano keyboard, with the notes that make up the chord pressed. That's all well and good, but I don't have a piano! Apart from some set pieces like barre chords, I can't really think of note combinations in the same way on a guitar, and certainly get flustered trying to harmonise on a violin. What I really need is a piano to sit down and work out harmonies at, which I could then play on the instrument of my choosing (playing a string of notes on any of those instruments isn't so much of a problem).
Unfortunately the biggest piece of floor space I currently have access to is about 1.3m x 0.4m. Maybe some cheap Bontempi would fit there, but not an 88-key upright. If there were a real-space version of the GarageBand digital keyboard, that would certainly fit...in fact it would probably fit in one of my nostrils. One octave doth not a piano make. Some people have suggested Clavinova, MODUS or similar electric pianos before. The thing is, they cost around £2k, whereas an upright is <£500.
Thursday, May 28, 2009
Wednesday, May 20, 2009
The rokeg blood pie^W^W^Wplot thickens
This seems to confirm the impression that the tool has been developed for some special internal use and might not be downloadable much longer. It's hard to tell, though; most of the company is being very quiet about it (indeed it wasn't until today that much internal noise was generated about the tool at all).
Of course, maybe I'm being duped. This could be some sort of company experiment to see, well, either how much free marketing they can get or who in the company is responsible for the press leaks. If it's the latter, then I need you all to take a look at my CV as I'll probably be relying on it - and you - soon ;-).
Anyway, take a look at the tool if you're interested, I've had reports that it works well but still haven't heard much feedback about the quality of the translation. BTW, interested in a Mac version of the tool? I can't promise anything but leave a message after the beep and I'll forward requests...
Tuesday, May 19, 2009
Detect the gagh lurking in your system!
Sophos Klingon Anti-Virus is a threat detection tool for Windows computers, but in Klingon. Ever wondered what Conficker and Rokeg blood pie have in common? No, neither have I. In fact, I doubt anyone has. Nonetheless, try out the tool and see what Romulan back-doors have been installed on your box.
(N.B. this means we have to expand our remit from "Enterprise" security software, to include at least the "HMS Bounty" from Star Trek IV)
Saturday, May 02, 2009
Rootier than root
Saturday, April 25, 2009
On dynamic vs. static polymorphism
One key factor was that Peter's solutions try to push all of the "smarts" of a design pattern into the compiler, using templates and metaprogramming to separate implementations from interfaces. On the other hand, my solutions use duck typing and dynamic method resolution to push all of the complexity into the runtime. Both solutions work, of course. It's also fairly obvious that they're both chosen based on the limitations and capabilities of the language we were each using. Nonetheless, it was interesting that we both had justifications for our chosen (and thus One True) approach.
In the Stroustroup corner, the justification is this: by making the compiler resolve all of the decisions, any problems in the code are resolved before it ever gets run, let alone before it gets into the hands of a user. Whereas the Cox defence argues that my time as a programmer is too expensive to spend sitting around waiting for g++ to generate metaprogramming code, so replace the compilation with comparitively cheap lookups at runtime - which also allows for classes that couldn't have possibly existed at compiletime, such as those added by the Python or Perl bridge.
This provided concrete evidence of a position that I've argued before - namely that Design Patterns are language-dependent. We both implemented Template Method. Peter's implementation involved a templatized abstract class which took a concrete subclass in the realisation (i.e. as the parameter in the <T>). My implementation is the usual Cocoa delegate pattern - the "abstract" (or more correctly undecorated) class takes any old id as the delegate, then tests whether it implements the delegation sequence points at runtime. Both implement the pattern, and that's about where the similiarities end.
Tuesday, April 21, 2009
Did you miss my NSConference talk?
Monday, April 20, 2009
I may have not been correct
Sunday, April 19, 2009
On default keychain settings
That almost - but not quite - solves the issue of a trojan horse attempting to access the secure password. Sure, a trojan application can't get at it without asking the user. What about other trojan code? How about a malicious SIMBL hijack or a bundle loaded with mach_override? It should be possible to mitigate those circumstances by using custom code signing requirements, but that's not exactly well documented, and it's not really good usability for an app to just die on its arse because the developer doesn't like the other software their user has.
There's a similar, related situation - what if the app has a flawed design allowing it to retrieve a keychain item when it doesn't need it? Sounds like something which could be hard to demonstrate and harder to use, until we remember that some applications have "the internet" as their set of input data. Using a web browser as an example, but remembering that I have no reason to believe whether Safari, Camino or any other browser is designed in such a way, imagine that the user has stored an internet password. Now all that the configuration settings on the user's Mac can achieve is to stop other applications from accessing the item. If that browser is itself subject to a "cross-site credentials request" flaw, where an attacking site can trick the browser into believing that a login form (or perhaps an HTTP 401 response, though that would be harder) comes from a victim site, then that attacker will be able to retrieve the victim password from the keychain without setting off any alarms with the user.
If the user had, rather than accepting the default keychain settings, chosen to require a password to unlock the keychain, then the user would at least have the chance to inspect the state of the browser at the time the request is made. OK, it would be better to do the right thing without involving the user, but it is at least a better set of circumstances than the default.
Friday, April 17, 2009
NSConference: the aftermath
It seems that my presentation and my Xcode top tip[*] went down really well, so thanks to all the attendees for being a great audience, asking thoughtful and challenging questions and being really supportive. It's been a couple of years since I've spoken to a sizable conference crowd, and I felt like everyone was on my side and wanted the talk - and indeed the whole conference - to be a success.
So yes, thanks to Scotty and Tim, Dave and Ben, and to all the speakers and attendees for such a fantastic conference. I'm already looking forward to next year's conference, and slightly saddened by having to come back to the real world over the weekend. I'll annotate my Keynote presentation and upload it when I can.
[*] Xcode "Run Shell Script" build phases get stored on one line in the project.pbxproj file, with all the line breaks replaced by \n. That sucks for version control because any changes by two devs result in a conflict over the whole script. So, have your build phase call an external .sh file where you really keep the shell script. Environment variables will still be available, and now you can work with SCM too :-).
Friday, April 03, 2009
Controlling opportunity
The Rational Unified Process goes for the slightly more neutral term Change Request Management, but the documentation seems to imply the same opinion, that it is the ability to make change requests which must be limited. The issue is that many requests for change in software projects are beneficial, and accepting the change request is not symptomatic of project failure. The most straightforward example is a bug report - this is a change request (please fix this defect) which converts broken software into working software. Similarly, larger changes such as new requirements could convert a broken business case into a working business case; ultimately turning a failed project into a revenue-generator.
In my opinion the various agile methodologies don't address this issue, either assuming that with the customer involved throughout, no large change would ever be necessary, or that the iterations are short enough for changes to be automatically catered for. I'm not convinced; perhaps after the sixth sprint of your content publishing app the customer decides to open a pet store instead.
I humbly suggest that project managers replace the word "control" in their change documentation with "opportunity" - let's accept that we're looking for ways to make better products, not that we need excuses never to edit existing Word files. OMG baseline be damned!
Wednesday, March 04, 2009
On noodles
Steph, who is a very good musician and knows what she's talking about, wrote that there are two ways to play a harp, a "get the music right" recitation style and a "get the rhythm right and everything else follows" style more suited to improvisation, noodling or folk playing.
That's not only true of the harp, it seems to hold for many instruments. For instance, in a moment of crazed, um, craziness this weekend I bought what's commonly referred to as a lute. In fact, a lute with much in common with this lute. Now I've been playing it for all of about two hours in total since Saturday, and can barely remember what note each course plays, and do a poor rendition of about four different tunes from a book of trivially simple lute tunes. But today marked an interesting transition, as it was the first day that I could make music up on the instrument without either knowing or concentrating on what I was doing. Only a couple of things (the song "Wooden Heart" made famous by Elvis Presley, and that banging dance-floor filler "Parson's Farewell") but this represented the point where I could make music on the lute - a different skill than remembering where and when to stick fingers on some bits of nylon, steel and wood.
And I think that's where the root of Steph's distinction of playing techniques really comes from; the unprepared style relies on having some music that needs to occur, and the ability for your hands (or nose or whatever your instrument is played with) to move around in some way which causes that music to exist. Whereas the prepared style relies on having some performance in mind that must be repeated, and requires that you think about moving $appendage in such-and-such way to recreate that performance. I find the distinction in conscious application to be an important one when playing the fiddle, an instrument I'm marginally better at than the lute. If I'm reading some music, playing solo or otherwise engaged in trying to play music, then I can only play whatever notes the music contained and in a fairly uninteresting manner. It's only if I'm able to relax and not think about the music that I can harmonise, ornament and otherwise play more interesting things than what was written on the page - even if not necessarily particularly well :-).
Monday, February 23, 2009
Cocoa: Model, View, Chuvmey
Chuvmey is a Klingon word meaning "leftovers" - it was the only way I could think of to keep the MVC abbreviation while impressing upon you, my gentle reader, the idea that what is often considered the Controller layer actually becomes a "Stuff" layer. Before explaining this idea, I'll point out that my thought processes were set in motion by listening to the latest Mac Developer Roundtable (iTunes link) podcast on code re-use.
My thesis is that the View layer contains Controller-ey stuff, and so does the Model layer, so the bit in between becomes full of multiple things; the traditional OpenStep-style "glue" or "shuttle" code which is what the NeXT documentation meant by Controller, dynamic aspects of the model which could be part of the Model layer, view customisation which could really be part of the View layer, and anything which either doesn't or we don't notice could fit elsewhere. Let me explain.
The traditional source for the MVC paradigm is Smalltalk, and indeed How to use Model-View-Controller is a somewhat legendary paper in the use of MVC in the Smalltalk environment. What we notice here is that the Controller is defined as:
The controller interprets the mouse and keyboard inputs from the user, commanding the model and/or the view to change as appropriate.
We can throw this view out straight away when talking about Cocoa, as keyboard and mouse events are handled by NSResponder, which is the superclass of NSView. That's right, the Smalltalk Controller and View are really wrapped together in the AppKit, both being part of the View. Many NSView subclasses handle events in some reasonable manner, allowing delegates to decorate this at key points in the interaction; some of the handlers are fairly complex like NSText. Often those decorators are written as Controller code (though not always; the Core Animation -animator proxies are really controller decorators, but all of the custom animations are implemented in NSView subclasses). Then there's the target-action mechanism for triggering events; those events typically exist in the Controller. But should they?
Going back to that Smalltalk paper, let's look at the Model:
The model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller).
If the behaviour - i.e. the use cases - are implemented in the Model, well where does that leave the Controller? Incidentally, I agree with and try to use this behavior-and-data definition of the Model, unlike paradigms such as Presentation-Abstraction-Control where the Abstraction layer really only deals with entities, with the dynamic behaviour being in services encapsulated in the Control layer. All of the user interaction is in the View, and all of the user workflow is in the Model. So what's left?
There are basically two things left for our application to do, but they're both implementations of the same pattern - Adaptor. On the one hand, there's preparing the Model objects to be suitable for presentation by the View. In Cocoa Bindings, Apple even use the class names - NSObjectController and so on - as a hint as to which layer this belongs in. I include in this "presentation adaptor" part of the Controller all those traditional data preparation schemes such as UITableView data sources. The other is adapting the actions etc. of the View onto the Model - i.e. isolating the Model from the AppKit, UIKit, WebObjects or whatever environment it happens to be running in. Even if you're only writing Mac applications, that can be a useful isolation; let's say I'm writing a Recipe application (for whatever reason - I'm not, BTW, for any managers who read this drivel). Views such as NSButton or NSTextField are suitable for any old Cocoa application, and Models such as GLRecipe are suitable for any old Recipe application. But as soon as they need to know about each other, the classes are restricted to the intersection of that set - Cocoa Recipe applications. The question of whether I write a WebObjects Recipes app in the future depends on business drivers, so I could presumably come up with some likelihood that I'm going to need to cross that bridge (actually, the bridge has been deprecated, chortle). But other environments for the Model to exist in don't need to be new products - the unit test framework counts. And isn't AppleScript really a View which drives the Model through some form of Adaptor? What about Automator…?
So let me finish by re-capping on what I think the Controller layer is. It's definitely an adaptor between Views and Models. But depending on who you ask and what software you're looking at, it could also be a decorator for some custom view behaviour, and maybe a service for managing the dynamic state of some model entities. To what extent that matters depends on whether it gets in the way of effectively writing the software you need to write.
Monday, February 09, 2009
When techs collide
Such a combination I found today, when I mixed a little bit of Distributed Objects with a soupçon of Cocoa Bindings to create, um, Distributed Bindings (calling it Cocoa Objects would just be rude).
It's actually just as simple as you think it will be, so there's no point in any sample code. You can basically use the answer to the FAQ question on DO. Once you've got the proxy object in the client, use it as the observable controller in -bind:toObject:withKeyPath:options:. And that's it!
Well, not quite it. You'll notice that things are a wee bit crashy, which is why this is somewhat like crossing the streams. Both Bindings and DO use the Proxy pattern to achieve their magic, but because the two systems have no special knowledge of each other the proxy connections are not kept in sync. If your server object mutates after the DO connection disappears, then it tries to send a KVO notification to an object that's no longer there…boom. Having a client-server system where the client can crash the server is of, well, dubious utility. There are some things that you could do to mitigate this, for instance looking for NSConnectionDidDieNotification (in the server) or opening a heartbeat RPC for the client to "check in" with the server. These fixes will work perfectly, if the vended object is updated predictably enough that you can reliably take care of broken connections between KVO notifications. Without that you're SoL, as the server won't reliably get a DO exception - more often than not it'll segfault. But while this may be unstable, it still is damned cool.