示例#1
0
 def create_valid_storage_name(self, name):
     storage_name = make_valid_attr_name(name)
     if storage_name in self.storageNames:
         suffix = 2
         base_name = storage_name
         while storage_name in self.storageNames:
             storage_name = ''.join([base_name, '_', str(suffix)])
             suffix += 1
     self.storageNames.append(storage_name)
     return storage_name
示例#2
0
 def create_valid_storage_name(self, name):
     storage_name = make_valid_attr_name(name)
     if storage_name in self.storageNames:
         suffix = 2
         base_name = storage_name
         while storage_name in self.storageNames:
             storage_name = ''.join([base_name, '_', str(suffix)])
             suffix+=1
     self.storageNames.append(storage_name)
     return storage_name
示例#3
0
文件: Sprite.py 项目: bcorfman/pug
    def set_archetype(self, TF):
        """set_archetype( TF): set archetype property.
        
if TF is True create default gname. 
if TF is "True" set archetype to True, but don't create default name
"""
        if TF == "True":
            self._archetype = True
        elif TF is True:
            if not self.gname:
                name = self.__class__.__name__
                superclasses = getmro(self.__class__)[1:]
                for cls in superclasses:
                    if name == cls.__name__ or name == 'Sprite':
                        name = ''.join(['My', name])
                        break
                name = make_valid_attr_name(name)
                self.gname = name
            self._archetype = True
        elif TF == False:
            self._archetype = False
示例#4
0
文件: Sprite.py 项目: bcorfman/pug
    def set_archetype(self, TF):
        """set_archetype( TF): set archetype property.
        
if TF is True create default gname. 
if TF is "True" set archetype to True, but don't create default name
""" 
        if TF == "True":
            self._archetype = True
        elif TF is True:
            if not self.gname:
                name = self.__class__.__name__
                superclasses = getmro(self.__class__)[1:]
                for cls in superclasses:
                    if name == cls.__name__ or name == 'Sprite':
                        name = ''.join(['My',name])    
                        break            
                name = make_valid_attr_name(name)
                self.gname = name
            self._archetype = True
        elif TF == False:
            self._archetype = False
示例#5
0
文件: storage.py 项目: bcorfman/pug
def save_object(obj, name=None, parentWindow=None):
    """save_object(obj): Export obj as a class to objects folder

name: the name to save the object as. If not provided, a dialog will be opened
parentWindow: the parent window of name dialog. If not provided, the 
    wx.ActiveWindow will be used
"""
    if not isinstance(obj, Node):
        raise TypeError('save_object() arg 1 must be a Node')
    if not name:
        if obj.archetype:
            name = obj.gname
        else:
            if obj.gname:
                name = obj.gname
            else:
                name = "MyClass"
        if not name:
            name = obj.__class__.__name__
        if parentWindow == None:
            parentWindow = wx.GetActiveWindow()
        objName = ''
        # we generally don't want to save with the same name as 
        # a base class of the same object
        superclasses = getmro(obj.__class__)[1:]
        for cls in superclasses:
            if name == cls.__name__ or name=='Sprite':
                name = ''.join(['My',name])
                break
        default = make_valid_attr_name(name)
        dlg = wx.TextEntryDialog( parentWindow, 
                                  "Enter the object's class/file name", 
                                  "Save Object", default)
        while not objName:
            if dlg.ShowModal() == wx.ID_OK:
                name = dlg.GetValue()
                errorDlg = None
                if name == 'Sprite':
                    errorDlg = wx.MessageDialog( dlg, 
                           "You can't use the names 'Sprite'",
                           "Reserved Name",
                           wx.OK)
                elif name != make_valid_attr_name(name):
                    errorDlg = wx.MessageDialog( dlg, 
                           "Name cannot contain spaces or special characters"+\
                           "\nand cannot start with a number",
                           "Invalid Name",
                           wx.OK)
                if errorDlg:   
                    errorDlg.ShowModal()
                    errorDlg.Destroy() 
                    dlg.SetValue(default)
                    dlg.SetFocus()      
                    continue                
                path = os.path.join('objects',''.join([name,'.py']))
                old_module = obj.__class__.__module__.split('.')
                if old_module[-2:-1][0] == 'objects' and \
                        old_module[-1:][0] != name:
                    # verify overwrite
                    try:
                        test = file(path)
                    except:
                        objName = name
                    else:
                        test.close()
                        confirmDlg = wx.MessageDialog( dlg, 
                                "\n".join([path,
                               "File already exists. Overwrite?"]),
                               "Confirm Replace",
                               wx.YES_NO | wx.NO_DEFAULT)
                        if confirmDlg.ShowModal() == wx.ID_YES:
                            if sys.platform == "win32":
                                files = os.listdir('objects')
                                testname = name + '.py'
                                for f in files:
                                    if f.lower() == testname.lower():
                                        sceneName = os.path.splitext(f)[0]
                                        break
                            else:
                                objName = name
                        confirmDlg.Destroy()
                else:
                    objName = name
            else:
                dlg.Destroy()
                return
        dlg.Destroy()
    else:
        name = make_valid_attr_name(name)
        objName = name
        path = os.path.join('objects',''.join([name,'.py']))
    try:
        if getattr(obj, 'archetype', False):
            # we don't want every instance to be an archetype
            obj.archetype = False
            archetype = True
        else:
            archetype = False    
        from pig.Sprite import Sprite
        exporter = code_exporter( obj, path, True, {'name':objName,
                                                  'base_class':Sprite})
        objDict = get_available_objects( True)
        oldclass = obj.__class__
        if oldclass != objDict[objName]:
            obj.__class__ = objDict[objName]            
        if archetype:
            # return archetype status after saving
            obj.archetype = True
            obj.gname = objName
            if exporter.file_changed:
                archetype_changed( obj, oldclass, exporter)
        return exporter
    except:
        show_exception_dialog()
