def create_sub_package(self, name): """ Creates a sub-package with the specified name. """ sub_package = File(join(self.filename, name)) sub_package.create_package() return
def delete_sub_package(self, name): """ Deletes the sub-package with the specified name. """ sub_package = File(join(self.filename, name)) sub_package.delete() return
def _finished_fired(self): """ This will just create a file at the location specified in the wizard pages. Override this method in a subclass for other resource types. """ container_page = self.pages[0] resource_page = self.pages[1] resource = File(resource_page.abs_path) resource.create_file() self._open_resource(file) # FIXME: Refresh the parent folder not the whole tree workspace = self.window.application.get_service(IWorkspace) self._refresh_container(workspace)
def _get_module_name(self, filename): """ Get the fully qualified module name for a filename. e.g. if the filename is:- '/enthought/envisage/core/core_plugin_definition.py' we would return:- 'envisage.core.core_plugin_definition' """ # Get the name of the module minus the '.py' module, ext = os.path.splitext(os.path.basename(filename)) # Start with the actual module name. module_path = [module] # If the directory is a Python package then add it to the module path. parent = File(os.path.dirname(filename)) while parent.is_package: module_path.insert(0, parent.name) parent = parent.parent return '.'.join(module_path)
def read_directory(filename, package=None): """ Parse every module in the specified directory. """ directory = File(filename) if not directory.is_folder: raise ValueError("%s is NOT a directory." % filename) if package is not None: contents = package.contents else: contents = [] for child in directory.children: if child.ext == '.py': contents.append(read_file(child.path, package)) elif child.is_package: if package is not None: sub_package_name = '%s.%s' % (package.name, child.name) sub_package = Package( filename=child.path, name=sub_package_name, parent=package) else: sub_package = Package(filename=child.path, name=child.name) read_directory(child.path, sub_package) contents.append(sub_package) return contents
def perform(self, event=None): from csurface_action import SurfaceParameter from scripts import surfscript cfile = self.window.application.get_service('cviewer.plugins.cff2.cfile.CFile') so = SurfaceParameter(cfile) so.edit_traits(kind='livemodal') if not so.pointset_da[so.pointset]['name'] == "None": # if cancel, not create surface # create a temporary file import tempfile myf = tempfile.mktemp(suffix='.py', prefix='my') f=open(myf, 'w') if so.labels_da[so.labels].has_key('da_idx'): labels = so.labels_da[so.labels]['da_idx'] else: labels = 0 f.write(surfscript % (so.pointset_da[so.pointset]['name'], so.pointset_da[so.pointset]['da_idx'], so.faces_da[so.faces]['name'], so.faces_da[so.faces]['da_idx'], so.labels_da[so.labels]['name'], labels)) f.close() self.window.workbench.edit(File(myf), kind=TextEditor,use_existing=False)
def perform(self, event=None): logger.info('OpenFileAction.perform()') pref_script_path = preference_manager.cviewerui.scriptpath dialog = FileDialog(parent=self.window.control, title='Open File', default_directory=pref_script_path) if dialog.open() == OK: self.window.workbench.edit(File(dialog.path), kind=TextEditor)
def _lookup(self, name): """ Looks up a name in this context. """ if name in self._cache: obj = self._cache[name] else: # Get the full path to the file. path = join(self.path, self._name_to_filename_map[name]) # If the file contains a serialized Python object then load it. for serializer in self._get_object_serializers(): if serializer.can_load(path): try: state = serializer.load(path) # If the load fails then we create a generic file resource # (the idea being that it might be useful to have access to # the file to see what went wrong). except: state = File(path) logger.exception('Error loading resource at %s' % path) break # Otherwise, it must just be a file or folder. else: # Directories are contexts. if os.path.isdir(path): state = self._context_factory(name, path) # Files are just files! elif os.path.isfile(path): state = File(path) else: raise ValueError('unrecognized file for %s' % name) # Get the actual object from the naming manager. obj = naming_manager.get_object_instance(state, name, self) # Update the cache. self._cache[name] = obj return obj
def _finished_fired(self): """ Performs the file resource creation if the wizard is finished successfully. """ csp = self.pages[0] fwp = self.pages[1] file = File(fwp.abs_path) file.create_file() # Refresh the workspace tree view view = self.window.get_view_by_id(RESOURCE_VIEW) if view is not None: # FIXME: Refresh the parent folder, not the whole tree. workspace = self.window.application.get_service(IWorkspace) wtv = view.tree_viewer.refresh(workspace)
def _finished_fired(self): """ Performs the folder resource creation if the wizard is finished successfully. """ csp = self.pages[0] fwp = self.pages[1] path = join(csp.directory, fwp.folder_name) folder = File(path) folder.create_folder() # Refresh the workspace tree view view = self.window.get_view_by_id(RESOURCE_VIEW) if view is not None: # FIXME: Refresh the parent folder not the whole tree workspace = self.window.application.get_service(IWorkspace) workspace.path = path wtv = view.tree_viewer.refresh(workspace)
def get_object_instance(self, state, name, context): """ Creates an object using the specified state information. """ obj = None if isinstance(state, Reference): if state.class_name == 'File' and len(state.addresses) > 0: obj = File(state.addresses[0].content) return obj
def _create_drag_event(self, event): # If the control no longer exists, don't send mouse event if self.control is None: return None # If the event (if there is one) doesn't contain the mouse position, # modifiers and buttons then get sensible defaults. try: x = event.x() y = event.y() except AttributeError: pos = self.control.mapFromGlobal(QtGui.QCursor.pos()) x = pos.x() y = pos.y() self.control.handler.last_mouse_pos = (x, y) # extract an object from the event, if we can try: mimedata = event.mimeData() copy = event.proposedAction() == QtCore.Qt.CopyAction except AttributeError: # this is a DragLeave event return DragEvent(x=x, y=self._flip_y(y), obj=None, copy=False, window=self, mimedata=None) try: from traitsui.qt4.clipboard import PyMimeData except ImportError: # traitsui isn't available, just make mimedata available on event obj = None else: mimedata = PyMimeData.coerce(mimedata) obj = mimedata.instance() if obj is None: files = mimedata.localPaths() if files: try: # try to extract file info from mimedata # XXX this is for compatibility with what wx does from apptools.io.api import File obj = [File(path=path) for path in files] except ImportError: pass return DragEvent(x=x, y=self._flip_y(y), obj=obj, copy=copy, window=self, mimedata=mimedata)
def perform(self, event=None): from scripts import corticocortico import tempfile myf = tempfile.mktemp(suffix='.py', prefix='my') f=open(myf, 'w') f.write(corticocortico) f.close() self.window.workbench.edit(File(myf), kind=TextEditor,use_existing=False)
def _unbind(self, name): """ Unbinds a name from this context. """ # Get the full path to the file. path = join(self.path, self._name_to_filename_map[name]) # Remove it! f = File(path) f.delete() # Update the name to filename map. del self._name_to_filename_map[name] # Update the cache. if name in self._cache: del self._cache[name] # Remove any attributes. if name in self._attributes: del self._attributes[name] self._save_attributes()
def __attributes_default(self): """ Initializes the '_attributes' trait. """ attributes_file = File(join(self.path, self.ATTRIBUTES_FILE)) if attributes_file.is_file: f = open(attributes_file.path, 'rb') attributes = pickle.load(f) f.close() else: attributes = {} return attributes
def _unbind(self, name): """ Unbinds a name from this context. """ # Get the full path to the file. path = join(self.path, self._name_to_filename_map[name]) # Remove it! f = File(path) f.delete() # Update the name to filename map. del self._name_to_filename_map[name] # Update the cache. if name in self._cache: del self._cache[name] # Remove any attributes. if name in self._attributes: del self._attributes[name] self._save_attributes() return
def perform(self, event=None): # from cnetwork_nbs_action import NBSNetworkParameter, NBSMoreParameter from scripts import nbsscript # cfile = self.window.application.get_service('cviewer.plugins.cff2.cfile.CFile') # # no = NBSNetworkParameter(cfile) # no.edit_traits(kind='livemodal') # # if (len(no.selected1) == 0 or len(no.selected2) == 0): # return # # mo = NBSMoreParameter(cfile, no.selected1[0], no.selected2[0]) # mo.edit_traits(kind='livemodal') # # import datetime as dt # a=dt.datetime.now() # ostr = '%s%s%s' % (a.hour, a.minute, a.second) # if not (len(no.selected1) == 0 or len(no.selected2) == 0): # # if cancel, not create surface # # create a temporary file # import tempfile # myf = tempfile.mktemp(suffix='.py', prefix='my') # f=open(myf, 'w') # f.write(nbsscript % (str(no.selected1), # mo.first_edge_value, # str(no.selected2), # mo.second_edge_value, # mo.THRES, # mo.K, # mo.TAIL, # ostr)) # f.close() # # self.window.workbench.edit(File(myf), kind=TextEditor,use_existing=False) import tempfile myf = tempfile.mktemp(suffix='.py', prefix='my') f=open(myf, 'w') f.write(nbsscript) f.close() self.window.workbench.edit(File(myf), kind=TextEditor,use_existing=False)
def perform(self, event=None): from cvolume_action import VolumeParameter from scripts import volslice cfile = self.window.application.get_service('cviewer.plugins.cff2.cfile.CFile') so = VolumeParameter(cfile) so.edit_traits(kind='livemodal') if True: #not so.pointset_da[so.pointset]['name'] == "None": # if cancel, not create surface # create a temporary file import tempfile myf = tempfile.mktemp(suffix='.py', prefix='my') f=open(myf, 'w') f.write(volslice % so.volumes[so.myvolume]['name']) f.close() self.window.workbench.edit(File(myf), kind=TextEditor,use_existing=False)
def _show_open_dialog(self, parent): """ Show the dialog to open a project. """ # Determine the starting point for browsing. It is likely most # projects will be stored in the default path used when creating new # projects. default_path = self.model_service.get_default_path() project_class = self.model_service.factory.PROJECT_CLASS if self.model_service.are_projects_files(): dialog = FileDialog( parent=parent, default_directory=default_path, title="Open Project", ) if dialog.open() == OK: path = dialog.path else: path = None else: dialog = DirectoryDialog( parent=parent, default_path=default_path, message="Open Project", ) if dialog.open() == OK: path = project_class.get_pickle_filename(dialog.path) if File(path).exists: path = dialog.path else: error( parent, "Directory does not contain a recognized " "project", ) path = None else: path = None return path
def perform(self, event=None): from cnetwork_action import MatrixEdgeNetworkParameter from scripts import conmatrixpyplot cfile = self.window.application.get_service('cviewer.plugins.cff2.cfile.CFile') no = MatrixEdgeNetworkParameter(cfile) no.edit_traits(kind='livemodal') if not no.netw[no.graph]['name'] == "None": # if cancel, not create surface # create a temporary file import tempfile myf = tempfile.mktemp(suffix='.py', prefix='my') f=open(myf, 'w') f.write(conmatrixpyplot % (no.netw[no.graph]['name'], no.edge_label)) f.close() self.window.workbench.edit(File(myf), kind=TextEditor,use_existing=False)
def save(self, location=None, overwrite=False): """ Save this project. The project is saved to its current location, identified by the value of the *location* trait, unless a new location is explicitly provided. The specification of a new location is used to do a 'save as' operation. If a new location is provided, and a file or directory already exists at that location, then an *AssertionError* exception is raised unless the overwrite flag is True. This ensures that users won't accidentally overwrite existing data. This method requires the overwrite flag because prompting the user to confirm the overwrite requires GUI interaction and thus should not be done at the model level. Note that, because we can rely on the location of a loaded project always being set to the location it was loaded from, there is no reason to try to force the *location* trait within a saved project to the location we are trying to save to. Instead, we update the value in the in-memory version of the project only if the save completed successfully. The dirty flag is always cleared upon a succesfull save of the project. An exception will be raised to indicate a failure. """ # Ensure saving (or save as) is allowed at this time. if location is None or location == self.location: if not self.is_save_allowed: raise AssertionError("Saving is currently not allowed.") elif location != self.location: if not self.is_save_as_allowed: raise AssertionError("Save as is currently not allowed.") # Use the internally-specified location unless a new location was # explicitly provided. The new location can not contain any starting # or trailing whitespace and it cannot overwrite an existing file or # directory unless that was explicitly allowed. loc = self.location if location is not None: location = location.strip() if len(location) > 0 and location != self.location: # Ensure we never overwrite existing files / directories just # because someone specified a new location. (Confirmation or # correction of overwriting requires prompting of the user and # is thus not part of the project model.) if os.path.exists(location) and overwrite is False: raise AssertionError("Can not overwrite existing " + "location [%s]" % location) # The requested location is valid so let's use it. loc = location # Ensure all necessary directories exist. If we're saving a file, then # these are the path upto the file name. If we're saving to a directory # then the path is the complete location. if self.PROJECTS_ARE_FILES: path, filename = os.path.split(loc) else: path = loc if len(path) > 0: f = File(path) if f.is_file: f.delete() if not f.exists: f.create_folders() # Save this project in a manner that derived classes can modify. self._save(loc) # If the save succeeds (no exceptions were raised), then update the # location of the project and clear the dirty flag. self.location = loc self.dirty = False return
def perform(self, event=None): logger.info('OpenFileAction.perform()') dialog = FileDialog(parent=self.window.control, title='Open File') if dialog.open() == OK: self.window.workbench.edit(File(dialog.path), kind=TextEditor)
def perform(self, event=None): logger.info('NewFileAction.perform()') self.window.workbench.edit(File(''), kind=TextEditor, use_existing=False)
def _rename(self, old_name, new_name): """ Renames an object in this context. """ # Get the old filename. old_filename = self._name_to_filename_map[old_name] old_file = File(join(self.path, old_filename)) # Lookup the object bound to the old name. This has the side effect # of adding the object to the cache under the name 'old_name'. obj = self._lookup(old_name) # We are renaming a LOCAL context (ie. a folder)... if old_file.is_folder: # Create the new filename. new_filename = new_name new_file = File(join(self.path, new_filename)) # Move the folder. old_file.move(new_file) # Update the 'Context' object. obj.path = new_file.path # Update the cache. self._cache[new_name] = obj del self._cache[old_name] # Refreshing the context makes sure that all of its contents # reflect the new name (i.e., sub-folders and files have the # correct path). # # fixme: This currently results in new copies of serialized # Python objects! We need to be a bit more judicious in the # refresh. obj.refresh() # We are renaming a file... elif isinstance(obj, File): # Create the new filename. new_filename = new_name new_file = File(join(self.path, new_filename)) # Move the file. old_file.move(new_file) # Update the 'File' object. obj.path = new_file.path # Update the cache. self._cache[new_name] = obj del self._cache[old_name] # We are renaming a serialized Python object... else: # Create the new filename. new_filename = new_name + old_file.ext new_file = File(join(self.path, new_filename)) old_file.delete() # Update the cache. if old_name in self._cache: self._cache[new_name] = self._cache[old_name] del self._cache[old_name] # Force the creation of the new file. # # fixme: I'm not sure that this is really the place for this. We # do it because often the 'name' of the object is actually an # attribute of the object itself, and hence we want the serialized # state to reflect the new name... Hmmm... self._rebind(new_name, obj) # Update the name to filename map. del self._name_to_filename_map[old_name] self._name_to_filename_map[new_name] = new_filename # Move any attributes over to the new name. if old_name in self._attributes: self._attributes[new_name] = self._attributes[old_name] del self._attributes[old_name] self._save_attributes() return
def _get_file_object(self, obj): """ Return a 'File' object for the object's source file. """ return File(path=inspect.getsourcefile(type(obj)))
def _get_root(self): return File(path=self.root_path)
def save(self, location=None, overwrite=False): """ Save this project. The project is saved to its current location, identified by the value of the *location* trait, unless a new location is explicitly provided. The specification of a new location is used to do a 'save as' operation. If a new location is provided, and a file or directory already exists at that location, then an *AssertionError* exception is raised unless the overwrite flag is True. This ensures that users won't accidentally overwrite existing data. This method requires the overwrite flag because prompting the user to confirm the overwrite requires GUI interaction and thus should not be done at the model level. Note that, because we can rely on the location of a loaded project always being set to the location it was loaded from, there is no reason to try to force the *location* trait within a saved project to the location we are trying to save to. Instead, we update the value in the in-memory version of the project only if the save completed successfully. The dirty flag is always cleared upon a succesfull save of the project. An exception will be raised to indicate a failure. """ # Ensure saving (or save as) is allowed at this time. if location is None or location == self.location: if not self.is_save_allowed: raise AssertionError('Saving is currently not allowed.') elif location != self.location: if not self.is_save_as_allowed: raise AssertionError('Save as is currently not allowed.') # Use the internally-specified location unless a new location was # explicitly provided. The new location can not contain any starting # or trailing whitespace and it cannot overwrite an existing file or # directory unless that was explicitly allowed. loc = self.location if location is not None: location = location.strip() if len(location) > 0 and location != self.location: # Ensure we never overwrite existing files / directories just # because someone specified a new location. (Confirmation or # correction of overwriting requires prompting of the user and # is thus not part of the project model.) if os.path.exists(location) and overwrite is False: raise AssertionError('Can not overwrite existing ' + \ 'location [%s]' % location) # The requested location is valid so let's use it. loc = location # Ensure all necessary directories exist. If we're saving a file, then # these are the path upto the file name. If we're saving to a directory # then the path is the complete location. if self.PROJECTS_ARE_FILES: path, filename = os.path.split(loc) else: path = loc if len(path) > 0: f = File(path) if f.is_file: f.delete() if not f.exists: f.create_folders() # Save this project in a manner that derived classes can modify. self._save(loc) # If the save succeeds (no exceptions were raised), then update the # location of the project and clear the dirty flag. self.location = loc self.dirty = False return