Ejemplo n.º 1
0
	def load(self, path):
		path = os.path.realpath(path)
		
		self._initPath( path )
		self._affirmDirectories()
		os.chdir( path )

		sys.path.insert( 0, self.envLibPath )
		sys.path.insert( 0, self.getBinaryPath( 'python' ) ) #for python extension modules

		self.info   = jsonHelper.tryLoadJSON( self.getBasePath( _GII_INFO_FILE ) )
		self.config = jsonHelper.tryLoadJSON( self.getConfigPath( _GII_CONFIG_FILE ) )
		if not self.config:
			self.config = {}
			jsonHelper.trySaveJSON( self.config, self.getConfigPath( _GII_CONFIG_FILE ) )

		if not self.info:
			self.info = {
				'name' : 'name',
				'version' : [0,0,1],
			}
			jsonHelper.trySaveJSON( self.info, self.getBasePath( _GII_INFO_FILE ) )
			
		self.cacheManager.load( _GII_ENV_CONFIG_DIR, self.envConfigPath )
		self.assetLibrary.load( _GII_ASSET_DIR, self.assetPath, self.path, self.envConfigPath )

		#will trigger other module
		signals.emitNow( 'project.preload', self )
		signals.emitNow( 'project.load', self )
		
		logging.info( 'project loaded: %s' % path )

		return True
Ejemplo n.º 2
0
    def run(self, **kwargs):
        if not self.initialized:
            if not self.init(**kwargs):
                return False
        hasError = False
        self.resetMainLoopBudget()

        try:
            signals.emitNow('app.pre_start')

            EditorModuleManager.get().startAllModules()
            self.getProject().getAssetLibrary().scanProject()

            signals.emitNow('app.start')
            signals.dispatchAll()

            self.saveConfig()

            EditorModuleManager.get().tellAllModulesAppReady()
            signals.emit('app.ready')

            #main loop
            while self.running:
                self.doMainLoop()

        except Exception, e:
            #TODO: popup a alert window?
            logging.exception(e)
            hasError = True
Ejemplo n.º 3
0
	def load(self, path):
		if not path:
			path = self.path
			if not self.path: return False

		if not os.path.exists( path + '/' + _PROJECT_INFO_FILE ): return False

		self._initPath( path )
		self._affirmDirectories()
		self.info = jsonHelper.tryLoadJSON( self.getBasePath( _PROJECT_INFO_FILE ) )

		if not os.path.exists( self.editorPath ):
			os.makedirs( self.editorPath )
		self.config = jsonHelper.tryLoadJSON( self.getBasePath( _PROJECT_EDITOR_DIR + '/' + _PROJECT_CONFIG_FILE ) )
		if not self.config:
			self.config = {}
			self.saveConfig()

		# self.cacheManager.load( _GII_ENV_CONFIG_DIR, self.envConfigPath )
		# self.assetLibrary.load( _GII_ASSET_DIR, self.assetPath, self.path, self.envConfigPath )

		self.loaded = True
		signals.emitNow( 'project.preload', self )
		signals.emitNow( 'project.load', self )

		return True
Ejemplo n.º 4
0
	def run( self, **kwargs ):
		if not self.initialized: 
			if not self.init( **kwargs ):
				return False
		hasError = False
		self.resetMainLoopBudget()
		
		try:
			signals.emitNow('app.pre_start')

			EditorModuleManager.get().startAllModules()
			self.getProject().getAssetLibrary().scanProject()

			signals.emitNow('app.start')
			signals.dispatchAll()

			self.saveConfig()

			EditorModuleManager.get().tellAllModulesAppReady()
			signals.emit('app.ready')

			#main loop
			while self.running:
				self.doMainLoop()

		except Exception, e:
			#TODO: popup a alert window?
			logging.exception( e )
			hasError = True
Ejemplo n.º 5
0
	def historyForward(self):
		hisSize = len(self.history)
		if self.historyPos > 0:
			self.historyPos -= 1
			selection=self.history[hisSize - self.historyPos]
			self.currentSelection=selection
			signals.emitNow('selection.changed', selection, self.key )
