Programming Using Tcl/Tk Seree Chinodom [email protected] .

44
Programming Using Tcl/Tk Seree Chinodom [email protected] http://lecture.compsci.buu.ac.th/ TclTk

Transcript of Programming Using Tcl/Tk Seree Chinodom [email protected] .

Page 1: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Programming Using Tcl/Tk

Seree Chinodom

[email protected]

http://lecture.compsci.buu.ac.th/TclTk

Page 2: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

“Programming productivity may be increased as much as five times when a suitable high-level language is used.”

F.P.Brooks, “The Mythical Man-Month”

“ [representation] is important, because how information is represented can greatly affect how easy it is do do different things with it.”

David Marr, “Vision”

Page 3: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Your Instructor

SMTS in Scientific Computing at Sandia National Labs Writing Tcl code since Fall 1994 Ph.D. in Chemistry, MIT 1992 Using Tcl/Tk for systems integration, automated test, d

istributed computing Wrote XCELL Design Environment

- Frie dm an Hill, E.J. and J.M. O’Connor, The XCELL Inte g rate d Product Re aliza tion Environm e nt: A Toolbox for Ag ile Cons truction of Cus tom Param e tri

c De s ig n Software , Proce e ding s of the 1 9 9 6 Ag ility Forum National Meeting, Boston, MA.

Page 4: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

What you’ll need A computer with WWW & FTP access

– (UNIX preferred; Win95, Win3.1 PC or Mac OK)

– Netscape Navigator (if available) for ‘Tclets’ A Tcl/Tk installation

– http://www.sunlabs.com/research/tcl/install.html Binaries and source

– Textbook– Ousterhout’s Tcl and the Tk Toolkit

(Addison-Wesley, ISBN 0-201-63337-X)

Other reading material

– Up-to-date man pages; Tk4.0 Porting document

Page 5: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Other References Exploring Expect, Don Libes (O'Reilly, ISBN 1-5659

2-090-2)– Recommended reading.

Practical Programming in Tcl and Tk, Brent Welch (Prentice Hall, ISBN 0-13-182007-9)– Lots of examples. Comes with a source disk.

http://www.sunlabs.com/research/tcl/

– Tcl/Tk home page. Source, docs, info. http://www.sunlabs.com/research/tcl/plugin/

– Home page for the new Navigator plug-in

Page 6: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Who you are

Write on a piece of paper:

– Your name

– What you do

– What you want to do with Tcl/Tk

– What other computer languages you know

– Anything you’d especially like to see covered

Page 7: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

What I’ll do Today: give an overview of the Tcl language Next four weeks:

– Using the Tcl language

– GUI development with Tk

– Important Tcl extensions like expect

– Integrating Tcl/Tk with C and C++ applications

– Writing ‘Tclets’ for the WWW Put course notes on the Web:

– http://herzberg.ca.sandia.gov/TclCourse/

– PowerPoint format only (sorry)

Page 8: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

What you’ll do Complete several small problem sets

– Coding problems and questions Complete a term programming project

– You should choose a small application that fills a real need or solves a real problem

– Examples: GUI for a command-line utility; task automation; a game or puzzle

– Briefly present your project at the last meeting Ask questions

– Participation in class or via email is expected

Page 9: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Grading System

Grade:

– 40% Homework

– 40% Project

– 20% Participation Scores: (None), OK, Good, Excellent Grading on a Curve. Mode is B+.

Page 10: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Overview of Tcl/Tk Component technologies:

– Tcl: embeddable scripting language– Tk: GUI toolkit and widgets based on Tcl.

The principle: universal scripting language controls everything: functions, interfaces, communication.

Results:– Raise the level of GUI programming: simpler, 5-10x fa

ster application development than X, raw Win32– Greater power: programmable applications work toget

her; cross-platform delivery– Active objects: replace data with scripts.

Page 11: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Outline

Tcl scripting language.

Tk toolkit.

Tk applications.

Survey of applications and extensions.

Conclusions.

Page 12: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Tcl: Tool Command Language

Interactive programs need command languages:

– Typically redone for each application.

– Result: weak, quirky.

– emacs and csh powerful, but can't reuse.

Solution: reusable scripting language.

– Interpreter is a C library.

– Provides basic features: variables, procedures, etc.

– Applications extend with additional features.

Page 13: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Scripting Language Philosophy

Large, complex applications:

– Performance important.

– Need structure.

– Goal: prevent bad things.

Interactive commands, scripting:

– Performance less important.

– Minimum structure: less overhead, easy interchange.

– Goal: enable good things.

Program size, complexity, reuse 1

One language can't meet all needs?

Page 14: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Two-Language Approach

Use Tcl for scripting, C or C++ for large things. Goals for Tcl:

– Minimal syntax: easy to learn and type.

– Minimal structure: make things play together.

– Simple interfaces to C: extensibility.

Program size, complexity, reuse 1

C Tcl

Page 15: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Tcl: Tool Command Language

Simple syntax (similar to sh, C, Lisp): set a 47 47

