• MacTech Network:
  • Tech Support
  • |
  • MacForge.net
  • |
  • Apple News
  • |
  • Register Domains
  • |
  • SSL Certificates
  • |
  • iPod Deals
  • |
  • Mac Deals
  • |
  • Mac Book Shelf

MAC TECH

  • Home
  • Magazine
    • About MacTech in Print
    • Issue Table of Contents
    • Subscribe
    • Risk Free Sample
    • Back Issues
    • MacTech DVD
  • Archives
    • MacTech Print Archives
    • MacMod
    • MacTutor
    • FrameWorks
    • develop
  • Forums
  • News
    • MacTech News
    • MacTech Blog
    • MacTech Reviews and KoolTools
    • Whitepapers, Screencasts, Videos and Books
    • News Scanner
    • Rumors Scanner
    • Documentation Scanner
    • Submit News or PR
    • MacTech News List
  • Store
  • Apple Expo
    • by Category
    • by Company
    • by Product
  • Job Board
  • Editorial
    • Submit News or PR
    • Writer's Kit
    • Editorial Staff
    • Editorial Calendar
  • Advertising
    • Benefits of MacTech
    • Mechanicals and Submission
    • Dates and Deadlines
    • Submit Apple Expo Entry
  • User
    • Register for Ongoing Raffles
    • Register new user
    • Edit User Settings
    • Logout
  • Contact
    • Customer Service
    • Webmaster Feedback
    • Submit News or PR
    • Suggest an article
  • Connect Tools
    • MacTech Live Podcast
    • RSS Feeds
    • Twitter

ADVERTISEMENT

Volume Number: 14 (1998)
Issue Number: 2
Column Tag: Alternate Environments

An FTP Fetch Client in Tcl/Tk

by Bruce O'Neel, Laurel MD

A light introduction to this powerful, multi-platform scripting language

Overview

Tcl/Tk (pronounced "tickle tee-kay") is a scripting language written by Dr. John Ousterhout while he was a professor at the University of California at Berkeley. Tcl can either be a standalone shell where you issue commands (like those of unix or the MPW shell), or it can be a library which you embed into your compiled program and use to issue commands. Tk is an extension to Tcl which provides graphical interface Tcl commands enabling you to write event driven programs with graphical interfaces.

Tcl/Tk has been very popular in the unix world for a long time and has recently been ported to Mac OS and Win95/NT. As of version 8.0 of Tcl/Tk, the Mac OS and Win95/NT ports have a native look and feel on their respective platforms. This article is going to provide a brief overview of Tcl/Tk and then present a demonstration Tcl/Tk program to fetch files using FTP.

Tcl/Tk Overview

Why is Tcl/Tk interesting? First, it is a dynamic scripting language. At run-time your scripts are byte compiled and run. You can get the names of procedures and variables at run-time; you can define new commands and new control statements at run-time; you can load new source code at run-time; and you can extend Tcl with your own shared libraries at run-time. Second, you can produce Mac like interfaces using the native port of Tk and you can do this quickly and interactively. Think of it as rapid prototyping for the Mac in a free language. Third, you can write scripts which can be moved unchanged from Mac OS to Win95/NT and most unix variants. Finally, you can easily write extensions to Tcl in any compiled language on the Mac, and they can either call and be called by C or produce shared libraries. These extensions also can be cross-platform if written to be portable. As an example, a group of people at NASA's Goddard Space Flight Center have written an extension to Tcl which reads and writes a file format called FITS used in astronomy ftp://legacy.gsfc.nasa.gov/software/ftools/release/other/fitstclmac-src.sit.hqx.

There are a few notes on Tcl's syntax that will make reading the code easier. First, remember that Tcl works by string substitution and that, from your point of view, everything is a string. $varname means look up the value that is currently assigned to a variable and put that string in place of $varname. [command arg arg] means execute what ever is between the square brackets and substitute the value in place of [command arg arg]. Finally, curly braces are used around parts of code you want to execute later and defer evaluation until sometime in the future.

An FTP Client

I thought that a good demo of Tcl/Tk for the Mac would be an FTP client. Now, I didn't want to rewrite Fetch or Anarchie, but, I did want a useful example. The example program works but there are many features left for the reader to complete and the sample probably won't work unless you FTP to a unix system. One develops a lot of respect for Anarchie or Fetch when you try to repeat their author's work.

So, even though this is just a simple example, what made it good for Tcl/Tk? First, it was quick and easy to write. I took about 4-6 hours to write most of the code, with a little bit of time to clean things up for publication. Second, the resulting executable is small at around 27 Kbytes and the UI is very Mac like. Third the same source worked on more than one system. I was also able to run this on a unix system pretty much unchanged for additional testing and on the unix system it looked like I was running a Motif application. Finally I wanted a GUI and TCP/IP sockets in my program and Tcl/Tk has all of this easily built in, debugged, and well documented. Plus, you can experiment interactively with your code rather than compile, link, run, crash, debug,and edit as you must normally do.