Ejemplo n.º 6
0
	def historyBack(self):
		hisSize = len(self.history)
		if self.historyPos < hisSize:
			self.historyPos += 1
			selection=self.history[hisSize - self.historyPos]
			self.currentSelection=selection
			signals.emitNow('selection.changed', selection, self.key )
Ejemplo n.º 7
0
    def load(self, path):
        if not path:
            path = self.path
            if not self.path: return False

        if not os.path.exists(path + '/' + _PROJECT_INFO_FILE): return False

        self._initPath(path)
        self._affirmDirectories()
        self.info = jsonHelper.tryLoadJSON(
            self.getBasePath(_PROJECT_INFO_FILE))

        if not os.path.exists(self.editorPath):
            os.makedirs(self.editorPath)
        self.config = jsonHelper.tryLoadJSON(
            self.getBasePath(_PROJECT_EDITOR_DIR + '/' + _PROJECT_CONFIG_FILE))
        if not self.config:
            self.config = {}
            self.saveConfig()

        # self.cacheManager.load( _GII_ENV_CONFIG_DIR, self.envConfigPath )
        # self.assetLibrary.load( _GII_ASSET_DIR, self.assetPath, self.path, self.envConfigPath )

        self.loaded = True
        signals.emitNow('project.preload', self)
        signals.emitNow('project.load', self)

        return True
Ejemplo n.º 8
0
 def changeSelection(self, selection):
     if selection:  # tommo todo: use weakref to hold selection
         if not isinstance(selection, list): selection = [selection]
     if selection is None:
         selection = []
         if not self.currentSelection: return
     self.currentSelection = selection
     signals.emitNow('selection.changed', selection, self.key)
Ejemplo n.º 9
0
	def changeSelection( self, selection ):
		if selection: # tommo todo: use weakref to hold selection	
			if not isinstance(selection, list): selection = [ selection ]
		if selection is None:
			selection = []
			if not self.currentSelection: return
		self.currentSelection = selection
		signals.emitNow('selection.changed', selection, self.key )
Ejemplo n.º 10
0
	def save(self):
		signals.emitNow('project.presave', self)

		if self.getBasePath():
			jsonHelper.trySaveJSON( self.info, self.getBasePath( _PROJECT_INFO_FILE ) )

		#save asset & cache
		self.assetLibrary.save()
		self.cacheManager.clearFreeCacheFiles()
		self.cacheManager.save()

		signals.emitNow( 'project.save', self )
		return True
Ejemplo n.º 11
0
    def init(self, **options):
        if options.get('stop_other_instance', False):
            if not checkSingleInstance():
                retryCount = 5
                logging.warning(
                    'running instance detected, trying to shut it down')
                sendRemoteMsg('shut_down')
                ready = False
                for i in range(retryCount):
                    time.sleep(1)
                    if checkSingleInstance():
                        ready = True
                        break
                if not ready:
                    logging.warning('timeout for shuting down other instance')
                    return False

        else:
            if not checkSingleInstance():
                logging.warning('running instance detected')
                return False

        self.loadConfig()

        if self.initialized: return True
        self.openProject()

        #scan packages
        excludePackages = self.getProject().getConfig('excluded_packages')
        self.packageManager.addExcludedPackage(excludePackages)

        if not self.packageManager.scanPackages(
                self.getPath(_GII_BUILTIN_PACKAGES_PATH)):
            return False

        if self.getProject().isLoaded():
            self.packageManager.scanPackages(self.getProject().envPackagePath)

        #modules
        EditorModuleManager.get().loadAllModules()
        signals.emitNow('module.loaded')  #some pre app-ready activities
        signals.dispatchAll()

        self.getProject().loadAssetLibrary()

        self.initialized = True
        self.running = True

        signals.connect('app.remote', self.onRemote)

        return True
