Beispiel #1
0
def saveAs(menu):

    scriptWindow = menu.ancestor(GafferUI.ScriptWindow)
    script = scriptWindow.scriptNode()
    currentFileName = script["fileName"].getValue()

    if currentFileName:
        path = Gaffer.FileSystemPath(currentFileName)
    else:
        path = Gaffer.FileSystemPath(os.getcwd())

    path.setFilter(__scriptPathFilter())

    dialogue = GafferUI.PathChooserDialogue(path,
                                            title="Save script",
                                            confirmLabel="Save")
    path = dialogue.waitForPath(parentWindow=scriptWindow)

    if not path:
        return

    path = str(path)
    if not path.endswith(".gfr"):
        path += ".gfr"

    script["fileName"].setValue(path)
    with GafferUI.ErrorDialogue.ExceptionHandler(title="Error Saving File",
                                                 parentWindow=scriptWindow):
        script.save()

    application = script.ancestor(Gaffer.ApplicationRoot.staticTypeId())
    addRecentFile(application, path)
    def testCancellation(self):

        p = Gaffer.FileSystemPath(os.path.dirname(__file__))

        # Children

        c = IECore.Canceller()
        c.cancel()

        with self.assertRaises(IECore.Cancelled):
            p.children(c)

        # Sequence properties

        for f in range(0, 100):
            with open(
                    os.path.join(self.temporaryDirectory(),
                                 "{}.txt".format(f)), "w") as f:
                f.write("x")

        p = Gaffer.FileSystemPath(os.path.join(self.temporaryDirectory(),
                                               "#.txt"),
                                  includeSequences=True)

        with self.assertRaises(IECore.Cancelled):
            p.property("fileSystem:owner", c)

        with self.assertRaises(IECore.Cancelled):
            p.property("fileSystem:group", c)

        with self.assertRaises(IECore.Cancelled):
            p.property("fileSystem:size", c)

        with self.assertRaises(IECore.Cancelled):
            p.property("fileSystem:modificationTime", c)
Beispiel #3
0
def _waitForFileName( initialFileName="", parentWindow=None ) :

	bookmarks = None
	if parentWindow is not None :
		if isinstance( parentWindow, GafferUI.ScriptWindow ) :
			scriptWindow = parentWindow
		else :
			scriptWindow = parentWindow.ancestor( GafferUI.ScriptWindow )
		if scriptWindow is not None :
			bookmarks = GafferUI.Bookmarks.acquire( scriptWindow.scriptNode().ancestor( Gaffer.ApplicationRoot.staticTypeId() ), category="reference" )

	if initialFileName :
		path = Gaffer.FileSystemPath( os.path.dirname( os.path.abspath( initialFileName ) ) )
	else :
		path = Gaffer.FileSystemPath( bookmarks.getDefault( parentWindow ) if bookmarks is not None else os.getcwd() )

	path.setFilter( Gaffer.FileSystemPath.createStandardFilter( [ "grf" ] ) )

	dialogue = GafferUI.PathChooserDialogue( path, title = "Load reference", confirmLabel = "Load", valid = True, leaf = True, bookmarks = bookmarks )
	path = dialogue.waitForPath( parentWindow = parentWindow )
	
	if not path :
		return ""
	
	return str( path )
Beispiel #4
0
    def testConstructWithFilter(self):

        p = Gaffer.FileSystemPath(__file__)
        self.failUnless(p.getFilter() is None)

        f = Gaffer.FileNamePathFilter(["*.exr"])
        p = Gaffer.FileSystemPath(__file__, filter=f)
        self.failUnless(p.getFilter().isSame(f))
    def testConstructWithFilter(self):

        p = Gaffer.FileSystemPath(__file__)
        self.assertIsNone(p.getFilter())

        f = Gaffer.FileNamePathFilter(["*.exr"])
        p = Gaffer.FileSystemPath(__file__, filter=f)
        self.assertTrue(p.getFilter().isSame(f))
    def __init__(self, path, root="/", minSequenceSize=1, filter=None):

        if not isinstance(path, Gaffer.Path):
            if isinstance(path, str):
                path = Gaffer.FileSystemPath(path)
            else:
                path = Gaffer.FileSystemPath(path, root)

        Gaffer.Path.__init__(self, path[:], path.root(), filter=filter)

        # we use the seed for creating base paths whenever we need them
        self.__basePathSeed = path
        self.__minSequenceSize = minSequenceSize
Beispiel #7
0
    def testCopy(self):

        p = Gaffer.FileSystemPath(self.__dir)
        p2 = p.copy()

        self.assertEqual(p, p2)
        self.assertEqual(str(p), str(p2))
