Posted on Leave a comment

More AppleScript

After my last post I really wanted to explore AppleScript some more. So that’s what I did.

One thing I like to do is listen to podcast episodes in chronological order. That is to say episodes from different podcasts. But also one episode at a time. The podcasts I subscribe to average about 50 minutes per episode. I use these as a measure of time while working. When an episode finishes I know it is time to take a quick break, get up, walk around for a minute it two. I don’t want the default iTunes behavior of going straight into the next episode and have to pause it when I get up. Some people might say that there is a particular program which can already do this easily. I didn’t really feel like getting a new program to do it since I was already managing them in iTunes. And I wanted something to do in AppleScript. It seemed like a good candidate.

I wrote this script for iTunes 10. There are problems with it in iTunes 11 because iTunes appears to sometimes discard “played” state of individual episodes. Anyway, here it is.

tell application "iTunes"
	set podcastsPlaylist to some playlist whose special kind is Podcasts
	set allUnplayedPodcastEpisodes to tracks in podcastsPlaylist whose unplayed is true
	if (length of allUnplayedPodcastEpisodes) is 1 then
		play first item in allUnplayedPodcastEpisodes
	else if (length of allUnplayedPodcastEpisodes) is greater than 1 then
		set oldestPodcastEpisode to first item in allUnplayedPodcastEpisodes
		repeat with i from 2 to length of allUnplayedPodcastEpisodes
			set podcastEpisode to item i in allUnplayedPodcastEpisodes
			if release date of podcastEpisode comes before release date of oldestPodcastEpisode then
				set oldestPodcastEpisode to podcastEpisode
			end if
		end repeat
		play oldestPodcastEpisode
	end if
end tell

My first post about AppleScript didn’t describe what the code does. Let’s do better with this post. People with little to no programming experience should still be able to understand it.


The first line, tell application "iTunes", means to use the iTunes dictionary for subsequent lines. An AppleScript dictionary contains information about commands and types specific to a particular application.

Line two, set podcastsPlaylist to some playlist whose special kind is Podcasts, may look a little strange to those unfamiliar with AppleScript, but familiar with other languages. The expression some playlist whose special kind is Podcasts searches all instances of the type playlist and returns the first one it finds with special kind of Podcasts. It turns out the only playlist with special kind of Podcasts is the official podcast playlist containing all episodes. The result is then set to the variable podcastsPlaylist.

The third line, set allUnplayedPodcastEpisodes to tracks in podcastsPlaylist whose unplayed is true, similarly takes care of many details for you. The expression tracks in podcastsPlaylist whose unplayed is true finds and returns all unplayed episodes in the variable podcastsPlaylist. (This is actually where the script trips up. iTunes appears to not save the unplayed value properly, and podcast episodes which I previously played appear unplayed.) The resulting list of that expression is then set to the variable allUnplayedPodcastEpisodes.

The next line, if (length of allUnplayedPodcastEpisodes) is 1 then, is an optimization. Most of the work of the script is in searching for the oldest episode. When there is only one unplayed episode it is automatically the oldest. This line checks for that condition. When there is only one episode, the next line, play first item in allUnplayedPodcastEpisodes, executes. The variable allUnplayedPodcastEpisodes is a list, meaning there are multiple elements. List elements are normally accessed by index with index 0 being the first element, index 1 being the second, and so on. AppleScript has some shortcuts, one of which is accessing the first element. The line sends the play command with that first element. The play command accepts a media object for iTunes to begin playing. The iTunes dictionary defines it, so it only works after a tell application "iTunes" command.

The next line, else if (length of allUnplayedPodcastEpisodes) is greater than 1 then, checks to make sure there are podcast episodes. If there aren’t any episodes there is no point to running any more code because in the end it wouldn’t do anything. The condition checks for more than one because it is clearer under what conditions the following code runs.

Now we’ve come to the interesting part. This is where we search for the oldest episode. Since the date of the oldest episode is unknown we must check every episode looking for the earliest date. A basic linear search is good for this. It goes through the list comparing each episode to the oldest known episode.

