<commit_before># plot_utils.py
# Common geometric plotting utilities for EiBotBoard
# https://github.com/evil-mad/plotink
#
# Intended to provide some common interfaces that can be used by
# EggBot, WaterColorBot, AxiDraw, and similar machines.
#
# Version 0.1, Dated January 8, 2016.
#
#
# The MIT License (MIT)
#
# Copyright (c) 2016 Evil Mad Scientist Laboratories
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from math import sqrt
import cspsubdiv
from bezmisc import *

def version():
	return "0.1"	# Version number for this document

def distance( x, y ):
	'''
	Pythagorean theorem!
	'''
	return sqrt( x * x + y * y )

def parseLengthWithUnits( str ):
	'''
	Parse an SVG value which may or may not have units attached
	This version is greatly simplified in that it only allows: no units,
	units of px, and units of %.  Everything else, it returns None for.
	There is a more general routine to consider in scour.py if more
	generality is ever needed.
	'''
	u = 'px'
	s = str.strip()
	if s[-2:] == 'px':
		s = s[:-2]
	elif s[-1:] == '%':
		u = '%'
		s = s[:-1]

	try:
		v = float( s )
	except:
		return None, None

	return v, u

def getLength( altself, name, default ):
	'''
	Get the <svg> attribute with name "name" and default value "default"
	Parse the attribute into a value and associated units.  Then, accept
	no units (''), units of pixels ('px'), and units of percentage ('%').
	'''
	str = altself.svg.get( name )
	if str:
		v, u = parseLengthWithUnits( str )
		if not v:
			# Couldn't parse the value
			return None
		elif ( u == '' ) or ( u == 'px' ):
			return v
		elif u == '%':
			return float( default ) * v / 100.0
		else:
			# Unsupported units
			return None
	else:
		# No width specified; assume the default value
		return float( default )

def subdivideCubicPath( sp, flat, i=1 ):
	"""
	Break up a bezier curve into smaller curves, each of which
	is approximately a straight line within a given tolerance
	(the "smoothness" defined by [flat]).

	This is a modified version of cspsubdiv.cspsubdiv(). I rewrote the recursive
	call because it caused recursion-depth errors on complicated line segments.
	"""

	while True:
		while True:
			if i >= len( sp ):
				return

			p0 = sp[i - 1][1]
			p1 = sp[i - 1][2]
			p2 = sp[i][0]
			p3 = sp[i][1]

			b = ( p0, p1, p2, p3 )

			if cspsubdiv.maxdist( b ) > flat:
				break
			i += 1

		one, two = beziersplitatt( b, 0.5 )
		sp[i - 1][2] = one[1]
		sp[i][0] = two[2]
		p = [one[2], one[3], two[1]]
		sp[i:1] = [p]

<commit_msg>Add additional unit parsing options<commit_after># plot_utils.py
# Common geometric plotting utilities for EiBotBoard
# https://github.com/evil-mad/plotink
#
# Intended to provide some common interfaces that can be used by
# EggBot, WaterColorBot, AxiDraw, and similar machines.
#
# Version 0.2, Dated February 1, 2016.
#
#
# The MIT License (MIT)
#
# Copyright (c) 2016 Evil Mad Scientist Laboratories
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from math import sqrt
import cspsubdiv
from bezmisc import *

def version():
	return "0.2"	# Version number for this document

def distance( x, y ):
	'''
	Pythagorean theorem!
	'''
	return sqrt( x * x + y * y )

def parseLengthWithUnits( str ):
	'''
	Parse an SVG value which may or may not have units attached
	This version is greatly simplified in that it only allows: no units,
	units of px, and units of %.  Everything else, it returns None for.
	There is a more general routine to consider in scour.py if more
	generality is ever needed.
	'''
	u = 'px'
	s = str.strip()
	if s[-2:] == 'px':
		s = s[:-2]
	elif s[-2:] == 'in':
		s = s[:-2]
		u = 'in'
	elif s[-2:] == 'mm':
		s = s[:-2]
		u = 'mm'
	elif s[-2:] == 'cm':
		s = s[:-2]
		u = 'cm'
	elif s[-1:] == '%':
		u = '%'
		s = s[:-1]

	try:
		v = float( s )
	except:
		return None, None

	return v, u

def getLength( altself, name, default ):
	'''
	Get the <svg> attribute with name "name" and default value "default"
	Parse the attribute into a value and associated units.  Then, accept
	no units (''), units of pixels ('px'), and units of percentage ('%').
	'''
	str = altself.svg.get( name )
	if str:
		v, u = parseLengthWithUnits( str )
		if not v:
			# Couldn't parse the value
			return None
		elif ( u == '' ) or ( u == 'px' ):
			return v
		elif u == '%':
			return float( default ) * v / 100.0
		else:
			# Unsupported units
			return None
	else:
		# No width specified; assume the default value
		return float( default )

def getLengthInches( altself, name ):
	'''
	Get the <svg> attribute with name "name" and default value "default"
	Parse the attribute into a value and associated units.  Then, accept
	units of inches ('in'), millimeters ('mm'), or centimeters ('cm')
	'''
	str = altself.svg.get( name )
	if str:
		v, u = parseLengthWithUnits( str )
		if not v:
			# Couldn't parse the value
			return None
		elif  u == 'in' :
			return v
		elif u == 'mm':
			return (float( v ) / 25.4)
		elif u == 'cm':
			return (float( v ) / 2.54)
		else:
			# Unsupported units
			return None

def subdivideCubicPath( sp, flat, i=1 ):
	"""
	Break up a bezier curve into smaller curves, each of which
	is approximately a straight line within a given tolerance
	(the "smoothness" defined by [flat]).

	This is a modified version of cspsubdiv.cspsubdiv(). I rewrote the recursive
	call because it caused recursion-depth errors on complicated line segments.
	"""

	while True:
		while True:
			if i >= len( sp ):
				return

			p0 = sp[i - 1][1]
			p1 = sp[i - 1][2]
			p2 = sp[i][0]
			p3 = sp[i][1]

			b = ( p0, p1, p2, p3 )

			if cspsubdiv.maxdist( b ) > flat:
				break
			i += 1

		one, two = beziersplitatt( b, 0.5 )
		sp[i - 1][2] = one[1]
		sp[i][0] = two[2]
		p = [one[2], one[3], two[1]]
		sp[i:1] = [p]

<|endoftext|>


<commit_before># PCEP message and implicit object definitions

# Copyright (c) 2012,2013 Cisco Systems, Inc. and others.  All rights reserved.
#
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License v1.0 which accompanies this distribution,
# and is available at http://www.eclipse.org/legal/epl-v10.html

from . import base
from . import object # Note: object here is a module

# RFC 5440 PCEP
class Open(base.Message):
    type_id = 1

    _sequence = [
        ('open', object.Open, 1),
    ]

# RFC 5440 PCEP
class Keepalive(base.Message):
    type_id = 2

    _sequence = [ ]

# RFC 5886 MON
class GMon(base.Group):
    _sequence = [
        ('mon', object.Monitoring, 1),
        ('pcc', object.PccIdReq, 1),
        ('pce', object.PceId, '*'),
    ]

# RFC 5440 PCEP
class GRro(base.Group):
    _sequence = [
        ('rro', object.Rro, 1),
        ('rbw', object.Bandwidth, '?'),
    ]

# RFC 5440 PCEP
# Note: RFC 5520 PK says there's either a PatkKey,
# or all other objects in a request
# In RFC 5440 PCEP, Endpoints is a REQUIRED object
class Request(base.Group):
    _sequence = [
        ('rp', object.Rp, 1),
        ('pk', object.PathKey, '?'), # RFC 5520 PK
        ('ep', object.Endpoints, '?'), # Actually required
        ('lsp', object.Lsp, '?'), # D STATEFUL
        ('lspa', object.Lspa, '?'),
        ('bw', object.Bandwidth, '?'),
        ('metric', object.Metric, '*'),
        ('of', object.Of, '?'), # RFC 5541 OF
        ('grro', GRro, '?'),
        ('iro', object.Iro, '?'),
        ('lb', object.LoadBalancing, '?'),
        ('xro', object.Xro, '?'), # RFC 5521 XRO
    ]

# RFC 5440 PCEP
class GSvec(base.Group):
    _sequence = [
        ('svec', object.Svec, 1),
        ('of', object.Of, '?'), # RFC 5541 OF
        ('metric', object.Metric, '*'), # RFC 5541 OF
    ]

# RFC 5440 PCEP
class PCReq(base.Message):
    type_id = 3

    _sequence = [
        ('gmon', GMon, '?'), # RFC 5886 MON
        ('gsvec', GSvec, '*'),
        ('request', Request, '+'),
    ]