示例#6
0
文件: storage.py 项目: bcorfman/pug
def save_scene_as( sceneName=None, fileName=None):#, parentWindow=None):
    """save_scene_as( sceneName=None, fileName=None)->Filename or False if fail 
    Save the current scene as a class in the scenes folder
        
sceneName: string with name to save as. If None, a dialog will be opened.
parentWindow: the parent window of name dialog. If not provided, the 
    wx.ActiveWindow will be used
"""
    wx.GetApp().apply()
    if get_scene_errors():
        return False
    if _DEBUG: print "util: save_scene_as"
    scene = PigDirector.scene
    if not sceneName:
        name = scene.__class__.__name__
        if name == 'Scene':
            name = 'MyScene'
        name = make_valid_attr_name(name)
        name.capitalize()
        if _DEBUG: print "util: save_scene_as 1"
        parentWindow=None
        if parentWindow == None:
            parentWindow = wx.GetActiveWindow()
        default = make_valid_attr_name(name)
        dlg = wx.TextEntryDialog( parentWindow, 
                                  "Enter the scene's class/file name", 
                                  "Save Scene", default)
        if _DEBUG: print "util: save_scene_as 2"
        while not sceneName:
            if dlg.ShowModal() == wx.ID_OK:
                name = dlg.GetValue()
                errorDlg = None
                if name == 'Scene':
                    errorDlg = wx.MessageDialog( dlg, 
                           "You can't use the name 'Scene'",
                           "Reserved Name",
                           wx.OK)
                elif name != make_valid_attr_name(name):
                    errorDlg = wx.MessageDialog( dlg, 
                           "Name cannot contain spaces or special characters"+\
                           "\nand cannot start with a number",
                           "Invalid Name",
                           wx.OK)
                if errorDlg:    
                    errorDlg.ShowModal()
                    errorDlg.Destroy() 
                    dlg.SetValue(default)
                    dlg.SetFocus()      
                    continue
                path = os.path.join('scenes', name + '.py')
                if name != scene.__class__.__name__:
                    try:
                        test = file(path)
                    except:
                        sceneName = name
                    else:
                        test.close()
                        confirmDlg = wx.MessageDialog( dlg, 
                               "Scene file already exists. Overwrite?",
                               "Confirm Replace",
                               wx.YES_NO | wx.NO_DEFAULT)
                        if confirmDlg.ShowModal() == wx.ID_YES:
                            if sys.platform == "win32":
                                files = os.listdir('scenes')
                                testname = name + '.py'
                                for f in files:
                                    if f.lower() == testname.lower():
                                        sceneName = os.path.splitext(f)[0]
                                        break
                            else:
                                sceneName = name
                        confirmDlg.Destroy()   
                else:    
                    sceneName = name             
            else:
                dlg.Destroy()
                return False
        dlg.Destroy()
    else:
        if sceneName == 'Scene':
            raise ValueError("Can't save over baseclass 'Scene'")
