Showing posts with label MacOS X. Show all posts
Showing posts with label MacOS X. Show all posts

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.

Wednesday, August 18, 2010

Fun with detailed files - and stat

In a previous post, I tried to find a way to convert Unix user and group ids into their corresponding names. After I reported my findings to the use-revolution mailing list, Andre Garzia stepped in, suggesting to take a look at the stat command.

Calling 'stat' through the shell function for every file would be costly and slow; using it to fetch the information for an entire folder in one go wouldn't be so bad, but if you already use the detailed files function built into revTalk, it would seem like a waste of cycles. So I decided to rewrite my work handlers, employing a caching mechanism for the id-to-name mapping, and using 'stat' to pick up the mapping information not available in the cache.
--> script-local 'static' variables

local sGroupIdMap, sUserIdMap

--> public functions and commands

command LoadIdMaps
p_LoadGroupIdMap
p_LoadUserIdMap
end LoadIdMaps

function GroupIdToName pGroupId, pFile
local tName, tShellCommand
put sGroupIdMap[pGroupId] into tName
if tName is empty and the platform is "MacOS" then
-- stat is only available on MacOS X
put p_GetFileStat(pFile, "%Sg") into tName
put tName into sGroupIdMap[pGroupId]
end if
return tName
end GroupIdToName

function UserIdToName pUserId, pFile
local tName, tShellCommand
put sUserIdMap[pUserId] into tName
if tName is empty and the platform is "MacOS" then
-- stat is only available on MacOS X
put p_GetFileStat(pFile, "%Su") into tName
put tName into sUserIdMap[pUserId]
end if
return tName
end UserIdToName

--> private functions and commands

private function p_GetFileStat pFile, pFormat
local tName, tShellCommand
-- make sure to escape spaces in the file name
replace space with backslash & space in pFile
put "stat -f" && pFormat && pFile into tShellCommand
put word 1 of shell(tShellCommand) into tName
return tName
end p_GetFileStat

private command p_LoadGroupIdMap
if the platform is "Win32" then exit p_LoadGroupIdMap
p_LoadFileIdMap "/etc/group", sGroupIdMap
end p_LoadGroupIdMap

private command p_LoadUserIdMap
if the platform is "Win32" then exit p_LoadUserIdMap
p_LoadFileIdMap "/etc/passwd", sUserIdMap
end p_LoadUserIdMap

private command p_LoadFileIdMap pFile, @pIdMap
local tData, tLine
put URL ("file:" & pFile) into tData
set the itemDelimiter to colon
repeat for each line tLine in tData
-- skip empty and comment lines
if tLine is empty \
or char 1 of tLine is "#" then next repeat
-- fill the id map
put item 1 of tLine into pIdMap[item 3 of tLine]
end repeat
end p_LoadFileIdMap

Armed with the above set of commands and functions, we can still use the detailed files function and obtain user and group names from a cache, calling into 'stat' as necessary. Let's update our sample button script:
on mouseUp
local tOldFolder, tNewFolder, tDetailedFiles
answer folder "Select a folder"
if the result is "Cancel" then exit mouseUp
put it into tNewFolder
--> extract the detailed files information
put the defaultFolder into tOldFolder
set the defaultFolder to tNewFolder
put the detailed files into tDetailedFiles
--> load the group and user id maps
LoadIdMaps
--> build the extended file information
local tDetailedFile, tExtendedFiles
local tFile, tUserId, tGroupId
repeat for each line tDetailedFile in tDetailedFiles
-- skip hidden files
if char 1 of tDetailedFile is "." then next repeat
-- fill the extended file entry
put urlDecode(item 1 of tDetailedFile) into tFile
put item 8 of tDetailedFile into tUserId
put item 9 of tDetailedFile into tGroupId
put tFileName & tab & \
UserIdToName(tUserId, tFile) & tab & \
GroupIdToName(tGroupId, tFile) & return \
after tExtendedFiles
end repeat
--> wrap things up
set the defaultFolder to tOldFolder
put char 1 to -2 of tExtendedFiles into field "Files"
end mouseUp

