Tag Archive 'AppleScript'

May 01 2008

Toggle Finder Hidden File Status

Published by under AppleScript

For some reason I prefer to have system files (hidden by default) shown in Finder (must be the Unix in my system from grad school). With that said, there are times when it would be nice to have these same files out of sight when working with a cluttered folder. After having thought many times about writing a short script to toggle hidden files on/off, I finally took a few minutes to crank out the code below:

Script Editor Click to paste code into the Script Editor

----------------------------------------
--  MacDeveloperTips.com
--  Toggle Finder hidden file status
----------------------------------------
try
  -- Get current value
  set toggle to do shell script "defaults read com.apple.finder AppleShowAllFiles"

  -- Toggle it
  if toggle = "ON" then
    do shell script "defaults write com.apple.finder AppleShowAllFiles OFF"
  else
    do shell script "defaults write com.apple.finder AppleShowAllFiles ON
  end if

  -- Restart Finder
  tell application "Finder" to quit
  delay 0.5 -- If you have problems, you can tweak the delay
  tell application "Finder" to launch
on error

  display dialog "Unable to toggle bit status." buttons {"Better luck next time"}
    with icon caution with title "Error"
end try

Notice the reference to delay – if you have problems with the scripting not running properly, you can experiment with a longer delay. There is minimal error handling, essentially just trapping errors and displaying the message below:

I prefer to save AppleScript code as an application, create an icon that serves as a reminder of what the script does, and drag/drop the application onto the Finder toolbar. You can see a screenshot below what my toolbar looks like (the icon for this script is the blue & white Finder image).

And speaking of icons, in an upcoming tip I’ll show you how easy it is to change an application icon on a Mac.

6 responses so far

Apr 29 2008

NetBeans, Java, AppleScript and iTunes – Part 2

Published by under Java

In part 1 of this series I demonstrated how to create a short Java application in NetBeans that communicated, using AppleScript, to the Mac apple event system. The application was a no thrills look into how to invoke the TextEdit application. Despite the brevity of the application it provided the foundation for this next tip, which will build on the ideas to create something a little more salient, as in, something that you might actually find yourself using.

The gist of the application is to instruct iTunes to play a random song, move to the next song, pause, etc. I’ll show one use of the application by wrapping the code into a bash script that allows you to invoke the program (and all commands) from within a terminal. Watch the video that follows for all the details…

This application is all of about 80 lines, including the bash script. Sometimes a little creative thinking and a few lines of code are all that’s needed to write an intriguing (and hopefully useful) application.


The music in the video is Led Zeppelin and the song: Moby Dick. Led Zeppelin at Amazon


No responses yet

Apr 24 2008

NetBeans, Java, AppleScript and iTunes – Part 1

Published by under Java

A few weeks back I demonstrated how to write Ruby code inside NetBeans to control scriptable applications on a Mac, that is, communicate between Ruby and the Apple Event system. In this post, I will turn things around a bit from the previous post and use NetBeans and Java to execute AppleScript.

There is a subtle difference, in the previous post the focus was on how to write code in Ruby (inside NetBeans) using the rb-appscript bridge. This time around the approach is to work with Java and pass AppleScript code to a set of Cocoa files (classes) that will act as the bridge between our application and the Mac system.

There is one caveat – the Cocoa-Java API is deprecated as of Mac OS X Tiger. The NSAppleScript and NSMutableDictionary classes are still available, however, they are no longer on the development path within Apple. There are scripting bridges that allow you to control scriptable applications using Python, Ruby, and Objective-C. Java Native Interface (JNI) is an additional option to call platform specific code. You can read more about JNI in this technical note: JNI development on Mac OS X.

One more note, if you follow the steps in this video and the classes NSAppleScript and NSMutableDictionary are shown with lines through them (for example, NSAppleScript), this has to do with a preference setting inside NetBeans to show deprecated classes with a strike-through. You can change this as follows: From the Preferences dialog, choose Fonts/Colors; click the Syntax option; from the Language list choose Java; click on Deprecated Element; in the Effects option, choose None.

Join me in Part 2 of this tip where I’ll show a more comprehensive (read: interesting) example where it’s all about controlling iTunes using Java.