#            save_scene_as( sceneName, fileName)
    if not fileName:
        fileName = ''.join([sceneName, '.py'])
    path = os.path.join('scenes',fileName)
    app = wx.GetApp()
    if _DEBUG: print "util: save_scene_as 4"
    selection = app.selectedObjectDict.keys()
    oldscene = PigDirector.scene
    from pig.editor.util import wait_for_state
    wait_for_state( None)
    if _DEBUG: print "util: save_scene_as 5"
    wx.GetApp().set_busy_state(True)
    saved = False
    try:
        if _DEBUG: print "util: save_scene_as enter code_exporter"
        code_exporter( scene, path, True, {'name':sceneName})
        if _DEBUG: print "util: save_scene_as exit code_exporter"
    except:
        if _DEBUG: print "util: save_scene_as 6"        
        show_exception_dialog()
    else:
        if _DEBUG: print "util: save_scene_as 7"        
        sceneDict = get_available_scenes(True)
        if '__Working__' not in path:
            PigDirector.scene.__class__ = sceneDict[sceneName]
        saved = True
        if _DEBUG: print "util: save_scene_as 8"        
    finally:
        if _DEBUG: print "util: save_scene_as 9"                
        wx.GetApp().set_busy_state(False)        
        if PigDirector.scene != oldscene:
            wx.GetApp().set_selection([])
            if _DEBUG: print "util: save_scene_as reset select:", selection
        from pig.editor.EditorState import EditorState
        wait_for_state(EditorState)
        if _DEBUG: print "util: save_scene_as 10"                
        wx.GetApp().refresh()
    if _DEBUG: print "util: save_scene_as 11"                
    if saved:
        return fileName
    else:
        return False
示例#7
0
文件: Scene.py 项目: bcorfman/pug
    def _create_object_code(self, storageDict, indentLevel, exporter):
        if _DEBUG: print "*******************enter scene save"
        storage_name = storageDict['storage_name']
        if storage_name == 'Scene' or storage_name == 'Scene':
            raise ValueError(''.join(["Can't over-write ",
                                      storage_name," base class."]))
        if not storageDict['as_class']:            
            raise ValueError("Scenes can only be stored as classes.")
        # start with basic export
        base_code = exporter.create_object_code(self, storageDict, indentLevel, 
                                                True)
        baseIndent = _INDENT * indentLevel       
        custom_code_list = []
        # custom code
#        # groups
#        if self._groups:
#            custom_code_list += [baseIndent, _INDENT, 'groups = ', 
#                                 str(self._groups.keys()),
#                                 '\n']
        # enter function
        if self.nodes:
            # create ordered list of nodes
            nodes = self.get_ordered_nodes()
            nodes.reverse() # store them from bottom-most to top-most
            
            # store archetypes at top of file
            archetypes = False
            for node in nodes:
                if not node.archetype:
                    continue
                if not archetypes:
                    custom_code_list += [baseIndent, _INDENT*2, 
                                         '# Archetypes\n']
                    archetypes = True
                # this node is a class archetype, figure out a save name
                if node.gname:
                    savename = make_valid_attr_name(node.gname)
                    node.gname = savename
                else:
                    # no gname, so find an available filename
                    tryname = base_tryname = 'MyObjectClass'
                    savename = ''
                    suffix = 1
                    while not savename:
                        path = os.path.join('objects',
                                            ''.join([tryname,'.py']))
                        try:
                            file(path)
                        except:
                            savename = tryname
                        else:
                            suffix+=1
                            tryname = ''.join([base_tryname, 
                                               str(suffix)])
                    node.gname = savename
                archetype_exporter = save_object( node, savename)
                if not archetype_exporter or \
                                        archetype_exporter.errorfilename:
                    error = ''.join(["Scene code export failed...",
                            "unable to save archetype:",
                            savename, node])
                    warnings.warn(error)
                    return
                time.sleep(0.1)
                module = __import__('.'.join(['objects',savename]),
                                   fromlist=[savename])
                reload(module)
                newclass = getattr(module,savename)
                node.__class__ = newclass
                nodeStorageDict = exporter.get_custom_storageDict(node)                            
                nodeStorageDict['name'] =''.join([savename,'_archetype'])
                nodeStorageDict['as_class'] = False # export as object
                node_code = exporter.create_object_code(node, 
                                                        nodeStorageDict, 
                                                        indentLevel + 2,
                                                        False)                    
                custom_code_list+=[node_code,'\n']
           
            # store instances
            instances = False
            for node in nodes:
                if node.archetype:
                    continue
                if not instances:
                    custom_code_list += [baseIndent, _INDENT*2, 
                                         '# Sprites\n']
                    instances = True
                else:
                    custom_code_list +=['\n',]
                nodeStorageDict = exporter.get_custom_storageDict(node)
                nodeStorageDict['as_class'] = False # export as object
                node_code = exporter.create_object_code(node, 
                                                        nodeStorageDict, 
                                                        indentLevel + 2,
                                                        False)                    
                custom_code_list += [node_code]
        #spacing before custom code
        if custom_code_list:
            custom_code_list = ['\n']+custom_code_list
        #add layers line
        layers = get_scene_layers()
        if layers != ["Background"]:
            layercode = ''.join([baseIndent, _INDENT,'layers = ', str(layers),
                                '\n'])
            base_code_lines = base_code.splitlines()
            base_code = '\n'.join([base_code_lines[0]] + [layercode] +\
                                  base_code_lines[1:])+'\n'
        # remove pass in base code if we have custom code
        if base_code.endswith('pass\n') and custom_code_list: 
            # clean up pass case (for looks)
            base_code = '\n'.join(base_code.splitlines()[0:-1])
        code = ''.join([base_code] + custom_code_list)
        if _DEBUG: print "*******************exit scene save"
        return code
