Esempio n. 1
0
	def __templatesOutliner_view_selectionModel__selectionChanged(self, selectedItems, deselectedItems):
		"""
		This method is triggered when **templatesOutliner.view** Model selection has changed.

		:param selectedItems: Selected items. ( QItemSelection )
		:param deselectedItems: Deselected items. ( QItemSelection )
		"""

		selectedTemplates = self.__templatesOutliner.getSelectedTemplates()
		template = foundations.common.getFirstItem(selectedTemplates)
		if not (template and foundations.common.pathExists(template.path)):
			return

		LOGGER.debug("> Parsing '{0}' Template for '{1}' section.".format(template.name,
																	self.__templateRemoteConnectionSection))
		templateSectionsFileParser = SectionsFileParser(template.path)
		templateSectionsFileParser.read() and templateSectionsFileParser.parse(
		rawSections=(self.__templateScriptSection))

		if not self.__templateRemoteConnectionSection in templateSectionsFileParser.sections:
			return

		LOGGER.debug("> {0}' section found.".format(self.__templateRemoteConnectionSection))
		connectionType = foundations.parsers.getAttributeCompound("ConnectionType",
		templateSectionsFileParser.getValue("ConnectionType", self.__templateRemoteConnectionSection))
		if connectionType.value == "Socket":
			LOGGER.debug("> Remote connection type: 'Socket'.")
			self.__tcpClientUi.address = foundations.parsers.getAttributeCompound("DefaultAddress",
			templateSectionsFileParser.getValue("DefaultAddress",
												self.__templateRemoteConnectionSection)).value
			self.__tcpClientUi.port = int(foundations.parsers.getAttributeCompound("DefaultPort",
			templateSectionsFileParser.getValue("DefaultPort",
												self.__templateRemoteConnectionSection)).value)
		elif connectionType.value == "Win32":
			LOGGER.debug("> Remote connection: 'Win32'.")
Esempio n. 2
0
	def getIblSetImagesPaths(self, iblSet, imageType):
		"""
		This method gets Ibl Set images paths.

		:param iblSet: Ibl Set. ( IblSet )
		:param imageType: Image type. ( String )
		:return: Images paths. ( List )
		"""

		imagePaths = []
		if imageType == "Background":
			path = iblSet.backgroundImage
			path and imagePaths.append(path)
		elif imageType == "Lighting":
			path = iblSet.lightingImage
			path and imagePaths.append(path)
		elif imageType == "Reflection":
			path = iblSet.reflectionImage
			path and imagePaths.append(path)
		elif imageType == "Plate":
			if foundations.common.pathExists(iblSet.path):
				LOGGER.debug("> Parsing Inspector Ibl Set file: '{0}'.".format(iblSet))
				sectionsFileParser = SectionsFileParser(iblSet.path)
				sectionsFileParser.read() and sectionsFileParser.parse()
				for section in sectionsFileParser.sections:
					if re.search(r"Plate\d+", section):
						imagePaths.append(os.path.normpath(os.path.join(os.path.dirname(iblSet.path),
																	sectionsFileParser.getValue("PLATEfile", section))))

		for path in imagePaths[:]:
			if not foundations.common.pathExists(path):
				imagePaths.remove(path) and LOGGER.warning(
				"!> {0} | '{1}' image file doesn't exists and will be skipped!".format(self.__class__.__name__, path))
		return imagePaths
Esempio n. 3
0
	def testRawSections(self):
		"""
		This method tests :class:`foundations.parsers.SectionsFileParser` class raw sections consistencies.
		"""

		sectionsFileParser = SectionsFileParser(TEMPLATE_FILE)
		sectionsFileParser.read() and sectionsFileParser.parse(rawSections=("Script",))
		self.assertListEqual(sectionsFileParser.sections["Script"]["_rawSectionContent"][0:10], SCRIPT_RAW_SECTION)