# RFC 5440 PCEP
class PcePathAttributes(base.Group):
    _sequence = [
        ('of', object.Of, '?'), # RFC 5541 OF
        ('lspa', object.Lspa, '?'),
        ('bw', object.Bandwidth, '?'),
        ('metric', object.Metric, '*'),
        ('iro', object.Iro, '?'), # Not in D STATEFUL-01
    ]

# RFC 5440 PCEP
class PcePath(base.Group):
    _sequence = [
        ('ero', object.Ero, 1),
        ('pcepa', PcePathAttributes, '?'),
    ]

# RFC 5886 MON
class MetricPce(base.Group):
    _sequence = [
        ('pce', object.PceId, 1),
        ('pt', object.ProcTime, '?'),
        ('ol', object.Overload, '?'),
    ]

# RFC 5440 PCEP
class Response(base.Group):
    _sequence = [
        ('rp', object.Rp, 1),
        ('gmon', GMon, '?'), # Without pce list # RFC 5886 MON
        ('lsp', object.Lsp, '?'), # D STATEFUL
        ('nopath', object.NoPath, '?'),
        ('pcepa', PcePathAttributes, '?'),
        ('path', PcePath, '*'),
        ('mp', MetricPce, '*'), # RFC 5886 MON
    ]

# RFC 5440 PCEP
class PCRep(base.Message):
    type_id = 4

    _sequence = [
        ('response', Response, '+'),
    ]

# RFC 5440 PCEP
class GNotify(base.Group):
    _sequence = [
        ('rp', object.Rp, '*'),
        ('notify', object.Notification, '+'),
    ]

# RFC 5440 PCEP
class PCNtf(base.Message):
    type_id = 5

    _sequence = [
        ('gnotify', GNotify, '+'),
    ]

# RFC 5440 PCEP
class GError(base.Group):
    """Unified PCEP error item"""
    _sequence = [
        ('rp', object.Rp, '*'),
        ('error', object.Error, '+'),
        ('lsp', object.Lsp, '?'), # D STATEFUL
    ]

# RFC 5440 PCEP
class PCErr(base.Message):
    type_id = 6

    _sequence = [
        ('gerror', GError, '+'),
        ('open', object.Open, '?'),
    ]

# RFC 5440 PCEP
class Close(base.Message):
    type_id = 7

    _sequence = [
        ('close', object.Close, 1)
    ]

# RFC 5886 MON
class PCMonReq(base.Message):
    type_id = 8

    _sequence = [
        ('gmon', GMon, 1),
        ('gsvec', GSvec, '*'),
        ('request', Request, '+'),
    ]

# RFC 5886 MON
class PCMonRep(base.Message):
    type_id = 9

    _sequence = [
        ('gmon', GMon, '?'), # Without pce list
        ('rp', object.Rp, '*'),
        ('mp', MetricPce, '*'),
    ]

# D STATEFUL
class PccPath(base.Group):
    _sequence = [
        ('ero', object.Ero, 1),
        ('lspa', object.Lspa, '?'),
        ('bw', object.Bandwidth, '?'),
        ('rro', object.Rro, '?'),
        ('metric', object.Metric, '*'),
    ]

# D STATEFUL
class StateReport(base.Group):
    _sequence = [
        ('lsp', object.Lsp, 1),
        ('path', PccPath, '*'),
    ]

# D STATEFUL
class PCRpt(base.Message):
    type_id = 10

    _sequence = [
        ('report', StateReport, '+'),
    ]

# D STATEFUL
class UpdateRequest(base.Group):
    _sequence = [
        ('lsp', object.Lsp, 1),
        ('path', PcePath, '*'),
    ]

# D STATEFUL
class PCUpd(base.Message):
    type_id = 11

    _sequence = [
        ('update', UpdateRequest, '+'),
    ]

# D STATEFUL
class CreateRequest(base.Group):
    _sequence = [
        ('end-points', object.Endpoints, 1),
        ('lspa', object.Lspa, 1),
        ('ero', object.Ero, '?'),
        ('bw', object.Bandwidth, '?'),
        ('metric', object.Metric, '*'),
    ]

# D STATEFUL
class PCCreate(base.Message):
    type_id = 12

    _sequence = [
        ('create', CreateRequest, '+'),
    ]

# We do not need special handling for unknown messages
class Unknown(base.Message):
    pass
base.Message.unknown_class = Unknown

<commit_msg>Fix pep8 violations in message/_message.py<commit_after># PCEP message and implicit object definitions

# Copyright (c) 2012,2013 Cisco Systems, Inc. and others.  All rights reserved.
#
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License v1.0 which accompanies this distribution,
# and is available at http://www.eclipse.org/legal/epl-v10.html

from . import base
from . import object  # Note: object here is a module

# RFC 5440 PCEP
class Open(base.Message):
    type_id = 1

    _sequence = [
        ('open', object.Open, 1),
    ]

# RFC 5440 PCEP
class Keepalive(base.Message):
    type_id = 2

    _sequence = []

# RFC 5886 MON
class GMon(base.Group):
    _sequence = [
        ('mon', object.Monitoring, 1),
        ('pcc', object.PccIdReq, 1),
        ('pce', object.PceId, '*'),
    ]

# RFC 5440 PCEP
class GRro(base.Group):
    _sequence = [
        ('rro', object.Rro, 1),
        ('rbw', object.Bandwidth, '?'),
    ]

# RFC 5440 PCEP
# Note: RFC 5520 PK says there's either a PatkKey,
# or all other objects in a request
# In RFC 5440 PCEP, Endpoints is a REQUIRED object
class Request(base.Group):
    _sequence = [
        ('rp', object.Rp, 1),
        ('pk', object.PathKey, '?'),  # RFC 5520 PK
        ('ep', object.Endpoints, '?'),  # Actually required
        ('lsp', object.Lsp, '?'),  # D STATEFUL
        ('lspa', object.Lspa, '?'),
        ('bw', object.Bandwidth, '?'),
        ('metric', object.Metric, '*'),
        ('of', object.Of, '?'),  # RFC 5541 OF
        ('grro', GRro, '?'),
        ('iro', object.Iro, '?'),
        ('lb', object.LoadBalancing, '?'),
        ('xro', object.Xro, '?'),  # RFC 5521 XRO
    ]

# RFC 5440 PCEP
class GSvec(base.Group):
    _sequence = [
        ('svec', object.Svec, 1),
        ('of', object.Of, '?'),  # RFC 5541 OF
        ('metric', object.Metric, '*'),  # RFC 5541 OF
    ]

# RFC 5440 PCEP
class PCReq(base.Message):
    type_id = 3

    _sequence = [
        ('gmon', GMon, '?'),  # RFC 5886 MON
        ('gsvec', GSvec, '*'),
        ('request', Request, '+'),
    ]

# RFC 5440 PCEP
class PcePathAttributes(base.Group):
    _sequence = [
        ('of', object.Of, '?'),  # RFC 5541 OF
        ('lspa', object.Lspa, '?'),
        ('bw', object.Bandwidth, '?'),
        ('metric', object.Metric, '*'),
        ('iro', object.Iro, '?'),  # Not in D STATEFUL-01
    ]

# RFC 5440 PCEP
class PcePath(base.Group):
    _sequence = [
        ('ero', object.Ero, 1),
        ('pcepa', PcePathAttributes, '?'),
    ]

# RFC 5886 MON
class MetricPce(base.Group):
    _sequence = [
        ('pce', object.PceId, 1),
        ('pt', object.ProcTime, '?'),
        ('ol', object.Overload, '?'),
    ]

# RFC 5440 PCEP
class Response(base.Group):
    _sequence = [
        ('rp', object.Rp, 1),
        ('gmon', GMon, '?'),  # Without pce list # RFC 5886 MON
        ('lsp', object.Lsp, '?'),  # D STATEFUL
        ('nopath', object.NoPath, '?'),
        ('pcepa', PcePathAttributes, '?'),
        ('path', PcePath, '*'),
        ('mp', MetricPce, '*'),  # RFC 5886 MON
    ]

# RFC 5440 PCEP
class PCRep(base.Message):
    type_id = 4

    _sequence = [
        ('response', Response, '+'),
    ]

# RFC 5440 PCEP
class GNotify(base.Group):
    _sequence = [
        ('rp', object.Rp, '*'),
        ('notify', object.Notification, '+'),
    ]

# RFC 5440 PCEP
class PCNtf(base.Message):
    type_id = 5

    _sequence = [
        ('gnotify', GNotify, '+'),
    ]

