2012-12-21

Tcl/Tk 8.6.0 RELEASED

Tcl/Tk 8.6.0 RELEASED

相關連結:
Changes in Tcl/Tk 8.6
Highlights of Tcl 8.6
Highlights of Tk 8.6


在各個 package 進入 stable 以後,Tcl/Tk 8.6.0 橫空出世,進入了版本為 8.6 的時代。下面是 8.6.0 release 的內容:

Tcl/Tk 8.6.0 Release Announcement
December 20, 2012

The Tcl Core Team is pleased to announce the 8.6.0 releases of the Tcl
dynamic language and the Tk toolkit.  This is the first stable release
of Tcl/Tk 8.6.  More details can be found below.  We would like to
express our gratitude to all those who submit bug reports and patches.
This information is invaluable in enabling us to identify and eliminate
problems in the core.

Where to get the new releases:
------------------------------

Tcl/Tk 8.6.0 sources are freely available as open source from the Tcl
Developer Xchange web site at:

         http://www.tcl.tk/software/tcltk/8.6.html

This web page also contains additional information about the releases,
including a summary of new features.  Sources are always available from
the Tcl SourceForge project's file distribution area:

        http://sourceforge.net/projects/tcl/files/Tcl/

For additional information:
---------------------------

Please visit the Tcl Developer Xchange web site:

         http://www.tcl.tk/

This site contains a variety of information about Tcl/Tk in general, the
core Tcl and Tk distributions, Tcl development tools, and much more.

Summary of Changes since Tcl/Tk 8.6b3:
------------------------------

--------

A complete list can be found in the changes file at the root of the
source tree.  The more complete ChangeLog is also included with each
source release.

The short list of key changes since the Tcl/Tk 8.6b3 release follows.
For those who have not been following alpha and beta development,
read on to the next sections for pointers to information on the changes
since Tcl/Tk 8.5.  All bug fixes in Tcl/Tk 8.5.13 are included, plus:

     * [TIP 405] New commands [lmap] and [dict map].

     * [TIP 416] New [load] options -global and -lazy.

     * [TIP 413] Default [string trim*] trimset changed to Unicode.
        *** POTENTIAL INCOMPATIBILITY ***

     * [TIP 400] New [zlib] options to set gzip compression dictionary.

     * Bytecode compiled: [array exists|set|unset] [format] [yield]
       [dict create|exists|merge|unset] [string first|last|map|range]
       [namespace current|code|qualifiers|tail|which] [tailcall]
       [info commands|coroutine|level|object] [regsub] [self].

     * Fixed crashes when some attempts to write to a variable in
       a namespace that does not exist fail.

     * Fixed paths returned from [tk_getOpenFile -multiple] on Windows.

     * Corrected decoding of base64 with trailing whitespace.

     * Updated packages:
        - dde 1.4.0 : Full Unicode support.
        - http 2.8.5 : keep-alive multiple callback bug fix.
        - tcltest 2.3.5 : legacy $argv support bug fix.
        - TclOO 1.0 : Stable interface built into Tcl.
        - Itcl 4.0.0 : Stable release.
        - tdbc + driver packages, 1.0.0 : Stable releases.
        - Thread 2.7.0 : Stable release.
        - Sqlite 3.7.15 : New release.

      * Threads inherit floating point setting from master on Windows.

      * [text] handle images and windows with names looking like indices.

      * Compile-time control over where [file tempfile] creates files.

      * Legacy Carbon sources removed.  For support, get Tk 8.5.12.

Summary of new features since Tcl/Tk 8.5:
-----------------------------------------

Development of Tcl/Tk 8.6 began in March 2008, shortly after the release
of Tcl/Tk 8.5.2.  The number of new features, bug fixes, and changes
since then is quite large.  New features in Tcl are recorded as Tcl
Improvement Proposals (TIPs) at:

         http://tip.tcl.tk/

Highlights of the new Tcl features include:

Object Oriented Programming

The commands of the TclOO package are now part of Tcl itself. This gives
Tcl a built-in object system that is fully dynamic, class-based, and
includes advanced features such as meta-classes, filters, and mixins.