Esempio n. 4
0
	def sendLoaderScriptToSoftware(self, template, loaderScriptPath):
		"""
		This method sends the Loader Script to associated 3d package.

		:param template: Template. ( Template )
		:param loaderScriptPath: Loader Script path. ( String )
		:return: Method success. ( Boolean )
		"""

		LOGGER.info("{0} | Starting remote connection!".format(self.__class__.__name__))
		templateSectionsFileParser = SectionsFileParser(template.path)
		templateSectionsFileParser.read() and templateSectionsFileParser.parse(
		rawSections=(self.__templateScriptSection))
		connectionType = foundations.parsers.getAttributeCompound("ConnectionType",
		templateSectionsFileParser.getValue("ConnectionType", self.__templateRemoteConnectionSection))

		if connectionType.value == "Socket":
			try:
				connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
				connection.settimeout(2.5)
				connection.connect((foundations.strings.toString(self.__tcpClientUi.address), 	self.__tcpClientUi.port))
				socketCommand = foundations.parsers.getAttributeCompound("ExecutionCommand",
								templateSectionsFileParser.getValue("ExecutionCommand",
								self.__templateRemoteConnectionSection)).value.replace("$loaderScriptPath",
																						loaderScriptPath)
				LOGGER.debug("> Current socket command: '%s'.", socketCommand)
				connection.send(socketCommand)
				self.__engine.notificationsManager.notify(
				"{0} | Socket connection command dispatched!".format(self.__class__.__name__))
				dataBack = connection.recv(4096)
				LOGGER.debug("> Received from connection: '{0}'.".format(dataBack))
				connection.close()
				LOGGER.info("{0} | Closing remote connection!".format(self.__class__.__name__))
			except socket.timeout as error:
				LOGGER.info("{0} | Closing remote connection on timeout!".format(self.__class__.__name__))
			except Exception as error:
				raise sibl_gui.exceptions.SocketConnectionError(
				"{0} | Socket connection error: '{1}'!".format(self.__class__.__name__, error))
		elif connectionType.value == "Win32":
			if platform.system() == "Windows" or platform.system() == "Microsoft":
				try:
					import win32com.client
					connection = win32com.client.Dispatch(foundations.parsers.getAttributeCompound("TargetApplication",
								templateSectionsFileParser.getValue("TargetApplication",
																	self.__templateRemoteConnectionSection)).value)
					connection._FlagAsMethod(self.__win32ExecutionMethod)
					connectionCommand = foundations.parsers.getAttributeCompound("ExecutionCommand",
										templateSectionsFileParser.getValue("ExecutionCommand",
										self.__templateRemoteConnectionSection)).value.replace("$loaderScriptPath",
																								loaderScriptPath)
					LOGGER.debug("> Current connection command: '%s'.", connectionCommand)
					getattr(connection, self.__win32ExecutionMethod)(connectionCommand)
					self.__engine.notificationsManager.notify(
					"{0} | Win32 connection command dispatched!".format(self.__class__.__name__))
				except Exception as error:
					raise sibl_gui.exceptions.Win32OLEServerConnectionError(
					"{0} | Win32 OLE server connection error: '{1}'!".format(self.__class__.__name__, error))
		return True
	def __views_setUi(self):
		"""
		This method sets the Views.
		"""

		selectedTemplates = self.__templatesOutliner.getSelectedTemplates()
		template = foundations.common.getFirstItem(selectedTemplates)
		if not (template and foundations.common.pathExists(template.path)):
			for view in self.__views:
				self.__view_clearUi(view)
			return

		LOGGER.debug("> Attempting to read '{0}' Template settings file.".format(template.name))
		commonAttributesOverrides = {}
		additionalAttributesOverrides = {}
		templateSettingsDirectory = os.path.join(self.__templatesSettingsDirectory, template.software, template.name)
		currentTemplateSettingsDirectory = os.path.join(templateSettingsDirectory, template.release)
		self.__templateSettingsFile = os.path.join(templateSettingsDirectory,
										template.release,
										os.path.basename(template.path))

		not foundations.common.pathExists(currentTemplateSettingsDirectory) and \
		foundations.io.setDirectory(currentTemplateSettingsDirectory)

		templateSettingsFile = None
		if foundations.common.pathExists(self.__templateSettingsFile):
			templateSettingsFile = self.__templateSettingsFile
		else:
			for version in sorted((
							path for path in os.listdir(templateSettingsDirectory)
							if re.search(r"\d\.\d\.\d", path)), reverse=True, key=lambda x:(foundations.strings.getVersionRank(x))):
				path = os.path.join(templateSettingsDirectory, version, os.path.basename(template.path))
				if foundations.common.pathExists(path):
					templateSettingsFile = path
					break

		if templateSettingsFile:
			LOGGER.debug("> Accessing '{0}' Template settings file: '{1}'.".format(template.name, templateSettingsFile))
			templateSettingsSectionsFileParser = SectionsFileParser(templateSettingsFile)
			templateSettingsSectionsFileParser.read() and templateSettingsSectionsFileParser.parse()
			commonAttributesOverrides.update(
			templateSettingsSectionsFileParser.sections[self.__templateCommonAttributesSection])
			additionalAttributesOverrides.update(
			templateSettingsSectionsFileParser.sections[self.__templateAdditionalAttributesSection])
		else:
			LOGGER.debug("> No Template settings file found for : '{0}'.".format(template.name))

		LOGGER.debug("> Parsing '{0}' Template for '{1}' and '{2}' section.".format(
		template.name, self.__templateCommonAttributesSection, self.__templateAdditionalAttributesSection))
		templateSectionsFileParser = SectionsFileParser(template.path)
		templateSectionsFileParser.read() and templateSectionsFileParser.parse(
		rawSections=(self.__templateScriptSection))

		self.__view_setUi(templateSectionsFileParser.sections.get(self.__templateCommonAttributesSection, {}),
								self.__commonView, commonAttributesOverrides)
		self.__view_setUi(templateSectionsFileParser.sections.get(self.__templateAdditionalAttributesSection, {}),
								self.__additionalView, additionalAttributesOverrides)
Esempio n. 6
0
    def testDefaultsSection(self):
        """
		This method tests :class:`foundations.parsers.SectionsFileParser` class default section consistency.
		"""

        sectionsFileParser = SectionsFileParser(DEFAULTS_FILE)
        sectionsFileParser.read() and sectionsFileParser.parse()
        for section in DEFAULTS_FILE_SECTIONS_AND_ATTRIBUTES:
            self.assertIn(section, sectionsFileParser.sections)
Esempio n. 7
0
	def testDefaultsSection(self):
		"""
		This method tests :class:`foundations.parsers.SectionsFileParser` class default section consistency.
		"""

		sectionsFileParser = SectionsFileParser(DEFAULTS_FILE)
		sectionsFileParser.read() and sectionsFileParser.parse()
		for section in DEFAULTS_FILE_SECTIONS_AND_ATTRIBUTES:
			self.assertIn(section, sectionsFileParser.sections)
Esempio n. 8
0
	def testSectionExists(self):
		"""
		This method tests :meth:`foundations.parsers.SectionsFileParser.sectionExists` method.
		"""

		for type, file in STANDARD_FILES.iteritems():
			sectionsFileParser = SectionsFileParser(file)
			sectionsFileParser.read() and sectionsFileParser.parse(rawSections=STANDARD_FILES_RAW_SECTIONS[type])
			self.assertTrue(sectionsFileParser.sectionExists(STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type].keys()[0]))
			self.assertFalse(sectionsFileParser.sectionExists("Unknown"))
Esempio n. 9
0
	def testParsingErrors(self):
		"""
		This method tests :class:`foundations.parsers.SectionsFileParser` class parsing errors consistencies.
		"""

		sectionsFileParser = SectionsFileParser(PARSING_ERRORS_FILE)
		sectionsFileParser.read() and sectionsFileParser.parse(raiseParsingErrors=False)
		for exception in sectionsFileParser.parsingErrors:
			self.assertIn(exception.line, PARSING_ERRORS_LINES_AND_VALUES)
			self.assertEqual(exception.value, PARSING_ERRORS_LINES_AND_VALUES[exception.line])