Ejemplo n.º 12
0
	def save( self ):
		logging.info( 'saving current project' )
		signals.emitNow('project.presave', self)
		#save project info & config
		jsonHelper.trySaveJSON( self.info,   self.getBasePath( _GII_INFO_FILE ), 'project info' )

		#save asset & cache
		self.assetLibrary.save()
		self.cacheManager.clearFreeCacheFiles()
		self.cacheManager.save()

		signals.emitNow( 'project.save', self ) #post save
		logging.info( 'project saved' )
		return True
Ejemplo n.º 13
0
	def changeSelection( self, selection ):
		#todo: use weakref to hold selection		
		if selection:			
			if not isinstance(selection, list): selection = [ selection ]
			hisSize = len(self.history)
			self.history = self.history[:hisSize - self.historyPos]
			self.history.append(selection)
			self.history = self.history[0:self.maxHistorySize]
			self.historyPos = 0
		if selection is None:
			selection = []
			if not self.currentSelection: return
		self.currentSelection = selection
		signals.emitNow('selection.changed', selection, self.key )
Ejemplo n.º 14
0
    def deploy(self, **option):
        base = self.getPath(option.get('path', 'output'))
        context = DeployContext(base)
        context.cleanPath()
        hostResPath = self.getHostPath('resource')
        gameLibPath = self.getGamePath('lib')

        logging.info('deploy current project')
        context.copyFilesInDir(hostResPath)
        context.copyFile(gameLibPath, 'lib')
        signals.emitNow('project.pre_deploy', context)
        #deploy asset library
        objectFiles = []

        for node in self.assetLibrary.assetTable.values():
            mgr = node.getManager()
            if not mgr: continue
            mgr.deployAsset(node, context)
        #copy scripts
        #copy static resources
        signals.emitNow('project.deploy', context)
        self.assetLibrary.saveAssetTable(path=base + '/asset/asset_index',
                                         deploy_context=context)
        context.flushTask()
        signals.emitNow('project.post_deploy', context)
        print('Deploy building done!')
        signals.emitNow('project.done_deploy', context)
Ejemplo n.º 15
0
	def deploy( self, **option ):
		base    = self.getPath( option.get( 'path', 'output' ) )
		context = DeployContext( base )
		context.cleanPath()
		hostResPath = self.getHostPath('resource')
		gameLibPath = self.getGamePath('lib')

		logging.info( 'deploy current project' )
		context.copyFilesInDir( hostResPath )
		context.copyFile( gameLibPath, 'lib' )
		signals.emitNow( 'project.pre_deploy', context )
		#deploy asset library
		objectFiles = []
				
		for node in self.assetLibrary.assetTable.values():
			mgr = node.getManager()
			if not mgr: continue
			mgr.deployAsset( node, context )
		#copy scripts
		#copy static resources
		signals.emitNow( 'project.deploy', context )
		self.assetLibrary.saveAssetTable(
				path    = base + '/asset/asset_index', 
				deploy_context  = context
			)
		context.flushTask()
		signals.emitNow( 'project.post_deploy', context )
		print( 'Deploy building done!' )
		signals.emitNow( 'project.done_deploy', context )
Ejemplo n.º 16
0
	def init( self, **options ):
		# if options.get( 'stop_other_instance', False ):
		# 	if not checkSingleInstance():
		# 		retryCount = 5
		# 		logging.warning( 'running instance detected, trying to shut it down' )
		# 		sendRemoteMsg( 'shut_down' )
		# 		ready = False
		# 		for i in range( retryCount ):
		# 			time.sleep( 1 )
		# 			if checkSingleInstance():
		# 				ready = True
		# 				break
		# 		if not ready:
		# 			logging.warning( 'timeout for shuting down other instance' )
		# 			return False

		# else:
		# 	if not checkSingleInstance():
		# 		logging.warning( 'running instance detected' )
		# 		return False
		
		self.loadConfig()
		self.loadSettings()

		if self.initialized: return True
		self.openProject()
		
		# #scan packages
		# excludePackages = self.getProject().getConfig( 'excluded_packages' )
		# self.packageManager.addExcludedPackage( excludePackages )

		# if not self.packageManager.scanPackages( self.getPath( _GII_BUILTIN_PACKAGES_PATH ) ):
		# 	return False

		# if self.getProject().isLoaded():
		# 	self.packageManager.scanPackages( self.getProject().envPackagePath )

		# #modules
		EditorModuleManager.get().loadAllModules()
		signals.emitNow( 'module.loaded' ) #some pre app-ready activities
		signals.dispatchAll()

		# self.getProject().loadAssetLibrary()

		self.initialized = True
		self.running     = True

		# signals.connect( 'app.remote', self.onRemote )

		return True
