www.gibmonks.com

  Previous section   Next section

Practical Programming in Tcl & Tk, Third Edition
By Brent B. Welch

Table of Contents
Chapter 42.  Managing User Preferences


Managing the Preferences File

The preference settings are saved in the per-user file. The file is divided into two parts. The tail is automatically rewritten by the preferences package. Users can manually add resource specifications to the beginning of the file and they will be preserved:

Example 42-8 Saving preferences settings to a file.
# PrefSave writes the resource specifications to the
# end of the per-user resource file,
proc PrefSave {} {
   global pref
   if [catch {
      set old [open $pref(userDefaults) r]
      set oldValues [split [read $old] \n]
      close $old
   }] {
      set oldValues {}
   }
   if [catch {open $pref(userDefaults).new w}out] {
      .pref.but.label configure -text \
      "Cannot save in $pref(userDefaults).new: $out"
       return
   }
   foreach line $oldValues {
      if {$line == \
             "!!! Lines below here automatically added"} {
         break
      } else {
         puts $out $line
      }
   }
   puts $out "!!! Lines below here automatically added"
   puts $out "!!! [exec date]"
   puts $out "!!! Do not edit below here"
   foreach item $preferences {
      set varName [PrefVar $item]
      set resName [PrefRes $item]
      if [info exists pref(entry,$varName)] {
         PrefEntrySet $pref(entry,$varName) $varName
      }
      set value [PrefValue $varName $resName]
      puts $out [format "%s\t%s" *${resName}: $value]
   }
   close $out
   set new [glob $pref(userDefaults).new]
   set old [file root $new]
   if [catch {file rename -force $new $old}err] {
      Status "Cannot install $new: $err"
      return
   }
   PrefDismiss
}

There is one fine point in PrefSave. The value from the entry widget for general-purpose items is obtained explicitly in case the user has not already pressed <Return> to update the Tcl variable.

The interface is rounded out with the PrefReset and PrefDismiss procedures. A reset is achieved by clearing the option database and reloading it, and then temporarily clearing the preference items and their associated variables and then redefining them with Pref_Add.

Example 42-9 Read settings from the preferences file.
proc PrefReset {} {
   global pref
   # Re-read user defaults
   option clear
   PrefReadFile $pref(appDefaults) startup
   PrefReadFile $pref(userDefaults) user
   # Clear variables
   set items $pref(items)
   set pref(items) {}
   foreach item $items {
      uplevel #0 [list unset [PrefVar $item]]
   }
   # Restore values
   Pref_Add $items
}
proc PrefDismiss {} {
   destroy .pref
   catch {destroy .prefitemhelp}
}

      Previous section   Next section
    Top