Beispiel #8
0
    def __init__(self,
                 key,
                 target=None,
                 acceptEmptyString=True,
                 defaultValue="",
                 **kw):

        self.__row = GafferUI.ListContainer(
            GafferUI.ListContainer.Orientation.Horizontal, spacing=4)

        self.__path = Gaffer.FileSystemPath()
        self.__pathWidget = GafferUI.PathWidget(self.__path)

        MetadataWidget.__init__(self,
                                self.__row,
                                key,
                                target,
                                defaultValue=defaultValue,
                                **kw)

        self.__row.append(self.__pathWidget)

        button = GafferUI.Button(image="pathChooser.png", hasFrame=False)
        button.clickedSignal().connect(Gaffer.WeakMethod(self.__buttonClicked),
                                       scoped=False)
        self.__row.append(button)

        self.__acceptEmptyString = acceptEmptyString

        self.__pathWidget.editingFinishedSignal().connect(Gaffer.WeakMethod(
            self.__editingFinished),
                                                          scoped=False)
Beispiel #9
0
def __fileNameCreator( plug, annotations ) :

	extensions = annotations.get( plug.getName() + ".extensions", None )
	if extensions is not None :
		extensions = extensions.value.split( "|" )
	else :
		extensions = []

	bookmarksCategory = annotations.get( plug.getName() + ".bookmarksCategory", None )
	if bookmarksCategory is not None :
		bookmarksCategory = bookmarksCategory.value
	else :
		# seems like a reasonable guess, and it's preferable to have a category
		# rather than to have any bookmarks made here pollute the bookmarks for
		# other browsers.
		bookmarksCategory = "texture"
			
	return GafferUI.PathPlugValueWidget(
		plug,
		path = Gaffer.FileSystemPath(
			"/",
			filter = Gaffer.FileSystemPath.createStandardFilter(
				extensions = extensions,
				extensionsLabel = "Show only supported files",
			),
		),
		pathChooserDialogueKeywords = {
			"bookmarks" : GafferUI.Bookmarks.acquire(
				plug.ancestor( Gaffer.ApplicationRoot.staticTypeId() ),
				pathType = Gaffer.FileSystemPath,
				category = bookmarksCategory,
			),
		},
	)
	def testSymLinkInfo( self ) :

		with open( self.__dir + "/a", "w" ) as f :
			f.write( "AAAA" )

		os.symlink( self.__dir + "/a", self.__dir + "/l" )

		# symlinks should report the info for the file
		# they point to.
		a = Gaffer.FileSystemPath( self.__dir + "/a" )
		l = Gaffer.FileSystemPath( self.__dir + "/l" )
		aInfo = a.info()
		self.assertEqual( aInfo["fileSystem:size"], l.info()["fileSystem:size"] )
		# unless they're broken
		os.remove( str( a ) )
		self.assertNotEqual( aInfo["fileSystem:size"], l.info()["fileSystem:size"] )
Beispiel #11
0
def open(menu):

    scriptWindow = menu.ancestor(GafferUI.ScriptWindow)

    path = Gaffer.FileSystemPath("/")
    path.addFilter(Gaffer.FileNamePathFilter(["*.gfr"]))
    path.addFilter(
        Gaffer.FileNamePathFilter([re.compile("^[^.].*")], leafOnly=False))
    dialogue = GafferUI.PathChooserDialogue(path,
                                            title="Open script",
                                            confirmLabel="Open")
    scriptWindow.addChildWindow(dialogue)
    path = dialogue.waitForPath()
    dialogue.hide()

    if not path:
        return

    currentScript = scriptWindow.getScript()
    application = scriptWindow.getScript().ancestor(
        Gaffer.ApplicationRoot.staticTypeId())

    currentNodes = [
        n for n in currentScript.children()
        if n.isInstanceOf(Gaffer.Node.staticTypeId())
    ]
    if not currentNodes and not currentScript["fileName"].getValue():
        script = currentScript
    else:
        script = Gaffer.ScriptNode()

    script["fileName"].setValue(str(path))
    script.load()

    application["scripts"].addChild(script)
    def test(self):

        # First, check that we have a mix of extensions in
        # our test directory. Otherwise we can't test anything.

        self.assertTrue(
            len(glob.glob(self.__testDirectory + "/*")) != len(
                glob.glob(self.__testDirectory + "/*.txt")))

        # Check that an unfiltered path can see all the files

        path = Gaffer.FileSystemPath(self.__testDirectory)
        children = path.children()
        self.assertEqual(len(children),
                         len(glob.glob(self.__testDirectory + "/*")))

        # Attach a filter, and check that the files are filtered
        txtFilter = Gaffer.FileNamePathFilter(["*.txt"])
        path.setFilter(txtFilter)

        children = path.children()
        self.assertEqual(len(children),
                         len(glob.glob(self.__testDirectory + "/*.txt")))

        # Copy the path and check the filter is working on the copy
        pathCopy = path.copy()
        self.assertEqual(len(pathCopy.children()), len(children))

        # Detach the filter and check that behaviour has reverted
        path.setFilter(None)
        children = path.children()
        self.assertEqual(len(children),
                         len(glob.glob(self.__testDirectory + "/*")))