# RFC 5440 PCEP
class GError(base.Group):
    """Unified PCEP error item"""
    _sequence = [
        ('rp', object.Rp, '*'),
        ('error', object.Error, '+'),
        ('lsp', object.Lsp, '?'),  # D STATEFUL
    ]

# RFC 5440 PCEP
class PCErr(base.Message):
    type_id = 6

    _sequence = [
        ('gerror', GError, '+'),
        ('open', object.Open, '?'),
    ]

# RFC 5440 PCEP
class Close(base.Message):
    type_id = 7

    _sequence = [
        ('close', object.Close, 1)
    ]

# RFC 5886 MON
class PCMonReq(base.Message):
    type_id = 8

    _sequence = [
        ('gmon', GMon, 1),
        ('gsvec', GSvec, '*'),
        ('request', Request, '+'),
    ]

# RFC 5886 MON
class PCMonRep(base.Message):
    type_id = 9

    _sequence = [
        ('gmon', GMon, '?'),  # Without pce list
        ('rp', object.Rp, '*'),
        ('mp', MetricPce, '*'),
    ]

# D STATEFUL
class PccPath(base.Group):
    _sequence = [
        ('ero', object.Ero, 1),
        ('lspa', object.Lspa, '?'),
        ('bw', object.Bandwidth, '?'),
        ('rro', object.Rro, '?'),
        ('metric', object.Metric, '*'),
    ]

# D STATEFUL
class StateReport(base.Group):
    _sequence = [
        ('lsp', object.Lsp, 1),
        ('path', PccPath, '*'),
    ]

# D STATEFUL
class PCRpt(base.Message):
    type_id = 10

    _sequence = [
        ('report', StateReport, '+'),
    ]

# D STATEFUL
class UpdateRequest(base.Group):
    _sequence = [
        ('lsp', object.Lsp, 1),
        ('path', PcePath, '*'),
    ]

# D STATEFUL
class PCUpd(base.Message):
    type_id = 11

    _sequence = [
        ('update', UpdateRequest, '+'),
    ]

# D STATEFUL
class CreateRequest(base.Group):
    _sequence = [
        ('end-points', object.Endpoints, 1),
        ('lspa', object.Lspa, 1),
        ('ero', object.Ero, '?'),
        ('bw', object.Bandwidth, '?'),
        ('metric', object.Metric, '*'),
    ]

# D STATEFUL
class PCCreate(base.Message):
    type_id = 12

    _sequence = [
        ('create', CreateRequest, '+'),
    ]

# We do not need special handling for unknown messages
class Unknown(base.Message):
    pass
base.Message.unknown_class = Unknown
<|endoftext|>


<commit_before>#!/usr/bin/env python
import os
import shutil

from setuptools import setup
from distutils.dist import Distribution as old_Distribution
from distutils.command.install import install as old_install
from distutils.command.install_data import install_data as old_install_data

# BEFORE importing distutils, remove MANIFEST. distutils doesn't properly
# update it when the contents of directories change.
if os.path.exists('MANIFEST'): os.remove('MANIFEST')

# We implement our own add_data_dir method, to avoid depending on numpy
# distutils, which would create an obvious boostrapping problem once we want to
# build numpy with scons
class Distribution(old_Distribution):
    """This new Distribution class is necessary to support the new data_dir
    argument in setup files."""
    def __init__(self, attrs = None):
        assert not hasattr(self, 'data_dir')
        self.data_dir = []
        old_Distribution.__init__(self, attrs)

        # Butt ugly: we add the data directories when the distribution is
        # initialized. But it does not work with eggs otherwise ?
        for d in self.data_dir:
            install_data_files = []
            for roots, dirs, files in os.walk(d):
                for file in files:
                    install_data_files.append((roots, [os.path.join(roots, file)]))

        if self.data_files:
            self.data_files.extend(install_data_files)
        else:
            self.data_files = install_data_files

# Main setup method
import release as R
setup(distclass = Distribution,
      name          = R.NAME,
      version       = R.VERSION,
      description   = R.DESCRIPTION,
      author        = R.AUTHOR,
      author_email  = R.AUTHOR_EMAIL,
      packages      = R.PACKAGES,
      package_data  = R.PACKAGE_DATA,
      data_dir      = R.DATA_DIR
      )
<commit_msg>Fix setupegg whose data_dir method did not work again<commit_after>#!/usr/bin/env python
import os
import shutil

from setuptools import setup
from distutils.dist import Distribution as old_Distribution
from distutils.command.install import install as old_install
from distutils.command.install_data import install_data as old_install_data
from distutils.command.sdist import sdist as old_sdist

# BEFORE importing distutils, remove MANIFEST. distutils doesn't properly
# update it when the contents of directories change.
if os.path.exists('MANIFEST'): os.remove('MANIFEST')

# We implement our own add_data_dir method, to avoid depending on numpy
# distutils, which would create an obvious boostrapping problem once we want to
# build numpy with scons
class Distribution(old_Distribution):
    """This new Distribution class is necessary to support the new data_dir
    argument in setup files."""
    def __init__(self, attrs = None):
        assert not hasattr(self, 'data_dir')
        self.data_dir = []
        old_Distribution.__init__(self, attrs)

class install_data(old_install_data):
    """this install_data command does not install data files into the wild, but
    put them into the package directory."""
    def finalize_options(self):
        if self.install_dir is None:
            installobj = self.distribution.get_command_obj('install')
            self.install_dir = installobj.install_purelib

    def run(self):
        old_install_data.run(self)

class install(old_install):
    """This install command extends the data_files list of data files using the
    data_dir argument."""
    def run(self):
        dist = self.distribution

        if dist.data_files is None:
            dist.data_files = []

        for d in dist.data_dir:
            install_data_files = []
            for roots, dirs, files in os.walk(d):
                for file in files:
                    install_data_files.append((roots, [os.path.join(roots, file)]))

            dist.data_files.extend(install_data_files)

        old_install.run(self)

class sdist(old_sdist):
    def add_defaults (self):
        old_sdist.add_defaults(self)

        dist = self.distribution

        if dist.data_files is None:
            dist.data_files = []

        for d in dist.data_dir:
            src_data_files = []
            for roots, dirs, files in os.walk(d):
                for file in files:
                    src_data_files.append(os.path.join(roots, file))
            self.filelist.extend(src_data_files)

# Main setup method
import release as R
setup(cmdclass = {'install': install, 'install_data': install_data, 'sdist': sdist},
      distclass = Distribution,
      name          = R.NAME,
      version       = R.VERSION,
      description   = R.DESCRIPTION,
      author        = R.AUTHOR,
      author_email  = R.AUTHOR_EMAIL,
      packages      = R.PACKAGES,
      package_data  = R.PACKAGE_DATA,
      data_dir      = R.DATA_DIR
      )
<|endoftext|>


<commit_before>import os
import py
import yaml
import string
import logging
import factory
import factory.fuzzy
from models import ContainerModel, MasterModel, MinionModel
from clients import DockerClient, NspawnClient

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

class BaseFactory(factory.Factory):

    class Meta:
        model = dict
        strategy = factory.BUILD_STRATEGY

class SaltConfigFactory(BaseFactory):

    tmpdir = None
    root = factory.LazyAttribute(
        lambda o: o.tmpdir.ensure_dir(o.factory_parent.name))
    conf_path = factory.LazyAttribute(lambda o: o.tmpdir / '{0}.conf.tar'.format(o.factory_parent.name))
    conf_type = None
    config = {}
    pillar = {}
    sls = {}
    id = factory.fuzzy.FuzzyText(
        length=5, prefix='id_', chars=string.ascii_letters)

    @factory.post_generation
    def extra_configs(obj, create, extracted, **kwargs):
        if extracted:
            config_path = obj['root'] / '{}.d'.format(obj['conf_type'])
            config_path.ensure_dir()
            for name, config in extracted.items():
                config_file = config_path / '{0}.conf'.format(name)
                config_file.write(
                    yaml.safe_dump(config, default_flow_style=False))

    @factory.post_generation
    def post(obj, create, extracted, **kwargs):
        config_path = obj['root'] / '{}.d'.format(obj['conf_type'])
        config_path.ensure_dir()
        config_file = obj['root'] / obj['conf_type']
        main_config = {
            'include': '{0}.d/*'.format(obj['conf_type'])
        }
        if obj['conf_type'] in ['minion', 'proxy']:
            main_config['id'] = obj['id']

        config_file.write(
            yaml.safe_dump(main_config, default_flow_style=False))

        config_path = obj['root'] / '{}.d'.format(obj['conf_type'])
        for name, config in obj['config'].items():
            config_file = config_path / '{0}.conf'.format(name)
            config_file.write(yaml.safe_dump(config, default_flow_style=False))

        pillar_path = obj['root'].ensure_dir('pillar')
        for name, content in obj['pillar'].items():
            sls_file = pillar_path / '{0}.sls'.format(name)
            sls_file.write(yaml.safe_dump(content, default_flow_style=False))

        sls_path = obj['root'].ensure_dir('sls')
        for name, source in obj['sls'].items():
            sls_file = sls_path / '{0}.sls'.format(name)
            sls_file.write(py.path.local(source).read())