The music in the video is Led Zeppelin and the song: Moby Dick.
Click the image to see more about about Led Zeppelin and the CD (at Amazon)


One response so far

Apr 14 2008

Finder and glob

Published by under AppleScript

I’ve found a really nice, well documented, AppleScript application that makes for easy work to use Unix path pattern expansion (glob) syntax along with Finder. This is the utility you want around when you need to select a specific set of files within Finder, and command-clicking just isn’t going to cut it.

For instance, when you need to select files with a unique patterns such as: files that contain the string “test” (anywhere within the filename), or only those files where the name contains “test” and the extension is “rb”.

The application I am referring to is lselect, and here are a few examples:

All files with “test” in the name and the extension “rb” will be selected:

Easy enough, however, lselect also allows you to add to the current list of selected files, as shown below where I ask for all files with a “C” extension (notice the button ‘Add Matches’):

The resulting list of files is shown below:

The source code for lselect is shown below (it looks rather long, however, much of the listing is comment blocks):

Script Editor Click here to paste the code below into the Script Editor

(*
  lselect 1.1 by Jim DeVona

http://anoved.net/lselect.html

  1.0: 1 November 2006
  1.1: 18 December 2006 (somewhat improved Column view behavior)

  Select files in the current Finder folder using shell glob syntax.
  When invoked, the user will be prompted to supply a glob pattern.
  The "ls" command line utility is used to determine which files match
  the pattern, and then they are selected.

  Suggested installation location:
    ~/Library/Scripts/Applications/Finder/lselect.scpt

  The script can be invoked with the standard Mac OS X Script Menu,
  but I've found FastScripts (http://www.red-sweater.com/fastscripts/)
  to be a preferable alternative, primarily because of the ease with
  which reliable keyboard bindings can be assigned. I use Command-G.

  Issues:
    - If the last match is a directory and the current view type is
      Column, other matches will not end up selected (they appear
      to lose selection when the Finder come to rest on and reveals the
      contents of the last directory). I don't know how to prevent this.
    - Spaces must be escaped to match properly: "iTunes\ Music"
    - Performance is poor with hundreds of matches; see notes below

  Wishes:
    - Select sub-matches within current selection
    - Select matches on desktop instead of in "Desktop" window
    - Support patterns like "../" (subfolder patterns work, but not parent)
*)