示例#8
0
文件: app.py 项目: bcorfman/pug
 def get_rect_setting_name(self, frame):
     return make_valid_attr_name(''.join([_RECTPREFIX,frame.Name]))
示例#9
0
 def get_rect_setting_name(self, frame):
     return make_valid_attr_name(''.join([_RECTPREFIX, frame.Name]))
示例#10
0
def save_object(obj, name=None, parentWindow=None):
    """save_object(obj): Export obj as a class to objects folder

name: the name to save the object as. If not provided, a dialog will be opened
parentWindow: the parent window of name dialog. If not provided, the 
    wx.ActiveWindow will be used
"""
    if not isinstance(obj, Node):
        raise TypeError('save_object() arg 1 must be a Node')
    if not name:
        if obj.archetype:
            name = obj.gname
        else:
            if obj.gname:
                name = obj.gname
            else:
                name = "MyClass"
        if not name:
            name = obj.__class__.__name__
        if parentWindow == None:
            parentWindow = wx.GetActiveWindow()
        objName = ''
        # we generally don't want to save with the same name as
        # a base class of the same object
        superclasses = getmro(obj.__class__)[1:]
        for cls in superclasses:
            if name == cls.__name__ or name == 'Sprite':
                name = ''.join(['My', name])
                break
        default = make_valid_attr_name(name)
        dlg = wx.TextEntryDialog(parentWindow,
                                 "Enter the object's class/file name",
                                 "Save Object", default)
        while not objName:
            if dlg.ShowModal() == wx.ID_OK:
                name = dlg.GetValue()
                errorDlg = None
                if name == 'Sprite':
                    errorDlg = wx.MessageDialog(
                        dlg, "You can't use the names 'Sprite'",
                        "Reserved Name", wx.OK)
                elif name != make_valid_attr_name(name):
                    errorDlg = wx.MessageDialog( dlg,
                           "Name cannot contain spaces or special characters"+\
                           "\nand cannot start with a number",
                           "Invalid Name",
                           wx.OK)
                if errorDlg:
                    errorDlg.ShowModal()
                    errorDlg.Destroy()
                    dlg.SetValue(default)
                    dlg.SetFocus()
                    continue
                path = os.path.join('objects', ''.join([name, '.py']))
                old_module = obj.__class__.__module__.split('.')
                if old_module[-2:-1][0] == 'objects' and \
                        old_module[-1:][0] != name:
                    # verify overwrite
                    try:
                        test = file(path)
                    except:
                        objName = name
                    else:
                        test.close()
                        confirmDlg = wx.MessageDialog(
                            dlg, "\n".join(
                                [path, "File already exists. Overwrite?"]),
                            "Confirm Replace", wx.YES_NO | wx.NO_DEFAULT)
                        if confirmDlg.ShowModal() == wx.ID_YES:
                            if sys.platform == "win32":
                                files = os.listdir('objects')
                                testname = name + '.py'
                                for f in files:
                                    if f.lower() == testname.lower():
                                        sceneName = os.path.splitext(f)[0]
                                        break
                            else:
                                objName = name
                        confirmDlg.Destroy()
                else:
                    objName = name
            else:
                dlg.Destroy()
                return
        dlg.Destroy()
    else:
        name = make_valid_attr_name(name)
        objName = name
        path = os.path.join('objects', ''.join([name, '.py']))
    try:
        if getattr(obj, 'archetype', False):
            # we don't want every instance to be an archetype
            obj.archetype = False
            archetype = True
        else:
            archetype = False
        from pig.Sprite import Sprite
        exporter = code_exporter(obj, path, True, {
            'name': objName,
            'base_class': Sprite
        })
        objDict = get_available_objects(True)
        oldclass = obj.__class__
        if oldclass != objDict[objName]:
            obj.__class__ = objDict[objName]
        if archetype:
            # return archetype status after saving
            obj.archetype = True
            obj.gname = objName
            if exporter.file_changed:
                archetype_changed(obj, oldclass, exporter)
        return exporter
    except:
        show_exception_dialog()
