Sunday, October 2, 2011

MacOSX standard artwork in LiveCode

When you develop an application for Mac, users have certain expectations about how your app will look and behave. One of the often forgotten parts of your user interface is the icon artwork - it is very tempting to simply buy an icon collection and then use it everywhere in your cross-platform application. However, to help developers achieve a consistent user interface, across multiple versions of the operating system, Apple has been adding 'template' images to its Cocoa NSImage class.

Here are a few examples which I recently used in a project:


For a complete list of the available template images, look here.

Great stuff, but how are we going to get at it from LiveCode? Not directly, I'm afraid. But all is not lost: a while back, Apple's Java engineers added to their Java implementation on MacOS X 10.5 Leopard (and later) the ability to fetch these images using a simple call:
Toolkit.getDefaultToolkit().getImage("NSImage://NSColorPanel")

You can see where I'm heading with this: writing a helper Java class that you can execute with a simple 'shell' function call. So let's start by writing up the Java class code. We'll set it up with two parameters: the first parameter accepts either "*" (to say you want a complete set of images) or a comma-separated list of image names; the second parameter is the output directory where the available images will be saved in PNG format.

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.EnumSet;
import javax.imageio.ImageIO;

public class NSImageFetcher {

public enum NSImageName {
// Image Template Constants
NSQuickLookTemplate,
NSBluetoothTemplate,
NSIChatTheaterTemplate,
NSSlideshowTemplate,
NSActionTemplate,
NSSmartBadgeTemplate,
NSPathTemplate,
NSInvalidDataFreestandingTemplate,
NSLockLockedTemplate,
NSLockUnlockedTemplate,
NSGoRightTemplate,
NSGoLeftTemplate,
NSRightFacingTriangleTemplate,
NSLeftFacingTriangleTemplate,
NSAddTemplate,
NSRemoveTemplate,
NSRevealFreestandingTemplate,
NSFollowLinkFreestandingTemplate,
NSEnterFullScreenTemplate,
NSExitFullScreenTemplate,
NSStopProgressTemplate,
NSStopProgressFreestandingTemplate,
NSRefreshTemplate,
NSRefreshFreestandingTemplate,
NSFolder,
NSTrashEmpty,
NSTrashFull,
NSHomeTemplate,
NSBookmarksTemplate,
NSCaution,
NSStatusAvailable,
NSStatusPartiallyAvailable,
NSStatusUnavailable,
NSStatusNone,
NSApplicationIcon,
NSMenuOnStateTemplate,
NSMenuMixedStateTemplate,
NSUserGuest,
NSMobileMe,
// Multiple Documents Drag Image
NSMultipleDocuments,
// Sharing Permissions Names Images
NSUser,
NSUserGroup,
NSEveryone,
// System Entity Images
NSBonjour,
NSDotMac,
NSComputer,
NSFolderBurnable,
NSFolderSmart,
NSNetwork,
// Toolbar Named Images
NSUserAccounts,
NSPreferencesGeneral,
NSAdvanced,
NSInfo,
NSFontPanel,
NSColorPanel,
// View Type Template Images
NSIconViewTemplate,
NSListViewTemplate,
NSColumnViewTemplate,
NSFlowViewTemplate;
}


public static Image getNSImage(final NSImageName nsImageName) {
return getNSImage(nsImageName.name());
}

public static Image getNSImage(final String nsImageName) {
return Toolkit.getDefaultToolkit().getImage("NSImage://" + nsImageName);
}

public static void saveNSImage(final NSImageName nsImageName, final File outputFile) throws IOException {
saveNSImage(nsImageName.name(), outputFile);
}

public static void saveNSImage(final String nsImageName, final File outputFile) throws IOException {
final Image nsImage = getNSImage(nsImageName);
if (nsImage != null) {
BufferedImage bufferedImage = null;
if (nsImage instanceof BufferedImage) {
bufferedImage = (BufferedImage) nsImage;
} else {
bufferedImage = new BufferedImage(nsImage.getWidth(null), nsImage.getHeight(null), BufferedImage.TYPE_INT_ARGB);
final Graphics bufImgGraphics = bufferedImage.getGraphics();
bufImgGraphics.drawImage(nsImage, 0, 0, null);
}
if (!outputFile.exists()) {
outputFile.createNewFile();
}
ImageIO.write(bufferedImage, "png", outputFile);
}
}

public static void main(String[] args) throws IOException {
// We can't run in headless mode or we get empty icons
// System.setProperty("java.awt.headless", "true");

if (args.length != 2) {
System.out.println("Usage: java NSImageFetcher <list of NSImageNames>,<output directory>");
return;
}
final File outputDirectory = new File(args[1]);
if ("*".equals(args[0])) {
for (final NSImageName nsImageName : EnumSet.allOf(NSImageName.class)) {
final File outputFile = new File(outputDirectory.getAbsolutePath() + File.separator + nsImageName.name() + ".png");
saveNSImage(nsImageName, outputFile);
}
} else {
for (final String nsImageName : args[0].split(",")) {
try {
final File outputFile = new File(outputDirectory.getAbsolutePath() + File.separator + nsImageName + ".png");
saveNSImage(nsImageName, outputFile);
} catch (IllegalArgumentException e) {
// ignore
}
}
}
}
}