The line set oldestPodcastEpisode to first item in allUnplayedPodcastEpisodes starts the algorithm. When first starting there is no “oldest episode” so one needs picked. We use the first element in the list because it is easy to access.

The following line, repeat with i from 2 to length of allUnplayedPodcastEpisodes, is the loop of what to look at. It tells the AppleScript interpreter to run the lines after it and before its corresponding end repeat multiple times. The portion with i says to use the variable i to store a different value each iteration. The rest of the line, from 2 to length of allUnplayedPodcastEpisode, says i will start as 2 and end as the number of elements in allUnplayedPodcastEpisode. Since it doesn’t define an increment, the value will increase by 1 each iteration. The first time an iteration runs i will be 2, the second time it will be 3, and so on until it equals the number of elements in allUnplayedPodcastEpisode. The first line within the loop, set podcastEpisode to item i in allUnplayedPodcastEpisodes stores the episode the loop is examining into a variable to make it easy to refer to later. It really just makes the code more readable. Instead of having item i in allUnplayedPodcastEpisodes every time we want to access the episode, we use the podcastEpisode variable.

The second line of the loop, if release date of podcastEpisode comes before release date of oldestPodcastEpisode then finds the older episode. It compares the release date of the currently known oldest episode to the episode of the loop iteration. When the release date of the iteration’s episode is before the oldest date the line inside the then block, set oldestPodcastEpisode to podcastEpisode, saves the iteration’s episodes as the oldest.

Once all elements of allUnplayedPodcastEpisodes have been examined, the script has saved the oldest episode in the oldestPodcastEpisode variable. At that point, we tell iTunes to play it by sending the play command.


That’s all. I covered a lot of the basics of AppleScript. Feel free to ask any questions in the comments.

Posted on Leave a comment

AppleScript to the Rescue

Screenshot
Screenshot
Screenshot of NetNewsWire AppleScript documentation

As a long time user of Google reader, it saddens me to see the service closed. A ton of information will be lost. All the starred articles and feeds no longer available will disappear into the ether.

I started looking into alternatives shortly after hearing about the intended closure. One reader I had heard a lot about in the past was NetNewsWire. One thing stuck out to me was the lack of sharing options. It has options to re-blog, save to Delicious, and send to Instapaper. There weren’t even options to share on Facebook or Twitter. I was particularly disappointed by no ability to save to Evernote. Evernote has greater persistence and searchability than other services. When adding an article to Evernote, the content syncs to all desktop clients. In the unlikely event Evernote shuts down, all the data in my Evernote maintains on my desktop.

Not to worry, AppleScript to the rescue. Both NetNewsWire and Evernote have AppleScript interfaces allowing automation of simple tasks. This script copies the current article in NetNewsWire into Evernote. Here is the code.

-- Get info about headline
tell application "NetNewsWire"
    set headlineTitle to title of selectedHeadline
    set headlineURL to URL of selectedHeadline
    set headlineDescription to description of selectedHeadline
    set headlinePublished to date published of selectedHeadline
end tell

-- Send it to Evernote
tell application "Evernote"
    set newNote to create note with html headlineDescription
    set title of newNote to headlineTitle
    set source URL of newNote to headlineURL
    set subject date of newNote to headlinePublished
end tell

Pretty straightforward. Also, Evernote must be open and logged in for the script to work.

Posted on Leave a comment

A diary on working with third party code

There comes a time for every developer when they must work with code written by somebody else. Some times it’s voluntary. Say for instance there is a useful library the developer wants to use instead of writing all the code themselves. Other times, it’s not. Like when a new developer joins a project already in progress. The example in this post is of the former.

I was recently working with a Unity plugin which enables easy development of 2D environments. Given that Unity is a 3D engine having a framework for 2D scenes is useful and speeds development. The team unanimously decided to use an existing plugin instead of building one in-house. We immediately started building the game around this framework. However we did have to pay a small fee.

A couple of days later came a surprise. The developer of the library released a major update. Version 2.0! Given that we had purchased the library less than a week before, we tried contacting the developer to find out if we could get the upgrade for free. We were a little concerned with the response, or lack thereof. We didn’t receive any response at all. Not a yes, not a no, nothing. Not a big deal, we still had version one to use.