The more observant amongst you may think "If all you needed was a file's user and group name, why not just 'stat' and get it over with?" - well, the detailed files function returns a lot of useful information in one go, including the size of the resource fork of a file on MacOS systems.
Just one more thing: the 'stat' function was added in MacOS X 10.4 Tiger - so if your application still needs to support MacOS X 10.3 Panther, you're going to have to merge in the 'nireport' call from the previous post. Consider it an exercise for the reader.

On to the next challenge!

Tuesday, August 17, 2010

Fun with detailed files

Earlier today, the following question was posted on the use-revolution mailing list: file owner & group names. Rev veteran Monte Goulding was wondering how to convert file owner and group ids into actual user and group names. I happily logged into the Solaris server at work and dug around a bit, finally replying that he could parse this information from the following two files:
/etc/group
/etc/passwd

And what would such a parsing script look like in revTalk? I'm glad you asked:
command LoadGroupIdMap @pGroupIdMap
p_LoadFileIdMap "/etc/group", pGroupIdMap
end LoadGroupIdMap

command LoadUserIdMap @pUserIdMap
p_LoadFileIdMap "/etc/passwd", pUserIdMap
end LoadUserIdMap

private command p_LoadFileIdMap pFile, @pIdMap
local tData, tLine
put URL ("file:" & pFile) into tData
set the itemDelimiter to colon
repeat for each line tLine in tData
-- skip empty and comment lines
if tLine is empty \
or char 1 of tLine is "#" then next repeat
-- fill the id map
put item 1 of tLine into pIdMap[item 3 of tLine]
end repeat
end p_LoadFileIdMap

Given that both files use a colon as item delimiter, and have the name as first item and the id as third item, I extracted the parsing into a separate private command. Put the above handlers in your stack script, and then fetch each id-to-name-mapping before interpreting the detailed files.
Here's a simple button script that uses the above commands:
on mouseUp
local tOldFolder, tNewFolder, tDetailedFiles
answer folder "Select a folder"
if the result is "Cancel" then exit mouseUp
put it into tNewFolder
--> extract the detailed files information
put the defaultFolder into tOldFolder
set the defaultFolder to tNewFolder
put the detailed files into tDetailedFiles
set the defaultFolder to tOldFolder
--> load the group and user id maps
local tGroupIdMap, tUserIdMap
LoadGroupIdMap tGroupIdMap
LoadUserIdMap tUserIdMap
--> build the extended file information
local tDetailedFile, tExtendedFiles
repeat for each line tDetailedFile in tDetailedFiles
-- skip hidden files
if char 1 of tDetailedFile is "." then next repeat
-- fill the extended file entry
put urlDecode(item 1 of tDetailedFile) & tab & \
tUserIdMap[item 8 of tDetailedFile] & tab & \
tGroupIdMap[item 9 of tDetailedFile] & return \
after tExtendedFiles
end repeat
--> wrap things up
put char 1 to -2 of tExtendedFiles into field "Files"
end mouseUp

Once I got home, I wanted to verify this on my MacOS X machine, only to discover that it wasn't properly mapping the uid and gid to user and group names. Intrigued, I dug a bit deeper and found out that MacOS X actually relies on a DirectoryService when it's not running in single-user mode. Lovely, but how can we get what we need using revTalk?
Well, it turns out you can use the nireport command via the shell function to fetch a list of the group and user names with id. So let's add another helper command to do things the MacOS X way, and update our existing commands to use the correct approach, depending on the platform.
command LoadGroupIdMap @pGroupIdMap
if the platform is "MacOS" then
p_LoadNireportIdMap "/groups gid name", pGroupIdMap
else if the platform is "Linux" then
p_LoadFileIdMap "/etc/group", pGroupIdMap
end if
end LoadGroupIdMap

command LoadUserIdMap @pUserIdMap
if the platform is "MacOS" then
p_LoadNireportIdMap "/users uid name", pUserIdMap
else if the platform is "Linux" then
p_LoadFileIdMap "/etc/passwd", pUserIdMap
end if
end LoadUserIdMap