There are two downsides to Mac Tcl/Tk applications. The first is that you have to install Tcl/Tk. The small application depends on some shared libraries, but, you could avoid the need to already have installed Tcl/Tk by using the non-shared version. The second downside is that the current version requires quite a bit of memory. The default is 4mb but you might have to bump this up if your programs crash. Many crashes are caused by running out of memory.

Displaying aWindow

The first thing the user sees when they start the program is a dialog produced by the new_connection proc, listed below. The dialog looks like

Figure 1. Open Connection Dialog.

Because Tcl/Tk is interactive, you could download it from http://sunscript.sun.com and type in each following command and watch what happens as you go. This is a very quick way to learn how Tcl/Tk works.

new_connection
This is the main dialog the user interacts with and an example of Tcl/Tk
programming. This asks the user for their hostname, username (optional),
password (optional), and directory to connect to. When they click the
connect button, it brings up a directory list of that directory.

# Procedure to open a new connection.
proc new_connection {} {
  
  # so we can access the global variable FTP
  global FTP

  # This sets the variable named t to the result of the 
  # toplevel command
  # toplevel, like all Tk Widget creation commands returns 
  # the name of the widget,
  # .new_connection in this case, as it's result.
  set t [toplevel .new_connection -menu .menubar]
  wm title $t "Open Connection"
  
  # create a text label
  label $t.title -text "Open a new FTP connection"
  # grid is a geometry manager. This puts the title on the 
  # screen.
  grid $t.title -columnspan 2

  label $t.hostl -text "Hostname:"
  # associate the variable FTP(hostname) with a text entry 
  # area on the screen.
  # note that there is not $ before FTP(hostname)
  entry $t.hoste -textvariable FTP(hostname)
  grid $t.hostl $t.hoste

  label $t.userl -text "Username:"
  entry $t.usere -textvariable FTP(username)
  grid $t.userl $t.usere
  
  label $t.passl -text "Password:"
  # -show * echos * rather than the user's keystrokes
  entry $t.passe -textvariable FTP(password) -show *
  grid $t.passl $t.passe
  
  label $t.dirl -text "Directory:"
  entry $t.dire -textvariable FTP(directory)
  
  # create a button which when it runs the command up_dir
  button $t.dirup -text "Up" -command "up_dir" 
  grid $t.dirl $t.dire $t.dirup
  
  # put up two radio buttons to set datamode. Tied together 
  # by the -variable option.
  radiobutton $t.binary -variable FTP(mode) -text Binary \
    -value Binary
  radiobutton $t.ascii -variable FTP(mode) -text Ascii \
    -value Ascii
  label $t.datamode -text "Data Mode: "
  grid $t.datamode $t.binary $t.ascii
  
  # frames hold things
  frame $t.direc
  label $t.direc.title -text "Remote Directory"
  # pack is another geometry manager and puts the title at 
  # the top of this frame
  pack $t.direc.title -side top
  # the following three commands set up a text box and two 
  # scroll bars
  set FTP(listbox) [listbox $t.direc.list \
    -xscrollcommand [list $t.direc.xscroll set] \
    -yscrollcommand [list $t.direc.yscroll set]]
  scrollbar $t.direc.xscroll -orient horizontal \
    -command [list $t.direc.list xview]
  scrollbar $t.direc.yscroll -orient vertical \
    -command [list $t.direc.list yview]
  # these pack commands put the listbox and the scrollbars on 
  # the screen
  pack $t.direc.xscroll -side bottom -fill x
  pack $t.direc.yscroll -side right -fill y
  pack $t.direc.list -side left -fill both -expand true
  
  # put the whole frame with the remote directory listing on 
  # the screen
  grid $t.direc -columnspan 2
  
  # attach the event of double mouse button 1 (on the Mac, 
  # double click) when within
  # the widget $t.direc.list to the event of running the 
  # command get_file_or_dir.
  # In other words, this sets up a routine such that when you 
  # double click 
  # in the list box your routine get_file_or_dir is called
  bind $t.direc.list <Double-1> {get_file_or_dir}

  button $t.connect -text Connect \
    -command "get_dir $t.direc.list"
  
  # destroy deletes a widget and all of it's children
  button $t.cancel -text Cancel -command "destroy $t"
  grid $t.connect $t.cancel
}

This code doesn't produce the nicest looking dialog, but, it's functional. It would be much prettier if I went through and added space around widgets and added colors. Note that the functions of the dialog are quite separate from the layout. This allows me to go through and change the design of the dialog without changing the supporting code.

Connecting to the Server

