Tag Archive 'finder'

May 01 2008

Toggle Finder Hidden File Status

Published by john 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.

Technorati Tags: , ,

3 responses so far

Apr 15 2008

Launch Applications from Terminal

Published by john under System

When working inside a terminal window, there’s a quick shortcut you can use to open a file (read, launch an application on a specific file or set of files). The beauty of this trick is that the command will work as if you clicked on an application icon(s) in Finder. For example, if you request to open a file with an extension of xml, the application associated with that extension will be started and the specified file will be passed to the application.

The command I am referring to is open; read on to see a few examples:

From a terminal window, to all the files with a “.rb” extension (in the current directory):

> open *.rb

To launch a browser at a specified URL, try this:

> open http://macDeveloperTips.com

And to open Finder in the current directory:

> open .

You can get more information about using the open command by viewing the manual page:

> man open

Technorati Tags: ,

No responses yet

Apr 14 2008

Finder and glob

Published by john 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.

Technorati Tags: , ,

No responses yet

Mar 28 2008

Copy Finder Path to Clipboard - Tip 2

Published by john under AppleScript, System, Tools/Utilities

Yesterday I wrote a short AppleScript application that copied the current path of the Finder window to the clipboard. A rather unassuming, yet handy application. One downside to this application is that if you want the path of a folder selected in Finder, you would have to double-click on the folder to change the Finder path to that folder location, and then you could engage the AppleSscript application to copy the path.

For example, in the figure below clicking the Script Editor icon that we created in yesterday’s post (to the right of the terminal window with green arrow) will copy the path /Applications/ to the clipboard. However, what if you intention was to copy the path of the highlighted folder, that is, /Applications/Utilities/Java/ ?

I’ve reworked the original example to add support for dragging a folder onto the icon and also moved the code for displaying a dialog box when an error occurs into a subroutine. Take a look at updated application below:

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

-- When clicking on the icon
try
  tell application "Finder"
    set currentPath to (POSIX path of (target of front window as alias))
    set the clipboard to currentPath
  end tell
on error
  my finderErrorMsg()
end try

-- When dropping a folder onto the icon
on open {droppedFolder}
  try
    tell application "Finder"
      set the currentPath to (POSIX path of droppedFolder as text)
      set the clipboard to currentPath
    end tell
  on error
    my finderErrorMsg
  end try
end open

-- Error msg when unable to copy a path to the clipboard
on finderErrorMsg()
  display dialog "Unable to copy a path to the clipboard.
                      Make sure Finder is referencing a directory/folder
                      within the file system."
                      buttons {"Ok"} with icon caution with title "Error"
end finderErrorMsg

With the addition of the on open reference (line 12) you can now drag/drop a folder in Finder onto the application icon and its path will be copied to the clipboard. Before you can use the script, you will need to save the AppleScript code as an application and drag the script onto the toolbar (remove any previous version of the program by right clicking and selecting ‘Remove Item’).

As a quick debugging tip, you can add a dialog box as shown below to display the path that was copied into the clipboard:

tell application "Finder"
  set currentPath to (POSIX path of (target of front window as text))
  set the clipboard to currentPath
  display dialog currentPath buttons {"ok"}
end tell
...

Now you can view the clipboard contents (through the dialog box) which makes the debugging process a little easier should you decide to tweak this application.

Another good example of the power of scripting on a Mac.

Technorati Tags: ,

No responses yet

Mar 27 2008

Copy Finder Path to Clipboard - Tip 1

Published by john under AppleScript, System, Tools/Utilities

I’ve written a short script that I’ve found more useful that I ever anticipated. It is nothing more than an AppleScript application that copies the current path of Finder to the clipboard. Sounds rather unassuming, however, I think you’ll be surprised how handy it is.

The AppleScript code is less than 10 lines that instruct Finder to get the path of the front most Finder window and copy the path to the clipboard.

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

try
  tell application "Finder"
    set currentPath to (POSIX path of (target of front window as alias))
    set the clipboard to currentPath
  end tell
on error
  display dialog "Unable to copy a path to the clipboard.
                      Make sure Finder is referencing a directory/folder
                      within the file system."
                      buttons {"Ok"} with icon caution with title "Error"
end try

From within Script Editor, save the code as an application and then drag/drop the application to the toolbar in Finder. The screenshot below shows the Script Editor icon in Finder (to the right of the terminal window with the green arrow), where it is now one click away.

There is a trivial amount of error handling in this short script. If you try and run this script while Finder is referencing the system (as compared to a directory/folder on the system) you’ll get the following error message.

In the next tip of this series we’ll drill down one level further and I’ll show how to copy the path of a selected folder within the current Finder window, to the clipboard.

Technorati Tags: ,

2 responses so far

Mar 25 2008

Open Terminal Here…

Published by john under System, Tools/Utilities

I can’t count how many times I’ve found myself in Finder and wanted to jump to a terminal at the current path location. The Open Terminal application is one of those little gems that will make you wonder how you ever got along without it. If you spend any time at all moving between Finder and a terminal, read on…

Installing the application is as simple as extracting the zip file and dragging the OpenTerminal.app file into a location where you store other scripts, tools, utilities, etc. I have a folder within my home directory where I dump all this kind of stuff, so down the road when I bump into this folder I’ll have a clue where the applications came from.

With the app installed, open Finder and drag the application to the toolbar. You’ll see the icon appear as shown here:

The first time you run this application you will be presented will an impressive list of options. The defaults work fine, however, take a few minutes to read through each option. Depending on how you work, chances are you can configure this app to keep pace with you.

Clicking on the Shell config option (on the top left) will present even more configurations choices:

If you are not using the default shell on Mac OS X (bash) I recommend choosing the ‘pushd’ option as this is another really handy tool to have when bouncing around the file system (pushd/popd are built-in commands on bash).

From here forward, whenever you are in Finder and want to jump to a terminal, simply click on the Open Terminal icon, and you’ll be whisked off to a terminal window. Slick.

The latest version will only work on Leopard, however, you can download an older version for Tiger as well. The only downside to this application is that the source code is not included. I’ll keep my eyes peeled for a similar version that includes the source. If you find one first, please post a comment.

Now if only the terminal was available through a right-click in Finder…

Technorati Tags: ,

3 responses so far