sourceafFancom::ComThread.fan

using [java] com.jacob.com::ComThread as JComThread

**
** Handles the tricky business of COM threading. 
** 
** TODO: Implement nested closure calls like wot 
** [Scriptcom]`http://svn.codehaus.org/groovy/modules/scriptom/trunk/scriptom/src/main/java/org/codehaus/groovy/scriptom/Scriptom.java` 
** does.
** 
** TODO: Investigate how calling 'release()' affects COM event handling.
** 
** In essence, call 'initSta()' at the start of your COM calls and 'release()' at the end.
** 
** For more details:
** - See [COM Apartments in JACOB]`http://danadler.com/jacob/JacobThreading.html` from JACOB
** - See [The Least You Need to Know about COM]`http://groovy.codehaus.org/The+Least+You+Need+to+Know+about+COM` from Groovy Scriptcom
** 
class ComThread {

    static const private |->| shutdownHook := |->| {
        JComThread.Release      
    }
    
    ** Initialise an STA thread.
    static Void initSta() {
        releaseThreadOnShutdown
        JComThread.InitSTA
    }

    ** Initialise aN MTA thread.
    static Void initMta() {
        releaseThreadOnShutdown
        JComThread.InitMTA
    }
    
    ** Release current COM resources for this thread.
    static Void release() {
        JComThread.Release
    }
    
    private static Void releaseThreadOnShutdown() {
        // ensure we don't keep adding more and more hooks!
        Env.cur.removeShutdownHook(shutdownHook)
        
        // (re)register the hook
        Env.cur.addShutdownHook(shutdownHook)
    }
}