Fast forward a few weeks, and then comes an issue. It turns out there was a bug in the library affecting sprites inside a scaled parent. I was able to fix the bug, but only by introducing another issue. Any sprite not in another object moved. I then found out the new version of the plugin fixes the bug among other new features. However, since we had not heard back from the developers it would be a paid upgrade for us.

In the end we bought version 2 of the library only to find out it introduced the same issue my fix did.

Anyway, there is no real lesson to learn from all this. It’s just one of the many issues we dealt with during development.

Posted on Leave a comment

Switching Engines

When I started work on Crowman & Wolfboy there had already been some development complete on the game. A few levels were already built and saving and loading were being coded. However we soon ran into several problems with development.

Documentation seemed really out-of-date with the original engine. Code wasn’t working as the documentation specified it should. Even the examples given didn’t work. It was a serious problem which made progress slow.

Not long after joining we started looking into alternatives. First, we came up with a list of requirements which an alternate need to meet to even be considered. With nearly all the art complete, the new engine needed to support 2D art assets. Nearly all engines are capable of this. A strictly 2D engine is the obvious answer, but 3D engines can be clamped into 2D so we didn’t want to rule them out. We wanted to target both iPhone and Android mobile platforms so solutions specific to one platform were quickly excluded. For example, when we were doing this Cocos2D only supported iOS and would require another separate engine for development on Android. Next, documentation needed to be current. This was the original problem we were trying to get away from.

From this list of requirements we narrowed the possibilities and eventually chose Unity. It is a 3D engine but has several frameworks for building 2D games. It supports exporting to both iOS and Android platforms. And lastly, documentation is excellent. As an added bonus, there is an active community using Unity.

Since switching we haven’t looked back.

Posted on Leave a comment

The Importance of Documentation

In the previous post I describe several forms of documentation and their uses. Hopefully it’s clear that each form is important and serves a distinct purpose. In a typical day, I find myself referencing at least two of these forms. some days I don’t reference any documentation. On days I do, it is most often a function list and forum.

For example, I might start off the day needing to do some complex operation with an object’s rotation in Unity. You can see Unity’s class list with the rest of their scripting documentation. I know an object’s rotation is represented by a quaternion so let’s start there. Now I see that the operation is already implemented as part of the class requiring only one line o code on my part. Later on, when it’s not working the way I expect, I can heard either their forum or Q/A site. Now I can search for other people with the same problem or ask a new question myself. An answer will probably send me back to the class list as a reference.

These are the kinds of connections present between all the forms of documentation. Each one serves a specific purpose and knowing that purpose will help you find information faster.

Posted on Leave a comment

The Many Forms of Documentation

When I tell non-progammers I’m a software engineer most of them ask about coding languages or mention something about HTML. They have this idea that programming is all code all the time. A lot more goes into programming than just code. Before writing any code an engineer needs to know what capabilities are already provided to him/her. This is known as documentation.

Documentation comes in many forms. You probably already know one. Dictionaries are the most basic forms of documentation. They exist for spoken languages as well as computer languages. They contain words and their definitions. Some even contain grammar information. The dictionaries for computer languages are often called specifications. They contain the reserved words and grammar definition of a language.

Every computer language has a specification. The Java specification is on Oracle’s website. The specification is the most important form of documentation for a language. It defines what can and cannot be written in the language. The specification also defines the syntax of the language. However, as important as a specification is, they are rarely referenced. Most are difficult to read and contain more information than the common programmer is looking for.

The most common form of documentation is a class or function list. This kind of documentation varies from language to language but all have the same basic information. They contain predefined classes, methods, and functions for use in code. PHP has an excellent function list with the ability for people to leave comments. Another excellent example is the Mozilla developer network. These types of documentation are useful because a programmer can use functionality which is already built and tested instead of having to build their own. Most of my bookmarks are to a class list for something. The Unity game engine actually includes a class list as part of its installation making it easier to find documentation while offline.

A third form of documentation is what I call tutorials. They go by many names, tutorial, how to, cookbook, et. al. They contain examples of how to do basic or complex tasks. These are useful when there isn’t a single function to accomplish a task, but you know it is commonly performed. Looking up a task in a tutorial often yields a simple example and information for more complex situations.