class MasterSaltConfigFactory(SaltConfigFactory):

    @factory.post_generation
    def apply_states(obj, create, extracted, **kwargs):
        if extracted:
            destination = 'masterless'
            config_path = obj['root'] / 'minion.d'
            config_path.ensure_dir()
            (config_path / 'masterless.conf').write(
                yaml.safe_dump(
                    {
                        'file_client': 'local',
                        'file_roots': {
                            'base': ["/etc/salt/{}".format(destination)]
                        },
                        'pillar_roots': {'base': ["/etc/salt/pillar"]}
                    },
                    default_flow_style=False
                )
            )
            sls_path = obj['root'].ensure_dir(destination)
            for name, source in extracted.items():
                sls_file = sls_path / '{0}.sls'.format(name)
                sls_file.write(py.path.local(source).read())

    @factory.post_generation
    def roster(obj, create, extracted, **kwargs):
        if extracted:
            roster = obj['root'] / 'roster'
            roster.write(yaml.safe_dump(extracted, default_flow_style=False))

class SyndicSaltConfigFactory(MasterSaltConfigFactory):

    @factory.post_generation
    def syndic_id(obj, create, extracted, **kwargs):
        config_path = obj['root'] / 'minion.d'
        config_path.ensure_dir()
        config_file = obj['root'] / 'minion'
        main_config = {'include': 'minion.d/*'}
        main_config['id'] = obj['id']
        config_file.write(
            yaml.safe_dump(main_config, default_flow_style=False))

class ContainerConfigFactory(BaseFactory):
    name = factory.fuzzy.FuzzyText(
        length=5, prefix='container_', chars=string.ascii_letters)
    salt_config = factory.SubFactory(SaltConfigFactory)
    image = None
    entrypoint = '/bin/bash'
    environment = dict()
    tty = True
    stdin_open = True
    working_dir = "/salt-toaster/"
    ports = [4000, 4506]

    @factory.lazy_attribute
    def client(self):
        if self.factory_parent.type == 'docker':
            return DockerClient(base_url='unix://var/run/docker.sock')
        elif self.factory_parent.type == 'nspawn':
            return NspawnClient('http+unix:///var/run/gunicorn.sock')

    @factory.lazy_attribute
    def volumes(self):
        volumes = [os.getcwd()]
        if os.getenv('SALT_REPO'):
            volumes.append(os.getenv('SALT_REPO'))
        return volumes

    @factory.lazy_attribute
    def host_config(self):
        params = dict(
            port_bindings={},
            binds={
                os.getcwd(): {
                    'bind': "/salt-toaster/",
                    'mode': 'ro'
                }
            }
        )
        salt_repo = os.getenv('SALT_REPO')
        if salt_repo and salt_repo in self.volumes:
            params['binds'][os.getenv('SALT_REPO')] = {
                'bind': '/salt/src/salt-devel/',
                'mode': 'rw'
            }

        return self.client.create_host_config(**params)

    @factory.post_generation
    def networking_config(self, create, extracted, **kwargs):
        if not self['client'].networks(names=[extracted['name']]):
            self['client'].create_network(**extracted)

        self['networking_config'] = self['client'].create_networking_config({
            extracted['name']: self['client'].create_endpoint_config()
        })

class ContainerFactory(BaseFactory):

    ip = None
    type = 'docker'
    config = factory.SubFactory(
        ContainerConfigFactory,
        networking_config=dict(name="network1", driver="bridge")
    )

    class Meta:
        model = ContainerModel

    @classmethod
    def build(cls, **kwargs):
        obj = super(ContainerFactory, cls).build(**kwargs)
        assert obj['config']['image']
        client = obj['config']['client']
        client.create_container(
            **{
                k: obj['config'][k] for k in obj['config'].keys()
                if k not in ['salt_config', 'client']
            }
        )
        obj['config']['client'].start(obj['config'])
        obj['ip'] = obj['config']['client'].getip(obj['config']['name'])

        try:
            resp = obj.run('salt --version')
            message = "{0}: {1}".format(
                obj['config']['salt_config']['conf_type'], resp.strip())
            logger.info(message)
        except TypeError:
            pass

        return obj

    @factory.post_generation
    def ip(self, create, extracted, **kwargs):
        if not create:
            return extracted

class SaltFactory(BaseFactory):

    container = factory.SubFactory(ContainerFactory)

    @classmethod
    def build(cls, **kwargs):
        obj = super(SaltFactory, cls).build(**kwargs)
        client = obj['container']['config']['client']

        client.configure_salt(obj['container']['config'])

        output = client.run(
            obj['container']['config']['name'], obj['cmd']
        )
        assert 'executable file not found' not in output
        return obj

class MasterFactory(SaltFactory):
    id = factory.LazyAttribute(lambda o: o.container['config']['salt_config']['id'])
    cmd = 'salt-master -d -l debug'
    container = factory.SubFactory(
        ContainerFactory,
        config__salt_config=factory.SubFactory(MasterSaltConfigFactory)
    )

    class Meta:
        model = MasterModel

    @classmethod
    def build(cls, **kwargs):
        obj = super(MasterFactory, cls).build(**kwargs)
        obj['container'].run("salt-call --local state.apply")
        return obj

class SyndicFactory(MasterFactory):

    container = factory.SubFactory(
        ContainerFactory,
        config__salt_config=factory.SubFactory(SyndicSaltConfigFactory)
    )

    @classmethod
    def build(cls, **kwargs):
        obj = super(SyndicFactory, cls).build(**kwargs)
        cmd = 'salt-syndic -d -l debug'
        docker_client = obj['container']['config']['docker_client']
        res = docker_client.exec_create(
            obj['container']['config']['name'], cmd)
        output = docker_client.exec_start(res['Id'])
        assert 'executable file not found' not in output
        return obj

class MinionFactory(SaltFactory):
    id = factory.LazyAttribute(lambda o: o.container['config']['salt_config']['id'])
    cmd = 'salt-minion -d -l debug'

    class Meta:
        model = MinionModel
<commit_msg>Fix SALT_REPO mount in devel<commit_after>import os
import py
import yaml
import string
import logging
import factory
import factory.fuzzy
from models import ContainerModel, MasterModel, MinionModel
from clients import DockerClient, NspawnClient

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

class BaseFactory(factory.Factory):

    class Meta:
        model = dict
        strategy = factory.BUILD_STRATEGY

class SaltConfigFactory(BaseFactory):

    tmpdir = None
    root = factory.LazyAttribute(
        lambda o: o.tmpdir.ensure_dir(o.factory_parent.name))
    conf_path = factory.LazyAttribute(lambda o: o.tmpdir / '{0}.conf.tar'.format(o.factory_parent.name))
    conf_type = None
    config = {}
    pillar = {}
    sls = {}
    id = factory.fuzzy.FuzzyText(
        length=5, prefix='id_', chars=string.ascii_letters)

    @factory.post_generation
    def extra_configs(obj, create, extracted, **kwargs):
        if extracted:
            config_path = obj['root'] / '{}.d'.format(obj['conf_type'])
            config_path.ensure_dir()
            for name, config in extracted.items():
                config_file = config_path / '{0}.conf'.format(name)
                config_file.write(
                    yaml.safe_dump(config, default_flow_style=False))

    @factory.post_generation
    def post(obj, create, extracted, **kwargs):
        config_path = obj['root'] / '{}.d'.format(obj['conf_type'])
        config_path.ensure_dir()
        config_file = obj['root'] / obj['conf_type']
        main_config = {
            'include': '{0}.d/*'.format(obj['conf_type'])
        }
        if obj['conf_type'] in ['minion', 'proxy']:
            main_config['id'] = obj['id']

        config_file.write(
            yaml.safe_dump(main_config, default_flow_style=False))

        config_path = obj['root'] / '{}.d'.format(obj['conf_type'])
        for name, config in obj['config'].items():
            config_file = config_path / '{0}.conf'.format(name)
            config_file.write(yaml.safe_dump(config, default_flow_style=False))

        pillar_path = obj['root'].ensure_dir('pillar')
        for name, content in obj['pillar'].items():
            sls_file = pillar_path / '{0}.sls'.format(name)
            sls_file.write(yaml.safe_dump(content, default_flow_style=False))

        sls_path = obj['root'].ensure_dir('sls')
        for name, source in obj['sls'].items():
            sls_file = sls_path / '{0}.sls'.format(name)
            sls_file.write(py.path.local(source).read())

