import os

"""
  CvsGui Macro Library Module "SafeTk"
  $Revision: 1.4 $
  
  written by Oliver Giesen, Aug 2002
  contact:
    email:  ogware@gmx.net
    jabber: ogiesen@jabber.org
    icq:    18777742

  Feel free to modify or distribute in whichever way you like,
   as long as it doesn't limit my personal rights to modify and
   redistribute this code.
   Apart from that the code is supplied "as-is", i.e. without warranty of any
   kind, either expressed or implied, regarding its quality or security.
   Have fun!

  When using Tkinter, the module FixTk is imported which creates
   an environment variable TCL_LIBRARY and points it at the TCL
   libraries within the Python installation.
   This has the unfortunate effect that TCL macros running from a
   separate installation of TCL will now try to locate packages
   within the Python directories instead of the TCL ones, which
   usually fails because the directories within the Python
   installation are named differently.
  This module employs a fix to this by removing said environment
   variable and only temporarily enabling it for the lifetime of
   a Tkinter-based Tk instance.
"""

try:
  from Tkinter import *
except:
  NoTk = 1
else:
  NoTk = -1  # indicates uninitialized

  TCL_LIB = 'TCL_LIBRARY'

  if os.environ.has_key(TCL_LIB):
    tcllib = os.environ[TCL_LIB]
  else:
    tcllib = ''

  def prepTk():
    """ ensure that TCL_LIBRARY points to the path determined in the FixTk module
    """
    global tcllib
    if not os.environ.has_key(TCL_LIB):
      os.environ[TCL_LIB] = tcllib

  def resetTk():
    """ delete the TCL_LIBRARY environment variable, so TCL has to go searching for
      extension packages on its own instead of depending on the Python search path.
      Make a backup of the value determined in the FixTk module so we could write it
      back again later.
    """
    global tcllib
    if os.environ.has_key(TCL_LIB):
      if tcllib == '':
        tcllib = os.environ[TCL_LIB]
      del os.environ[TCL_LIB]
    #print 'reset TCL path'

  class SafeTkRoot( Tk):
    """ A replacement for the Tk class which ensures the TCL_LIBRARY variable lives
      only as long as the Tk-instance does.
    """
    def __init__( self, obj):
      prepTk()
      Tk.__init__( self, baseName=str(obj))

    def destroy( self):
      #print 'destroying SafeTkRoot instance'
      Tk.destroy( self)
      resetTk()
      
    def __del__( self):
      #print 'finalizing SafeTkRoot instance'
      resetTk()

def checkTk():
  """ Checks whether Tk could be invoked without exceptions. The check is only
    performed once. Later calls simply return the previous result.
  """
  global NoTk
  try:
    if NoTk < 0:
      try:
        testtk = SafeTkRoot( 'justChecking')
        testtk.destroy()
        del testtk
        NoTk = 0
        print 'Tk is available, Tk-macros are enabled'
      except:
        NoTk = 1
        #raise
  finally:
    return NoTk == 0
    #if NoTk: raise