Ejemplo n.º 17
0
    def save(self):
        signals.emitNow('project.presave', self)

        if self.getBasePath():
            jsonHelper.trySaveJSON(self.info,
                                   self.getBasePath(_PROJECT_INFO_FILE))

        #save asset & cache
        self.assetLibrary.save()
        self.cacheManager.clearFreeCacheFiles()
        self.cacheManager.save()

        signals.emitNow('project.save', self)
        return True
Ejemplo n.º 18
0
    def save(self):
        logging.info('saving current project')
        signals.emitNow('project.presave', self)
        #save project info & config
        jsonHelper.trySaveJSON(self.info, self.getBasePath(_GII_INFO_FILE),
                               'project info')

        #save asset & cache
        self.assetLibrary.save()
        self.cacheManager.clearFreeCacheFiles()
        self.cacheManager.save()

        signals.emitNow('project.save', self)  #post save
        logging.info('project saved')
        return True
Ejemplo n.º 19
0
    def unregisterAssetNode(self, oldnode):
        assert oldnode
        logging.info('unregister: %s' % repr(oldnode))

        for child in oldnode.getChildren()[:]:
            self.unregisterAssetNode(child)

        if oldnode != self.rootNode:
            oldnode.getManager().forgetAsset(oldnode)
            signals.emitNow('asset.unregister', oldnode)
            if oldnode.parentNode:
                oldnode.parentNode.removeChild(oldnode)
                oldnode.parentNode = None
            path = oldnode.getNodePath()
            del self.assetTable[path]
            assert not self.assetTable.has_key(path)
Ejemplo n.º 20
0
Archivo: asset.py Proyecto: tommo/gii
	def unregisterAssetNode(self, oldnode):
		assert oldnode
		logging.info( 'unregister: %s' % repr(oldnode) )
		
		for child in oldnode.getChildren()[:]:
			self.unregisterAssetNode(child)

		if oldnode != self.rootNode:
			oldnode.getManager().forgetAsset( oldnode )
			signals.emitNow('asset.unregister', oldnode)
			if oldnode.parentNode: 
				oldnode.parentNode.removeChild(oldnode)
				oldnode.parentNode = None
			path = oldnode.getNodePath()
			del self.assetTable[path]
			assert not self.assetTable.has_key(path)	
Ejemplo n.º 21
0
    def pausePreview(self):
        if self.paused: return
        self.canvas.setInputDevice(None)
        # jhook = self.getModule ('joystick_hook')
        # if jhook: jhook.setInputDevice (None)

        self.getApp().resetMainLoopBudget()

        signals.emitNow('preview.pause')
        logging.info('pause game preview')
        self.enableMenu('main/preview/start_game', True)
        self.enableMenu('main/preview/pause_game', False)

        self.window.setWindowTitle('Game Preview[ Paused ]')
        self.qtool.setStyleSheet(
            'QToolBar{ border-top: 1px solid rgb (255, 0, 0); }')

        self.paused = True
        self.getRuntime().pause()
        self.canvas.startRefreshTimer(self.nonActiveFPS)
Ejemplo n.º 22
0
    def stopPreview(self):
        if self.paused is None: return
        logging.info('stop game preview')

        jhook = self.getModule('joystick_hook')
        if jhook: jhook.setInputDevice(None)

        self.getApp().resetMainLoopBudget()

        signals.emitNow('preview.stop')
        self.updateTimer.stop()
        self.enableMenu('main/preview/stop_game', False)
        self.enableMenu('main/preview/pause_game', False)
        self.enableMenu('main/preview/start_game', True)

        self.window.setWindowTitle('Game Preview')
        self.qtool.setStyleSheet('QToolBar{ border-top: none; }')

        self.paused = None
        self.updateTimer = None
        self.canvas.startRefreshTimer(self.nonActiveFPS)
        logging.info('game preview stopped')