Esempio n. 10
0
    def testRawSections(self):
        """
		This method tests :class:`foundations.parsers.SectionsFileParser` class raw sections consistencies.
		"""

        sectionsFileParser = SectionsFileParser(TEMPLATE_FILE)
        sectionsFileParser.read() and sectionsFileParser.parse(
            rawSections=("Script", ))
        self.assertListEqual(
            sectionsFileParser.sections["Script"]["_rawSectionContent"][0:10],
            SCRIPT_RAW_SECTION)
	def initializeProfile(self):
		"""
		This method gets initializes the Component Profile.
		
		:return: Method success. ( Boolean )
		"""

		LOGGER.debug("> Building '{0}' profile.".format(self.__file))

		sectionsFileParser = SectionsFileParser(self.__file)
		sectionsFileParser.read() and sectionsFileParser.parse()

		if sectionsFileParser.sections:
			fileStructureParsingError = lambda attribute: foundations.exceptions.FileStructureParsingError(
			"{0} | No '{1}' attribute found, '{2}' file structure seems invalid!".format(
			self.__class__.__name__, attribute, self.__file))

			self.__directory = os.path.dirname(self.__file)
			self.__name = sectionsFileParser.getValue("Name", "Component", default=None)
			if self.__name is None:
				raise fileStructureParsingError("Name")

			self.__title = sectionsFileParser.getValue("Title", "Component", default=None)
			if self.__title is None:
				self.__title = self.__name

			self.__package = sectionsFileParser.getValue("Module", "Component", default=None)
			if self.__package is None:
				raise fileStructureParsingError("Module")

			self.__attribute = sectionsFileParser.getValue("Object", "Component", default=None)
			if self.__attribute is None:
				raise fileStructureParsingError("Object")

			self.__require = sectionsFileParser.getValue("Require", "Component", default=None)
			self.__require = list() if self.__require is None else self.__require.split("|")

			self.__version = sectionsFileParser.getValue("Version", "Component", default=None)
			if self.__version is None:
				raise fileStructureParsingError("Version")

			self.__author = sectionsFileParser.getValue("Author", "Informations", default=None)

			self.__email = sectionsFileParser.getValue("Email", "Informations", default=None)

			self.__url = sectionsFileParser.getValue("Url", "Informations", default=None)

			self.__description = sectionsFileParser.getValue("Description", "Informations", default=None)

			return True
		else:
			raise foundations.exceptions.FileStructureParsingError(
			"{0} | No sections found, '{1}' file structure seems invalid!".format(self.__class__.__name__, self.__file))
Esempio n. 12
0
	def testStripQuotationMarkers(self):
		"""
		This method tests :class:`foundations.parsers.SectionsFileParser` class quotation markers consistencies.
		"""

		sectionsFileParser = SectionsFileParser(STRIPPING_FILE)
		sectionsFileParser.read() and sectionsFileParser.parse(stripQuotationMarkers=False)
		for section in STRIPPING_FILE_SECTIONS_AND_ATTRIBUTES_STRIPPED:
			self.assertIn(section, sectionsFileParser.sections)
			for attribute, value in STRIPPING_FILE_SECTIONS_AND_ATTRIBUTES_STRIPPED[section].iteritems():
				self.assertIn(attribute, sectionsFileParser.sections[section])
				self.assertIn(value, sectionsFileParser.sections[section].itervalues())
Esempio n. 13
0
	def testNamespaces(self):
		"""
		This method tests :class:`foundations.parsers.SectionsFileParser` class namespaces consistencies.
		"""

		for type, file in STANDARD_FILES.iteritems():
			sectionsFileParser = SectionsFileParser(file)
			sectionsFileParser.read() and sectionsFileParser.parse(rawSections=STANDARD_FILES_RAW_SECTIONS[type],
																	namespaces=False)
			for section in STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type]:
				for attribute in sectionsFileParser.sections[section]:
					self.assertIn(attribute, STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type][section]["stripped"])
Esempio n. 14
0
    def testParsingErrors(self):
        """
		This method tests :class:`foundations.parsers.SectionsFileParser` class parsing errors consistencies.
		"""

        sectionsFileParser = SectionsFileParser(PARSING_ERRORS_FILE)
        sectionsFileParser.read() and sectionsFileParser.parse(
            raiseParsingErrors=False)
        for exception in sectionsFileParser.parsingErrors:
            self.assertIn(exception.line, PARSING_ERRORS_LINES_AND_VALUES)
            self.assertEqual(exception.value,
                             PARSING_ERRORS_LINES_AND_VALUES[exception.line])
Esempio n. 15
0
	def testSections(self):
		"""
		This method tests :class:`foundations.parsers.SectionsFileParser` class sections consistencies.
		"""

		for type, file in STANDARD_FILES.iteritems():
			sectionsFileParser = SectionsFileParser(file)
			sectionsFileParser.read() and sectionsFileParser.parse(rawSections=STANDARD_FILES_RAW_SECTIONS[type])
			self.assertListEqual(sectionsFileParser.sections.keys(), STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type].keys())
			sectionsFileParser.parse(orderedDictionary=False, rawSections=STANDARD_FILES_RAW_SECTIONS[type])
			for section in STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type]:
				self.assertIn(section, sectionsFileParser.sections)