The last form of documentation I will cover is the forum. This kind of documentation is a little different from the others. People ask questions and others answer. It requires a community of people capable of answering questions. There are many forums about programming. The most popular now is stack overflow. What makes these work is the community. With so many people willing to answer questions it is likely there is somebody capable of answering one you might have. Over time the forum becomes a reference as more questions receive answers.

There are other forms of documentation like BNF and class diagrams which I may cover later. Until then, know the differences and purposes of each kind of documentation.

Posted on Leave a comment

Why Math?

When I was in high school I took a class most students take. It was a trigonometry class. Most of my classmates had a frequent recurring question, “Why do we need to know this?” The teacher wasn’t very helpful with giving an answer. So I took it upon myself to come up with one. Being a youth myself it proved a difficult task. What I came up with were two rather unsatisfying answers. The first answer was simply, “for the test.” My other answer looked a little further into the future and was, “for next year’s class.” Little did I know that I would continue using it for years to come.

Most recently I used trig in programming the camera movement for Windom. There were two rules for it’s motion. One, the camera should move in a parabolic shape vertically, close to the character when low and high and far from the character when in the middle heights. And two, it should move in a circle horizontally around the character. Those of you who know your trig should already see how it will come into play.

I was working from a drawing of what the motion should be. But what I needed was a function which defines the distance from the character. So as a starting point, I decided to find the function which defines the drawing. Here’s a visual.

Stick figure with parabolic camera motion

Here’s what I knew. The line of symmetry goes through the top of the character, there is a point on the parabola at the character’s feet and one above the character. The function which defines this is h(sqrt(-x/m)+1) where h is the height of the character and m is the furthest distance modifier. It turns out this function isn’t very useful. It gives a height when provided with the distance from the character. I wanted a distance from the character provided with the height. Easy, just take the inverse. The result with some simplification is hm(1-x^2). That is what defines the distance which the camera should be from the character given the height of the camera.

The rest is comparatively easy. I know the rotational point where the camera should be in radians. It is just a matter of using trig to convert to x and z coordinates. I went with x=d*sin(r) and z=d*cos(r) where d is the distance provided by the the function in the previous paragraph and r is the rotational position in radians.

If I didn’t know trig the circular motion part would have been immensely more difficult. When I was in high school I never expected to need trig for very much but now I have more appreciation for it.

Posted on Leave a comment

Apple Sales Tax

There has been much talk lately over Apple’s recent changes to its app store guidelines. It seems apps aren’t making much profit from ebook sales. You see, anytime an app on iOS makes an ebook sale, 30% of the sale goes to Apple.

When I first heard about the rules I thought they seemed a little odd. I tried to think of an equivalent rule with brick and mortar stores. It took a long time, but finally I found something. It’s not quite the same, but it is quite similar. What I came up with is sales tax.

As with any fees, businesses have a choice to make. Are the fees passed on to customers or absorbed into costs? I can’t imagine ebook retailers having large margins. Passing fees onto customers is a risky option.

However, that’s not the main problem. The ebook retailers have a competitor who is unaffected by these fees, Apple. Apple runs its own ebook store in iBooks. But how does a company apply a fee to itself? This gives the iBooks store an unfair advantage over all other ebook retailers. This would be like the state tax department running a competitive retail store. To me that doesn’t seem fair. But then again, I’m not a retailer and don’t run a business selling ebooks.

Posted on Leave a comment

Javascript Controlled SVG Part 2

I have already covered utility functions and GUI code, but most of the code is for calculations of color data. This post will explain how all of the code ties together.

When the user first loads the color picker the default state is loaded. All values are zero and correspondingly the color is black. RGB (0,0,0) is black and HSV (0°,0,0) is black.

All event handlers do basically the same thing. First the master color color data  is updated to reflect the changes made by the user. Next the RGB, HSV, and hex code are updated to reflect the color data. If the user is changing RGB values, those copied to the color date and used to calculate HSV and hex code. If the user is changing HSV values, those copied to the color date and used to calculate RGB and hex code.