Ejemplo n.º 23
0
    def load(self, path):
        path = os.path.realpath(path)

        self._initPath(path)
        self._affirmDirectories()
        os.chdir(path)

        sys.path.insert(0, self.envLibPath)
        sys.path.insert(
            0, self.getBinaryPath('python'))  #for python extension modules

        self.info = jsonHelper.tryLoadJSON(self.getBasePath(_GII_INFO_FILE))
        self.config = jsonHelper.tryLoadJSON(
            self.getConfigPath(_GII_CONFIG_FILE))
        if not self.config:
            self.config = {}
            jsonHelper.trySaveJSON(self.config,
                                   self.getConfigPath(_GII_CONFIG_FILE))

        if not self.info:
            self.info = {
                'name': 'name',
                'version': [0, 0, 1],
            }
            jsonHelper.trySaveJSON(self.info, self.getBasePath(_GII_INFO_FILE))

        self.cacheManager.load(_GII_ENV_CONFIG_DIR, self.envConfigPath)
        self.assetLibrary.load(_GII_ASSET_DIR, self.assetPath, self.path,
                               self.envConfigPath)

        #will trigger other module
        signals.emitNow('project.preload', self)
        signals.emitNow('project.load', self)

        logging.info('project loaded: %s' % path)

        return True
Ejemplo n.º 24
0
    def startPreview(self):
        if self.paused == False: return
        runtime = self.getRuntime()
        runtime.changeRenderContext('game', self.viewWidth, self.viewHeight)
        self.canvas.setInputDevice(runtime.getInputDevice('device'))
        self.canvas.startRefreshTimer(self.activeFPS)
        self.canvas.interceptShortcut = True
        self.getApp().setMinimalMainLoopBudget()
        # jhook = self.getModule ( 'joystick_hook' )
        # if jhook:
        # 	jhook.refreshJoysticks ()
        # 	jhook.setInputDevice ( runtime.getInputDevice ('device') )

        self.enableMenu('main/preview/pause_game', True)
        self.enableMenu('main/preview/stop_game', True)
        self.enableMenu('main/preview/start_game', False)

        if self.paused:  #resume
            logging.info('resume game preview')
            signals.emitNow('preview.resume')

        elif self.paused is None:  #start
            logging.info('start game preview')
            signals.emitNow('preview.start')
            signals.emitNow('preview.resume')
            self.updateTimer = self.window.startTimer(60, self.updateView)

            getAKU().setFuncOpenWindow(self.onOpenWindow)

        self.window.setWindowTitle('Game Preview [ RUNNING ]')
        self.qtool.setStyleSheet(
            'QToolBar{ border-top: 1px solid rgb (0, 120, 0); }')
        self.paused = False
        runtime.resume()
        self.setFocus()
        logging.info('game preview started')

        entryScript = self.getProject().getScriptLibPath('main.lua')
        import os
        if os.path.exists(entryScript):
            getAKU().runScript(entryScript)