New version 4 of the popular package Itcl (aka [incr Tcl]) is also
included, now built on a TclOO foundation, granting support for some
traditional OO Tcl programming out of the box as well.

Stackless Evaluation

The evaluation of many levels of nested proc calls are no longer
implemented as a stack of nested C routine calls. This revision in the
internal implementation of Tcl evaluation makes deep recursion in Tcl
scripts safe to do. But there's more...

This new implementation enables a collection of new commands,
[coroutine], [tailcall], [yield], and [yieldto] that provide profound
new capabilities and models of concurrency to Tcl scripts.

Enhanced Exceptions

New commands [try] and [throw] and a wealth of new -errorcode values
enable far more precise trapping and handling of exceptions using a
familiar construct.

Batteries Included

Tcl delivers in the pkgs subdirectory a bundled collection of
third-party packages built and installed along with Tcl.

Thread-enabled Operations

A thread-enabled default build, a bundled Thread package, and new
command [interp cancel] make Tcl 8.6 ready for your multi-threaded
programming tasks.

SQL Database Powered

The bundled Tcl DataBase Connectivity (tdbc) interface package makes it
possible to write your SQL database-powered scripts decoupled from any
particular database engine. The bundled sqlite3 and tdbc::sqlite3
packages supply a powerful and popular SQL database engine ready to use.

IPv6 Networking

Both client and server [socket]s support IPv6 where platform support
exists.

Built-in Zlib Compression

New command [zlib] provides utilities to handle compression of data and
streams.

List Processing

New commands [lmap] and [dict map] enable the elegant expression of
transformations over Tcl containers.

Stacked Channels by Script

New commands [chan push] and [chan pop] expose the power of stacked
channels without the need to write C code.

Additional New Features

Temporary file creation, enhancements to list sorting and setting, dict
filtering, half-close of bidirectional channels, encoding and decoding
of binary sequences, finer control over load, and many many more.

Highlights of the new Tk features include:

Built-in PNG Image Support

Photo images now support read/write in the PNG format, with the ability
to set the alpha channel.

Busy Windows

New command [tk busy] is a variant of [blt::busy] that lets the
interactivity of windows be suspended and restored as required by the
needs of the program.

New Font Selection Dialog Interface

New command [tk fontchooser] provides a portable interface to the
standard font selector of the platform, whether that is modal or not.

Angled Text

New option "-angle $degrees" to [$canvas create text] for rotating
displayed text.

Moving Things on a Canvas

New commands [$canvas moveto], [$canvas imove] and [$canvas rchars]
for moving and manipulating canvas items.

Additional New Features

Text widget cursor control, more window manager hints, and a collection
of modernizations in appearance and function.

The complete summary of new features visible to Tcl scripts in the
Tcl/Tk 8.6 releases is:

         http://wiki.tcl.tk/Changes+in+Tcl%2fTk+8.6

Each item includes links to the TIP(s) that approved the change.

There have also been changes to the C API for the Tcl and Tk libraries
that are not visible to Tcl scripts, but are important to those who
create extensions and applications that use Tcl/Tk.  The relevant TIPs
are:

   TIP #265: A Convenient C-side Command Option Parser for Tcl
   TIP #307: Make TclTransferResult() Public
   TIP #316: Portable Access Functions for Stat Buffers
   TIP #322: Publish the NRE API
   TIP #330: Eliminate interp->result from the Public Headers
   TIP #335: An API for Detecting Active Interpreters
   TIP #336: Supported Access To interp->errorline
   TIP #337: Make TclBackgroundException() Public
   TIP #338: Embedder Access to Startup Scripts of *_Main()
   TIP #353: NR-enabled Expressions for Extensions
   TIP #356: NR-enabled Substitutions for Extensions
   TIP #357: Export TclLoadFile

These lists of feature changes are starting points for exploring the
new capabilities of Tcl/Tk 8.6.0.  As more developers become familiar
with the new tools, expect more guides to effective use of the new
features to appear online.

Building and installing Tcl will also build and install a set of
packages bundled with it in source code distribution form under the
pkgs subdirectory.  These packages are Itcl, Thread, sqlite3, tdbc,
and several tdbc driver packages.

