#!/bin/ksh ~/.mgltools/pythonsh
########################################################################
#
#    Vision Network - Python source code - file generated by vision
#    Friday 31 July 2009 13:20:28 
#    
#       The Scripps Research Institute (TSRI)
#       Molecular Graphics Lab
#       La Jolla, CA 92037, USA
#
# Copyright: Daniel Stoffler, Michel Sanner and TSRI
#   
# revision: Guillaume Vareille
#  
#########################################################################
#
# $Header: /opt/cvs/python/packages/share1.5/Vision/doc/Examples/lena_net.py,v 1.4 2009/07/31 20:31:15 vareille Exp $
#
# $Id: lena_net.py,v 1.4 2009/07/31 20:31:15 vareille Exp $
#


if __name__=='__main__':
    from sys import argv
    if '--help' in argv or '-h' in argv or '-w' in argv: # run without Vision
        withoutVision = True
        from Vision.VPE import NoGuiExec
        ed = NoGuiExec()
        from NetworkEditor.net import Network
        import os
        masterNet = Network("process-"+str(os.getpid()))
        ed.addNetwork(masterNet)
    else: # run as a stand alone application while vision is hidden
        withoutVision = False
        from Vision import launchVisionToRunNetworkAsApplication, mainLoopVisionToRunNetworkAsApplication
	if '-noSplash' in argv:
	    splash = False
	else:
	    splash = True
        masterNet = launchVisionToRunNetworkAsApplication(splash=splash)
        import os
        masterNet.filename = os.path.abspath(__file__)
from traceback import print_exc
## loading libraries ##
from Vision.PILNodes import imagelib
try:
    masterNet
except (NameError, AttributeError): # we run the network outside Vision
    from NetworkEditor.net import Network
    masterNet = Network()

masterNet.getEditor().addLibraryInstance(imagelib,"Vision.PILNodes", "imagelib")

try:
    ## saving node Read Image ##
    from Vision.PILNodes import ReadImage
    Read_Image_0 = ReadImage(constrkw={}, name='Read Image', library=imagelib)
    masterNet.addNode(Read_Image_0,65,19)
    apply(Read_Image_0.inputPortByName['filename'].configure, (), {'datatype': 'string', 'originalDatatype': 'str'})
    Read_Image_0.inputPortByName['filename'].widget.set(r"lena.jpg", run=False)
except:
    print "WARNING: failed to restore ReadImage named Read Image in network masterNet"
    print_exc()
    Read_Image_0=None

try:
    ## saving node Show Image ##
    from Vision.PILNodes import ShowImage
    Show_Image_1 = ShowImage(constrkw={}, name='Show Image', library=imagelib)
    masterNet.addNode(Show_Image_1,101,268)
except:
    print "WARNING: failed to restore ShowImage named Show Image in network masterNet"
    print_exc()
    Show_Image_1=None

try:
    ## saving node Scale ##
    from Vision.PILNodes import ResizeImage
    Scale_2 = ResizeImage(constrkw={}, name='Scale', library=imagelib)
    masterNet.addNode(Scale_2,93,158)
    Scale_2.inputPortByName['scale'].widget.set(1.0, run=False)
    Scale_2.inputPortByName['filter'].widget.set(r"NEAREST", run=False)
except:
    print "WARNING: failed to restore ResizeImage named Scale in network masterNet"
    print_exc()
    Scale_2=None

#masterNet.run()
masterNet.freeze()

## saving connections for network lena ##
if Read_Image_0 is not None and Scale_2 is not None:
    try:
        masterNet.connectNodes(
            Read_Image_0, Scale_2, "image", "image", blocking=True
            , splitratio=[0.4860562115510304, 0.3184572750131901])
    except:
        print "WARNING: failed to restore connection between Read_Image_0 and Scale_2 in network masterNet"
if Scale_2 is not None and Show_Image_1 is not None:
    try:
        masterNet.connectNodes(
            Scale_2, Show_Image_1, "scaledImage", "image", blocking=True
            , splitratio=[0.25532499146494703, 0.38342871127466627])
    except:
        print "WARNING: failed to restore connection between Scale_2 and Show_Image_1 in network masterNet"
masterNet.runOnNewData.value = False

if __name__=='__main__':
    from sys import argv
    lNodePortValues = []
    if (len(argv) > 0) and argv[1].startswith('-'):
        lArgIndex = 2
    else:
        lArgIndex = 1
    while lArgIndex < len(argv) and argv[lArgIndex][-3:]!='.py':
        lNodePortValues.append(argv[lArgIndex])
        lArgIndex += 1
    masterNet.setNodePortValues(lNodePortValues)
    if '--help' in argv or '-h' in argv: # show help
        masterNet.helpForNetworkAsApplication()
    elif '-w' in argv: # run without Vision and exit
         # create communicator
        from NetworkEditor.net import Communicator
        masterNet.communicator = Communicator(masterNet)
        print 'Communicator listening on port:', masterNet.communicator.port

        import socket
        f = open(argv[0]+'.sock', 'w')
        f.write("%s %i"%(socket.gethostbyname(socket.gethostname()),
                         masterNet.communicator.port))
        f.close()

        # create communication socket
        import socket
        HOST = ''                 # Symbolic name meaning the local host
        PORT = 50010              # Arbitrary non-privileged port
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((HOST, PORT))
        s.listen(5)
        s.setblocking(0)
        masterNet.socket = s
        masterNet.socketConnections = []
        masterNet.HOST = HOST
        masterNet.PORT = PORT

        masterNet.run()

    else: # stand alone application while vision is hidden
        if '-e' in argv: # run and exit
            masterNet.run()
        elif '-r' in argv or len(masterNet.userPanels) == 0: # no user panel => run
            masterNet.run()
            mainLoopVisionToRunNetworkAsApplication(masterNet.editor)
        else: # user panel
            mainLoopVisionToRunNetworkAsApplication(masterNet.editor)