Once the user has filled out the connection dialog and clicked Connect it's time to get a directory listing. The bit of code which talks to the remote FTP server and gets directory looks like this:

ftp_get_dir
This bit of code reads the global FTP array variable and returns as its
result the directory listing from the remote system. It connects to
FTP(hostname) as user FTP(username), or anonymous if blank, using a
password of FTP(password), or user@host if blank. It then changes directory
to FTP(directory) and gets that directory and returns the result as a big
string.

# The guts of getting an FTP directory. Note that this is 
# the netscape connect, do 
# something, and quit. Really inefficient but much easier to 
# implement.
proc ftp_get_dir {} {
  global FTP
  set FTP(data_sock) 0

  update_status \
    "Getting directory from site $FTP(hostname)"

  update_status "Establishing FTP connection ..."
  
  # connect to the remote system
  set FTP(ftp_sock) [socket $FTP(hostname) ftp]
  fconfigure $FTP(ftp_sock) -blocking 0 -buffering none
  
  # call a routine ftp_read_line when the remote socket is 
  # readable
  fileevent $FTP(ftp_sock) readable ftp_read_line

  if {[ftp_read] > 3} {
    return
  }

  update_status "Logging in ..."

  # send the username and password
  if {[string compare $FTP(username) ""]} {
    puts $FTP(ftp_sock) "USER $FTP(username)"
  } else {
    puts $FTP(ftp_sock) "USER anonymous"
  }
  if {[ftp_read] > 3} {
    return
  }

  if {[string compare $FTP(password) ""]} {
    puts $FTP(ftp_sock) "PASS $FTP(password)"
  } else {
    puts $FTP(ftp_sock) "PASS user@hostname"
  }
  if {[ftp_read] > 3} {
    return
  }

  # change to the user selected directory or /
  if {[string compare $FTP(directory) ""]} {
    puts $FTP(ftp_sock) "CWD $FTP(directory)"
  } else {
    puts $FTP(ftp_sock) "CWD /"
  }
  if {[ftp_read] > 3} {
    return 
  }

  update_status "Setting up for transfer ..."

  # transfer directories in ascii mode
  puts $FTP(ftp_sock) "TYPE A"
  if {[ftp_read] > 3} {
    return
  }

  # get a server socket on our system so that the remote 
  # system can send
  # us the directory listing
  update_status "Opening server port ..."

  set serv_sock [socket -server notify_connect 0]

  update_status "Setting up to retrieve directory ..."
  
  set hostip [lindex [fconfigure $FTP(ftp_sock) -sockname] 0]
  set serv_port [lindex [fconfigure $serv_sock -sockname] 2]

  # expr is how we do math
  set serv_up [expr "int($serv_port/256)"]
  set serv_lw [expr "$serv_port-$serv_up*256"]
  regsub -all {\.} $hostip "," hostip

  # send the port command to the remote system
  puts $FTP(ftp_sock) "PORT $hostip,$serv_up,$serv_lw"
  if {[ftp_read] > 3} {
    close $serv_sock
    fileevent $FTP(ftp_sock) readable ""
    close $FTP(ftp_sock)
    return
  }

  # send the list command
  puts $FTP(ftp_sock) "LIST"

  if {[ftp_read] > 3} {
    close $serv_sock
    fileevent $FTP(ftp_sock) readable ""
    close $FTP(ftp_sock)  
    return
  }

  update_status "Retrieving dir ..."

  fconfigure $FTP(data_sock) -translation auto

  # keep reading on the server socket until end of file.
  while { ! [eof $FTP(data_sock)] } {
    set buf [read $FTP(data_sock) 1024]
    append result $buf
  }

  # clean up and exit
  update_status "Closing connection ..."

  puts $FTP(ftp_sock) "QUIT"
  fileevent $FTP(ftp_sock) readable ""
  close $FTP(ftp_sock)
  close $serv_sock
  close $FTP(data_sock)
  return $result
}

This bit of code talks to a remote system and implements enough of the FTP protocol to get a file listing. Basically it sends a USER command, followed by a PASS command to log in with a user name and a password. Then it sends a CWD command to change to the proper directory. Next it sends a PORT command, probably the only tricky bit. The FTP protocol uses two channels. The first is the command/result channel which is where we send commands such as USER and PASS and get responses. The second is the data channel which is where we transfer files. This is different from the http protocol where we would use the same channel for both transfers.

To request a file or directory listing from the remote system we set up a server port on the local system and tell the remote system what that port number is with the PORT command. The remote system opens a connection to that port and sends the remote file or directory listing over that connection. The PORT command has a slightly odd syntax of the form A,B,C,D,E,F where the local numeric IP address is A.B.C.D and E is the port address high byte and F is the port address low byte. Once we've gotten the port command sent, we send the LIST command. The remote system opens a socket to the port we gave it and sends the result. Once we see and end of file on our server socket we are done and can send the QUIT command. You can experiment with the FTP protocol by using a telnet client to connect to port 21 on most systems. You can also get ftp://nic.merit.edu/documents/rfc/rfc0959.txt and read all of the gory details.

