Posted on 1 Comment

Using those pointers

In my last post I outlined a way to manage native object lifecycle from C# in Unity. But I skipped one of the conveniences of calling native functions. You can call a function without matching the declared type of the pointer parameters. That means you don’t need to use CFTypeRef everywhere.

The pointer you have in C# is untyped, it is void *. That’s the same as CFTypeRef. But you can declare and call native functions which are your type. Let’s take a look at one of the classes we could build from the last post.

// nativeClass.h
@interface NativeClass
- (instancetype) init;
@end
// nativeClass.m
#import "nativeClass.h"
@implementation NativeClass
- (instancetype) init
{
  // omitted for brevity
}
@end

#if __cplusplus
extern "C" {
#endif
CFTypeRef _createNativeClass()
{
  return CFBridgingRetain([[NativeClass alloc] init]);
}

void _destroyNativeClass(CFTypeRef nativeClassInstance)
{
  CFRelease(nativeClassInstance);
}
#if __cplusplus
}
#endif
// NativeClass.cs
using System;
using System.Runtime.InteropServices;
public class NativeClass : IDisposable
{
  [DllImport("__Internal")]
  static extern IntPtr _createNativeClass();

  [DllImport("__Internal")]
  static extern void _destroyNativeClass(IntPtr nativeClassInstance);

  IntPtr m_Instance;

  public NativeClass()
  {
    m_Instance = _createNativeClass();
  }

  public void Dispose()
  {
    _destroyNativeClass(m_Instance);
  }
}

This is a very basic native class which has its lifecycle controlled from C#. But we can take things a step further with our own functions. Let’s add a method to our objective-c interface.

// nativeClass.h
@interface NativeClass
- (instancetype) init;
- (void)doSomeStuff;
@end

Now we can add an implementation, and provide a C function wrapper. Remember, C# can call C functions, but not objective-c. So we need to write a simple C wrapper for any methods we want to call from C#.

// nativeClass.m
#import "nativeClass.h"
@implementation NativeClass
- (instancetype) init
{
  // omitted for brevity
}

- (void)doSomeStuff
{
  // Only the best algorithm
}
@end

#if __cplusplus
extern "C" {
#endif
CFTypeRef _createNativeClass()
{
  return CFBridgingRetain([[NativeClass alloc] init]);
}

void _destroyNativeClass(CFTypeRef nativeClassInstance)
{
  CFRelease(nativeClassInstance);
}

void _doSomeStuffNativeClass(const NativeClass * instance)
{
  [instance doSomeStuff];
}
#if __cplusplus
}
#endif

Notice the declared pointer type in the function parameters. It is NativeClass * instead of CFTypeRef which was used last time. Yes, this actually works. Finally, let’s add the C# code for this method.

// NativeClass.cs
using System;
using System.Runtime.InteropServices;
public class NativeClass : IDisposable
{
  [DllImport("__Internal")]
  static extern IntPtr _createNativeClass();

  [DllImport("__Internal")]
  static extern void _destroyNativeClass(IntPtr nativeClassInstance);

  [DllImport("__Internal")]
  static extern void _doSomeStuffNativeClass(IntPtr instance);

  IntPtr m_Instance;

  public NativeClass()
  {
    m_Instance = _createNativeClass();
  }

  public void Dispose()
  {
    _destroyNativeClass(m_Instance);
  }

  void DoSomeStuff()
  {
    _doSomeStuffNativeClass(m_Instance);
  }
}

In C#, the pointer remains an IntPtr which is essentially a void * or CFTypeRef. But we can call functions with the proper type declared in the function parameters. That means no casting is needed when we marshal our pointer into native objective-c.

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

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.