Substitutions: set b $a 47

set b [expr $a+10] 57

Quoting: set b "a is $a" a is 47 set b {[expr $a+10]} [expr $a+10]

Page 16: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

More On The Tcl Language

Rich set of built-in commands:– Variables, associative arrays, lists.– C-like expressions.– Conditionals, looping:

3if "$x < " { ii iii iiiiii" "}

– Procedures.– Access to files, subprocesses, network sockets

Page 17: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

More On The Tcl Language

Only data representation is zero-terminated strings:– Easy access from C.– Programs and data interchangeable.

set cmd1 "exec notepad"...

eval $cmd1 (notepad.exe launches under Windows)

– Unfortunately, no 8-bit data

Page 18: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Factorial Procedure

Defining and using procedures is easy!

proc fac x {

if $x<=1 {return 1}

-expr $x*[fac [expr $x 1]]

}

i 4 24

Page 19: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Embedding Tcl In Applications

Application generates scripts.

Tcl parses scripts, passes words to command procedures.

Application extends built-in command set:– Define new object types in C.

– Implement primitive operations as new Tcl commands.

– Build complex features with Tcl scripts.

Parser

Init

CommandLoop

Application Commands

Built-In Commands

Tcl Application

Note that the command loop can also be in the Tcl/Tk box.

Page 20: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Extensions

Extensions can be developed independently:– Network communication, database access, security, ...

Applications can include combinations of extensions.

Parser

Init

CommandLoop

Application Commands

Built-In Commands

Tcl Application

Extension Commands

Extension

Page 21: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

The Tk Toolkit

The problem:

– Too hard to build applications with nice user interfaces.

– Even harder to do so cross-platform The wrong solution:

– C++, object-oriented toolkits, Java’s AWT

– Only small improvement (10-20%?): must stillprogram at a low level.

The right solution:

– Raise the level of programming.

– Create interfaces by writing Tcl scripts.

Page 22: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Creating User Interfaces With Tk

Additional Tcl commands:

– Create Motif-like widgets (on all platforms)

– Arrange widgets.

– Bind events to Tcl commands.

– Manipulate selection, focus, window manager, etc.

Library of C procedures:

– Create new widget classes.

– Create new geometry managers.

Page 23: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

The Tcl interpreter.

The Tk toolkit.

Optionally, application-specific C code (primitives):

– New commands.

– New widgets.

Tcl scripts (compose primitives into actions):

– Build user interface.

– Respond to events.

What's A Tk-Based Application?

Tcl commands

Page 24: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Wish: Windowing Shell

Create user interfaces by writing Tcl scripts. Hello, world:

- - button .hello text "Hello, world" command exit

pack .hello

Simple directory browser: 30 lines Web browser: 2000 lines 10x less code for simple things.

Page 25: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Browser Wish Script

# 40!/usr/local/bin/wish .

- iiii i." ." - - 20 20w idth height iiiii -iiii iiii. iiiiiii -iiiiiii i. ".list yview"

- - pack .scroll side right fill y wm title . "File Browser"

0if {$argc > } { 0set dir [lindex $argv ] i} {

iii i.}

[ [ * .*]] {foreach i lsort glob iiiiii iii ii.}

-- i.<1 >{ iiiiiiiiii iiii[]}

- bind all <Control c> {destroy .}

proc browse {dir file} { { ! = " . " } { iiii iiiiiiiiii/ } if {file isdirectory $file] { exec browse $file & i} { iiiiii i[] { exec emacs $file & } { iiiiii iiiiii" " } }}

Page 26: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Other Uses For Tcl Data representation:

– Store data on disk as Tcl scripts.– To load information, evaluate script– Good for app configuration

Active objects:– Store scripts in objects.– Evaluate scripts to give objects behavior.

Communication: send Tcl scripts between applications. Executable content:

– Active e-mail messages (Safe-Tcl)– Web pages (Tclets)

Page 27: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Status

Runs on all UNIX/X platforms.

Runs on Win32/Win16/Mac as of version 7.4/4.1.

Source and documentation freely available.

New Netscape Plug-In may increase audience.

100,000 developers world-wide?

Hundreds of commercial products, free extensions.

Newsgroup: comp.lang.tcl.

2 introductory books (Ousterhout, Welch).

Page 28: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Representative Applications Multimedia, groupware. Active e-mail messages. System administration. Testing. Scientific applications: instrument control, simulation,

visualization, CAD. Real-time control system for offshore platform. British teletext system. Feature animation at Walt Disney Studios. On-air broadcast control system for NBC.

Page 29: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Popular Extensions

Expect: remote control for interactive UNIX programs such as iii, telnet, iiiii, and fsck:

#!//// spawn rlogin [lindex $argv 0]

- #expect re "($| |%) " send "cd [pwd]\r"

- #expect re "($| |%) " send "setenv DISPLAY $env(DISPLAY)\r"

interact

Expect is available via anonymous FTP

– ftp://ftp.cme.nist.gov/pub/expect/