All event handlers ultimately call the update function. This in-turn updates the handle locations, background gradients, and preview area. each is separated into its own function.

The updateHandles function uses the color data to update the locations of the sliders. Let’s go over one group in the function.

var redHandle = max - colorData.red / 255 * 199;
document.getElementById("redHandle").setAttribute("y",redHandle);
document.getElementById("redLabel").firstChild.nodeValue = Math.round(colorData.red);

The first line is responsible for calculating the top side of the red value slider handle. Yes, I know it has magic numbers. if you read my earlier posts you would know this is more like a proof of concept than a finished product. magic numbers never make it into my finished works. 255 is the maximum value for red, 199 is for the size of the slider. Looking at it now, 199 could be replaced with (max - min). The second line moves the handle to the new position. The third updates the value displayed below the slider. These three lines are repeated for every slider with different constants.

The background of each slider shows the resulting color of moving that particular slider. These gradients need updated every time the color data changes. doing so is as easy as calculating color data as if the slider is set to each end. The hue background is slightly different. It has one gradient with all the hues represented and two overlays. one overlay is completely white representing the saturation. the other is black representing the value. The opacity of each overlay is adjusted according to the current location of the corresponding slider.

The preview is easier to compute than any topic discussed so far. Using the RGB color data, the hex code is calculated. Each color is converted using the deciToHexDigits function to ensure placement of zeros. The resulting string is then shown to the user and applied as the fill of the preview area.

Posted on Leave a comment

Javascript Controlled SVG Part 1

In my last post I described the experience and development of my first true attempt at SVG. This post will describe the javascript code which implements the behavior of that color picker. This is meant to describe the code to somebody who understands basic programming but not necessarily javascript or working with graphics. If you have a solid grasp on javascript and programming GUIs you can skip this post.

All code is viewable in the source of the page.

First let’s cover the “global” variables. The first, HEX, is used as a constant in the conversion from decimal to hexadecimal (more on that soon). The colorData variable is used to store the state of the color data and is directly modified and displayed by the sliders. The min and max variables are treated more like constants as they represent the minimum and maximum pixel locations of the sliders. The selected variable points to the currently selected slider, or null if none are selected. To be selected means the user is currently modifying that slider. Finally, button points to the button currently in use by the user, or null if none are in use.

Now for the functions. The code covered in this post does not include application logic. These functions facilitate communication between the graphical state and the data and most are event handlers. Most of them are fairly straightforward.

The first function is mouseCoords. This function is pretty straightforward. It takes any mouse event fired by the browser, extracts the coordinates of the event, and returns a single object containing the x and y coordinates.

deciToHex takes an integer and returns a string of the hexadecimal representation. The deciToHexDigits function converts an integer to a zero padded hex string which has a minimum number of digits. It takes two parameters, the integer to convert and the number of digits.

The update function updates the graphical state to reflect any changes to the data. It should be called anytime the state changes.

The drag function is deprecated and no longer works. However, you will notice it is still being called by some SVG elements. This was used early in development but never removed when replacements were developed. In a non-educational, shipping product any code referring to it should be removed. The reason it is still in the source is because it was handed in that way and this is meant to be an archive of what was graded.

The selectHandle function is the event handler for when a user clicks in one of the handles of a slider. It sets the global for the currently selected handle. The unselect function sets the state of all objects to not selected. It is similar to a “select none” action in most applications. It affects all sliders and buttons.

The buttonOver, buttonDown, buttonOut, and buttonUp functions are all event handlers working in conjunction with makeButtonDown and makeButtonUp to control the graphical state of the buttons. When the user mouse-downs on a button the global button is set to point to that button and the grical state of it changes. The user can then mouse-out and mouse-over the button with only the state of that button changing. If the user then mouse-ups anywhere outside of the button no action is performed and the global is set to null. This functionality is similar to native buttons on most platforms. If the user mouse-downs on a button and proceeds to mouse-up over the same button, it is considered a click. the click is reflected by changing the color data withing the boundaries of each attribute followed by the graphical update.

Color Picker

The next post (Part 2) will cover the application logic and associated code.