And here's the LiveCode button script to put all the images into a subdirectory 'resources' in the directory where the stack is saved:

on mouseUp
-- save settings
local tOldDefaultFolder, tOldHideConsoleWindows
put the defaultFolder into tOldDefaultFolder
set the defaultFolder to StackFolderPath()
put the hideConsoleWindows into tOldHideConsoleWindows
set the hideConsoleWindows to true
-- call the command line via shell
local tShellCommand, tShellResult
put "java NSImageFetcher" && \
quote & "*" & quote && \
quote & StackFolderPath("resources") & quote into tShellCommand
answer tShellCommand & return & shell(tShellCommand)
-- restore settings
set the defaultFolder to tOldDefaultFolder
set the hideConsoleWindows to tOldHideConsoleWindows
-- go ahead and link
end mouseUp

function StackFolderPath pRelativePath
local tPath
put the effective filename of this stack into tPath
set the itemDelimiter to slash
if pRelativePath is empty then
delete item -1 of tPath
else
put pRelativePath into item -1 of tPath
end if
return tPath
end StackFolderPath

Okay, MacOSX comes with a preinstalled Java runtime so the above should work on MacOSX 10.5 Leopard, MacOSX 10.6 Snow Leopard and even on MacOSX 10.7 Lion (since there's still a Java 6 'out of the box'). Naturally, the artwork may change between operating system versions. So my approach would be to:
- check if there is a '<MyCompanyName>/<MyAppName>/resources' directory in the user's preferences directory (by means of the 'specialFolderPath' function);
- if the directory is absent, create it and use the 'shell' function as above to fetch the images I need, and save the 'systemVersion' in a text file in the same directory
- if the directory is present, compare the current value of the 'systemVersion' with the one saved in said directory, and once again fetch the images if there's a difference

It's up to you to either use references to these .PNG images by setting the 'filename' property of an 'image' control; or to then import the .PNG files into a stack.

Note that this artwork is copyrighted by Apple, Inc. You shouldn't extract it and then use it in your apps on any platform other than MacOSX. Oh, and please head the warning "You should always use named images according to their intended purpose, and not according to how the image appears when loaded. The appearance of images can change between releases. If you use an image for its intended purpose (and not because of it looks), your code should look correct from release to release."

Sunday, September 25, 2011

Determining the Aqua UI appearance on MacOS X

Due to high workload at the day-job, I haven't been able to keep my schedule regarding the experiment building a Ribbon custom control for LiveCode. It's still going to happen, but is going to take a bit longer than planned. In the meantime, I will post some tidbits that are relevant to those that design custom controls for LiveCode.

In MacOS X, the Preferences application has a panel titled Appearance:



Yeah, I know I'm still on MacOS X Snow Leopard 10.6.8 - just waiting for Lion 10.7.2 before I upgrade.
Anyway, the Appearance option menu has two entries: Blue and Graphite.



Below that option menu, is the Highlight color option menu; and if we want to know this color in our LiveCode scripts, all we have to do is check the global 'hiliteColor' property. But there's no built-in way to access the Appearance. So how can we get this information? Do we have to write an external to find out whether we should have blue or graphite custom controls?

As it turns out, we can get at this system setting by using the 'defaults' command via the 'shell' function. Just plop the following in a button script:

on mouseUp
local tVariant, tAppearance
put word 1 to -1 \
of shell("defaults read -g AppleAquaColorVariant") \
into tVariant
switch tVariant
case 1
put "Blue" into tAppearance
break
case 6
put "Graphite" into tAppearance
break
default
put "Unrecognized appearance variant [" & \
tVariant & "]" into tAppearance
break
end switch
answer tAppearance
end mouseUp


Click the button, and depending on your operating system and preferences setting, you'll see the appropriate message. It appears that at one point there were a few more appearances, but they were lost during a chopping frenzy in Cupertino. Be that as it may, you now have a way to check for the appearance setting in the preferences window.

Sunday, August 7, 2011

Experimenting with ribbons in LiveCode (part 4)

Four weeks ago, we kicked off an experiment to create a ribbon control for LiveCode. By now, we have a clear goal, derived an initial XML structure for our 'ribbonText' property, and in the previous post, we finally got some visual work done, implementing the ribbon background and tabs. The next logical step is to implement our ribbon groups.

There is actually more to a ribbon group than initially meets the eye:
- groups can have an associated dialog (e.g. to call up the classic font dialog)
- groups can be added to the quick access toolbar
- groups have rules for dynamic resizing

But we'll postpone these juicier bits until wev'e gotten around to actually adding buttons to our ribbon control. Right now, our goal is to turn the group definitions in our ribbonText property into controls. First we extend the ribbonText parser to also read the <Group> definitions from the XML structure, and then we add the necessary code to the 'qrtRexRibbonGroupsBehavior' script. Under our current (limited) interpretation, each ribbon group is nothing more than the label and the separator next to it.

Once more, I've opted for the approach of taking a slice from a screenshot to represent the separator, as I couldn't get the stroke and fill gradients of a graphic to exactly mirror the original. Maybe one of these days I'll throw out the images and replace them all with gradients anyway - but today is not that day. At any rate, with just two controls to add, it's pretty easy.



And by separating out the code that triggers the population of the nested RibbonGroups custom control group, we can easily switch ribbon group sets by handling the custom 'ribbonTabPick' event that is dispatched from the nested RibbonTabs custom control group which we implemented in the previous post.

Download the current revision here - next time we'll tackle the buttons.

Tuesday, August 2, 2011

Experimenting with ribbons in LiveCode (part 3)

Three weeks ago, we kicked off an experiment to create a ribbon control for LiveCode. By now, we have a good plan, and we have an initial XML structure for our 'ribbonText' property. So let's go ahead and start putting together some code! Let's start with the ribbon background and header area, shall we?

I really wanted to do it all with only graphics, gradients and effects, but I couldn't quite get the details right. So eventually I went for the oldest trick in the book: I took a screenshot and then extracted three slices from the image: 2 pixels wide for the left and right edge, and then 1 pixel wide for the center. You can't use this slice as a pattern for another control, but you can just stretch that image as far as you need: because the original is only 1 pixel wide, the engine can stretch the image at a low cost, because there is no interpolation required.



Let's get a head start on the ApplicationMenu button: take some more screenshots while hovering and after clicking on it; then extract the images for each state of the ApplicationMenu; drop in a button and assign the appropriate image ids for the button's regular, hilited and hover icons. This is not the time for the menu itself, though, so let's move on to the ribbon tabs.



But before that, let's drop in a field "RibbonText" and a button to apply it to our ribbon group. It will make testing a whole lot easier as we go and add features.



Pop quiz: what is the fastest way to create a custom tab header in LiveCode?
Answer: why, a radio button group, of course!

I know what you're thinking: "Hold on, have you lost your marbles? Doesn't a group of radio buttons look like this?"



Well, sure - but by setting a few properties, you can turn that into this:



And that's accomplished without any scripting; once you start handling mouse event messages, you can dynamically apply graphic effects to even greater effect. But that won't suffice for our ribbon, I'm afraid, altough the principle stands: a group of 'radio buttons' can adequately implement our ribbon tabs, as long as they don't have to do it on their own...

There are several factors that determine a ribbon tab's appearance: whether or not the tab is hilited, whether or not the mouse is hovering over the tab, and whether the mouse is pressed or not. So we will enlist the help of some image controls to achieve each of these appearances.

Once again, we use an image editor to take three slices from a screenshot: one for the left edge, one for the right edge, and another to serve as a background, stretched accross the gap. Rinse and repeat for each appearance. The width of the tab can be calculated by taking the formattedWidth of the button, and adding another eighteen pixels, nine on each side, for good measure.

With our approach clearly outlined, we can code the creation of all the controls needed for the ribbon tabs, one tab at a time: first we create the three images for the tab, and then a heavily modified radio button; next, we determine the correct rectangle of our tab button, and adapt the rectangles of our three backing images to match; finally, we inject copies of the appropriate original images; and all the layers are as we would expect.



As soon as we have the tab creation working correctly, we can code the necessary engine event message handlers, property getters and setters, as well as a splash of private commands to make the ribbon tabs act like the real deal. I'd rather not paste the code into this blog post - just download the current revision here and take a good look at the scripts in the qrtRexBehaviors substack.

Next time, we'll tackle the creation of groups - and the weather is still a bit of a mess, so check back soon!