Beispiel #13
0
def exportSelection(menu):

    scriptWindow = menu.ancestor(GafferUI.ScriptWindow)
    script = scriptWindow.scriptNode()

    selection = script.selection()
    parent = selection[0].parent()
    for node in selection:
        if not parent.isAncestorOf(node):
            assert (node.parent().isAncestorOf(parent))
            parent = node.parent()

    path = Gaffer.FileSystemPath(os.getcwd())
    path.setFilter(__scriptPathFilter())

    dialogue = GafferUI.PathChooserDialogue(path,
                                            title="Export selection",
                                            confirmLabel="Export")
    path = dialogue.waitForPath(parentWindow=scriptWindow)

    if not path:
        return

    path = str(path)
    if not path.endswith(".gfr"):
        path += ".gfr"

    script.serialiseToFile(path, parent, script.selection())
    def testCopy(self):

        p = Gaffer.FileSystemPath(self.temporaryDirectory())
        p2 = p.copy()

        self.assertEqual(p, p2)
        self.assertEqual(str(p), str(p2))
Beispiel #15
0
    def testEnabled(self):

        p = Gaffer.FileSystemPath(self.__dir, includeSequences=True)
        self.assertTrue(p.getIncludeSequences())

        p.setFilter(
            Gaffer.FileSequencePathFilter(
                mode=Gaffer.FileSequencePathFilter.Keep.Files))
        self.assertEqual(p.getFilter().getMode(),
                         Gaffer.FileSequencePathFilter.Keep.Files)
        self.assertEqual(
            set([str(c) for c in p.children()]),
            set([
                self.__dir + "/singleFile.txt",
                self.__dir + "/dir",
            ]))

        p.getFilter().setEnabled(False)
        self.assertEqual(
            set([str(c) for c in p.children()]),
            set([
                self.__dir + "/singleFile.txt", self.__dir + "/a.001.txt",
                self.__dir + "/a.002.txt", self.__dir + "/a.004.txt",
                self.__dir + "/b.003.txt", self.__dir + "/dir",
                self.__dir + "/a.###.txt", self.__dir + "/b.###.txt"
            ]))
Beispiel #16
0
    def __addClicked(self, *unused):

        bookmarks = GafferUI.Bookmarks.acquire(self, category="image")
        path = Gaffer.FileSystemPath(bookmarks.getDefault(self))
        path.setIncludeSequences(True)

        path.setFilter(
            Gaffer.FileSystemPath.createStandardFilter(
                GafferImage.ImageReader.supportedExtensions(),
                "Show only image files",
                includeSequenceFilter=True,
            ))

        dialogue = GafferUI.PathChooserDialogue(path,
                                                title="Add image",
                                                confirmLabel="Add",
                                                valid=True,
                                                leaf=True,
                                                bookmarks=bookmarks)
        dialogue.pathChooserWidget().pathListingWidget().setColumns(
            dialogue.pathChooserWidget().pathListingWidget().getColumns() + [
                GafferUI.PathListingWidget.StandardColumn(
                    "Frame Range", "fileSystem:frameRange")
            ])

        path = dialogue.waitForPath(
            parentWindow=self.ancestor(GafferUI.Window))
        if not path:
            return

        with Gaffer.UndoScope(self.getPlug().ancestor(Gaffer.ScriptNode)):
            self.__images().addChild(
                GafferImage.Catalogue.Image.load(str(path)))
            self.getPlug().setValue(len(self.__images()) - 1)
Beispiel #17
0
    def __exportClicked(self, *unused):

        bookmarks = GafferUI.Bookmarks.acquire(self, category="image")
        path = Gaffer.FileSystemPath(bookmarks.getDefault(self))

        path.setFilter(
            Gaffer.FileSystemPath.createStandardFilter(
                GafferImage.ImageReader.supportedExtensions(),
                "Show only image files",
                includeSequenceFilter=True,
            ))

        dialogue = GafferUI.PathChooserDialogue(path,
                                                title="Export image",
                                                confirmLabel="Export",
                                                leaf=True,
                                                bookmarks=bookmarks)

        path = dialogue.waitForPath(
            parentWindow=self.ancestor(GafferUI.Window))
        if not path:
            return

        index = self.__indexFromSelection()
        with GafferUI.ErrorDialogue.ErrorHandler(
                parentWindow=self.ancestor(GafferUI.Window)):
            self.__images()[index].save(str(path))
