Exemplo n.º 1
0
 def reload_scene(self):
     """Reload scene from version on disk"""
     if _DEBUG: print 'reload_scene 1'
     scene = self
     self.stop_scene()
     while wx.GetApp().busyState == True:
         time.sleep(0.05)
     dlg = wx.MessageDialog( self.frame,
                    "Current state of scene will be lost.\nContinue?",
                    'Confirm Reload', 
                    wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
     go_ahead = dlg.ShowModal()
     if go_ahead == wx.ID_NO:
         return False    
     if Director.scene.__class__ == Scene:
         self.set_scene("Scene")
         return True
     if _DEBUG: print 'reload_scene 2'
     scenename = self.scene.__class__.__name__
     try:
         if _DEBUG: print 'reload_scene 3'
         test_scene_code(scenename)
     except:
         if _DEBUG: print 'reload_scene 3.2'            
         show_exception_dialog(prefix='Unable to reload scene: ')
     else:
         if _DEBUG: print 'reload_scene 3.5'    
         self.set_scene(scenename, True)
         if _DEBUG: print 'reload_scene 3.6'   
         return True         
Exemplo n.º 2
0
 def open_project(self, project_path=None):
     """Open a pig project"""
     try:
         open_project( project_path)
     except:
         show_exception_dialog()
         return
Exemplo n.º 3
0
 def open_project(self, project_path=None):
     """Open a pig project"""
     try:
         open_project(project_path)
     except:
         show_exception_dialog()
         return
Exemplo n.º 4
0
    def button_press(self, event=None, button=None):  
        """Call the appropriate function"""
        try:
            if event:
                button = event.GetEventObject()
            elif button is None:
                return
            else:
                button = self.buttonDict[button]
            retvalue = self.functionDict[button]()
            if button.type == 'play' and retvalue == True:
                button.Enable(False)
                if self.buttonDict['pause']:
                    self.buttonDict['pause'].Enable(True)
            if button.type == 'stop':
                if self.buttonDict['play']:
                    self.buttonDict['play'].Enable(True)
#                    self.buttonDict['play'].SetValue(False)
                if self.buttonDict['pause']:
#                    self.buttonDict['pause'].SetValue(False)
                    self.buttonDict['pause'].Enable(False)
        except:
            show_exception_dialog(self.control)
            try:
                wx.EndBusyCursor()
            except:
                pass
        self.refresh_window()
Exemplo n.º 5
0
 def set_attribute_value(self):
     object = getattr(self.window.object, self.attribute)
     current_val = self.get_attribute_value()
     val = self.get_control_value()
     do_fn = partial( self.set_values, 
                      object,                         
                      self.aguidata['sub_attributes'][:],
                      val)
     try:
         do_fn()
     except:
         from pug.syswx.util import show_exception_dialog
         show_exception_dialog()
         return False
     else:
         undo_fn = partial( self.set_values,
                            object,
                            self.aguidata['sub_attributes'][:],
                            current_val)
         if self.aguidata['undo']:
             wx.GetApp().history.add(
                         "Set "+self.attribute+" of "+self.window.shortPath, 
                         undo_fn, do_fn, 
                         (self.window.object, self.attribute))            
         return True
Exemplo n.º 6
0
    def import_settings(self):
        # pug settings
        try:
            from _pug_settings import pug_settings  #@UnresolvedImport
        except:
            self.pug_settings = self.create_default_pug_settings()
            self.save_pug_settings()
        else:
            self.pug_settings = self.create_default_pug_settings(pug_settings)

        # game settings
        try:
            from _project_settings import project_settings  #@UnresolvedImport
        except:
            project_settings = self.create_default_project_settings()
            if not project_settings.initial_scene:
                project_settings.initial_scene = '__Editor__'
            try:
                save_project_settings(project_settings)
            except:
                if wx.GetApp():
                    show_exception_dialog()
                else:
                    raise
        else:
            project_settings = self.create_default_project_settings(
                project_settings)
        self.project_settings = project_settings
Exemplo n.º 7
0
    def openExecuteWindow(self, event = None):
        routine = self.get_routine()
        doc = getdoc(routine)
        if (doc):
            text = doc
        else:
            text = ''.join([self.attribute,self.arguments])
        dlg = wx.TextEntryDialog(self.control, text,
                ''.join(['Enter Arguments for ',routine.__name__]))

        if dlg.ShowModal() == wx.ID_OK:
            attribute = self.attribute
            realself = self
            self = self.window.object
            wx.BeginBusyCursor()
            try:
                exec(''.join(['(args, kwargs) = realself.parseargs(',
                                   dlg.GetValue(),')']))
            except:
                wx.EndBusyCursor()                
                show_exception_dialog( realself.control)
            else:
                self = realself
                retValue = None
                try:
                    retValue = routine.__call__(*args, **kwargs)
                except:
                    wx.EndBusyCursor()                
                    show_exception_dialog( self.control)
                    self.openExecuteWindow()
                else:
                    wx.EndBusyCursor()
                    self.display_retvalue( retValue)
                    self.refresh_window()
        dlg.Destroy()
Exemplo n.º 8
0
    def import_settings(self):
        # pug settings
        try:
            from _pug_settings import pug_settings #@UnresolvedImport
        except:
            self.pug_settings = self.create_default_pug_settings()
            self.save_pug_settings()
        else:
            self.pug_settings = self.create_default_pug_settings( pug_settings)

        # game settings
        try:
            from _project_settings import project_settings #@UnresolvedImport
        except:
            project_settings = self.create_default_project_settings()
            if not project_settings.initial_scene:
                project_settings.initial_scene = '__Editor__'
            try:
                save_project_settings( project_settings)
            except:
                if wx.GetApp():
                    show_exception_dialog()
                else:
                    raise
        else:
            project_settings = self.create_default_project_settings(
                                                            project_settings)
        self.project_settings = project_settings
Exemplo n.º 9
0
    def button_press(self, event=None, button=None):
        """Call the appropriate function"""
        try:
            if event:
                button = event.GetEventObject()
            elif button is None:
                return
            else:
                button = self.buttonDict[button]
            retvalue = self.functionDict[button]()
            if button.type == 'play' and retvalue == True:
                button.Enable(False)
                if self.buttonDict['pause']:
                    self.buttonDict['pause'].Enable(True)
            if button.type == 'stop':
                if self.buttonDict['play']:
                    self.buttonDict['play'].Enable(True)
#                    self.buttonDict['play'].SetValue(False)
                if self.buttonDict['pause']:
                    #                    self.buttonDict['pause'].SetValue(False)
                    self.buttonDict['pause'].Enable(False)
        except:
            show_exception_dialog(self.control)
            try:
                wx.EndBusyCursor()
            except:
                pass
        self.refresh_window()
Exemplo n.º 10
0
 def reload_scene(self):
     """Reload scene from version on disk"""
     if _DEBUG: print 'reload_scene 1'
     scene = self
     self.stop_scene()
     while wx.GetApp().busyState == True:
         time.sleep(0.05)
     dlg = wx.MessageDialog(
         self.frame, "Current state of scene will be lost.\nContinue?",
         'Confirm Reload', wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
     go_ahead = dlg.ShowModal()
     if go_ahead == wx.ID_NO:
         return False
     if Director.scene.__class__ == Scene:
         self.set_scene("Scene")
         return True
     if _DEBUG: print 'reload_scene 2'
     scenename = self.scene.__class__.__name__
     try:
         if _DEBUG: print 'reload_scene 3'
         test_scene_code(scenename)
     except:
         if _DEBUG: print 'reload_scene 3.2'
         show_exception_dialog(prefix='Unable to reload scene: ')
     else:
         if _DEBUG: print 'reload_scene 3.5'
         self.set_scene(scenename, True)
         if _DEBUG: print 'reload_scene 3.6'
         return True
Exemplo n.º 11
0
 def on_new_view_button(self, event = None):  
     try:
         obj = self.get_obj()
         if obj:
             self.PugFrame(parent=wx.GetApp().get_project_frame(),
                           obj=obj, objectpath=self._getNewPath())
     except:
         wx.EndBusyCursor()
         show_exception_dialog()
Exemplo n.º 12
0
 def _auto_refresh(self, msecs):
     try:
         self.refresh()
     except:
         print "_auto_refresh error:\n", exc_info()
         show_exception_dialog()
     else:
         self._autoRefreshTimer = wx.CallLater(msecs, self._auto_refresh,
                                               msecs)
Exemplo n.º 13
0
 def _auto_refresh(self, msecs):
     try:
         self.refresh()
     except:
         print "_auto_refresh error:\n",exc_info()
         show_exception_dialog()
     else:   
         self._autoRefreshTimer = wx.CallLater(msecs, 
                                               self._auto_refresh, msecs)
Exemplo n.º 14
0
 def on_new_view_button(self, event=None):
     try:
         obj = self.get_obj()
         if obj:
             self.PugFrame(parent=wx.GetApp().get_project_frame(),
                           obj=obj,
                           objectpath=self._getNewPath())
     except:
         wx.EndBusyCursor()
         show_exception_dialog()
Exemplo n.º 15
0
 def save_pug_settings(self):
     if self.scene:
         self.pug_settings.initial_scene = self.sceneclass.__name__
     if wx.GetApp():
         wx.GetApp().create_frame_settings(self.pug_settings)
     try:
         pug.code_exporter(self.pug_settings, "_pug_settings.py", True,
                           {'name': 'pug_settings'})
     except:
         if wx.GetApp():
             show_exception_dialog()
         else:
             raise
Exemplo n.º 16
0
 def save_pug_settings(self):
     if self.scene:
         self.pug_settings.initial_scene = self.sceneclass.__name__
     if wx.GetApp():
         wx.GetApp().create_frame_settings( self.pug_settings)
     try:
         pug.code_exporter( self.pug_settings, "_pug_settings.py", True, 
                  {'name':'pug_settings'})              
     except:
         if wx.GetApp():
             show_exception_dialog()
         else:
             raise
Exemplo n.º 17
0
 def code_export(self, event=None):
     if self.hasSavedAs.get(event.Id + 1):
         lastfolder, lastfilename = self.hasSavedAs.get(event.Id + 1)
         self.apply()
         if event.Id in [_MENU_EXPORT_CLASS, _MENU_EXPORT_CLASS_AS]:
             asClass = True
         else:
             asClass = False
         try:
             code_exporter(self.object,
                           os.path.join(lastfolder, lastfilename), asClass)
         except:
             show_exception_dialog(self)
     else:
         event.Id += 1
         self.code_export_as(event)
Exemplo n.º 18
0
Arquivo: app.py Projeto: bcorfman/pug
    def finalize_project_object(self, object):
        if object is None:
            object = self.projectObject
        if not self.projectFrame:
            try:
                frame = PugFrame(obj=object, title=self.projectName, 
                      objectpath=self.projectObjectName) 
            except:
                show_exception_dialog()
            self.set_project_frame(frame)
        self.register_selection_watcher(object)
#        if self.initProgressDialog:
#            self.initProgressDialog.Destroy()
        
        self.SetExitOnFrameDelete(True)
        self.projectFrame.Raise()
Exemplo n.º 19
0
 def execute(self, event = None):
     routine = self.get_routine()
     if callable(routine):
         try:
             wx.BeginBusyCursor()
             retValue = routine.__call__()
         except:
             wx.EndBusyCursor()                
             show_exception_dialog( self.control)
         else:
             wx.EndBusyCursor()                
             try:
                 self.display_retvalue( retValue)
                 self.refresh_window()                
             except:
                 # anything could have happened, like deleting the object etc.
                 pass
Exemplo n.º 20
0
    def finalize_project_object(self, object):
        if object is None:
            object = self.projectObject
        if not self.projectFrame:
            try:
                frame = PugFrame(obj=object,
                                 title=self.projectName,
                                 objectpath=self.projectObjectName)
            except:
                show_exception_dialog()
            self.set_project_frame(frame)
        self.register_selection_watcher(object)
        #        if self.initProgressDialog:
        #            self.initProgressDialog.Destroy()

        self.SetExitOnFrameDelete(True)
        self.projectFrame.Raise()
Exemplo n.º 21
0
 def execute(self, event=None):
     routine = self.get_routine()
     if callable(routine):
         try:
             wx.BeginBusyCursor()
             retValue = routine.__call__()
         except:
             wx.EndBusyCursor()
             show_exception_dialog(self.control)
         else:
             wx.EndBusyCursor()
             try:
                 self.display_retvalue(retValue)
                 self.refresh_window()
             except:
                 # anything could have happened, like deleting the object etc.
                 pass
Exemplo n.º 22
0
 def code_export(self, event=None):
     if self.hasSavedAs.get(event.Id + 1):
         lastfolder, lastfilename = self.hasSavedAs.get(event.Id + 1)
         self.apply()
         if event.Id in [ _MENU_EXPORT_CLASS, _MENU_EXPORT_CLASS_AS]:
             asClass = True
         else:
             asClass = False
         try:
             code_exporter(self.object, 
                         os.path.join(lastfolder, lastfilename), 
                         asClass)
         except:
             show_exception_dialog(self)
     else:
         event.Id += 1
         self.code_export_as(event)
Exemplo n.º 23
0
 def _on_pug_quit(self):
     if getattr(self.project_settings, 'save_settings_on_quit', True):
         try:
             save_project_settings(self.project_settings)
         except:
             show_exception_dialog()
     if getattr(self.pug_settings, 'save_settings_on_quit', True):
         if os.name == 'nt':
             try:
                 window_pos = self.canvas.GetWindowPosition()
                 if not self.canvas.IsIconic():
                     self.pug_settings.rect_opioid_window = tuple(
                                         self.canvas.GetWindowPosition() +\
                                         self.canvas.GetWindowSize())
             except:
                 pass
         self.save_pug_settings()
     self.Director.realquit()
     time.sleep(1)
Exemplo n.º 24
0
 def _on_pug_quit(self):
     if getattr(self.project_settings,'save_settings_on_quit',True):
         try:
             save_project_settings( self.project_settings)
         except:
             show_exception_dialog()
     if getattr(self.pug_settings,'save_settings_on_quit',True):
         if os.name == 'nt':
             try:
                 window_pos = self.canvas.GetWindowPosition()
                 if not self.canvas.IsIconic():
                     self.pug_settings.rect_opioid_window = tuple( 
                                         self.canvas.GetWindowPosition() +\
                                         self.canvas.GetWindowSize())
             except:
                 pass
         self.save_pug_settings()
     self.Director.realquit()
     time.sleep(1)   
Exemplo n.º 25
0
 def set_attribute_value(self):
     object = getattr(self.window.object, self.attribute)
     current_val = self.get_attribute_value()
     val = self.get_control_value()
     do_fn = partial(self.set_values, object,
                     self.aguidata['sub_attributes'][:], val)
     try:
         do_fn()
     except:
         from pug.syswx.util import show_exception_dialog
         show_exception_dialog()
         return False
     else:
         undo_fn = partial(self.set_values, object,
                           self.aguidata['sub_attributes'][:], current_val)
         if self.aguidata['undo']:
             wx.GetApp().history.add(
                 "Set " + self.attribute + " of " + self.window.shortPath,
                 undo_fn, do_fn, (self.window.object, self.attribute))
         return True
Exemplo n.º 26
0
 def add_button_click(self, event=None):
     dlg = ComponentAddDlg(None, self.object)
     # dlg.Center()
     if dlg.ShowModal() == wx.ID_OK:
         component = dlg.component
     else:
         component = None
     if component:
         try:
             dlg.browser.tree.AddRecent(component)
             instance = self.object.components.add(component)
             do_fn = partial(self.object.components.add, instance)
             undo_fn = partial(remove_component, self.object, instance)
             if self.aguidata["undo"]:
                 wx.GetApp().history.add("Add component: " + component.__name__, undo_fn, do_fn)
             self.editList.component_added(instance)
             self.window.refresh()
             self.edit_button_click()
         except:
             show_exception_dialog()
     dlg.Destroy()
Exemplo n.º 27
0
    def execute_scene( self, doSave=True):
        """execute_scene()
        
Run the scene being editted in a new process.
"""
        try:
            if doSave and not self.Director.project_started:
                saved = self.save_using_working_scene()
                if not saved:
                    dlg = wx.MessageDialog( self.frame,
                          "The scene failed to save properly.\nExecute anyway?",
                          'Save Failed', 
                          wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
                    continue_shutdown = dlg.ShowModal()
                    if continue_shutdown == wx.ID_NO:
                        return False                               
            save_project_settings( self.project_settings)
            python_process("main.py", "__Working__")
        except:
            show_exception_dialog()
            return False
        return True
Exemplo n.º 28
0
def create_new_project(path=None, name=None, source=None):
    """create_new_project(path, name, source)->path to project or None if failed
    
Create a new pig project
path: path to create project in. default: query user
name: name of new project. default: query user
source: source path to copy project from. default: pig.editor.New_Project
"""
    if not name:
        dlg = wx.TextEntryDialog( parent,
                                  "Project Name",
                                  "Create New Project", 
                                  "MyProject")
        if dlg.ShowModal() != wx.ID_OK:
            return
        name = dlg.GetValue()
        dlg.Destroy()
    if not name:
        return
    if not path:
        parent = wx.GetApp().get_project_frame()
        dlg = wx.DirDialog( parent, "Create " + name + \
                            " project in folder:",
                            style=wx.DD_DEFAULT_STYLE )
        if dlg.ShowModal() != wx.ID_OK:
            return
        path = dlg.GetPath()
        dlg.Destroy()
    if not source:
        this_folder = os.path.split( os.path.abspath(__file__))[0]
        source = os.path.join( this_folder, 'New_Project')
    project_path = os.path.join( path, name)
    try:
        shutil.copytree(source, project_path)
    except:
        show_exception_dialog( modal=True)          
        return  
    return project_path
Exemplo n.º 29
0
    def openExecuteWindow(self, event=None):
        routine = self.get_routine()
        doc = getdoc(routine)
        if (doc):
            text = doc
        else:
            text = ''.join([self.attribute, self.arguments])
        dlg = wx.TextEntryDialog(
            self.control, text,
            ''.join(['Enter Arguments for ', routine.__name__]))

        if dlg.ShowModal() == wx.ID_OK:
            attribute = self.attribute
            realself = self
            self = self.window.object
            wx.BeginBusyCursor()
            try:
                exec(''.join([
                    '(args, kwargs) = realself.parseargs(',
                    dlg.GetValue(), ')'
                ]))
            except:
                wx.EndBusyCursor()
                show_exception_dialog(realself.control)
            else:
                self = realself
                retValue = None
                try:
                    retValue = routine.__call__(*args, **kwargs)
                except:
                    wx.EndBusyCursor()
                    show_exception_dialog(self.control)
                    self.openExecuteWindow()
                else:
                    wx.EndBusyCursor()
                    self.display_retvalue(retValue)
                    self.refresh_window()
        dlg.Destroy()
Exemplo n.º 30
0
 def add_button_click(self, event=None):
     dlg = ComponentAddDlg( None, self.object)
     #dlg.Center()
     if dlg.ShowModal() == wx.ID_OK:
         component = dlg.component
     else:
         component = None
     if component:
         try:
             dlg.browser.tree.AddRecent(component)
             instance = self.object.components.add(component)                
             do_fn = partial( self.object.components.add, instance)
             undo_fn = partial( remove_component, self.object, instance)
             if self.aguidata['undo']:
                 wx.GetApp().history.add(
                                     "Add component: " + component.__name__,
                                     undo_fn, do_fn)
             self.editList.component_added(instance)
             self.window.refresh()
             self.edit_button_click()
         except:
             show_exception_dialog()
     dlg.Destroy()
Exemplo n.º 31
0
    def execute_scene(self, doSave=True):
        """execute_scene()
        
Run the scene being editted in a new process.
"""
        try:
            if doSave and not self.Director.project_started:
                saved = self.save_using_working_scene()
                if not saved:
                    dlg = wx.MessageDialog(
                        self.frame,
                        "The scene failed to save properly.\nExecute anyway?",
                        'Save Failed',
                        wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
                    continue_shutdown = dlg.ShowModal()
                    if continue_shutdown == wx.ID_NO:
                        return False
            save_project_settings(self.project_settings)
            python_process("main.py", "__Working__")
        except:
            show_exception_dialog()
            return False
        return True
Exemplo n.º 32
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()
Exemplo n.º 33
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
Exemplo n.º 34
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
Exemplo n.º 35
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()
Exemplo n.º 36
0
def on_drop_files( x, y, filenames): 
    types = deepcopy(_filetypes) # make a typeinfo list
    for typeinfo in types:
        typeinfo.append([]) # make a list to store files associated with types
    unknown = []
    for filename in filenames:
        splitname = filename.rsplit('.',1)
        typefound = False
        if len(splitname) == 1:
            unknown.append(filename)
            continue
        for typeinfo in types:
            if splitname[1].lower() in typeinfo[1]:
                typeinfo[2].append(filename)
                typefound = True
                break
        if not typefound:
            unknown.append(filename)
    projectPath = get_project_path()
    if len(filenames) - len(unknown) == 1:
        filename = filenames[0]
        dest = projectPath
        if unknown:
            return ([])
        for typeinfo in types:
            if typeinfo[2]:
                title = "Copy "+typeinfo[0]+" into project" 
                dest = os.path.join(dest, typeinfo[0], 
                                    os.path.split(filename)[1])
        if filename == dest:
            dlg = wx.MessageDialog( wx.GetApp().get_project_frame(),
                    "Use 'Reload Files' button if you want to refresh files.",
                    "Files already in project!", wx.OK)
            wx.GetApp().raise_all_frames()
            dlg.ShowModal()
            return ([])
        else:
            dlg = wx.MessageDialog( wx.GetApp().get_project_frame(),
                        "Copy file:\n"+filename+"\nto:\n"+dest+"?\n\n"+\
                        "If file exists, it will be overwritten.",
                        title, wx.YES_NO | wx.ICON_QUESTION)
            wx.GetApp().raise_all_frames()
            if dlg.ShowModal() == wx.ID_YES:
                try:
                    shutil.copyfile(filename, dest)
                except:
                    show_exception_dialog()
            return [dest]
    else:
        title = "Copy multiple files into project"
        message = ""
        copies = []
        for typeinfo in types:
            if not typeinfo[2]:
                continue
            message += "Copy "+typeinfo[0]+" files:\n\n"
            for filename in typeinfo[2]:
                dest = os.path.join(projectPath, typeinfo[0], 
                                    os.path.split(filename)[1])
                if filename == dest:
                    dlg = wx.MessageDialog( wx.GetApp().get_project_frame(),
                    "Use 'Reload Files' button if you want to refresh files.",
                            "Files already in project!", wx.OK)
                    wx.GetApp().raise_all_frames()
                    dlg.ShowModal()
                    return ([])                
                message += "> "+filename+" to "+dest+"\n"
                copies += (filename,dest)
            message += "\n"
        message += "If files exist, they will be overwritten."
        dlg = wx.MessageDialog( wx.GetApp().get_project_frame(),
                    message, title, wx.YES_NO | wx.ICON_QUESTION)
        wx.GetApp().raise_all_frames()
        copied = []
        if dlg.ShowModal() == wx.ID_YES:
            for filename, dest in copies:
                try:                
                    shutil.copyfile(filename, dest)
                except:
                    show_exception_dialog()
                else:
                    copied.append(dest)
        return copied