Esempio n. 16
0
	def testAttributeExists(self):
		"""
		This method tests :meth:`foundations.parsers.SectionsFileParser.attributeExists` method.
		"""

		for type, file in STANDARD_FILES.iteritems():
			sectionsFileParser = SectionsFileParser(file)
			sectionsFileParser.read() and sectionsFileParser.parse(False, rawSections=STANDARD_FILES_RAW_SECTIONS[type])
			for attribute in RANDOM_ATTRIBUTES[type]:
				self.assertTrue(sectionsFileParser.attributeExists(attribute, namespace.getNamespace(attribute,
																									rootOnly=True)))
				self.assertFalse(sectionsFileParser.attributeExists("Unknown", namespace.getNamespace(attribute,
																									rootOnly=True)))
Esempio n. 17
0
	def testGetAllAttributes(self):
		"""
		This method tests :meth:`foundations.parsers.SectionsFileParser.getAllAttributes` method.
		"""

		for type, file in STANDARD_FILES.iteritems():
			sectionsFileParser = SectionsFileParser(file)
			sectionsFileParser.read() and sectionsFileParser.parse(rawSections=STANDARD_FILES_RAW_SECTIONS[type])
			attributes = sectionsFileParser.getAllAttributes()
			testsAttributes = []
			for section in STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type]:
				testsAttributes.extend(STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type][section]["namespaced"])
			self.assertListEqual(attributes.keys(), testsAttributes)
Esempio n. 18
0
    def testSectionExists(self):
        """
		This method tests :meth:`foundations.parsers.SectionsFileParser.sectionExists` method.
		"""

        for type, file in STANDARD_FILES.iteritems():
            sectionsFileParser = SectionsFileParser(file)
            sectionsFileParser.read() and sectionsFileParser.parse(
                rawSections=STANDARD_FILES_RAW_SECTIONS[type])
            self.assertTrue(
                sectionsFileParser.sectionExists(
                    STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type].keys()[0]))
            self.assertFalse(sectionsFileParser.sectionExists("Unknown"))
def listTemplatesReleases():
	"""
	This definition lists Templates releases.
	"""

	for template in sorted(list(foundations.walkers.filesWalker(os.path.normpath(TEMPLATES_PATH), (TEMPLATES_EXTENSION,), ("\._",)))):
		sectionsFileParser = SectionsFileParser(template)
		sectionsFileParser.read() and sectionsFileParser.parse(rawSections=("Script",))

		LOGGER.info("{0} | '{1}': '{2}'.".format(listTemplatesReleases.__name__,
												foundations.strings.getSplitextBasename(template),
												foundations.parsers.getAttributeCompound("Release",
												sectionsFileParser.getValue("Release", "Template")).value))
Esempio n. 20
0
	def testComments(self):
		"""
		This method tests :class:`foundations.parsers.SectionsFileParser` class comments consistencies.
		"""

		for type, file in STANDARD_FILES.iteritems():
			sectionsFileParser = SectionsFileParser(file)
			sectionsFileParser.read() and sectionsFileParser.parse(rawSections=STANDARD_FILES_RAW_SECTIONS[type])
			self.assertEqual(sectionsFileParser.comments, OrderedDict())
			sectionsFileParser.parse(rawSections=STANDARD_FILES_RAW_SECTIONS[type], stripComments=False)
			for comment, value in RANDOM_COMMENTS[type].iteritems():
				self.assertIn(comment, sectionsFileParser.comments)
				self.assertEqual(value["id"], sectionsFileParser.comments[comment]["id"])
Esempio n. 21
0
	def testGetAttributes(self):
		"""
		This method tests :meth:`foundations.parsers.SectionsFileParser.getAttributes` method.
		"""

		for type, file in STANDARD_FILES.iteritems():
			sectionsFileParser = SectionsFileParser(file)
			sectionsFileParser.read() and sectionsFileParser.parse(rawSections=STANDARD_FILES_RAW_SECTIONS[type])
			for section in STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type]:
				self.assertListEqual(sectionsFileParser.getAttributes(
				section, orderedDictionary=True, stripNamespaces=True).keys(),
				STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type][section]["stripped"])
				self.assertListEqual(sectionsFileParser.getAttributes(section).keys(),
				STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type][section]["namespaced"])
Esempio n. 22
0
    def testNamespaces(self):
        """
		This method tests :class:`foundations.parsers.SectionsFileParser` class namespaces consistencies.
		"""

        for type, file in STANDARD_FILES.iteritems():
            sectionsFileParser = SectionsFileParser(file)
            sectionsFileParser.read() and sectionsFileParser.parse(
                rawSections=STANDARD_FILES_RAW_SECTIONS[type],
                namespaces=False)
            for section in STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type]:
                for attribute in sectionsFileParser.sections[section]:
                    self.assertIn(
                        attribute, STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type]
                        [section]["stripped"])
Esempio n. 23
0
    def testStripQuotationMarkers(self):
        """
		This method tests :class:`foundations.parsers.SectionsFileParser` class quotation markers consistencies.
		"""

        sectionsFileParser = SectionsFileParser(STRIPPING_FILE)
        sectionsFileParser.read() and sectionsFileParser.parse(
            stripQuotationMarkers=False)
        for section in STRIPPING_FILE_SECTIONS_AND_ATTRIBUTES_STRIPPED:
            self.assertIn(section, sectionsFileParser.sections)
            for attribute, value in STRIPPING_FILE_SECTIONS_AND_ATTRIBUTES_STRIPPED[
                    section].iteritems():
                self.assertIn(attribute, sectionsFileParser.sections[section])
                self.assertIn(
                    value, sectionsFileParser.sections[section].itervalues())
Esempio n. 24
0
    def testGetAllAttributes(self):
        """
		This method tests :meth:`foundations.parsers.SectionsFileParser.getAllAttributes` method.
		"""

        for type, file in STANDARD_FILES.iteritems():
            sectionsFileParser = SectionsFileParser(file)
            sectionsFileParser.read() and sectionsFileParser.parse(
                rawSections=STANDARD_FILES_RAW_SECTIONS[type])
            attributes = sectionsFileParser.getAllAttributes()
            testsAttributes = []
            for section in STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type]:
                testsAttributes.extend(
                    STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type][section]
                    ["namespaced"])
            self.assertListEqual(attributes.keys(), testsAttributes)