Beispiel #18
0
    def _run(self, args):

        if len(args["files"]) < 1 or len(args["files"]) > 2:

            raise Exception("Must view exactly one file.")

        self.__window = GafferUI.Window(
            title="Gaffer Viewer", sizeMode=GafferUI.Window.SizeMode.Manual)

        self.__window.setChild(
            GafferUI.CompoundPathPreview(
                Gaffer.FileSystemPath(args["files"][0])))

        self.__closedConnection = self.__window.closedSignal().connect(
            Gaffer.WeakMethod(self.__closed))

        ## \todo The window doesn't appear without this naughtiness. I think we either need to
        # add a similar method in the public interface, or maybe make a SizeConstraintContainer
        # or something along those lines.
        self.__window._qtWidget().setMinimumSize(300, 200)
        self.__window.setVisible(True)

        GafferUI.EventLoop.mainEventLoop().start()

        return 0
Beispiel #19
0
def __importReference(menu, node):

    bookmarks = GafferUI.Bookmarks.acquire(node, category="reference")

    path = Gaffer.FileSystemPath(bookmarks.getDefault(menu))
    path.setFilter(Gaffer.FileSystemPath.createStandardFilter(["grf"]))

    window = menu.ancestor(GafferUI.Window)
    dialogue = GafferUI.PathChooserDialogue(path,
                                            title="Import reference",
                                            confirmLabel="Import",
                                            leaf=True,
                                            valid=True,
                                            bookmarks=bookmarks)
    path = dialogue.waitForPath(parentWindow=window)

    if not path:
        return

    scriptNode = node.ancestor(Gaffer.ScriptNode)
    with GafferUI.ErrorDialogue.ErrorHandler(title="Error Importing Reference",
                                             closeLabel="Oy vey",
                                             parentWindow=window):
        with Gaffer.UndoScope(scriptNode):
            scriptNode.executeFile(str(path),
                                   parent=node,
                                   continueOnError=True)
Beispiel #20
0
def _waitForFileName( initialFileName="", parentWindow=None ) :

	if initialFileName :
		path = Gaffer.FileSystemPath( os.path.dirname( os.path.abspath( initialFileName ) ) )
	else :
		path = Gaffer.FileSystemPath( os.getcwd() )

	path.setFilter( Gaffer.FileSystemPath.createStandardFilter( [ "grf" ] ) )

	dialogue = GafferUI.PathChooserDialogue( path, title = "Load reference", confirmLabel = "Load" )
	path = dialogue.waitForPath( parentWindow = parentWindow )
	
	if not path :
		return ""
	
	return str( path )
Beispiel #21
0
    def __init__(self,
                 plug,
                 path=None,
                 pathChooserDialogueKeywords=None,
                 **kw):

        self.__row = GafferUI.ListContainer(
            GafferUI.ListContainer.Orientation.Horizontal, spacing=4)

        GafferUI.PlugValueWidget.__init__(self, self.__row, plug, **kw)

        self.__path = path if path is not None else Gaffer.FileSystemPath()

        self.__pathChooserDialogueKeywords = pathChooserDialogueKeywords

        pathWidget = GafferUI.PathWidget(self.__path)
        self._addPopupMenu(pathWidget)
        self.__row.append(pathWidget)

        button = GafferUI.Button(image="pathChooser.png", hasFrame=False)
        self.__buttonClickedConnection = button.clickedSignal().connect(
            Gaffer.WeakMethod(self.__buttonClicked))
        self.__row.append(button)

        self.__editingFinishedConnection = pathWidget.editingFinishedSignal(
        ).connect(Gaffer.WeakMethod(self.__setPlugValue))

        self._updateFromPlug()
    def testPropertyNames(self):

        p = Gaffer.FileSystemPath(self.temporaryDirectory())

        a = p.propertyNames()
        self.assertTrue(isinstance(a, list))

        self.assertTrue("fileSystem:group" in a)
        self.assertTrue("fileSystem:owner" in a)
        self.assertTrue("fileSystem:modificationTime" in a)
        self.assertTrue("fileSystem:size" in a)

        self.assertTrue("fileSystem:frameRange" not in a)
        p = Gaffer.FileSystemPath(self.temporaryDirectory(),
                                  includeSequences=True)
        self.assertTrue("fileSystem:frameRange" in p.propertyNames())