private command p_LoadFileIdMap pFile, @pIdMap
local tData, tLine
put URL ("file:" & pFile) into tData
set the itemDelimiter to colon
repeat for each line tLine in tData
-- skip empty and comment lines
if tLine is empty \
or char 1 of tLine is "#" then next repeat
-- fill the id map
put item 1 of tLine into pIdMap[item 3 of tLine]
end repeat
end p_LoadFileIdMap

private command p_LoadNireportIdMap pParams, @pIdMap
local tData, tLine
put shell ("nireport ." && pParams) into tData
set the itemDelimiter to tab
repeat for each line tLine in tData
put item 2 of tLine into pIdMap[item 1 of tLine]
end repeat
end p_LoadNireportIdMap

This seemed to do the trick on my iMac PowerPC G5 running MacOS X 10.4 Tiger - but when I tried it on my MacBook Pro Intel running MacOS X 10.6 Snow Leopard, it failed as there is no "nireport" command available. As it turns out, Apple dropped NetInfo when MacOS X 10.5 Leopard came out. So my solution is not quite complete, unfortunately.

To be continued...

Sunday, October 25, 2009

Revolution, Snow Leopard and AppleEvent handlers

As you know, Macs have always sported a rather different operating system - in fact, MacOSX is quite good at hiding its powerful UNIX underpinnings from the average user, while still offering its full power to the more advanced computer user. But tossing out the old brittle 'cooperative multi-tasking' MacOS Classic, and swapping in the modern, robust NeXtStep with a new coat of paint, required that the Apple developers came up with a whole compatibility layer, named Carbon.

And one of the things that Carbon brought with it, was the system of Apple Events - added in System 7.0, this new type of event allowed Mac applicatiosn to talk to one another. Later, these Apple Events formed the underpinning of AppleScript, the system-wide scripting mechanism that is widely used for automating processes (and in turn, underpins the Automator tasks that allow you to point-and-click automation workflows in MacOSX).

What exactly is an Apple Event? An AppleEvent has a generic Class and Id, as well as associated data - and our rev stacks can handle these events by implementing an 'appleEvent' handler in our (stack) script. Alright, but why should I care as revDeveloper? Because if you want to write a decent Mac application, you had better implement the 'core' events. These are apple events of class 'aevt' and have an id of 'oapp' (open application), 'odoc' (open document), 'pdoc' (print document) or 'quit' (exit application).

Now, the revEngine is kind enough to handle the 'oapp' and 'quit' events for us, translating them into built-in events for us to handle, So we can concentrate on 'odoc' and 'pdoc' - and in fact, we only need to bother with these if we have some sort of 'editor' application. Of course, the Quartam Reports Layout Builder is exactly such an application. So I implemented a simple handler in my stack:
on appleEvent pClass, pId
if pClass is "aevt" and pId is "odoc" then
-- get the associated data
request appleEvent data
put it into tFilePath
-- now handle opening the file somewhere else
OpenFile tFilePath
else
-- let the revEngine handle other events
pass appleEvent
end if
end appleEvent