Esempio n. 25
0
	def testParse(self):
		"""
		This method tests :meth:`foundations.parsers.SectionsFileParser.parse` method.
		"""

		for type, file in STANDARD_FILES.iteritems():
			sectionsFileParser = SectionsFileParser(file)
			sectionsFileParser.read()
			parseSuccess = sectionsFileParser.parse(rawSections=STANDARD_FILES_RAW_SECTIONS[type])
			self.assertTrue(parseSuccess)

			self.assertIsInstance(sectionsFileParser.sections, OrderedDict)
			self.assertIsInstance(sectionsFileParser.comments, OrderedDict)
			sectionsFileParser.parse(orderedDictionary=False, rawSections=STANDARD_FILES_RAW_SECTIONS[type])
			self.assertIsInstance(sectionsFileParser.sections, dict)
			self.assertIsInstance(sectionsFileParser.comments, dict)
Esempio n. 26
0
	def testGetValue(self):
		"""
		This method tests :meth:`foundations.parsers.SectionsFileParser.getValue` method.
		"""

		for type, file in STANDARD_FILES.iteritems():
			sectionsFileParser = SectionsFileParser(file)
			sectionsFileParser.read() and sectionsFileParser.parse(False, rawSections=STANDARD_FILES_RAW_SECTIONS[type])
			for attribute, value in RANDOM_ATTRIBUTES[type].iteritems():
				self.assertIsInstance(sectionsFileParser.getValue(attribute, namespace.getNamespace(attribute,
																									rootOnly=True)), str)
				self.assertIsInstance(sectionsFileParser.getValue(attribute, namespace.getNamespace(attribute,
																									rootOnly=True),
																									encode=True), unicode)
				self.assertEqual(sectionsFileParser.getValue(attribute, namespace.getNamespace(attribute,
																								rootOnly=True)), value)
Esempio n. 27
0
    def testSections(self):
        """
		This method tests :class:`foundations.parsers.SectionsFileParser` class sections consistencies.
		"""

        for type, file in STANDARD_FILES.iteritems():
            sectionsFileParser = SectionsFileParser(file)
            sectionsFileParser.read() and sectionsFileParser.parse(
                rawSections=STANDARD_FILES_RAW_SECTIONS[type])
            self.assertListEqual(
                sectionsFileParser.sections.keys(),
                STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type].keys())
            sectionsFileParser.parse(
                orderedDictionary=False,
                rawSections=STANDARD_FILES_RAW_SECTIONS[type])
            for section in STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type]:
                self.assertIn(section, sectionsFileParser.sections)
Esempio n. 28
0
    def testComments(self):
        """
		This method tests :class:`foundations.parsers.SectionsFileParser` class comments consistencies.
		"""

        for type, file in STANDARD_FILES.iteritems():
            sectionsFileParser = SectionsFileParser(file)
            sectionsFileParser.read() and sectionsFileParser.parse(
                rawSections=STANDARD_FILES_RAW_SECTIONS[type])
            self.assertEqual(sectionsFileParser.comments, OrderedDict())
            sectionsFileParser.parse(
                rawSections=STANDARD_FILES_RAW_SECTIONS[type],
                stripComments=False)
            for comment, value in RANDOM_COMMENTS[type].iteritems():
                self.assertIn(comment, sectionsFileParser.comments)
                self.assertEqual(value["id"],
                                 sectionsFileParser.comments[comment]["id"])
Esempio n. 29
0
	def setContent(self):
		"""
		This method initializes the class attributes.

		:return: Method success. ( Boolean )
		"""

		sectionsFileParser = SectionsFileParser(self.path)
		sectionsFileParser.read() and sectionsFileParser.parse(rawSections=("Script"))

		if sectionsFileParser.sections:
			self.helpFile = foundations.parsers.getAttributeCompound("HelpFile",
							sectionsFileParser.getValue("HelpFile", "Template")).value and \
							os.path.join(os.path.dirname(self.path),
										foundations.parsers.getAttributeCompound("HelpFile",
										sectionsFileParser.getValue("HelpFile", 	"Template")).value) or None
			self.title = foundations.parsers.getAttributeCompound("Name",
						sectionsFileParser.getValue("Name", 	"Template")).value
			self.author = foundations.parsers.getAttributeCompound("Author",
						sectionsFileParser.getValue("Author", "Template")).value
			self.email = foundations.parsers.getAttributeCompound("Email",
						sectionsFileParser.getValue("Email", "Template")).value
			self.url = foundations.parsers.getAttributeCompound("Url",
						sectionsFileParser.getValue("Url", "Template")).value
			self.release = foundations.parsers.getAttributeCompound("Release",
							sectionsFileParser.getValue("Release", "Template")).value
			self.date = foundations.parsers.getAttributeCompound("Date",
						sectionsFileParser.getValue("Date", "Template")).value
			self.software = foundations.parsers.getAttributeCompound("Software",
							sectionsFileParser.getValue("Software", "Template")).value
			self.version = foundations.parsers.getAttributeCompound("Version",
							sectionsFileParser.getValue("Version", "Template")).value
			self.renderer = foundations.parsers.getAttributeCompound("Renderer",
							sectionsFileParser.getValue("Renderer", "Template")).value
			self.outputScript = foundations.parsers.getAttributeCompound("OutputScript",
								sectionsFileParser.getValue("OutputScript", "Template")).value
			self.comment = foundations.parsers.getAttributeCompound("Comment",
							sectionsFileParser.getValue("Comment", "Template")).value

			return True

		else:
			raise foundations.exceptions.FileStructureParsingError(
			"{0} | '{1}' no sections found, file structure seems invalid!".format(self.__class__.__name__, self.path))