Ejemplo n.º 25
0
Archivo: asset.py Proyecto: tommo/gii
	def importModifiedAssets( self ):
		def _ignoreBundleChildrenNode( node ):
			for child in node.getChildren()[:]:
				if not child.isVirtual():
					_ignoreBundleChildrenNode( child )
					child.modifyState = 'ignored'
					self.unregisterAssetNode( child )

		def _markVirtualChildrenRemoving( node, removingAssets ):			
			for child in node.getChildren()[:]:
				if child.isVirtual():
					_markVirtualChildrenRemoving( child, removingAssets )
					child.modifyState = 'removing'
					removingAssets[ child ] = True

		#collect modified state
		removingAssets = {}
		modifiedAssetList = []
		for node in self.assetTable.values():
			if node.modifyState and not node.isVirtual():
				modifiedAssetList.append( node )
				logging.info( u'asset modified: {0}'.format( node.getNodePath() ) )
		modifiedAssetList = sorted( modifiedAssetList, key = lambda node: node.getPathDepth() )
		#try importing with each asset manager, in priority order
		for manager in self.assetManagers:
			if not modifiedAssetList: break
			done = []
			rest = []
			for node in modifiedAssetList:
				if node.modifyState in ( 'removed', 'ignored' ) :
					done.append( node )
					continue
				if not node.modifyState: #might get imported as a sub asset 
					done.append( node )
					continue
				if not manager.acceptAsset( node ):
					rest.append( node )
					continue
				
				isNew = node.modifyState == 'new'
				if not isNew:
					_markVirtualChildrenRemoving( node, removingAssets )

				if node.getManager() != manager: node.setManager( manager )
				if manager.importAsset( node, reload = not isNew ) != False:
					logging.info( u'assets imported: {0}'.format( node.getNodePath() ) )
					node.modifyState  =  False
					done.append( node )
				else:
					rest.append( node )

				if not isNew:
					signals.emitNow( 'asset.modified',  node )
					# if node.isBundle():
					for child in node.children:
						signals.emitNow( 'asset.modified', child )

				if node.isBundle():
					_ignoreBundleChildrenNode( node )
					
			for node in done:				
				if node.modifyState == 'ignored': continue
				if node.isBundle():
					node._updateFileTime( self._getBundleMTime( node.getAbsFilePath() ) )					
				else:
					node._updateFileTime()
			modifiedAssetList = rest
			rest = []

		for node in modifiedAssetList: #nodes without manager
			if node.isBundle():
				node._updateFileTime( self._getBundleMTime( node.getAbsFilePath() ) )					
			else:
				node._updateFileTime()

		for node in removingAssets.keys():
			if node.modifyState == 'removing':
				self.unregisterAssetNode( node )
				node.modifyState = 'removed'

		#end of for
		signals.emitNow( 'asset.post_import_all' )
		logging.info( 'modified assets imported' )
Ejemplo n.º 26
0
class Project(object):
    _singleton = None

    @staticmethod
    def get():
        return Project._singleton

    @staticmethod
    def findProject(path=None):
        #TODO: return project info dict instead of path?
        path = os.path.abspath(path or '')
        opath = None
        while path and not (path in ('', '/', '\\')):
            if   os.path.exists( path + '/' + _GII_ENV_CONFIG_DIR ) \
            and  os.path.exists( path + '/' + _GII_INFO_FILE ) :
                #get info
                info = jsonHelper.tryLoadJSON(path + '/' + _GII_INFO_FILE)
                info['path'] = path
                return info
            #go up level
            opath = path
            path = os.path.dirname(path)
            if path == opath: break
        return None

    def __init__(self):
        assert not Project._singleton
        Project._singleton = self

        self.path = None
        self.cacheManager = CacheManager()
        self.assetLibrary = AssetLibrary()

        self.info = {'name': 'Name', 'author': 'author', 'version': '1.0.0'}

        self.config = {}

    def isLoaded(self):
        return self.path != None

    def _initPath(self, path):
        self.path = path

        self.binaryPath = path + '/' + _GII_BINARY_DIR
        self.gamePath = path + '/' + _GII_GAME_DIR

        self.envPath = path + '/' + _GII_ENV_DIR
        self.envPackagePath = path + '/' + _GII_ENV_PACKAGE_DIR
        self.envDataPath = path + '/' + _GII_ENV_DATA_DIR
        self.envConfigPath = path + '/' + _GII_ENV_CONFIG_DIR
        self.envLibPath = path + '/' + _GII_ENV_LIB_DIR

        self.assetPath = path + '/' + _GII_ASSET_DIR

        self.scriptLibPath = path + '/' + _GII_SCRIPT_LIB_DIR

        self.hostPath = path + '/' + _GII_HOST_DIR
        self.hostExtensionPath = path + '/' + _GII_HOST_EXTENSION_DIR

    def _affirmDirectories(self):
        #mkdir - lv1
        _affirmPath(self.binaryPath)

        _affirmPath(self.envPath)
        _affirmPath(self.envPackagePath)
        _affirmPath(self.envDataPath)
        _affirmPath(self.envLibPath)
        _affirmPath(self.envConfigPath)

        _affirmPath(self.gamePath)
        _affirmPath(self.assetPath)
        _affirmPath(self.scriptLibPath)

        _affirmPath(self.hostPath)
        _affirmPath(self.hostExtensionPath)

    def init(self, path, name):
        info = Project.findProject(path)
        if info:
            raise ProjectException('Gii project already initialized:' +
                                   info['path'])
        #
        path = os.path.realpath(path)
        if not os.path.isdir(path):
            raise ProjectException('%s is not a valid path' % path)
        self._initPath(path)
        #
        logging.info('copy template contents')
        from MainModulePath import getMainModulePath

        def ignore(src, names):
            return ['.DS_Store']

        shutil.copytree(getMainModulePath('template/host'),
                        self.getPath('host'), ignore)
        shutil.copytree(getMainModulePath('template/game'),
                        self.getPath('game'), ignore)
        shutil.copy(getMainModulePath('template/.gitignore'), self.getPath())
        #
        self._affirmDirectories()

        try:
            self.cacheManager.init(_GII_ENV_CONFIG_DIR, self.envConfigPath)
        except OSError, e:
            raise ProjectException('error creating cache folder:%s' % e)

        self.assetLibrary.load(_GII_ASSET_DIR, self.assetPath, self.path,
                               self.envConfigPath)

        signals.emitNow('project.init', self)
        logging.info('project initialized: %s' % path)
        self.info['name'] = name
        self.saveConfig()
        self.save()
        return True