However, with the release of Snow Leopard, the format of the associated data appears to have changed rather dramatically. In previous releases, we would get a file path that we could use directly in file processing. For instance, your 'OpenFile' handler could look something like this:
on OpenFile pFilePath
put URL ("binfile:" & pFilePath into tBinaryData
-- go ahead and parse the content of the file
end OpenFile

For Snow Leopard, the good engineers at Apple have decided to change the format and where a file path from an 'odoc' event used to look something like "/My Big Project/Layouts/My First Layout.qrl", it now looks something like "file://localhost/My%20Big%20Project/Layouts/My%20First%20Layout.qrl" - presumabl, they're paving the way for other protocls than "file://" in the future, but this change has left our apps in the dust. I'm sure they were kind enough to update the Cocoa framework to translate this automatically, but what about us who don't drink the Objective-C Kool-Aid?

Well, the '%20' substitute for the space character, clued me in that there was some sort of URL encoding going on. So after a bit of fiddling, I came up with the following workaround for this prickly problem:
on appleEvent pCLass, pId
if pClass is "aevt" and pId is "odoc" then
-- get the associated data
request appleEvent data
put NormalizedPath(it) into tFilePath
-- now handle opening the file somewhere else
OpenFile tFilePath
else
-- let the revEngine handle other events
pass appleEvent
end if
end appleEvent

function NormalizedPath pFilePath
put pFilePath into tNormalizedPath
-- workaround change in Snow Leopard
if char 1 to 7 of pFilePath is "file://" then
set the itemDelimiter to slash
delete item 1 to 3 of pFilePath -- remove "file://localhost" from front
repeat for each item pFilePart in pFilePath
put slash & urlDecode(tFilePart) after tNormalizedPath
end repeat
end if
return tNormalizedPath
end NormalizedPath

Splitting off the NormalizedPath function means I can reuse it for the 'pdoc' Apple Event, if I ever were to support that. Plus, I can now add that to my 'generic' library that I share among all my applications. Anyway, I hope this blog post is of help to some fellow revDeveloper baffled by this problem.

Monday, June 23, 2008

New Items on my Bookshelf

One of the defining characteristics of Information Technology, is that it is constantly shifting, and that you need to spend a lot of time just to keep up with the topics that you focus on. Not to mention the pet projects that you hope you'll eventually get around to but have already bought some books on for that magical moment when have time to actually read them.

And maybe I should wait to buy these books until I have that copious free time needed to properly digest their contents, but hey, what better motivation to move things along than a growing stack of books that you convince yourself have to be read before the end of the summer? A little pressure never hurt anyone, right?

On with the show - what did I recently add to my collection?

The Definitive ANTLR Reference - if you've ever dreamt of building domain-specific languages, ANTLR is the tool to get if you're not already knee-deep in LEX and YACC. Now why on earth would you need that? Well, if you're building business applications, this sort of embedded scripting languages can make a world of difference when it comes to customizing the workflow of your application.
Granted, if your focus is exclusively on MacOS X, you're better off making your application OSA-scriptable, so that your users can interact with your application via AppleScript. Or go one step further, and embed Automator actions. But if you're not that lucky, and you need cross-platform scripting, ANTLR and the visual grammar development environment ANTLRWorks will make your life a heck of a lot easier - producing code that is actually readable, rather than the undecipherable state machine mess that you get from YACC.

And now that we're talking about MacOS X (ooh, there was a smooth transition to the next book) - I just got my copy of Cocoa Programming for MacOS X by Aaron Hillegass. The just-released third edition was updated for MacOS X Tiger and Leopard, including coverage of XCode 3, Objective-C 2, Core Data, the garbage collector and Core Animation.
While I also have a copy of the Wrox-book Beginning MacOS X Programming, this will be the one that gets me going with Cocoa (that's my story and I'm sticking to it!) as the last Mac-specific development I did was using Think Pascal and the first 5 books of the original Inside Mac series, back in the day when Macs used Motorola 680x0 processors and we were happy to get System 7.

The last book I want to mention is The Art of SQL. Now I may live and breathe databases but you can never learn enough tricks of the trade. In this book, the author aims to teach people who are no longer novices how to write good SQL code from the start and most importantly, to have a view of SQL code that goes beyond individual SQL statements.
Remember the days when developers managed to fit entire accounting applications, including the data, onto a set of floppy disks or (gasp, we will never fill that up) 10 megabyte hard disks, running in 128 kilobyte RAM or less? With the way database sizes are exploding nowadays, you need to plan ahead and employ a different strategy - so I'm definitely looking forward to getting more in-depth than ever.

And just in case you're wondering: no, I don't always cuddle up on the sofa with a mug of hot cocoa and this type of book. Whenever I get a chance, I'll read books by Raymond E. Feist, Tad Williams, David Eddings, Margaret Weis and Tracy Hickmann. Hmm, another stereotypical geek trait: fantasy and science fiction. Ah well, when the shoe fits :-)