Esempio n. 30
0
    def testParse(self):
        """
		This method tests :meth:`foundations.parsers.SectionsFileParser.parse` method.
		"""

        for type, file in STANDARD_FILES.iteritems():
            sectionsFileParser = SectionsFileParser(file)
            sectionsFileParser.read()
            parseSuccess = sectionsFileParser.parse(
                rawSections=STANDARD_FILES_RAW_SECTIONS[type])
            self.assertTrue(parseSuccess)

            self.assertIsInstance(sectionsFileParser.sections, OrderedDict)
            self.assertIsInstance(sectionsFileParser.comments, OrderedDict)
            sectionsFileParser.parse(
                orderedDictionary=False,
                rawSections=STANDARD_FILES_RAW_SECTIONS[type])
            self.assertIsInstance(sectionsFileParser.sections, dict)
            self.assertIsInstance(sectionsFileParser.comments, dict)
Esempio n. 31
0
    def testAttributeExists(self):
        """
		This method tests :meth:`foundations.parsers.SectionsFileParser.attributeExists` method.
		"""

        for type, file in STANDARD_FILES.iteritems():
            sectionsFileParser = SectionsFileParser(file)
            sectionsFileParser.read() and sectionsFileParser.parse(
                False, rawSections=STANDARD_FILES_RAW_SECTIONS[type])
            for attribute in RANDOM_ATTRIBUTES[type]:
                self.assertTrue(
                    sectionsFileParser.attributeExists(
                        attribute,
                        foundations.namespace.getNamespace(attribute,
                                                           rootOnly=True)))
                self.assertFalse(
                    sectionsFileParser.attributeExists(
                        "Unknown",
                        foundations.namespace.getNamespace(attribute,
                                                           rootOnly=True)))
Esempio n. 32
0
    def testGetAttributes(self):
        """
		This method tests :meth:`foundations.parsers.SectionsFileParser.getAttributes` method.
		"""

        for type, file in STANDARD_FILES.iteritems():
            sectionsFileParser = SectionsFileParser(file)
            sectionsFileParser.read() and sectionsFileParser.parse(
                rawSections=STANDARD_FILES_RAW_SECTIONS[type])
            for section in STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type]:
                self.assertListEqual(
                    sectionsFileParser.getAttributes(
                        section, orderedDictionary=True,
                        stripNamespaces=True).keys(),
                    STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type][section]
                    ["stripped"])
                self.assertListEqual(
                    sectionsFileParser.getAttributes(section).keys(),
                    STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type][section]
                    ["namespaced"])
Esempio n. 33
0
    def getIblSetImagesPaths(self, iblSet, imageType):
        """
		This method gets Ibl Set images paths.

		:param iblSet: Ibl Set. ( IblSet )
		:param imageType: Image type. ( String )
		:return: Images paths. ( List )
		"""

        imagePaths = []
        if imageType == "Background":
            path = iblSet.backgroundImage
            path and imagePaths.append(path)
        elif imageType == "Lighting":
            path = iblSet.lightingImage
            path and imagePaths.append(path)
        elif imageType == "Reflection":
            path = iblSet.reflectionImage
            path and imagePaths.append(path)
        elif imageType == "Plate":
            if foundations.common.pathExists(iblSet.path):
                LOGGER.debug(
                    "> Parsing Inspector Ibl Set file: '{0}'.".format(iblSet))
                sectionsFileParser = SectionsFileParser(iblSet.path)
                sectionsFileParser.read() and sectionsFileParser.parse()
                for section in sectionsFileParser.sections:
                    if re.search(r"Plate\d+", section):
                        imagePaths.append(
                            os.path.normpath(
                                os.path.join(
                                    os.path.dirname(iblSet.path),
                                    sectionsFileParser.getValue(
                                        "PLATEfile", section))))

        for path in imagePaths[:]:
            if not foundations.common.pathExists(path):
                imagePaths.remove(path) and LOGGER.warning(
                    "!> {0} | '{1}' image file doesn't exists and will be skipped!"
                    .format(self.__class__.__name__, path))
        return imagePaths
Esempio n. 34
0
	def setContent(self):
		"""
		This method initializes the class attributes.

		:return: Method success. ( Boolean )
		"""

		sectionsFileParser = SectionsFileParser(self.path)
		sectionsFileParser.read() and sectionsFileParser.parse()

		if sectionsFileParser.sections:
			self.title = sectionsFileParser.getValue("Name", "Header")
			self.author = sectionsFileParser.getValue("Author", "Header")
			self.link = sectionsFileParser.getValue("Link", "Header")
			self.icon = os.path.normpath(os.path.join(os.path.dirname(self.path),
										sectionsFileParser.getValue("ICOfile", "Header"))) \
										if sectionsFileParser.getValue("ICOfile", "Header") else None
			self.previewImage = os.path.normpath(os.path.join(os.path.dirname(self.path),
								 				sectionsFileParser.getValue("PREVIEWfile", "Header"))) \
								 				if sectionsFileParser.getValue("PREVIEWfile", "Header") else None
			self.backgroundImage = os.path.normpath(os.path.join(os.path.dirname(self.path),
													sectionsFileParser.getValue("BGfile", "Background"))) \
													if sectionsFileParser.getValue("BGfile", "Background") else None
			self.lightingImage = os.path.normpath(os.path.join(os.path.dirname(self.path),
												sectionsFileParser.getValue("EVfile", "Enviroment"))) \
												if sectionsFileParser.getValue("EVfile", "Enviroment") else None
			self.reflectionImage = os.path.normpath(os.path.join(os.path.dirname(self.path),
													sectionsFileParser.getValue("REFfile", "Reflection"))) \
													if sectionsFileParser.getValue("REFfile", "Reflection") else None
			self.location = sectionsFileParser.getValue("Location", "Header")
			self.latitude = sectionsFileParser.getValue("GEOlat", "Header")
			self.longitude = sectionsFileParser.getValue("GEOlong", "Header")
			self.date = sectionsFileParser.getValue("Date", "Header")
			self.time = sectionsFileParser.getValue("Time", "Header")
			self.comment = sectionsFileParser.getValue("Comment", "Header")

			return True
		else:
			raise foundations.exceptions.FileStructureParsingError(
			"{0} | '{1}' no sections found, file structure seems invalid!".format(self.__class__.__name__, self.path))