示例#11
0
def save_scene_as(sceneName=None, fileName=None):  #, parentWindow=None):
    """save_scene_as( sceneName=None, fileName=None)->Filename or False if fail 
    Save the current scene as a class in the scenes folder
        
sceneName: string with name to save as. If None, a dialog will be opened.
parentWindow: the parent window of name dialog. If not provided, the 
    wx.ActiveWindow will be used
"""
    wx.GetApp().apply()
    if get_scene_errors():
        return False
    if _DEBUG: print "util: save_scene_as"
    scene = PigDirector.scene
    if not sceneName:
        name = scene.__class__.__name__
        if name == 'Scene':
            name = 'MyScene'
        name = make_valid_attr_name(name)
        name.capitalize()
        if _DEBUG: print "util: save_scene_as 1"
        parentWindow = None
        if parentWindow == None:
            parentWindow = wx.GetActiveWindow()
        default = make_valid_attr_name(name)
        dlg = wx.TextEntryDialog(parentWindow,
                                 "Enter the scene's class/file name",
                                 "Save Scene", default)
        if _DEBUG: print "util: save_scene_as 2"
        while not sceneName:
            if dlg.ShowModal() == wx.ID_OK:
                name = dlg.GetValue()
                errorDlg = None
                if name == 'Scene':
                    errorDlg = wx.MessageDialog(
                        dlg, "You can't use the name 'Scene'", "Reserved Name",
                        wx.OK)
                elif name != make_valid_attr_name(name):
                    errorDlg = wx.MessageDialog( dlg,
                           "Name cannot contain spaces or special characters"+\
                           "\nand cannot start with a number",
                           "Invalid Name",
                           wx.OK)
                if errorDlg:
                    errorDlg.ShowModal()
                    errorDlg.Destroy()
                    dlg.SetValue(default)
                    dlg.SetFocus()
                    continue
                path = os.path.join('scenes', name + '.py')
                if name != scene.__class__.__name__:
                    try:
                        test = file(path)
                    except:
                        sceneName = name
                    else:
                        test.close()
                        confirmDlg = wx.MessageDialog(
                            dlg, "Scene file already exists. Overwrite?",
                            "Confirm Replace", wx.YES_NO | wx.NO_DEFAULT)
                        if confirmDlg.ShowModal() == wx.ID_YES:
                            if sys.platform == "win32":
                                files = os.listdir('scenes')
                                testname = name + '.py'
                                for f in files:
                                    if f.lower() == testname.lower():
                                        sceneName = os.path.splitext(f)[0]
                                        break
                            else:
                                sceneName = name
                        confirmDlg.Destroy()
                else:
                    sceneName = name
            else:
                dlg.Destroy()
                return False
        dlg.Destroy()
    else:
        if sceneName == 'Scene':
            raise ValueError("Can't save over baseclass 'Scene'")


#            save_scene_as( sceneName, fileName)
    if not fileName:
        fileName = ''.join([sceneName, '.py'])
    path = os.path.join('scenes', fileName)
    app = wx.GetApp()
    if _DEBUG: print "util: save_scene_as 4"
    selection = app.selectedObjectDict.keys()
    oldscene = PigDirector.scene
    from pig.editor.util import wait_for_state
    wait_for_state(None)
    if _DEBUG: print "util: save_scene_as 5"
    wx.GetApp().set_busy_state(True)
    saved = False
    try:
        if _DEBUG: print "util: save_scene_as enter code_exporter"
        code_exporter(scene, path, True, {'name': sceneName})
        if _DEBUG: print "util: save_scene_as exit code_exporter"
    except:
        if _DEBUG: print "util: save_scene_as 6"
        show_exception_dialog()
    else:
        if _DEBUG: print "util: save_scene_as 7"
        sceneDict = get_available_scenes(True)
        if '__Working__' not in path:
            PigDirector.scene.__class__ = sceneDict[sceneName]
        saved = True
        if _DEBUG: print "util: save_scene_as 8"
    finally:
        if _DEBUG: print "util: save_scene_as 9"
        wx.GetApp().set_busy_state(False)
        if PigDirector.scene != oldscene:
            wx.GetApp().set_selection([])
            if _DEBUG: print "util: save_scene_as reset select:", selection
        from pig.editor.EditorState import EditorState
        wait_for_state(EditorState)
        if _DEBUG: print "util: save_scene_as 10"
        wx.GetApp().refresh()
    if _DEBUG: print "util: save_scene_as 11"
    if saved:
        return fileName
    else:
        return False