Page 30: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Popular Extensions, cont'd Archives via anonymous FTP:

ftp://ftp.neosoft.com/pub/tcl TclX: general-purpose extensions:

– POSIX system calls.

– Keyed lists.

– File scanning (similar to awk).

– Date/time manipulation.

– Debugging, help, profiling.

Oratcl and Sybtcl: access to commercial databases.

Incr tcl: object-oriented programming in Tcl.

Page 31: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Popular Extensions, cont'd Tcl-DP: socket-based remote procedure calls, distributed objects

– Sample ‘unique ID’ server: 0set myId

i{}{ iiiiii iiii iiii iiii return $myId}

dp_MakeRPCServer 4545

– Sample client: set server [dp_MakeRPCClient foo.bar.com 4545]

dp_rpc $server GetId

Not yet updated for Tcl 7.4/4.1 socket command

Page 32: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Where You Might Use Tcl and Tk

Creating graphical user interfaces. Testing. Applications that need scripting or extension facilities. Platform-independent applications. Creating interactive content for the WWW.

Page 33: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Drawbacks

Must learn new language

– Substitution rules confusing to some people.

– Competitors: JavaScript, Visual Basic…

Interpreted language has performance limits– Surprisingly high; not much worse than Java

C interfaces incompatible with Xt, Motif library.

– Motif look-and-feel on PC, Mac for now.

Page 34: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

What’s up at Sun Labs?

Create exciting Internet applications:

– Netscape Plug-In available now! Increase accessibility:

– More work on PC/Mac ports (native look and feel).

– SpecTcl: interactive GUI builder (available now)

– Better development tools (debugger, etc.) Improving the language/toolkit:

– Incremental on-the-fly compiler (some progress)

– Better support for modules, data structures. Dynamically loadable extensions now possible

Page 35: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Summing up...

High-level programming:

– Less to learn.

– Build applications more quickly. Universal scripting language:

– Extend and modify applications at run-time.

– Make many things work together. Use scripts instead of data:

– Active objects, executable content.

Tcl + Tk = shell of the 1990's?

Page 36: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Tcl Language Programming

There are two parts to learning Tcl:

1. Syntax and substitution rules:

– Substitutions simple, but may be confusing at first.

2. Built-in commands:

– Can learn individually as needed.

– Control structures are commands, not language syntax.

TCL HAS NO FIXED GRAMMAR!

Page 37: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Basics

Tcl script =– Sequence of commands.– Commands separated by newlines, semi-colons.

Tcl command =– One or more words separated by white space.– First word is command name, others are arguments.– Returns string result.

Examples:

22set a set the variable ‘a’ to 22

", !" world’s shortest program

Page 38: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Division Of Responsibility

Tcl Parser

Command Procedure

Command

Words

Result

Interprets words. Can invoke parser recursively. Produces string result.

Chops commands into words. Makes substitutions. Does not interpret values of words. Single pass operation!

Page 39: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Arguments Parser assigns no meaning to arguments (quoting by default,

evaluation is special):C: 4 10x = ; y = x+

y is 14Tcl: 4 10set x ; set y x+

y is "x+10" Different commands assign different meanings to their argu

ments. “Type-checking” must be done by commands themselves.

122set a 2432expr / .

"122" ii -iiii iiiii -ii iii.iiiiii iiiiii iiiiiiiiiii

Page 40: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Variable Substitution

Syntax: $varName Variable name is letters, digits, underscores.

– This is a little white lie, actually. May occur anywhere in a word.

Sample command Result

66set b 66

iii i i i set a $b 66

set a $b+$b+$b 666666

set a $b.3 663

set a $b4 no such variable

Page 41: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Command Substitution

Syntax: [script]

Evaluate script, substitute result.

May occur anywhere within a word.

Sample command Result

set b 8 8

set a [expr $b+2] 10 - -set a "b 3 is [expr $b 3]"

- 3 5b is

Page 42: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Controlling Word Structure

Words break at white space and semi-colons, except:

– Double-quotes prevent breaks: set a "x is $x; y is $y"

– Curly braces prevent breaks and substitutions: set a {[expr $b*$c]}

– Backslashes quote special characters: set a word\ with\ \$\ and\ space

– Backslashes can escape newline (continuation)

Substitutions don't change word structure: set a "two words" set b $a

Page 43: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

Notes on Substitution and Parsing

Tcl substitution rules are simple and absolute

– Example: comments - 22 33set a ; set b < OK

- # this is a comment < OK - 22#set a same thing? < Wrong! - 22#set a ; same thing < OK

Parser looks at a command just once! It’s OK to experiment

– Expressions exist that can’t be written in one command

– Sometimes things get hairy “{[“cmd”]}”

Page 44: Programming Using Tcl/Tk Seree Chinodom seree@buu.ac.th .

For Next Week...

Get your Tcl/Tk environment set up Try the demos, especially Tk’s ‘widget’ Type in ‘Hello, World’ and get it to work Read Chapters 1 through 5 of Ousterhout