Esempio n. 35
0
    def testGetValue(self):
        """
		This method tests :meth:`foundations.parsers.SectionsFileParser.getValue` method.
		"""

        for type, file in STANDARD_FILES.iteritems():
            sectionsFileParser = SectionsFileParser(file)
            sectionsFileParser.read() and sectionsFileParser.parse(
                False, rawSections=STANDARD_FILES_RAW_SECTIONS[type])
            for attribute, value in RANDOM_ATTRIBUTES[type].iteritems():
                self.assertIsInstance(
                    sectionsFileParser.getValue(
                        attribute,
                        foundations.namespace.getNamespace(attribute,
                                                           rootOnly=True)),
                    str)
                self.assertIsInstance(
                    sectionsFileParser.getValue(
                        attribute,
                        foundations.namespace.getNamespace(attribute,
                                                           rootOnly=True),
                        encode=True), unicode)
                self.assertEqual(
                    sectionsFileParser.getValue(
                        attribute,
                        foundations.namespace.getNamespace(attribute,
                                                           rootOnly=True)),
                    value)
            self.assertEqual(
                sectionsFileParser.getValue("attribute",
                                            "section",
                                            default=None), None)
            self.assertEqual(
                sectionsFileParser.getValue("attribute",
                                            "section",
                                            default=list()), list())
Esempio n. 36
0
	def getLoaderScript(self, template, iblSet, overrideKeys):
		"""
		This method builds a Loader Script.

		:param template: Template path. ( String )
		:param iblSet: Ibl Set path. ( String )
		:param overrideKeys: Override keys. ( Dictionary )
		:return: Loader Script. ( List )
		"""

		LOGGER.debug("> Parsing Template file: '{0}'.".format(template))
		templateSectionsFileParser = SectionsFileParser(template)
		templateSectionsFileParser.read() and templateSectionsFileParser.parse(
											rawSections=(self.__templateScriptSection))
		templateSections = dict.copy(templateSectionsFileParser.sections)

		for attribute, value in dict.copy(templateSections[self.__templateIblSetAttributesSection]).iteritems():
			templateSections[self.__templateIblSetAttributesSection][foundations.namespace.removeNamespace(attribute,
																								rootOnly=True)] = value
			del templateSections[self.__templateIblSetAttributesSection][attribute]

		LOGGER.debug("> Binding Templates file attributes.")
		bindedAttributes = dict(((attribute, foundations.parsers.getAttributeCompound(attribute, value))
							for section in templateSections if section not in (self.__templateScriptSection)
							for attribute, value in templateSections[section].iteritems()))

		LOGGER.debug("> Parsing Ibl Set file: '{0}'.".format(iblSet))
		iblSetSectionsFileParser = SectionsFileParser(iblSet)
		iblSetSectionsFileParser.read() and iblSetSectionsFileParser.parse()
		iblSetSections = dict.copy(iblSetSectionsFileParser.sections)

		LOGGER.debug("> Flattening Ibl Set file attributes.")
		flattenedIblAttributes = dict(((attribute, foundations.parsers.getAttributeCompound(attribute, value))
		 						for section in iblSetSections
								for attribute, value in iblSetSections[section].iteritems()))

		for attribute in flattenedIblAttributes:
			if attribute in bindedAttributes:
				bindedAttributes[attribute].value = flattenedIblAttributes[attribute].value

		if "Lights|DynamicLights" in bindedAttributes:
			LOGGER.debug("> Building '{0}' custom attribute.".format("Lights|DynamicLights"))
			dynamicLights = []
			for section in iblSetSections:
				if re.search(r"Light\d+", section):
					dynamicLights.append(section)
					lightName = iblSetSectionsFileParser.getValue("LIGHTname", section)
					dynamicLights.append(lightName and lightName or self.__unnamedLightName)
					lightColorTokens = iblSetSectionsFileParser.getValue("LIGHTcolor", section).split(",")
					for color in lightColorTokens:
						dynamicLights.append(color)
					dynamicLights.append(iblSetSectionsFileParser.getValue("LIGHTmulti", section))
					dynamicLights.append(iblSetSectionsFileParser.getValue("LIGHTu", section))
					dynamicLights.append(iblSetSectionsFileParser.getValue("LIGHTv", section))

			LOGGER.debug("> Adding '{0}' custom attribute with value: '{1}'.".format("Lights|DynamicLights",
																					", ".join(dynamicLights)))
			bindedAttributes["Lights|DynamicLights"].value = self.__defaultStringSeparator.join(dynamicLights)

		LOGGER.debug("> Updating attributes with override keys.")
		for attribute in overrideKeys:
			if attribute in bindedAttributes:
				bindedAttributes[attribute].value = overrideKeys[attribute] and overrideKeys[attribute].value or None

		LOGGER.debug("> Updating Loader Script content.")
		loaderScript = templateSectionsFileParser.sections[
						self.__templateScriptSection][templateSectionsFileParser.rawSectionContentIdentifier]

		boundLoaderScript = []
		for line in loaderScript:
			bindingParameters = re.findall(r"{0}".format(self.__bindingIdentifierPattern), line)
			if bindingParameters:
				for parameter in bindingParameters:
					for attribute in bindedAttributes.itervalues():
						if not parameter == attribute.link:
							continue

						LOGGER.debug("> Updating Loader Script parameter '{0}' with value: '{1}'.".format(parameter,
																										attribute.value))
						line = line.replace(parameter, attribute.value if attribute.value else "-1")
			boundLoaderScript.append(line)
		return boundLoaderScript