class MasterSaltConfigFactory(SaltConfigFactory):

    @factory.post_generation
    def apply_states(obj, create, extracted, **kwargs):
        if extracted:
            destination = 'masterless'
            config_path = obj['root'] / 'minion.d'
            config_path.ensure_dir()
            (config_path / 'masterless.conf').write(
                yaml.safe_dump(
                    {
                        'file_client': 'local',
                        'file_roots': {
                            'base': ["/etc/salt/{}".format(destination)]
                        },
                        'pillar_roots': {'base': ["/etc/salt/pillar"]}
                    },
                    default_flow_style=False
                )
            )
            sls_path = obj['root'].ensure_dir(destination)
            for name, source in extracted.items():
                sls_file = sls_path / '{0}.sls'.format(name)
                sls_file.write(py.path.local(source).read())

    @factory.post_generation
    def roster(obj, create, extracted, **kwargs):
        if extracted:
            roster = obj['root'] / 'roster'
            roster.write(yaml.safe_dump(extracted, default_flow_style=False))

class SyndicSaltConfigFactory(MasterSaltConfigFactory):

    @factory.post_generation
    def syndic_id(obj, create, extracted, **kwargs):
        config_path = obj['root'] / 'minion.d'
        config_path.ensure_dir()
        config_file = obj['root'] / 'minion'
        main_config = {'include': 'minion.d/*'}
        main_config['id'] = obj['id']
        config_file.write(
            yaml.safe_dump(main_config, default_flow_style=False))

class ContainerConfigFactory(BaseFactory):
    name = factory.fuzzy.FuzzyText(
        length=5, prefix='container_', chars=string.ascii_letters)
    salt_config = factory.SubFactory(SaltConfigFactory)
    image = None
    entrypoint = '/bin/bash'
    environment = dict()
    tty = True
    stdin_open = True
    working_dir = "/salt-toaster/"
    ports = [4000, 4506]

    @factory.lazy_attribute
    def client(self):
        if self.factory_parent.type == 'docker':
            return DockerClient(base_url='unix://var/run/docker.sock')
        elif self.factory_parent.type == 'nspawn':
            return NspawnClient('http+unix:///var/run/gunicorn.sock')

    @factory.lazy_attribute
    def volumes(self):
        volumes = [os.getcwd()]
        if os.environ.get('FLAVOR') == 'devel' and os.environ.get('SALT_REPO'):
            volumes.append(os.environ['SALT_REPO'])
        return volumes

    @factory.lazy_attribute
    def host_config(self):
        params = dict(
            port_bindings={},
            binds={
                os.getcwd(): {
                    'bind': "/salt-toaster/",
                    'mode': 'ro'
                }
            }
        )
        if os.environ.get('SALT_REPO') in self.volumes:
            params['binds'][os.environ['SALT_REPO']] = {
                'bind': '/salt/src/salt-devel',
                'mode': 'rw'
            }
        return self.client.create_host_config(**params)

    @factory.post_generation
    def networking_config(self, create, extracted, **kwargs):
        if not self['client'].networks(names=[extracted['name']]):
            self['client'].create_network(**extracted)

        self['networking_config'] = self['client'].create_networking_config({
            extracted['name']: self['client'].create_endpoint_config()
        })

class ContainerFactory(BaseFactory):

    ip = None
    type = 'docker'
    config = factory.SubFactory(
        ContainerConfigFactory,
        networking_config=dict(name="network1", driver="bridge")
    )

    class Meta:
        model = ContainerModel

    @classmethod
    def build(cls, **kwargs):
        obj = super(ContainerFactory, cls).build(**kwargs)
        assert obj['config']['image']
        client = obj['config']['client']
        client.create_container(
            **{
                k: obj['config'][k] for k in obj['config'].keys()
                if k not in ['salt_config', 'client']
            }
        )
        obj['config']['client'].start(obj['config'])
        obj['ip'] = obj['config']['client'].getip(obj['config']['name'])

        try:
            resp = obj.run('salt --version')
            message = "{0}: {1}".format(
                obj['config']['salt_config']['conf_type'], resp.strip())
            logger.info(message)
        except TypeError:
            pass

        return obj

    @factory.post_generation
    def ip(self, create, extracted, **kwargs):
        if not create:
            return extracted

class SaltFactory(BaseFactory):

    container = factory.SubFactory(ContainerFactory)

    @classmethod
    def build(cls, **kwargs):
        obj = super(SaltFactory, cls).build(**kwargs)
        client = obj['container']['config']['client']

        client.configure_salt(obj['container']['config'])

        output = client.run(
            obj['container']['config']['name'], obj['cmd']
        )
        assert 'executable file not found' not in output
        return obj

class MasterFactory(SaltFactory):
    id = factory.LazyAttribute(lambda o: o.container['config']['salt_config']['id'])
    cmd = 'salt-master -d -l debug'
    container = factory.SubFactory(
        ContainerFactory,
        config__salt_config=factory.SubFactory(MasterSaltConfigFactory)
    )

    class Meta:
        model = MasterModel

    @classmethod
    def build(cls, **kwargs):
        obj = super(MasterFactory, cls).build(**kwargs)
        obj['container'].run("salt-call --local state.apply")
        return obj

class SyndicFactory(MasterFactory):

    container = factory.SubFactory(
        ContainerFactory,
        config__salt_config=factory.SubFactory(SyndicSaltConfigFactory)
    )

    @classmethod
    def build(cls, **kwargs):
        obj = super(SyndicFactory, cls).build(**kwargs)
        cmd = 'salt-syndic -d -l debug'
        docker_client = obj['container']['config']['docker_client']
        res = docker_client.exec_create(
            obj['container']['config']['name'], cmd)
        output = docker_client.exec_start(res['Id'])
        assert 'executable file not found' not in output
        return obj

class MinionFactory(SaltFactory):
    id = factory.LazyAttribute(lambda o: o.container['config']['salt_config']['id'])
    cmd = 'salt-minion -d -l debug'

    class Meta:
        model = MinionModel
<|endoftext|>


<commit_before><commit_msg>Implementando metodo off.<commit_after><|endoftext|>


<commit_before>from os import path

from sdl2 import *
from ctypes import ArgumentError
from glaze.GL import loadGL, glGetIntegerv, glGetStringi, glGetString, GL_NUM_SHADING_LANGUAGE_VERSIONS, \
    GL_SHADING_LANGUAGE_VERSION, \
    GL_VERSION, GL_NUM_EXTENSIONS, GL_EXTENSIONS, glEnable, GL_MULTISAMPLE

from .Logging import _Logger, logLevelsEnum
from .backends.base_backend import BaseBackend
from .events_processing.EventsManagerClass import Event, EventsManager
from .scene_management.ScenesManagerClass import ScenesManager
from .texture_management.TextureManagerClass import TexturesManager
from .windowing.sdl_window import Window
from .ThreadingManagerClass import ThreadingManager
from .plugin_management.PluginsManagerClass import PluginsManager
from .video import VideoManager

class globalsStruct:
    oglversionraw = None
    oglmajor = None
    oglminor = None
    glslmajor = None
    glslminor = None
    dummyContext = None
    dummyWindow = None
    glslall = None
    multisample = False