Compatibility issues:
--------------------
The Tcl/Tk 8.6.0 releases are highly compatible with prior releases
of Tcl/Tk since 8.1.  There are a handful of changes that may cause
programs and scripts written for prior releases to behave differently
with Tcl/Tk 8.6.0.  Here we summarize the known things to watch out for.

Build and platform support issues:

  * Default build configuration for Tcl is now --enable-threads.  Use
    the configure option --disable-threads if your use of Tcl is
    incompatible with a thread-enabled build.

  * The --enable-aqua build for Tk on Mac OS X is a Cocoa implementation.
    Tk 8.6 no longer supports Carbon, even as a compile-time option.
    This implies dropping support for pre-Leopard (10.5) releases of
    Mac OS X.  See Tk 8.5.12 for last Carbon-supporting release.

  * Attempts to run on Win9x systems will panic.

  * Support for pre-ANSI compilers via _ANSI_ARGS_ removed.

  * The included support for Xcode builds on Mac OS X requires at least
    Tiger (10.4).

Script-visible issues:

  * As a general comment, any scripts that rely on the precise text of
    an error message or error code (a common issue in test suites) may
    need revision.  Tcl/Tk 8.6 includes many revisions to the text of
    many error messages for the sake of clarity or readability, and a
    large collection of new error code values useful for the new [try]
    command.

  * On exit, Tcl will no longer flush open non-blocking channels. Scripts
    relying on open non-blocking channels being flushed on exit will have
    to be modified to explicitly flush or close those channels.

  * Tk color names have been redefined to match Web color standards.

  * Tk defines many more virtual events that control the built-in widget
    set.  These can override virtual events created in your scripts with
    the [event add] command, changing program behavior.

  * The default bindings have changed.

  * On Unix-like platforms, [load] is implemented as a call to dlopen(),
    with the flags (RTLD_NOW|RTLD_LOCAL) passed by default.  If your use
    of [load] requires otherwise, use the new -global or -lazy options to
    [load] to set the RTLD_GLOBAL or RTLD_LAZY flags respectively.

  * The default set of whitespace characters trimmed by the
    [string trim*] commands was changed to add more Unicode whitespace
    characters.

  * When a channel gets std channel status on creation, it now gets the
    appropriate name matching std*, and no other.

  * A workaround built in to the default [unknown] command allowed
    programs to make errors with [namespace code].  Scripts are now
    expected to use [namespace code] correctly.

Issues for users of the public C API:

  * C code compiled with USE_TCL_STUBS now must be linked against a
    stub library.  The Tcl shared library no longer exports variables
    used in the stub interface.  Analogous changes also made to Tk.

  * The Tcl_Interp no longer contains the fields "result" or "errorline".
    Update your programs to use the supported interfaces
    Tcl_GetStringResult(), Tcl_(Get|Set)ErrorLine(), and
    Tcl_Set(Obj)Result().  While working on that update, use temporary
    workarounds of
       #define USE_INTERP_RESULT
       #define USE_INTERP_ERRORLINE
    to keep existing code working until the update is complete.

  * Tcl_Exit() no longer calls Tcl_Finalize() to do a complete orderly
    teardown of Tcl.  It calls handlers registered by
    Tcl_CreateExitHandler() and little else.  Most of the tasks skipped
    will be accomplished by the OS anyway, freeing memory and such.
    This avoids many tricky finalization bugs, especially in
    multi-threaded operation.  Callers of Tcl_Exit() that want to keep
    a full teardown may call Tcl_Finalize() themselves, or set the
    environment variable TCL_FINALIZE_ON_EXIT to non-zero.

  * System encoding during Tcl library initialization now iso8859-1,
    not identity.

  * A [load]able extension is no longer [unload]able unless it signals
    its ability to be [unload]ed by exporting suitable _Unload()
    and _SafeUnload() routines.

  * Tcl_GetObjType(), Tcl_GetChannelType(), Tcl_FSGetFileSystemForPath()
    now return const (read-only) pointers.

  * Tcl_SetMainLoop() can now only influence Tcl_Main() if it is called
    from the same thread as Tcl_Main().

  * Providers of a Tcl_Filesystem will need to update their
    Tcl_FSFileAttrStringProc entry to match the prototype

       typedef const char * CONST86 *Tcl_FSFileAttrStringsProc(
             Tcl_Obj *pathPtr, Tcl_Obj **objPtrRef);

    where CONST86 indicates a new const on the return value in Tcl 8.6.

  * The Tcl_ObjType "option" is no longer registered.  Callers of
    Tcl_GetObjType("option") must be prepared to accept NULL as a result.

