# -*- mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
#
#    Copyright (c) 2001 Internet Discovery Incorporated.
#
#	$Id$

import Tix, Tkinspect, os, sys, traceback, string
import tkMessageBox

class Tk(Tix.Tk, Tkinspect.Tk):
    """Toplevel widget of Tix which represents mostly the main window
    of an application. It has an associated Tcl interpreter."""

    def __init__(self, screenName=None, baseName=None, className='Tix'):
        r"""Intinialize Tix and load tcl Tcl dde command. You must have
        the Tcl dde package installed for Tixinspect to work.
        Look for the ddl in %PYTHONROOT%\tcl\dde1.1\tcldde83.dll."""

        Tix.Tk.__init__(self, screenName, baseName, className)
	self.root = self

	self.hooks = None
        server_name = "%s#%x" % (string.lower(className), os.getpid())
        if sys.platform == "win32":
	    try:
                if 0:
                    # Try this instead of Tcl's dde command: it may be more
                    # reliable, though "reliable DDE" is an oxymoron. Untested.
                    text = "Problems starting the dde server."
                    import dde
                    import DdeTclEval
                    import win32ui
                    server = dde.CreateServer()
                    server.AddTopic(DdeTclEval.TclSystemTopic())
                    server.AddTopic(DdeTclEval.TclRequestTopic("TclEval", self))
                    server.Create(server_name)
                    # maybe win32gui.PumpWaitingMessages() instead?
                    code = compile ("win32ui.PumpWaitingMessages(0, -1)",
                                    '<string>', 'eval')
                    if self.hooks is None: self.hooks = []
                    self.hooks.append(code)
                else:
                    # Make sure $tix_library is last to clobber pkgIndex.tcl
                    self.tk.eval('lappend auto_path $tix_library')
                    
                    # Look for these files and set the package if found.
                    # This is true for a Tix install from Tide applications.
                    self.tk.eval('''
                    set dde_file [file join $tix_library tcldde83.dll]
                    if {[file isfile $dde_file]} {
                    	package ifneeded dde 1.1 [list load $dde_file dde]
                    }
                    set reg_file [file join $tix_library tclreg83.dll]
                    if {[file isfile $reg_file]} {
                    	package ifneeded registry 1.1 [list load $reg_file registry]
                    }
                    unset dde_file reg_file
                    ''')

                    self.tk.eval('package require dde')
                    self.tk.eval('dde servername ' + server_name)
            except:
                t, v, tb = sys.exc_info()
                text = "You must have the Tcl dde package installed for Tixinspect to work.\n"
                text += r"Look for the file %PYTHONROOT%\tcl\dde1.1\tcldde83.dll."
                text += "\n"
                for line in traceback.format_exception(t,v,tb):
                    text += line + '\n'
                d = tkMessageBox.showerror ( 'Tixinspect Error', text)
                sys.exit(1)

        self.tk.eval('tk appname ' + server_name)
        self.tk.eval('global argv argc; set argv {}; set argc 0')
        self.tkinspect_enable_eval()

        # Sanity checking for any Tix application
        try:
            # Make sure Tix is installed on this platform
            self.tk.eval("package require Tix")
        except:
            t, v, tb = sys.exc_info()
            text = "Error loading Tix\n"
            for line in traceback.format_exception(t,v,tb): text = text + line + '\n'
            try:
                tkMessageBox.showerror ('Txinspect Error', text)
            except:
                sys.stderr.write( text )
            sys.exit(1)


    def tixinspect_start (self, file):
        """Source the Tcl file that loads this application."""
        if not os.path.isfile(file):
            text = 'File not found! ' + file
            # print text
            d = tkMessageBox.showerror ( 'Error', text)
            self.tkinspect_quit (1)
        else:
            try:
                dir = os.path.dirname (file)
                self.tk.eval('global tixinspect_library; set tixinspect_library {%s}' % dir)
                os.chdir(dir)
                if sys.platform == "win32":
                    self.tk.eval('source {%s}' % file)
                else:
                    self.tk.eval('source {%s}' % file)
            except:
                t, v, tb = sys.exc_info()
                # print  'Tixinspect error: '
                text = ""
                for line in traceback.format_exception(t,v,tb):
                    text += line + '\n'
                try:
                    text += self.tk.eval('set errorInfo')
                    d = tkMessageBox.showerror ( 'Tixinspect Error', text)
                except:
                    t, v, tb = sys.exc_info()
                    print  'tkMessageBox error: '
                    for line in traceback.format_exception(t,v,tb): print line
                    print 'Error sourcing file! ' + text
                self.tkinspect_quit (1)

def main(name, file):
    """Source a tcl FILE into this Python Tix application called NAME."""
    root = Tk(className=name)
    # Make sure Tix is installed on this platform
    import Tix
    try:
        # Make sure Tcl/Tk knows Tix is installed on this platform
        # This can fail even if import Tix succeeds
        root.tk.eval('package require Tix')
    except:
        if not os.environ.haskey('TIX_LIBRARY'):
            text = "Please set the environment variable TIX_LIBRARY"
            tkMessageBox.showerror ('%s Error\n%s' % (name, text))
            sys.exit(1)

        dir = os.environ['TIX_LIBRARY']
        if os.path.isdir(dir):
            text = "The directory set in TIX_LIBRARY does not exist"
            tkMessageBox.showerror ('%s Error\n%s%s' % (name, text))
            sys.exit(1)
        
        try:
            # Maybe the library is not on the auto_path
            root.tk.eval("global auto_path env; lappend auto_path $env(TIX_LIBRARY)")
            root.tk.eval("package require Tix")
        except:
            t, v, tb = sys.exc_info()
            text = "You must have Tix installed for %s to work" % name
            for line in traceback.format_exception(t,v,tb):
                text += line + '\n'
            d = tkMessageBox.showerror ('%s Error\n%s' % (name, text))
            raise SystemExit , 1

    root.tixinspect_start (file)
    root.tkinspect_mainloop ()
    try:
        #print 'Destroying'
        root.destroy()
    except:
        #print 'Already Destroyed'
        pass


if __name__ == "__main__":
    dir = ""
    if len(sys.argv) > 0:
        # Assume the name of the file containing the tixinspect Tcl source
        # is the same as argument on the command line with .tcl
	dir = os.path.dirname(sys.argv[0])
    if not dir or not os.path.isdir(dir) or not os.path.isabs(dir):
        # Or, assume it's in the same directory as this one:
        dir = os.getcwd()
    file = os.path.join(dir, 'Tixinspect.tcl')
    main('Tixinspect', file)