Beispiel #23
0
def __exportOSLShader(nodeEditor, node):

    bookmarks = GafferUI.Bookmarks.acquire(node, category="shader")

    path = Gaffer.FileSystemPath(bookmarks.getDefault(nodeEditor))
    path.setFilter(Gaffer.FileSystemPath.createStandardFilter(["osl"]))

    dialogue = GafferUI.PathChooserDialogue(path,
                                            title="Export OSL Shader",
                                            confirmLabel="Export",
                                            leaf=True,
                                            bookmarks=bookmarks)
    path = dialogue.waitForPath(
        parentWindow=nodeEditor.ancestor(GafferUI.Window))

    if not path:
        return

    path = str(path)
    if not path.endswith(".osl"):
        path += ".osl"

    with GafferUI.ErrorDialogue.ErrorHandler(title="Error Exporting Shader",
                                             parentWindow=nodeEditor.ancestor(
                                                 GafferUI.Window)):
        with open(path, "w") as f:
            with nodeEditor.getContext():
                f.write(
                    node.source(os.path.splitext(os.path.basename(path))[0]))
Beispiel #24
0
def __pathAndBookmarks( scriptWindow ) :

	bookmarks = GafferUI.Bookmarks.acquire(
		scriptWindow,
		pathType = Gaffer.FileSystemPath,
		category = "script",
	)

	currentFileName = scriptWindow.scriptNode()["fileName"].getValue()
	if currentFileName :
		path = Gaffer.FileSystemPath( os.path.dirname( os.path.abspath( currentFileName ) ) )
	else :
		path = Gaffer.FileSystemPath( bookmarks.getDefault( scriptWindow ) )

	path.setFilter( Gaffer.FileSystemPath.createStandardFilter( [ "gfr" ] ) )

	return path, bookmarks
Beispiel #25
0
	def __init__( self, data=None, editable=True, header=False, showIndices=True, path=None, pathChooserDialogueKeywords={}, **kw ) :

		GafferUI.VectorDataWidget.__init__( self, data=data, editable=editable, header=header, showIndices=showIndices, **kw )

		self.__path = path if path is not None else Gaffer.FileSystemPath( "/" )
		self.__pathChooserDialogueKeywords = pathChooserDialogueKeywords

		self.__editConnection = self.editSignal().connect( Gaffer.WeakMethod( self.__edit ) )
    def testRelativePath(self):

        os.chdir(self.temporaryDirectory())

        with open(self.temporaryDirectory() + "/a", "w") as f:
            f.write("AAAA")

        p = Gaffer.FileSystemPath("a")

        self.assertEqual(str(p), "a")
        self.assertFalse(p.isEmpty())
        self.assertTrue(p.isValid())

        p2 = Gaffer.FileSystemPath("nonexistent")

        self.assertEqual(str(p2), "nonexistent")
        self.assertFalse(p2.isEmpty())
        self.assertFalse(p2.isValid())
Beispiel #27
0
    def testInfoOfInvalidPath(self):

        fp = Gaffer.FileSystemPath("/iSurelyDontExist")
        self.assertEqual(fp.isValid(), False)
        self.assertEqual(fp.info(), None)

        sp = Gaffer.SequencePath(fp)
        self.assertEqual(sp.isValid(), False)
        self.assertEqual(sp.info(), None)
Beispiel #28
0
    def testPropertyNames(self):

        p = Gaffer.FileSystemPath(self.__dir)

        a = p.propertyNames()
        self.assertTrue(isinstance(a, list))

        self.assertTrue("fileSystem:group" in a)
        self.assertTrue("fileSystem:owner" in a)
        self.assertTrue("fileSystem:modificationTime" in a)
        self.assertTrue("fileSystem:size" in a)
    def testGroup(self):

        p = Gaffer.FileSystemPath(self.temporaryDirectory())
        p.append("t")

        with open(str(p), "w") as f:
            f.write("AAAA")

        g = p.property("fileSystem:group")
        self.assertTrue(isinstance(g, str))
        self.assertEqual(g, grp.getgrgid(os.stat(str(p)).st_gid).gr_name)
    def testOwner(self):

        p = Gaffer.FileSystemPath(self.temporaryDirectory())
        p.append("t")

        with open(str(p), "w") as f:
            f.write("AAAA")

        o = p.property("fileSystem:owner")
        self.assertTrue(isinstance(o, str))
        self.assertEqual(o, pwd.getpwuid(os.stat(str(p)).st_uid).pw_name)