Ejemplo n.º 27
0
    def importModifiedAssets(self):
        def _ignoreBundleChildrenNode(node):
            for child in node.getChildren()[:]:
                if not child.isVirtual():
                    _ignoreBundleChildrenNode(child)
                    child.modifyState = 'ignored'
                    self.unregisterAssetNode(child)

        def _markVirtualChildrenRemoving(node, removingAssets):
            for child in node.getChildren()[:]:
                if child.isVirtual():
                    _markVirtualChildrenRemoving(child, removingAssets)
                    child.modifyState = 'removing'
                    removingAssets[child] = True

        #collect modified state
        removingAssets = {}
        modifiedAssetList = []
        for node in self.assetTable.values():
            if node.modifyState and not node.isVirtual():
                modifiedAssetList.append(node)
                logging.info(u'asset modified: {0}'.format(node.getNodePath()))
        modifiedAssetList = sorted(modifiedAssetList,
                                   key=lambda node: node.getPathDepth())
        #try importing with each asset manager, in priority order
        for manager in self.assetManagers:
            if not modifiedAssetList: break
            done = []
            rest = []
            for node in modifiedAssetList:
                if node.modifyState in ('removed', 'ignored'):
                    done.append(node)
                    continue
                if not node.modifyState:  #might get imported as a sub asset
                    done.append(node)
                    continue
                if not manager.acceptAsset(node):
                    rest.append(node)
                    continue

                isNew = node.modifyState == 'new'
                if not isNew:
                    _markVirtualChildrenRemoving(node, removingAssets)

                if node.getManager() != manager: node.setManager(manager)
                if manager.importAsset(node, reload=not isNew) != False:
                    logging.info(u'assets imported: {0}'.format(
                        node.getNodePath()))
                    node.modifyState = False
                    done.append(node)
                else:
                    rest.append(node)

                if not isNew:
                    signals.emitNow('asset.modified', node)
                    # if node.isBundle():
                    for child in node.children:
                        signals.emitNow('asset.modified', child)

                if node.isBundle():
                    _ignoreBundleChildrenNode(node)

            for node in done:
                if node.modifyState == 'ignored': continue
                if node.isBundle():
                    node._updateFileTime(
                        self._getBundleMTime(node.getAbsFilePath()))
                else:
                    node._updateFileTime()
            modifiedAssetList = rest
            rest = []

        for node in modifiedAssetList:  #nodes without manager
            if node.isBundle():
                node._updateFileTime(
                    self._getBundleMTime(node.getAbsFilePath()))
            else:
                node._updateFileTime()

        for node in removingAssets.keys():
            if node.modifyState == 'removing':
                self.unregisterAssetNode(node)
                node.modifyState = 'removed'

        #end of for
        signals.emitNow('asset.post_import_all')
        logging.info('modified assets imported')