class Engine:
    def __init__(self, backend, multiSampleLevel=0, maxContext=(2, 1), useQT=False, useDebug=False):
        self._logger = _Logger()
        if not useQT:
            # Init SDL>>>>>>>>>>>>>>>>>>>>>>>>>
            if SDL_Init(SDL_INIT_EVERYTHING) != 0:
                sdlerr = self.getSDLError()
                self.log('Error on SDL init: ' + sdlerr, logLevelsEnum.error)
                raise Exception('Error on SDL init: ' + sdlerr)

        self.maxContext = maxContext
        assert issubclass(backend, BaseBackend)
        self.backend = backend
        self.path = EngineRoot((path.dirname(__file__),))

        self.events = EventsManager()
        self.textures = TexturesManager()
        self.scenes = ScenesManager()
        self.videos = VideoManager()
        self.threading = ThreadingManager()
        self.plugins = PluginsManager()
        self.globals = globalsStruct()
        self.models = None
        self.shaders = None
        self.sounds = None
        self.io = None
        self.localqueue = None
        self._running = False
        self._windows = {}
        self._useQT = useQT
        self._isInitialized = False

        if not useQT:
            self._setAttribs(multiSampleLevel, maxContext, useDebug)

    def initialize(self, maxThreads=2):
        self._createDummyWindowAndContext()
        loadGL()
        self._fillGLInfo()
        self.backend = self.backend(self)
        self._initializeManagers(maxThreads)
        self._isInitialized = True

    def _initializeManagers(self, maxThreads):
        # self.localqueue = Queue()

        self.log('Initializing systems...', logLevelsEnum.debug)

        self.log('\t Shaders...', logLevelsEnum.debug)
        self.shaders = self.backend.getShadersManager()

        self.log('\t Textures...', logLevelsEnum.debug)
        self.textures.initialize(self)

        self.log('\t Models...', logLevelsEnum.debug)
        from .model_management.ModelsManagerClass import ModelsManager
        self.models = ModelsManager()
        self.models.initialize(self)

        self.log('\t Sounds...', logLevelsEnum.debug)
        from .sound_management.SoundsManagerClass import SoundsManager
        self.sounds = SoundsManager()

        # self.log('\t IOHelper...', logLevelsEnum.debug)
        # from .IOHelperClass import IOHelper
        # self.io = IOHelper()

        self.log('\t Threading...', logLevelsEnum.debug)
        self.threading.initialize(maxThreads)

        self.log('\t Scenes...', logLevelsEnum.debug)
        self.scenes.initialize(self)

        self.log('\t Plugins...', logLevelsEnum.debug)
        self.plugins.initialize(self)

        self.log('\t Videos...', logLevelsEnum.debug)
        self.videos.initialize(self)

    def _setAttribs(self, multiSampleLevel, restrictContextTo, useDebug):
        SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8)
        SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8)
        SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8)
        SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8)
        SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 24)

        for depth in [24, 16]:
            if SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, depth) == 0:
                break
            else:
                if depth == 16:
                    error = 'Error setting depth size: ' + self.getSDLError()
                    self.log(error)
                    raise RuntimeError(error)

        if restrictContextTo:
            # Todo: add context fallback
            SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, restrictContextTo[0])
            SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, restrictContextTo[1])

        # SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG)
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE)

        if useDebug:
            res = SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG)
            if res != 0:
                error = 'Error setting SDL debug context flag: ' + self.getSDLError()
                self.log(error)
                raise RuntimeError(error)

        if SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1) != 0:
            error = 'Error setting SDL shared context flag: ' + self.getSDLError()
            self.log(error)
            raise RuntimeError(error)

        isDOubleBuffered = not SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1)

        if not isDOubleBuffered:
            self.log('Error setting SDL double buffer flag: ' + self.getSDLError(), logLevelsEnum.info)

        if multiSampleLevel is not None and multiSampleLevel > 0:
            from warnings import warn
            warn('Multisample is not implemented')
            # self._multisampleSetup(multiSampleLevel, SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN)

        # Next causes multisample to fail.
        # if SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1) != 0:
        #     error = 'Error setting SDL hw acceleration flag: ' + self.getSDLError()
        #     self.log(error)
        #     raise RuntimeError(error)

    def updateLoop(self):
        self._running = True
        while self._running:
            activeWindows = {}
            while len(self._windows) > 0:
                winID, win = self._windows.popitem()
                if win._running:
                    win.update()
                    activeWindows[winID] = win
            if len(activeWindows) > 0:
                self._windows = activeWindows.copy()
            else:
                self._running = False

        for win in self._windows.values():
            try:
                win.close()
            except:
                pass

    def _terminateManagers(self):
        if self._isInitialized:
            self.log('Terminating systems...', logLevelsEnum.debug)
            self.textures.terminate()
            self.shaders.terminate()
            self.sounds.terminate()
            self.scenes.terminate()
            self.threading.terminate()
            self.plugins.terminate()
            self.videos.terminate()

            # self.localqueue.close()

    def postEvent(self, event):
        if not issubclass(type(event), Event) or not isinstance(event, Event):
            raise TypeError('"event" object must be of type "Event" or inherith from it.\n'
                            'It is of type: ' + str(type(event)))

        self.events._announce(event)

    def createWindow(self, title='', gameName='', size=None, FullScreenSize=None, fullscreen=False,
                     vSynch=True, iconPath=None):
        """

        :rtype: Window
        """
        if not self._isInitialized:
            raise RuntimeError('engine is not initialized')
        win = Window(self, title, gameName, size, FullScreenSize, fullscreen, vSynch, iconPath)
        self._windows[id(win)] = win
        return win

    def createQTWidget(self, title='', gameName='', size=None, FullScreenSize=None, fullscreen=False,
                       vSynch=True, iconPath=None):
        """

        :rtype: e3DGLWidget
        """

        if not self._isInitialized:
            raise RuntimeError('engine is not initialized')
        from .windowing.qt_window import e3DGLWidget
        win = e3DGLWidget(self, title, gameName, size, FullScreenSize, fullscreen, vSynch, iconPath)
        return win

    def _fillGLInfo(self):
        self.globals.oglversionraw = glGetString(GL_VERSION)
        ss = self.globals.oglversionraw.split(' ')
        ss2 = ss[0].split('.')
        self.globals.oglmajor = int(ss2[0])
        self.globals.oglminor = int(ss2[1])
        ssb = glGetString(GL_SHADING_LANGUAGE_VERSION).split(' ')
        ss3 = ssb[0].split('.')
        self.globals.glslmajor = int(ss3[0])
        self.globals.glslminor = int(ss3[1])

        try:
            self._fillSuportedGLSLVersions()
        except:
            pass
        self.log('OpenGL version: ' + str(self.globals.oglversionraw), logLevelsEnum.info)
        self.log('GLSL version: {}.{}'.format(self.globals.glslmajor, self.globals.glslminor), logLevelsEnum.info)
        if len(self.globals.glslall) > 0:
            self.log('{} GLSL supported versions'.format(len(self.globals.glslall)), logLevelsEnum.debug)
            for ver in self.globals.glslall:
                self.log('{} GLSL supported'.format(ver))

    def _fillSuportedGLSLVersions(self):
        import numpy as np
        num = np.array([0], np.int32)
        glGetIntegerv(GL_NUM_SHADING_LANGUAGE_VERSIONS, num)
        vl = []
        for e in range(num[0]):
            vl.append(glGetStringi(GL_SHADING_LANGUAGE_VERSION, e))
        self.globals.glslall = vl

    def logSupportedExtensions(self):
        num = glGetIntegerv(GL_NUM_EXTENSIONS)
        for e in range(num):
            self.log(glGetStringi(GL_EXTENSIONS, e), logLevelsEnum.info)

    def _createDummyWindowAndContext(self):
        if not self._useQT:
            self._dummySDL()
        else:
            self._dummyQT()

    def _dummyQT(self):
        from PySide.QtOpenGL import QGLWidget, QGLFormat
        format = QGLFormat()
        format.setRedBufferSize(8)
        format.setGreenBufferSize(8)
        format.setBlueBufferSize(8)
        format.setDepthBufferSize(24)
        format.setAlphaBufferSize(8)
        format.setDoubleBuffer(True)
        format.setDirectRendering(True)
        format.setDepth(True)
        format.setAlpha(True)
        format.setVersion(2, 1)
        format.setProfile(QGLFormat.CoreProfile)

        self._format = format
        try:
            self.globals.dummyWindow = QGLWidget(format)
        except Exception as ex:
            error = 'Error creating dummy window: ' + str(ex)
            self.log(error, logLevelsEnum.error)
            raise RuntimeError(error)

        try:
            _, self.globals.dummyContext = self._getNewContext()
        except:
            raise
        self.globals.dummyWindow.makeCurrent()

    def _dummySDL(self):
        flags = SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN

        try:
            self.globals.dummyWindow = SDL_CreateWindow('', -1, -1, 0, 0, flags)
        except ArgumentError:
            self.globals.dummyWindow = SDL_CreateWindow(b'', -1, -1, 0, 0, flags)
        sdlerr = self.getSDLError()
        if self.globals.dummyWindow is None or sdlerr != '':
            error = 'Error creating dummy window: ' + sdlerr
            self.log(error, logLevelsEnum.error)
            raise RuntimeError(error)

        try:
            _, self.globals.dummyContext = self._getNewContext()
        except:
            raise
        SDL_GL_MakeCurrent(self.globals.dummyWindow, self.globals.dummyContext)

    def _getNewContext(self, window=None):
        """

        @rtype : (SDL_Window, SDL_GLContext)
        """
        if window is None:
            window = self.globals.dummyWindow
        if not self._useQT:
            newContext = SDL_GL_CreateContext(window)
            if not newContext:
                sdlerr = self.getSDLError()
                error = 'Error creating context: ' + sdlerr
                self.log(error, logLevelsEnum.error)
                raise RuntimeError(error)
        else:
            newContext = self.globals.dummyWindow.context()  # todo: check correction with qt

        return window, newContext

    def _multisampleSetup(self, multisampleLevel, flags):
        window = None
        ms = SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1)
        if ms < 0:
            self.log('Error enabling multisample: ' + self.getSDLError(), logLevelsEnum.warning)
            self.globals.multisample = False
        else:
            self.globals.multisample = True
        level = multisampleLevel
        while level > 0:
            if SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, level) == 0:
                try:
                    window = SDL_CreateWindow('', -1, -1, 0, 0, flags)
                except ArgumentError:
                    window = SDL_CreateWindow(b'', -1, -1, 0, 0, flags)
                cont = SDL_GL_CreateContext(window)
                if cont is not None:
                    SDL_GL_DeleteContext(cont)
                    break

            level -= 1
            if level > 0:
                if window is not None:
                    SDL_DestroyWindow(window)
                    window = None
                self.log('Error setting multisample level {}. Trying {}'.format(level + 1, level), logLevelsEnum.info)

        if level == 0:
            self.log('Multisample disabled: ' + self.getSDLError() + ".")
            SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0)
            SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0)

        if window is not None:
            SDL_DestroyWindow(window)

    @staticmethod
    def getSDLError():
        sderr = SDL_GetError()
        try:
            sderr = sderr.decode()
        except:
            pass
        return sderr

    def terminate(self):
        self._running = False
        try:
            self._terminateManagers()
        except Exception as ex:
            self.log('Error in \'Engine.terminate\': ' + str(ex), logLevelsEnum.error)
        if not self._useQT:
            if self._isInitialized:
                SDL_GL_DeleteContext(self.globals.dummyContext)
                SDL_DestroyWindow(self.globals.dummyWindow)
            SDL_Quit()
        else:
            if self._isInitialized:
                self.globals.dummyWindow.doneCurrent()
                self.globals.dummyWindow.deleteLater()
        self.log('Engine Terminated', logLevelsEnum.info)

    def log(self, message, messageType=logLevelsEnum.debug):
        self._logger.log(message, messageType)

