#!/bin/ksh ~/.mgltools/pythonsh
########################################################################
#
#    Vision Network - Python source code - file generated by vision
#    Thursday 30 July 2009 15:50:54 
#    
#       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/Tutorial/cartoon/cartoon1_net.py,v 1.5 2009/07/31 00:54:52 vareille Exp $
#
# $Id: cartoon1_net.py,v 1.5 2009/07/31 00:54:52 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
from Vision.StandardNodes import stdlib
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")

masterNet.getEditor().addLibraryInstance(stdlib,"Vision.StandardNodes", "stdlib")

try:
    ## saving node Show Image ##
    from Vision.PILNodes import ShowImage
    Show_Image_0 = ShowImage(constrkw={}, name='Show Image', library=imagelib)
    masterNet.addNode(Show_Image_0,192,334)
    apply(Show_Image_0.configure, (), {'paramPanelImmediate': 1, 'expanded': False})
except:
    print "WARNING: failed to restore ShowImage named Show Image in network masterNet"
    print_exc()
    Show_Image_0=None

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

try:
    ## saving node Read Image ##
    from Vision.PILNodes import ReadImage
    Read_Image_2 = ReadImage(constrkw={}, name='Read Image', library=imagelib)
    masterNet.addNode(Read_Image_2,30,238)
    apply(Read_Image_2.inputPortByName['filename'].configure, (), {'datatype': 'string', 'originalDatatype': 'str'})
    Read_Image_2.inputPortByName['filename'].rebindWidget()
    Read_Image_2.inputPortByName['filename'].widget.set(r"/home/vareille/dev/Data/crnCartoon0000_movie/crnCartoon0000.png", run=False)
    Read_Image_2.inputPortByName['filename'].unbindWidget()
    apply(Read_Image_2.configure, (), {'paramPanelImmediate': 1})
except:
    print "WARNING: failed to restore ReadImage named Read Image in network masterNet"
    print_exc()
    Read_Image_2=None

try:
    ## saving node Filename ##
    from Vision.StandardNodes import Filename
    Filename_3 = Filename(constrkw={}, name='Filename', library=stdlib)
    masterNet.addNode(Filename_3,30,156)
    Filename_3.inputPortByName['format'].widget.set(r"cartoonMovie/crnCartoon%04d.png", run=False)
    apply(Filename_3.configure, (), {'paramPanelImmediate': 1})
except:
    print "WARNING: failed to restore Filename named Filename in network masterNet"
    print_exc()
    Filename_3=None

try:
    ## saving node iterate ##
    from Vision.StandardNodes import Iterate
    iterate_4 = Iterate(constrkw={}, name='iterate', library=stdlib)
    masterNet.addNode(iterate_4,13,77)
except:
    print "WARNING: failed to restore Iterate named iterate in network masterNet"
    print_exc()
    iterate_4=None

try:
    ## saving node range ##
    from Vision.StandardNodes import Range
    range_5 = Range(constrkw={}, name='range', library=stdlib)
    masterNet.addNode(range_5,147,1)
    range_5.inputPortByName['fromInd'].widget.set(0, run=False)
    apply(range_5.inputPortByName['toInd'].widget.configure, (), {'increment': None})
    range_5.inputPortByName['toInd'].widget.set(99, run=False)
    range_5.inputPortByName['step'].widget.set(1, run=False)
    apply(range_5.configure, (), {'paramPanelImmediate': 1})
except:
    print "WARNING: failed to restore Range named range in network masterNet"
    print_exc()
    range_5=None

#masterNet.run()
masterNet.freeze()

## saving connections for network cartoon1 ##
if Read_Image_2 is not None and Scale_1 is not None:
    try:
        masterNet.connectNodes(
            Read_Image_2, Scale_1, "image", "image", blocking=True
            , splitratio=[0.71482003319228049, 0.57797893896099328])
    except:
        print "WARNING: failed to restore connection between Read_Image_2 and Scale_1 in network masterNet"
if Scale_1 is not None and Show_Image_0 is not None:
    try:
        masterNet.connectNodes(
            Scale_1, Show_Image_0, "scaledImage", "image", blocking=True
            , splitratio=[0.25052336357358551, 0.22046770659249654])
    except:
        print "WARNING: failed to restore connection between Scale_1 and Show_Image_0 in network masterNet"
if Filename_3 is not None and Read_Image_2 is not None:
    try:
        masterNet.connectNodes(
            Filename_3, Read_Image_2, "filename", "filename", blocking=True
            , splitratio=[0.27515207739560127, 0.20724709739092084])
    except:
        print "WARNING: failed to restore connection between Filename_3 and Read_Image_2 in network masterNet"
if iterate_4 is not None and Filename_3 is not None:
    try:
        masterNet.connectNodes(
            iterate_4, Filename_3, "iter", "number", blocking=True
            , splitratio=[0.31440627865824977, 0.28982036323827226])
    except:
        print "WARNING: failed to restore connection between iterate_4 and Filename_3 in network masterNet"
if range_5 is not None and iterate_4 is not None:
    try:
        masterNet.connectNodes(
            range_5, iterate_4, "data", "listToLoopOver", blocking=True
            , splitratio=[0.57147914730620286, 0.66714915974363409])
    except:
        print "WARNING: failed to restore connection between range_5 and iterate_4 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)