Esempio n. 37
0
	def testWrite(self):
		"""
		This method tests :meth:`foundations.parsers.SectionsFileParser.write` method.
		"""

		# Standard sections files.
		for type, file in STANDARD_FILES.iteritems():
			readSectionsFileParser = SectionsFileParser(file)
			readSectionsFileParser.read() and \
			readSectionsFileParser.parse(stripComments=False, rawSections=STANDARD_FILES_RAW_SECTIONS[type])

			writeSectionsFileParser = SectionsFileParser(tempfile.mkstemp()[1])
			writeSectionsFileParser.sections = readSectionsFileParser.sections
			writeSectionsFileParser.comments = readSectionsFileParser.comments
			writeSectionsFileParser.write()

			checkingSectionsFileParser = SectionsFileParser(writeSectionsFileParser.file)
			checkingSectionsFileParser.read() and checkingSectionsFileParser.parse(stripComments=False,
																			rawSections=STANDARD_FILES_RAW_SECTIONS[type])
			self.assertDictEqual(readSectionsFileParser.sections, checkingSectionsFileParser.sections)
			os.remove(writeSectionsFileParser.file)

		# Standard sections files with namespaces.
		for type, file in STANDARD_FILES.iteritems():
			readSectionsFileParser = SectionsFileParser(file)
			readSectionsFileParser.read() and readSectionsFileParser.parse(namespaces=True,
																			stripComments=False,
																			rawSections=STANDARD_FILES_RAW_SECTIONS[type])

			writeSectionsFileParser = SectionsFileParser(tempfile.mkstemp()[1])
			writeSectionsFileParser.sections = readSectionsFileParser.sections
			writeSectionsFileParser.comments = readSectionsFileParser.comments
			writeSectionsFileParser.write(namespaces=True)

			checkingSectionsFileParser = SectionsFileParser(writeSectionsFileParser.file)
			checkingSectionsFileParser.read() and checkingSectionsFileParser.parse(namespaces=False,
																			stripComments=False,
																			rawSections=STANDARD_FILES_RAW_SECTIONS[type])
			self.assertDictEqual(readSectionsFileParser.sections, checkingSectionsFileParser.sections)
			os.remove(writeSectionsFileParser.file)

		# Default section file.
		readSectionsFileParser = SectionsFileParser(DEFAULTS_FILE)
		readSectionsFileParser.read() and readSectionsFileParser.parse()

		writeSectionsFileParser = SectionsFileParser(tempfile.mkstemp()[1])
		writeSectionsFileParser.sections = readSectionsFileParser.sections
		writeSectionsFileParser.comments = readSectionsFileParser.comments
		writeSectionsFileParser.write()

		checkingSectionsFileParser = SectionsFileParser(writeSectionsFileParser.file)
		checkingSectionsFileParser.read() and checkingSectionsFileParser.parse()
		os.remove(writeSectionsFileParser.file)
Esempio n. 38
0
    def testWrite(self):
        """
		This method tests :meth:`foundations.parsers.SectionsFileParser.write` method.
		"""

        # Standard sections files.
        for type, file in STANDARD_FILES.iteritems():
            readSectionsFileParser = SectionsFileParser(file)
            readSectionsFileParser.read() and \
            readSectionsFileParser.parse(stripComments=False, rawSections=STANDARD_FILES_RAW_SECTIONS[type])

            fileDescriptor, path = tempfile.mkstemp()
            writeSectionsFileParser = SectionsFileParser(path)
            writeSectionsFileParser.sections = readSectionsFileParser.sections
            writeSectionsFileParser.comments = readSectionsFileParser.comments
            writeSectionsFileParser.write()

            checkingSectionsFileParser = SectionsFileParser(
                writeSectionsFileParser.path)
            checkingSectionsFileParser.read(
            ) and checkingSectionsFileParser.parse(
                stripComments=False,
                rawSections=STANDARD_FILES_RAW_SECTIONS[type])
            self.assertDictEqual(readSectionsFileParser.sections,
                                 checkingSectionsFileParser.sections)
            os.close(fileDescriptor)

        # Standard sections files with namespaces.
        for type, file in STANDARD_FILES.iteritems():
            readSectionsFileParser = SectionsFileParser(file)
            readSectionsFileParser.read() and readSectionsFileParser.parse(
                namespaces=True,
                stripComments=False,
                rawSections=STANDARD_FILES_RAW_SECTIONS[type])

            fileDescriptor, path = tempfile.mkstemp()
            writeSectionsFileParser = SectionsFileParser(path)
            writeSectionsFileParser.sections = readSectionsFileParser.sections
            writeSectionsFileParser.comments = readSectionsFileParser.comments
            writeSectionsFileParser.write(namespaces=True)

            checkingSectionsFileParser = SectionsFileParser(
                writeSectionsFileParser.path)
            checkingSectionsFileParser.read(
            ) and checkingSectionsFileParser.parse(
                namespaces=False,
                stripComments=False,
                rawSections=STANDARD_FILES_RAW_SECTIONS[type])
            self.assertDictEqual(readSectionsFileParser.sections,
                                 checkingSectionsFileParser.sections)
            os.close(fileDescriptor)

        # Default section file.
        readSectionsFileParser = SectionsFileParser(DEFAULTS_FILE)
        readSectionsFileParser.read() and readSectionsFileParser.parse()

        fileDescriptor, path = tempfile.mkstemp()
        writeSectionsFileParser = SectionsFileParser(path)
        writeSectionsFileParser.sections = readSectionsFileParser.sections
        writeSectionsFileParser.comments = readSectionsFileParser.comments
        writeSectionsFileParser.write()

        checkingSectionsFileParser = SectionsFileParser(
            writeSectionsFileParser.path)
        checkingSectionsFileParser.read() and checkingSectionsFileParser.parse(
        )
        os.close(fileDescriptor)