Issues for users of the private interfaces:

  * Callers of the Tcl*Startup*() routines should convert to using the
    corresponding (now public) Tcl_*Startup*() routines.

  * Callers of TclFindElement() must adapt to its revised specification
    for its final argument.

  * TclpGetUserHome() and TclSetPreInitScript() now return const
    (read-only) pointers.

2012-12-08

使用 Ftp 下載氣象局的預報資料

package require ftp

set ftpServer [::ftp::Open ftpsv.cwb.gov.tw Anonymous guest@guest.com]
::ftp::Cd $ftpServer pub
::ftp::Cd $ftpServer forecast
::ftp::Get $ftpServer W002.txt

使用 ftp package 來下載檔案。

2012-09-23

proc body and args

考慮下面 Tcl 文件裡的示範:
proc printProc {procName} {
    set result [list proc $procName]
    set formals {}
    foreach var [info args $procName] {
        if {[info default $procName $var def]} {
            lappend formals [list $var $def]
        } else {
            # Still need the list-quoting because variable
            # names may properly contain spaces.
            lappend formals [list $var]
        }
    }
    puts [lappend result $formals [info body $procName]]
}

所以我們可以很容易的知道 proc 參數和函式文字內容的資訊。也就是說,我們可以使用 info command 來拿到某個函式的內容(也就是使用 info body $procname 來拿到),並且使用 eval 執行之。

下面是一些練習的嘗試:
proc hello {x} {
    puts $x
}

proc rand {x} {
    set num [expr rand()]
    return [expr $num * $x]
}

proc hello2 {procname x} {
    if {[string compare "hello" $procname]==0} {
        incr x
    }     
    eval [info body $procname]
}   

hello2 hello 3
hello2 rand 10

很神奇吧?雖然我不知道有什麼用處,但是可以直接拿別的 proc 的 function body 來執行,對我而言是很神奇的。

2012-09-08

遞迴練習

namespace path {::tcl::mathop ::tcl::mathfunc}

proc fac n {
    if {$n <= 1} {
        return 1;
    } else {
        return [+ $n [fac [- $n 1]]]
    }    
}

簡單的遞迴練習程式,為了多一些變化,所以使用了不透過 expr 的方式。

2012-06-24

stdout and stderr

在使用 exec 執行 git clone B2G 的 source code 時,希望可以看到目前的情況,所以:

set B2G_git [list git clone https://github.com/andreasgal/B2G.git B2G >@stdout 2>@stderr]
puts "Using git clone B2G source code..." 
exec {*}$B2G_git
整個程式如下,不過我只是急救章的寫一個來用,還沒有完整的測試過:

#!/usr/bin/tclsh
#
# Purpose: Get B2G project source code
# Update date: 2012/06/24
#


# global variable
#
set B2GDir [pwd]
append B2GDir "/B2G"

set B2G_GIT "https://github.com/andreasgal/B2G.git"


# 
# get_source procedure: using git clone to get source code
#
proc get_source {} {
  puts "########## get start ##########"

  set B2G_git [list git clone $::B2G_GIT B2G >@stdout 2>@stderr]
  puts "Using git clone B2G source code..." 
  exec {*}$B2G_git

  puts "########## get end ##########"
}


# 
# update_source procedure: using git pull to update source code
#
proc update_source {} {
  puts "B2G folder exists!!! --- try to update"
  set git_pull [list git pull >@stdout 2>@stderr]

  puts "########## upate start ##########"

  cd $::B2GDir
  set fileExist [file exists .git]
  if {$fileExist > 0} {
    puts "Using git pull to update B2G source code..." 
    exec {*}$git_pull
  } else {
    puts "Error!!!"
    puts "B2G folder exists but no .get folder!!!"
  }

  puts "########## upate end ##########"
}


#
# Main procedure, get B2G project source code
#
if {$argc > 0} {
  set argv0 [string toupper [lindex $argv 0]]
  if { [expr [string compare $argv0 "GET" ] == 0] } {  
    set fileExist [file exists $B2GDir]
    if {!$fileExist} {
       get_source
    } else {
       update_source
    }
  } elseif { [expr [string compare $argv0 "UPDATE" ] == 0] } {
    set fileExist [file exists $B2GDir]
    if {!$fileExist} {
       puts "B2G folder does not exist!!!"
    } else {
       update_source
    }
  }
} elseif {$argc == 0} {
  puts "User does not use GET or UPDATE parameter..."
  puts "Check B2G folder..."
  set fileExist [file exists $B2GDir]
  if {!$fileExist} {
     get_source
  } else {
     update_source
  }
}

2012-01-10

tcllib 1.14 is out

 我現在才注意到,在 2011.12.13,tcllib 已經釋出了新版 v1.14

Overview
========

21 new packages in 7 modules
30 changed packages in 24 modules
8 internally changed packages in 8 modules
328 unchanged packages in 89 modules
393 packages, total in 107 modules, total

2012-01-08

Coroutines

在 8.6 引進新的 Non-Recursive Engine (NRE) 之後,帶進了新的功能 Coroutines。不過 Coroutine 對我而言是很陌生的東西,所以做一下初學筆記。

在看過網路上對於 Coroutine 的介紹以後,我想可以簡單的總結如下:

Croutine 是自 1960 年代就已經現身的多工實做技術,原理相當單純,在 Coroutine 的 "yield" 是屬於程式語言層面,透過特定技巧或機制,讓原本循序執行的陳述指令,得以做出交錯執行的結果,可以說是 Windows 3.X 「合作式多工」的基礎概念(十分類似)。

用簡單的一句話來說 Coroutine,就是可以暫時中斷,之後再繼續執行的程序。


下面是從 Tcl 8.6 manual page copy 出來的例子:

coroutine accumulator apply {{} {
    set x 0
    while 1 {
        # yield $x: 丟資料並且把主控權交給呼叫者
        incr x [yield $x]
    }
}}

for {set i 0} {$i < 10} {incr i} {
    puts "$i -> [accumulator $i]"
}

manual page 裡還有其它的例子幫助理解,希望我對 Coroutines 的理解是正確的。

Wub

Wub
wub - Wub pure tcl HTTP1.1 server, client and tool suite


雖然 Wub 發展有一段時間了,不過我是最近才發現的。

截錄自 Tcler Wiki 的介紹:

Wub is a web-server written in pure-Tcl. It runs the Wiki you're now reading. It absolutely requires Tcl 8.6 and tracks the HEAD closely. It should help in creating highly-dynamic (and portable) web applications. It is the successor in spirit of Tclhttpd, aiming to preserve the best of it while using the bleeding-edge latest Tcl facilities to simplify and extend.


Tcler Wiki 就是使用 Wub 架起來的,非常好的 working example。

2012-01-07

備份 (on Windows)

跟之前一樣的程式,只是加上 GUI 表示目前正在備份中,加上練習 thread 使用的部份。

#!/usr/bin/tclsh
#
# This file is used to backup my homepage
#

package require Tk
package require Thread

set ::gThread [thread::create {thread::wait} ]

label .greetings -text "Now backup my homepage..." -bd 4 -relief ridge
pack .greetings -fill both

wm title . "Backup"

thread::send -async $::gThread { 
    set backupfile $env(HOME)
    append backupfile "\\My Documents"
    append backupfile "\\Homepage-"
    append backupfile [clock format [clock seconds] -format %Y%m%d]
    append backupfile ".7z"

    set backupdir $env(HOME)
    append backupdir "\\My Documents"
    append backupdir "\\public_html"

    set fileExist [file exists $backupfile]
    if {$fileExist > 0} {
        puts "Now try to remove old backup file."
        file delete $backupfile
    }

    set var [list 7z a $backupfile $backupdir]
    exec {*}$var        
} result


vwait result
exit