Retrieving a file is just as easy as getting a listing. The routine ftp_get_file is almost identical to ftp_get_dir, but instead of using a LIST command to get a directory listing, we use a RETR command to get a remote file. Also, we write the file out to disk rather than returning it's contents as a string.

Adding a Menubar

Up to now all of the code has been generic Tcl/Tk. While it's nice to produce portable applications, we use Macs because we like them and we'd like our applications to look Mac-like. Tcl/Tk 8.0 has some nice features built in that we can use to make the application look more like a Mac. If we create a menu widget called say .menubar, and then add an entry to that called .menubar.apple, items on this menu will be in the Apple menu. So, we add a menubar as follows:

part of the main program 
This will add the Mac menus such that they work like Mac menus. We
create a menubar named .menubar and then add Apple and File entries
to it. The Apple entrys will appear under the Apple menu as you'd expect
and the File menu will be the first menu after the Apple menu. We'll add
an accelerator to the Quit menu option with Meta-Q which will be
translated to Command-Q on the Mac.

# make a menubar
menu .menubar -tearoff 0

# add the file menu
.menubar add cascade -menu .menubar.file -label "File"
menu .menubar.file -tearoff 0

# add the apple menu
.menubar add cascade -menu .menubar.apple  
menu .menubar.apple -tearoff 0
# add the about entry
.menubar.apple add command -label "About..." \
  -command aboutbox

# add entries to the file menu
.menubar.file add command -label "New Connection..." \
  -command new_connection
.menubar.file add separator
# this will be the normal mac quit keyboard acclerator
.menubar.file add command -label "Quit" \
  -command exit -accelerator "Meta-Q"

# make the menu the menu for the toplevel . window. Whenever
# the . window is the frontmost window then the menubar 
# .menubar will be the menu at the top of the screen.

. configure -menu .menubar

The only other Mac specific command is console hide at the end of the program. This prevents the Tcl console from appearing. The Tcl console is where you would type Tcl commands if you were using Tcl interactively.

The last thing to do to generate a standalone Mac executable is to drag your Tcl source file onto the program Drag & Drop Tclets and answer the questions. This little program will build a Tcl executable which can be double-clicked to run our Tcl script.

Conclusion

After reading this article you should have gained an appreciation for Tcl/Tk and some things you can do with it on the Mac. It's also possible to control other programs with the TclAppleScript extension, which ships with Tcl/Tk 8.0. This allows you to use Tcl to tie together multiple programs as you can with AppleScript. Now that Tcl/Tk has native look-and-feel, the Mac Tcl scripts look like Mac programs and Tcl/Tk gives you a quick way to write Mac programs.

Bibliography and References

  • Ousterhout, John K. Tcl and the Tk Toolkit, Addison-Wesley, 1994.
  • Welch, Brent B. Practical programming in Tcl & Tk, Prentice Hall, 1997.

For more information you should check the main site at http://sunscript.sun.com/ and an excellent overview paper on Tcl/Tk and scripting languages is from http://www.sunlabs.com/~ouster/scripting.html.


Bruce O'Neil beoneel@macconnect.com spends his work time working on astrophysics satellites and his spare time playing with his lovely wife and children. What time is left is devoted to his PowerBook.

 
MacTech Only Search:
Community Search:

 
 
 

 
 
 
 
 
  • SPREAD THE WORD:
  • Slashdot
  • Digg
  • Del.icio.us
  • Reddit
  • Newsvine
  • Generate a short URL for this page:



MacTech Magazine. www.mactech.com
Toll Free 877-MACTECH, Outside US/Canada: 805-494-9797
MacTech is a registered trademark of Xplain Corporation. Xplain, "The journal of Apple technology", Apple Expo, Explain It, MacDev, MacDev-1, THINK Reference, NetProfessional, Apple Expo, MacTech Central, MacTech Domains, MacNews, MacForge, and the MacTutorMan are trademarks or service marks of Xplain Corporation. Sprocket is a registered trademark of eSprocket Corporation. Other trademarks and copyrights appearing in this printing or software remain the property of their respective holders.
All contents are Copyright 1984-2010 by Xplain Corporation. All rights reserved. Theme designed by Icreon.
 
Nov. 20: Take Control of Syncing Data in Sow Leopard' released
Nov. 19: Cocktail 4.5 (Leopard Edition) released
Nov. 19: macProVideo offers new Cubase tutorials
Nov. 18: S Stardom anounces Safe Capsule, a companion piece for Apple's
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live
Nov. 17: Ableton releases Max for Live