class PathPiece(str):
    def __new__(cls, elements):
        basePath = path.join(*elements)
        base = path.abspath(basePath)
        obj = str.__new__(cls, base)
        obj.base = base
        return obj

class EngineRoot(PathPiece):
    def __init__(self, elements):
        super(EngineRoot, self).__init__()
        self.defaults = DefaultPath((self.base, 'defaults'))

class DefaultPath(PathPiece):
    def __init__(self, elements):
        super(DefaultPath, self).__init__()
        self.shaders = PathPiece((self.base, 'shaders'))
        self.textures = PathPiece((self.base, 'textures'))
        self.primitives = PathPiece((self.base, 'primitives'))
        self.fonts = PathPiece((self.base, 'fonts'))
        # self.sounds = PathPiece((self.base, 'sounds'))

<commit_msg>Fix typos.<commit_after>from os import path

from sdl2 import *
from ctypes import ArgumentError
from glaze.GL import loadGL, glGetIntegerv, glGetStringi, glGetString, GL_NUM_SHADING_LANGUAGE_VERSIONS, \
    GL_SHADING_LANGUAGE_VERSION, \
    GL_VERSION, GL_NUM_EXTENSIONS, GL_EXTENSIONS, glEnable, GL_MULTISAMPLE

from .Logging import _Logger, logLevelsEnum
from .backends.base_backend import BaseBackend
from .events_processing.EventsManagerClass import Event, EventsManager
from .scene_management.ScenesManagerClass import ScenesManager
from .texture_management.TextureManagerClass import TexturesManager
from .windowing.sdl_window import Window
from .ThreadingManagerClass import ThreadingManager
from .plugin_management.PluginsManagerClass import PluginsManager
from .video import VideoManager

class globalsStruct:
    oglversionraw = None
    oglmajor = None
    oglminor = None
    glslmajor = None
    glslminor = None
    dummyContext = None
    dummyWindow = None
    glslall = None
    multisample = False