tell application "Finder"

  (*
    Determine the present working directory as alias and POSIX path.
    If the insertion location is not a folder, use its parent. This is the
    case when a file is selected in Column view (otherwise, file selections
    do not seem to be treated as the insertion location).
  *)
  set pwdAlias to insertion location as alias
  if not (exists folder pwdAlias) then
    set pwdAlias to (container of pwdAlias) as alias
  end if
  set pwd to POSIX path of pwdAlias

  (*
    Ask the user what to select. Dialog time out is equivalent to cancellation.
    The default "Select Matches" option clears the current Finder selection,
    whereas "Add Matches" leaves it intact. Clearing the selection is not done
    in Column view if the displayed folder is the only thing selected.
  *)
  set dr to display dialog "Glob pattern:" default answer ¬
    "" buttons {"Cancel", "Add Matches", "Select Matches"} ¬
    default button 3 cancel button 1 with title pwd giving up after 60
  if button returned of dr is equal to "" then
    return
  else if button returned of dr is equal to "Select Matches" then
    try
      -- do not clear selection if the only thing selected is the focal folder
      if selection as alias is not equal to pwdAlias then select {}
    on error
      -- more than one thing already selected
      select {}
    end try
  end if

  (*
    Initialize list of selected files. Generally identical to selection returned
    by Finder, except the present working directory should not be included,
    which is initially selected in some Column view circumstances (see above).
    This is a little clumsy; selection state is vaguely defined in Column view.
  *)
  set selectables to selection
  try
    if selection as alias is equal to pwdAlias then set selectables to {}
  end try

  (*
    Get the glob pattern given by the user.
    We treat a blank pattern as cancellation (use * to select everything).
    Alternatively, omit this conditional to select the containing folder;
    this ought to be the default behavior once "../" issues are ironed out.
  *)
  set query to text returned of dr
  if query = "" then return

  (*
    Ask ls for a listing of files that match the given pattern.
    From the ls man page:
      -d Directories are listed as plain files (not searched recursively).
    If nothing matches the query, ls will return an error; just stop.
  *)
  try
    tell me to set matches to do shell script ("/bin/ls -d " & quoted form of pwd & query)
  on error
    return
  end try

  (*
    Parse each line of the response from ls as the path to a match.
    The visibility test is twofold: the "info for" test throws an error on
    Icon^M (the full name doesn't survive all translations and transmissions).
    This try-info-for-visibilty test is the main bottleneck;
    for faster handling of many matches (100s), replace this
    repeat body with "set end of selectables to matchpath as POSIX file"
  *)
  repeat with matchpath in paragraphs of matches
    set posixmatch to matchpath as POSIX file
    try
      set fileinfo to info for posixmatch without size
      if visible of fileinfo then set end of selectables to posixmatch
    end try
  end repeat

  (*
    Conclude by selecting the results.
    The "try" protects against cases we don't [yet] handle,
    such as certain "../" path traversals and anything else that may come up.
    If the last item of selectables is a directory and we're using
    Column view, other items may not end up selected.
  *)
  try
    select every item of selectables
  on error errMsg number errNum
    display alert "Could not make selection (" & errNum & "):" message errMsg as critical
    return
  end try
end tell

Here is brief list of glob syntax you can try with lselect:

? Match any one character.
* Match any sequence of zero or more characters.
[abc] Match any one character in abc. A range of characters may be specified as a-z, or 0-9.
[^abc] Match any one character not in abc.
{a,b,c} Matches any of the strings a, b, or c, which may consist of more than one character each.

lselect shows a good use of AppleScript, is well documented and it’s handy…all good things.

2 responses so far

Apr 02 2008

NetBeans 6.1, Ruby and AppleScript

Published by under Tools/Utilities

What do NetBeans, Ruby and AppleScript have in common? There’s a circular definition of sorts to explain…to start, all are tools available to developers working on Mac. Next, NetBeans has full support for creating, debugging and packaging Ruby code. And finally, Ruby (with the right tools in place) can be used within NetBeans to control scriptable applications on a Mac, something which is typically accomplished using AppleScript.

In this post I’ll describe more about how all these tools come together to provide an interesting approach for using Ruby as an alternative to AppleScript, and working with NetBeans as the development environment for writing and building those same applications.

The screencast that follows will walk you through all the steps to download the tools you’ll need, build from source a scripting bridge (rb-appscript) for Ruby to AppleScript, and finally, create several short examples to demonstrate how you can use Ruby, from within NetBeans to control scriptable applications.

For more information, follow these links:

If you are interested to learn more about using Ruby as an alternative to AppleScript, I’ve written as series of posts you can find here: Part 1, Part 2, Part 3, Part 4, Part 5, Part 6

If you write an interesting application in NetBeans, using Ruby and rb-appscript, drop me a note, as I’d like to post several good examples showing the interaction of all these tools.

As an aside, NetBeans is sponsoring a blogging contest for the 6.1 Beta. If you are interested in learning more, visit the NetBeans Blogging Contest. And who knows, you could walk away with one of ten $500 American Express gift certificates!

No responses yet

Mar 14 2008

Ruby, an AppleScript Alternative – Part 4

Published by under Ruby

My intention in starting this series of posts on Ruby was to re-write two short AppleScript applications; one that turns down the volume at shutdown, and one that resets the volume upon bootup. We’ve covered enough information up to this point to have all we need to write the Ruby version (using rb-appscript).
Continue reading...

No responses yet

Mar 13 2008

Ruby, an AppleScript Alternative – Part 3

Published by under Ruby

So enough of the introductions (see Part 1 and Part 2), let’s get on with the code. To get started, let’s look at how to use scripting additions from within rb-appscript as the application that I have in mind will need to display a dialog box (which is located in Standard Additions). We can get a list of the additions currently available as well as a list of commands using the following Ruby code:
Continue reading...

No responses yet

Next »