Ejemplo n.º 28
0
 def init(self, path):
     signals.emitNow('project.init', self)
Ejemplo n.º 29
0
	def init(self, path):
		signals.emitNow('project.init', self)
Ejemplo n.º 30
0
class EditorApp(object):
    _singleton = None

    @staticmethod
    def get():
        return _singleton

    def __init__(self):
        assert (not EditorApp._singleton)
        EditorApp._singleton = self
        EditorModuleManager.get()._app = self

        self.defaultMainloopBudget = 0.005

        self.initialized = False
        self.projectLoaded = False
        self.flagModified = False
        self.debugging = False
        self.running = False
        self.basePath = getMainModulePath()
        self.dataPaths = []
        self.config = {}
        self.packageManager = PackageManager()

        self.commandRegistry = EditorCommandRegistry.get()
        self.remoteCommandRegistry = RemoteCommandRegistry.get()

        self.registerDataPath(self.getPath('data'))

        signals.connect('module.register', self.onModuleRegister)

    def onModuleRegister(self, m):
        if self.running:
            logging.info('registered in runtime:' + m.getName())
            EditorModuleManager.get().loadModule(m)

    def init(self, **options):
        if options.get('stop_other_instance', False):
            if not checkSingleInstance():
                retryCount = 5
                logging.warning(
                    'running instance detected, trying to shut it down')
                sendRemoteMsg('shut_down')
                ready = False
                for i in range(retryCount):
                    time.sleep(1)
                    if checkSingleInstance():
                        ready = True
                        break
                if not ready:
                    logging.warning('timeout for shuting down other instance')
                    return False

        else:
            if not checkSingleInstance():
                logging.warning('running instance detected')
                return False

        self.loadConfig()

        if self.initialized: return True
        self.openProject()

        #scan packages
        excludePackages = self.getProject().getConfig('excluded_packages')
        self.packageManager.addExcludedPackage(excludePackages)

        if not self.packageManager.scanPackages(
                self.getPath(_GII_BUILTIN_PACKAGES_PATH)):
            return False

        if self.getProject().isLoaded():
            self.packageManager.scanPackages(self.getProject().envPackagePath)

        #modules
        EditorModuleManager.get().loadAllModules()
        signals.emitNow('module.loaded')  #some pre app-ready activities
        signals.dispatchAll()

        self.getProject().loadAssetLibrary()

        self.initialized = True
        self.running = True

        signals.connect('app.remote', self.onRemote)

        return True

    def run(self, **kwargs):
        if not self.initialized:
            if not self.init(**kwargs):
                return False
        hasError = False
        self.resetMainLoopBudget()

        try:
            signals.emitNow('app.pre_start')

            EditorModuleManager.get().startAllModules()
            self.getProject().getAssetLibrary().scanProject()

            signals.emitNow('app.start')
            signals.dispatchAll()

            self.saveConfig()

            EditorModuleManager.get().tellAllModulesAppReady()
            signals.emit('app.ready')

            #main loop
            while self.running:
                self.doMainLoop()

        except Exception, e:
            #TODO: popup a alert window?
            logging.exception(e)
            hasError = True

        signals.emitNow('app.close')

        signals.dispatchAll()
        EditorModuleManager.get().stopAllModules()

        if not hasError:
            self.getProject().save()

        signals.dispatchAll()
        EditorModuleManager.get().unloadAllModules()
        return True