class Engine:
    def __init__(self, backend, multiSampleLevel=0, maxContext=(2, 1), useQT=False, useDebug=False):
        self._logger = _Logger()
        if not useQT:
            # Init SDL>>>>>>>>>>>>>>>>>>>>>>>>>
            if SDL_Init(SDL_INIT_EVERYTHING) != 0:
                sdlerr = self.getSDLError()
                self.log('Error on SDL init: ' + sdlerr, logLevelsEnum.error)
                raise Exception('Error on SDL init: ' + sdlerr)

        self.maxContext = maxContext
        assert issubclass(backend, BaseBackend)
        self.backend = backend
        self.path = EngineRoot((path.dirname(__file__),))

        self.events = EventsManager()
        self.textures = TexturesManager()
        self.scenes = ScenesManager()
        self.videos = VideoManager()
        self.threading = ThreadingManager()
        self.plugins = PluginsManager()
        self.globals = globalsStruct()
        self.models = None
        self.shaders = None
        self.sounds = None
        self.io = None
        self.localqueue = None
        self._running = False
        self._windows = {}
        self._useQT = useQT
        self._isInitialized = False

        if not useQT:
            self._setAttribs(multiSampleLevel, maxContext, useDebug)

    def initialize(self, maxThreads=2):
        self._createDummyWindowAndContext()
        loadGL()
        self._fillGLInfo()
        self.backend = self.backend(self)
        self._initializeManagers(maxThreads)
        self._isInitialized = True

    def _initializeManagers(self, maxThreads):
        # self.localqueue = Queue()

        self.log('Initializing systems...', logLevelsEnum.debug)

        self.log('\t Shaders...', logLevelsEnum.debug)
        self.shaders = self.backend.getShadersManager()

        self.log('\t Textures...', logLevelsEnum.debug)
        self.textures.initialize(self)

        self.log('\t Models...', logLevelsEnum.debug)
        from .model_management.ModelsManagerClass import ModelsManager
        self.models = ModelsManager()
        self.models.initialize(self)

        self.log('\t Sounds...', logLevelsEnum.debug)
        from .sound_management.SoundsManagerClass import SoundsManager
        self.sounds = SoundsManager()

        # self.log('\t IOHelper...', logLevelsEnum.debug)
        # from .IOHelperClass import IOHelper
        # self.io = IOHelper()

        self.log('\t Threading...', logLevelsEnum.debug)
        self.threading.initialize(maxThreads)

        self.log('\t Scenes...', logLevelsEnum.debug)
        self.scenes.initialize(self)

        self.log('\t Plugins...', logLevelsEnum.debug)
        self.plugins.initialize(self)

        self.log('\t Videos...', logLevelsEnum.debug)
        self.videos.initialize(self)

    def _setAttribs(self, multiSampleLevel, restrictContextTo, useDebug):
        SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8)
        SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8)
        SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8)
        SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8)
        SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 24)

        for depth in [24, 16]:
            if SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, depth) == 0:
                break
            else:
                if depth == 16:
                    error = 'Error setting depth size: ' + self.getSDLError()
                    self.log(error)
                    raise RuntimeError(error)

        if restrictContextTo:
            # Todo: add context fallback
            SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, restrictContextTo[0])
            SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, restrictContextTo[1])

        # SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG)
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE)

        if useDebug:
            res = SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG)
            if res != 0:
                error = 'Error setting SDL debug context flag: ' + self.getSDLError()
                self.log(error)
                raise RuntimeError(error)

        if SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1) != 0:
            error = 'Error setting SDL shared context flag: ' + self.getSDLError()
            self.log(error)
            raise RuntimeError(error)

        isDoubleBuffered = not SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1)

        if not isDoubleBuffered:
            self.log('Error setting SDL double buffer flag: ' + self.getSDLError(), logLevelsEnum.info)

        if multiSampleLevel is not None and multiSampleLevel > 0:
            from warnings import warn
            warn('Multisample is not implemented')
            # self._multisampleSetup(multiSampleLevel, SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN)

        # Next causes multisample to fail.
        # if SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1) != 0:
        #     error = 'Error setting SDL hw acceleration flag: ' + self.getSDLError()
        #     self.log(error)
        #     raise RuntimeError(error)

    def updateLoop(self):
        self._running = True
        while self._running:
            activeWindows = {}
            while len(self._windows) > 0:
                winID, win = self._windows.popitem()
                if win._running:
                    win.update()
                    activeWindows[winID] = win
            if len(activeWindows) > 0:
                self._windows = activeWindows.copy()
            else:
                self._running = False

        for win in self._windows.values():
            try:
                win.close()
            except Exception:
                pass

    def _terminateManagers(self):
        if self._isInitialized:
            self.log('Terminating systems...', logLevelsEnum.debug)
            self.textures.terminate()
            self.shaders.terminate()
            self.sounds.terminate()
            self.scenes.terminate()
            self.threading.terminate()
            self.plugins.terminate()
            self.videos.terminate()

            # self.localqueue.close()

    def postEvent(self, event):
        if not issubclass(type(event), Event) or not isinstance(event, Event):
            raise TypeError('"event" object must be of type "Event" or inherith from it.\n'
                            'It is of type: ' + str(type(event)))

        self.events._announce(event)

    def createWindow(self, title='', gameName='', size=None, FullScreenSize=None, fullscreen=False,
                     vSynch=True, iconPath=None):
        """

        :rtype: Window
        """
        if not self._isInitialized:
            raise RuntimeError('engine is not initialized')
        win = Window(self, title, gameName, size, FullScreenSize, fullscreen, vSynch, iconPath)
        self._windows[id(win)] = win
        return win

    def createQTWidget(self, title='', gameName='', size=None, FullScreenSize=None, fullscreen=False,
                       vSynch=True, iconPath=None):
        """

        :rtype: e3DGLWidget
        """

        if not self._isInitialized:
            raise RuntimeError('engine is not initialized')
        from .windowing.qt_window import e3DGLWidget
        win = e3DGLWidget(self, title, gameName, size, FullScreenSize, fullscreen, vSynch, iconPath)
        return win

    def _fillGLInfo(self):
        self.globals.oglversionraw = glGetString(GL_VERSION)
        ss = self.globals.oglversionraw.split(' ')
        ss2 = ss[0].split('.')
        self.globals.oglmajor = int(ss2[0])
        self.globals.oglminor = int(ss2[1])
        ssb = glGetString(GL_SHADING_LANGUAGE_VERSION).split(' ')
        ss3 = ssb[0].split('.')
        self.globals.glslmajor = int(ss3[0])
        self.globals.glslminor = int(ss3[1])

        try:
            self._fillSuportedGLSLVersions()
        except Exception:
            pass
        self.log('OpenGL version: ' + str(self.globals.oglversionraw), logLevelsEnum.info)
        self.log('GLSL version: {}.{}'.format(self.globals.glslmajor, self.globals.glslminor), logLevelsEnum.info)
        if len(self.globals.glslall) > 0:
            self.log('{} GLSL supported versions'.format(len(self.globals.glslall)), logLevelsEnum.debug)
            for ver in self.globals.glslall:
                self.log('{} GLSL supported'.format(ver))

    def _fillSuportedGLSLVersions(self):
        import numpy as np
        num = np.array([0], np.int32)
        glGetIntegerv(GL_NUM_SHADING_LANGUAGE_VERSIONS, num)
        vl = []
        for e in range(num[0]):
            vl.append(glGetStringi(GL_SHADING_LANGUAGE_VERSION, e))
        self.globals.glslall = vl

    def logSupportedExtensions(self):
        num = glGetIntegerv(GL_NUM_EXTENSIONS)
        for e in range(num):
            self.log(glGetStringi(GL_EXTENSIONS, e), logLevelsEnum.info)

    def _createDummyWindowAndContext(self):
        if not self._useQT:
            self._dummySDL()
        else:
            self._dummyQT()

    def _dummyQT(self):
        from PySide.QtOpenGL import QGLWidget, QGLFormat
        format = QGLFormat()
        format.setRedBufferSize(8)
        format.setGreenBufferSize(8)
        format.setBlueBufferSize(8)
        format.setDepthBufferSize(24)
        format.setAlphaBufferSize(8)
        format.setDoubleBuffer(True)
        format.setDirectRendering(True)
        format.setDepth(True)
        format.setAlpha(True)
        format.setVersion(2, 1)
        format.setProfile(QGLFormat.CoreProfile)

        self._format = format
        try:
            self.globals.dummyWindow = QGLWidget(format)
        except Exception as ex:
            error = 'Error creating dummy window: ' + str(ex)
            self.log(error, logLevelsEnum.error)
            raise RuntimeError(error)

        try:
            _, self.globals.dummyContext = self._getNewContext()
        except Exception:
            raise
        self.globals.dummyWindow.makeCurrent()

    def _dummySDL(self):
        flags = SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN

        try:
            self.globals.dummyWindow = SDL_CreateWindow('', -1, -1, 0, 0, flags)
        except ArgumentError:
            self.globals.dummyWindow = SDL_CreateWindow(b'', -1, -1, 0, 0, flags)
        sdlerr = self.getSDLError()
        if self.globals.dummyWindow is None or sdlerr != '':
            error = 'Error creating dummy window: ' + sdlerr
            self.log(error, logLevelsEnum.error)
            raise RuntimeError(error)

        try:
            _, self.globals.dummyContext = self._getNewContext()
        except Exception:
            raise
        SDL_GL_MakeCurrent(self.globals.dummyWindow, self.globals.dummyContext)

    def _getNewContext(self, window=None):
        """

        @rtype : (SDL_Window, SDL_GLContext)
        """
        if window is None:
            window = self.globals.dummyWindow
        if not self._useQT:
            newContext = SDL_GL_CreateContext(window)
            if not newContext:
                sdlerr = self.getSDLError()
                error = 'Error creating context: ' + sdlerr
                self.log(error, logLevelsEnum.error)
                raise RuntimeError(error)
        else:
            newContext = self.globals.dummyWindow.context()  # todo: check correction with qt

        return window, newContext

    def _multisampleSetup(self, multisampleLevel, flags):
        window = None
        ms = SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1)
        if ms < 0:
            self.log('Error enabling multisample: ' + self.getSDLError(), logLevelsEnum.warning)
            self.globals.multisample = False
        else:
            self.globals.multisample = True
        level = multisampleLevel
        while level > 0:
            if SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, level) == 0:
                try:
                    window = SDL_CreateWindow('', -1, -1, 0, 0, flags)
                except ArgumentError:
                    window = SDL_CreateWindow(b'', -1, -1, 0, 0, flags)
                cont = SDL_GL_CreateContext(window)
                if cont is not None:
                    SDL_GL_DeleteContext(cont)
                    break

            level -= 1
            if level > 0:
                if window is not None:
                    SDL_DestroyWindow(window)
                    window = None
                self.log('Error setting multisample level {}. Trying {}'.format(level + 1, level), logLevelsEnum.info)

        if level == 0:
            self.log('Multisample disabled: ' + self.getSDLError() + ".")
            SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0)
            SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0)

        if window is not None:
            SDL_DestroyWindow(window)

    @staticmethod
    def getSDLError():
        sderr = SDL_GetError()
        try:
            sderr = sderr.decode()
        except Exception:
            pass
        return sderr

    def terminate(self):
        self._running = False
        try:
            self._terminateManagers()
        except Exception as ex:
            self.log('Error in \'Engine.terminate\': ' + str(ex), logLevelsEnum.error)
        if not self._useQT:
            if self._isInitialized:
                SDL_GL_DeleteContext(self.globals.dummyContext)
                SDL_DestroyWindow(self.globals.dummyWindow)
            SDL_Quit()
        else:
            if self._isInitialized:
                self.globals.dummyWindow.doneCurrent()
                self.globals.dummyWindow.deleteLater()
        self.log('Engine Terminated', logLevelsEnum.info)

    def log(self, message, messageType=logLevelsEnum.debug):
        self._logger.log(message, messageType)

class PathPiece(str):
    def __new__(cls, elements):
        basePath = path.join(*elements)
        base = path.abspath(basePath)
        obj = str.__new__(cls, base)
        obj.base = base
        return obj

class EngineRoot(PathPiece):
    def __init__(self, elements):
        super(EngineRoot, self).__init__()
        self.defaults = DefaultPath((self.base, 'defaults'))

class DefaultPath(PathPiece):
    def __init__(self, elements):
        super(DefaultPath, self).__init__()
        self.shaders = PathPiece((self.base, 'shaders'))
        self.textures = PathPiece((self.base, 'textures'))
        self.primitives = PathPiece((self.base, 'primitives'))
        self.fonts = PathPiece((self.base, 'fonts'))
        # self.sounds = PathPiece((self.base, 'sounds'))
<|endoftext|>